@rongcloud/plugin-rtc 5.5.2 → 5.5.3
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.ts +3 -3
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/index.umd.js +1 -1
- package/package.json +2 -2
package/dist/index.esm.js
CHANGED
|
@@ -12,4 +12,4 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
|
12
12
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
13
13
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
14
14
|
PERFORMANCE OF THIS SOFTWARE.
|
|
15
|
-
***************************************************************************** */function v(e,t,r,i){return new(r||(r=Promise))((function(s,o){function n(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,a)}c((i=i.apply(e,t||[])).next())}))}const O=new e("RCRTC");var L,A,D;!function(e){e[e.SUCCESS=1e4]="SUCCESS",e[e.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",e[e.PARAMS_ERROR=50001]="PARAMS_ERROR",e[e.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",e[e.NOT_IN_ROOM=50003]="NOT_IN_ROOM",e[e.SERVICE_INVALID=50004]="SERVICE_INVALID",e[e.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",e[e.SIGNAL_ERROR=53001]="SIGNAL_ERROR",e[e.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",e[e.REQUEST_FAILED=53004]="REQUEST_FAILED",e[e.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",e[e.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",e[e.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",e[e.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",e[e.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",e[e.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",e[e.BROWSER_PERMISSION_DENIED=53012]="BROWSER_PERMISSION_DENIED",e[e.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",e[e.INVALID_TAGS=53014]="INVALID_TAGS",e[e.INVALID_USER_ID=53015]="INVALID_USER_ID",e[e.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",e[e.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",e[e.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",e[e.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",e[e.TRACK_NOT_READY=53020]="TRACK_NOT_READY",e[e.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",e[e.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",e[e.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",e[e.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",e[e.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",e[e.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",e[e.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",e[e.SIGNAL_JOIN_RTC_ROOM_REFUSED=53028]="SIGNAL_JOIN_RTC_ROOM_REFUSED",e[e.NO_PERMISSION_TO_USE_REQUESTED_DEVICE=53029]="NO_PERMISSION_TO_USE_REQUESTED_DEVICE",e[e.THE_FUNCTION_IS_DISABLED_IN_PKROOM=53030]="THE_FUNCTION_IS_DISABLED_IN_PKROOM",e[e.SOME_TRACKS_PUBLISH_FAILED=53031]="SOME_TRACKS_PUBLISH_FAILED",e[e.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO=53032]="MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO",e[e.JWT_TIME_OUT=1004]="JWT_TIME_OUT",e[e.SYSTEM_PERMISSION_DENIED=53033]="SYSTEM_PERMISSION_DENIED",e[e.PUBLISH_TRACKS_IS_INVALID=53034]="PUBLISH_TRACKS_IS_INVALID"}(L||(L={})),function(e){e.L_INDEX_INSTALL_RTC_PLUGIN_O="L-index_install_rtc_plugin-O",e.L_RTC_CLIENT_CONNECTION_STATE_S="L-rtc_client_connection_state-S",e.L_RTC_CLIENT_DISCONNECT_S="L-rtc_client_disconnect-S",e.L_RTC_CLIENT_MESSAGE_O="L-rtc_client_message-O",e.L_RTC_CLIENT_DESTROY_S="L-rtc_client_destroy-S",e.L_RTC_CLIENT_JOIN_RTC_ROOM_T="L-rtc_client_join_rtc_room-T",e.L_RTC_CLIENT_JOIN_RTC_ROOM_R="L-rtc_client_join_rtc_room-R",e.L_RTC_CLIENT_JOIN_LIVING_ROOM_T="L-rtc_client_join_living_room-T",e.L_RTC_CLIENT_JOIN_LIVING_ROOM_R="L-rtc_client_join_living_room-R",e.L_RTC_CLIENT_GET_AUDIENCE_CLIENT_O="L-rtc_client_get_audience_client-O",e.L_RTC_CLIENT_LEAVE_ROOM_T="L-rtc_client_leave_room-T",e.L_RTC_CLIENT_LEAVE_ROOM_R="L-rtc_client_leave-room-R",e.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O="L-rtc_client_create_microphone_audio_track-O",e.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O="L-rtc_client_create_camera_video_track-O",e.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O="L-rtc_client_create_microphone_and_camera_tracks-O",e.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O="L-rtc_client_create_screen_video_track-O",e.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_AND_AUDIO_TRACKS_O="L-rtc_client_create_screen_video_and_audio_tracks-O",e.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O="L-rtc_client_create_local_audio_track-O",e.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O="L-rtc_client_create_local_video_track-O",e.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O="L-rtc_client_create_local_file_tracks-O",e.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O="L-rtc_client_create_local_tracks-O",e.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_T="L-rtc_client_join_living_room_as_audience-T",e.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R="L-tcclient_join_living_room_as_audience_R",e.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_T="L-rtc_client_leave_living_room_as_audience-T",e.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R="L-rtc_client_leave_living_room_as_audience-R",e.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_T="L-rtc_client_upgrade_to_anchor_room-T",e.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R="L-rtc_client_upgrade_to_anchor_room-R",e.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_T="L-rtc_client_downgrade_to_audience_room-T",e.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R="L-rtc_client_downgrade_to_audience_room-R",e.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O="L-rtc_client_get_joined_room_info-O",e.L_AUDIENCE_CLIENT_SUBSCRIBE_T="L-audinence_client_subscribe-T",e.L_AUDIENCE_CLIENT_SUBSCRIBE_R="L-audinence_client_subscribe-R",e.L_AUDIENCE_CLIENT_UNSUBSCRIBE_T="L-audinence_client_unsubscribe-T",e.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R="L-audinence_client_unsubscribe-R",e.L_PINGER_START_O="L-pinger_start-O",e.L_PINGER_STOP_O="L-pinger_stop-O",e.L_PINGER_SEND_RTCPING_T="L-pinger_send_rtcping-T",e.L_PINGER_SEND_RTCPING_R="L-pinger_send_rtcping-R",e.L_ABSTRACT_ROOM_SEND_MESSAGE_T="L-abstract_room_send_message-T",e.L_ABSTRACT_ROOM_SEND_MESSAGE_R="L-abstract_room_send_message-R",e.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_T="L-abstract_room_set_room_attribute-T",e.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R="L-abstract_room_set_room_attribute_R",e.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_T="L-abstract_room_delete_room_attribute_T",e.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R="L-abstract_room_delete_room_attribute_R",e.L_ABSTRACT_ROOM_PUBLISH_T="L-abstract_room_publish-T",e.L_ABSTRACT_ROOM_PUBLISH_R="L-abstract_room_publish-R",e.L_ABSTRACT_ROOM_UNPUBLISH_T="L-abstract_room_unpublish-T",e.L_ABSTRACT_ROOM_UNPUBLISH_R="L-abstract_room_unpublish-R",e.L_ABSTRACT_ROOM_SUBSCRIBE_T="L-abstract_room_subscribe-T",e.L_ABSTRACT_ROOM_SUBSCRIBE_R="L-abstract_room_subscribe-R",e.L_ABSTRACT_ROOM_UNSUBSCRIBE_T="L-abstract_room_unsubscribe-T",e.L_ABSTRACT_ROOM_UNSUBSCRIBE_R="L-abstract_room_unsubscribe-R",e.L_ABSTRACT_ROOM_REGISTER_ROOM_EVENT_LISTENER_O="L-abstract_room_register_room_event_listener-O",e.L_ABSTRACT_ROOM_REGISTER_REPORT_LISTENER_O="L-abstract_room_register_report_listener-O",e.L_ABSTRACT_ROOM_AUDIO_LEVEL_O="L-abstract_room_audio_level-O",e.L_ABSTRACT_ROOM_RECONNECTED_T="L-abstract_room_reconnected-T",e.L_ABSTRACT_ROOM_RECONNECTED_R="L-abstract_room_reconnected-R",e.L_ABSTRACT_ROOM_CALL_APP_LISTENER_O="L-abstract_room_call_app_listener-O",e.L_LIVING_ROOM_RECONNECTED_T="L-living_room_reconnected-T",e.L_LIVING_ROOM_RECONNECTED_R="L-living_room_reconnected-R",e.L_LIVING_ROOM_ENABLE_INNER_CDN_T="L-living_room_enable_inner_cdn-T",e.L_LIVING_ROOM_ENABLE_INNER_CDN_R="L-living_room_enable_inner_cdn-R",e.L_LIVING_ROOM_SPREAD_CDN_INFO_T="L-living_room_spread_cdn_info-T",e.L_LIVING_ROOM_SPREAD_CDN_INFO_R="L-living_room_spread_cdn_info-R",e.L_LIVING_ROOM_JOINED_PK_ROOM_T="L-living_room_joined_pk_room-T",e.L_LIVING_ROOM_JOINED_PK_ROOM_R="L-living_room_joined_pk_room-R",e.L_LIVING_ROOM_LEAVE_PK_ROOM_T="L-living_room_leave_pk_room-T",e.L_LIVING_ROOM_LEAVE_PK_ROOM_R="L-living_room_leave_pk_room-R",e.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O="L-living_room_get_room_pk_handler-O",e.L_LIVING_ROOM_QUIT_ALL_PK_ROOM_O="L-living_room_quit_all_pk_room-O",e.L_LIVING_PK_HANDLER_REGISTER_ROOM_PK_EVENT_LISTENER_O="L-living_pk_handler_register_room_pk_event_listener-O",e.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_T="L-living_pk_handler_request_join_other_room-T",e.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R="L-living_pk_handler_request_join_other_room-R",e.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_T="L-living_pk_handler_cancel_request_join_other_room-T",e.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R="L-living_pk_handler_cancel_request_join_other_room-R",e.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_T="L-living_pk_handler_response_join_other_room-T",e.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R="L-living_pk_handler_response_join_other_room-R",e.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_T="L-living_pk_handler_join_other_room-T",e.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R="L-living_pk_handler_join_other_room-R",e.L_LIVING_PK_HANDLER_LEAVE_OTHER_ROOM_T="L-living_pk_handler_leave_other_room-T",e.L_LIVING_PK_HANDLER_LEAVE_OTHER_ROOM_R="L-living_pk_handler_leave_other_room-R",e.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_T="L-audience_living_room_singal_data_change-T",e.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R="L-audience_living_room_singal_data_change-R",e.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_T="L-audience_living_room_get_cdn_play_url-T",e.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R="L-audience_living_room_get_cdn_play_url-R",e.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_T="L-audience_living_room_subscribe-T",e.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R="L-audience_living_room_subscribe-R",e.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_T="L-audience_living_room_unsubscribe-T",e.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R="L-audience_living_room_unsubscribe-R",e.L_AUDIENCE_LIVING_ROOM_AUDIO_LEVEL_CHANGE_O="L-audience_living_room_audio_level_change-O",e.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O="L-mcu_config_builder_set_host_video_track-O",e.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O="L-mcu_config_builder_set_mix_layout_mode-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O="L-mcu_config_builder_set_output_video_resolution-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O="L-mcu_config_builder_set_output_video_fps-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O="L-mcu_config_builder_set_output_video_bitrate-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O="L-mcu_config_builder_set_output_tiny_video_resolution-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O="L-mcu_config_builder_set_output_tiny_video_fps-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O="L-mcu_config_builder_set_output_tiny_video_bitrate-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O="L-mcu_config_builder_set_output_video_render_mode-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O="L-mcu_config_builder_set_output_audio_bitrate-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O="L-mcu_config_builder_set_output_background_color-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O="L-mcu_config_builder_add_output_background_picture-O",e.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O="L-mcu_config_builder_remove_output_background_picture-O",e.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O="L-mcu_config_builder_clear_output_background_picture-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O="L-mcu_config_builder_set_output_background_picture-fill-mode-O",e.L_MCU_CONFIG_BUILDER_ADD_PUBLISH_STREAM_URLS_O="L-mcu_config_builder_add_publish_stream_urls-O",e.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O="L-mcu_config_builder_remove_publish_stream_urls-O",e.L_MCU_CONFIG_BUILDER_CLEAR_PUBLISH_STREAM_URLS_O="L-mcu_config_builder_clear_publish_stream_urls-O",e.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O="L-mcu_config_builder_add_customize_layout_video-O",e.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O="L-mcu_config_builder_remove_customize_layout_video-O",e.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_LAYOUT_VIDEO_O="L-mcu_config_builder_clear_customize_layout_video-O",e.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O="L-mcu_config_builder_set_customize_input_audio-O",e.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O="L-mcu_config_builder_add_customize_input_audio-O",e.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O="L-mcu_config_builder_remove_customize_input_audio-O",e.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_INPUT_AUDIO_O="L-mcu_config_builder_clear_customize_input_audio-O",e.L_MCU_CONFIG_BUILDER_RESET_O="L-mcu_config_builder_reset-O",e.L_MCU_CONFIG_BUILDER_FLUSH_O="L-mcu_config_builder_flush-O",e.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O="L-mcu_config_builder_add_single_water_mark-O",e.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O="L-mcu_config_builder_remove_single_water_mark-O",e.L_MCU_CONFIG_BUILDER_CLEAR_SINGLE_WATER_MARK_O="L-mcu_config_builder_clear_single_water_mark-O",e.L_MEDIA_SERVICE_SET_MCU_CONFIG_T="L-media_service_set_mcu_config-T",e.L_MEDIA_SERVICE_SET_MCU_CONFIG_R="L-media_service_set_mcu_config-R",e.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_T="L-media_service_get_cnd_resource_info-T",e.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R="L-media_service_get_cnd_resource_info-R",e.L_MEDIA_SERVICE_REQUEST_T="L-media_service_request-T",e.L_MEDIA_SERVICE_REQUEST_R="L-media_service_request-R",e.L_LOCAL_TRACK_INNER_SET_PUBLISHED_O="L-loacl_track_inner_set_published-O",e.L_LOCAL_TRACK_DESTROY_O="L-loacl_track_destroy-O",e.L_LOCAL_TRACK_SET_BITRATE_O="L-loacl_track_set_bitrate-O",e.L_LOCAL_TRACK_SET_LOCAL_MUTED_O="L-loacl_track_set_local_muted-O",e.L_TRACK_PLAY_T="L-track_play-T",e.L_TRACK_PLAY_R="L-track_play-R",e.L_TRACK_MUTE_O="L-track_mute-O",e.L_TRACK_UNMUTE_O="L-track_unmute-O",e.L_REMOTE_TRACK_INNER_SET_SUBSCRIBED_O="L-remote_track_inner_set_subscribed-O",e.L_ABSTRACT_STAT_PARSER_FORMAT_RTC_STATE_REPORT_O="L-abstract_stat_parser_format_rtc_state_report-O",e.L_A_SDP_STRATEGY_SET_SDP_SEMANTICS_O="L-a_sdp_strategy_set_sdp_semantics-O",e.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O="L-a_sdp_strategy_set_remote_answer-O",e.L_RTC_PEER_CONNECTION_GET_STATS_DATA_O="L-rtc_peer_connection_get_stats_data-O",e.L_RTC_PEER_CONNECTION_ADD_LOCAL_TRACK_O="L-rtc_peer_connection_add_local_track-O",e.L_RTC_PEER_CONNECTION_GET_LOCAL_TRACKS_O="L-rtc_peer_connection_get_local_tracks-O",e.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S="L-rtc_peer_connection_ice_connection_state-S",e.L_RTC_PEER_CONNECTION_CONNECTION_STATE_S="L-rtc_peer_connection_connection_state-S",e.L_RTC_PEER_CONNECTION_SET_BITRATE_O="L-rtc_peer_connection_set_bitrate-O",e.L_RTC_PEER_CONNECTION_CREATE_OFFER_O="L-rtc_peer_connection_create_offer-O",e.L_RTC_PEER_CONNECTION_SET_REMOTE_ANSWER_O="L-rtc_peer_connection_set_remote_answer-O",e.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O="L-rtc_peer_connection_remove_local_track_by_id-O",e.L_RTC_PEER_CONNECTION_REMOVE_ALL_LOCAL_TRACK_O="L-rtc_peer_connection_remove_all_local_track-O",e.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_O="L-rtc_peer_connection_remove_local_track-O",e.L_RTC_PEER_CONNECTION_UPDATE_SUB_REMOTE_TRACKS_O="L-rtc_peer_connection_update_sub_remote_tracks-O",e.L_RTC_PEER_CONNECTION_LOCAL_TRACK_MUTED_O="L-rtc_peer_connection_local_track_muted-O",e.L_RTC_PEER_CONNECTION_DESTROY_O="L-rtc_peer_connection_destroy-O",e.L_RTC_SET_RECOMMEND_BITRATE_O="L_rtc_set_recommend_bitrate_O",e.L_RTC_SDP_BITRATE_O="L_rtc_sdp_bitrate_O",e.L_RTC_3ANOISE_NODE_O="L_RTC_AAAnoiseNode_O",e.L_RTC_3ANOISE_NODE_E="L_RTC_AAAnoiseNode_E",e.L_RTC_3ANOISE_NODE_STOP_O="L_RTC_AAAnoiseNode_Stop_O",e.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_T="L_rtc_client_join_cross_rtc_room_T",e.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_R="L_rtc_client_join_cross_rtc_room_R",e.L_QS_CREATE_OFFER_O="L-qs_create_offer-O",e.L_QS_PUBLISH_EXCHANGE_O="L-qs_publish_exchange-O",e.L_QS_SUBSCRIBE_EXCHANGE_O="L-qs_subscribe_exchange-O",e.L_QS_GET_ANSWER_O="L-qs_get_answer-O",e.L_QS_SET_LOCAL_DESCRIPTION_O="L-qs_set_local_description-O",e.L_QS_GET_RESOURCES_O="L-qs_get_resources-O",e.L_QS_TRACK_READY_O="L-qs_track_ready-O",e.L_QS_JOIN_ROOM_S="RTC-joinRoomRtc-S",e.L_QS_SUBSCRIBE_S="RTC-subscribe-S",e.L_QS_UNSUBSCRIBE_S="RTC-unsubscribe-S",e.L_QS_PUBLISH_S="RTC-publishRtc-S",e.L_QS_UNPUBLISH_S="RTC-unpublishRtc-S",e.L_QS_ICE_STATUS_S="RTC-iceStatus-S",e.L_QS_KICKED_S="RTC-forcedOffline-S",e.L_QS_PUB_ICE_STATUS_S="RTC-pubIceConnected-S",e.L_QS_SUB_ICE_STATUS_S="RTC-subIceConnected-S",e.L_QS_RECV_PUB_MSG_S="RTC-recvPubMsg-S"}(A||(A={})),function(e){e.FAILED="fail",e.SUCCESSED="success",e.TIMEOUT="timeout",e.INFO="info"}(D||(D={}));let N=!0,b=!0;function k(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function y(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return s.apply(this,arguments);const o=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),s.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(r))return o.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"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 U(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(N=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function P(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(b=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function M(){if("object"==typeof window){if(N)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function x(e,t){b&&console.warn(e+" is deprecated, please use "+t+" instead.")}function w(e){return"[object Object]"===Object.prototype.toString.call(e)}function B(e){return w(e)?Object.keys(e).reduce((function(t,r){const i=w(e[r]),s=i?B(e[r]):e[r],o=i&&!Object.keys(s).length;return void 0===s||o?t:Object.assign(t,{[r]:s})}),{}):e}function V(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?V(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{V(e,e.get(t),r)}))})))}function $(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&V(e,r,s)}))})),s}const F=M;function G(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[s("min",r)]=i.ideal,t.optional.push(e),e={},e[s("max",r)]=i.ideal,t.optional.push(e)):(e[s("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const n=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||n)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{let n=(r=r.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!n&&r.length&&t.includes("back")&&(n=r[r.length-1]),n&&(e.video.deviceId=o.exact?{exact:n.deviceId}:{ideal:n.deviceId}),e.video=i(e.video),F("chrome: "+JSON.stringify(e)),s(e)}))}e.video=i(e.video)}return F("chrome: "+JSON.stringify(e)),s(e)},o=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(r.getUserMedia=function(e,t,i){s(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(o(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return s(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(o(e))))))}}}function K(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function j(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",(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const s=new Event("track");s.track=r.track,s.receiver=i,s.transceiver={receiver:i},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const s=new Event("track");s.track=r,s.receiver=i,s.transceiver={receiver:i},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else y(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function H(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 r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let s=r.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.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 J(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,i]=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 s=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const i=function(e){r(o(s(e)))};return t.apply(this,[i,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(o(s(t)))},r])})).then(r,i)}}function q(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 r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>$(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}),y(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>$(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,r,i;return this.getSenders().forEach((r=>{r.track===e&&(t?i=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?i=!0:r=t),t.track===e))),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function W(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,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=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();r.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function Y(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return W(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=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 r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],s=e._streams[i.id];r=r.replace(new RegExp(s.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function n(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],s=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.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,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[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 s=this.getSenders().find((e=>e.track===t));if(s)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[r.id];if(o)o.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=o(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=n(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:o(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((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Q(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function z(e,t){y(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var Z=Object.freeze({__proto__:null,shimMediaStream:K,shimOnTrack:j,shimGetSendersWithDtmf:H,shimGetStats:J,shimSenderReceiverGetStats:q,shimAddTrackRemoveTrackWithNative:W,shimAddTrackRemoveTrack:Y,shimPeerConnection:Q,fixNegotiationNeeded:z,shimGetUserMedia:G,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const i=r.video&&r.video.width,s=r.video&&r.video.height,o=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},i&&(r.video.mandatory.maxWidth=i),s&&(r.video.mandatory.maxHeight=s),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});var X,ee,te=(X=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 r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){var r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((function(e){return 0===e.indexOf(r)}))},t.parseCandidate=function(e){for(var t,r={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]},i=8;i<t.length;i+=2)switch(t[i]){case"raddr":r.relatedAddress=t[i+1];break;case"rport":r.relatedPort=parseInt(t[i+1],10);break;case"tcptype":r.tcpType=t[i+1];break;case"ufrag":r.ufrag=t[i+1],r.usernameFragment=t[i+1];break;default:r[t[i]]=t[i+1]}return r},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 r=e.type;return t.push("typ"),t.push(r),"host"!==r&&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(" "),r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\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,r={},i=e.substr(e.indexOf(" ")+1).split(";"),s=0;s<i.length;s++)r[(t=i[s].trim().split("="))[0].trim()]=t[1];return r},t.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var i=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.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="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r},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 r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substr(6)},t.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){var r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},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,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){var i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],s=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&s?{usernameFragment:i.substr(12),password:s.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 r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" "),s=3;s<i.length;s++){var o=i[s],n=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(n){var a=t.parseRtpMap(n),c=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(a.parameters=c.length?t.parseFmtp(c[0]):{},a.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),r.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(a.name.toUpperCase())}}}return t.matchPrefix(e,"a=extmap:").forEach((function(e){r.headerExtensions.push(t.parseExtmap(e))})),r},t.writeRtpDescription=function(e,r){var i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" UDP/TLS/RTP/SAVPF ",i+=r.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((function(e){i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));var s=0;return r.codecs.forEach((function(e){e.maxptime>s&&(s=e.maxptime)})),s>0&&(i+="a=maxptime:"+s+"\r\n"),i+="a=rtcp-mux\r\n",r.headerExtensions&&r.headerExtensions.forEach((function(e){i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){var r,i=[],s=t.parseRtpParameters(e),o=-1!==s.fecMechanisms.indexOf("RED"),n=-1!==s.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,d=t.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));d.length>0&&d[0].length>1&&d[0][0]===c&&(r=d[0][1]),s.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&r&&(t.rtx={ssrc:r}),i.push(t),o&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:n?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&c&&i.push({ssrc:c});var _=t.matchPrefix(e,"b=");return _.length&&(_=0===_[0].indexOf("b=TIAS:")?parseInt(_[0].substr(7),10):0===_[0].indexOf("b=AS:")?1e3*parseInt(_[0].substr(5),10)*.95-16e3:void 0,i.forEach((function(e){e.maxBitrate=_}))),i},t.parseRtcpParameters=function(e){var r={},i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);var s=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=s.length>0,r.compound=0===s.length;var o=t.matchPrefix(e,"a=rtcp-mux");return r.mux=o.length>0,r},t.parseMsid=function(e){var r,i=t.matchPrefix(e,"a=msid:");if(1===i.length)return{stream:(r=i[0].substr(7).split(" "))[0],track:r[1]};var s=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return s.length>0?{stream:(r=s[0].value.split(" "))[0],track:r[1]}:void 0},t.parseSctpDescription=function(e){var r,i=t.parseMLine(e),s=t.matchPrefix(e,"a=max-message-size:");s.length>0&&(r=parseInt(s[0].substr(19),10)),isNaN(r)&&(r=65536);var o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substr(12),10),protocol:i.fmt,maxMessageSize:r};if(t.matchPrefix(e,"a=sctpmap:").length>0){var n=t.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(n[0],10),protocol:n[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){var r=[];return r="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&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,r,i){var s=void 0!==r?r:2;return"v=0\r\no="+(i||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,r,i,s){var o=t.writeRtpDescription(e.kind,r);if(o+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),o+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===i?"actpass":"active"),o+="a=mid:"+e.mid+"\r\n",e.direction?o+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?o+="a=sendrecv\r\n":e.rtpSender?o+="a=sendonly\r\n":e.rtpReceiver?o+="a=recvonly\r\n":o+="a=inactive\r\n",e.rtpSender){var n="msid:"+s.id+" "+e.rtpSender.track.id+"\r\n";o+="a="+n,o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+n,e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+n,o+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+t.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+t.localCName+"\r\n"),o},t.getDirection=function(e,r){for(var i=t.splitLines(e),s=0;s<i.length;s++)switch(i[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[s].substr(2)}return r?t.getDirection(r):"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 r=t.splitLines(e)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){var r=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var r=t.splitLines(e),i=0;i<r.length;i++)if(r[i].length<2||"="!==r[i].charAt(1))return!1;return!0},e.exports=t},X(ee={exports:{}},ee.exports),ee.exports);function re(e,t,r,i,s){var o=te.writeRtpDescription(e.kind,t);if(o+=te.writeIceParameters(e.iceGatherer.getLocalParameters()),o+=te.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":s||"active"),o+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?o+="a=sendrecv\r\n":e.rtpSender?o+="a=sendonly\r\n":e.rtpReceiver?o+="a=recvonly\r\n":o+="a=inactive\r\n",e.rtpSender){var n=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=n;var a="msid:"+(i?i.id:"-")+" "+n+"\r\n";o+="a="+a,o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,o+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+te.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+te.localCName+"\r\n"),o}function ie(e,t){var r={codecs:[],headerExtensions:[],fecMechanisms:[]},i=function(e,t){e=parseInt(e,10);for(var r=0;r<t.length;r++)if(t[r].payloadType===e||t[r].preferredPayloadType===e)return t[r]},s=function(e,t,r,s){var o=i(e.parameters.apt,r),n=i(t.parameters.apt,s);return o&&n&&o.name.toLowerCase()===n.name.toLowerCase()};return e.codecs.forEach((function(i){for(var o=0;o<t.codecs.length;o++){var n=t.codecs[o];if(i.name.toLowerCase()===n.name.toLowerCase()&&i.clockRate===n.clockRate){if("rtx"===i.name.toLowerCase()&&i.parameters&&n.parameters.apt&&!s(i,n,e.codecs,t.codecs))continue;(n=JSON.parse(JSON.stringify(n))).numChannels=Math.min(i.numChannels,n.numChannels),r.codecs.push(n),n.rtcpFeedback=n.rtcpFeedback.filter((function(e){for(var t=0;t<i.rtcpFeedback.length;t++)if(i.rtcpFeedback[t].type===e.type&&i.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var i=0;i<t.headerExtensions.length;i++){var s=t.headerExtensions[i];if(e.uri===s.uri){r.headerExtensions.push(s);break}}})),r}function se(e,t,r){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(r)}function oe(e,t){var r=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 r||e.addRemoteCandidate(t),!r}function ne(e,t){var r=new Error(t);return r.name=e,r.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[e],r}var ae=function(e,t){function r(t,r){r.addTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function i(t,r,i,s){var o=new Event("track");o.track=r,o.receiver=i,o.transceiver={receiver:i},o.streams=s,e.setTimeout((function(){t._dispatchEvent("track",o)}))}var s=function(r){var i=this,s=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){i[e]=s[e].bind(s)})),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",r=JSON.parse(JSON.stringify(r||{})),this.usingBundle="max-bundle"===r.bundlePolicy,"negotiate"===r.rtcpMuxPolicy)throw ne("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var i=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var s="string"==typeof i;return s&&(i=[i]),i=i.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||r?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(r=!0,!0)})),delete e.url,e.urls=s?i[0]:i,!!i.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var o=r.iceCandidatePoolSize;o>0;o--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=te.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(s.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(s.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),s.prototype.onicecandidate=null,s.prototype.onaddstream=null,s.prototype.ontrack=null,s.prototype.onremovestream=null,s.prototype.onsignalingstatechange=null,s.prototype.oniceconnectionstatechange=null,s.prototype.onconnectionstatechange=null,s.prototype.onicegatheringstatechange=null,s.prototype.onnegotiationneeded=null,s.prototype.ondatachannel=null,s.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},s.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},s.prototype.getConfiguration=function(){return this._config},s.prototype.getLocalStreams=function(){return this.localStreams},s.prototype.getRemoteStreams=function(){return this.remoteStreams},s.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,i={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&&r)i.iceTransport=this.transceivers[0].iceTransport,i.dtlsTransport=this.transceivers[0].dtlsTransport;else{var s=this._createIceAndDtlsTransports();i.iceTransport=s.iceTransport,i.dtlsTransport=s.dtlsTransport}return t||this.transceivers.push(i),i},s.prototype.addTrack=function(t,r){if(this._isClosed)throw ne("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var i;if(this.transceivers.find((function(e){return e.track===t})))throw ne("InvalidAccessError","Track already exists.");for(var s=0;s<this.transceivers.length;s++)this.transceivers[s].track||this.transceivers[s].kind!==t.kind||(i=this.transceivers[s]);return i||(i=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),i.track=t,i.stream=r,i.rtpSender=new e.RTCRtpSender(t,i.dtlsTransport),i.rtpSender},s.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var i=e.clone();e.getTracks().forEach((function(e,t){var r=i.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),i.getTracks().forEach((function(e){r.addTrack(e,i)}))}},s.prototype.removeTrack=function(t){if(this._isClosed)throw ne("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 r=this.transceivers.find((function(e){return e.rtpSender===t}));if(!r)throw ne("InvalidAccessError","Sender was not created by this connection.");var i=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(i)&&this.localStreams.indexOf(i)>-1&&this.localStreams.splice(this.localStreams.indexOf(i),1),this._maybeFireNegotiationNeeded()},s.prototype.removeStream=function(e){var t=this;e.getTracks().forEach((function(e){var r=t.getSenders().find((function(t){return t.track===e}));r&&t.removeTrack(r)}))},s.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},s.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},s.prototype._createIceGatherer=function(t,r){var i=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var s=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(s,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(e){var r=!e.candidate||0===Object.keys(e.candidate).length;s.state=r?"completed":"gathering",null!==i.transceivers[t].bufferedCandidateEvents&&i.transceivers[t].bufferedCandidateEvents.push(e)},s.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),s},s.prototype._gather=function(t,r){var i=this,s=this.transceivers[r].iceGatherer;if(!s.onlocalcandidate){var o=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,s.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),s.onlocalcandidate=function(e){if(!(i.usingBundle&&r>0)){var o=new Event("icecandidate");o.candidate={sdpMid:t,sdpMLineIndex:r};var n=e.candidate,a=!n||0===Object.keys(n).length;if(a)"new"!==s.state&&"gathering"!==s.state||(s.state="completed");else{"new"===s.state&&(s.state="gathering"),n.component=1,n.ufrag=s.getLocalParameters().usernameFragment;var c=te.writeCandidate(n);o.candidate=Object.assign(o.candidate,te.parseCandidate(c)),o.candidate.candidate=c,o.candidate.toJSON=function(){return{candidate:o.candidate.candidate,sdpMid:o.candidate.sdpMid,sdpMLineIndex:o.candidate.sdpMLineIndex,usernameFragment:o.candidate.usernameFragment}}}var d=te.getMediaSections(i._localDescription.sdp);d[o.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+o.candidate.candidate+"\r\n",i._localDescription.sdp=te.getDescription(i._localDescription.sdp)+d.join("");var _=i.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==i.iceGatheringState&&(i.iceGatheringState="gathering",i._emitGatheringStateChange()),a||i._dispatchEvent("icecandidate",o),_&&(i._dispatchEvent("icecandidate",new Event("icecandidate")),i.iceGatheringState="complete",i._emitGatheringStateChange())}},e.setTimeout((function(){o.forEach((function(e){s.onlocalcandidate(e)}))}),0)}},s.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var i=new e.RTCDtlsTransport(r);return i.ondtlsstatechange=function(){t._updateConnectionState()},i.onerror=function(){Object.defineProperty(i,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:i}},s.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var r=this.transceivers[e].iceTransport;r&&(delete r.onicestatechange,delete this.transceivers[e].iceTransport);var i=this.transceivers[e].dtlsTransport;i&&(delete i.ondtlsstatechange,delete i.onerror,delete this.transceivers[e].dtlsTransport)},s.prototype._transceive=function(e,r,i){var s=ie(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(s.encodings=e.sendEncodingParameters,s.rtcp={cname:te.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(s.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(s)),i&&e.rtpReceiver&&s.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?s.encodings=e.recvEncodingParameters:s.encodings=[{}],s.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(s.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(s.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(s))},s.prototype.setLocalDescription=function(e){var t,r,i=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(ne("TypeError",'Unsupported type "'+e.type+'"'));if(!se("setLocalDescription",e.type,i.signalingState)||i._isClosed)return Promise.reject(ne("InvalidStateError","Can not set local "+e.type+" in state "+i.signalingState));if("offer"===e.type)t=te.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=te.parseRtpParameters(e);i.transceivers[t].localCapabilities=r})),i.transceivers.forEach((function(e,t){i._gather(e.mid,t)}));else if("answer"===e.type){t=te.splitSections(i._remoteDescription.sdp),r=t.shift();var s=te.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var o=i.transceivers[t],n=o.iceGatherer,a=o.iceTransport,c=o.dtlsTransport,d=o.localCapabilities,_=o.remoteCapabilities;if(!(te.isRejected(e)&&0===te.matchPrefix(e,"a=bundle-only").length)&&!o.rejected){var u=te.getIceParameters(e,r),l=te.getDtlsParameters(e,r);s&&(l.role="server"),i.usingBundle&&0!==t||(i._gather(o.mid,t),"new"===a.state&&a.start(n,u,s?"controlling":"controlled"),"new"===c.state&&c.start(l));var h=ie(d,_);i._transceive(o,h.codecs.length>0,!1)}}))}return i._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?i._updateSignalingState("have-local-offer"):i._updateSignalingState("stable"),Promise.resolve()},s.prototype.setRemoteDescription=function(s){var o=this;if(-1===["offer","answer"].indexOf(s.type))return Promise.reject(ne("TypeError",'Unsupported type "'+s.type+'"'));if(!se("setRemoteDescription",s.type,o.signalingState)||o._isClosed)return Promise.reject(ne("InvalidStateError","Can not set remote "+s.type+" in state "+o.signalingState));var n={};o.remoteStreams.forEach((function(e){n[e.id]=e}));var a=[],c=te.splitSections(s.sdp),d=c.shift(),_=te.matchPrefix(d,"a=ice-lite").length>0,u=te.matchPrefix(d,"a=group:BUNDLE ").length>0;o.usingBundle=u;var l=te.matchPrefix(d,"a=ice-options:")[0];return o.canTrickleIceCandidates=!!l&&l.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(i,c){var l=te.splitLines(i),h=te.getKind(i),R=te.isRejected(i)&&0===te.matchPrefix(i,"a=bundle-only").length,m=l[0].substr(2).split(" ")[2],p=te.getDirection(i,d),S=te.parseMsid(i),T=te.getMid(i)||te.generateIdentifier();if(R||"application"===h&&("DTLS/SCTP"===m||"UDP/DTLS/SCTP"===m))o.transceivers[c]={mid:T,kind:h,protocol:m,rejected:!0};else{var C,I,E,g,f,v,O,L,A;!R&&o.transceivers[c]&&o.transceivers[c].rejected&&(o.transceivers[c]=o._createTransceiver(h,!0));var D,N,b=te.parseRtpParameters(i);R||(D=te.getIceParameters(i,d),(N=te.getDtlsParameters(i,d)).role="client"),O=te.parseRtpEncodingParameters(i);var k=te.parseRtcpParameters(i),y=te.matchPrefix(i,"a=end-of-candidates",d).length>0,U=te.matchPrefix(i,"a=candidate:").map((function(e){return te.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===s.type||"answer"===s.type)&&!R&&u&&c>0&&o.transceivers[c]&&(o._disposeIceAndDtlsTransports(c),o.transceivers[c].iceGatherer=o.transceivers[0].iceGatherer,o.transceivers[c].iceTransport=o.transceivers[0].iceTransport,o.transceivers[c].dtlsTransport=o.transceivers[0].dtlsTransport,o.transceivers[c].rtpSender&&o.transceivers[c].rtpSender.setTransport(o.transceivers[0].dtlsTransport),o.transceivers[c].rtpReceiver&&o.transceivers[c].rtpReceiver.setTransport(o.transceivers[0].dtlsTransport)),"offer"!==s.type||R){if("answer"===s.type&&!R){I=(C=o.transceivers[c]).iceGatherer,E=C.iceTransport,g=C.dtlsTransport,f=C.rtpReceiver,v=C.sendEncodingParameters,L=C.localCapabilities,o.transceivers[c].recvEncodingParameters=O,o.transceivers[c].remoteCapabilities=b,o.transceivers[c].rtcpParameters=k,U.length&&"new"===E.state&&(!_&&!y||u&&0!==c?U.forEach((function(e){oe(C.iceTransport,e)})):E.setRemoteCandidates(U)),u&&0!==c||("new"===E.state&&E.start(I,D,"controlling"),"new"===g.state&&g.start(N)),!ie(C.localCapabilities,C.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&C.sendEncodingParameters[0].rtx&&delete C.sendEncodingParameters[0].rtx,o._transceive(C,"sendrecv"===p||"recvonly"===p,"sendrecv"===p||"sendonly"===p),!f||"sendrecv"!==p&&"sendonly"!==p?delete C.rtpReceiver:(A=f.track,S?(n[S.stream]||(n[S.stream]=new e.MediaStream),r(A,n[S.stream]),a.push([A,f,n[S.stream]])):(n.default||(n.default=new e.MediaStream),r(A,n.default),a.push([A,f,n.default])))}}else{(C=o.transceivers[c]||o._createTransceiver(h)).mid=T,C.iceGatherer||(C.iceGatherer=o._createIceGatherer(c,u)),U.length&&"new"===C.iceTransport.state&&(!y||u&&0!==c?U.forEach((function(e){oe(C.iceTransport,e)})):C.iceTransport.setRemoteCandidates(U)),L=e.RTCRtpReceiver.getCapabilities(h),t<15019&&(L.codecs=L.codecs.filter((function(e){return"rtx"!==e.name}))),v=C.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var P,M=!1;if("sendrecv"===p||"sendonly"===p){if(M=!C.rtpReceiver,f=C.rtpReceiver||new e.RTCRtpReceiver(C.dtlsTransport,h),M)A=f.track,S&&"-"===S.stream||(S?(n[S.stream]||(n[S.stream]=new e.MediaStream,Object.defineProperty(n[S.stream],"id",{get:function(){return S.stream}})),Object.defineProperty(A,"id",{get:function(){return S.track}}),P=n[S.stream]):(n.default||(n.default=new e.MediaStream),P=n.default)),P&&(r(A,P),C.associatedRemoteMediaStreams.push(P)),a.push([A,f,P])}else C.rtpReceiver&&C.rtpReceiver.track&&(C.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===C.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),C.associatedRemoteMediaStreams=[]);C.localCapabilities=L,C.remoteCapabilities=b,C.rtpReceiver=f,C.rtcpParameters=k,C.sendEncodingParameters=v,C.recvEncodingParameters=O,o._transceive(o.transceivers[c],!1,M)}}})),void 0===o._dtlsRole&&(o._dtlsRole="offer"===s.type?"active":"passive"),o._remoteDescription={type:s.type,sdp:s.sdp},"offer"===s.type?o._updateSignalingState("have-remote-offer"):o._updateSignalingState("stable"),Object.keys(n).forEach((function(t){var r=n[t];if(r.getTracks().length){if(-1===o.remoteStreams.indexOf(r)){o.remoteStreams.push(r);var s=new Event("addstream");s.stream=r,e.setTimeout((function(){o._dispatchEvent("addstream",s)}))}a.forEach((function(e){var t=e[0],s=e[1];r.id===e[2].id&&i(o,t,s,[r])}))}})),a.forEach((function(e){e[2]||i(o,e[0],e[1],[])})),e.setTimeout((function(){o&&o.transceivers&&o.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()},s.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")},s.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},s.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))},s.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 r=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",r)}},s.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 r=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",r)}},s.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(ne("InvalidStateError","Can not call createOffer after close"));var i=r.transceivers.filter((function(e){return"audio"===e.kind})).length,s=r.transceivers.filter((function(e){return"video"===e.kind})).length,o=arguments[0];if(o){if(o.mandatory||o.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==o.offerToReceiveAudio&&(i=!0===o.offerToReceiveAudio?1:!1===o.offerToReceiveAudio?0:o.offerToReceiveAudio),void 0!==o.offerToReceiveVideo&&(s=!0===o.offerToReceiveVideo?1:!1===o.offerToReceiveVideo?0:o.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--i<0&&(e.wantReceive=!1):"video"===e.kind&&--s<0&&(e.wantReceive=!1)}));i>0||s>0;)i>0&&(r._createTransceiver("audio"),i--),s>0&&(r._createTransceiver("video"),s--);var n=te.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(i,s){var o=i.track,n=i.kind,a=i.mid||te.generateIdentifier();i.mid=a,i.iceGatherer||(i.iceGatherer=r._createIceGatherer(s,r.usingBundle));var c=e.RTCRtpSender.getCapabilities(n);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"),i.remoteCapabilities&&i.remoteCapabilities.codecs&&i.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(i.remoteCapabilities&&i.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=i.sendEncodingParameters||[{ssrc:1001*(2*s+1)}];o&&t>=15019&&"video"===n&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),i.wantReceive&&(i.rtpReceiver=new e.RTCRtpReceiver(i.dtlsTransport,n)),i.localCapabilities=c,i.sendEncodingParameters=d})),"max-compat"!==r._config.bundlePolicy&&(n+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),n+="a=ice-options:trickle\r\n",r.transceivers.forEach((function(e,t){n+=re(e,e.localCapabilities,"offer",e.stream,r._dtlsRole),n+="a=rtcp-rsize\r\n",!e.iceGatherer||"new"===r.iceGatheringState||0!==t&&r.usingBundle||(e.iceGatherer.getLocalCandidates().forEach((function(e){e.component=1,n+="a="+te.writeCandidate(e)+"\r\n"})),"completed"===e.iceGatherer.state&&(n+="a=end-of-candidates\r\n"))}));var a=new e.RTCSessionDescription({type:"offer",sdp:n});return Promise.resolve(a)},s.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(ne("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(ne("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var i=te.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.usingBundle&&(i+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),i+="a=ice-options:trickle\r\n";var s=te.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,o){if(!(o+1>s)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?i+="m=application 0 DTLS/SCTP 5000\r\n":i+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?i+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(i+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(i+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var n;if(e.stream)"audio"===e.kind?n=e.stream.getAudioTracks()[0]:"video"===e.kind&&(n=e.stream.getVideoTracks()[0]),n&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1});var a=ie(e.localCapabilities,e.remoteCapabilities);!a.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,i+=re(e,a,"answer",e.stream,r._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(i+="a=rtcp-rsize\r\n")}}));var o=new e.RTCSessionDescription({type:"answer",sdp:i});return Promise.resolve(o)},s.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(i,s){if(!r._remoteDescription)return s(ne("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var o=e.sdpMLineIndex;if(e.sdpMid)for(var n=0;n<r.transceivers.length;n++)if(r.transceivers[n].mid===e.sdpMid){o=n;break}var a=r.transceivers[o];if(!a)return s(ne("OperationError","Can not add ICE candidate"));if(a.rejected)return i();var c=Object.keys(e.candidate).length>0?te.parseCandidate(e.candidate):{};if("tcp"===c.protocol&&(0===c.port||9===c.port))return i();if(c.component&&1!==c.component)return i();if((0===o||o>0&&a.iceTransport!==r.transceivers[0].iceTransport)&&!oe(a.iceTransport,c))return s(ne("OperationError","Can not add ICE candidate"));var d=e.candidate.trim();0===d.indexOf("a=")&&(d=d.substr(2)),(t=te.getMediaSections(r._remoteDescription.sdp))[o]+="a="+(c.type?d:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=te.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var _=0;_<r.transceivers.length&&(r.transceivers[_].rejected||(r.transceivers[_].iceTransport.addRemoteCandidate({}),(t=te.getMediaSections(r._remoteDescription.sdp))[_]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=te.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));_++);i()}))},s.prototype.getStats=function(t){if(t&&t instanceof e.MediaStreamTrack){var r=null;if(this.transceivers.forEach((function(e){e.rtpSender&&e.rtpSender.track===t?r=e.rtpSender:e.rtpReceiver&&e.rtpReceiver.track===t&&(r=e.rtpReceiver)})),!r)throw ne("InvalidAccessError","Invalid selector.");return r.getStats()}var i=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&i.push(e[t].getStats())}))})),Promise.all(i).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 r=e[t];if(r&&r.prototype&&r.prototype.getStats){var i=r.prototype.getStats;r.prototype.getStats=function(){return i.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var i;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(i=e[r]).type]||i.type,t.set(r,e[r])})),t}))}}}));var o=["createOffer","createAnswer"];return o.forEach((function(e){var t=s.prototype[e];s.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)}})),(o=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=s.prototype[e];s.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=s.prototype[e];s.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)}})),s};function ce(e){const t=e&&e.navigator,r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(e){return r(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 de(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 _e(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 r=new Event("enabled");r.enabled=e,this.dispatchEvent(r)}})}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 r=ae(e,t.version);e.RTCPeerConnection=function(e){return e&&e.iceServers&&(e.iceServers=function(e,t){let r=!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&&x("RTCIceServer.url","RTCIceServer.urls");const i="string"==typeof t;return i&&(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&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=i?t[0]:t,!!t.length}}))}(e.iceServers,t.version),M("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype}function ue(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var le=Object.freeze({__proto__:null,shimPeerConnection:_e,shimReplaceTrack:ue,shimGetUserMedia:ce,shimGetDisplayMedia:de});function he(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){x("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function Re(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 me(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 r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,o]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(s,o)}}function pe(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 r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.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 Se(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}),y(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Te(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){x("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Ce(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ie(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],r=e&&"sendEncodings"in e;r&&e.sendEncodings.forEach((e=>{if("rid"in e){if(!/^[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 i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function Ee(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 ge(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 fe(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 ve=Object.freeze({__proto__:null,shimOnTrack:Re,shimPeerConnection:me,shimSenderGetStats:pe,shimReceiverGetStats:Se,shimRemoveStream:Te,shimRTCDataChannel:Ce,shimAddTransceiver:Ie,shimGetParameters:Ee,shimCreateOffer:ge,shimCreateAnswer:fe,shimGetUserMedia:he,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})}});function Oe(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((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.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 r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function Le(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 r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function Ae(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,s=t.setLocalDescription,o=t.setRemoteDescription,n=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=r.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[r]);return t?(s.then(e,t),Promise.resolve()):s};let a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function De(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(Ne(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function Ne(e){return e&&void 0!==e.video?Object.assign({},e,{video:B(e.video)}):e}function be(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];!i.hasOwnProperty("urls")&&i.hasOwnProperty("url")?(x("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function ke(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 ye(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 r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video")}return t.apply(this,arguments)}}function Ue(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Pe=Object.freeze({__proto__:null,shimLocalStreamsAPI:Oe,shimRemoteStreamsAPI:Le,shimCallbacksAPI:Ae,shimGetUserMedia:De,shimConstraints:Ne,shimRTCIceServerUrls:be,shimTrackEventTransceiver:ke,shimCreateOfferLegacy:ye,shimAudioContext:Ue});function Me(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 r=new t(e),i=te.parseCandidate(e.candidate),s=Object.assign(r,i);return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,y(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function xe(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 r=function(e){if(!e||!e.sdp)return!1;const t=te.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=te.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},i=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r},s=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r},o=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const s=te.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?i=parseInt(s[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i},n=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(r(arguments[0])){const e=i(arguments[0]),t=s(e),r=o(arguments[0],e);let n;n=0===t&&0===r?Number.POSITIVE_INFINITY:0===t||0===r?Math.max(t,r):Math.min(t,r);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>n}),this._sctp=a}return n.apply(this,arguments)}}function we(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],s=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},y(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Be(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 r=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 r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function Ve(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=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:r}):t.sdp=r}return r.apply(this,arguments)}}function $e(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.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():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}var Fe=Object.freeze({__proto__:null,shimRTCIceCandidate:Me,shimMaxMessageSize:xe,shimSendThrowTypeError:we,shimConnectionState:Be,removeExtmapAllowMixed:Ve,shimAddIceCandidateNullOrEmpty:$e});const Ge=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=M,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=k(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=k(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=k(r.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=k(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:i,commonShim:Fe,extractVersion:k,disableLog:U,disableWarnings:P};switch(i.browser){case"chrome":if(!Z||!Q||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),s;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),s;r("adapter.js shimming chrome."),s.browserShim=Z,$e(e,i),G(e,i),K(e),Q(e,i),j(e),Y(e,i),H(e),J(e),q(e),z(e,i),Me(e),Be(e),xe(e,i),we(e),Ve(e,i);break;case"firefox":if(!ve||!me||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),s;r("adapter.js shimming firefox."),s.browserShim=ve,$e(e,i),he(e,i),me(e,i),Re(e),Te(e),pe(e),Se(e),Ce(e),Ie(e),Ee(e),ge(e),fe(e),Me(e),Be(e),xe(e,i),we(e);break;case"edge":if(!le||!_e||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),s;r("adapter.js shimming edge."),s.browserShim=le,ce(e),de(e),_e(e,i),ue(e),xe(e,i),we(e);break;case"safari":if(!Pe||!t.shimSafari)return r("Safari shim is not included in this adapter release."),s;r("adapter.js shimming safari."),s.browserShim=Pe,$e(e,i),be(e),ye(e),Ae(e),Oe(e),Le(e),ke(e),De(e),Ue(e),Me(e),xe(e,i),we(e),Ve(e,i);break;default:r("Unsupported browser!")}return s}({window:"undefined"==typeof window?void 0:window});var Ke,je,He;!function(e){e.FPS_10="FPS_10",e.FPS_15="FPS_15",e.FPS_24="FPS_24",e.FPS_30="FPS_30"}(Ke||(Ke={})),function(e){e.W176_H132="W176_H132",e.W176_H144="W176_H144",e.W180_H180="W180_H180",e.W240_H180="W240_H180",e.W240_H240="W240_H240",e.W256_H144="W256_H144",e.W320_H180="W320_H180",e.W320_H240="W320_H240",e.W360_H360="W360_H360",e.W480_H360="W480_H360",e.W480_H480="W480_H480",e.W640_H360="W640_H360",e.W640_H480="W640_H480",e.W720_H480="W720_H480",e.W848_H480="W848_H480",e.W960_H720="W960_H720",e.W1280_H720="W1280_H720",e.W1920_H1080="W1920_H1080"}(je||(je={})),function(e){e[e.AUDIO_ONLY=0]="AUDIO_ONLY",e[e.VIDEO_ONLY=1]="VIDEO_ONLY",e[e.AUDIO_VIDEO=2]="AUDIO_VIDEO"}(He||(He={}));const Je={[je.W176_H132]:{width:176,height:132,maxBitrate:150,minBitrate:80},[je.W176_H144]:{width:176,height:144,maxBitrate:150,minBitrate:80},[je.W180_H180]:{width:180,height:180,maxBitrate:200,minBitrate:100},[je.W240_H180]:{width:240,height:180,maxBitrate:240,minBitrate:120},[je.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[je.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[je.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[je.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[je.W360_H360]:{width:360,height:360,maxBitrate:520,minBitrate:140},[je.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[je.W480_H480]:{width:480,height:480,maxBitrate:800,minBitrate:180},[je.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[je.W640_H480]:{width:640,height:480,maxBitrate:900,minBitrate:200},[je.W720_H480]:{width:720,height:480,maxBitrate:1e3,minBitrate:200},[je.W848_H480]:{width:848,height:480,maxBitrate:1860,minBitrate:200},[je.W960_H720]:{width:960,height:720,maxBitrate:2e3,minBitrate:250},[je.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[je.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},qe=e=>{const t={192:180,368:360,1088:1080};return t[e]?t[e]:e},We=(e,t)=>{e=qe(e),t=qe(t);const r=Je[`W${e}_H${t}`];if(r)return r;const i=e*t;return Object.keys(Je).map((e=>Je[e])).sort(((e,t)=>e.height*e.width-t.width*t.height)).filter((e=>e.height*e.width>=i))[0]||Je.W1920_H1080},Ye={10:1,15:1,24:1.5,30:1.5},Qe=e=>{let t=Number.MAX_VALUE,r=1;for(const i in Ye){const s=Math.abs(e-parseInt(i));s<t&&(t=s,r=Ye[i])}return r},ze={getCameras:()=>v(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))})),getMicrophones:()=>v(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))})),getSpeakers:()=>v(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audiooutput"===e.kind))}))};var Ze,Xe;!function(e){e.AUDIO="audio",e.VIDEO="video"}(Ze||(Ze={}));class et extends t{constructor(e,t,r,i,s){super(),this._tag=e,this._userId=t,this._kind=r,this._isLocalTrack=i,this._roomId=s,this._localMuted=!1,this._remoteMuted=!1,this._streamId=[this._userId||this._roomId,this._tag].join("_"),this._id=[this._streamId,this.isAudioTrack()?0:1].join("_")}getStreamId(){return this._streamId}getTrackId(){return this._id}getUserId(){return this._userId}__innerGetMediaStreamTrack(){return this._msTrack}get streamTrack(){return this._msTrack}getTag(){return this._tag}isLocalTrack(){return this._isLocalTrack}isVideoTrack(){return"video"===this._kind}isAudioTrack(){return"audio"===this._kind}isReady(){var e;return"live"===(null===(e=this._msTrack)||void 0===e?void 0:e.readyState)}__innerSetMediaStreamTrack(e){this._msTrack=e,this._setLocalMuted(this._localMuted);const t=this._msStream=this._msStream||new MediaStream,r=t.getTracks()[0];r&&t.removeTrack(r),e?t.addTrack(e):this._element&&(this._element.pause(),this._element.srcObject=null)}_setLocalMuted(e){this._msTrack&&(this._msTrack.enabled=!e),this._localMuted=e}mute(){return O.info(`set ${this._id} enabled: false`),r.info(A.L_TRACK_MUTE_O,{status:D.SUCCESSED,id:this._id},{logSource:i.RTC}),this._setLocalMuted(!0)}unmute(){return O.info(`set ${this._id} enabled: true`),r.info(A.L_TRACK_UNMUTE_O,{status:D.SUCCESSED,id:this._id},{logSource:i.RTC}),this._setLocalMuted(!1)}isLocalMuted(){return this._localMuted}isMCUTrack(){return Boolean(this._roomId)}isOwnerMuted(){return this._remoteMuted}play(e,t){return v(this,void 0,void 0,(function*(){if(r.info(A.L_TRACK_PLAY_T,{element:e,options:t,msg:`start play trackId: ${this._id}`},{logSource:i.RTC}),!this._msTrack)return O.warn(`the track is not ready to play -> id: ${this._id}`),r.error(A.L_TRACK_PLAY_R,{status:D.FAILED,code:L.TRACK_NOT_READY,msg:`play error -> id: ${this._id}`},{logSource:i.RTC}),{code:L.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&(O.warn(`the track's readyState is 'ended' -> id: ${this._id}`),r.error(A.L_TRACK_PLAY_R,{status:D.FAILED,code:"",msg:`the track's readyState is ended -> id: ${this._id}`},{logSource:i.RTC})),null==t?void 0:t.volume){if(!s(null==t?void 0:t.volume))return O.error(`${null==t?void 0:t.volume} is not a number, the valid range of options.volume is 0-100`),r.error(A.L_TRACK_PLAY_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> options.volume不是数字"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};(null==t?void 0:t.volume)<0&&(t.volume=0,O.warn("the valid range of options.volume is 0-100, the value of volume has been set 0"),r.warn(A.L_TRACK_PLAY_R,{status:D.FAILED,code:"",msg:"params error -> options.volume < 0"},{logSource:i.RTC})),(null==t?void 0:t.volume)>100&&(t.volume=100,O.warn("the valid range of options.volume is 0-100, the value of volume has been set 100"),r.warn(A.L_TRACK_PLAY_R,{status:D.FAILED,code:"",msg:"params error -> options.volume > 100"},{logSource:i.RTC}))}if(null==t?void 0:t.audioDeviceId){if(!(yield ze.getSpeakers()).map((e=>e.deviceId)).includes(t.audioDeviceId))return O.error(`the options.audioDeviceId is invalid --\x3e ${t.audioDeviceId}`),r.error(A.L_TRACK_PLAY_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> options.audioDeviceId"},{logSource:i.RTC}),{code:L.PARAMS_ERROR}}const o=this.isVideoTrack();return!o||e&&(e instanceof HTMLVideoElement||this.__validateVideoNodeName(e))?(this._element=o?e:this._element||new Audio,this._localMuted&&this._setLocalMuted(!1),this._element.srcObject&&this._element.srcObject===this._msStream||this._element.pause(),this._element.onloadstart=e=>{var t,s;O.debug(`HTMLMediaElement onloadstart -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(A.L_TRACK_PLAY_R,{status:D.INFO,msg:`HTMLMediaElement onloadstart -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.ondurationchange=e=>{var t,s;O.debug(`HTMLMediaElement ondurationchange -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(A.L_TRACK_PLAY_R,{status:D.INFO,msg:`HTMLMediaElement ondurationchange -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onloadedmetadata=e=>{var t,s;O.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(A.L_TRACK_PLAY_R,{status:D.INFO,msg:`HTMLMediaElement onloadedmetadata -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onloadeddata=e=>{var t,s;O.debug(`HTMLMediaElement onloadeddata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(A.L_TRACK_PLAY_R,{status:D.INFO,msg:`HTMLMediaElement onloadeddata -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onabort=e=>{var t,s;O.info(`HTMLMediaElement onabort -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(A.L_TRACK_PLAY_R,{status:D.INFO,msg:`HTMLMediaElement onabort -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.oncanplay=e=>v(this,void 0,void 0,(function*(){var s,n,a;O.info(`HTMLMediaElement oncanplay -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`),r.info(A.L_TRACK_PLAY_R,{status:D.INFO,msg:`HTMLMediaElement oncanplay -> id: ${null===(n=e.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:i.RTC});try{yield null===(a=this._element)||void 0===a?void 0:a.play(),(null==t?void 0:t.audioDeviceId)&&!o&&(yield this._element.setSinkId(t.audioDeviceId))}catch(e){if("No permission to use requested device"===e.message)return O.error(`setSinkId failed -> ${e.message}`),void r.error(A.L_TRACK_PLAY_R,{status:D.FAILED,code:L.NO_PERMISSION_TO_USE_REQUESTED_DEVICE,msg:"No permission"},{logSource:i.RTC});O.error(e),r.error(A.L_TRACK_PLAY_R,{status:D.FAILED,code:L.TRACK_PLAY_ERROR,msg:"play error"},{logSource:i.RTC})}})),this._element.onvolumechange=e=>{var t,s;const o=Math.floor(100*(null===(t=e.target)||void 0===t?void 0:t.volume));O.info(`HTMLMediaElement onvolumechange -> volume: ${o}, trackId: ${this._id}`),r.info(A.L_TRACK_PLAY_R,{status:D.INFO,msg:`HTMLMediaElement onvolumechange -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.srcObject=this._msStream,this._element.autoplay=!0,o&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),o||!(null==t?void 0:t.volume)&&0!==(null==t?void 0:t.volume)||(this._element.volume=(null==t?void 0:t.volume)/100),r.info(A.L_TRACK_PLAY_R,{status:D.SUCCESSED,element:e,options:t},{logSource:i.RTC}),{code:L.SUCCESS}):(O.error(`the video track need an <video> to play -> id: ${this._id}`),r.error(A.L_TRACK_PLAY_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> element不是一个video标签"},{logSource:i.RTC}),{code:L.VIDEO_TRACK_MISS_MEDIA_ELEMENT})}))}__innerDestroy(){this.__innerSetMediaStreamTrack(void 0)}__releaseMediaElement(){this._element&&(this._element.remove(),this._element.srcObject=null)}__validateVideoNodeName(e){return e&&e.nodeName&&"VIDEO"===e.nodeName.toUpperCase()}}!function(e){e.Speech="Speech",e.Music="Music",e.MusicHigh="MusicHigh"}(Xe||(Xe={}));const tt={[Xe.Music]:{max:64,min:64},[Xe.MusicHigh]:{max:128,min:128},[Xe.Speech]:{max:32,min:32}};var rt;!function(e){e.LEVEL0="LEVEL0",e.LEVEL1="LEVEL1",e.LEVEL2="LEVEL2",e.LEVEL3="LEVEL3",e.LEVEL4="LEVEL4",e.LEVEL5="LEVEL5"}(rt||(rt={}));const it={[rt.LEVEL0]:{max:150,min:80},[rt.LEVEL1]:{max:280,min:120},[rt.LEVEL2]:{max:650,min:150},[rt.LEVEL3]:{max:1e3,min:200},[rt.LEVEL4]:{max:2200,min:250},[rt.LEVEL5]:{max:4e3,min:400}};class st{static setStatus(e=!0){st.isOpen=e}static setWroklet(e,t){st.workletModule=e,st.workletModule=t}static transformStreamTrack(e){var t;return v(this,void 0,void 0,(function*(){if(!st.isOpen)return new Promise((t=>{t({track:null==e?void 0:e.getAudioTracks()[0],stop:()=>{}})}));let r=new AudioContext({sampleRate:44100}),s=r.createMediaStreamSource(e),o=r.createMediaStreamDestination(),n=null,a=null;if(n=yield r.audioWorklet.addModule(st.workletModule).then((()=>(O.info(A.L_RTC_3ANOISE_NODE_O,{status:D.SUCCESSED,message:{msg:"addModule RC3AnoiseTrack.workletModule success"}},{logSource:i.RTC}),fetch(st.workletWasm,{cache:"force-cache",credentials:"same-origin"}).then((e=>e.arrayBuffer())).catch((e=>{throw new Error(e.message)}))))).then((e=>(a=new AudioWorkletNode(r,"process-worklet",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{binary:e}}),a))).catch((e=>{O.info(A.L_RTC_3ANOISE_NODE_E,{status:D.FAILED,message:{msg:e.message}},{logSource:i.RTC})})),!n)return new Promise((t=>{t({track:null==e?void 0:e.getAudioTracks()[0],stop:()=>{}})}));s.connect(n).connect(o);let c=null===(t=null==o?void 0:o.stream)||void 0===t?void 0:t.getAudioTracks()[0],d=()=>{O.info(A.L_RTC_3ANOISE_NODE_STOP_O,{status:D.SUCCESSED,message:{msg:"call stop RC3AnoiseTrack.workletModule"}},{logSource:i.RTC}),null==n||n.port.postMessage({type:"stop",msg:""}),setTimeout((()=>{const t=null==e?void 0:e.getAudioTracks()[0];null==t||t.stop(),r.suspend(),r.close(),o.disconnect(),n.disconnect(),s.disconnect(),r=null,n=null,o=null,s=null,a=null,e=null,null==c||c.stop(),c=null,d=null}),200)};return{track:c,stop:d}}))}}st.workletModule="https://cdn.ronghub.com/plugin-rtc/wasm/5.0.0-alpha.2/process-worklet.js",st.workletWasm="https://cdn.ronghub.com/plugin-rtc/wasm/5.0.0-alpha.2/AudioProcessing.wasm",st.isOpen=!1;class ot extends et{constructor(e,t,r,i){super(e,t,r,!0),this._isDestroyed=!1,this._isPublished=!1,this.__innerSetMediaStreamTrack(i),i.onended=()=>{i.onended=null,this.emit(ot.EVENT_LOCAL_TRACK_END,this),this.removeAll(ot.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(e){return new Promise(((t,s)=>{const o=this._localMuted!==e;super._setLocalMuted(e),this._remoteMuted=this._localMuted,o&&this.emit(ot.__INNER_EVENT_MUTED_CHANGE__,this,t),r.info(A.L_LOCAL_TRACK_SET_LOCAL_MUTED_O,{status:D.SUCCESSED,bool:e},{logSource:i.RTC})}))}__innerSetPublished(e){r.info(A.L_LOCAL_TRACK_INNER_SET_PUBLISHED_O,{status:D.SUCCESSED,bool:e},{logSource:i.RTC}),this._isPublished=e}isPublished(){return this._isPublished}destroy(){var e;O.info(`track is destroyed -> trackId: ${this.getTrackId()}`),this._isDestroyed=!0,null===(e=this._msTrack)||void 0===e||e.stop(),super.__innerDestroy(),this.isAudioTrack()&&super.__releaseMediaElement(),this.emit(ot.__INNER_EVENT_DESTROY__,this),r.info(A.L_LOCAL_TRACK_DESTROY_O,{status:D.SUCCESSED},{logSource:i.RTC})}isDestroyed(){return this._isDestroyed}setBitrate(e=0,t=0,o=0){if(!s(e)||!s(t)||!s(o)||e<=0||t<=0||e<t)return O.error("setBitrate params error ->"),void r.error(A.L_LOCAL_TRACK_SET_BITRATE_O,{status:D.FAILED,code:"",msg:`params error -> max: ${e},min: ${t}, start: ${o}`},{logSource:i.RTC});r.info(A.L_LOCAL_TRACK_SET_BITRATE_O,{status:D.SUCCESSED,max:e,min:t,start:o},{logSource:i.RTC}),this._bitrateInfo={max:e,min:t,start:o}}getBitrate(){var e,t,r,i,s,o,n;let{min:a,max:c,start:d}={min:0,max:0,start:0};return(null===(e=this._msTrack)||void 0===e?void 0:e.kind)===Ze.VIDEO?({min:a,max:c}=vt(this._msTrack)):(null===(t=this._msTrack)||void 0===t?void 0:t.kind)===Ze.AUDIO&&({min:a,max:c}={min:32,max:32}),(null===(r=this._bitrateInfo)||void 0===r?void 0:r.max)&&(d=.7*(null===(i=this._bitrateInfo)||void 0===i?void 0:i.max)),{min:(null===(s=this._bitrateInfo)||void 0===s?void 0:s.min)||a,max:(null===(o=this._bitrateInfo)||void 0===o?void 0:o.max)||c,start:(null===(n=this._bitrateInfo)||void 0===n?void 0:n.start)||d}}}ot.EVENT_LOCAL_TRACK_END="local-track-end",ot.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",ot.__INNER_EVENT_DESTROY__="inner-destroy";class nt extends ot{constructor(e,t,r){super(e,t,"audio",r),this._stopProcess=()=>{}}setRecommendBitrate(e){if(!o("livingType",e,(e=>e in Xe)))return void r.warn(A.L_RTC_SET_RECOMMEND_BITRATE_O,{status:D.FAILED,msg:"params error -> setRecommendBitrate Audio"},{logSource:i.RTC});const t=tt[e];this.setBitrate(t.max,t.min,t.start||.7*t.max)}setBitrate(e,...t){const[r=1,i=.7*e||1]=t;super.setBitrate(e,r,i)}__innerSetMediaStreamTrack(e){if(e)if(st.isOpen){const t=new MediaStream([e]);st.transformStreamTrack(t).then((({track:e,stop:t})=>{super.__innerSetMediaStreamTrack(e),this._stopProcess=t}))}else super.__innerSetMediaStreamTrack(e);else super.__innerSetMediaStreamTrack(e),this._stopProcess()}}class at extends ot{constructor(e,t,r,i=!1){super(e,t,"video",r),this._isTiny=i}__isTiny(){return this._isTiny}getStreamId(){const e=super.getStreamId();return this._isTiny?`${e}_tiny`:e}getTrackId(){const e=super.getTrackId();return this._isTiny?`${e}_tiny`:e}setRecommendBitrate(e){if(!o("livingType",e,(e=>e in rt)))return void r.warn(A.L_RTC_SET_RECOMMEND_BITRATE_O,{status:D.FAILED,msg:"params error -> setRecommendBitrate Video"},{logSource:i.RTC});const t=it[e];this.setBitrate(t.max,t.min,t.start||.7*t.max)}setBitrate(e,...t){const[r=1,i=.7*e||1]=t;super.setBitrate(e,r,i)}}class ct extends ot{constructor(e,t,r,i,s){super(e,t,r,i),this._resource=s,ct.__innerSetMapping(this.getTrackId(),s)}static __innerSetMapping(e,t){const r=this._mapping.get(t)||[];r.push(e),this._mapping.set(t,r)}static __innerRemoveMapping(e,t){var r,i;const s=null===(r=this._mapping.get(t))||void 0===r?void 0:r.filter((t=>t!==e));s&&s.length>0?this._mapping.set(t,s):(this._mapping.delete(t),t.pause(),t.src="",null===(i=t.parentNode)||void 0===i||i.removeChild(t))}destroy(){this.isAudioTrack()&&this.mute(),ct.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}ct._mapping=new Map;class dt extends ct{constructor(e,t,r,i){super(e,t,"video",r,i)}}class _t extends ct{constructor(e,t,r,i){super(e,t,"audio",r,i),this._stopProcess=()=>{}}_setLocalMuted(e){const t=Object.create(null,{_setLocalMuted:{get:()=>super._setLocalMuted}});return v(this,void 0,void 0,(function*(){return this._resource&&(this._resource.muted=e),t._setLocalMuted.call(this,e)}))}play(){return this._setLocalMuted(!1),Promise.resolve({code:L.SUCCESS})}__innerSetMediaStreamTrack(e){if(e)if(st.isOpen){const t=new MediaStream([e]);st.transformStreamTrack(t).then((({track:e,stop:t})=>{super.__innerSetMediaStreamTrack(e),this._stopProcess=t}))}else super.__innerSetMediaStreamTrack(e);else super.__innerSetMediaStreamTrack(e),this._stopProcess()}}class ut extends nt{}class lt extends at{}class ht extends at{}class Rt extends nt{}class mt extends et{constructor(e,t,r,i){super(e,t,r,!1,i),this._isSubscribed=!1}__innerSetRemoteMuted(e){this._remoteMuted=e}__innerSetSubscribed(e){this._isSubscribed=e,r.debug(A.L_REMOTE_TRACK_INNER_SET_SUBSCRIBED_O,{status:D.SUCCESSED,bool:e},{logSource:i.RTC})}isSubscribed(){return this._isSubscribed}}class pt extends mt{constructor(e,t,r){super(e,t,"audio",r)}}class St extends mt{constructor(e,t,r){super(e,t,"video",r),this._isSubTiny=!1}__innerSetIsTinyTrack(e){this._isSubTiny=e}isSubTiny(){return this._isSubTiny}}const Tt=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),Ct=e=>JSON.stringify(e),It=e=>/^[a-zA-Z\d-=]+$/g.test(e),Et="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),gt=e=>{if(void 0===e)return 0;if(s(e))return e;const t=e;return t.exact||t.ideal||t.max||0},ft=e=>{const t=e.getSettings(),r=e.getConstraints();return{width:gt(r.width)||t.width||0,height:gt(r.height)||t.height||0,frameRate:t.frameRate||gt(r.frameRate)}},vt=e=>{const{width:t,height:r,frameRate:i}=ft(e),s=We(t||1920,r||1080),o=Qe(i);return{min:s.minBitrate*o,max:s.maxBitrate*o}},Ot=e=>[e.msid,e.mediaType].join("_"),Lt=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},At=(e,t)=>[e,t].join("_"),Dt=e=>e.map((e=>Object.assign({},e))),Nt=(e,t,r=!1)=>{e=e.slice();const i=[],s=[],o=[];return t.forEach((t=>{const s=Ot(t);let n=e.findIndex((e=>Ot(e)===s));if(r&&(n=e.findIndex((e=>e.uri===t.uri))),-1===n)return void i.push(t);const a=e[n];a.uri!==t.uri?i.push(t):a.state!==t.state&&o.push(t),e.splice(n,1)})),s.push(...e),{publishedList:i,unpublishedList:s,modifiedList:o}},bt=()=>{let e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return e=`${e.replace(/-/g,"")}0`,e=parseInt(e,16),e=(e=>{const t="0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ+/".split(""),r=t.length+1;let i=+e;const s=[];do{const e=i%r;i=(i-e)/r,s.unshift(t[e])}while(i);return s.join("")})(e),e.length>22&&(e=e.slice(0,22)),e},kt=e=>{if(Je[e]){const{width:t,height:r}=Je[e];return{width:t,height:r}}const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},yt=e=>!!je[e],Ut=e=>!!Ke[e],Pt=e=>parseInt(e.replace("FPS_","")),Mt=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=Ge.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function xt(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function wt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const Bt=e=>"[object Null]"===Object.prototype.toString.call(e),Vt=e=>1===e.type,$t=(e,t)=>{const r={},i=Object.keys(e.users);return i.length&&i.forEach((i=>{const s=[],o=e.users[i];if(o.extra){const{roomId:e}=JSON.parse(o.extra);if(t!==e)return}if(o.uris)try{s.push(...JSON.parse(o.uris))}catch(e){O.warn(`invalid user data -> userId: ${i}, userData: ${o}`)}r[i]=s})),r},Ft=(e,t)=>{const r=t.filter((e=>"RC_RTC_SESSIONID"===e.key))[0],i=r?r.value:"",s=t.filter((e=>"RC_ANCHOR_LIST"===e.key)).map((e=>JSON.parse(e.value||"[]")))[0],o=t.filter((e=>e.key.includes("RC_RES_"))).map((e=>JSON.parse(e.value||"{}"))),n=o.length?JSON.parse(o[0].mcu_uris||"[]"):[],a=[];n.forEach((t=>{const{mediaType:r,tag:i}=t,s=r===He.AUDIO_ONLY?new pt(i,"",e):new St(i,"",e);a.push(s)}));const c=[],d=[];o.forEach((e=>{const t=JSON.parse(e.uris||"[]");c.push(...t),t.forEach((e=>{const{mediaType:t,tag:r,msid:i}=e,s=i.split("_")[0],o=t===He.AUDIO_ONLY?new pt(r,s):new St(r,s);d.push(o)}))}));const _=t.filter((e=>"RC_CDN"===e.key)).map((e=>{const t=JSON.parse(e.value||"[]");return JSON.parse(t.cdn_uris)[0]}))[0];return{sessionId:i,remoteUserIds:s||[],remoteRTCUris:c,remoteMUCUris:n,remoteRTCTracks:d,remoteMCUTracks:a,remoteTracks:[...d,...a],CDNUris:_||{}}},Gt=e=>e instanceof et?e.getTrackId():e.track.getTrackId(),Kt=e=>{if(!n(e)||void 0===e.low||void 0===e.high)return e;let{low:t}=e;t<0&&(t+=4294967296),t=t.toString(16);return parseInt(e.high.toString(16)+"00000000".replace(new RegExp(`0{${t.length}}$`),t),16)};var jt,Ht;!function(e){e.PUBLISH="RCRTC:PublishResource",e.UNPUBLISH="RCRTC:UnpublishResource",e.MODIFY="RCRTC:ModifyResource",e.TOTAL_CONTENT_RESOURCE="RCRTC:TotalContentResources",e.STATE="RCRTC:state",e.ROOM_NOTIFY="RCRTC:RoomNtf",e.USER_NOTIFY="RCRTC:UserNtf",e.KICK="RCRTC:kick",e.PK_INVITE="RCRTC:invite",e.PK_INVITE_TIMEOUT="RCRTC:inviteTimeout",e.PK_CANCEL_INVITE="RCRTC:cancelInvite",e.PK_INVITE_ANSWER="RCRTC:answerInvite",e.PK_END="RCRTC:endInvite",e.OTHER_ROOM_OFFLINE="RCRTC:otherRoomOffline",e.ROOM_TASK_FINISH="RCRTC:roomTaskFinish"}(jt||(jt={})),function(e){e.SUCCESS="Success",e.FAIL="Fail"}(Ht||(Ht={}));class Jt{constructor(e,t,r,i=5e3,s=6e4){this._roomId=e,this._roomMode=t,this._context=r,this._gap=i,this._offlineKickTime=s,this._latestTimestamp=Date.now(),this._started=!1,this._timer=null}start(){this._started||(O.info("rtcping start ->"),r.info(A.L_PINGER_START_O,{status:D.SUCCESSED,interval:this._gap},{logSource:i.RTC}),this._started=!0,this._checkAlive())}_sendPing(){return new Promise((e=>{this._context.rtcPing(this._roomId,this._roomMode).then(e).catch((t=>{O.error(`rtcping receive unknown error -> ${t}`),e(a.UNKNOWN)})),setTimeout(e,5e3,a.TIMEOUT)}))}_checkAlive(){var e,t,i;return v(this,void 0,void 0,(function*(){O.info("rtcping ->"),r.info(A.L_PINGER_SEND_RTCPING_T,{roomId:this._roomId,msg:"send rtcping"});const s=yield this._sendPing(),o=Date.now();return s===a.SUCCESS?(O.info("rtcping success ->"),r.info(A.L_PINGER_SEND_RTCPING_R,{roomId:this._roomId,msg:"send rtcping success"}),this._latestTimestamp=o,null===(e=this.onPingResult)||void 0===e||e.call(this,Ht.SUCCESS),void(this._timer=setTimeout((()=>this._checkAlive()),this._gap))):(r.info(A.L_PINGER_SEND_RTCPING_R,{roomId:this._roomId,msg:"send rtcping failed",code:s}),O.warn(`rtcping failed -> code: ${s}`),null===(t=this.onPingResult)||void 0===t||t.call(this,Ht.FAIL),40003===s||o-this._latestTimestamp>this._offlineKickTime?(this.stop(),void(null===(i=this.onFailed)||void 0===i||i.call(this,40003===s))):void(this._timer=setTimeout((()=>this._checkAlive()),500)))}))}stop(){this._started&&(O.info("rtcping stop ->"),r.info(A.L_PINGER_STOP_O,{status:D.SUCCESSED},{logSource:i.RTC}),this._started=!1,this._timer&&(clearTimeout(this._timer),this._timer=null))}}const qt=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),Wt=(e,t,r)=>v(void 0,void 0,void 0,(function*(){const i=[];return yield Promise.any(e.map((e=>v(void 0,void 0,void 0,(function*(){const s=`${e.detectorAddr.replace(/^(https?:\/\/)?/,"https://")}/rtc/detector/ping?t=${o=1e3,n=9999,o+Math.floor(Math.random()*(n-o))}`;var o,n;const a={jwt:r},d=yield t.httpReq({url:s,body:JSON.stringify(a),timeout:5e3,method:c.POST});if(O.info(`ping res => ${JSON.stringify({status:d.status,host:e})}`),200!==d.status)return Promise.reject();i.push(e.clusterId)}))))),i})),Yt=(e,t)=>v(void 0,void 0,void 0,(function*(){const r=(e=>{var t;if(!e)return"";let r;try{r=JSON.parse(e.voipCallInfo||'{ "strategy": 0 }')}catch(t){return O.warn(`parse \`voipCallInfo\` of navi failed: ${e.voipCallInfo}`),""}if(0===r.strategy)return"";const i=null===(t=r.callEngine)||void 0===t?void 0:t.filter((e=>4===e.engineType));if(!i||0===i.length)return"";const s=i[0];return s.detectorManager?s.detectorManager:""})(t),i=(s=t)&&s.jwt||"";var s;let o=null,n=120,a=0;const _={jwt:i};if(r&&i){const t=yield e.httpReq({url:`${r}/rtc/detector/servers`,body:JSON.stringify(_),headers:{"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${Mt.browser}|${Mt.version}`,ClientVersion:"5.5.2","Client-Session-Id":qt(),"Request-Id":Date.now().toString()},method:c.POST}),s=t.data&&JSON.parse(t.data).detectorAddrs;n=t.data&&JSON.parse(t.data).clientDetectMinute,a=t.data&&JSON.parse(t.data).resultCode,s&&d(s)&&(o=yield Wt(s,e,i))}return{fastMediaUrl:o,clientDetectMinute:n,status:a}}));class Qt{constructor(){}static getMemo(){return this._memo||(this._memo=new Qt),this._memo}static destroy(){this._memo={}}}const zt=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${Mt.browser}|${Mt.version}`,ClientVersion:"5.5.2","Client-Session-Id":qt(),"Request-Id":Date.now().toString()});class Zt{constructor(e,t,r,i=5e3){this._runtime=e,this._context=t,this._msUrl=r,this._timeout=i,this._msInNavi=[],this._failedMs=[],this._rtcFinger=void 0,this._clusterId="",this._configUrl="",this._msList=[],Zt.isDetector||t.getConnectionStatus()!==_.CONNECTED||this.detectorMediaSever()}detectorMediaSever(){if(this._msUrl)return;const e=Date.now(),t=Zt.detectValidMinute+Zt.detectorTime>e;Zt.isDetector=t,r.info(`set msInDetector => ${JSON.stringify(Zt.msInDetector)}`);const i=this._context.getNaviInfo();!t&&i&&u(i)&&(this._msList=[],this._getDetectorUrls(i))}_getDetectorUrls(e){return v(this,void 0,void 0,(function*(){if(Zt.isDetector)return;Zt.isDetector=!0;const{fastMediaUrl:t,clientDetectMinute:r,status:i}=yield Yt(this._runtime,e);if(i===L.JWT_TIME_OUT&&Zt.naviRefetchCount<5){this._context.getPluginContext().refetchNaviInfo().then((()=>{this.detectorMediaSever()})),++Zt.naviRefetchCount,O.info(`RCMediaService refetch navi count => ${Zt.naviRefetchCount}`)}Zt.msInDetector=t||[],Zt.detectorTime=Date.now(),Zt.detectValidMinute=60*r*1e3,O.info(`RCMediaService detectorTime => ${Zt.detectorTime}`),O.info(`RCMediaService detectValidMinute => ${Zt.detectValidMinute}`)}))}getNaviMS(){return this._msUrl?[this._msUrl]:(l(this._msList)&&!this._clusterId||(this._msList=this.setMediaServiceList()),this._msList)}setMediaServiceList(){let e=[],t=[];return this._clusterId&&(this._clusterId=this._clusterId.replace(/^(https?:\/\/)?/,"https://"),this._msList.push(this._clusterId)),O.info(`MediaServiceList _clusterId -> ${this._clusterId}`),l(Zt.msInDetector)&&(Zt.msInDetector=Zt.msInDetector.map((e=>e.replace(/^(https?:\/\/)?/,"https://"))),this._msList.push(Zt.msInDetector[0]),e=Zt.msInDetector.concat().splice(1,Zt.msInDetector.length-1)),O.info(`MediaServiceList msInDetector ->${JSON.stringify(Zt.msInDetector)}`),0===this._msInNavi.length&&(0===this._failedMs.length?this._msInNavi.push(...(e=>{var t;if(!e)return[];let r;try{r=JSON.parse(e.voipCallInfo||'{ "strategy": 0 }')}catch(t){return O.warn(`parse \`voipCallInfo\` of navi failed: ${e.voipCallInfo}`),[]}if(0===r.strategy)return[];const i=null===(t=r.callEngine)||void 0===t?void 0:t.filter((e=>4===e.engineType));if(!i||0===i.length)return[];const s=i[0],o=[];return s.mediaServer&&o.push(s.mediaServer.replace(/^(https?:\/\/)?/,"https://")),s.backupMediaServer&&s.backupMediaServer.forEach((e=>{o.push(e.replace(/^(https?:\/\/)?/,"https://"))})),o})(this._context.getNaviInfo())):(this._msInNavi.push(...this._failedMs),this._failedMs.length=0)),O.info(`MediaServiceList _msInNavi-> ${JSON.stringify(this._msInNavi)}`),t=this._msInNavi.concat().splice(1,this._msInNavi.length-1),this._msList.push(this._msInNavi[0]),this._msList=[...this._msList,...e,...t],this._msList=[...new Set(this._msList)],O.info(`MediaServiceList msList -> ${JSON.stringify(this._msList)}`),this._msList}_request(e,t,s){return v(this,void 0,void 0,(function*(){const o=Qt.getMemo();o.mediaService=[];const n=this.getNaviMS();if(0===n.length)return O.warn(`request '${e}' failed -> have no valid service address.`),r.error(A.L_MEDIA_SERVICE_REQUEST_R,{status:D.FAILED,code:L.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"invalid navi_url"},{logSource:i.RTC}),{code:L.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(s.rtcFinger=this._rtcFinger);for(let a=0;a<n.length;a+=1){const d=Date.now(),_=`${n[a]}${e}`,u=zt(),l=Object.assign(Object.assign({},u),t),h=JSON.stringify(s),R=u["Request-Id"];r.info(A.L_MEDIA_SERVICE_REQUEST_T,{path:e,headers:t,body:s,reqId:R},{logSource:i.RTC}),O.info(`request -> Request-Id: ${R}, url: ${_}, headers: ${JSON.stringify(l)}, body: ${h}, timeout: ${this._timeout}`);const{status:m,data:p}=yield this._runtime.httpReq({url:_,body:h,headers:l,method:c.POST,timeout:this._timeout});if(o.mediaService.push({start:d,end:Date.now(),reqId:R,status:m,url:_}),200===m){const e=JSON.parse(p);return e.rtcFinger&&(this._rtcFinger=e.rtcFinger),e.clusterId&&(this._clusterId=e.clusterId),O.info(`request success -> Request-Id: ${R}`),r.info(A.L_MEDIA_SERVICE_REQUEST_R,{status:D.SUCCESSED,url:_,reqId:R},{logSource:i.RTC}),{code:L.SUCCESS,data:e}}O.warn(`request failed -> Request-Id: ${R}, status: ${m}, url: ${_}`),this._failedMs.push(...this._msInNavi.splice(a,1)),r.error(A.L_MEDIA_SERVICE_REQUEST_R,{status:D.FAILED,code:"",reqId:R,url:_,msg:`request error -> Request-Id: ${R}, status: ${m}, url: ${_}`},{logSource:i.RTC})}return{code:L.REQUEST_FAILED}}))}exchange(e,t){var r;return v(this,void 0,void 0,(function*(){const i=yield this._request("/exchange",e,t);if(i.code===L.SUCCESS&&(null===(r=i.data)||void 0===r?void 0:r.resultCode)===L.SUCCESS){const{urls:e}=i.data;e&&(this._configUrl=e.configUrl)}return i}))}exit(e){return v(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/exit",e,{});return t}))}broadcastSubscribe(e,t){return this._request("/broadcast/subscribe",e,t)}broadcastExit(e){return v(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/broadcast/exit",e,{});return{code:t}}))}setMcuConfig(e,t){return v(this,void 0,void 0,(function*(){if(r.info(A.L_MEDIA_SERVICE_SET_MCU_CONFIG_T,{headers:e,body:t},{logSource:i.RTC}),!this._configUrl)return O.warn("RCMediaService.setMcuConfig failed -> RCRTCCode.MCU_SERVER_NOT_FOUND"),r.error(A.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:D.FAILED,code:L.MCU_SERVER_NOT_FOUND,msg:"MCU not found"},{logSource:i.RTC}),{code:L.MCU_SERVER_NOT_FOUND};const s=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,o=zt(),n=Object.assign(Object.assign({},o),e),a=JSON.stringify(t),d=o["Request-Id"];O.info(`request -> Request-Id: ${d}, url: ${s}, headers: ${JSON.stringify(n)}, body: ${a}`);const{status:_,data:u}=yield this._runtime.httpReq({url:s,headers:n,body:a,method:c.POST});if(200===_){O.info(`request success -> Request-Id: ${d}`);const e=JSON.parse(u);return r.info(A.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:D.SUCCESSED,reqId:d},{logSource:i.RTC}),{code:e.resultCode,res:e}}return O.warn(`request failed -> Request-Id: ${d}, status: ${_}, url: ${s}`),r.error(A.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:D.FAILED,code:L.REQUEST_FAILED,msg:`request error -> Request-Id: ${d}, status: ${_}, url: ${s}`},{logSource:i.RTC}),{code:L.REQUEST_FAILED}}))}getCDNResourceInfo(e,t){return v(this,void 0,void 0,(function*(){r.info(A.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_T,{headers:e,url:t},{logSource:i.RTC});const s=zt(),o=Object.assign(Object.assign({},s),e),n=s["Request-Id"];O.info(`request -> Request-Id: ${n}, url: ${t}, headers: ${JSON.stringify(o)}`);const{status:a,data:d}=yield this._runtime.httpReq({url:t,headers:o,method:c.GET});if(200===a){O.info(`request success -> Request-Id: ${s["Request-Id"]}`);const e=JSON.parse(d);return r.info(A.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:D.SUCCESSED,reqId:s["Request-Id"]},{logSource:i.RTC}),{code:e.resultCode,res:e}}return O.warn(`request failed -> Request-Id: ${s["Request-Id"]}, status: ${a}, url: ${t}`),r.info(A.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:D.FAILED,code:L.REQUEST_FAILED,msg:`request error -> Request-Id: ${s["Request-Id"]}, status: ${a}, url: ${t}`},{logSource:i.RTC}),{code:L.REQUEST_FAILED}}))}}var Xt;Zt.isDetector=!1,Zt.msInDetector=[],Zt.detectorTime=0,Zt.detectValidMinute=72e5,Zt.naviRefetchCount=0,function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(Xt||(Xt={}));const er=(e,t)=>Math.round(8*t/e),tr=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},rr=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.round(e*r)},ir=(e,t,r,i)=>{if(0===t)return 0;if(!r||!i)return tr(e/t,3);const s=t-i;if(0===s)return 0;const o=e-r;return o<0||s<0?0:tr(o/s,3)},sr=e=>{const{jitter:t,rtt:r,packetsLostRate:i}=e;return!Bt(t)||!Bt(r)||0!==i};class or{constructor(e,t,r){this._rtcPeerConn=e,this._sdpSemantics=t,this._currentUserId=r,this._latestPacketsSent={},this._latestBytesSent={},this._latestBytesRecv={},this._latestPacketsRecv={}}updateBytesSent(e,t,r){let i,s;if(this._latestBytesSent[e]&&t<this._latestBytesSent[e].bytesSent&&this.clearLatestpacketsSent([e]),this._latestBytesSent[e]){const{bytesSent:o,timestamp:n}=this._latestBytesSent[e];i=t-o,s=r-n,this._latestBytesSent[e]={bytesSent:t,timestamp:r}}else i=t,s=1e3,this._latestBytesSent[e]={bytesSent:t,timestamp:r};return er(s,i)}updateBytesRecv(e,t,r){let i,s;if(this._latestBytesRecv[e]&&t<this._latestBytesRecv[e].bytesRecv&&this.clearLatestPacketsRecv([e]),this._latestBytesRecv[e]){const{bytesRecv:o,timestamp:n}=this._latestBytesRecv[e];i=t-o,s=r-n,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r}}else i=t,s=1e3,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r};return er(s,i)}updateSenderPacketsLost(e,t,r){let i;if(Object.prototype.hasOwnProperty.call(this._latestPacketsSent[e],"packetsSent")){const{packetsLost:s,packetsSent:o}=this._latestPacketsSent[e];i=ir(t,r,s,o),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=s===t?o:r}else i=ir(t,r),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=r;return i}updateReceiverPacketsLost(e,t,r){let i;if(this._latestPacketsRecv[e]){const{packetsLost:s,packetsRecv:o}=this._latestPacketsRecv[e];i=ir(t,r+t,s,o+s)}else i=ir(t,r);return this._latestPacketsRecv[e]={packetsLost:t,packetsRecv:r},i}clearLatestpacketsSent(e){e.forEach((e=>{if(parseInt(e.split("_").pop())===He.VIDEO_ONLY){const t=`${e}_tiny`;delete this._latestPacketsSent[t],delete this._latestBytesSent[t]}delete this._latestPacketsSent[e],delete this._latestBytesSent[e]}))}clearLatestPacketsRecv(e){e.forEach((e=>{delete this._latestPacketsRecv[e],delete this._latestBytesRecv[e]}))}parseRTCStatsReport(e){const t={};for(const r of e.keys())r.includes("RTCCodec_")||(t[r]=e.get(r));return t}formatRCRTCStateReport(e){const t={senders:[],receivers:[]};return r.info(A.L_ABSTRACT_STAT_PARSER_FORMAT_RTC_STATE_REPORT_O,{status:D.SUCCESSED,stats:e,reports:t},{logSource:i.RTC}),t}getAudioLevelList(e){return[]}getResourceIdByParseSdp(e){var t,r;const{ssrc:i}=e,s=e.kind||e.mediaType,o=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,n=null===(r=this._rtcPeerConn.currentRemoteDescription)||void 0===r?void 0:r.sdp;let a;a="unified-plan"===this._sdpSemantics?new RegExp("a=msid:(.*?) "):new RegExp(`a=ssrc:${i} msid:(.*?) `);const c=null==o?void 0:o.split("\r\nm="),d=null==c?void 0:c.filter((e=>e.includes(`a=ssrc:${i}`)))[0],_=null==d?void 0:d.match(a);let u=_?_[1]:"";if(u){if("audio"===s)return`${u}_0`;const e=u.replace(`${this._currentUserId}_`,"").split("_");return e.length>1&&"tiny"===e[1]?`${this._currentUserId}_${e[0]}_1_tiny`:`${u}_1`}const l=null==n?void 0:n.split("\r\nm="),h=null==l?void 0:l.filter((e=>e.includes(`a=ssrc:${i}`)))[0],R=null==h?void 0:h.match(a);return u=R?R[1]:"",u?`${u}_${"video"===s?1:0}`:""}isValidSender(e){var t;const r=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}isValidReceiver(e){var t;const r=null===(t=this._rtcPeerConn.currentRemoteDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}}class nr extends or{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let s=0,o=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const n=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const{id:a,kind:c,transportId:d,mediaSourceId:_,remoteId:u,packetsSent:l,bytesSent:h,trackId:R,encoderImplementation:m,pliCount:p,nackCount:S,firCount:T}=n;if(!R)return;let{framesPerSecond:C,frameWidth:I,frameHeight:E}=n;"video"!==c||I||E||C||(I=e[R].frameWidth,E=e[R].frameHeight,C=_?e[_].framesPerSecond:null);const g=e[u];let f=null,v=null,O=0;g&&(f=g.jitter,v=g.roundTripTime,O=g.packetsLost),s+=O;const L=this.getResourceIdByParseSdp(n);if(!L)return;const A=_?e[_].audioLevel:e[R].audioLevel;let D=null;!this._latestPacketsSent[L]&&(this._latestPacketsSent[L]={}),g?D=this.updateSenderPacketsLost(L,O,l):this._latestPacketsSent[L].crtPacketsSent=l;let N=this.updateBytesSent(L,h,r);N<0&&(N=0),o+=N,t.senders.push({id:a,trackId:L,kind:c,packetsLostRate:D,remoteResource:!1,audioLevel:A||0===A?rr(A):null,frameWidth:I,frameHeight:E,frameRate:C,bitrate:N,jitter:f?Math.round(1e3*f):f,rtt:v,encoderImplementation:m,pliCount:p,nackCount:S,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));i.filter((e=>/RTCRemoteInboundRtp(Video|Audio)Stream_/.test(e))).forEach((r=>{const{localId:i,jitter:s,roundTripTime:o,packetsLost:n}=e[r],a=t.senders.filter((e=>e.id===i))[0];if(a&&!sr(a)){const t=this.getResourceIdByParseSdp(e[a.id]);a.jitter=Math.round(1e3*s),a.rtt=o;const r=this._latestPacketsSent[t].crtPacketsSent;a.packetsLostRate=this.updateSenderPacketsLost(t,n,r)}}));let n=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const o=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:_,bytesReceived:u,framesPerSecond:l,kind:h,codecImplementationName:R,nackCount:m,pliCount:p}=o;if(!a)return;let{frameWidth:S,frameHeight:T,audioLevel:C}=o;"video"===h?S||T||(S=e[a].frameWidth,T=e[a].frameHeight):C||(C=e[a].audioLevel),s+=c;const I=this.getResourceIdByParseSdp(o),E=this.updateReceiverPacketsLost(I,c,d);let g=this.updateBytesRecv(I,u,r);g<0&&(g=0),n+=g,t.receivers.push({trackId:I,kind:h,packetsLostRate:E,remoteResource:!0,audioLevel:C||0===C?rr(C):null,frameWidth:S,frameHeight:T,frameRate:l,bitrate:g,jitter:_?Math.round(1e3*_):0,codecImplementationName:R,nackCount:m,pliCount:p,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:_,remoteCandidateId:u}=r,l=e[_],{ip:h,port:R,networkType:m}=l,p=e[u],{ip:S,port:T,protocol:C}=p;t.iceCandidatePair={IP:h,port:R,networkType:m,remoteIP:S,remotePort:T,protocol:C,bitrateRecv:n,bitrateSend:o,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:s},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTPAudioStream_/.test(e))).forEach((r=>{var i;const s=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(s))return;const{mediaSourceId:o,trackId:n}=s,a=this.getResourceIdByParseSdp(s),c=o&&e[o]?e[o].audioLevel:(null===(i=e[n])||void 0===i?void 0:i.audioLevel)||null;t.push({trackId:a,audioLevel:c||0===c?rr(c):null})}));return r.filter((e=>/^RTCInboundRTPAudioStream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:s}=i,o=i.audioLevel||e[s].audioLevel,n=this.getResourceIdByParseSdp(i);t.push({trackId:n,audioLevel:o||0===o?rr(o):null})})),t}}class ar extends or{formatRCRTCStateReport(e){const t=+new Date,r={senders:[],receivers:[],timestamp:t};let i=0,s=0,o=0;for(const n in e){const a=e[n],{type:c}=a;if("outbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(a))continue;const{id:o,kind:n,bytesSent:c,packetsSent:d,bitrateMean:_,framerateMean:u,nackCount:l,pliCount:h,remoteId:R}=a,{jitter:m,roundTripTime:p,packetsLost:S}=R?e[R]:{jitter:null,roundTripTime:null,packetsLost:0},T=this.getResourceIdByParseSdp(a);i+=S;let C=null;!this._latestPacketsSent[T]&&(this._latestPacketsSent[T]={}),R?C=this.updateSenderPacketsLost(T,S,d):this._latestPacketsSent[T].crtPacketsSent=d;let I=0;"video"===n?_&&(I=Math.floor(_/1e3)):I=this.updateBytesSent(T,c,t),I<0&&(I=0),s+=I,r.senders.push({trackId:T,kind:n,packetsLostRate:C,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:I,jitter:m?Math.round(1e3*m):null,rtt:p,encoderImplementation:null,pliCount:h,nackCount:l,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}if("remote-inbound-rtp"===c){const{localId:t}=a,i=this.getResourceIdByParseSdp(e[t]),s=r.senders.filter((e=>e.trackId===i))[0];s&&sr(s)&&(s.jitter=Math.round(1e3*a.jitter),s.rtt=a.rtt,s.packetsLostRate=this.updateSenderPacketsLost(i,a.packetsLost,this._latestPacketsSent[i].crtPacketsSent))}if("inbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(a))continue;const{id:e,packetsLost:s,bytesReceived:n,packetsReceived:c,jitter:d,framerateMean:_,kind:u,bitrateMean:l,nackCount:h,pliCount:R}=a,m=this.getResourceIdByParseSdp(a);i+=s;const p=this.updateReceiverPacketsLost(m,s,c);let S=0;"video"===u?l&&(S=Math.floor(l/1e3)):S=this.updateBytesRecv(m,n,t),S<0&&(S=0),o+=S,r.receivers.push({trackId:m,kind:u,packetsLostRate:p,remoteResource:!0,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(_),bitrate:S,jitter:d?Math.round(1e3*d):null,codecImplementationName:null,nackCount:h,pliCount:R,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}if("candidate-pair"===c&&"succeeded"===a.state){const t=e[a.localCandidateId],{address:n,port:c}=t,d=e[a.remoteCandidateId],{address:_,port:u,protocol:l}=d;r.iceCandidatePair={IP:n,port:c,networkType:null,remoteIP:_,remotePort:u,protocol:l,bitrateRecv:o,bitrateSend:s,rtt:null,availableOutgoingBitrate:null,availableIncomingBitrate:null,totalPacketsLost:i}}}return r.iceCandidatePair&&(r.iceCandidatePair.bitrateSend=s),r.iceCandidatePair&&(r.iceCandidatePair.bitrateRecv=o),r}getAudioLevelList(e){const t=[];for(const r in e){const i=e[r],{type:s}=i;if("outbound-rtp"===s){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}if("inbound-rtp"===s){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}}return t}}class cr extends or{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let s=0,o=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const s=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(s))return;const n=this.getResourceIdByParseSdp(s),{mediaType:a,transportId:c,remoteId:d,packetsSent:_,bytesSent:u,trackId:l,encoderImplementation:h,pliCount:R,nackCount:m,firCount:p}=s;if(!l)return;const{audioLevel:S,frameHeight:T,frameWidth:C}=e[l];let I=this.updateBytesSent(n,u,r);I<0&&(I=0),o+=I,t.senders.push({trackId:n,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:S||0===S?rr(S):null,frameWidth:C,frameHeight:T,frameRate:null,bitrate:I,jitter:null,rtt:null,encoderImplementation:h,pliCount:R,nackCount:m,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));let n=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const o=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:_,bytesReceived:u,mediaType:l,nackCount:h,pliCount:R}=o,m=this.getResourceIdByParseSdp(o);if(!a)return;const{frameHeight:p,frameWidth:S,audioLevel:T}=e[a];s+=c;const C=this.updateReceiverPacketsLost(m,c,d);let I=this.updateBytesRecv(m,u,r);I<0&&(I=0),n+=I,t.receivers.push({trackId:m,kind:l,packetsLostRate:C,remoteResource:!0,audioLevel:T||0===T?rr(T):null,frameWidth:S,frameHeight:p,frameRate:null,bitrate:I,jitter:_,codecImplementationName:null,nackCount:h,pliCount:R,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:_,remoteCandidateId:u}=r,l=e[_],{address:h,port:R}=l,m=e[u],{address:p,port:S,protocol:T}=m;t.iceCandidatePair={IP:h||null,port:R,networkType:null,remoteIP:p,remotePort:S,protocol:T,bitrateRecv:n,bitrateSend:o,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:s},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const{trackId:s,mediaType:o}=i;if("video"===o)return;const n=this.getResourceIdByParseSdp(i),a=e[s];t.push({trackId:n,audioLevel:a||0===a?rr(a):null})}));return r.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:s,mediaType:o}=i;if(!s||"video"===o)return;const{audioLevel:n}=e[s],a=this.getResourceIdByParseSdp(i);t.push({trackId:a,audioLevel:n||0===n?rr(n):null})})),t}}class dr{constructor(e,t){this.SDP=e,this.type=t,this.SDPHeader="",this.videoStreams=[],this.audioStreams=[];const r=this.getStreamIndex();this.spliteStreams(r)}get videoSdps(){return this.videoStreams.slice()}get audioSdps(){return this.audioStreams.slice()}static trimBlankLine(e){return e.replace(/\n\r\s*\r\n/g,"\r\n").replace(/\s+\r\n/g,"\r\n")}getStreamIndex(){const e=new RegExp("m=(?:video|audio)","img"),t=new Set([0]);let r=e.exec(this.SDP);for(;null!==r;)t.add(null==r?void 0:r.index),r=e.exec(this.SDP);return t.add(this.SDP.length),[...t]}spliteStreams(e){this.SDPHeader=this.SDP.substring(e[0],e[1]).replace(/\r\ns=-/g,`\r\ns=${(new Date).valueOf()}`);for(let t=1;t<e.length;t++){const r=this.SDP.substring(e[t],e[t+1]);/^\bm=video\b/.test(r)?this.videoStreams.push(r):this.audioStreams.push(r)}}static clearInactiveOrRecvonly(e){return/\ba=(recvonly|inactive)\b/.test(e)?e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,""):e}setHeaderBitrate(e){this.SDPHeader=this.SDPHeader.replace(/(\r\ns=[^\r\n]+)/gi,`$1\r\nc=IN IP4 0.0.0.0\r\nb=AS:${e*dr.KBitrate}\r\nb=TIAS:${e*dr.KBitrate*850}`)}setAudiosBitrate(e){return O.info(A.L_RTC_SDP_BITRATE_O,{bitrate:e,msg:"SDP setAudiosBitrate"},{logSource:i.RTC}),this.audioStreams=this.audioStreams.map((t=>this.setAudioItemBitrate(t,e))),this}setAudioBitrateWithStreamId(e,t){return O.info(A.L_RTC_SDP_BITRATE_O,{bitrate:e,streamId:t,msg:"SDP setAudioBitrateWithStreamId"},{logSource:i.RTC}),this.audioStreams=this.audioStreams.map((r=>new RegExp(`\\bmsid:${t}\\b`,"ig").test(r)?this.setAudioItemBitrate(r,e):r)),this}setAudioBitrateWithMid(e,t){return O.info(A.L_RTC_SDP_BITRATE_O,{bitrate:e,mid:t,msg:"SDP setAudioBitrateWithMid"},{logSource:i.RTC}),this.audioStreams=this.audioStreams.map((r=>new RegExp(`\\bmid:${t}\\b`,"ig").test(r)?this.setAudioItemBitrate(r,e):r)),this}setAudioItemBitrate(e,t){if(0===t.max&&/\ba=inactive\b/gi.test(e))return e;if(!/\bmaxaveragebitrate\b/gi.test(e)){const r=["$1","maxaveragebitrate="+t.max*dr.KBitrate];e=e.replace(/(\buseinbandfec=[^\r\n]+)/gi,r.join(";"))}return this.addAudioBlineAS(e,t)}addAudioBlineAS(e,t){return/\bb=AS:\d+\b/gi.test(e)?e:e.replace(/(\bc=IN[^\r\n]+)/gi,`$1\r\nb=AS:${t.max*dr.KBitrate}\r\nb=TIAS:${t.max*dr.KBitrate*850}`)}setVideosBitrate(e){return O.info(A.L_RTC_SDP_BITRATE_O,{bitrate:e,msg:"SDP setVideosBitrate"},{logSource:i.RTC}),this.videoStreams=this.videoStreams.map((t=>this.setVideoItemBitrate(t,e))),this}setVideoBitrateWithStreamId(e,t){return O.info(A.L_RTC_SDP_BITRATE_O,{bitrate:e,streamId:t,msg:"SDP setVideoBitrateWithStreamId"},{logSource:i.RTC}),this.videoStreams=this.videoStreams.map((r=>new RegExp(`\\bmsid:${t}\\b`,"ig").test(r)?this.setVideoItemBitrate(r,e):r)),this}setVideoBitrateWithMid(e,t){return O.info(A.L_RTC_SDP_BITRATE_O,{bitrate:e,mid:t,msg:"SDP setVideoBitrateWithMid"},{logSource:i.RTC}),this.videoStreams=this.videoStreams.map((r=>new RegExp(`\\bmid:${t}\\b`,"ig").test(r)?this.setVideoItemBitrate(r,e):r)),this}setVideoItemBitrate(e,t){if(0===t.max&&/\ba=inactive\b/gi.test(e))return e;if(!/\bx-google-max-bitrate\b/.test(e)){console.log("old:",e);const r=["$1","x-google-max-bitrate="+t.max*dr.KBitrate,"x-google-min-bitrate="+t.min*dr.KBitrate,`x-google-start-bitrate=${t.start||t.max*dr.KBitrate*.7}`];e=e.replace(/(\bprofile-level-id=42[e0]01f\b)/gi,r.join(";"))}return this.addVideoBlineAS(e,t)}addVideoBlineAS(e,t){return/\bb=AS:\d+\b/gi.test(e)?e:e.replace(/(\bc=IN[^\r\n]+)/gi,`$1\r\nb=AS:${t.max*dr.KBitrate}\r\nb=TIAS:${t.max*dr.KBitrate*850}`)}clearnSsrcWithMid(e,t){return this.audioStreams=this.audioStreams.map((r=>new RegExp(`\\bmid:${e}\\b`,"ig").test(r)?this.clearSSRC(r,t):r)),this.videoStreams=this.videoStreams.map((r=>new RegExp(`\\bmid:${e}\\b`,"ig").test(r)?this.clearSSRC(r,t):r)),this}clearSSRC(e,t){if(t===ur.SENDONLY){if(/\ba=sendonly\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}if(t===ur.RECVONLY){if(/\ba=recvonly\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}if(t===ur.INACTIVE){if(/\ba=inactive\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}return e}}var _r,ur,lr,hr,Rr,mr,pr,Sr,Tr,Cr,Ir,Er,gr,fr,vr,Or,Lr;dr.KBitrate=1,function(e){e.PLANB="plan-b",e.UNIFIEDPLAN="unified-plan"}(_r||(_r={})),function(e){e.SENDONLY="sendonly",e.RECVONLY="recvonly",e.INACTIVE="inactive"}(ur||(ur={}));class Ar{constructor(e){this._peer=e,this._outboundStreams={}}static setSdpSemantics(e){r.info(A.L_A_SDP_STRATEGY_SET_SDP_SEMANTICS_O,{status:D.SUCCESSED,sdpSemantics:e},{logSource:i.RTC});const{browser:t,version:s,supportsUnifiedPlan:o}=Mt;r.debug(`sdpSemantics, browser: ${t}, version: ${s}, supportsUnifiedPlan: ${o}`),o?/chrome/i.test(t)?this._sdpSemantics=s>92?"unified-plan":s<72?"plan-b":e:/firefox/i.test(t)?this._sdpSemantics="unified-plan":/safari/i.test(t)?this._sdpSemantics=s<12?"plan-b":"unified-plan":this._sdpSemantics="unified-plan":this._sdpSemantics="plan-b"}static getSdpSemantics(){return Ar._sdpSemantics}getOutboundVideoInfo(){const e=[];for(const t in this._outboundStreams){const r=this._outboundStreams[t].getVideoTracks()[0];if(!r)continue;const i=/_tiny$/.test(t),{width:s,height:o}=ft(r);e.push({trackId:r.id,simulcast:i?Xt.TINY:Xt.NORMAL,resolution:`${s}x${o}`})}return e}setRemoteAnswer(e){return v(this,void 0,void 0,(function*(){e=dr.trimBlankLine(e),O.info(`set remote answer -> ${e}`);try{yield this._peer.setRemoteDescription({type:"answer",sdp:e})}catch(e){return O.error(e),r.info(A.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:D.FAILED,code:"",msg:e},{logSource:i.RTC}),L.SET_REMOTE_DESCRIPTION_FAILED}return r.info(A.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:D.SUCCESSED,sdp:e},{logSource:i.RTC}),L.SUCCESS}))}getStatParsr(e,t,r){return/chrome/i.test(Mt.browser)?new nr(e,t,r):/Firefox/i.test(Mt.browser)?new ar(e,t,r):/Safari/i.test(Mt.browser)?new cr(e,t,r):null}resetSdp(e){return dr.trimBlankLine(e)}}class Dr extends dr{constructor(e){super(e,_r.PLANB),this.SDP=e}stringify(){const e=[this.SDPHeader];[...this.audioStreams,...this.videoStreams].forEach((t=>{const r=t.match(/\ba=mid:(video|audio)\b/),i=dr.clearInactiveOrRecvonly(t);r&&r[1]===Ze.AUDIO&&(e[1]=i),r&&r[1]===Ze.VIDEO&&(e[2]=i)}));const t=e.join("");return dr.trimBlankLine(t)}setAudioBitrateWithStreamId(e,t){return O.warn("plan-b not support set Audio Bitrate With Stream Id"),this}setVideoBitrateWithStreamId(e,t){return O.warn("plan-b not support set Video Bitrate With Stream Id"),this}}class Nr extends Ar{constructor(){super(...arguments),this.senders={},this._localTracks=[]}addLocalTrack(e){this._localTracks.includes(e)||this._localTracks.push(e);const t=e.getStreamId(),r=e.__innerGetMediaStreamTrack(),i=this._outboundStreams[t]||(this._outboundStreams[t]=new MediaStream);i.getTracks().forEach((e=>{e.kind===r.kind&&i.removeTrack(e)})),i.addTrack(r);const s=e.getTrackId(),o=this.senders[s];o?o.replaceTrack(r):this.senders[s]=this._peer.addTrack(r,i)}removeLocalTrack(e){const t=this._localTracks.findIndex((t=>t===e));t>=0&&this._localTracks.splice(t,1);const r=e.getTrackId(),i=this.senders[r];i&&(i.replaceTrack(null),this._peer.removeTrack(i),delete this.senders[r])}updateSubRemoteTracks(e){}updateRecvTransceiverMap(e,t){}setBitrate(e,t,r){this._maxBitrate=e,this._minBitrate=t,this._startBitrate=r||.7*e}createOffer(e){return v(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0});for(const e in this._outboundStreams){const r=this._outboundStreams[e].id;t.sdp=t.sdp.replace(new RegExp(r,"g"),e)}t.sdp&&(t.sdp=dr.clearInactiveOrRecvonly(t.sdp));const s=Qt.getMemo();return r.info(A.L_QS_SET_LOCAL_DESCRIPTION_O,{identify:s.qualityStatusId},{logSource:i.RTC}),yield this._peer.setLocalDescription(t),{type:"offer",semantics:"plan-b",sdp:t.sdp}}))}setRemoteAnswer(e){return e=this.resetSdp(e),super.setRemoteAnswer(e)}resetSdp(e){const t=new Dr(e),r={max:0,min:0},i={max:0,min:0};return this._localTracks.forEach((e=>{const{min:t,max:s,start:o}=e.getBitrate();e.isAudioTrack()&&(i.max=i.max<s?s:i.max,i.min=i.min>t?t:i.min,i.max===s?i.start=o:i.start=.7*i.max),e.isVideoTrack()&&(r.max=r.max<s?s:r.max,r.min=r.min>t?t:r.min,r.max===s?r.start=o:r.start=.7*r.max)})),t.setAudiosBitrate(i),t.setVideosBitrate(r),t.stringify()}}class br extends dr{constructor(e){super(e,_r.UNIFIEDPLAN),this.SDP=e}stringify(){const e=[this.SDPHeader];[...this.audioStreams,...this.videoStreams].forEach((t=>{const r=t.match(/\ba=mid:(\d+)\b/);r&&r[1]&&(e[+r[1]+1]=t)})),this.SDPHeader="",this.videoStreams=[],this.audioStreams=[];const t=e.join("");return dr.trimBlankLine(t)}}class kr{static splitSections(e){return e.split("\nm=").map(((e,t)=>`${(t>0?`m=${e}`:e).trim()}\r\n`))}static getMediaSections(e){const t=kr.splitSections(e);return t.shift(),t}static parseExtmap(e){const t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}}static splitLines(e){return e.trim().split("\n").map((e=>e.trim()))}static parseMLine(e){const t=kr.splitLines(e)[0].substr(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}}static matchPrefix(e,t){return kr.splitLines(e).filter((e=>0===e.indexOf(t)))}static parseMsid(e){let t;const r=kr.matchPrefix(e,"a=msid:");if(1===r.length)return t=r[0].substr(7).split(" "),{stream:t[0],track:t[1]};const i=kr.matchPrefix(e,"a=ssrc:").map((e=>kr.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return i.length>0&&i[0].value?(t=i[0].value.split(" "),{stream:t[0],track:t[1]}):{stream:"",track:""}}static parseSsrcMedia(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r}static getMid(e){const t=kr.matchPrefix(e,"a=mid:")[0];if(t)return t.substr(6)}}class yr extends Ar{constructor(){super(...arguments),this._sendTransceiver={},this._localTracks={},this._recvAudio=[],this._recvVideo=[],this._recvTransceiver={},this._subedTracks=[],this.midMsid={}}setBitrate(e,t,r){O.warn("the interface named `setBitrate` is invalid while sdpSemantics value is `unified-plan`")}addLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId(),i=e.__innerGetMediaStreamTrack();this._localTracks[t]=e;const s=this._outboundStreams[r]||(this._outboundStreams[r]=new MediaStream);s.getTracks().forEach((e=>{e.kind===i.kind&&s.removeTrack(e)})),s.addTrack(i);const o=this._sendTransceiver[t];o?(o.sender.replaceTrack(i),o.direction="sendonly"):this._sendTransceiver[t]=this._peer.addTransceiver(i,{direction:"sendonly",streams:[s]})}removeLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId();e.__innerGetMediaStreamTrack(),delete this._localTracks[t];const i=this._sendTransceiver[t];if(!i)return;i.direction="inactive",this._peer.removeTrack(i.sender),i.sender.replaceTrack(null);const s=this._outboundStreams[r];(e.isAudioTrack()?s.getAudioTracks():s.getVideoTracks()).forEach((e=>s.removeTrack(e)));const o=this._sendTransceiver[`${t}_tiny`];if(!o||"inactive"===o.direction)return;o.direction="inactive";const{sender:n}=o,a=n.track;this._peer.removeTrack(n),n.replaceTrack(null);this._outboundStreams[`${r}_tiny`].removeTrack(a),a.stop()}updateRecvTransceiverMap(e,t){const{mediaType:r}=Lt(e);this._recvTransceiver[e]=t;const i=r===He.AUDIO_ONLY?this._recvAudio:this._recvVideo,s=i.findIndex((e=>e===t));s>=0&&i.splice(s,1)}updateSubRemoteTracks(e){const t=e.slice(),r=this._subedTracks.slice();this._subedTracks=e.slice();for(let e=t.length-1;e>=0;e-=1){const i=t[e],s=r.findIndex((e=>e===i));s>=0&&(t.splice(e,1),r.splice(s,1))}r.length&&r.forEach((e=>{const t=e.getTrackId();e.__innerSetMediaStreamTrack(void 0);const r=this._recvTransceiver[t];r&&(r.direction="inactive")}));const i={audio:0,video:0};t.length&&t.forEach((e=>{const t=e.isAudioTrack()?"audio":"video",r=this._recvTransceiver[e.getTrackId()];r?r.direction="recvonly":i[t]+=1}));for(let e=this._recvAudio.length;e<i.audio;e+=1)this._recvAudio.push(this._peer.addTransceiver("audio",{direction:"recvonly"}));for(let e=this._recvVideo.length;e<i.video;e+=1)this._recvVideo.push(this._peer.addTransceiver("video",{direction:"recvonly"}))}createOffer(e){return v(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e});let s=t.sdp;for(const e in this._outboundStreams){const t=this._outboundStreams[e].id;s=s.replace(new RegExp(t,"g"),e)}s=this.resetOfferSdp(s),s=s.replace(/(a=ice-options:trickle)/g,"$1\r\na=ice-options:renomination"),t.sdp=s;const o=Qt.getMemo();return r.info(A.L_QS_SET_LOCAL_DESCRIPTION_O,{identify:o.qualityStatusId},{logSource:i.RTC}),yield this._peer.setLocalDescription(t),{type:"offer",semantics:"unified-plan",sdp:s}}))}setRemoteAnswer(e){e=this.resetAnswerSdp(e);const t=/[\r\n]+\r\n[\r\n]+/g;return t.test(e)&&(O.warn(`answer sdp invalid -> ${JSON.stringify(e)}`),e=e.replace(t,"\r\n")),super.setRemoteAnswer(e)}resetOfferSdp(e){var t;const r=new br(e);for(const i in this._sendTransceiver){const s=this._sendTransceiver[i],o=null===(t=s.sender.track)||void 0===t?void 0:t.kind;let{direction:n,mid:a}=s;if(!a){kr.getMediaSections(e).forEach((e=>{kr.parseExtmap(e);const{kind:t}=kr.parseMLine(e);let{stream:r}=kr.parseMsid(e);const s=kr.getMid(e);"video"===o?/tiny$/.test(r)?r=r.replace(/tiny$/gi,"1_tiny"):r+="_1":r+="_0",r===i&&o===t&&s&&(a=s)}))}if(a){if(n===ur.SENDONLY){const e=this._localTracks[i],t=null==e?void 0:e.getBitrate();o===Ze.AUDIO&&t&&r.setAudioBitrateWithMid(t,a),o===Ze.VIDEO&&t&&r.setVideoBitrateWithMid(t,a)}n===ur.INACTIVE&&r.clearnSsrcWithMid(a,ur.INACTIVE)}}for(const e in this._recvTransceiver){const t=this._recvTransceiver[e],{direction:i,mid:s}=t;s&&i===ur.INACTIVE&&r.clearnSsrcWithMid(s,ur.RECVONLY)}return r.stringify()}resetAnswerSdp(e){var t;const r=new br(e);for(const e in this._sendTransceiver){const i=this._sendTransceiver[e],{mid:s}=i;if(s){const o=this._localTracks[e],n=null==o?void 0:o.getBitrate(),a=null===(t=i.sender.track)||void 0===t?void 0:t.kind;a===Ze.AUDIO&&n&&r.setAudioBitrateWithMid(n,s),a===Ze.VIDEO&&n&&r.setVideoBitrateWithMid(n,s)}}return r.stringify()}}!function(e){e[e.new=0]="new",e[e.checking=1]="checking",e[e.connected=2]="connected",e[e.completed=3]="completed",e[e.failed=4]="failed",e[e.disconnected=5]="disconnected",e[e.closed=6]="closed"}(lr||(lr={}));class Ur extends t{constructor(e,t,r,i){super(),this._pcName=e,this._reTryExchange=t,this._currentUserId=r,this._polarisReport=i,this.pubLocalTracks={},this._reTryExchangeTimer=null,this._reportStatsTimer=null,this._reportR3R4ToPolarisTimer=null,this._isDestroyed=!1,this._reportStatsData=null,this._originReportStatsData=null,this._reportListener=null;const s=Ar.getSdpSemantics(),o=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:s});this._sdpStrategy="plan-b"===s?new Nr(o):new yr(o),this._rtcPeerConn.oniceconnectionstatechange=this._onICEConnectionStateChange.bind(this),this._rtcPeerConn.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._rtcPeerConn.ontrack=this._onTrackReady.bind(this),this.reportParser=this._sdpStrategy.getStatParsr(this._rtcPeerConn,s,this._currentUserId)}getName(){return this._pcName}getLocalTracks(){return r.info(A.L_RTC_PEER_CONNECTION_GET_LOCAL_TRACKS_O,{status:D.SUCCESSED,trackIds:Object.keys(this.pubLocalTracks)},{logSource:i.RTC}),Object.values(this.pubLocalTracks)}_onConnectionStateChange(){O.info(`onconnectionstatechange -> ${this._rtcPeerConn.connectionState}, ${this._pcName}`),r.info(A.L_RTC_PEER_CONNECTION_CONNECTION_STATE_S,{status:D.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:i.RTC})}startAutoExecute(e=1e3){this._reportStatsTimer=setTimeout((()=>{this._reportHandle(e),this._reportStatsTimer=this.startAutoExecute()}),e)}stopAutoExecute(){clearTimeout(this._reportStatsTimer)}_onICEConnectionStateChange(){var e,t,s,o,n,a,c,d,_,u,l,m,p,S,T,C,I,E,g,f,v,L,N,b,k,y;const U=Date.now(),P=Qt.getMemo();P.iceStatusData||(P.iceStatusData={}),P.iceNewStatusData&&(P.iceOldStatusData=P.iceNewStatusData),P.iceNewStatusData={start:U,status:this._rtcPeerConn.iceConnectionState};const M={dur:0,pices:0,ices:0,rid:null===(e=P.joinRoomData)||void 0===e?void 0:e.roomId,csnid:null===(t=P.clientData)||void 0===t?void 0:t.clientSessionId,snid:"",time:0,rcdts:[],lcdts:[],cncdts:null,cr:"unknown",net:"unknown",uid:this._currentUserId};if(P.qualitySubscribeReportData=M,O.info(`oniceconnectionstatechange -> ${this._rtcPeerConn.iceConnectionState}, ${this._pcName}`),r.info(A.L_QS_SET_LOCAL_DESCRIPTION_O,{identify:P.qualityStatusId},{logSource:i.RTC}),"connected"===this._rtcPeerConn.iceConnectionState){if(!(null===(s=P.iceStatusData)||void 0===s?void 0:s.subscribeNotReport)&&(null===(o=P.iceStatusData)||void 0===o?void 0:o.subscribe)){P.iceStatusData.subscribeNotReport=!0;const e=P.iceStatusData.notFirst?0:(null===(n=P.iceNewStatusData)||void 0===n?void 0:n.start)-(null===(c=null===(a=P.iceStatusData)||void 0===a?void 0:a.subscribe)||void 0===c?void 0:c.time)||0,t=JSON.stringify(Object.assign(P.qualitySubscribeReportData,{dur:e,pices:lr[null===(d=P.iceOldStatusData)||void 0===d?void 0:d.status],ices:lr[null===(_=P.iceNewStatusData)||void 0===_?void 0:_.status],time:U}));h(R.STATISTICS,A.L_QS_SUB_ICE_STATUS_S,t,i.RTC)}if(!(null===(u=P.iceStatusData)||void 0===u?void 0:u.publishNotReport)&&(null===(l=P.iceStatusData)||void 0===l?void 0:l.publish)){P.iceStatusData.publishNotReport=!0;const e=P.iceStatusData.notFirst?0:(null===(m=P.iceNewStatusData)||void 0===m?void 0:m.start)-(null===(S=null===(p=P.iceStatusData)||void 0===p?void 0:p.publish)||void 0===S?void 0:S.time)||0,t=JSON.stringify(Object.assign(P.qualitySubscribeReportData,{dur:e,pices:lr[null===(T=P.iceOldStatusData)||void 0===T?void 0:T.status],ices:lr[null===(C=P.iceNewStatusData)||void 0===C?void 0:C.status],time:U}));h(R.STATISTICS,A.L_QS_PUB_ICE_STATUS_S,t,i.RTC)}P.iceStatusData.notFirst=!0;const e=JSON.stringify(Object.assign(P.qualitySubscribeReportData,{dur:(null===(I=P.iceNewStatusData)||void 0===I?void 0:I.start)-(null===(E=P.iceOldStatusData)||void 0===E?void 0:E.start),pices:lr[null===(g=P.iceOldStatusData)||void 0===g?void 0:g.status],ices:lr[null===(f=P.iceNewStatusData)||void 0===f?void 0:f.status],time:U,cncdts:[]}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,e,i.RTC),this._reportStatsTimer&&this.stopAutoExecute(),this.startAutoExecute()}if("failed"===this._rtcPeerConn.iceConnectionState||"disconnected"===this._rtcPeerConn.iceConnectionState){const e=JSON.stringify(Object.assign(P.qualitySubscribeReportData,{dur:(null===(v=P.iceNewStatusData)||void 0===v?void 0:v.start)-(null===(L=P.iceOldStatusData)||void 0===L?void 0:L.start),pices:lr[null===(N=P.iceOldStatusData)||void 0===N?void 0:N.status],ices:lr[null===(b=P.iceNewStatusData)||void 0===b?void 0:b.status],time:U}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,e,i.RTC),O.warn(`${this._pcName} iceconenction state is failed, exchange SDP to try again.`),r.error(A.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:D.FAILED,code:"",msg:`${this._pcName} iceconenction state is ${this._rtcPeerConn.iceConnectionState}, exchange SDP to try again.`},{logSource:i.RTC}),this._reTryExchange(),this._reTryExchangeTimer=setInterval(this._reTryExchange,15e3)}try{null===(y=null===(k=this._reportListener)||void 0===k?void 0:k.onICEConnectionStateChange)||void 0===y||y.call(k,this._rtcPeerConn.iceConnectionState,this._pcName)}catch(e){O.error("onICEConnectionStateChange error",e,this._pcName),r.error(A.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:D.FAILED,code:"",msg:`${this._pcName}, ${e}`},{logSource:i.RTC})}r.info(A.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:D.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:i.RTC})}_onTrackReady(e){if(!e.streams.length)return;const t=e.streams[0].id,{track:s}=e.receiver,o=[t,"audio"===s.kind?He.AUDIO_ONLY:He.VIDEO_ONLY].join("_");this._updateRecvTransceiverMap(o,e.transceiver);const n=Qt.getMemo();r.info(A.L_QS_TRACK_READY_O,{identify:n.qualityStatusId},{logSource:i.RTC}),this.emit(Ur.__INNER_EVENT_TRACK_READY__,e)}setBitrate(e,t,s){return v(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(e,t,s),r.info(A.L_RTC_PEER_CONNECTION_SET_BITRATE_O,{status:D.SUCCESSED,max:e,min:t,start:s},{logSource:i.RTC})}))}createOffer(e){return v(this,void 0,void 0,(function*(){const t=yield this._sdpStrategy.createOffer(e);return O.debug(`offer -> ${JSON.stringify(t.sdp)}`),r.info(A.L_RTC_PEER_CONNECTION_CREATE_OFFER_O,{status:D.SUCCESSED,offerSDP:t.sdp},{logSource:i.RTC}),t}))}setRemoteAnswer(e){return v(this,void 0,void 0,(function*(){return O.debug(`answer -> ${JSON.stringify(e)}`),r.info(A.L_RTC_PEER_CONNECTION_SET_REMOTE_ANSWER_O,{status:D.SUCCESSED,answer:e},{logSource:i.RTC}),this._sdpStrategy.setRemoteAnswer(e)}))}getLocalTrack(e){return this.pubLocalTracks[e]||null}addLocalTrack(e){this.pubLocalTracks[e.getTrackId()]=e,this._sdpStrategy.addLocalTrack(e),e.off(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.on(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.on(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),r.info(A.L_RTC_PEER_CONNECTION_ADD_LOCAL_TRACK_O,{status:D.SUCCESSED,trackId:e.getTrackId()},{logSource:i.RTC})}removeLocalTrackById(e){const t=this.getLocalTrack(e);t?(r.info(A.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:D.SUCCESSED,trackId:e},{logSource:i.RTC}),this.removeLocalTrack(t)):r.warn(A.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:D.FAILED,code:"",msg:"track not found"},{logSource:i.RTC})}removeAllLocalTrack(){Object.keys(this.pubLocalTracks).forEach((e=>{/_tiny$/.test(e)||this.removeLocalTrackById(e)})),r.info(A.L_RTC_PEER_CONNECTION_REMOVE_ALL_LOCAL_TRACK_O,{status:D.SUCCESSED},{logSource:i.RTC})}removeLocalTrack(e){const t=e.getTrackId();delete this.pubLocalTracks[t],this._sdpStrategy.removeLocalTrack(e),e.__innerSetPublished(!1),e.off(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this);const s=`${t}_tiny`,o=this.getLocalTrack(s);o&&(this._sdpStrategy.removeLocalTrack(o),delete this.pubLocalTracks[s],o.destroy()),r.info(A.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_O,{status:D.SUCCESSED,trackId:t},{logSource:i.RTC})}_updateRecvTransceiverMap(e,t){this._sdpStrategy.updateRecvTransceiverMap(e,t)}updateSubRemoteTracks(e){this._sdpStrategy.updateSubRemoteTracks(e),r.info(A.L_RTC_PEER_CONNECTION_UPDATE_SUB_REMOTE_TRACKS_O,{status:D.SUCCESSED,trackIds:e.map((e=>e.getTrackId()))},{logSource:i.RTC})}getOutboundVideoInfo(){return this._sdpStrategy.getOutboundVideoInfo()}_onLocalTrackMuted(e,t){const s=this.getLocalTrack(`${e.getTrackId()}_tiny`);s&&(s.__innerGetMediaStreamTrack().enabled=!e.isLocalMuted()),this.emit(ot.__INNER_EVENT_MUTED_CHANGE__,e,t),r.info(A.L_RTC_PEER_CONNECTION_LOCAL_TRACK_MUTED_O,{status:D.SUCCESSED,trackId:e.getTrackId()},{logSource:i.RTC})}_onLocalTrackDestroied(e){this.emit(ot.__INNER_EVENT_DESTROY__,e)}registerReportListener(e){this._reportListener=e}_createRCRTCStateReport(e){const{timestamp:t,iceCandidatePair:r,senders:i,receivers:s}=JSON.parse(JSON.stringify(e));null==r||delete r.totalPacketsLost;for(const e in r)Bt(r[e])&&delete r[e];return{timestamp:t,iceCandidatePair:r,senders:i.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),receivers:s.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),pcName:this._pcName}}_getStatsData(e=1e3){var t,r,i;return v(this,void 0,void 0,(function*(){let s=null;if((null===(t=this._originReportStatsData)||void 0===t?void 0:t.timestamp)&&this._originReportStatsData.timestamp>Date.now()-e)s=this._originReportStatsData.data;else{const e=yield this._rtcPeerConn.getStats();s=null===(r=this.reportParser)||void 0===r?void 0:r.parseRTCStatsReport(e),this._originReportStatsData={data:s,timestamp:Date.now()}}return null===(i=this.reportParser)||void 0===i?void 0:i.formatRCRTCStateReport(s)}))}getAudioLevelReportData(e=1e3){var t,r,i;return v(this,void 0,void 0,(function*(){let s=null;if((null===(t=this._originReportStatsData)||void 0===t?void 0:t.timestamp)&&this._originReportStatsData.timestamp>Date.now()-e)s=this._originReportStatsData.data;else{const e=yield this._rtcPeerConn.getStats();s=null===(r=this.reportParser)||void 0===r?void 0:r.parseRTCStatsReport(e),this._originReportStatsData={data:s,timestamp:Date.now()}}if(!s)return[];return null===(i=this.reportParser)||void 0===i?void 0:i.getAudioLevelList(s)}))}_reportHandle(e){var t,r;return v(this,void 0,void 0,(function*(){const i=yield this._getStatsData(e);if(!i)return;this._reportStatsData=i;const s=this._createRCRTCStateReport(i);null===(r=null===(t=this._reportListener)||void 0===t?void 0:t.onStateReport)||void 0===r||r.call(t,s)}))}_getCacheStatsData(){return this._reportStatsData}_sendR3R4Data(){var e;return v(this,void 0,void 0,(function*(){const t=this._getCacheStatsData();if(!t)return!0;if(t.senders.length||t.receivers.length){return yield null===(e=this._polarisReport)||void 0===e?void 0:e.sendR3R4Data(t)}}))}__reportR3R4ToPolaris(){return v(this,void 0,void 0,(function*(){clearTimeout(this._reportR3R4ToPolarisTimer),yield this._sendR3R4Data(),this._reportR3R4ToPolarisTimer=setTimeout((()=>{this.__reportR3R4ToPolaris()}),2e3)}))}getRTCPeerConn(){return this._rtcPeerConn}destroy(){this.clear(),this.clearReTryExchangeTimer(),clearTimeout(this._reportR3R4ToPolarisTimer),this._reportStatsTimer&&(this.stopAutoExecute(),this._reportStatsTimer=null),this.registerReportListener(null),this._rtcPeerConn.close(),this._isDestroyed=!0,this.reportParser=null,r.info(A.L_RTC_PEER_CONNECTION_DESTROY_O,{status:D.SUCCESSED},{logSource:i.RTC})}clearReTryExchangeTimer(){clearInterval(this._reTryExchangeTimer),this._reTryExchangeTimer=null}isDestroyed(){return this._isDestroyed}}Ur.__INNER_EVENT_TRACK_READY__="inner-track-ready",function(e){e[e.DISABLE=0]="DISABLE",e[e.ENABLE=1]="ENABLE"}(hr||(hr={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(Rr||(Rr={}));class Pr{constructor(e,t,r,i,s=Rr.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=i,this._userRole=s}_send(e){return v(this,void 0,void 0,(function*(){let t=!1;if(this._context.getConnectionStatus()!==_.CONNECTED)return t;return t=(yield this._context.setRTCState(this._roomId,e))===a.SUCCESS,t}))}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=bt(),this._runtime.localStorage.setItem(e,t)),t}_getRealResourceId(e){let t=e;const r=e.indexOf("_tiny");return r>-1&&(t=e.slice(0,r)),t}_getPolarisTrackId(e){let t="";const r=e.split("_");if(e.includes("_tiny")){const e=r.pop(),i=parseInt(r.pop())===He.AUDIO_ONLY?"audio":"video",s=r.pop();t=[r.join("_"),s,e,i].join("_")}else{const e=parseInt(r.pop())===He.AUDIO_ONLY?"audio":"video",i=r.pop();t=[r.join("_"),i,e].join("_")}return t}sendR3R4Data(e){return v(this,void 0,void 0,(function*(){const{iceCandidatePair:t,senders:r,receivers:i}=e,s=(null==t?void 0:t.bitrateSend)||-1,o=(null==t?void 0:t.bitrateRecv)||-1,n=(null==t?void 0:t.networkType)||"unknown",a=(null==t?void 0:t.rtt)||-1,c=`${(null==t?void 0:t.IP)||-1}:${null==t?void 0:t.port}`,d=(null==t||t.remoteIP,null==t||t.remotePort,(null==t?void 0:t.availableIncomingBitrate)||-1),_=(null==t?void 0:t.availableOutgoingBitrate)||-1,u=(null==t?void 0:t.totalPacketsLost)||-1,l=this._context.getCurrentId();let h=`R3\t${s}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${_}\t${u}\t${l}\r`,R=`R4\t${o}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${_}\t${u}\t${l}\r`;const m=r.map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:s,bitrate:o,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:_,jitter:u,nackCount:l,pliCount:h,rtt:R,googFirsSent:m,encoderImplementation:p}=e,S=this._getPolarisTrackId(r),T=this._getRealResourceId(r);return{trackId:S,googCodecName:p||String(-1),audioLevel:i||0===i?i:-1,bitrate:o||0===o?o:-1,packetsLostRate:n||0===n?n:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:h||0===h?h:-1,rtt:R||-1,googFirsSent:m,samplingRate:s,googRenderDelayMs:_,encoderImplementation:p||String(-1),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(T))||void 0===t?void 0:t.isLocalMuted())?hr.DISABLE:hr.ENABLE}})),p=i.filter((e=>!!e.trackId)).map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:s,bitrate:o,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:_,jitter:u,nackCount:l,pliCount:h,rtt:R,googFirsReceived:m,codecImplementationName:p}=e,S=this._getPolarisTrackId(r),T=this._getRealResourceId(r);return{trackId:S,googCodecName:p||String(-1),audioLevel:i||0===i?i:-1,bitrate:o||0===o?o:-1,packetsLostRate:n||0===n?n:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:h||0===h?h:-1,rtt:R||-1,googFirsReceived:m,samplingRate:s,googRenderDelayMs:_,codecImplementationName:p||String(-1),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(T))||void 0===t?void 0:t.isLocalMuted())?hr.DISABLE:hr.ENABLE}}));let S=!1;h+=m.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsSent}\t${e.encoderImplementation}\t${e.trackState}`)).join("\n"),e.senders.length&&(S=yield this._send(`${h}\r${this._userRole}`));let T=!1;return R+=p.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsReceived}\t${e.codecImplementationName}\t${e.trackState}`)).join("\n"),e.receivers.length&&(T=yield this._send(`${R}\r${this._userRole}`)),!(!S&&!T)}))}sendR1(){const e=`R1\t5.5.2\t${this._context.getCoreVersion()}\tweb\t${navigator.platform}\t-1\t${Mt.browser}\t${Mt.version}\t${this._getClientID()}\t${this._userRole}`;this._send(e)}sendR2(e,t,r){const i=`R2\t${e}\t${t}\t${this._getClientID()}\r${r.join("\t")}\r${this._userRole}`;this._send(i)}}class Mr{constructor(e){this._room=e,this._audioLevelChangeHandler=null,this._timer=null}_audioLevelReport(e){return v(this,void 0,void 0,(function*(){if(!this._audioLevelChangeHandler)return;const t=[],r=this._room.__getPC();for(let i=0;i<r.length;i++){const s=r[i];if("new"===s.getRTCPeerConn().iceConnectionState)return;const o=yield s.getAudioLevelReportData(e);null==o||o.forEach((e=>{const{userId:r}=Lt(e.trackId),i=this._room.getCrtUserId()===r?this._room.getLocalTrack(e.trackId):this._room.getRemoteTrack(e.trackId);i&&t.push({track:i,audioLevel:e.audioLevel||0})}))}this._audioLevelChangeHandler(t)}))}startAutoExecute(e=1e3){this._timer=setTimeout((()=>{this._audioLevelReport(e),this._timer=this.startAutoExecute(e)}),e)}stopAutoExecute(){clearTimeout(this._timer)}onAudioLevelChange(e,t){t<300||t>1e3?O.error('the valid range of onAudioLevelChange params "gap" is: > 300 && < 1000'):e?(this._audioLevelChangeHandler=e,this.startAutoExecute(t)):this._audioLevelChangeHandler=null}clearAudioLevelReportTimer(){this._timer&&(this.stopAutoExecute(),this._timer=null)}}!function(e){e[e.ANCHOR=1]="ANCHOR",e[e.AUDIENCE=2]="AUDIENCE"}(mr||(mr={}));class xr{constructor(e=!1,t,r,i,s){this._useMutilPeerC=e,this._roomId=t,this._reTryExchange=r,this._currentUserId=i,this._polarisReport=s,this._mutilPeerC={}}get useMutilPeerC(){return this._useMutilPeerC}_isPub(e){if(!e.length)return!1;const{track:t}=e[0]instanceof ot||e[0]instanceof mt?{track:e[0]}:e[0];return t.isLocalTrack()}_groupTracksByTag(e){const t={};return e.forEach((e=>{const{track:r}=e instanceof ot?{track:e}:e,i=r.getTag();t[i]?t[i].push(e):t[i]=[e]})),t}_genPCName(e,t){let r=null;return r=e?this._useMutilPeerC?`${this._roomId}_${t}`:`${this._roomId}_pub`:`${this._roomId}_sub`,r}_createOnePeerCItem(e,t){if(this._mutilPeerC[e]&&!this._mutilPeerC[e].pc.isDestroyed())this._mutilPeerC[e].tracks=t;else{const r=this._isPub(t),i=new Ur(e,(()=>this._reTryExchange(e,r)),this._currentUserId,this._polarisReport);this._mutilPeerC[e]={pc:i,tracks:t,isPub:r}}return Object.assign(Object.assign({},this._mutilPeerC[e]),{pcName:e})}createPeerCList(e){const t=[],r=this._isPub(e);if(!this._useMutilPeerC){const r=this._genPCName(!0);return t.push(this._createOnePeerCItem(r,e)),t}if(this._useMutilPeerC&&!r){const r=this._genPCName(!1);return t.push(this._createOnePeerCItem(r,e)),t}const i=this._groupTracksByTag(e);for(const e in i){const s=this._genPCName(r,e),o=i[e];t.push(this._createOnePeerCItem(s,o))}return t}_removeAllLocalTrack(){this.getPCList().forEach((e=>e.removeAllLocalTrack()))}destroyPeerC(e){this._mutilPeerC[e].pc.destroy()}_destroyAllPeerC(){this.getPCList().forEach((e=>e.destroy()))}getPCItemByPCName(e){return this._mutilPeerC[e]}getPCByTrackId(e,t=!0){const{tag:r}=Lt(e),i=this._genPCName(t,r);return this._mutilPeerC[i].pc}getPCList(){const e=[];for(const t in this._mutilPeerC)e.push(this._mutilPeerC[t].pc);return e}getMutilPeerCData(){return this._mutilPeerC}setPeerCData(e,t,r){}clear(){this._removeAllLocalTrack(),this._destroyAllPeerC()}}!function(e){e[e.Unknow=0]="Unknow",e[e.Publish=1]="Publish",e[e.UnPublish=2]="UnPublish",e[e.JoinRoom=3]="JoinRoom",e[e.LeaveRoom=4]="LeaveRoom",e[e.UpdateSubscribeTask=5]="UpdateSubscribeTask",e[e.SubscribedTask=6]="SubscribedTask",e[e.UnSubscribedTask=7]="UnSubscribedTask",e.AsyncCommand="AsyncCommand"}(pr||(pr={})),function(e){e.NORMAL="normal",e.MIDDLE="middle",e.TAIL="tail"}(Sr||(Sr={})),function(e){e[e.LOW=0]="LOW",e[e.NORMAL=1]="NORMAL",e[e.HIGH=2]="HIGH"}(Tr||(Tr={})),function(e){e[e.Destroy=40400]="Destroy"}(Cr||(Cr={}));class wr{get priority(){return Tr.LOW}get kind(){return pr.Unknow}}class Br extends wr{constructor(e=Sr.NORMAL){super(),this.state=e}get kind(){return pr.AsyncCommand}setState(e){this.state=e}pickoutSubscribed(e,t){const{unsubscribe:r,subscribe:i}=this.calcSubscribeList(e,t);return Br.AsyncSubscribeTasks=[],Br.AsyncUnsubscribeTasks=[],Br.AsyncUpdateSubscribeTasks=[],{subscribe:i,unsubscribe:r}}calcSubscribeList(e,t){const r=[],i=new Set,s=[],o=new Set,n=this.formateTrack(e),a=this.formateTrack(t);return a.forEach((e=>{const t=`${e.track.getTrackId()}_SUB_${e.subTiny?"0":"1"}`;this.trackInSubscribeList(e,n)||i.has(t)||(r.push(e),i.add(t))})),n.forEach((e=>{const t=`${e.track.getTrackId()}_SUB_${e.subTiny?"0":"1"}`;this.trackInSubscribeList(e,a)||o.has(t)||(s.push(e),o.add(t))})),{unsubscribe:r,subscribe:s}}formateTrack(e){return e.map((e=>e instanceof mt?{track:e,subTiny:!1}:Object.assign({subTiny:!1},e)))}trackInSubscribeList(e,t){if(0===t.length)return!1;return t.findIndex((t=>t.track.getTrackId()===e.track.getTrackId()&&t.subTiny===e.subTiny))>-1}}Br.AsyncSubscribeTasks=[],Br.AsyncUnsubscribeTasks=[],Br.AsyncUpdateSubscribeTasks=[];class Vr extends class{constructor(e,t,r,i,s,o,n,a,c){this.context=e,this.service=t,this.peerMgr=r,this.roomId=i,this.crtUserId=s,this.roomMode=o,this.polarisReport=n,this.isUpgrade=a,this.isMainRoom=c,this._remoteTracks={},this._subscribedList=[],this._collectSubscribeList=[],this._CDNUris=null,this._CDNEnable=!1,this._destroyed=!1}get useMutilPeerC(){return this.peerMgr.useMutilPeerC}getResourcesByUserId(e){return this._roomResources[e]}getRemoteTrack(e){return this._remoteTracks[e]}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getRemoteTracks(){return this._remoteTracks}getSessionId(){return this._sessionId}getAllUserIds(){return Object.keys(this._roomResources)}getRemoteUserIds(){return this.getAllUserIds().filter((e=>e!==this.crtUserId))}getSubscribedList(){return this._subscribedList}getCollectSubscribeList(){return this._collectSubscribeList}getPublishedResourceByTrackId(e){const{userId:t}=Lt(e);return this._roomResources[t].find((t=>Ot(t)===e))}getToken(){return this._token}getLocalTrack(e){return this.peerMgr.getPCByTrackId(e).getLocalTrack(e)}getLocalTracks(){const e=[];return this.peerMgr.getPCList().forEach((t=>{e.push(...t.getLocalTracks())})),e}getTrackState(e){var t;return(null===(t=this.getLocalTrack(e))||void 0===t?void 0:t.isLocalMuted())?0:1}getCDNEnable(){return this._CDNEnable}getCDNUris(){return this._CDNUris}}{_initRemoteTracks(){for(const e in this._roomResources){const t=this._roomResources[e];e!==this.crtUserId&&0!==t.length&&t.forEach((e=>{const t=Ot(e),{tag:r,userId:i,mediaType:s}=Lt(t),o=s===He.AUDIO_ONLY?new pt(r,i):new St(r,i);o.__innerSetRemoteMuted(0===e.state),this._remoteTracks[t]=o}))}}initWithRoomData(e){this._sessionId=e.sessionId,this._token=e.token,this.isUpgrade?this._roomResources={}:this._roomResources=$t(e,this.roomId),this._initRemoteTracks(),this.setResourcesByUserId(this.crtUserId,this.getResourcesByUserId(this.crtUserId)||[]),O.info(`room data -> ${JSON.stringify(this._roomResources)}`)}assignRoomData(e){Object.assign(this._roomResources,e)}setResourcesByUserId(e,t){this._roomResources[e]=t}removeRemoteTrack(e){delete this._remoteTracks[e]}removeResourcesByUserId(e){delete this._roomResources[e]}addRemoteTrack(e){this._remoteTracks[e.getTrackId()]=e}removeRemoteTracks(){const e=Object.values(this._remoteTracks);e.length&&(e.forEach((e=>{e.isAudioTrack()&&e.__releaseMediaElement()})),this._remoteTracks={})}setCDNEnabel(e){this._CDNEnable=e}setCDNUris(e){this._CDNUris=e}resetSubscribedList(e){this._subscribedList.splice(0,this._subscribedList.length,...e),this.resetCollectSubscribeList(e)}resetCollectSubscribeList(e){this._collectSubscribeList.splice(0,this._collectSubscribeList.length,...e)}}class $r extends class{constructor(e,t){this._store=e,this.abortCode=t,this._queue=[],this._busy=!1,this._isDestroyed=!1}_next(){this._busy=!1,this._execute()}_execute(){return v(this,void 0,void 0,(function*(){if(this._isDestroyed||this._busy||0===this._queue.length)return;this._busy=!0;const{command:e,resolve:t,reject:r}=this._queue.shift();let i;try{i=yield e.execute(this._store,this)}catch(e){return r(e),void this._next()}t(i),this._next()}))}push(e){return new Promise(((t,r)=>{if(this._isDestroyed)return;const{kind:i}=e;this._queue.length>0&&i===pr.AsyncCommand&&({command:e,resolve:t,reject:r}=this.commandOffset(e,t,r));const{priority:s}=e;if(s===Tr.LOW)this._queue.push({command:e,resolve:t,reject:r});else{const i=this._queue.findIndex((e=>e.command.priority<s)),o=-1===i?this._queue.length-1:i;this._queue.splice(o,0,{command:e,resolve:t,reject:r})}Promise.resolve().then((()=>{this._execute()}))}))}commandOffset(e,t,r){const i=this._queue.length-1;if(!(this._queue[i].command.kind===pr.AsyncCommand))return{command:e,resolve:t,reject:r};const[s]=this._queue.splice(i,1);s.command instanceof Br&&(s.command.setState(Sr.MIDDLE),e instanceof Br&&e.setState(Sr.TAIL));const o=e.execute;return e.execute=function(t,r){return v(this,void 0,void 0,(function*(){return s.command.execute.call(s.command,t,r),o.call(e,t,r)}))},{command:e,resolve:e=>{s.resolve.call(s,e),t(e)},reject:e=>{s.reject.call(s,e),r(e)}}}isDestroyed(){return this._isDestroyed}destroy(){this._isDestroyed||(this._isDestroyed=!0,this._queue.forEach((e=>{e.resolve({code:this.abortCode})})),this._queue.length=0)}}{constructor(e,t,r,i,s,o,n,a,c){super(new Vr(e,t,r,i,s,o,n,a,c),L.ROOM_HAS_BEEN_DESTROYED)}get store(){return this._store}destroy(){super.destroy(),this._store.removeRemoteTracks()}}class Fr extends wr{execute(e){return v(this,void 0,void 0,(function*(){const t=e.getResourcesByUserId(e.crtUserId),r=t.slice();t.length=0,O.info(`unpublish uris before rejoin -> ${JSON.stringify(r)}`);const i=yield e.context.setRTCTotalRes(e.roomId,Tt(jt.UNPUBLISH,r),Ct([]),jt.TOTAL_CONTENT_RESOURCE,Ct([]));i!==a.SUCCESS?O.error(`unpublish uris before rejoin failed -> code: ${i}`):O.info("unpublish uris before rejoin success")}))}}!function(e){e[e.RTC=0]="RTC",e[e.LIVE=2]="LIVE",e[e.CROSS_MUTI=7]="CROSS_MUTI",e[e.CROSS_LIVE=8]="CROSS_LIVE"}(Ir||(Ir={})),function(e){e[e.KICK=0]="KICK",e[e.REFUSE=1]="REFUSE",e[e.COEXIST=2]="COEXIST"}(Er||(Er={}));class Gr extends wr{constructor(e,t,r,i,s,o){super(),this.roomId=e,this.roomType=t,this.joinType=r,this.livingType=i,this.innerUserDatas=s,this.outerUserDatas=o}get kind(){return pr.JoinRoom}execute(e,t){var s,c,d,u,l,S;return v(this,void 0,void 0,(function*(){const T=Qt.getMemo(),C={dur:0,cod:0,rid:"",rtp:this.roomType,csnid:"",snid:"",time:0,cr:"unknown",net:"unknown",uid:""};T.qualityJoinRoomReportData=C,T.joinRoomData={start:Date.now()};const{context:I,service:E}=e;let g=A.L_RTC_CLIENT_JOIN_RTC_ROOM_R;if(this.roomType===Ir.LIVE?g=A.L_RTC_CLIENT_JOIN_LIVING_ROOM_R:this.roomType===Ir.CROSS_MUTI&&(g=A.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_R),I.getConnectionStatus()!==_.CONNECTED)return r.error(g,{status:D.FAILED,code:L.SIGNAL_DISCONNECTED,msg:"im not connected"},{logSource:i.RTC}),{code:L.SIGNAL_DISCONNECTED};if(E.detectorMediaSever(),Vt(I.getNaviInfo()))return r.error(g,{status:D.FAILED,code:L.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_usl error"},{logSource:i.RTC}),{code:L.PACKAGE_ENVIRONMENT_ERROR};if(!o("roomId",this.roomId,m,!0))return r.error(g,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(!o("roomType",this.roomType,(e=>void 0!==Ir[e])))return r.error(g,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> roomType"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(!o("outerUserDatas",this.outerUserDatas,n,!1))return r.error(g,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(this.outerUserDatas){if(!Object.keys(this.outerUserDatas).every((e=>o(`outerUserDatas.${e}`,this.outerUserDatas[e],p,!0))))return r.error(g,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:i.RTC}),{code:L.PARAMS_ERROR}}if(!E.getNaviMS().length)return r.error(g,{status:D.FAILED,code:L.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:i.RTC}),{code:L.NOT_OPEN_VIDEO_AUDIO_SERVER};O.info(`joinRoom -> roomId: ${this.roomId}; joinType: ${this.joinType||Er.KICK}`);const{code:f,data:v}=yield I.joinRTCRoom(this.roomId,this.roomType,this.livingType,this.joinType,this.innerUserDatas,this.outerUserDatas);if(f!==a.SUCCESS||!v){const t=Date.now(),o=JSON.stringify(Object.assign(T.qualityJoinRoomReportData,{dur:t-((null===(s=T.joinRoomData)||void 0===s?void 0:s.start)||0),cod:f,rid:this.roomId,csnid:null===(c=T.clientData)||void 0===c?void 0:c.clientSessionId,snid:e.getSessionId(),time:t,uid:e.crtUserId}));h(R.STATISTICS,A.L_QS_JOIN_ROOM_S,o,i.RTC),O.warn(`joinRoom failed -> code: ${f}`);const n=40032===f?L.SIGNAL_JOIN_RTC_ROOM_REFUSED:f;return r.error(g,{status:D.FAILED,code:n,msg:`joinRoom failed -> code: ${f}`},{logSource:i.RTC}),{code:n}}O.info(`joinRoom success -> userId: ${I.getCurrentId()}, roomId: ${this.roomId}, data: ${JSON.stringify(v)}`);const N=Date.now(),b=JSON.stringify(Object.assign(T.qualityJoinRoomReportData,{dur:N-((null===(d=T.joinRoomData)||void 0===d?void 0:d.start)||0),cod:f,rid:this.roomId,csnid:null===(u=T.clientData)||void 0===u?void 0:u.clientSessionId,snid:v.sessionId,time:N,uid:e.crtUserId}));h(R.STATISTICS,A.L_QS_JOIN_ROOM_S,b,i.RTC),T.joinRoomData={start:null===(l=T.joinRoomData)||void 0===l?void 0:l.start,roomId:this.roomId},e.initWithRoomData(v);e.getResourcesByUserId(e.crtUserId).length>0&&t.push(new Fr);const k=null===(S=v.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===S?void 0:S.value;return k&&e.setCDNUris(JSON.parse(k)[0]),r.info(g,{status:D.SUCCESSED,userId:e.crtUserId,roomId:this.roomId,data:v},{logSource:i.RTC}),{code:L.SUCCESS,data:v}}))}}function Kr(e,t,r,i){return v(this,void 0,void 0,(function*(){return{sdp:yield r.createOffer(t),extend:JSON.stringify({resolutionInfo:r.getOutboundVideoInfo()}),subscribeList:e.filter((e=>{const t=e.track.getTrackId(),{userId:r}=Lt(t),s=i.getResourcesByUserId(r);if(!s)return!1;const o=s.filter((e=>t===`${e.msid}_${e.mediaType}`)).length;return o})).map((e=>({simulcast:e.subTiny?Xt.TINY:Xt.NORMAL,resolution:"",uri:i.getPublishedResourceByTrackId(e.track.getTrackId()).uri}))),switchstream:!1}}))}function jr(e,t,r){return v(this,void 0,void 0,(function*(){const i=yield e.setRTCCDNUris(t,jt.TOTAL_CONTENT_RESOURCE,JSON.stringify([r]));return i!==a.SUCCESS?(O.error(`spreadCDNInfo failed -> code: ${i}`),{code:L.SIGNAL_ERROR}):(O.info("spreadCDNInfo succeed"),{code:L.SUCCESS})}))}function Hr(e,t,r){return v(this,void 0,void 0,(function*(){const i=yield e.setRTCData(t,"cdn_uris",JSON.stringify([r]),!0,Or.ROOM);return i!==a.SUCCESS?(O.error(`setRoomCDNInfo failed -> code: ${i}`),{code:L.SIGNAL_ERROR}):(O.info("setRoomCDNInfo succeed"),{code:L.SUCCESS})}))}function Jr(e){return v(this,void 0,void 0,(function*(){const{context:t}=e,{roomId:s}=e,o=Object.assign({},e.getCDNUris(),{enableInnerCDN:e.getCDNEnable()});r.info(A.L_LIVING_ROOM_SPREAD_CDN_INFO_T,{roomId:s,CDNUris:o},{logSource:i.RTC});const n=(yield Promise.all([jr(t,s,o),Hr(t,s,o)])).every((e=>e.code===L.SUCCESS));return n?r.info(A.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:D.SUCCESSED,CDNUris:o},{logSource:i.RTC}):r.error(A.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:D.FAILED,code:L.SIGNAL_ERROR,msg:"signal error"},{logSource:i.RTC}),n?{code:L.SUCCESS}:{code:L.SIGNAL_ERROR}}))}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(gr||(gr={})),function(e){e.BEGIN="begin",e.END="end"}(fr||(fr={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(vr||(vr={})),function(e){e[e.ROOM=1]="ROOM",e[e.PERSON=2]="PERSON"}(Or||(Or={}));class qr extends wr{constructor(e,t){super(),this.headers=e,this.reqBody=t}execute(e,t){var r,i;return v(this,void 0,void 0,(function*(){const t=yield e.service.exchange(this.headers,this.reqBody);if(e.roomMode!==Ir.LIVE)return t;const s=null===(i=null===(r=t.data)||void 0===r?void 0:r.urls)||void 0===i?void 0:i.pull_url;if(t.code!==L.SUCCESS||!s)return t;const o=JSON.parse(s);return e.setCDNUris(o),(null==o?void 0:o.broadcast)===vr.SPREAD&&(e.setCDNEnabel(!0),Jr(e)),t}))}}class Wr extends wr{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(e,t){var s,n;return v(this,void 0,void 0,(function*(){const{tracks:a,forceReq:c}=this,{roomId:_}=e;if(!o("tracks",a,(()=>d(a)&&a.every((e=>e instanceof mt||e.track instanceof mt))),!0))return O.warn(`update sublist failed, tracks is invalid -> roomId: ${_}`),{code:L.PARAMS_ERROR};O.info(`update subscribe list -> roomId: ${_}, forceReq: ${c}, tracks: ${a.map(Gt)}`);let u=a.map((e=>e instanceof mt?{track:e}:Object.assign({},e)));const l={};u=u.filter((t=>{const r=t.track.getTrackId();return e.getRemoteTrack(r)?!l[r]&&(l[r]=!0,!0):(O.warn(`track cannot found in room -> trackId: ${r}`),!1)})).map((e=>Object.assign({},e)));const m=e.getSubscribedList().map((e=>Object.assign({},e)));if(!c){let e=!1;if(u.forEach((t=>{const r=m.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);m.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),m.length&&(e=!0),!e)return{code:L.SUCCESS}}const{pc:p,pushOtherRooms:S,headers:T}=this.subhook(a);p.updateSubRemoteTracks(u.map((e=>e.track)));const C=Qt.getMemo();r.info(A.L_QS_CREATE_OFFER_O,{identify:C.qualityStatusId},{logSource:i.RTC});const I={dur:0,cod:0,rid:e.roomId,csnid:null===(s=C.clientData)||void 0===s?void 0:s.clientSessionId,snid:e.getSessionId(),rsid:"",msa:"",msas:[],time:0,resid:"",mtp:0,smct:1,cr:"unknown",net:"unknown",uid:"",stp:0};C.qualitySubscribeReportData=I,C.subscribeData={start:Date.now()};const E={dur:0,cod:0,rid:e.roomId,csnid:null===(n=C.clientData)||void 0===n?void 0:n.clientSessionId,snid:e.getSessionId(),rsid:"",msa:"",msas:[],time:0,resid:"",mtp:0,smct:1,uid:"",stp:0};C.qualityUnsubscribeReportData=E,C.unsubscribeData={start:Date.now()};const g=yield Kr(u,!1,p,e);S&&(g.pushOtherRooms=S),r.info(A.L_QS_SUBSCRIBE_EXCHANGE_O,{identify:C.qualityStatusId},{logSource:i.RTC});const f=yield new qr(T,g).execute(e,t),v=u.map((e=>e.track.getTrackId()));if(f.code!==L.SUCCESS){let e=[],t=Date.now();return C.mediaService.forEach((t=>{e.push({rsid:t.reqId,rsdur:t.end-t.start,msa:t.url,rscod:t.rscod})})),C.subscribeCommand&&(C.subscribeCommand=!1,u.forEach((r=>{var s,o;const n=JSON.stringify(Object.assign(C.qualitySubscribeReportData,{dur:t-((null===(s=C.subscribeData)||void 0===s?void 0:s.start)||0),cod:f.code,msas:e,time:t,resid:r.track.getTrackId(),mtp:Lt(r.track.getTrackId()).mediaType,smct:r.track instanceof at&&(null===(o=r.track)||void 0===o?void 0:o.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,n,i.RTC)}))),C.unsubscribeCommand&&(C.unsubscribeCommand=!1,u.forEach((r=>{var s,o;const n=JSON.stringify(Object.assign(C.qualityUnsubscribeReportData,{dur:t-((null===(s=C.unsubscribeData)||void 0===s?void 0:s.start)||0),cod:f.code,time:t,msas:e,resid:r.track.getTrackId(),mtp:Lt(r.track.getTrackId()).mediaType,smct:r.track instanceof at&&(null===(o=r.track)||void 0===o?void 0:o.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,n,i.RTC)}))),{code:f.code}}const{sdp:D,resultCode:N,message:b,subscribedList:k}=f.data;if(N!==L.SUCCESS){let e=[],t=Date.now();return C.mediaService.forEach((t=>{e.push({rsid:t.reqId,rsdur:t.end-t.start,msa:t.url,rscod:t.rscod})})),C.subscribeCommand&&(C.subscribeCommand=!1,u.forEach((r=>{var s,o;const n=JSON.stringify(Object.assign(C.qualitySubscribeReportData,{dur:t-((null===(s=C.subscribeData)||void 0===s?void 0:s.start)||0),cod:N,msas:e,time:t,resid:r.track.getTrackId(),mtp:Lt(r.track.getTrackId()).mediaType,smct:r.track instanceof at&&(null===(o=r.track)||void 0===o?void 0:o.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,n,i.RTC)}))),C.unsubscribeCommand&&(C.unsubscribeCommand=!1,u.forEach((r=>{var s,o;const n=JSON.stringify(Object.assign(C.qualityUnsubscribeReportData,{dur:t-((null===(s=C.unsubscribeData)||void 0===s?void 0:s.start)||0),cod:N,msas:e,time:t,resid:r.track.getTrackId(),mtp:Lt(r.track.getTrackId()).mediaType,smct:r.track instanceof at&&(null===(o=r.track)||void 0===o?void 0:o.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,n,i.RTC)}))),O.error(`change subscribe list failed: ${N}`),{code:N}}r.info(A.L_QS_GET_ANSWER_O,{identify:C.qualityStatusId},{logSource:i.RTC}),O.debug(`subscribe success: ${v.join(",")}`);const y=yield p.setRemoteAnswer(D.sdp);if(y!==L.SUCCESS){let e=[],t=Date.now();return C.mediaService.forEach((t=>{e.push({rsid:t.reqId,rsdur:t.end-t.start,msa:t.url,rscod:t.rscod})})),C.subscribeCommand&&(C.subscribeCommand=!1,u.forEach((r=>{var s,o;const n=JSON.stringify(Object.assign(C.qualitySubscribeReportData,{dur:t-((null===(s=C.subscribeData)||void 0===s?void 0:s.start)||0),cod:y,msas:e,time:t,resid:r.track.getTrackId(),mtp:Lt(r.track.getTrackId()).mediaType,smct:r.track instanceof at&&(null===(o=r.track)||void 0===o?void 0:o.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,n,i.RTC)}))),C.unsubscribeCommand&&(C.unsubscribeCommand=!1,u.forEach((r=>{var s,o;const n=JSON.stringify(Object.assign(C.qualityUnsubscribeReportData,{dur:t-((null===(s=C.unsubscribeData)||void 0===s?void 0:s.start)||0),cod:y,msas:e,time:t,resid:r.track.getTrackId(),mtp:Lt(r.track.getTrackId()).mediaType,smct:r.track instanceof at&&(null===(o=r.track)||void 0===o?void 0:o.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,n,i.RTC)}))),{code:y}}let U=[],P=Date.now();C.mediaService.forEach((e=>{U.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),C.subscribeCommand&&(C.subscribeCommand=!1,u.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(C.qualitySubscribeReportData,{dur:P-((null===(t=C.subscribeData)||void 0===t?void 0:t.start)||0),cod:y,msas:U,time:P,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,s,i.RTC)}))),C.unsubscribeCommand&&(C.unsubscribeCommand=!1,u.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(C.qualityUnsubscribeReportData,{dur:P-((null===(t=C.unsubscribeData)||void 0===t?void 0:t.start)||0),cod:y,msas:U,time:P,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,s,i.RTC)}))),C.iceStatusData?C.iceStatusData.subscribe={time:Date.now()}:C.iceStatusData={};const M=null==k?void 0:k.map((e=>`${e.msid}_${e.mediaType}`)),x=u.filter((e=>null==M?void 0:M.includes(e.track.getTrackId()))),w=u.filter((e=>!(null==M?void 0:M.includes(e.track.getTrackId())))),B=e.getRemoteTracks();for(const e in B){const t=x.some((t=>t.track.getTrackId()===e));B[e].__innerSetSubscribed(t);const r=x.some((t=>t.track.getTrackId()===e&&t.subTiny));B[e].isVideoTrack()&&B[e].__innerSetIsTinyTrack(r)}return e.resetSubscribedList(x),r.info(A.L_QS_GET_RESOURCES_O,{identify:C.qualityStatusId},{logSource:i.RTC}),w.length?{code:L.SUCCESS,failedList:w}:{code:L.SUCCESS}}))}}class Yr extends wr{constructor(e,t){super(),this.tracks=e,this.subhook=t}execute(e,t){return v(this,void 0,void 0,(function*(){const{tracks:s}=this,{roomId:n}=e;if(r.info(A.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:s.map(Gt)},{logSource:i.RTC}),!o("tracks",s,(()=>d(s)&&s.length>0&&s.every((e=>e instanceof mt))),!0))return O.warn(`unsubscribe failed, tracks is invalid -> roomId: ${n}`),r.warn(A.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};O.info(`unsubscribe -> roomId: ${n}, tracks: ${s.map(Gt)}`);const a=e.getSubscribedList().map((e=>Object.assign({},e))).filter((e=>!s.includes(e.track)));e.polarisReport.sendR2(gr.SUBSCRIBE,fr.END,s.map((e=>e.getTrackId()))),r.info(A.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:s.map(Gt),roomId:n},{logSource:i.RTC});return Qt.getMemo().unsubscribeCommand=!0,new Wr(a,this.subhook,!1).execute(e,t)}))}}class Qr extends wr{constructor(e,t){super(),this.msgContent=e,this.subhook=t}get priority(){return Tr.NORMAL}execute(e,t){return v(this,void 0,void 0,(function*(){const r=[],i=[],s=[],o=[],n={joined:r,left:i,upgrade:s,downgrade:o},{users:a}=this.msgContent;if(0===a.length)return n;for(let t=0;t<a.length;t++){const r=a[t];if(r.extra&&r.extra.roomId!==e.roomId)return n;if(1==+r.state&&!e.getRemoteUserIds().includes(r.userId))return n}a.forEach((t=>{const{userId:n}=t;if(0==+t.state){O.info(`user joined -> ${n}`);const i=e.getResourcesByUserId(n);i||(t.switchRoleType?s.push(n):r.push(n)),e.setResourcesByUserId(n,i||[])}else O.info(`user left -> ${n}`),t.switchRoleType?o.push(n):i.push(n)}));const c=[...i,...o];if(c.length){const r=[],i=[];c.forEach((t=>{r.push(...e.getRemoteTracksByUserId(t)),i.push(t)})),r.length&&(yield new Yr(r,this.subhook).execute(e,t),r.forEach((t=>e.removeRemoteTrack(t.getTrackId())))),i.length&&i.forEach((t=>e.removeResourcesByUserId(t)))}return n}))}}class zr extends wr{constructor(e,t,r){super(),this.subhook=e,this.tracks=t,this.onTrackUnpublish=r}execute(e,t){return v(this,void 0,void 0,(function*(){const{tracks:r}=this;yield new Yr(r,this.subhook).execute(e,t),r.forEach((t=>{t.__innerDestroy(),e.removeRemoteTrack(t.getTrackId())})),this.onTrackUnpublish(r)}))}}class Zr extends wr{constructor(e,t,r,i,s){super(),this.msgContent=e,this.messageType=t,this.senderId=r,this.subhook=i,this.callback=s}get priority(){return Tr.NORMAL}execute(e,t){var r,i;return v(this,void 0,void 0,(function*(){const{uris:s}=this.msgContent,o=[],n=[],a=[];let c;const d=this.senderId,{messageType:_}=this,u=e.getResourcesByUserId(d)||[];switch(e.setResourcesByUserId(d,u),_){case jt.MODIFY:a.push(...s);break;case jt.PUBLISH:o.push(...s);break;case jt.UNPUBLISH:n.push(...s);break;case jt.TOTAL_CONTENT_RESOURCE:c=Nt(u,s),o.push(...c.publishedList),n.push(...c.unpublishedList),a.push(...c.modifiedList)}if(o.length>0){const r=u.map(Ot),i=[],s=[];if(o.forEach((t=>{const o=Ot(t),n=r.indexOf(o),{userId:a,tag:c,mediaType:d}=Lt(o);n>-1?u[n]=t:u.push(t);let _=e.getRemoteTrack(o);_?_.isSubscribed()&&i.push(_):(_=d===He.AUDIO_ONLY?new pt(c,a):new St(c,a),e.addRemoteTrack(_),s.push(_)),_.__innerSetRemoteMuted(0===t.state)})),i.length){const r=i.map((e=>e.getTrackId()));O.debug(`resub tracks -> ${JSON.stringify(r)}`);const{code:s}=yield new Wr(i,this.subhook).execute(e,t);s!==L.SUCCESS&&O.error(`resub tracks failed -> code: ${s}, ids: ${JSON.stringify(r)}`)}this.callback.onTrackPublish(s)}if(n.length>0){const r=n.map(Ot);for(let e=u.length-1;e>=0;e-=1){const t=u[e];r.includes(Ot(t))&&u.splice(e,1)}const i=n.map((t=>{const r=Ot(t);return e.getRemoteTrack(r)}));yield new zr(this.subhook,i,this.callback.onTrackUnublish).execute(e,t)}if(a.length>0){const t=u.map(Ot);for(let r=0;r<a.length;r+=1){const i=a[r],s=Ot(i),o=t.indexOf(s);u[o].state=i.state;const n=e.getRemoteTrack(s);n.__innerSetRemoteMuted(0===i.state),n.isAudioTrack()?this.callback.onAudioMute(n):this.callback.onVideoMute(n)}}if(e.roomMode!==Ir.LIVE)return;const l=this.msgContent;if(!l.cdn_uris)return;const h=(null===(r=e.getCDNUris())||void 0===r?void 0:r.enableInnerCDN)!==l.cdn_uris[0].enableInnerCDN;e.setCDNUris(l.cdn_uris[0]),h&&this.callback.onCDNEnableChange(!!(null===(i=e.getCDNUris())||void 0===i?void 0:i.enableInnerCDN))}))}}class Xr extends wr{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(e,t){return v(this,void 0,void 0,(function*(){const{tracks:s,forceReq:n}=this,{roomId:a}=e;if(r.info(A.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:s.map(Gt),forceReq:n},{logSource:i.RTC}),!o("tracks",s,(()=>d(s)&&s.length>0&&s.every((e=>e instanceof mt||e.track instanceof mt))),!0))return O.warn(`subscribe failed, tracks is invalid -> roomId: ${a}`),r.error(A.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};O.info(`subscribe -> roomId: ${a}, tracks: ${s.map(Gt)}`);const c=e.getSubscribedList().map((e=>Object.assign({},e))),_=s.map((e=>e instanceof mt?{track:e}:e));let u=!1;const l=[];if(_.forEach((e=>{const t=e.track.getTrackId();l.push(t);const r=c.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:c.push(e),u=!0)})),!u&&!n)return r.warn(A.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:D.FAILED,code:"",msg:"repeat subscribe"},{logSource:i.RTC}),{code:L.SUCCESS};e.polarisReport.sendR2(gr.SUBSCRIBE,fr.BEGIN,l),r.info(A.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:s.map(Gt),roomId:a},{logSource:i.RTC});return Qt.getMemo().subscribeCommand=!0,new Wr(c,this.subhook,!0).execute(e,t)}))}}class ei extends wr{constructor(e,t){super(),this.tracks=e,this.pubhook=t}get kind(){return pr.Publish}_removePubFailedTracks(e,t){e.forEach((e=>{const r=e instanceof ot?e:e.track;O.debug(`remove pub failed track from peerconnection -> trackId: ${r.getTrackId()}`),t.removeLocalTrackById(r.getTrackId())}))}__publish(e,t,s,o,n){var a;return v(this,void 0,void 0,(function*(){const{pcName:c,pc:d,headers:_}=t,{roomId:u}=e,l=[];s.forEach((e=>{const{track:t}=e instanceof ot?{track:e}:e;l.push(t)})),s.sort(((e,t)=>{const{track:r}=e instanceof ot?{track:e}:e,{max:i}=r.getBitrate(),{track:s}=t instanceof ot?{track:t}:t,{max:o}=s.getBitrate();return i-o}));if(d.getLocalTracks().length+((e,t)=>{let r=0;return e.forEach((e=>{const i=e instanceof ot?e.getTrackId():e.track.getTrackId();t.getLocalTrack(i)||(e instanceof ot?r++:e.pubTiny&&e.track.isVideoTrack()&&(r+=2))})),r})(s,d)>10)return O.error(`publish failed, tracks limit exceeded -> roomId: ${u}`),{code:L.PUBLISH_TRACK_LIMIT_EXCEEDED,tracks:l};O.debug(`publish tracks -> roomId: ${u}, tracks: ${s.map(Gt)}`);for(let e=0;e<s.length;e++){const t=s[e],{track:r,pubTiny:i}=t instanceof ot?{pubTiny:!1,track:t}:t;if(r.isVideoTrack()&&i){let e;try{e=r.__innerGetMediaStreamTrack().clone();const t=i.frameRate||Ke.FPS_15,s=i.resolution||je.W176_H144,{width:o,height:n}=kt(s),a=Pt(t);yield e.applyConstraints({width:o,height:n,frameRate:a})}catch(t){null==e||e.stop(),O.warn(`pubTiny failed -> id: ${r.getTrackId()}, msg: ${t.message}`);break}d.addLocalTrack(new at(r.getTag(),r.getUserId(),e,!0))}d.addLocalTrack(r)}d.clearReTryExchangeTimer();const m=e.useMutilPeerC?[]:e.getSubscribedList(),p=`${Date.now()}`,S=Qt.getMemo();S.qualityStatus=p,r.info(A.L_QS_CREATE_OFFER_O,{identify:p},{logSource:i.RTC});const T={dur:0,cod:0,rid:e.roomId,csnid:null===(a=S.clientData)||void 0===a?void 0:a.clientSessionId,snid:e.getSessionId(),rsid:"",msa:"",msas:[],sigs:[],time:0,resid:"",mtp:0,smct:1,cr:"unknown",net:"unknown",uid:e.crtUserId,stp:0};S.qualityPublishReportData=T,S.publish={start:Date.now()};const C=yield Kr(m,!1,d,e);o&&(C.pushOtherRooms=o),r.info(A.L_QS_PUBLISH_EXCHANGE_O,{identify:p},{logSource:i.RTC});const I=yield new qr(_,C).execute(e,n);if(I.code!==L.SUCCESS){const e=Date.now();let t=[];return S.mediaService.forEach((e=>{t.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),l.forEach((r=>{var s;const o=JSON.stringify(Object.assign(S.qualityPublishReportData,{dur:e-((null===(s=S.publish)||void 0===s?void 0:s.start)||0),cod:I.code,msas:t,time:e,resid:r.getTrackId(),mtp:Lt(r.getTrackId()).mediaType,smct:r instanceof at&&r.__isTiny()?2:1}));h(R.STATISTICS,A.L_QS_PUBLISH_S,o,i.RTC)})),O.error(`publish failed -> roomId: ${u}, code: ${I.code}`),this._removePubFailedTracks(s,d),{code:I.code,tracks:l}}r.info(A.L_QS_GET_ANSWER_O,{status:D.SUCCESSED,identify:p},{logSource:i.RTC});const{sdp:E,resultCode:g,message:f}=I.data;if(g!==L.SUCCESS){const e=Date.now();let t=[];return S.mediaService.forEach((e=>{t.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),l.forEach((r=>{var s;const o=JSON.stringify(Object.assign(S.qualityPublishReportData,{dur:e-((null===(s=S.publish)||void 0===s?void 0:s.start)||0),cod:g,msas:t,time:e,resid:r.getTrackId(),mtp:Lt(r.getTrackId()).mediaType,smct:r instanceof at&&r.__isTiny()?2:1}));h(R.STATISTICS,A.L_QS_PUBLISH_S,o,i.RTC)})),O.error(`publish failed -> roomId: ${u}, code: ${g}, msg: ${f}`),this._removePubFailedTracks(s,d),{code:g,tracks:l}}const v=yield d.setRemoteAnswer(E.sdp);if(v!==L.SUCCESS){const e=Date.now();let t=[];return S.mediaService.forEach((e=>{t.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),l.forEach((r=>{var s;const o=JSON.stringify(Object.assign(S.qualityPublishReportData,{dur:e-((null===(s=S.publish)||void 0===s?void 0:s.start)||0),cod:v,msas:t,time:e,resid:r.getTrackId(),mtp:Lt(r.getTrackId()).mediaType,smct:r instanceof at&&r.__isTiny()?2:1}));h(R.STATISTICS,A.L_QS_PUBLISH_S,o,i.RTC)})),{code:v,tracks:l}}return Object.assign(Object.assign({},I),{tracks:l})}))}_mergePublishRes(e,t){return v(this,void 0,void 0,(function*(){const r=t.crtUserId,{roomId:s}=t;let o="";const n=[],c=t.getResourcesByUserId(r),d=[...c];let _=[];e.forEach((e=>{if(e.code!==L.SUCCESS){const{tracks:t}=e;return void n.push({code:e.code,tracks:t})}const{publishList:r,urls:i,mcuPublishList:s}=e.data;o=null==i?void 0:i.liveUrl;r.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:t.getTrackState(Ot(e))},e))).forEach((e=>{const{isInclude:t,index:r}=((e,t)=>{let r=!1,i=0;for(let s=0;s<t.length;s++){const o=t[s];if(`${e.msid}_${e.mediaType}`==`${o.msid}_${o.mediaType}`){r=!0,i=s;break}}return{isInclude:r,index:i}})(e,d);t?d.splice(r,1,e):d.push(e)}));const a=(null==s?void 0:s.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))))||[];_=a}));const{publishedList:u}=Nt(c,d),l=Qt.getMemo();l.publishSignalTotal={start:Date.now()};const m=yield t.context.setRTCTotalRes(s,Tt(jt.PUBLISH,u),Ct(d),jt.TOTAL_CONTENT_RESOURCE,Ct(_));if(m!==a.SUCCESS){const e=Date.now();let t=[];l.mediaService.forEach((e=>{t.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const r=[];return r.push({dur:Date.now()-(l.publishSignalTotal.start||0),cod:m}),d.forEach((s=>{var o;const n=JSON.stringify(Object.assign(l.qualityPublishReportData,{dur:e-((null===(o=l.publish)||void 0===o?void 0:o.start)||0),cod:m,msas:t,sigs:r,time:e,resid:Ot(s),mtp:s.mediaType,smct:s.simulcast}));h(R.STATISTICS,A.L_QS_PUBLISH_S,n,i.RTC)})),O.error(`send publish streams notification failed: ${m}`),{code:L.SIGNAL_ERROR}}const p=Date.now();let S=[];l.mediaService.forEach((e=>{S.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const T=[];T.push({dur:Date.now()-(l.publishSignalTotal.start||0),cod:m}),d.forEach((e=>{var t;const r=JSON.stringify(Object.assign(l.qualityPublishReportData,{dur:p-((null===(t=l.publish)||void 0===t?void 0:t.start)||0),cod:m,msas:S,sigs:T,time:p,resid:Ot(e),mtp:e.mediaType,smct:e.simulcast}));h(R.STATISTICS,A.L_QS_PUBLISH_S,r,i.RTC)})),l.iceStatusData?l.iceStatusData.publish={time:Date.now()}:l.iceStatusData={},t.setResourcesByUserId(r,d);const C=u.map((e=>Ot(e)));t.polarisReport&&t.polarisReport.sendR2(gr.PUBLISH,fr.BEGIN,C),u.forEach((e=>{const r=t.useMutilPeerC?`${s}_${(e=>{const t=e.split("_");return{tag:t.pop(),userId:t.join("_")}})(e.msid).tag}`:`${s}_pub`,{pc:i}=t.peerMgr.getPCItemByPCName(r);i.getLocalTrack(`${e.msid}_${e.mediaType}`).__innerSetPublished(!0)})),O.debug(`publish success: ${C.join(",")}`);const I={code:L.SUCCESS};return o&&(I.liveUrl=o),n.length&&(I.failedTracks=n,I.code=L.SOME_TRACKS_PUBLISH_FAILED),I}))}execute(e,t){return v(this,void 0,void 0,(function*(){let{tracks:s}=this;const{roomId:n}=e;if(r.info(A.L_ABSTRACT_ROOM_PUBLISH_T,{trackIds:s.map(Gt)},{logSource:i.RTC}),!o("tracks",s,(()=>d(s)&&s.length>0&&s.every((e=>e instanceof ot||e.track instanceof ot))),!0))return O.warn(`publish failed, tracks is invalid -> roomId: ${n}`),r.error(A.L_ABSTRACT_ROOM_PUBLISH_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(s=s.filter((e=>{const{track:t}=e instanceof ot?{track:e}:e,i=t.isDestroyed();return i&&r.warn(A.L_ABSTRACT_ROOM_PUBLISH_R,{status:D.FAILED,msg:`track -> ${t.getTrackId()} has beem destroyed`}),!i})),!s.length)return{code:L.PUBLISH_TRACKS_IS_INVALID};const a=[],{plist:c,pushOtherRooms:_}=this.pubhook(s);for(let r=0;r<c.length;r++){const i=c[r];a.push(this.__publish(e,i,i.tracks,_,t))}const u=yield Promise.all(a),l=yield this._mergePublishRes(u,e);return r.info(A.L_ABSTRACT_ROOM_PUBLISH_R,{status:D.SUCCESSED,roomId:n,trackIds:s.map(Gt)},{logSource:i.RTC}),l}))}}class ti extends wr{constructor(e,t){super(),this.tracks=e,this.unpubhook=t}get kind(){return pr.UnPublish}__unpublish(e,t,r,s){var o;return v(this,void 0,void 0,(function*(){const{pcName:n,pc:a}=r,c=s.map((e=>e.getTrackId()));if(0===c.map(e.getPublishedResourceByTrackId.bind(e)).filter((e=>!!e)).length)return{code:L.SUCCESS,tracks:s};c.forEach((e=>a.removeLocalTrackById(e))),e.polarisReport.sendR2(gr.PUBLISH,fr.END,c),a.clearReTryExchangeTimer();const d=e.useMutilPeerC?[]:e.getSubscribedList(),_=Qt.getMemo(),u={dur:0,cod:0,rid:e.roomId,csnid:null===(o=_.clientData)||void 0===o?void 0:o.clientSessionId,snid:e.getSessionId(),rsid:"",msa:"",msas:[],sigs:[],time:0,resid:"",mtp:0,smct:1,uid:e.crtUserId,stp:0};_.qualityUnpublishReportData=u,_.unpublish={start:Date.now()};const l=yield Kr(d,!1,a,e),{pushOtherRooms:m,headers:p}=this.unpubhook(s,n);m&&(l.pushOtherRooms=m);const S=yield new qr(p,l).execute(e,t);if(S.code!==L.SUCCESS){const e=Date.now();return s.forEach((t=>{var r;const s=t.getTrackId(),o=JSON.stringify(Object.assign(_.qualityUnpublishReportData,{dur:e-((null===(r=_.unpublish)||void 0===r?void 0:r.start)||0),cod:S.code,time:e,resid:s,mtp:Lt(s).mediaType,smct:t instanceof at&&t.__isTiny()?2:1}));h(R.STATISTICS,A.L_QS_UNPUBLISH_S,o,i.RTC)})),O.error(`exchange failed -> code: ${S.code}`),{code:S.code,tracks:s}}return Object.assign(Object.assign({},S),{tracks:s})}))}_mergeUnpublishRes(e,t){return v(this,void 0,void 0,(function*(){const r=e.context.getCurrentId(),{roomId:s}=e,o=Qt.getMemo(),n=[],c=[],d=[],_=[];let u=[];for(let r=0;r<t.length;r++){const s=t[r];if(s.code!==L.SUCCESS){const{tracks:e}=s;c.push({code:s.code,tracks:e});continue}const{resultCode:a,message:l,mcuPublishList:m}=s.data;if(a!==L.SUCCESS){const e=Date.now();let t=[];o.mediaService.forEach((e=>{t.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),d.forEach((r=>{var s;if(r){const n=JSON.stringify(Object.assign(o.qualityUnpublishReportData,{dur:e-((null===(s=o.publish)||void 0===s?void 0:s.start)||0),cod:a,msas:t,time:e,resid:Ot(r),mtp:r.mediaType,smct:r.simulcast}));h(R.STATISTICS,A.L_QS_UNPUBLISH_S,n,i.RTC)}})),O.error(`unpublish streams failed -> code: ${a}, msg: ${l}`)}const p=s.tracks.map((e=>e.getTrackId()));_.push(...p);const S=p.map(e.getPublishedResourceByTrackId.bind(e)).filter((e=>!!e));d.push(...S),n.push(s);const T=m?m.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[];u=T}const l=e.getResourcesByUserId(r),m=l.filter((e=>!d.includes(e)));o.unPublishSignalTotal={start:Date.now()};const p=yield e.context.setRTCTotalRes(s,Tt(jt.UNPUBLISH,d),Ct(m),jt.TOTAL_CONTENT_RESOURCE,Ct(u));if(p!==a.SUCCESS){const e=Date.now();let t=[];o.mediaService.forEach((e=>{t.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const r=[];return r.push({dur:Date.now()-(o.unPublishSignalTotal.start||0),cod:p}),l.forEach((s=>{var n;const a=JSON.stringify(Object.assign(o.qualityUnpublishReportData,{dur:e-((null===(n=o.publish)||void 0===n?void 0:n.start)||0),cod:p,msas:t,sigs:r,time:e,resid:Ot(s),mtp:s.mediaType,smct:s.simulcast}));h(R.STATISTICS,A.L_QS_UNPUBLISH_S,a,i.RTC)})),O.error("send unpublish notification failed:",p),{code:L.SIGNAL_ERROR}}O.debug(`unpublish success -> tracks: ${_.join(",")}`);const S=Date.now();let T=[];o.mediaService.forEach((e=>{T.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const C=[];C.push({dur:Date.now()-(o.unPublishSignalTotal.start||0),cod:p}),l.forEach((e=>{var t;const r=JSON.stringify(Object.assign(o.qualityUnpublishReportData,{dur:S-((null===(t=o.publish)||void 0===t?void 0:t.start)||0),cod:L.SUCCESS,msas:T,sigs:C,time:S,resid:Ot(e),mtp:e.mediaType,smct:e.simulcast}));h(R.STATISTICS,A.L_QS_UNPUBLISH_S,r,i.RTC)})),n.forEach((t=>v(this,void 0,void 0,(function*(){const{sdp:r}=t.data,{tracks:i}=t,s=e.peerMgr.getPCByTrackId(i[0].getTrackId());yield s.setRemoteAnswer(r.sdp)})))),e.setResourcesByUserId(r,m);const I={code:L.SUCCESS};return c.length&&(I.failedTracks=c,I.code=L.SOME_TRACKS_PUBLISH_FAILED),I}))}execute(e,t){return v(this,void 0,void 0,(function*(){const{crtUserId:s,roomId:n}=e,{tracks:a}=this;r.info(A.L_ABSTRACT_ROOM_UNPUBLISH_T,{trackIds:a.map(Gt)},{logSource:i.RTC});if(!o("tracks",a,(()=>a.every((e=>e.getUserId()===s&&e instanceof ot))),!0))return O.warn(`unpublish failed, tracks is invalid -> roomId: ${n}, tracks: ${a.map(Gt)}`),r.error(A.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};const c=e.peerMgr.createPeerCList(a),d=[];for(let r=0;r<c.length;r++){const{tracks:i}=c[r];d.push(this.__unpublish(e,t,c[r],i))}const _=yield Promise.all(d);let u=_.length;if(_.forEach((e=>{e.code!==L.SUCCESS||e.data||(u-=1)})),0===u)return{code:L.SUCCESS};const l=yield this._mergeUnpublishRes(e,_);return r.info(A.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:D.SUCCESSED,roomId:n,trackIds:a.map(Gt)},{logSource:i.RTC}),l}))}}class ri extends wr{constructor(e,t){super(),this.localTrack=e,this._recvSignalResultFn=t}execute(e,t){return v(this,void 0,void 0,(function*(){const{localTrack:t}=this,r=t.getTrackId(),{crtUserId:i,roomId:s}=e,o=[{resourceId:r,enabled:!t.isLocalMuted()}],n=e.getResourcesByUserId(i),c=[];for(let e=0;e<n.length;e+=1){const t=n[e],r=Ot(t),i=o.findIndex((e=>e.resourceId===r));if(i>=0){const{enabled:e}=o[i];t.state=e?1:0,c.push(t);break}}const d=yield e.context.setRTCTotalRes(s,Tt(jt.MODIFY,c),Ct(n),jt.TOTAL_CONTENT_RESOURCE);this._recvSignalResultFn(d),d!==a.SUCCESS&&O.error(`notice \`track.enabled\` change failed -> code: ${d}`)}))}}class ii extends wr{constructor(e,t,r){super(),this.pcName=e,this.isPub=t,this.retryHook=r}get priority(){return Tr.HIGH}execute(e,t){return v(this,void 0,void 0,(function*(){const{pcName:r,isPub:i}=this,{useMutilPeerC:s}=e,{pc:o}=e.peerMgr.getPCItemByPCName(r),n=i&&s?[]:e.getSubscribedList(),a=yield Kr(n,!0,o,e),{pushOtherRooms:c,headers:d}=this.retryHook(r);c&&(a.pushOtherRooms=c);const _=yield new qr(d,a).execute(e,t);if(_.code!==L.SUCCESS)return void O.error(`reTryExchange failed: ${_.code}, pcName: ${r}`);const{sdp:u,resultCode:l}=_.data;l===L.SUCCESS?(o.clearReTryExchangeTimer(),yield o.setRemoteAnswer(u.sdp)):O.error(`reTryExchange failed: ${l}, pcName: ${r}`)}))}}class si extends wr{constructor(e,t,r){super(),this.subhook=e,this.callbacks=t,this.livingType=r}get priority(){return Tr.HIGH}execute(e,t){return v(this,void 0,void 0,(function*(){const{livingType:s}=this,{roomId:o,crtUserId:n,roomMode:c}=e;r.info(A.L_ABSTRACT_ROOM_RECONNECTED_T,{livingType:s},{logSource:i.RTC});if(e.peerMgr.getPCList().some((e=>"closed"===e.getRTCPeerConn().connectionState)))return O.warn("RTCPeerConnection closed. Please rejoin room to restore services."),r.error(A.L_ABSTRACT_ROOM_RECONNECTED_R,{status:D.FAILED,code:"",msg:"RTCPeerConnection closed"},{logSource:i.RTC}),void this.callbacks.onPeerClosed();const{code:d,data:_}=yield e.context.joinRTCRoom(o,c,s);if(d!==a.SUCCESS)return O.error(`RTC __onReconnected getRTCRoomInfo failed: ${d}`),void r.error(A.L_ABSTRACT_ROOM_RECONNECTED_R,{status:D.FAILED,code:d,msg:""},{logSource:i.RTC});O.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(_)}`);const u=[],l={},h={},R={},m=$t(_,o),p=Object.keys(m),S=e.getAllUserIds();for(let t=p.length-1;t>=0;t-=1){const r=p[t],i=S.indexOf(r);if(-1===i){u.push(r),l[r]=Dt(m[r]);continue}const s=e.getResourcesByUserId(r),o=m[r],{publishedList:n,modifiedList:a,unpublishedList:c}=Nt(s,o,!0);l[r]=Dt(n),h[r]=Dt(c),R[r]=Dt(a),S.splice(i,1)}S.length&&S.forEach((t=>{e.removeResourcesByUserId(t)})),e.assignRoomData(m),S.length&&this.callbacks.onUserLeave(S),u.length&&this.callbacks.onUserJoin(u);for(const r in h){if(r===n)continue;const i=h[r];if(i.length){const r=i.map((t=>e.getRemoteTrack(Ot(t))));yield new zr(this.subhook,r,this.callbacks.onTrackUnpublish).execute(e,t)}}return Object.keys(l).forEach((t=>{const r=l[t];if(0===r.length)return;const i=r.map((t=>{const r=Ot(t),{userId:i,tag:s,mediaType:o}=Lt(r),n=o===He.AUDIO_ONLY?new pt(s,i):new St(s,i);return e.addRemoteTrack(n),n.__innerSetRemoteMuted(0===t.state),n}));this.callbacks.onTrackPublish(i)})),Object.keys(R).forEach((t=>{R[t].forEach((t=>{const r=Ot(t),i=e.getRemoteTrack(r);i.__innerSetRemoteMuted(0===t.state),i.isAudioTrack()?this.callbacks.onAudioMuteChange(i):this.callbacks.onVideoMuteChange(i)}))})),e.roomMode===Ir.LIVE&&this.executeInLivingRoom(e,_),r.info(A.L_ABSTRACT_ROOM_RECONNECTED_R,{status:D.SUCCESSED,roomData:_},{logSource:i.RTC}),{data:_}}))}executeInLivingRoom(e,t){var s,o;if(r.error(A.L_LIVING_ROOM_RECONNECTED_T,{roomData:t},{logSource:i.RTC}),!t)return void r.info(A.L_LIVING_ROOM_RECONNECTED_R,{status:D.FAILED,code:"",msg:"room not fond"},{logSource:i.RTC});const{roomInfo:n}=t,a=null===(s=n.filter((e=>"cdn_uris"===e.key))[0])||void 0===s?void 0:s.value;if(!a)return void r.error(A.L_LIVING_ROOM_RECONNECTED_R,{status:D.FAILED,code:"",msg:"cdn_uris not found"},{logSource:i.RTC});const c=JSON.parse(a),d=(null===(o=e.getCDNUris())||void 0===o?void 0:o.enableInnerCDN)!==c.enableInnerCDN;e.setCDNUris(c),r.info(A.L_LIVING_ROOM_RECONNECTED_R,{status:D.SUCCESSED,roomData:t},{logSource:i.RTC}),d&&this.callbacks.onCDNEnableChange(c.enableInnerCDN)}}class oi extends Br{constructor(e,t,r,i=Sr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var r,i,s;return v(this,void 0,void 0,(function*(){const{tracks:o}=this,{roomId:n}=e;if(O.info(`unsubscribe -> roomId: ${n}, tracks: ${o.map(Gt)}`),this.state===Sr.NORMAL){const i=e.getSubscribedList().slice(),{code:s,failedList:n}=yield new Wr(o,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,i);return null===(r=this.callbacks)||void 0===r||r.onTaskCompleted({code:s,subscribe:c,unsubscribe:d,failedList:n}),{code:s,failedList:n}}if(this.state===Sr.TAIL){const{code:r}=yield new oi(this.tracks,this.subhook,this.callbacks,Sr.MIDDLE).execute(e,t);if(r===L.SUCCESS){const r=e.getCollectSubscribeList().slice(0),o=e.getSubscribedList().slice(),{code:n,failedList:a}=yield new Wr(r,this.subhook).execute(e,t);if(n!==L.SUCCESS)return null===(i=this.callbacks)||void 0===i||i.onTaskCompleted({code:n,subscribe:[],unsubscribe:[],failedList:a}),{code:n,failedList:a};const c=e.getSubscribedList().slice(0),{subscribe:d,unsubscribe:_}=this.pickoutSubscribed(c,o);return null===(s=this.callbacks)||void 0===s||s.onTaskCompleted({code:n,subscribe:d,unsubscribe:_,failedList:a}),{code:n,failedList:a}}return{code:r}}return Br.AsyncUpdateSubscribeTasks.splice(Br.AsyncUpdateSubscribeTasks.length,0,...this.tracks),new Promise((t=>{const r=this.formateTrack(o);e.resetCollectSubscribeList(r),t({code:L.SUCCESS})}))}))}}class ni extends Br{constructor(e,t,r,i=Sr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var s;return v(this,void 0,void 0,(function*(){const{tracks:n}=this,{roomId:a}=e;if(this.state===Sr.NORMAL){const r=e.getSubscribedList().slice(),{code:i,failedList:o}=yield new Xr(n,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,r);return null===(s=this.callbacks)||void 0===s||s.onTaskCompleted({code:i,subscribe:c,unsubscribe:d,failedList:o}),{code:i,failedList:o}}if(r.info(A.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:n.map(Gt)},{logSource:i.RTC}),!o("tracks",n,(()=>d(n)&&n.length>0&&n.every((e=>e instanceof mt||e.track instanceof mt))),!0))return O.warn(`subscribe failed, tracks is invalid -> roomId: ${a}`),r.error(A.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};O.info(`subscribe -> roomId: ${a}, tracks: ${n.map(Gt)}`);const c=this.getSubscribedList(e).map((e=>Object.assign({},e))),_=n.map((e=>e instanceof mt?{track:e}:e)),u=[];if(_.forEach((e=>{const t=e.track.getTrackId();u.push(t);const r=c.find((e=>e.track.getTrackId()===t));if(r){if(r.subTiny===e.subTiny)return;r.subTiny=e.subTiny}else c.push(e)})),e.polarisReport.sendR2(gr.SUBSCRIBE,fr.BEGIN,u),r.info(A.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:n.map(Gt),roomId:a},{logSource:i.RTC}),this.state===Sr.TAIL){const{code:r}=yield new ni(this.tracks,this.subhook,this.callbacks,Sr.MIDDLE).execute(e,t);if(r===L.SUCCESS){const r=e.getCollectSubscribeList().slice(0);return new oi(r,this.subhook,this.callbacks).execute(e,t)}return{code:r}}return Br.AsyncSubscribeTasks.splice(Br.AsyncSubscribeTasks.length,0,...this.tracks),new Promise((t=>{e.resetCollectSubscribeList(c),t({code:L.SUCCESS})}))}))}getSubscribedList(e){return this.state===Sr.MIDDLE?e.getCollectSubscribeList():e.getSubscribedList()}}class ai extends Br{constructor(e,t,r,i=Sr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var s;return v(this,void 0,void 0,(function*(){const{tracks:n}=this,{roomId:a}=e;if(this.state===Sr.NORMAL){const r=e.getSubscribedList().slice(),{code:i,failedList:o}=yield new Yr(n,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,r);return null===(s=this.callbacks)||void 0===s||s.onTaskCompleted({code:i,subscribe:c,unsubscribe:d,failedList:o}),{code:i,failedList:o}}if(r.info(A.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:n.map(Gt)},{logSource:i.RTC}),!o("tracks",n,(()=>d(n)&&n.length>0&&n.every((e=>e instanceof mt))),!0))return O.warn(`unsubscribe failed, tracks is invalid -> roomId: ${a}`),r.warn(A.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};O.info(`unsubscribe -> roomId: ${a}, tracks: ${n.map(Gt)}`);const c=this.getSubscribedList(e).map((e=>Object.assign({},e))).filter((e=>!n.includes(e.track)));if(e.polarisReport.sendR2(gr.SUBSCRIBE,fr.END,n.map((e=>e.getTrackId()))),r.info(A.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:n.map(Gt),roomId:a},{logSource:i.RTC}),this.state===Sr.TAIL){const{code:r}=yield new ai(this.tracks,this.subhook,this.callbacks,Sr.MIDDLE).execute(e,t);if(r===L.SUCCESS){const r=e.getCollectSubscribeList().slice(0).map((e=>e.track));return new oi(r,this.subhook,this.callbacks).execute(e,t)}return{code:r}}return Br.AsyncUnsubscribeTasks.splice(Br.AsyncUnsubscribeTasks.length,0,...this.tracks),new Promise((t=>{e.resetCollectSubscribeList(c),t({code:L.SUCCESS})}))}))}getSubscribedList(e){return this.state===Sr.MIDDLE?e.getCollectSubscribeList():e.getSubscribedList()}}!function(e){e[e.SERVER_KICK=1]="SERVER_KICK",e[e.OTHER_KICK=2]="OTHER_KICK"}(Lr||(Lr={}));const ci={[Lr.SERVER_KICK]:1,[Lr.OTHER_KICK]:5},di="evt-leave";class _i extends t{constructor(e,t,r,i,s,o,n,a,c,d=qt()){super(),this._context=e,this._runtime=t,this._roomId=r,this._service=s,this._initOptions=o,this._useMutilPeerC=c,this._clientSessionId=d,this._appListener=null,this._reportListener=null,this._onRecvPKMsg=null,this._polarisReport=new Pr(this._context,this._runtime,this._roomId,this),this._peerCManager=new xr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._invoker=new $r(this._context,this._service,this._peerCManager,r,this._context.getCurrentId(),i,this._polarisReport,n,a),this._store=this._invoker.store}__innerInit(e,t,r,i,s){return v(this,void 0,void 0,(function*(){const{code:o,data:n}=yield this._invoker.push(new Gr(this._roomId,e,t,r,i,s));return o!==L.SUCCESS?{code:o}:(this._initWithRoomData(n.offlineKickTime),{code:o,data:n})}))}_initWithRoomData(e){var t;this._pinger=new Jt(this._store.roomId,this._store.roomMode,this._context,this._initOptions.pingGap,1e3*e),this._pinger.onFailed=this._kickoff.bind(this),this._pinger.onPingResult=this._handlePingResult.bind(this),this._pinger.start(),null===(t=this._polarisReport)||void 0===t||t.sendR1()}_handlePingResult(e){this._callAppListener("onPing",e)}setBitrate(e,t,r){if(this._useMutilPeerC)return void O.error("`RCAbstractRoom.setBitrate` is disabled, use `RCLocalTrack.setBitrate` instead.");O.warn("`RCAbstractRoom.setBitrate` will be deprecated, use `RCLocalTrack.setBitrate` instead."),S("max",e,(e=>s(e)&&e>Math.max(t||1,200)),!0),S("min",t,(t=>s(t)&&t>=1&&(!s(e)||t<e)),!0),S("start",r,(r=>s(r)&&r>t&&r<=e));this._peerCManager.getPCList().forEach((i=>{i.setBitrate(e,t,r)}))}_onTrackReady(e){const t=e.streams[0].id,{track:s}=e.receiver,o=[t,"audio"===s.kind?He.AUDIO_ONLY:He.VIDEO_ONLY].join("_"),n=this._store.getRemoteTrack(o);if(!n)return void O.warn(`cannot found remote track ${s.id}`);n.__innerSetMediaStreamTrack(s);const a=Qt.getMemo();r.info(A.L_QS_TRACK_READY_O,{identify:a.qualityStatusId},{logSource:i.RTC}),this._callAppListener("onTrackReady",n)}_callAppListener(e,...t){var s;"onPing"!==e&&r.info(A.L_ABSTRACT_ROOM_CALL_APP_LISTENER_O,{status:D.SUCCESSED,eventType:e,attrs:t},{logSource:i.RTC}),"onPing"!==e&&O.info(`${e} callback ->`,...t);const o=null===(s=this._appListener)||void 0===s?void 0:s[e];if(o)try{o(...t)}catch(e){O.error(e)}}_onTrackUnpublish(e){this._callAppListener("onTrackUnpublish",e)}__parseInnerMessage(e){var t;const{targetId:s,conversationType:o}=e;if(s!==this._roomId)return r.warn(A.L_RTC_CLIENT_MESSAGE_O,{status:D.FAILED,message:`roomId is different, msg roomId-> ${s}, this._roomId-> ${this._roomId} `},{logSource:i.RTC}),!0;O.info(`recv inner msg -> message: ${JSON.stringify(e)} | roomid: ${this._roomId}`);const{content:n}=e,a=Qt.getMemo();switch(e.messageType){case jt.KICK:this._kickoff(!0,n);break;case jt.STATE:this._stateHandle(n);break;case jt.MODIFY:case jt.PUBLISH:case jt.UNPUBLISH:case jt.TOTAL_CONTENT_RESOURCE:if(!a.messageData){a.messageData={sentTime:e.sentTime,senderUserId:e.senderUserId};const r=Date.now(),o={dur:r-e.sentTime,puid:e.senderUserId,rid:s,csnid:null===(t=a.clientData)||void 0===t?void 0:t.clientSessionId,snid:this.getSessionId(),time:r,cr:"unknown",net:"unknown",uid:this.getCrtUserId()},n=JSON.stringify(o);h(R.STATISTICS,A.L_QS_RECV_PUB_MSG_S,n,i.RTC)}this._resourceHandle(n,e.messageType,e.senderUserId);break;case jt.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",e.messageType,e.content);break;case jt.USER_NOTIFY:O.warn(`TODO: ${jt.USER_NOTIFY}`);break;case jt.PK_INVITE:case jt.PK_CANCEL_INVITE:case jt.PK_INVITE_TIMEOUT:case jt.PK_INVITE_ANSWER:case jt.PK_END:this._onRecvPKMsg&&this._onRecvPKMsg(e);break;case jt.OTHER_ROOM_OFFLINE:break;default:this._callAppListener("onMessageReceive",e.messageType,n,e.senderUserId,e.messageUId)}return!0}_kickoff(e,t){return v(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;let r,s;if(O.warn(`onKickOff -> byServer: ${e}`),this.emit(di),this._leaveHandle(!e),e){((null==t?void 0:t.users)||[]).forEach((e=>{e.userId===this._context.getCurrentId()&&(s=e.type,r=e.kickExtra)}));const e=Date.now(),o=JSON.stringify({cod:ci[s||1],rid:this._roomId,csnid:this.getClientSessionId(),snid:this.getSessionId(),time:e,cr:"unknown",net:"unknown",uid:this.getCrtUserId()});h(R.STATISTICS,A.L_QS_KICKED_S,o,i.RTC)}this._callAppListener("onKickOff",e,s,r)}))}_rtcpeerClosed(){this.emit(di),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,t,r){return v(this,void 0,void 0,(function*(){const{uris:i,ignore:s}=e;!s&&i&&this._invoker.push(new Zr(e,t,r,this._subhook.bind(this),{onAudioMute:this._onAudioMuteChange.bind(this),onVideoMute:this._onVideoMuteChange.bind(this),onTrackPublish:this._onTrackPublish.bind(this),onTrackUnublish:this._onTrackUnpublish.bind(this),onCDNEnableChange:this._callAppListener.bind(this,"onCDNEnableChange")}))}))}_onTrackPublish(e){this._callAppListener("onTrackPublish",e)}_stateHandle(e){var t;return v(this,void 0,void 0,(function*(){const{left:r,joined:i,upgrade:s,downgrade:o}=yield this._invoker.push(new Qr(e,this._subhook.bind(this)));if(null===(t=this._appListener)||void 0===t?void 0:t.onSwitchRole)return s.length&&s.forEach((e=>this._callAppListener("onSwitchRole",e,mr.ANCHOR))),o.length&&o.forEach((e=>this._callAppListener("onSwitchRole",e,mr.AUDIENCE))),i.length&&this._callAppListener("onUserJoin",i),void(r.length&&this._callAppListener("onUserLeave",r));const n=[...i,...s],a=[...r,...o];n.length&&this._callAppListener("onUserJoin",n),a.length&&this._callAppListener("onUserLeave",a)}))}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}__getPC(){return this._store.peerMgr.getPCList()}getRemoteUserIds(){return this._store.getRemoteUserIds()}getRemoteTracks(){const e=[];return this.getRemoteUserIds().forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),e}getRemoteTracksByUserId(e){return this._store.getRemoteTracksByUserId(e)}getSessionId(){return this._store.getSessionId()}sendMessage(e,t){return v(this,void 0,void 0,(function*(){r.info(A.L_ABSTRACT_ROOM_SEND_MESSAGE_T,{name:e,content:t},{logSource:i.RTC});const{code:s}=yield this._context.sendMessage(T.RTC_ROOM,this._roomId,{messageType:e,content:t,isStatusMessage:!0});return s!==a.SUCCESS?(O.error(`send message failed -> code: ${s}`),r.error(A.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:D.FAILED,code:s,msg:""},{logSource:i.RTC}),{code:L.SIGNAL_ERROR}):(r.info(A.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:D.SUCCESSED,name:e,content:t},{logSource:i.RTC}),{code:L.SUCCESS})}))}setRoomAttribute(e,t,s,o=!1){return v(this,void 0,void 0,(function*(){r.info(A.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_T,{roomId:this._roomId,key:e,value:t,message:s,isInner:o},{logSource:i.RTC});const n=yield this._context.setRTCData(this._roomId,e,t,o,Or.ROOM,s);return n!==a.SUCCESS?(O.error(`SetRoomAttributeValue Failed: ${n}`),r.error(A.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:D.FAILED,code:n,msg:""},{logSource:i.RTC}),{code:L.SIGNAL_ERROR}):(r.info(A.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:D.SUCCESSED,roomId:this._roomId,key:e,value:t,message:s,isInner:o},{logSource:i.RTC}),{code:L.SUCCESS})}))}deleteRoomAttributes(e,t,s=!1){return v(this,void 0,void 0,(function*(){r.info(A.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_T,{roomId:this._roomId,keys:e,message:t,isInner:s},{logSource:i.RTC});const o=yield this._context.removeRTCData(this._roomId,e,s,Or.ROOM,t);return o!==a.SUCCESS?(O.error(`DeleteRoomAttribute Failed: ${o}`),r.error(A.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:D.FAILED,code:o,msg:""},{logSource:i.RTC}),{code:L.SIGNAL_ERROR}):(r.info(A.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:D.SUCCESSED,roomId:this._roomId,keys:e,message:t,isInner:s},{logSource:i.RTC}),{code:L.SUCCESS})}))}getRoomAttributes(e=[],t=!1){return v(this,void 0,void 0,(function*(){const{code:r,data:i}=yield this._context.getRTCData(this._roomId,e,t,Or.ROOM);return r!==a.SUCCESS?(O.error(`GetRoomAttributes Failed: ${r}`),{code:L.SIGNAL_ERROR}):{code:L.SUCCESS,data:i}}))}_setUserAttributeValue(e,t,r){return this._context.setRTCData(this._roomId,e,t,!1,Or.PERSON,r)}_deleteUserAttributes(e,t){return this._context.removeRTCData(this._roomId,e,!1,Or.PERSON,t)}_getUserAttributes(e){return this._context.getRTCData(this._roomId,e,!1,Or.PERSON)}isDestroyed(){return this._invoker.isDestroyed()}__destroy(e){return this._leaveHandle(e)}_muteRemoteTracksBeforeQuit(){const e=Object.values(this._store.getRemoteTracks());e.length&&e.forEach((e=>e.mute()))}_leaveHandle(e){var t;return v(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;Qt.destroy(),this._invoker.destroy(),this._muteRemoteTracksBeforeQuit(),this._muteRemoteTracksBeforeQuit(),null===(t=this._audioLevelReport)||void 0===t||t.clearAudioLevelReportTimer(),e&&(yield this._context.quitRTCRoom(this._roomId)),this._store.isMainRoom&&(yield this._quitAllPKRoom()),this._pinger.stop();const r=[];Object.keys(this._peerCManager.getMutilPeerCData()).forEach((e=>{r.push(this._service.exit(this._getRTCReqestHeaders(e)))})),yield Promise.all(r),this._releasePCManager(),this._polarisReport=null}))}_releasePCManager(){const e=this._peerCManager.getPCList();null==e||e.forEach((e=>{e.off(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)})),this._peerCManager.clear(),this._peerCManager=null}_onLocalTrackDestroied(e){e instanceof at&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(e,t){return v(this,void 0,void 0,(function*(){this._invoker.push(new ri(e,t))}))}publish(e){return v(this,void 0,void 0,(function*(){return this._invoker.push(new ei(e,this._pubhook.bind(this)))}))}_getPushOtherRoomsParams(){return[]}_reTryExchange(e,t){return v(this,void 0,void 0,(function*(){this._invoker.push(new ii(e,t,(e=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(e)}))))}))}_getRTCReqestHeaders(e){return{"App-Key":this._context.getAppkey(),RoomId:this._roomId,Token:this._store.getToken(),RoomType:this._store.roomMode,UserId:this._context.getCurrentId(),"Client-Session-Id":this._clientSessionId,"Peer-Connection-Id":e}}unpublish(e){return v(this,void 0,void 0,(function*(){return this._invoker.push(new ti(e,((e,t)=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(t)}))))}))}_getResourceById(e){return this._store.getPublishedResourceByTrackId(e)}_isValidResourceId(e){var t;const{userId:r}=Lt(e);return!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>Ot(t)===e)))}_subhook(e){const{pc:t,pcName:r}=this._peerCManager.createPeerCList(e)[0];return t.on(Ur.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),t.__reportR3R4ToPolaris(),t.registerReportListener(this._reportListener),t.clearReTryExchangeTimer(),{pc:t,pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(r)}}_pubhook(e){return{plist:this._peerCManager.createPeerCList(e).map((e=>{const{pc:t,pcName:r}=e;return t.on(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.on(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),t.registerReportListener(this._reportListener),t.__reportR3R4ToPolaris(),Object.assign(Object.assign({},e),{headers:this._getRTCReqestHeaders(r)})})),pushOtherRooms:this._getPushOtherRoomsParams()}}subscribe(e){return v(this,void 0,void 0,(function*(){return this._invoker.push(new Xr(e,this._subhook.bind(this)))}))}addSubscribeTask(e){this._invoker.push(new ni(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}unsubscribe(e){return v(this,void 0,void 0,(function*(){return this._invoker.push(new Yr(e,this._subhook.bind(this)))}))}addUnsubscribeTask(e){this._invoker.push(new ai(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}updateSubList(e){return v(this,void 0,void 0,(function*(){return this._invoker.push(new Wr(e,this._subhook.bind(this)))}))}addUpdateSubscribeListTask(e){this._invoker.push(new oi(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}_onTaskCompleted(e){this._callAppListener("onTaskCompleted",e.code,e.subscribe,e.unsubscribe,e.failedList)}getLocalTrack(e){return this._store.getLocalTrack(e)}getLocalTracks(){return this._store.getLocalTracks()}getRemoteTrack(e){return this._store.getRemoteTrack(e)||null}get subscribedTracks(){return this._store.getSubscribedList().slice()}registerRoomEventListener(e){r.info(A.L_ABSTRACT_ROOM_REGISTER_ROOM_EVENT_LISTENER_O,{status:D.SUCCESSED,listener:e&&Object.keys(e)},{logSource:i.RTC}),this._appListener=e}registerReportListener(e){r.info(A.L_ABSTRACT_ROOM_REGISTER_REPORT_LISTENER_O,{status:D.SUCCESSED,listener:e&&Object.keys(e)},{logSource:i.RTC}),this._reportListener=e}onAudioLevelChange(e,t){var s;r.info(A.L_ABSTRACT_ROOM_AUDIO_LEVEL_O,{status:D.SUCCESSED,handler:null==e?void 0:e.name,gap:t},{logSource:i.RTC}),null===(s=this._audioLevelReport)||void 0===s||s.clearAudioLevelReportTimer(),this._audioLevelReport=new Mr(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}__onReconnected(e){return v(this,void 0,void 0,(function*(){return this._invoker.push(new si(this._subhook.bind(this),{onPeerClosed:this._rtcpeerClosed.bind(this),onAudioMuteChange:this._onAudioMuteChange.bind(this),onVideoMuteChange:this._onVideoMuteChange.bind(this),onUserJoin:this._callAppListener.bind(this,"onUserJoin"),onUserLeave:this._callAppListener.bind(this,"onUserLeave"),onTrackPublish:this._onTrackPublish.bind(this),onTrackUnpublish:this._onTrackUnpublish.bind(this),onCDNEnableChange:this._callAppListener.bind(this,"onCDNEnableChange")},e))}))}_onAudioMuteChange(e){this._callAppListener("onAudioMuteChange",e)}_onVideoMuteChange(e){this._callAppListener("onVideoMuteChange",e)}_registerPKMsgListener(e){this._onRecvPKMsg=e}_quitAllPKRoom(){}getClientSessionId(){return this._clientSessionId}}class ui extends wr{constructor(e,t){super(),this.data=e,this.cdnValues=t}execute(e,t){var r,i,s,o;return v(this,void 0,void 0,(function*(){const t={"App-Key":e.context.getAppkey(),Token:e.getToken(),RoomId:e.roomId,UserId:e.context.getCurrentId(),SessionId:e.getSessionId()},{code:n,res:a}=yield e.service.setMcuConfig(t,this.data);if(n!==L.SUCCESS)return O.error(`set MCU config failed: ${n}`),{code:n};O.info("set MCU config success"),a.pull_url&&e.setCDNUris(JSON.parse(a.pull_url));const c=this.cdnValues;return n===L.SUCCESS&&((null===(i=null===(r=c.output)||void 0===r?void 0:r.video.normal)||void 0===i?void 0:i.width)||(null===(o=null===(s=c.output)||void 0===s?void 0:s.video.normal)||void 0===o?void 0:o.fps))&&Jr(e),{code:n,res:a}}))}}var li,hi,Ri,mi;!function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(li||(li={})),function(e){e[e.CUSTOMIZE=1]="CUSTOMIZE",e[e.SUSPENSION=2]="SUSPENSION",e[e.ADAPTATION=3]="ADAPTATION"}(hi||(hi={})),function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(Ri||(Ri={})),function(e){e[e.AUDIO_VIDEO_ALL=0]="AUDIO_VIDEO_ALL",e[e.AUDIO_VIDEO_NO=1]="AUDIO_VIDEO_NO",e[e.AUDIO_ALL_VIDEO_NO=2]="AUDIO_ALL_VIDEO_NO",e[e.AUDIO_NO_VIDEO_ALL=3]="AUDIO_NO_VIDEO_ALL",e[e.AUDIO_VIDEO_INPUT=4]="AUDIO_VIDEO_INPUT",e[e.AUDIO_ALL_VIDEO_INPUT=5]="AUDIO_ALL_VIDEO_INPUT",e[e.AUDIO_NO_VIDEO_INPUT=6]="AUDIO_NO_VIDEO_INPUT",e[e.AUDIO_INPUT_VIDEO_ALL=7]="AUDIO_INPUT_VIDEO_ALL",e[e.AUDIO_INPUT_VIDEO_NO=8]="AUDIO_INPUT_VIDEO_NO",e[e.ROOM_AUDIO_VIDEO_APPEND=9]="ROOM_AUDIO_VIDEO_APPEND",e[e.ROOM_AUDIO_VIDEO_NOT_APPEND=10]="ROOM_AUDIO_VIDEO_NOT_APPEND",e[e.ROOM_AUDIO_APPEND=11]="ROOM_AUDIO_APPEND",e[e.ROOM_AUDIO_NOT_APPEND=12]="ROOM_AUDIO_NOT_APPEND",e[e.ROOM_VIDEO_APPEND=13]="ROOM_VIDEO_APPEND",e[e.ROOM_VIDEO_NOT_APPEND=14]="ROOM_VIDEO_NOT_APPEND"}(mi||(mi={}));const pi=()=>({version:2,mode:hi.SUSPENSION});class Si{constructor(e,t){this._invoker=e,this._isValidTrackId=t,this._values=pi()}setHostVideoTrack(e){if(O.info(`setHostVideoTrack -> videoTrackId: ${e}`),!this._isValidTrackId(e))return O.error(`setHostVideoTrack failed -> videoTrackId is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:D.FAILED,code:"",msg:"params error -> videoTrackId"},{logSource:i.RTC}),this;const{mediaType:t,tag:s,userId:o}=Lt(e);return t!==He.VIDEO_ONLY?(O.error(`setHostVideoTrack failed -> kind of resource is not 'video' -> ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:D.FAILED,code:"",msg:"not video"},{logSource:i.RTC}),this):(this._values.host_stream_id=At(o,s),r.info(A.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:D.SUCCESSED,videoTrackId:e},{logSource:i.RTC}),this)}setMixLayoutMode(e){O.info(`setMixLayoutMode -> mode: ${e}`);return[hi.CUSTOMIZE,hi.SUSPENSION,hi.ADAPTATION].includes(e)?(this._values.mode=e,r.info(A.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:D.SUCCESSED,mode:e},{logSource:i.RTC}),this):(O.error(`setMixLayoutMode failed -> mode is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:D.SUCCESSED,code:"",msg:`params error -> mode: ${e}`},{logSource:i.RTC}),this)}_addOutputValue(e,t,r="normal"){const i=this._values.output||(this._values.output={video:{normal:{width:640,height:480}}});if("cdn"===e)return void(i.cdn=t);if("audio"===e)return void(i.audio={bitrate:t});const{video:s}=i;if("normal"!==r&&"tiny"!==r)if("backgroundColor"!==r)if("exparams"!==r){if("backgroundPicture"===r){const e=s.backgroundPicture||(s.backgroundPicture={fillMode:li.CROP,picture:[]});Object.assign(e,t)}}else s.exparams={renderMode:t};else s.backgroundColor=t;else{const e=s[r]||(s[r]={});Object.assign(e,t)}}setOutputVideoResolution(e){if(O.info(`setOutputVideoResolution -> resolution: ${e}`),!yt(e))return O.error(`setOutputVideoResolution failed -> resolution is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:D.FAILED,code:"",msg:`params error -> resolution: ${e}`},{logSource:i.RTC}),this;const{width:t,height:s}=kt(e);return this._addOutputValue("video",{width:t,height:s},"normal"),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:D.SUCCESSED,resolution:e},{logSource:i.RTC}),this}setOutputVideoFPS(e){if(O.info(`setOutputVideoFPS -> fps: ${e}`),!Ut(e))return O.error(`setOutputVideoFPS failed -> fps is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:D.FAILED,code:"",msg:`params error -> fps: ${e}`},{logSource:i.RTC}),this;const t=Pt(e);return this._addOutputValue("video",{fps:t},"normal"),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:D.SUCCESSED,fps:e},{logSource:i.RTC}),this}setOutputVideoBitrate(e){return O.info(`setOutputVideoBitrate -> bitrate: ${e}`),!s(e)||e<=0?(O.error(`setOutputVideoBitrate failed -> bitrate is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:D.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:i.RTC})):this._addOutputValue("video",{bitrate:e},"normal"),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:D.SUCCESSED,bitrate:e},{logSource:i.RTC}),this}setOutputTinyVideoResolution(e){if(O.info(`setOutputTinyVideoResolution -> resolution: ${e}`),!yt(e))return O.error(`setOutputTinyVideoResolution failed -> resolution is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:D.FAILED,code:"",msg:`params error -> resolution: ${e}`},{logSource:i.RTC}),this;const{width:t,height:s}=kt(e);return this._addOutputValue("video",{width:t,height:s},"tiny"),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:D.SUCCESSED,resolution:e},{logSource:i.RTC}),this}setOutputTinyVideoFPS(e){if(O.info(`setOutputTinyVideoFPS -> fps: ${e}`),!Ut(e))return O.error(`setOutputTinyVideoFPS failed -> fps is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:D.FAILED,code:"",msg:`params error -> fps: ${e}`},{logSource:i.RTC}),this;const t=Pt(e);return this._addOutputValue("video",{fps:t},"tiny"),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:D.SUCCESSED,fps:e},{logSource:i.RTC}),this}setOutputTinyVideoBitrate(e){return O.info(`setOutputTinyVideoBitrate -> bitrate: ${e}`),!s(e)||e<=0?(O.error(`setOutputTinyVideoBitrate failed -> bitrate is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:D.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:i.RTC})):this._addOutputValue("video",{bitrate:e},"tiny"),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:D.SUCCESSED,bitrate:e},{logSource:i.RTC}),this}setOutputVideoRenderMode(e){return O.info(`setOutputVideoRenderMode -> renderMode: ${e}`),[Ri.CROP,Ri.WHOLE].includes(e)?this._addOutputValue("video",e,"exparams"):(O.error(`setOutputVideoRenderMode failed -> renderMode is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:D.FAILED,code:"",msg:`params error -> renderMode: ${e}`},{logSource:i.RTC})),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:D.SUCCESSED,renderMode:e},{logSource:i.RTC}),this}setOutputAudioBitrate(e){return O.info(`setOutputAudioBitrate -> bitrate: ${e}`),s(e)&&e>0?this._addOutputValue("audio",e):(O.error(`setOutputAudioBitrate failed -> bitrate is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:D.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:i.RTC})),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:D.SUCCESSED,bitrate:e},{logSource:i.RTC}),this}setOutputBackgroundColor(e){return O.info(`setOutputBackgroundColor -> color: ${e}`),/^0x[a-fA-F0-9]{6}$/.test(e)?this._addOutputValue("video",e,"backgroundColor"):(O.error(`setOutputBackgroundColor failed -> color is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:D.FAILED,code:"",msg:`params error -> color: ${e}`},{logSource:i.RTC})),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:D.SUCCESSED,color:e},{logSource:i.RTC}),this}addOutputBackgroundPicture(e,t,o,n,a){var c,d,_;if(O.info(`addOutputBackgroundPicture -> uri: ${e}, x: ${t}, y: ${o}, w: ${n}, h: ${a}`),!C(e))return O.error(`addOutputBackgroundPicture failed -> uri is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:D.FAILED,code:"",msg:`params error -> uri: ${e}`},{logSource:i.RTC}),this;if([t,o,n,a].some((e=>!s(e)||e<0||e>1)))return O.error(`addOutputBackgroundPicture failed -> some attrs of (x, y, w, h) is invalid: ${t}, ${o}, ${n}, ${a}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:D.FAILED,code:"",msg:`params error -> x: ${t}, y: ${o}, w: ${n}, h: ${a}`},{logSource:i.RTC}),this;const u=(null===(_=null===(d=null===(c=this._values.output)||void 0===c?void 0:c.video)||void 0===d?void 0:d.backgroundPicture)||void 0===_?void 0:_.picture)||[];return u.push({uri:e,w:n,h:a,x:t,y:o}),this._addOutputValue("video",{picture:u},"backgroundPicture"),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:D.SUCCESSED,uri:e,x:t,y:o,w:n,h:a},{logSource:i.RTC}),this}removeOutputBackgroundPicture(e){var t,s,o;if(O.info(`removeOutputBackgroundPicture -> uri: ${e}`),!C(e))return O.error(`removeOutputBackgroundPicture failed -> uri is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:D.FAILED,code:"",msg:`params error -> uri: ${e}`},{logSource:i.RTC}),this;let n=null===(o=null===(s=null===(t=this._values.output)||void 0===t?void 0:t.video)||void 0===s?void 0:s.backgroundPicture)||void 0===o?void 0:o.picture;return n&&(n=n.filter((t=>t.uri!==e)),this._addOutputValue("video",{pictures:n},"backgroundPicture")),r.info(A.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:D.SUCCESSED,uri:e},{logSource:i.RTC}),this}clearOutputBackgroundPicture(){return O.info("clearOutputBackgroundPicture ->"),this._addOutputValue("video",{pictures:[]},"backgroundPicture"),r.info(A.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:D.SUCCESSED},{logSource:i.RTC}),this}setOutputBackgroundPictureFillMode(e){return O.info(`setOutputBackgroundPictureFillMode -> fillMode: ${e}`),[li.CROP,li.WHOLE].includes(e)?this._addOutputValue("video",{fillMode:e},"backgroundPicture"):(O.error(`setOutputBackgroundPictureFillMode failed -> fillMode is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:D.FAILED,code:"",msg:`params error -> fillMode: ${e}`},{logSource:i.RTC})),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:D.SUCCESSED,fillMode:e},{logSource:i.RTC}),this}addPublishStreamUrls(e){var t,s;O.info(`addPublishStreamUrls -> urls: ${e.join(",")}`);const o=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!o.test(e))))return O.error(`addPublishStreamUrls failed -> urls is invalid: ${e.join(",")}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:D.FAILED,code:"",msg:`params error -> urls: ${e.join(",")}`},{logSource:i.RTC}),this;const n=(null===(s=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===s?void 0:s.concat())||[];let a=!1;return e.forEach((e=>{n.some((t=>t.pushurl===e))||(a=!0,n.push({pushurl:e}))})),n.length>5?(O.error("addPublishStreamUrls failed -> publish stream urls no more than 5!"),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:D.FAILED,code:"",msg:`params error -> publish stream urls no more than 5, length: ${e.length}`},{logSource:i.RTC}),this):(a&&this._addOutputValue("cdn",n),r.info(A.L_MCU_CONFIG_BUILDER_ADD_PUBLISH_STREAM_URLS_O,{status:D.SUCCESSED,urls:e},{logSource:i.RTC}),this)}removePublishStreamUrls(e){var t,s;O.info(`removePublishStreamUrls -> urls: ${e.join(",")}`);const o=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!o.test(e))))return O.error(`removePublishStreamUrls failed -> urls contain invalid items: ${e.join(",")}`),r.error(A.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:D.FAILED,code:"",msg:`params error -> urls: ${e.join(",")}`},{logSource:i.RTC}),this;const n=(null===(s=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===s?void 0:s.concat())||[];for(let t=n.length-1;t>=0;t-=1){const{pushurl:r}=n[t],i=e.indexOf(r);i>=0&&(e.splice(i,1),n.splice(t,1))}return this._addOutputValue("cdn",n),r.info(A.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:D.SUCCESSED,urls:e},{logSource:i.RTC}),this}clearPublishStreamUrls(){return O.info("clearPublishStreamUrls ->"),this._addOutputValue("cdn",[]),r.info(A.L_MCU_CONFIG_BUILDER_CLEAR_PUBLISH_STREAM_URLS_O,{status:D.SUCCESSED},{logSource:i.RTC}),this}addCustomizeLayoutVideo(e,t,o,n,a){if(O.info(`addCustomizeLayoutVideo -> trackId: ${e}, x: ${t}, y: ${o}, width: ${n}, height: ${a}`),!m(e)||!this._isValidTrackId(e))return O.error(`addCustomizeLayoutVideo failed -> trackId is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;if(!s(t)||!s(o))return O.error(`addCustomizeLayoutVideo failed -> some attrs of (x, y) is invalid: ${t}, ${o}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.FAILED,code:"",msg:`params error -> x: ${t}, y: ${o}`},{logSource:i.RTC}),this;if([n,a].some((e=>!s(e)||e<0)))return O.error(`addCustomizeLayoutVideo failed -> some attrs of (width, height) is invalid: ${n}, ${a}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.FAILED,code:"",msg:`params error -> width: ${n}, height: ${a}`},{logSource:i.RTC}),this;const{userId:c,tag:d,mediaType:_}=Lt(e);if(_!==He.VIDEO_ONLY)return O.error(`addCustomizeLayoutVideo failed -> kind of trackId is not 'video': ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}的资源不是视频`},{logSource:i.RTC}),this;const u=At(c,d),l=this._values.input||(this._values.input={}),h=l.video||(l.video=[]);return h.some((e=>e.height===a&&e.width===n&&e.stream_id===u&&e.user_id===c&&e.x===t&&e.y===o))?(r.warn(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.FAILED,code:"",msg:"Duplicate configuration item ignored"},{logSource:i.RTC}),this):(h.push({user_id:c,stream_id:u,x:t,y:o,width:n,height:a}),r.info(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.SUCCESSED,trackId:e,x:t,y:o,width:n,height:a},{logSource:i.RTC}),this)}removeCustomizeLayoutVideo(e){if(O.info(`clearCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return O.error(`clearCustomizeInputAudio failed -> trackId is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const{userId:t,tag:s,mediaType:o}=Lt(e);if(o!==He.VIDEO_ONLY)return O.error(`clearCustomizeInputAudio failed -> kind of trackId is not 'video': ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}的资源不是视频`},{logSource:i.RTC}),this;const n=At(t,s),{input:a}=this._values;return(null==a?void 0:a.video)&&a.video.length>0&&(a.video=a.video.filter((e=>e.stream_id===n))),r.info(A.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.SUCCESSED,trackId:e},{logSource:i.RTC}),this}clearCustomizeLayoutVideo(){O.info("clearCustomizeLayoutVideo ->");const{input:e}=this._values;return null==e||delete e.video,r.info(A.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.SUCCESSED},{logSource:i.RTC}),this}setCustomizeInputAudio(e){if(O.info(`setCustomizeInputAudio -> trackIds: ${e.join(",")}`),e.some((e=>this._isValidTrackId(e))))return O.warn(`setCustomizeInputAudio failed -> trackIds contain invalid items: $${e.join(",")}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:D.FAILED,code:"",msg:`params error -> trackIds: ${e.join(",")}`},{logSource:i.RTC}),this;return(this._values.input||(this._values.input={})).audio=e.map((e=>{const{userId:t,tag:r}=Lt(e);return{stream_id:At(t,r),user_id:t}})),this._values.inputFilterMode=mi.AUDIO_INPUT_VIDEO_ALL,r.info(A.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:D.SUCCESSED,trackIds:e},{logSource:i.RTC}),this}addCustomizeInputAudio(e){if(O.info(`addCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return O.warn(`addCustomizeInputAudio failed -> trackId is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const t=this._values.input||(this._values.input={}),s=t.audio||(t.audio=[]),{userId:o,tag:n}=Lt(e),a=At(o,n);return s.some((e=>e.stream_id===a&&e.user_id===o))?(r.warn(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:D.FAILED,code:"",msg:`trackId:${e} is exist`},{logSource:i.RTC}),this):(s.push({user_id:o,stream_id:a}),this._values.inputFilterMode=mi.AUDIO_INPUT_VIDEO_ALL,r.info(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:D.SUCCESSED,trackId:e},{logSource:i.RTC}),this)}removeCustomizeInputAudio(e){if(O.info(`removeCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return O.error(`removeCustomizeInputAudio failed -> trackId is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const{input:t}=this._values;if(!(null==t?void 0:t.audio)||0===t.audio.length)return r.error(A.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:D.FAILED,code:"",msg:"not audio"},{logSource:i.RTC}),this;const{userId:s,tag:o}=Lt(e),n=At(s,o);return t.audio=t.audio.filter((e=>s!==e.user_id||n!==e.stream_id)),r.info(A.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:D.SUCCESSED,trackId:e},{logSource:i.RTC}),this}clearCustomizeInputAudio(){O.info("clearCustomizeInputAudio ->");const{input:e}=this._values;return(null==e?void 0:e.audio)&&delete e.audio,this._values.inputFilterMode=mi.AUDIO_VIDEO_ALL,r.info(A.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_INPUT_AUDIO_O,{status:D.SUCCESSED},{logSource:i.RTC}),this}addPictureWaterMark(e,t,o,n,a,c){if(O.info(`addPictureWaterMark -> trackId: ${e} uri: ${t}, x: ${o}, y: ${n}, w: ${a}, h: ${c}`),!this._isValidTrackId(e))return O.warn(`addPictureWaterMark failed -> trackId is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;if(!C(t))return O.error(`addPictureWaterMark failed -> uri is invalid: ${t}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:D.FAILED,code:"",msg:`params error -> uri: ${t}`},{logSource:i.RTC}),this;if([o,n,a,c].some((e=>!s(e)||e<0||e>1)))return O.error(`addPictureWaterMark failed -> some attrs of (x, y, w, h) is invalid: ${o}, ${n}, ${a}, ${c}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:D.FAILED,code:"",msg:`params error -> x: ${o}, y: ${n}, w: ${a}, h: ${c}`},{logSource:i.RTC}),this;const{userId:d,tag:_}=Lt(e),u=At(d,_),l=this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]}),{singleScreen:h}=l;O.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(h)}`);const R=h.filter((e=>e.streamId===u))[0];return O.info(`addPictureWaterMark target-> : ${R}`),R?R.picture.push({uri:t,w:a,h:c,x:o,y:n}):h.push({streamId:u,picture:[{uri:t,w:a,h:c,x:o,y:n}]}),O.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(h)}`),this._values.waterMark.singleScreen=h,O.info(`addPictureWaterMark this._values.waterMark.singleScreen-> : ${JSON.stringify(this._values.waterMark.singleScreen)}`),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:D.SUCCESSED,trackId:e,uri:t,x:o,y:n,w:a,h:c},{logSource:i.RTC}),this}clearPictureWaterMark(){O.info("clearOutputBackgroundPicture ->");return(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen=[],r.info(A.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:D.SUCCESSED},{logSource:i.RTC}),this}removePictureWaterMark(e,t){if(!m(e)||!this._isValidTrackId(e))return r.error(A.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const{userId:s,tag:o}=Lt(e),n=At(s,o),a=this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]}),{singleScreen:c}=a;return c.forEach((e=>{e.streamId===n&&(e.picture=e.picture.filter((e=>e.uri!==t)))})),r.info(A.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O,{status:D.SUCCESSED,trackId:e,uri:t},{logSource:i.RTC}),this}reset(){return O.info("MCUConfigBuilder.reset ->"),this._values=pi(),r.info(A.L_MCU_CONFIG_BUILDER_RESET_O,{status:D.SUCCESSED},{logSource:i.RTC}),this}flush(e=!0){return v(this,void 0,void 0,(function*(){const t=JSON.parse(JSON.stringify(this._values)),{code:s}=yield this._invoker.push(new ui(t,this._values));return e&&(this._values=pi()),r.info(A.L_MCU_CONFIG_BUILDER_FLUSH_O,{status:D.SUCCESSED},{logSource:i.RTC}),{code:s}}))}__innerGetValues(){return JSON.parse(JSON.stringify(this._values))}}var Ti,Ci,Ii,Ei;!function(e){e[e.VIDEO=0]="VIDEO",e[e.AUDIO=1]="AUDIO"}(Ti||(Ti={})),function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(Ci||(Ci={}));class gi extends wr{constructor(e,t,r){super(),this.roomId=e,this.hooks=t,this.roomPKHandler=r}_exchangeWithPushOtherRoom(e,t){return v(this,void 0,void 0,(function*(){if(!e.getLocalTracks().length)return;const r=Object.values(e.peerMgr.getMutilPeerCData()),i=Object.keys(e.peerMgr.getMutilPeerCData());for(let s=0;s<r.length;s++){const{pc:o,isPub:n}=r[s],a=n&&e.useMutilPeerC?[]:e.getSubscribedList(),c=yield Kr(a,!1,o,e),{pushOtherRooms:d,headers:_}=this.hooks(i[s]);c.pushOtherRooms=d;const u=yield new qr(_,c).execute(e,t);if(u.code!==L.SUCCESS)return void O.error(`exchange with pushOtherRoom failed: ${u.code}`);const{sdp:l,resultCode:h}=u.data;if(h!==L.SUCCESS)return void O.error(`exchange with pushOtherRoom failed: ${h}`);o.setRemoteAnswer(l.sdp)}}))}execute(e,t){return v(this,void 0,void 0,(function*(){const{roomId:s}=this;if(r.info(A.L_LIVING_ROOM_JOINED_PK_ROOM_T,{roomId:s,userId:e.crtUserId},{logSource:i.RTC}),!this.roomPKHandler)return void r.error(A.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:D.FAILED,code:"",msg:"_roomPKHandler not exist"},{logSource:i.RTC});const o=this.roomPKHandler.getPKInfo(s);if(!o)return O.warn(`exchange to update pushOtherRoom cancel, pkInfo lost -> roomId: ${s}`),void r.error(A.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:D.FAILED,code:"",msg:"PKInfo not exist"},{logSource:i.RTC});yield this._exchangeWithPushOtherRoom(e,t),r.info(A.L_LIVING_ROOM_JOINED_PK_ROOM_T,{status:D.SUCCESSED,roomId:s,userId:e.crtUserId,PKInfo:o},{logSource:i.RTC})}))}}class fi extends wr{constructor(e,t,r,i,s,o){super(),this.pkHandler=e,this.room=t,this._PKInfo=r,this.hooks=i,this._joinedPKRooms=s,this.isQuitPK=o}get kind(){return pr.LeaveRoom}quitRoomPK(e,t){return v(this,void 0,void 0,(function*(){if(!this._PKInfo[e])return;const{inviterRoomId:r,inviteeRoomId:i,inviterUserId:s,inviteSessionId:o}=this._PKInfo[e],n={inviteeRoomId:i,inviterRoomId:r,userId:t.crtUserId},c={roomId:t.roomId,endRoomId:e,sessionId:o,content:JSON.stringify(n),keys:[`${r}|${s}`]};O.info(`quitRoomPK -> params: ${JSON.stringify(c)}`);const d=yield t.context.endRoomPK(c);return d!==a.SUCCESS?(O.error(`quitRoomPK failed: ${d}`),{code:L.SIGNAL_ERROR}):(O.info("quitRoomPK success"),delete this._PKInfo[e],{code:L.SUCCESS})}))}execute(e,t){return v(this,void 0,void 0,(function*(){const{room:s,isQuitPK:o}=this,n=s.getRoomId();return O.info(`leavePKRoom -> userId: ${e.crtUserId} , roomId: ${n}`),r.info(A.L_LIVING_ROOM_LEAVE_PK_ROOM_T,{roomId:n,userId:e.crtUserId,isQuitPK:o},{logSource:i.RTC}),yield s.__destroy(!0),delete this._joinedPKRooms[n],yield new gi(n,this.hooks,this.pkHandler).execute(e,t),o&&this.quitRoomPK(n,e),r.info(A.L_LIVING_ROOM_LEAVE_PK_ROOM_R,{status:D.SUCCESSED,roomId:n,userId:e.crtUserId,isQuitPK:o},{logSource:i.RTC}),{code:L.SUCCESS}}))}}class vi{constructor(e,t,r,i,s,o,n,a,c,d,_){this._invoker=e,this._PKInfo=t,this._hooks=r,this._context=i,this._runtime=s,this._service=o,this._initOptions=n,this._mainLivingRoom=a,this._registerPKMsgListener=c,this._onJoinedPKRoom=d,this._clientSessionId=_,this._inviteTimeout=30,this._appListener=null,this._joinedPKRooms={},this._registerPKMsgListener(this._onRecvPKMsg.bind(this)),this._mainRoomId=this._mainLivingRoom.getRoomId()}_callAppListener(e,...t){var r;O.info(`${e} callback ->`,...t);const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){O.error(e)}}_onInvite(e){const t=e.inviteInfo||{},{inviterRoomId:r,inviterUserId:i,extra:s}=t,o={inviterRoomId:r,inviterUserId:i,extra:s};this._PKInfo[r]=t,this._callAppListener("onRequestJoinOtherRoom",o)}_onCancelInvite(e){const{inviterRoomId:t,inviterUserId:r,extra:i}=e.inviteInfo||{},s={inviterRoomId:t,inviterUserId:r,extra:i};delete this._PKInfo[t],this._callAppListener("onCancelRequestOtherRoom",s)}_onInviteTimeout(e){}_onInviteAnswer(e){const{answerCode:t,inviteContent:r}=e,{inviteSessionId:i,inviterUserId:s,inviterRoomId:o,inviteeUserId:n,inviterUserAutoMix:a,inviteeUserAutoMix:c,inviteeRoomId:d,extra:_}=r,u={agree:1===t,inviterRoomId:o,inviterUserId:s,inviteeRoomId:d,inviteeUserId:n,extra:_};this._PKInfo[d]=this._PKInfo[d]||{inviteSessionId:i,inviterRoomId:o,inviterUserId:s,inviterUserAutoMix:a,inviteeRoomId:d},this._PKInfo[d].inviteeUserAutoMix=c,this._callAppListener("onResponseJoinOtherRoom",u)}createLeaveOtherRoomCommand(e,t){return new fi(this,e,this._PKInfo,this._hooks,this._joinedPKRooms,t)}_onPKEnd(e){return v(this,void 0,void 0,(function*(){const{inviteeRoomId:t,inviterRoomId:r,userId:i}=e.inviteInfo,s=r===this._mainRoomId?t:r,o={endRoomId:s,endUserId:i},n=this._joinedPKRooms[s];n&&(yield this._invoker.push(this.createLeaveOtherRoomCommand(n))),delete this._PKInfo[s],this._callAppListener("onFinishOtherRoom",o)}))}_onRecvPKMsg(e){const{targetId:t,content:r,messageType:i}=e;switch(i){case jt.PK_INVITE:this._onInvite(r);break;case jt.PK_CANCEL_INVITE:this._onCancelInvite(r);break;case jt.PK_INVITE_TIMEOUT:this._onInviteTimeout(r);break;case jt.PK_INVITE_ANSWER:this._onInviteAnswer(r);break;case jt.PK_END:this._onPKEnd(r)}}registerRoomPKEventListener(e){r.info(A.L_LIVING_PK_HANDLER_REGISTER_ROOM_PK_EVENT_LISTENER_O,{status:D.SUCCESSED,listener:e&&Object.keys(e)},{logSource:i.RTC}),this._appListener=e}requestJoinOtherRoom(e,t,s){return v(this,void 0,void 0,(function*(){if(r.info(A.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:e,inviteeUserId:t,options:s},{logSource:i.RTC}),!o("inviteeRoomId",e,m,!0)||!o("inviteeUserId",t,m,!0))return r.error(A.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> inviteeRoomId 或 inviteeUserId"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};O.info(`requestRoomPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; options: ${JSON.stringify(s||{})}`);const n=qt(),c=!I(null==s?void 0:s.autoMix)||(null==s?void 0:s.autoMix),d={inviteSessionId:n,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:c,inviteeRoomId:e,inviteeUserId:t,inviteeTimeoutTime:this._inviteTimeout,extra:(null==s?void 0:s.extra)||""},_={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteTimeout:this._inviteTimeout,inviteInfo:JSON.stringify(d),inviteSessionId:n};O.info(`requestRoomPK -> params: ${JSON.stringify(_)}`);const u=yield this._context.requestRoomPK(_);return u!==a.SUCCESS?(O.error(`requestRoomPK failed: ${u}`),r.error(A.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:u,msg:""},{logSource:i.RTC}),{code:u}):(O.info("requestRoomPK success"),this._PKInfo[e]={inviteSessionId:n,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:c,inviteeRoomId:e},r.info(A.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{inviteeRoomId:e,inviteeUserId:t,options:s},{logSource:i.RTC}),{code:L.SUCCESS})}))}cancelRequestJoinOtherRoom(e,t,s){return v(this,void 0,void 0,(function*(){if(r.info(A.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:e,inviteeUserId:t,extra:s,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),!o("inviteeRoomId",e,m,!0)||!o("inviteeUserId",t,m,!0))return r.error(A.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> inviteeRoomId or inviteeUserId"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(!this._PKInfo[e])return O.error(`The request to connect with ${t} user in room ${e} is not initiated`),r.error(A.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:`The request to connect with ${t} user in room ${e} is not initiated`},{logSource:i.RTC}),{code:L.PARAMS_ERROR};O.info(`canceRequestJoinPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; extra: ${s}`);const n={inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviteeRoomId:e,inviteeUserId:t,extra:s||""},c={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteSessionId:this._PKInfo[e].inviteSessionId,inviteInfo:JSON.stringify(n)};O.info(`canceRequestJoinPK -> params: ${JSON.stringify(c)}`);const d=yield this._context.cancelRoomPK(c);return d!==a.SUCCESS?(O.error(`canceRequestJoinPK failed: ${d}`),r.error(A.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:d,msg:`The request to connect with ${t} user in room ${e} is not initiated`},{logSource:i.RTC}),{code:d}):(O.info("canceRequestJoinPK success"),r.info(A.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:D.SUCCESSED,inviteeRoomId:e,inviteeUserId:t,extra:s},{logSource:i.RTC}),delete this._PKInfo[e],{code:L.SUCCESS})}))}responseJoinOtherRoom(e,t,s,n){return v(this,void 0,void 0,(function*(){if(r.info(A.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_T,{inviterRoomId:e,inviterUserId:t,agree:s,options:n,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),!o("inviterRoomId",e,m,!0)||!o("inviterUserId",t,m,!0))return r.error(A.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> inviterRoomId or inviterUserId"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(!this._PKInfo[e])return O.error(`User ${t} in room ${e} did not send a request for connection`),r.error(A.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:`User ${t} in room ${e} did not send a request for connection`},{logSource:i.RTC}),{code:L.PARAMS_ERROR};O.info(`responseRoomPK -> inviterRoomId: ${e}; inviterUserId: ${t}; agree: ${s}; options: ${JSON.stringify(n||{})}`);const{inviteSessionId:c,inviterUserAutoMix:d}=this._PKInfo[e],_=!I(null==n?void 0:n.autoMix)||(null==n?void 0:n.autoMix),u={inviteSessionId:c,inviterRoomId:e,inviterUserId:t,inviterUserAutoMix:d,inviteeRoomId:this._mainRoomId,inviteeUserId:this._context.getCurrentId(),inviteeUserAutoMix:_},l=Object.assign(u,{inviterUserAutoMix:d}),h=s?Object.assign(u,{MultiRoomKey:`${e}|${this._mainRoomId}`,MultiRoomValue:JSON.stringify(l)}):u;!E(null==n?void 0:n.extra)&&Object.assign(h,{extra:n.extra});const R={agree:s,roomId:this._mainRoomId,inviteSessionId:c,inviteRoomId:e,inviteUserId:t,content:JSON.stringify(h),key:`${e}|${this._mainRoomId}`,value:JSON.stringify(u)};O.info(`responseRoomPK -> params: ${JSON.stringify(R)}`);const p=yield this._context.responseRoomPK(R);return p!==a.SUCCESS?(O.error(`responseRoomPK failed: ${p}`),r.error(A.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:p,msg:""},{logSource:i.RTC}),{code:p}):(O.info("responseRoomPK success"),r.info(A.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:D.SUCCESSED,inviterRoomId:e,inviterUserId:t,agree:s,options:n,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),this._PKInfo[e].inviteeUserAutoMix=_,{code:L.SUCCESS})}))}joinOtherRoom(e){return v(this,void 0,void 0,(function*(){if(r.info(A.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_T,{roomId:e,userId:this._context.getCurrentId()},{logSource:i.RTC}),!o("roomId",e,m,!0))return r.error(A.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(this._context.getConnectionStatus()!==_.CONNECTED)return r.error(A.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.SIGNAL_DISCONNECTED,msg:"IM disconnected"},{logSource:i.RTC}),{code:L.SIGNAL_DISCONNECTED};if(O.info(`JoinPKRoom, roomId: ${e}`),this._joinedPKRooms[e])return r.warn(A.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:L.REPERT_JOIN_ROOM};const t=Ti.VIDEO,s={extra:`{"roomId": "${this._mainRoomId}"}`},n=new Ai(this._context,this._runtime,e,this._service,this._initOptions,t,!1,!1,!1,this._clientSessionId),{code:a,data:c}=yield n.__innerInit(Ir.LIVE,void 0,t,s);return a!==L.SUCCESS?(O.error(`JoinPKRoom failed -> code: ${a}`),r.error(A.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:a,msg:""},{logSource:i.RTC}),{code:a}):(O.info(`JoinPKRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(c)}`),this._joinedPKRooms[e]=n,yield this._onJoinedPKRoom(e,n),r.info(A.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:D.SUCCESSED,roomId:e,userId:this._context.getCurrentId()},{logSource:i.RTC}),{room:n,code:L.SUCCESS,userIds:n.getRemoteUserIds(),tracks:n.getRemoteTracks()})}))}leaveOtherRoom(e,t){return v(this,void 0,void 0,(function*(){return this._invoker.push(this.createLeaveOtherRoomCommand(e,t))}))}getPKInfo(e){return this._PKInfo[e]}getAllPKInfo(){return this._PKInfo}getJoinedPKRooms(){return this._joinedPKRooms}}!function(e){e[e.OPEN=1]="OPEN",e[e.STOP=2]="STOP"}(Ii||(Ii={}));class Oi extends wr{constructor(e,t){super(),this.cdnValues=e,this.enable=t}execute(e,t){return v(this,void 0,void 0,(function*(){const{enable:s}=this;if(r.info(A.L_LIVING_ROOM_ENABLE_INNER_CDN_T,{roomId:e.roomId,enable:s},{logSource:i.RTC}),!e.isMainRoom)return O.error("the `enableInnerCDN` is disabled in PK room"),r.error(A.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:D.FAILED,code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!I(s))return O.error("`enable` is invalid"),r.error(A.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> enable"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};e.setCDNEnabel(s);const o={version:2,output:{inCDNModel:s?Ii.OPEN:Ii.STOP}},{code:n}=yield new ui(o,this.cdnValues).execute(e,t);if(n!==L.SUCCESS)return O.error(`enableInnerCDN failed -> code: ${n}`),r.error(A.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:D.FAILED,code:n,msg:"signal error"},{logSource:i.RTC}),{code:L.SIGNAL_ERROR};const a=e.getCDNUris();if(a&&a.broadcast!==vr.SPREAD)return O.info("enableInnerCDN succeed"),r.info(A.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:D.SUCCESSED,enable:s},{logSource:i.RTC}),{code:L.SUCCESS};const{code:c}=yield Jr(e);return c===L.SUCCESS?(O.info("enableInnerCDN succeed"),r.info(A.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:D.SUCCESSED,enable:s},{logSource:i.RTC}),{code:L.SUCCESS}):(O.error(`enableInnerCDN failed -> code: ${c}`),r.error(A.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:D.FAILED,code:c,msg:""},{logSource:i.RTC}),{code:c})}))}}!function(e){e[e.AnchorToViewer=1]="AnchorToViewer",e[e.ViewerToAnchor=2]="ViewerToAnchor"}(Ei||(Ei={}));class Li extends wr{constructor(e){super(),this.livingType=e}execute(e,t){var r;return v(this,void 0,void 0,(function*(){const{code:i,data:s}=yield e.context.rtcIdentityChange(e.roomId,Ei.ViewerToAnchor,this.livingType);if(i!==a.SUCCESS||!s)return{code:i};e.initWithRoomData(s);e.getResourcesByUserId(e.crtUserId).length>0&&t.push(new Fr);const o=null===(r=s.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===r?void 0:r.value;return o&&e.setCDNUris(JSON.parse(o)[0]),{code:i,data:s}}))}}class Ai extends _i{constructor(e,t,r,i,s,o,n,a,c,d){super(e,t,r,Ir.LIVE,i,s,n,a,c,d),this._livingType=o,this._mcuConfigBuilder=new Si(this._invoker,this._isValidResourceId.bind(this))}_initAfterCatchRoomData(e){if(this._store.isUpgrade&&this._afterChangedRole(e),this._store.isMainRoom){const t=((e,t)=>{const r={};return t.forEach((t=>{const i=JSON.parse(t.value),{inviterRoomId:s,inviteeRoomId:o}=i;r[e===s?o:s]=JSON.parse(t.value)})),r})(this._roomId,e.roomInfo);this._roomPKHandler=new vi(this._invoker,t,(e=>({headers:this._getRTCReqestHeaders(e),pushOtherRooms:this._getPushOtherRoomsParams()})),this._context,this._runtime,this._service,this._initOptions,this,super._registerPKMsgListener.bind(this),this._onJoinedPKRoom.bind(this),this._clientSessionId)}}__innerInit(e,t,s,n,a){const c=Object.create(null,{__innerInit:{get:()=>super.__innerInit}});return v(this,void 0,void 0,(function*(){if(!o("livingType",s,(e=>e===Ti.AUDIO||e===Ti.VIDEO)))return r.error(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> livingType"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};const{code:d,data:_}=yield c.__innerInit.call(this,e,t,s,n,a);return d===L.SUCCESS&&_&&this._initAfterCatchRoomData(_),{code:d,data:_}}))}__innerInitByIdentityChange(){return v(this,void 0,void 0,(function*(){const{code:e,data:t}=yield this._invoker.push(new Li(this._livingType));return e===a.SUCCESS&&t&&(this._initAfterCatchRoomData(t),this._initWithRoomData(t.offlineKickTime),r.info(A.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:D.SUCCESSED,roomData:t},{logSource:i.RTC})),e}))}publish(e){const t=Object.create(null,{publish:{get:()=>super.publish}});return v(this,void 0,void 0,(function*(){return this._store.isMainRoom?t.publish.call(this,e):(O.warn("the `publish` is disabled in PK room "),r.error(A.L_ABSTRACT_ROOM_PUBLISH_R,{status:D.FAILED,code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}unpublish(e){const t=Object.create(null,{unpublish:{get:()=>super.unpublish}});return v(this,void 0,void 0,(function*(){return this._store.isMainRoom?t.unpublish.call(this,e):(O.warn("the `unpublish` is disabled in PK room "),r.error(A.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:D.FAILED,code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}_isValidResourceId(e){var t;const{userId:r}=Lt(e),i=!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>Ot(t)===e)));let s=!1;const{code:o,roomPKHandler:n}=this.getRoomPKHandler();if(o!==L.SUCCESS||!n)return i;const a=n.getJoinedPKRooms(),c=[];return Object.values(a).forEach((e=>{c.push(...e.getRemoteTracks())})),s=c.some((t=>e===t.getTrackId())),i||s}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._store.isMainRoom?this._mcuConfigBuilder:(O.error("the `getMCUConfigBuilder` is disabled in PK room"),{code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}enableInnerCDN(e){return v(this,void 0,void 0,(function*(){return this._invoker.push(new Oi(this._mcuConfigBuilder.__innerGetValues(),e))}))}_resourceHandle(e,t,r){const i=Object.create(null,{_resourceHandle:{get:()=>super._resourceHandle}});return v(this,void 0,void 0,(function*(){i._resourceHandle.call(this,e,t,r)}))}_afterChangedRole(e){const t=$t(e,this._roomId),r=this._context.getCurrentId(),i=Object.keys(t);setTimeout((()=>{var s;const o=i.filter((e=>e!==r));o.length>0&&this._callAppListener("onUserJoin",o);for(const e in t)e!==r&&this._resourceHandle({uris:t[e]},jt.TOTAL_CONTENT_RESOURCE,e);if(!(null===(s=e.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===s?void 0:s.value))return;const n=this._store.getCDNUris();(null==n?void 0:n.push_mode)===Ci.MANUAL&&this._callAppListener("onCDNEnableChange",null==n?void 0:n.enableInnerCDN)}))}__getCDNEnable(){var e;return!!(null===(e=this._store.getCDNUris())||void 0===e?void 0:e.enableInnerCDN)}__getCDNPushMode(){var e;return null===(e=this._store.getCDNUris())||void 0===e?void 0:e.push_mode}_onJoinedPKRoom(e,t){return v(this,void 0,void 0,(function*(){this._invoker.push(new gi(e,(e=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(e)})),this._roomPKHandler))}))}_getPushOtherRoomsParams(){const e=[];if(!this.isMainRoom()||!this._roomPKHandler)return e;const t=this._roomPKHandler.getJoinedPKRooms();for(const r in t){const i=t[r].getSessionId(),s=this._roomPKHandler.getPKInfo(r);if(!s)continue;const{inviterUserAutoMix:o,inviteeUserAutoMix:n,inviterUserId:a}=s,c=this._context.getCurrentId()===a;e.push({roomId:r,sessionId:i,autoMix:c?!!o:!!n})}return e}getRoomPKHandler(){return this._store.isMainRoom?(r.info(A.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:D.SUCCESSED},{logSource:i.RTC}),{code:L.SUCCESS,roomPKHandler:this._roomPKHandler}):(O.error("the `getRoomPKHandler` is disabled in PK room"),r.error(A.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:D.SUCCESSED,code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}_quitAllPKRoom(){return v(this,void 0,void 0,(function*(){const e=this._roomPKHandler.getJoinedPKRooms();for(const t in e)this._roomPKHandler.leaveOtherRoom(e[t]);r.info(A.L_LIVING_ROOM_QUIT_ALL_PK_ROOM_O,{status:D.SUCCESSED,roomIds:Object.keys(e)},{logSource:i.RTC})}))}isMainRoom(){return this._store.isMainRoom}}class Di extends _i{constructor(e,t,r,i,s,o,n,a,c,d=Ir.RTC){super(e,t,r,d,i,s,o,n,a,c)}}const Ni=new class{constructor(){this.queue=[],this.locked=!1,this.taskCount=0}checkToStart(){return v(this,void 0,void 0,(function*(){if(0===this.queue.length||this.locked)return;this.locked=!0;const{resolve:e,task:t,reject:r}=this.queue.shift();let i;try{i=yield t(),e(i)}catch(e){r(e)}this.locked=!1,this.checkToStart()}))}push(e,t=""){const r=new Promise(((t,r)=>{this.queue.push({resolve:t,task:e,reject:r})}));return this.checkToStart(),r}},bi=(e,t="")=>Ni.push(e,t);class ki{constructor(e,t,r,i){this._context=e,this._useMutilPeerC=i,this._rtcToken="",this._liveUrl="",this._subTracks=[],this._clientSessionId=qt(),this._livingType=null,this._mediaType=null,this._subTiny=!1,this._fromRetry=!1,this._appListener=null,this._service=new Zt(t,e,r.mediaServer),this._peerCManager=new xr(this._useMutilPeerC,this._context.getCurrentId(),this._reTryExchange.bind(this),this._context.getCurrentId())}_getReqHeaders(e){return v(this,void 0,void 0,(function*(){const t=this._context.getCurrentId(),r=t;if(!this._rtcToken){const{code:t,data:i}=yield this._context.getRTCToken(r,Ir.LIVE,e);if(t!==a.SUCCESS)return O.error(`getRTCToken failed: ${t}`),{code:L.SIGNAL_ERROR};this._rtcToken=i.rtcToken}return{code:L.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:t,RoomId:r,RoomType:Ir.LIVE,Token:this._rtcToken,"Peer-Connection-Id":this._pcName,"Client-Session-Id":this._clientSessionId}}}))}_clearSubscribeInfo(){var e;this._liveUrl="",this._livingType=null,this._mediaType=null,this._subTiny=!1,this._subTracks.length=0,null===(e=this._pc)||void 0===e||e.destroy(),this._pc=null}_reTryExchange(){var e;return v(this,void 0,void 0,(function*(){this._fromRetry=!0;const{code:t}=yield this.subscribe(this._liveUrl,this._livingType,this._mediaType,this._subTiny);t===L.SUCCESS&&(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer())}))}subscribe(e,t,r,i=!1){return v(this,void 0,void 0,(function*(){return bi((()=>this.__subscribe(e,t,r,i)),"audience-client-sub")}))}__subscribe(e,t,s,o=!1){var n;return v(this,void 0,void 0,(function*(){r.info(A.L_AUDIENCE_CLIENT_SUBSCRIBE_T,{liveUrl:e,livingType:t,mediaType:s,subTiny:o},{logSource:i.RTC});const a=[];if(Vt(this._context.getNaviInfo()))return r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:L.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:i.RTC}),{code:L.PACKAGE_ENVIRONMENT_ERROR,tracks:a};if(!this._fromRetry&&(null===(n=this._pc)||void 0===n||n.clearReTryExchangeTimer()),this._fromRetry=!1,!p(e))return O.error(`liveUrl is invalid: ${e}`),r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:`params error -> liveUrl: ${e}`},{logSource:i.RTC}),{code:L.PARAMS_ERROR,tracks:a};if(![Ti.AUDIO,Ti.VIDEO].includes(t))return O.error(`livingType is invalid: ${t}`),r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:`params error -> livingType: ${t}`},{logSource:i.RTC}),{code:L.PARAMS_ERROR,tracks:a};if(![He.AUDIO_ONLY,He.VIDEO_ONLY,He.AUDIO_VIDEO].includes(s))return O.error(`mediaType is invalid: ${s}`),r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:`params error -> -> mediaType: ${s}`},{logSource:i.RTC}),{code:L.PARAMS_ERROR,tracks:a};if(this._liveUrl&&this._liveUrl!==e)return r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:L.BROADCAST_SUB_LIST_NOT_EMPTY,msg:"repeat subscribe"},{logSource:i.RTC}),{code:L.BROADCAST_SUB_LIST_NOT_EMPTY,tracks:a};if(!this._pc){const{pcName:e,pc:t}=this._peerCManager.createPeerCList(a)[0];this._pc=t,this._pcName=e,this._pc.on(Ur.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this._pc.registerReportListener(this._reportListener),this._pc.__reportR3R4ToPolaris()}this._liveUrl=e;const{code:c,headers:d}=yield this._getReqHeaders(t);if(c!==L.SUCCESS)return r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:c,msg:""},{logSource:i.RTC}),{code:c,tracks:a};const _=`rc_mcu_${Date.now()}`,u="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new pt(u,_),new St(u,_)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const l=`${Date.now()}`;Qt.getMemo().qualityStatus=l,r.info(A.L_QS_CREATE_OFFER_O,{identify:l},{logSource:i.RTC});const h={sdp:yield this._pc.createOffer(!0),liveUrl:e,mediaType:s,simulcast:o?Xt.TINY:Xt.NORMAL,switchstream:!1};r.info(A.L_QS_SUBSCRIBE_EXCHANGE_O,{identify:l},{logSource:i.RTC});const R=yield this._service.broadcastSubscribe(d,h);if(R.code!==L.SUCCESS)return O.error(`andience subscribe failed: ${R.code}`),r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:R.code,msg:""},{logSource:i.RTC}),{code:R.code,tracks:a};const m=R.data;if(m.resultCode!==L.SUCCESS)return O.error(`andience subscribe failed! code: ${m.resultCode}; message: ${m.message}`),r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:m.resultCode,msg:""},{logSource:i.RTC}),{code:m.resultCode,tracks:a};O.debug(`andience subscribe success: ${e}`),this._livingType=t,this._mediaType=s,this._subTiny=o;const{sdp:S,subscribedList:T}=m;r.info(A.L_QS_GET_ANSWER_O,{identify:l},{logSource:i.RTC});const C=[];return T.forEach((e=>{const{mediaType:t}=e,r=this._subTracks[t];C.push(r),r.__innerSetRemoteMuted(!0)})),r.info(A.L_QS_GET_RESOURCES_O,{identify:l},{logSource:i.RTC}),this._pc.setRemoteAnswer(S.sdp),r.info(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.SUCCESSED,liveUrl:e},{logSource:i.RTC}),{code:L.SUCCESS,tracks:C}}))}unsubscribe(){return v(this,void 0,void 0,(function*(){return bi((()=>this.__unsubscribe()),"audience-client-unsub")}))}__unsubscribe(){var e;return v(this,void 0,void 0,(function*(){if(r.info(A.L_AUDIENCE_CLIENT_UNSUBSCRIBE_T,{liveUrl:this._liveUrl},{logSource:i.RTC}),null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer(),!this._rtcToken||!this._liveUrl)return r.warn(A.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:D.FAILED,code:"",msg:"Address does not exist, without unsubscribe"},{logSource:i.RTC}),{code:L.SUCCESS};const{headers:t}=yield this._getReqHeaders(),{code:s}=yield this._service.broadcastExit(t);return s!==L.SUCCESS?(O.error(`broadcast unsubscribe failed: ${s}`),r.error(A.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:D.FAILED,code:s,msg:""},{logSource:i.RTC})):(O.debug("broadcast unsubscribe success"),r.info(A.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:D.SUCCESSED,liveUrl:this._liveUrl},{logSource:i.RTC})),this._clearSubscribeInfo(),{code:s}}))}registerReportListener(e){this._reportListener=e}registerTrackEventListener(e){this._appListener=e}_onTrackReady(e){var t,s;const{track:o}=e.receiver,n="audio"===o.kind?He.AUDIO_ONLY:He.VIDEO_ONLY,a=this._subTracks[n];a.__innerSetMediaStreamTrack(o);const c=Qt.getMemo();r.info(A.L_QS_CREATE_OFFER_O,{identify:c.qualityStatusId},{logSource:i.RTC});try{null===(s=null===(t=this._appListener)||void 0===t?void 0:t.onTrackReady)||void 0===s||s.call(t,a)}catch(e){O.error(e)}}}var yi,Ui;!function(e){e.RTMP="rtmp",e.FLV="flv",e.HLS="hls"}(yi||(yi={})),function(e){e[e.NOT_HTTPS=0]="NOT_HTTPS",e[e.HTTPS=1]="HTTPS"}(Ui||(Ui={}));const Pi=Object.assign(Object.assign({},kt(je.W176_H144)),{frameRate:Pt(Ke.FPS_15)});class Mi{constructor(e,t,r,i,s,o,n,a=qt()){this._context=e,this._runtime=t,this._initOptions=r,this._roomId=i,this._joinResData=s,this.livingType=o,this._useMutilPeerC=n,this._clientSessionId=a,this._roomAnchorList=[],this._roomRes={},this._roomAnchorRes={},this._remoteTracks={},this._appListener=null,this._pc=null,this._subscribedList=[],this._sessionId="",this._destroyed=!1,this._isPulling=!1,this._pullTime=0,this._reportListener=null,this._setInitData(),this._service=new Zt(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new Pr(this._context,this._runtime,this._roomId,this,Rr.Audience),this._polarisReport.sendR1(),this._peerCManager=new xr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._context.registerRTCSignalListener((e=>v(this,void 0,void 0,(function*(){const{time:t,type:r,roomId:i}=this._context.decodeRtcNotify(e);if(O.warn(`registerRTCSignalListener -> ${JSON.stringify({time:t,type:r,roomId:i})}`),1===r)this._startPull(i,t)}))))}_startPull(e,t){return v(this,void 0,void 0,(function*(){if(this._isPulling)return;this._isPulling=!0;if(this._pullTime>t)return void(this._isPulling=!1);const{code:r,data:i}=yield this._context.pullRTCRoomEntry(e);if(r===a.SUCCESS){this._isPulling=!1,this._pullTime=i.syncTime||0;const t=(null==i?void 0:i.kvEntries)||[];O.info(`_startPull -> ${JSON.stringify(t)}`),this.singalDataChange(t,e)}}))}_setInitData(){const{sessionId:e,remoteUserIds:t,remoteRTCUris:r,remoteMUCUris:i,remoteTracks:s,CDNUris:o}=Ft(this._roomId,this._joinResData.kvEntries);this._sessionId=e,this._roomAnchorList=t,s.forEach((e=>{this._remoteTracks[e.getTrackId()]=e})),this._CDNUris=o,r.forEach((e=>{const t=e.msid.split("_")[0];this._roomAnchorRes[t]?this._roomAnchorRes[t].push(e):this._roomAnchorRes[t]=[e]})),i.forEach((e=>{const{mediaType:t,tag:r}=e,i=[this._roomId,r,t].join("_");this._roomRes[i]=e})),r.forEach((e=>{const t=Ot(e);this._roomRes[t]=e}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinLivingRoomAsAudience` to catch another instance.";return O.warn(e),L.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(e,t){var s;if(r.info(A.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_T,{singalData:e,roomId:t,userId:this._context.getCurrentId()},{logSource:i.RTC}),t!==this._roomId)return O.warn(`singalDataChange -> not the current room data: data roomId: ${t}, current roomId: ${this._roomId}`),void r.error(A.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:D.FAILED,code:"",msg:`id inconsistency -> params id:${t},current id:${this._roomId}`},{logSource:i.RTC});O.debug("singalDataChange -> singalData:",JSON.stringify(e||{}));const o=[],n=null===(s=e.filter((e=>"RC_CDN"===e.key))[0])||void 0===s?void 0:s.value;n&&this._diffCDNUris(JSON.parse(JSON.parse(n).cdn_uris)[0]),e.forEach((e=>{const{key:t,value:r,timestamp:i,uid:s}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),i=JSON.parse(e.uris||"[]");return o.push(...t),void this._diffAnchorResource(i,s)}if("RC_ANCHOR_LIST"===t){const e=JSON.parse(r||"[]"),{joinUserIds:t,leftUserIds:i}=this._diffAnchorList(e);t.length>0&&this._handleNewJoinedAnchor(t),i.length>0&&this._handleLeftedAnchor(i)}})),this._diffRoomResource(o),r.info(A.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:D.SUCCESSED,singalData:e,roomId:t,userId:this._context.getCurrentId()},{logSource:i.RTC})}_diffAnchorList(e){const t=e.filter((e=>this._roomAnchorList.indexOf(e)<0));return{leftUserIds:this._roomAnchorList.filter((t=>e.indexOf(t)<0)),joinUserIds:t}}_handleNewJoinedAnchor(e){this._roomAnchorList.push(...e),this._callAppListener("onAnchorJoin",e)}_handleLeftedAnchor(e){return v(this,void 0,void 0,(function*(){this._roomAnchorList=this._roomAnchorList.filter((t=>!(e.indexOf(t)>-1)));const t=[];e.forEach((e=>{t.push(...this.getRemoteTracksByUserId(e)),delete this._roomAnchorRes[e]})),t.length&&(yield this.unsubscribe(t),t.forEach((e=>delete this._remoteTracks[e.getTrackId()]))),this._callAppListener("onAnchorLeave",e)}))}_diffRoomResource(e){return v(this,void 0,void 0,(function*(){const t=[],r=[],i=[];e.forEach((e=>{const r=Ot(e),{userId:s,tag:o,mediaType:n}=Lt(r),a=[this._roomId,o,n].join("_");if(!this._remoteTracks[a]){const r=n===He.AUDIO_ONLY?new pt(o,"",this._roomId):new St(o,"",this._roomId);t.push(r),this._remoteTracks[a]=r,this._roomRes[r.getTrackId()]=e}i.push(a)})),Object.keys(this._remoteTracks).forEach((e=>{i.indexOf(e)<0&&this._remoteTracks[e].isMCUTrack()&&r.push(this._remoteTracks[e])})),t.length>0&&this._callAppListener("onTrackPublish",t),r.length>0&&this._onUserUnpublish(r,"onTrackUnpublish")}))}_diffAnchorResource(e,t){return v(this,void 0,void 0,(function*(){const r=this._roomAnchorRes[t]||(this._roomAnchorRes[t]=[]),{publishedList:i,unpublishedList:s,modifiedList:o}=Nt(r,e);if(i.length){const e=r.map(Ot),t=[],s=[];if(i.forEach((i=>{const o=Ot(i),n=e.indexOf(o),{userId:a,tag:c,mediaType:d}=Lt(o);n>-1?r[n]=i:r.push(i);let _=this._remoteTracks[o];this._roomRes[o]=i,_?_.isSubscribed()&&t.push(_):(_=d===He.AUDIO_ONLY?new pt(c,a):new St(c,a),this._remoteTracks[o]=_,s.push(_)),_.__innerSetRemoteMuted(0===i.state)})),t.length){const e=t.map((e=>e.getTrackId()));O.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:r}=yield bi((()=>this._subscribeHandle(t,!0)));r!==L.SUCCESS&&O.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(e)}`)}this._callAppListener("onAnchorTrackPublish",s)}if(s.length){const e=s.map(Ot);for(let t=r.length-1;t>=0;t-=1){const i=r[t];e.includes(Ot(i))&&r.splice(t,1)}const t=s.map((e=>{const t=Ot(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t,"onAnchorTrackUnpublish")}if(o.length){const e=r.map(Ot);for(let t=0;t<o.length;t++){const i=o[t],s=Ot(i),n=e.indexOf(s);r[n].state=i.state;const a=this._remoteTracks[s];a.__innerSetRemoteMuted(0===i.state),a.isAudioTrack()?this._callAppListener("onAudioMuteChange",a):this._callAppListener("onVideoMuteChange",a)}}}))}_onUserUnpublish(e,t){return v(this,void 0,void 0,(function*(){yield this.unsubscribe(e),e.forEach((e=>{this._subscribedList=this._subscribedList.filter((t=>t.track.getTrackId()!==e.getTrackId())),delete this._roomRes[e.getTrackId()],e.__innerDestroy(),delete this._remoteTracks[e.getTrackId()]})),this._callAppListener(t,e)}))}_callAppListener(e,...t){var r;O.info(`${e} callback ->`,...t);const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){O.error(e)}}_reTryExchange(){return v(this,void 0,void 0,(function*(){bi((()=>v(this,void 0,void 0,(function*(){var e;const{reqBody:t}=yield this._createSubscribeParams(this._subscribedList,{},!0),r=yield this._exchangeHandle(t);if(r.code!==L.SUCCESS)return O.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:s}=r.data;if(s!==L.SUCCESS)return O.error(`reTryExchange failed: ${s}`),{code:s};this._pc.clearReTryExchangeTimer();const o=this._subscribedList.filter((e=>e.track.isMCUTrack()));if(o.length>0){const t=o[0].track.getTrackId(),r=null===(e=this._roomRes[t])||void 0===e?void 0:e.msid,s=[this._roomId,"RongCloudRTC"].join("_");i.sdp=i.sdp.replace(new RegExp(r,"g"),s)}const n=yield this._pc.setRemoteAnswer(i.sdp);return n!==L.SUCCESS?{code:n}:void 0}))),"audience-retry-exchange")}))}_createSubscribeParams(e,t,r){return v(this,void 0,void 0,(function*(){const i=yield this._pc.createOffer(r),s={resolutionInfo:[]},o={min:0,max:0};Object.keys(t).forEach((e=>{const{mediaStream:r,tinyStream:n}=t[e];[r,n].forEach(((t,r)=>{var n;const a=1===r?[e,"tiny"].join("_"):e;i.sdp=null===(n=i.sdp)||void 0===n?void 0:n.replace(new RegExp(t.id,"g"),a);const c=t.getVideoTracks()[0];if(!c)return;const d=0===r,{width:_,height:u,frameRate:l}=d?ft(c):Pi;s.resolutionInfo.push({trackId:c.id,simulcast:d?Xt.NORMAL:Xt.TINY,resolution:`${_}x${u}`});const h=We(_,u),R=Qe(l);o.min+=h.minBitrate*R,o.max+=h.maxBitrate*R}))}));return{reqBody:{sdp:i,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?Xt.TINY:Xt.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:o,offer:i}}))}_subscribeHandle(e,t=!1){var s;return v(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return r.error(A.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:D.FAILED,code:L.ROOM_HAS_BEEN_DESTROYED,msg:"room destroyed"},{logSource:i.RTC}),{code:L.ROOM_HAS_BEEN_DESTROYED};if(!o("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof mt||e.track instanceof mt))),!0))return r.error(A.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};const{pc:n,pcName:a}=this._peerCManager.createPeerCList(e)[0];this._pc=n,this._pc.__reportR3R4ToPolaris(),this._pcName=a,this._pc.registerReportListener(this._reportListener),this._addPeerCEvent();const c=this._subscribedList.map((e=>Object.assign({},e))),_=e.map((e=>e instanceof mt?{track:e}:e));let u=!1;const l=[];return _.forEach((e=>{const t=e.track.getTrackId();l.push(t);const r=c.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:c.push(e),u=!0)})),u||t?(null===(s=this._polarisReport)||void 0===s||s.sendR2(gr.SUBSCRIBE,fr.BEGIN,l),r.info(A.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:D.SUCCESSED,trackIds:e.map(Gt),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:t},{logSource:i.RTC}),this._updateSubListHandle(c,!0)):(r.warn(A.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:D.FAILED,code:"",msg:"repeat subscribe"},{logSource:i.RTC}),{code:L.SUCCESS})}))}_addPeerCEvent(){this._pc.on(Ur.__INNER_EVENT_TRACK_READY__,(e=>{const t=e.streams[0].id,{track:s}=e.receiver,o=[t,"audio"===s.kind?He.AUDIO_ONLY:He.VIDEO_ONLY].join("_"),n=this._remoteTracks[o];if(!n)return void O.warn("cannot found RCRemoteTrack:",s.id);n.__innerSetMediaStreamTrack(s);const a=Qt.getMemo();r.info(A.L_QS_TRACK_READY_O,{identify:a.qualityStatusId},{logSource:i.RTC}),this._callAppListener("onTrackReady",n)}))}_getReqHeaders(){const e=this._context.getCurrentId();return{"App-Key":this._context.getAppkey(),RoomId:e,Token:this._joinResData.token,RoomType:Ir.LIVE,UserId:e,"Session-Id":this._sessionId,"Peer-Connection-Id":this._pcName,"Client-Session-Id":this._clientSessionId}}_exchangeHandle(e){return this._service.broadcastSubscribe(this._getReqHeaders(),e)}_updateSubListHandle(e,t=!1){var s;return v(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:L.ROOM_HAS_BEEN_DESTROYED};if(!o("resources",e,(()=>d(e)&&e.every((e=>e instanceof mt||e.track instanceof mt))),!0))return{code:L.PARAMS_ERROR};let n=e.map((e=>e instanceof mt?{track:e}:Object.assign({},e)));const a={};n=n.filter((e=>{const t=e.track.getTrackId();return!a[t]&&(a[t]=!0,!0)})).map((e=>Object.assign({},e)));const c=this._subscribedList.map((e=>Object.assign({},e)));if(!t){let e=!1;if(n.forEach((t=>{const r=c.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);c.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),c.length&&(e=!0),!e)return{code:L.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(n.map((e=>e.track)));const _=Qt.getMemo(),u={dur:0,cod:0,rid:this._roomId,csnid:this._clientSessionId,snid:this._sessionId,rsid:"",msa:"",msas:[],time:0,resid:"",mtp:0,smct:1,cr:"unknown",net:"unknown",uid:"",stp:0};_.qualitySubscribeReportData=u,_.subscribeData={start:Date.now()};const l={dur:0,cod:0,rid:this._roomId,csnid:this._clientSessionId,snid:this._sessionId,rsid:"",msa:"",msas:[],time:0,resid:"",mtp:0,smct:1,uid:"",stp:0};_.qualityUnsubscribeReportData=l,_.unsubscribeData={start:Date.now()},r.info(A.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_T,{trackIds:e.map(Gt),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:t},{logSource:i.RTC});const{reqBody:m}=yield this._createSubscribeParams(n,{},!1),p=yield this._exchangeHandle(m);let S=[],T=Date.now();if(_.mediaService.forEach((e=>{S.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),c.length){const e=[];c.forEach((t=>{e.push(t.track.getTrackId())})),null===(s=this._pc.reportParser)||void 0===s||s.clearLatestPacketsRecv(e)}if(p.code!==L.SUCCESS)return _.subscribeCommand&&(_.subscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualitySubscribeReportData,{dur:T-((null===(t=_.subscribeData)||void 0===t?void 0:t.start)||0),cod:p.code,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,s,i.RTC)}))),_.unsubscribeCommand&&(_.unsubscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualityUnsubscribeReportData,{dur:T-((null===(t=_.unsubscribeData)||void 0===t?void 0:t.start)||0),cod:p.code,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,s,i.RTC)}))),{code:p.code};const{sdp:C,resultCode:I,message:E,subscribedList:g}=p.data;if(I!==L.SUCCESS)return _.subscribeCommand&&(_.subscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualitySubscribeReportData,{dur:T-((null===(t=_.subscribeData)||void 0===t?void 0:t.start)||0),cod:I,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,s,i.RTC)}))),_.unsubscribeCommand&&(_.unsubscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualityUnsubscribeReportData,{dur:T-((null===(t=_.unsubscribeData)||void 0===t?void 0:t.start)||0),cod:I,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,s,i.RTC)}))),O.error("change subscribe list failed:",E,I),{code:I};n.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:i}=Lt(t.getTrackId()),s=[i,r].join("_");C.sdp=C.sdp.replace(new RegExp(e,"g"),s)}}));const f=yield this._pc.setRemoteAnswer(C.sdp);if(f!==L.SUCCESS)return _.subscribeCommand&&(_.subscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualitySubscribeReportData,{dur:T-((null===(t=_.subscribeData)||void 0===t?void 0:t.start)||0),cod:f,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,s,i.RTC)}))),_.unsubscribeCommand&&(_.unsubscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualityUnsubscribeReportData,{dur:T-((null===(t=_.unsubscribeData)||void 0===t?void 0:t.start)||0),cod:f,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,s,i.RTC)}))),{code:f};_.subscribeCommand&&(_.subscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualitySubscribeReportData,{dur:T-((null===(t=_.subscribeData)||void 0===t?void 0:t.start)||0),cod:f,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,s,i.RTC)}))),_.unsubscribeCommand&&(_.unsubscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualityUnsubscribeReportData,{dur:T-((null===(t=_.unsubscribeData)||void 0===t?void 0:t.start)||0),cod:f,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,s,i.RTC)})));const v=null==g?void 0:g.map((e=>`${e.msid}_${e.mediaType}`)),D=n.filter((e=>{if(e.track.isMCUTrack()){const t=this._roomRes[e.track.getTrackId()],r=`${t.msid}_${t.mediaType}`;return v.includes(r)}return null==v?void 0:v.includes(e.track.getTrackId())})),N=null==D?void 0:D.map((e=>`${e.track.getTrackId()}`)),b=n.filter((e=>!(null==N?void 0:N.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=D.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...D),b.length?{code:L.SUCCESS,failedList:b}:{code:L.SUCCESS}}))}_diffCDNUris(e){return v(this,void 0,void 0,(function*(){if(this._CDNUris.url&&!e.url)return this._callAppListener("onCDNInfoDisable"),void(this._CDNUris=e);(!this._CDNUris||!this._CDNUris.url&&e.url)&&this._callAppListener("onCDNInfoEnable",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`});const t=this._CDNUris.w&&e.w&&this._CDNUris.w!==e.w,r=this._CDNUris.h&&e.h&&this._CDNUris.h!==e.h,i=this._CDNUris.fps&&e.fps&&this._CDNUris.fps!==e.fps;(t||r||i)&&this._callAppListener("onCDNInfoChange",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`}),this._CDNUris=e}))}_getCDNPlayUrl(e){return v(this,void 0,void 0,(function*(){const{w:t,h:r,fps:i}=e,s=this._initOptions.pullInnerCDNProtocol||yi.FLV,o=this._initOptions.pullInnerCDNUseHttps===Ui.NOT_HTTPS?Ui.NOT_HTTPS:Ui.HTTPS;if(!this._CDNUris.url)return O.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${L.CDN_RESOURCE_IS_EMPTY}`),{code:L.CDN_RESOURCE_IS_EMPTY};const n={"App-Key":this._context.getAppkey(),Token:this._joinResData.token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},a=[],{w:c=0,h:d=1}=this._CDNUris;c/d>1?(t&&a.push(`w=${t}`),r&&a.push(`h=${r}`)):(t&&a.push(`h=${t}`),r&&a.push(`w=${r}`)),i&&a.push(`fps=${i}`),a.push(`kind=${s}`),a.push(`is_https=${o}`);const _=a.join("&");let u=`${this._CDNUris.url}?`;_&&(u+=_);const{code:l,res:h}=yield this._service.getCDNResourceInfo(n,u);return l!==L.SUCCESS?(O.error(`getCDNPlayUrl failed: ${l}`),{code:l}):(O.info(`getCDNPlayUrl success: ${null==h?void 0:h.data.pull_url}`),{code:l,CDNPlayUrl:null==h?void 0:h.data.pull_url})}))}getCDNPlayUrl(e,t){return v(this,void 0,void 0,(function*(){if(r.info(A.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_T,{resolution:e,fps:t},{logSource:i.RTC}),e&&!yt(e))return O.error("`resolution` is invalid"),r.error(A.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> resolution"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(t&&!Ut(t))return O.error("`fps` is invalid"),r.error(A.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> fps"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};const{width:s,height:o}=e?kt(e):{width:null,height:null},n=t?Pt(t):null,a={};return s&&(a.w=s),o&&(a.h=o),n&&(a.fps=n),r.info(A.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:D.SUCCESSED,resolution:e,fps:t},{logSource:i.RTC}),this._getCDNPlayUrl(a)}))}subscribe(e){return v(this,void 0,void 0,(function*(){return Qt.getMemo().subscribeCommand=!0,bi((()=>this._subscribeHandle(e,!1)),"audience-sub")}))}addSubscribeTask(e){return v(this,void 0,void 0,(function*(){return Qt.getMemo().subscribeCommand=!0,bi((()=>this._subscribeHandle(e,!1)),"audience-sub")}))}__unsubscribe(e){var t;return v(this,void 0,void 0,(function*(){if(r.info(A.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_T,{trackIds:e.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:i.RTC}),!o("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof mt))),!0))return O.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),r.error(A.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};const s=this._subscribedList.map((e=>Object.assign({},e))).filter((t=>!e.includes(t.track)));null===(t=this._polarisReport)||void 0===t||t.sendR2(gr.SUBSCRIBE,fr.END,e.map((e=>e.getTrackId()))),r.info(A.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:D.SUCCESSED,trackIds:e.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:i.RTC});return Qt.getMemo().unsubscribeCommand=!0,this._updateSubListHandle(s,!1)}))}unsubscribe(e){return v(this,void 0,void 0,(function*(){return bi((()=>this.__unsubscribe(e)),"audience-unsub")}))}addUnsubscribeTask(e){return v(this,void 0,void 0,(function*(){return bi((()=>this.__unsubscribe(e)),"audience-unsub")}))}__destroy(e){var t,r;return v(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(t=this._audioLevelReport)||void 0===t||t.clearAudioLevelReportTimer(),e&&(yield this._context.quitLivingRoomAsAudience(this._roomId)),yield this._service.broadcastExit(this._getReqHeaders()),null===(r=this._pc)||void 0===r||r.destroy(),Qt.destroy(),this._polarisReport=null,this._context.registerRTCSignalListener(void 0))}))}getRemoteTrack(e){return this._remoteTracks[e]}__getPC(){return this._peerCManager.getPCList()}getLocalTrack(e){return{}}__onReconnected(){return v(this,void 0,void 0,(function*(){const{code:e}=yield this._context.joinLivingRoomAsAudience(this._roomId,Ir.LIVE);e!==a.SUCCESS&&O.error("join living room error when on reconnected")}))}registerRoomEventListener(e){this._appListener=e}onAudioLevelChange(e,t){var s;null===(s=this._audioLevelReport)||void 0===s||s.clearAudioLevelReportTimer(),this._audioLevelReport=new Mr(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3),r.info(A.L_AUDIENCE_LIVING_ROOM_AUDIO_LEVEL_CHANGE_O,{status:D.SUCCESSED,handler:null==e?void 0:e.name,gap:t},{logSource:i.RTC})}registerReportListener(e){this._reportListener=e}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}getSessionId(){return this._sessionId}getRemoteUserIds(){return this._roomAnchorList}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getRemoteTracks(){const e=[],t=[];for(const e in this._remoteTracks){if(2===t.length)break;const r=this._remoteTracks[e];r.isMCUTrack()&&t.push(r)}return this._roomAnchorList.forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),[...t,...e]}getRemoteRTCTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()||e.push(r)}return e}getRemoteMCUTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()&&e.push(r)}return e}getCDNInfo(){return this._CDNUris.w?{resolution:`W${this._CDNUris.w}_H${this._CDNUris.h}`,fps:`FPS_${this._CDNUris.fps}`,CDNEnable:this._CDNUris.enableInnerCDN}:{CDNEnable:!1}}getClientSessionId(){return this._clientSessionId}}class xi{constructor(e){this._context=e,this._isElectron=/Electron/.test(navigator.userAgent)}_getMediaStream(e,t="getUserMedia"){return v(this,void 0,void 0,(function*(){try{const r=this.setConstraintsConfig(e),i=yield navigator.mediaDevices[t](r);return{code:L.SUCCESS,stream:i}}catch(e){if("Permission denied"===e.message)return{code:L.BROWSER_PERMISSION_DENIED};if("Permission denied by system"===e.message)return{code:L.SYSTEM_PERMISSION_DENIED};O.error(`get user media failed -> ${e.message}`)}return{code:"getUserMedia"===t?L.GET_USER_MEDIA_FAILED:L.GET_DISPLAY_MEDIA_FAILED}}))}setConstraintsConfig(e){if((null==e?void 0:e.audio)&&!this._isElectron){"boolean"==typeof e.audio&&(e.audio={});const t=navigator.mediaDevices.getSupportedConstraints();t.noiseSuppression&&(e.audio.noiseSuppression=!!t.noiseSuppression),t.autoGainControl&&(e.audio.autoGainControl=!!t.autoGainControl),t.echoCancellation&&(e.audio.echoCancellation=!!t.echoCancellation),O.info(`browser supported -> ${JSON.stringify(t)}`)}return e}createMicrophoneAudioTrack(e="RongCloudRTC",t){return v(this,void 0,void 0,(function*(){if(!It(e))return r.error(A.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS};const s=this._context.getCurrentId();if(!s)return r.error(A.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID};const{stream:o,code:n}=yield this._getMediaStream({audio:{deviceId:null==t?void 0:t.micphoneId,sampleRate:null==t?void 0:t.sampleRate}});if(n!==L.SUCCESS)return r.error(A.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:D.FAILED,code:n,msg:"Failed to get microphone audio stream"},{logSource:i.RTC}),{code:n};const a=o.getAudioTracks()[0],c=new ut(e,s,a);return r.info(A.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:D.SUCCESSED,trackId:c.getTrackId()},{logSource:i.RTC}),{code:n,track:c}}))}createCameraVideoTrack(e="RongCloudRTC",t){return v(this,void 0,void 0,(function*(){if(!It(e))return r.error(A.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS};const s=this._context.getCurrentId();if(!s)return r.error(A.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID};const o=yt(null==t?void 0:t.resolution)?t.resolution:je.W640_H480,{width:n,height:a}=kt(o),{stream:c,code:d}=yield this._getMediaStream({video:{deviceId:null==t?void 0:t.cameraId,frameRate:Pt((null==t?void 0:t.frameRate)||Ke.FPS_15),width:n,height:a,facingMode:null==t?void 0:t.faceMode}});if(d!==L.SUCCESS)return r.error(A.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"Failed to get camera video stream"},{logSource:i.RTC}),{code:d};const _=c.getVideoTracks()[0],u=new lt(e,s,_);return r.info(A.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:D.SUCCESSED,trackId:u.getTrackId()},{logSource:i.RTC}),{code:d,track:u}}))}createMicrophoneAndCameraTracks(e="RongCloudRTC",t){var s,o,n,a,c,d;return v(this,void 0,void 0,(function*(){const _=[];if(!It(e))return r.error(A.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS,tracks:_};const u=this._context.getCurrentId();if(!u)return r.error(A.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID,tracks:_};const l=yt(null===(s=null==t?void 0:t.video)||void 0===s?void 0:s.resolution)?t.video.resolution:je.W640_H480,{width:h,height:R}=kt(l),{stream:m,code:p}=yield this._getMediaStream({video:{deviceId:null===(o=null==t?void 0:t.video)||void 0===o?void 0:o.cameraId,frameRate:Pt((null===(n=null==t?void 0:t.video)||void 0===n?void 0:n.frameRate)||Ke.FPS_15),width:h,height:R,facingMode:null===(a=null==t?void 0:t.video)||void 0===a?void 0:a.faceMode},audio:{deviceId:null===(c=null==t?void 0:t.audio)||void 0===c?void 0:c.micphoneId,sampleRate:null===(d=null==t?void 0:t.audio)||void 0===d?void 0:d.sampleRate}});return p!==L.SUCCESS?(r.error(A.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:D.FAILED,code:p,msg:"Failed to get audio and video stream of camera and microphone"},{logSource:i.RTC}),{code:p,tracks:_}):(m.getTracks().forEach((t=>{"video"===t.kind?_.push(new lt(e,u,t)):_.unshift(new ut(e,u,t))})),r.info(A.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:D.SUCCESSED,trackIds:_.map((e=>e.getTrackId()))},{logSource:i.RTC}),{code:p,tracks:_})}))}createScreenVideoTrack(e="screenshare",t){return v(this,void 0,void 0,(function*(){const r=yield this._createScreenTracks(e,!1,A.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,t);return r.code===L.SUCCESS?{code:r.code,track:r.tracks[0]}:r}))}createScreenWithAudioTracks(e="screenshare",t){return v(this,void 0,void 0,(function*(){return this._createScreenTracks(e,!0,A.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_AND_AUDIO_TRACKS_O,t)}))}_createScreenTracks(e,t,s,o){var n,a;return v(this,void 0,void 0,(function*(){if(!It(e))return r.error(s,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS};const c=this._context.getCurrentId();if(!c)return r.error(s,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID};if(!wt())return r.error(A.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:D.FAILED,code:L.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:i.RTC}),{code:L.BROWSER_NOT_SUPPORT};const d=/macintosh|mac os x/i.test(navigator.userAgent);this._isElectron&&d&&t&&r.warn(s,{status:D.INFO,code:L.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO,msg:"mac in electron not support screen share with audio"});const _=(!this._isElectron||!d)&&t;if(this._isElectron&&!E(null==o?void 0:o.chromeMediaSourceId)&&!p(null==o?void 0:o.chromeMediaSourceId))return r.error(s,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> options.chromeMediaSourceId type is string"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};const u=yt(null==o?void 0:o.resolution)?o.resolution:je.W1280_H720,{width:l,height:h}=kt(u),R=this._isElectron?{mandatory:{chromeMediaSourceId:null==o?void 0:o.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:l,maxWidth:l,minHeight:h,maxHeight:h}}:{frameRate:Pt((null==o?void 0:o.frameRate)||Ke.FPS_15),width:l,height:h};!(null==o?void 0:o.chromeMediaSourceId)&&this._isElectron&&(null===(n=R.mandatory)||void 0===n||delete n.chromeMediaSourceId);let m=null;_&&this._isElectron&&(null===(a=R.mandatory)||void 0===a||delete a.chromeMediaSourceId,m={mandatory:{chromeMediaSource:"desktop"}});const{stream:S,code:T}=yield this._getMediaStream({video:R,audio:m||_},this._isElectron?"getUserMedia":"getDisplayMedia");if(T!==L.SUCCESS)return r.error(s,{status:D.FAILED,code:T,msg:"Failed to get shared screen video stream"},{logSource:i.RTC}),{code:T};const C=S.getVideoTracks()[0],I=[new ht(e,c,C)];if(_){const t=S.getAudioTracks()[0];t&&I.push(new Rt(e,c,t))}return r.info(s,{status:D.SUCCESSED,trackIds:I.map((e=>e.getTrackId()))},{logSource:i.RTC}),{code:T,tracks:I}}))}createLocalAudioTrack(e,t){return v(this,void 0,void 0,(function*(){if(!It(e))return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"audio"!==t.kind)return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"Failed to create custom stream"},{logSource:i.RTC}),{code:L.CREATE_CUSTOM_TRACK_FAILED};const s=this._context.getCurrentId();if(!s)return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID};const o=new nt(e,s,t);return r.info(A.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:D.SUCCESSED,trackId:o.getTrackId()},{logSource:i.RTC}),{code:L.SUCCESS,track:o}}))}createLocalVideoTrack(e,t){return v(this,void 0,void 0,(function*(){if(!It(e))return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"video"!==t.kind)return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:D.FAILED,code:L.CREATE_CUSTOM_TRACK_FAILED,msg:"Failed to create custom stream"},{logSource:i.RTC}),{code:L.CREATE_CUSTOM_TRACK_FAILED};const s=this._context.getCurrentId();if(!s)return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID};const o=new at(e,s,t);return r.info(A.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:D.SUCCESSED,trackId:o.getTrackId()},{logSource:i.RTC}),{code:L.SUCCESS,track:o}}))}createLocalFileTracks(e,t,s){return v(this,void 0,void 0,(function*(){if(!It(e))return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS,tracks:[]};if(!xt())return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:D.FAILED,code:L.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:i.RTC}),{code:L.BROWSER_NOT_SUPPORT,tracks:[]};const o=t instanceof File?URL.createObjectURL(t):t;if(!C(o)&&!/^blob:/.test(o))return O.warn(`createLocalFileTracks failed: params error -> url: ${o}`),r.error(A.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> file"},{logSource:i.RTC}),{code:L.PARAMS_ERROR,tracks:[]};const n=this._context.getCurrentId();return n?new Promise((t=>{const a=document.createElement("video");(null==s?void 0:s.withoutAudio)&&(a.muted=!0),a.onloadedmetadata=()=>{const c=[];let d;try{const e=a.mozCaptureStream?"mozCaptureStream":"captureStream";d=a[e]()}catch(e){O.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${o}`),O.error(e),r.error(A.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:D.FAILED,code:L.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:i.RTC}),t({code:L.CREATE_FILE_TRACK_FAILED,tracks:c})}const[_,u]=xi.getTracksWithOptions(d,s);_&&c.push(new _t(e,n,_,a)),u&&c.push(new dt(e,n,u,a)),0===c.length&&(a.pause(),a.src=""),a.onerror=null,r.info(A.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:D.SUCCESSED,trackIds:c.map((e=>e.getTrackId()))},{logSource:i.RTC}),t({code:L.SUCCESS,tracks:c})},a.onerror=()=>{O.error(`create RCLocalFileTrack failed -> url: ${o}`),r.error(A.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:D.FAILED,code:L.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:i.RTC}),t({code:L.CREATE_FILE_TRACK_FAILED,tracks:[]})},a.src=o,a.loop=!0,a.play()})):(r.error(A.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID,tracks:[]})}))}createLocalTracks(e,t,s){return v(this,void 0,void 0,(function*(){const o=[];if(!It(e))return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS,tracks:o};if(!(t instanceof MediaStream))return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> stream"},{logSource:i.RTC}),{code:L.PARAMS_ERROR,tracks:o};const n=this._context.getCurrentId();if(!n)return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID,tracks:o};const[a,c]=xi.getTracksWithOptions(t,s);return a&&o.push(new nt(e,n,a)),c&&o.push(new at(e,n,c)),r.info(A.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:D.SUCCESSED,trackIds:o.map((e=>e.getTrackId()))},{logSource:i.RTC}),{code:L.SUCCESS,tracks:o}}))}static getTracksWithOptions(e,t){const r=[];return r[0]=(null==t?void 0:t.withoutAudio)?void 0:e.getAudioTracks()[0],r[1]=(null==t?void 0:t.withoutVideo)?void 0:e.getVideoTracks()[0],r}}class wi extends xi{constructor(e,t,r){super(e),this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,Ar.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new Zt(this._runtime,this._context,this._options.mediaServer,this._options.timeout),this._context.registerConnectionStateChangeListener(this._onIMStatusChange.bind(this)),this._context.registerDisconnectListener(this._onIMDisconnect.bind(this)),this._context.registerDestroyListener(this._onIMUninit.bind(this)),this._context.registerMessageListener(this._handleMessage.bind(this)),this._context.getPluginContext().onnavidatachange=this.naviDataChange.bind(this)}_handleMessage(e){if(e.conversationType!==T.RTC_ROOM)return!1;if(this._crtRoom instanceof Ai){this._getJoinedPKRoomList().forEach((t=>{t.__parseInnerMessage(e)}))}return r.info(A.L_RTC_CLIENT_MESSAGE_O,{status:D.SUCCESSED,message:e},{logSource:i.RTC}),this._crtRoom?(this._crtRoom.__parseInnerMessage(e),!0):(r.warn(A.L_RTC_CLIENT_MESSAGE_O,{status:D.FAILED,message:"the crtRoom is empty"},{logSource:i.RTC}),!0)}naviDataChange(e){r.info(`on navi change data => ${JSON.stringify(e)}`),this._service.detectorMediaSever()}_getJoinedPKRoomList(){const{code:e,roomPKHandler:t}=this._crtRoom.getRoomPKHandler();if(e===L.SUCCESS&&t){const e=t.getJoinedPKRooms()||{};return Object.values(e)}return[]}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(e,t,s,o,n=Ir.RTC){return v(this,void 0,void 0,(function*(){if(r.info(A.L_RTC_CLIENT_JOIN_RTC_ROOM_T,{roomId:e,joinType:t,outerUserDatas:s,useMutilPeerC:o,roomType:n},{logSource:i.RTC}),this._crtRoom)return r.error(A.L_RTC_CLIENT_JOIN_RTC_ROOM_R,{status:D.FAILED,code:L.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:L.REPERT_JOIN_ROOM};const a=this._crtRoom=new Di(this._context,this._runtime,e,this._service,this._options,!1,!1,o,qt()),{code:c}=yield a.__innerInit(n,t,void 0,void 0,s);return c!==L.SUCCESS?(this._crtRoom=null,{code:c}):(a.once(di,(()=>{this._crtRoom=null})),{code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()})}))}joinCrossRTCRoom(e,t,s,o,n=Ir.CROSS_MUTI){return v(this,void 0,void 0,(function*(){if(r.info(A.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_T,{roomId:e,joinType:t,outerUserDatas:s,useMutilPeerC:o,roomType:n},{logSource:i.RTC}),this._crtRoom)return r.error(A.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_R,{status:D.FAILED,code:L.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:L.REPERT_JOIN_ROOM};const a=this._crtRoom=new Di(this._context,this._runtime,e,this._service,this._options,!1,!1,o,qt(),n),{code:c}=yield a.__innerInit(n,t,void 0,void 0,s);return c!==L.SUCCESS?(this._crtRoom=null,{code:c}):(a.once(di,(()=>{this._crtRoom=null})),{code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()})}))}joinLivingRoom(e,t,s,o,n){return v(this,void 0,void 0,(function*(){if(r.info(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_T,{roomId:e,livingType:t,joinType:s,outerUserDatas:o,useMutilPeerC:n},{logSource:i.RTC}),this._crtRoom)return r.error(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:D.FAILED,code:L.REPERT_JOIN_ROOM,msg:`Join the room repeatedly -> roomId: ${e}`},{logSource:i.RTC}),{code:L.REPERT_JOIN_ROOM};const a=this._crtRoom=new Ai(this._context,this._runtime,e,this._service,this._options,t,!1,!0,n),{code:c}=yield a.__innerInit(Ir.LIVE,s,t,void 0,o);if(c!==L.SUCCESS)return this._crtRoom=null,{code:c};a.once(di,(()=>{this._crtRoom=null}));const d={code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()};return a.__getCDNPushMode()===Ci.MANUAL&&Object.assign(d,{CDNEnable:a.__getCDNEnable()}),d}))}getAudienceClient(e){return this._audience||(this._audience=new ki(this._context,this._runtime,this._options,e)),r.info(A.L_RTC_CLIENT_GET_AUDIENCE_CLIENT_O,{status:D.SUCCESSED},{logSource:i.RTC}),this._audience}_onIMStatusChange(e){if(O.debug(`signal server connection state change: ${e}`),r.info(A.L_RTC_CLIENT_CONNECTION_STATE_S,{status:D.SUCCESSED,data:e},{logSource:i.RTC}),e===_.CONNECTED){if(this._service.detectorMediaSever(),this._crtRoom instanceof Ai){this._getJoinedPKRoomList().forEach((e=>{e.__onReconnected()}))}this._crtRoom&&this._crtRoom.__onReconnected()}}_onIMDisconnect(){r.info(A.L_RTC_CLIENT_DISCONNECT_S,{status:D.SUCCESSED},{logSource:i.RTC}),O.debug("TODO -> on IM disconnect")}_onIMUninit(){r.info(A.L_RTC_CLIENT_DESTROY_S,{status:D.SUCCESSED},{logSource:i.RTC}),O.debug("TODO -> on IM client ondestroy")}leaveRoom(e){var t,s;return v(this,void 0,void 0,(function*(){return r.info(A.L_RTC_CLIENT_LEAVE_ROOM_T,{userId:this._context.getCurrentId(),roomId:null===(t=this._crtRoom)||void 0===t?void 0:t.getRoomId()},{logSource:i.RTC}),this._crtRoom?(yield this._crtRoom.__destroy(!0),O.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),this._service.detectorMediaSever(),r.info(A.L_RTC_CLIENT_LEAVE_ROOM_R,{status:D.SUCCESSED,userId:this._context.getCurrentId(),roomId:null===(s=this._crtRoom)||void 0===s?void 0:s.getRoomId()},{logSource:i.RTC}),this._crtRoom=null,{code:L.SUCCESS}):(r.warn(A.L_RTC_CLIENT_LEAVE_ROOM_R,{status:D.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:i.RTC}),{code:L.SUCCESS})}))}joinLivingRoomAsAudience(e,t,s){return v(this,void 0,void 0,(function*(){if(r.info(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_T,{roomId:e,livingType:t,useMutilPeerC:s},{logSource:i.RTC}),this._service.detectorMediaSever(),Vt(this._context.getNaviInfo()))return r.error(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:D.FAILED,code:L.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:i.RTC}),{code:L.PACKAGE_ENVIRONMENT_ERROR};if(!o("roomId",e,m,!0)||!o("livingType",t,(e=>e===Ti.AUDIO||e===Ti.VIDEO)))return r.error(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:D.FAILED,code:L.PACKAGE_ENVIRONMENT_ERROR,msg:"params error -> roomId or livingType"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return r.error(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:D.FAILED,code:L.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:L.REPERT_JOIN_ROOM};if(!this._service.getNaviMS().length)return r.error(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:D.FAILED,code:L.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:i.RTC}),{code:L.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:n,data:c}=yield this._context.joinLivingRoomAsAudience(e,Ir.LIVE,t);if(n!==a.SUCCESS)return O.error("audienceJoinLivingRoomError:",n),r.error(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:D.FAILED,code:L.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED,msg:"signal error -> audience join room"},{logSource:i.RTC}),{code:L.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};O.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(c)}`);const d=qt();Qt.getMemo().clientData={clientSessionId:d};const _=new Mi(this._context,this._runtime,this._options,e,c,t,s,d);return this._crtAudienceLivingRoom=_,r.info(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:D.SUCCESSED,roomData:c},{logSource:i.RTC}),{room:_,code:L.SUCCESS,userIds:_.getRemoteUserIds(),RTCTracks:_.getRemoteRTCTracks(),MCUTracks:_.getRemoteMCUTracks(),CDNUris:_.getCDNInfo()}}))}leaveLivingRoomAsAudience(e){return v(this,void 0,void 0,(function*(){return r.info(A.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_T,{roomId:e.getRoomId(),userId:this._context.getCurrentId()},{logSource:i.RTC}),this._crtAudienceLivingRoom?this._crtAudienceLivingRoom!==e?(r.error(A.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> room"},{logSource:i.RTC}),{code:L.PARAMS_ERROR}):(yield this._crtAudienceLivingRoom.__destroy(!0),this._crtAudienceLivingRoom=null,r.info(A.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:D.SUCCESSED,roomId:e.getRoomId(),userId:this._context.getCurrentId()},{logSource:i.RTC}),{code:L.SUCCESS}):(r.warn(A.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:D.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:i.RTC}),{code:L.SUCCESS})}))}upgradeToAnchorRoom(e){return v(this,void 0,void 0,(function*(){if(!o("room",e,(()=>e instanceof Mi),!0))return r.error(A.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> room"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(r.info(A.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_T,{roomId:e.getRoomId(),userId:this._context.getCurrentId()},{logSource:i.RTC}),this._crtRoom)return r.error(A.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:D.FAILED,code:L.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:L.REPERT_JOIN_ROOM};const t=e.getRoomId(),s=this._crtRoom=new Ai(this._context,this._runtime,t,this._service,this._options,e.livingType,!0,!0,!1,e.getClientSessionId()),n=yield s.__innerInitByIdentityChange();return n!==a.SUCCESS?(O.warn(`change room identity failed -> code: ${n}`),this._crtRoom=null,r.error(A.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:D.FAILED,code:L.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:i.RTC}),{code:L.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):(s.once(di,(()=>{this._crtRoom=null})),yield this._crtAudienceLivingRoom.__destroy(!1),this._crtAudienceLivingRoom=null,{room:s,code:L.SUCCESS,userIds:s.getRemoteUserIds(),tracks:s.getRemoteTracks()})}))}downgradeToAudienceRoom(e){return v(this,void 0,void 0,(function*(){if(r.info(A.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_T,{roomId:e._roomId,userId:this._context.getCurrentId()},{logSource:i.RTC}),!e.isMainRoom())return O.error("the `downgradeToAudienceRoom` is disabled in PK room"),r.error(A.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:D.FAILED,code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!o("room._roomId",e._roomId,m,!0))return r.error(A.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> room._roomId"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return r.error(A.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:D.FAILED,code:L.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:L.REPERT_JOIN_ROOM};const{code:t,data:s}=yield this._context.rtcIdentityChange(e._roomId,Ei.AnchorToViewer,e.getLivingType());if(t!==a.SUCCESS)return O.error("change room identity error",t),r.error(A.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:D.FAILED,code:L.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:i.RTC}),{code:L.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};O.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(s)}`),r.info(A.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:D.SUCCESSED,roomData:s},{logSource:i.RTC});const n=e.getClientSessionId(),c=new Mi(this._context,this._runtime,this._options,e._roomId,s,e.getLivingType(),!1,n);return this._crtAudienceLivingRoom=c,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:c,code:L.SUCCESS,userIds:c.getRemoteUserIds(),RTCTracks:c.getRemoteRTCTracks(),MCUTracks:c.getRemoteMCUTracks(),CDNUris:c.getCDNInfo()}}))}getJoinedRoomInfo(){return v(this,void 0,void 0,(function*(){const{code:e,data:t}=yield this._context.getRTCJoinedUserInfo(this._context.getCurrentId());return e!==a.SUCCESS?(O.error("getJoinedUserInfo error",e),r.error(A.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:D.FAILED,code:e,msg:"Switch identity error"},{logSource:i.RTC}),{code:e}):(r.info(A.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:D.SUCCESSED,roomInfo:t},{logSource:i.RTC}),{code:L.SUCCESS,data:t})}))}reportSDKInfo(){this._context.reportSDKInfo({"plugin-rtc":"5.5.2"})}}const Bi="rtcRJoin_data",Vi="rtcRExit",$i="rtcRInfo",Fi="rtcUData",Gi="rtcUDel",Ki="rtcSetData",ji="userSetData",Hi="rtcQryData",Ji="rtcDelData",qi="rtcToken",Wi="rtcUserState",Yi="rtcUList",Qi="viewerJoinR",zi="viewerExitR",Zi="rtcPullKv",Xi="rtcIdentityChange",es="rtcInvite",ts="rtcCancelInvite",rs="rtcInviteAnswer",is="rtcEndInvite",ss="rtcQueryJoined",os="reportsdk";var ns;!function(e){e.RtcInput="RtcInput",e.RtcUserListOutput="RtcUserListOutput",e.SetUserStatusInput="SetUserStatusInput",e.RtcSetDataInput="RtcSetDataInput",e.RtcUserSetDataInput="RtcUserSetDataInput",e.RtcDataInput="RtcDataInput",e.RtcSetOutDataInput="RtcSetOutDataInput",e.MCFollowInput="MCFollowInput",e.RtcTokenOutput="RtcTokenOutput",e.RtcQryOutput="RtcQryOutput",e.RtcQryUserOutDataInput="RtcQryUserOutDataInput",e.RtcUserOutDataOutput="RtcUserOutDataOutput",e.RtcQueryListInput="RtcQueryListInput",e.RtcRoomInfoOutput="RtcRoomInfoOutput",e.RtcValueInfo="RtcValueInfo",e.RtcKeyDeleteInput="RtcKeyDeleteInput",e.RtcNotifyMsg="RtcNotifyMsg",e.RtcPullKV="RtcPullKV",e.RtcKVOutput="RtcKVOutput",e.RtcQueryUserJoinedInput="RtcQueryUserJoinedInput",e.RtcQueryUserJoinedOutput="RtcQueryUserJoinedOutput",e.RtcViewerJoinedOutput="RtcViewerJoinedOutput",e.RtcInviteInput="RtcInviteInput",e.RtcCancelInviteInput="RtcCancelInviteInput",e.RtcInviteAnswerInput="RtcInviteAnswerInput",e.RtcEndInviteInput="RtcEndInviteInput",e.RtcReportSDKInput="RtcReportSDKInput"}(ns||(ns={}));const as={[ns.RtcInput]:["roomType","broadcastType","extraInnerData","needSysChatroom","identityChangeType","joinType","innerDatas","outerDatas"],[ns.RtcUserListOutput]:["users","token","sessionId","roomInfo"],[ns.SetUserStatusInput]:["status"],[ns.RtcSetDataInput]:["interior","target","key","value","objectName","content"],[ns.RtcUserSetDataInput]:["valueInfo","objectName","content"],[ns.RtcDataInput]:["interior","target","key","objectName","content"],[ns.RtcSetOutDataInput]:["target","valueInfo","objectName","content"],[ns.MCFollowInput]:["state"],[ns.RtcTokenOutput]:["rtcToken"],[ns.RtcQryOutput]:["outInfo"],[ns.RtcQryUserOutDataInput]:["userId"],[ns.RtcUserOutDataOutput]:["user"],[ns.RtcQueryListInput]:["order"],[ns.RtcRoomInfoOutput]:["roomId","roomData","userCount","list"],[ns.RtcValueInfo]:["key","value"],[ns.RtcKeyDeleteInput]:["key"],[ns.RtcNotifyMsg]:["type","time","roomId"],[ns.RtcPullKV]:["timestamp","roomId"],[ns.RtcKVOutput]:["entries","bFullUpdate","syncTime"],[ns.RtcQueryUserJoinedInput]:["userId"],[ns.RtcQueryUserJoinedOutput]:["info"],[ns.RtcInviteInput]:["invitedUserId","timeoutTime","invitedRoomId","inviteInfo","inviteSessionId"],[ns.RtcCancelInviteInput]:["invitedUserId","invitedRoomId","inviteInfo","inviteSessionId"],[ns.RtcInviteAnswerInput]:["inviteUserId","answerCode","inviteRoomId","inviteSessionId","content","key","value"],[ns.RtcEndInviteInput]:["inviteRoomId","inviteSessionId","inviteContent","inviteRoomKeys"],[ns.RtcReportSDKInput]:["sdkInfo"]},cs=`\npackage Modules;\nmessage probuf {\n enum JoinType {\n KICK = 0; //踢前一个设备\n REFUSE = 1; //当前加入拒绝\n COEXIST = 2; //两个设备共存\n }\n enum targetType {\n ROOM =1 ;\n PERSON = 2;\n }\n message ${ns.SetUserStatusInput}\n {\n optional int32 status=1;\n }\n message ${ns.MCFollowInput}\n {\n required string state = 1;\n }\n message ${ns.RtcQueryListInput}{\n optional int32 order=1;\n }\n message ${ns.RtcKeyDeleteInput}{\n repeated string key=1;\n }\n message ${ns.RtcValueInfo}{\n required string key=1;\n required string value=2;\n }\n message RtcUserInfo{\n required string userId=1;\n repeated ${ns.RtcValueInfo} userData=2; //用户资源信息\n }\n message ${ns.RtcUserListOutput}{\n repeated RtcUserInfo users=1;\n optional string token=2;\n optional string sessionId=3;\n repeated RtcValueInfo roomInfo = 4; //房间key value\n repeated RtcKVEntity entries = 5;//直播KV属性对象集合\n optional int64 syncTime = 6;//所有属性的最大时间戳(下次拉取KV时用)。\n optional int32 offlineKickTime = 7;//server超时踢人时间,默认60s\n }\n message RtcRoomInfoOutput{\n optional string roomId = 1;\n repeated ${ns.RtcValueInfo} roomData = 2;\n optional int32 userCount = 3;\n repeated RtcUserInfo list=4;\n }\n message ${ns.RtcInput}{\n required int32 roomType=1;\n optional int32 broadcastType=2;\n optional RtcValueInfo extraInnerData = 3;\n optional bool needSysChatroom = 4; //是否需要同步聊天室\n optional IdentityChangeType identityChangeType = 5; //身份变更类型\n optional JoinType joinType = 6; // 加入房间类型\n repeated ${ns.RtcValueInfo} innerDatas = 7; //用户内部inner数据,角色或者连麦信息等\n repeated ${ns.RtcValueInfo} outerDatas = 8; //用户内部outer数据,自定义数据结构RtcInput。\n }\n message ${ns.RtcQryOutput}{\n repeated ${ns.RtcValueInfo} outInfo=1;\n }\n message ${ns.RtcDataInput}{\n required bool interior=1;\n required targetType target=2;\n repeated string key=3;\n optional string objectName=4;\n optional string content=5;\n }\n message ${ns.RtcSetDataInput}{\n required bool interior=1;\n required targetType target=2;\n required string key=3;\n required string value=4;\n optional string objectName=5;\n optional string content=6;\n }\n message ${ns.RtcUserSetDataInput} {\n repeated ${ns.RtcValueInfo} valueInfo = 1;\n required string objectName = 2;\n repeated ${ns.RtcValueInfo} content = 3;\n }\n message RtcQryInput{\n required bool isInterior=1;\n required targetType target=2;\n repeated string key=3;\n }\n message RtcDelDataInput{\n repeated string key=1;\n required bool isInterior=2;\n required targetType target=3;\n }\n message RtcOutput\n {\n optional int32 nothing=1;\n }\n message ${ns.RtcTokenOutput}{\n required string rtcToken=1;\n }\n message ${ns.RtcSetOutDataInput}{\n required targetType target=1;\n repeated ${ns.RtcValueInfo} valueInfo=2;\n optional string objectName=3;\n optional string content=4;\n }\n message ${ns.RtcQryUserOutDataInput}{\n repeated string userId = 1;\n }\n message ${ns.RtcUserOutDataOutput}{\n repeated RtcUserInfo user = 1;\n }\n message ${ns.RtcNotifyMsg} \n {\n required int32 type= 1; //(通知类型 1:rtc房间状态KV变更通知)\n optional int64 time= 2; //消息产生时间\n optional string roomId=3; //主播房间id\n }\n message ${ns.RtcPullKV}\n {\n required int64 timestamp = 1;\n required string roomId = 2;\n }\n message RtcKVEntity \n {\n required string key = 1;\n required string value = 2;\n optional int32 status = 3;\n optional int64 timestamp = 4;\n optional string uid = 5;\n }\n message ${ns.RtcKVOutput}\n {\n repeated RtcKVEntity entries = 1;\n optional bool bFullUpdate = 2;\n optional int64 syncTime = 3; \n }\n enum IdentityChangeType \n {\n AnchorToViewer = 1; //1为主播变观众\n ViewerToAnchor = 2; //2为观众变主播\n }\n message ${ns.RtcQueryUserJoinedInput}\n {\n required string userId = 1;\n }\n message RtcJoinedInfo\n {\n required string deviceId = 1; //设备ID\n required string roomId = 2; //加入的房间ID\n optional int64 joinTime = 3; //加入的时间\n }\n message ${ns.RtcQueryUserJoinedOutput}\n {\n repeated RtcJoinedInfo info = 1;\n }\n message ${ns.RtcViewerJoinedOutput}\n {\n required string rtcToken=1;\n repeated RtcKVEntity entries = 2;//KV属性对象集合\n optional int64 syncTime = 3;//所有属性的最大时间戳(下次拉取KV时用)。\n }\n message ${ns.RtcInviteInput}\n {\n required string invitedUserId=1; //被邀请的人的uid\n optional int32 timeoutTime=2; //邀请超时时间(秒),默认三十秒\n required string invitedRoomId=3; //被邀请的房间\n required string inviteInfo=4; //邀请的信息(包含邀请人,被邀请人,各自userid)客户端定义好.协议栈和server透传\n required string inviteSessionId= 5; //客户端保证唯一性(建议roomid_userid_时间戳_随机数)\n }\n message ${ns.RtcCancelInviteInput}\n {\n required string invitedUserId=1; //被邀请的人的uid\n required string invitedRoomId=2; //被邀请的房间\n required string inviteInfo=3; //取消邀请的信息(包含邀请人,被邀请人,各自userid)客户端定义好.协议栈和server透传\n required string inviteSessionId=4; //邀请的sessionId,客户端发起邀请时产生\n }\n message ${ns.RtcInviteAnswerInput}\n {\n required string inviteUserId=1; //邀请的人的uid\n required int32 answerCode=2; //是否接受连麦邀请.0为拒绝,1为接受\n required string inviteRoomId=3; //邀请的房间\n required string inviteSessionId=4; //邀请的sessionId\n required string content=5; //需要转发的content\n optional string key=6; //如果接受的话,需要加这个字段,放在room级别的k和v,新加入房间的能拉取到\n optional string value=7; //如果接受的话,需要加这个字段,放在room级别的k和v,新加入房间的能拉取到\n }\n message ${ns.RtcEndInviteInput}\n {\n required string inviteRoomId=1; //邀请的房间\n required string inviteSessionId=2; //邀请的sessionId\n required string inviteContent=3; //结束连麦的信息(需要透传给房间内其他人)\n repeated string inviteRoomKeys=4; //需要删除连麦的信息的key\n }\n message ${ns.RtcReportSDKInput} {\n required string sdkInfo=1; // 用户集成的 sdk 信息,json 格式 {"web-rtc": "4.0.3.7"}\n }\n}\n`,ds=(e,t,r,i,s,o)=>{const n=s?Object.keys(s).map((t=>e.encode(ns.RtcValueInfo,{key:t,value:s[t]},!0))):void 0,a=o?Object.keys(o).map((t=>e.encode(ns.RtcValueInfo,{key:t,value:o[t]},!0))):void 0;return e.encode(ns.RtcInput,{roomType:t,broadcastType:r,joinType:i,innerDatas:n,outerDatas:a})},_s=(e,t)=>{const r=e.decode(ns.RtcUserListOutput,t),{users:i,token:s,sessionId:o,roomInfo:n,entries:a,offlineKickTime:c}=r,d={};return g(i,(e=>{const{userId:t,userData:r}=e,i={};g(r,(e=>{const{key:t,value:r}=e;i[t]=r})),d[t]=i})),{users:d,token:s,sessionId:o,roomInfo:n,kvEntries:a,offlineKickTime:c}};class us{constructor(e,t){this.context=e,this.codec=t}joinRTCRoom(e,t,r,i,s,o){return v(this,void 0,void 0,(function*(){const n=ds(this.codec,t,r,i,s,o),{code:c,buffer:d}=yield this.context.rtcSignaling(e,Bi,!0,n);let _;return c===a.SUCCESS&&d&&(_=_s(this.codec,d)),{code:c,data:_}}))}quitRTCRoom(e){return v(this,void 0,void 0,(function*(){const t=this.codec.encode(ns.SetUserStatusInput,{status:0}),{code:r}=yield this.context.rtcSignaling(e,Vi,!0,t);return r}))}getRTCRoomInfo(e){return v(this,void 0,void 0,(function*(){const t=this.codec.encode(ns.RtcQueryListInput,{order:2}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,$i,!0,t);let s;return r===a.SUCCESS&&i&&(s=this.codec.decode(ns.RtcRoomInfoOutput,i)),{code:r,data:s}}))}getRTCUserInfoList(e){return v(this,void 0,void 0,(function*(){const t=this.codec.encode(ns.RtcQueryListInput,{order:2}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,Fi,!0,t);let s;if(r===a.SUCCESS&&i){s={users:_s(this.codec,i).users}}return{code:r,data:s}}))}getRTCUserInfo(e){throw new Error("Method not implemented.")}removeRTCUserInfo(e,t){return v(this,void 0,void 0,(function*(){const r=this.codec.encode(ns.RtcKeyDeleteInput,{key:t}),{code:i}=yield this.context.rtcSignaling(e,Gi,!1,r);return i}))}setRTCData(e,t,r,i,s,o){return v(this,void 0,void 0,(function*(){const n=this.codec.encode(ns.RtcSetDataInput,{interior:i,target:s,key:t,value:r,objectName:null==o?void 0:o.name,content:null==o?void 0:o.content}),{code:a}=yield this.context.rtcSignaling(e,Ki,!1,n);return a}))}setRTCTotalRes(e,t,r,i,s){return v(this,void 0,void 0,(function*(){const o={objectName:i,content:this.codec.encode(ns.RtcValueInfo,{key:t.name,value:t.content},!0),valueInfo:[this.codec.encode(ns.RtcValueInfo,{key:"uris",value:r},!0),this.codec.encode(ns.RtcValueInfo,{key:"mcu_uris",value:s},!0)]},n=this.codec.encode(ns.RtcUserSetDataInput,o),{code:a}=yield this.context.rtcSignaling(e,ji,!0,n);return a}))}setRTCCDNUris(e,t,r){return v(this,void 0,void 0,(function*(){const i=this.codec.encode(ns.RtcUserSetDataInput,{objectName:t,valueInfo:this.codec.encode(ns.RtcValueInfo,{key:"cdn_uris",value:r},!0)}),{code:s}=yield this.context.rtcSignaling(e,ji,!0,i);return s}))}getRTCData(e,t,r,i){return v(this,void 0,void 0,(function*(){const s=this.codec.encode(ns.RtcDataInput,{interior:r,target:i,key:t}),{code:o,buffer:n}=yield this.context.rtcSignaling(e,Hi,!0,s);if(o!==a.SUCCESS||!n)return{code:o};const{outInfo:c}=this.codec.decode(ns.RtcQryOutput,n),d={};return c.forEach((e=>{d[e.key]=e.value})),{code:o,data:d}}))}removeRTCData(e,t,r,i,s){return v(this,void 0,void 0,(function*(){const o=this.codec.encode(ns.RtcDataInput,{interior:r,target:i,key:t,objectName:null==s?void 0:s.name,content:null==s?void 0:s.content}),{code:n}=yield this.context.rtcSignaling(e,Ji,!1,o);return n}))}setRTCOutData(e,t,r,i){return v(this,void 0,void 0,(function*(){throw new Error("JSEngine's method not implemented.")}))}getRTCOutData(e,t){return v(this,void 0,void 0,(function*(){throw new Error("JSEngine's method not implemented.")}))}getRTCToken(e,t,r){return v(this,void 0,void 0,(function*(){const i=ds(this.codec,t,r),{code:s,buffer:o}=yield this.context.rtcSignaling(e,qi,!0,i);if(s!==a.SUCCESS||!o)return{code:s};const{rtcToken:n}=this.codec.decode(ns.RtcTokenOutput,o);return{code:s,data:{rtcToken:n}}}))}setRTCState(e,t){return v(this,void 0,void 0,(function*(){const r=this.codec.encode(ns.MCFollowInput,{state:t}),{code:i}=yield this.context.rtcSignaling(e,Wi,!0,r);return i}))}getRTCUserList(e){return v(this,void 0,void 0,(function*(){const t=this.codec.encode(ns.RtcQueryListInput,{order:2}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,Yi,!0,t);if(r!==a.SUCCESS||!i)return{code:r};return{code:r,data:_s(this.codec,i)}}))}joinLivingRoomAsAudience(e,t,r){var s,o;return v(this,void 0,void 0,(function*(){const n=ds(this.codec,t,r),c=Qt.getMemo(),d={dur:0,cod:0,rid:"",rtp:t,csnid:"",snid:"",time:0,cr:"unknown",net:"unknown",uid:""};c.qualityJoinRoomReportData=d,c.joinRoomData={start:Date.now()};const{code:_,buffer:u}=yield this.context.rtcSignaling(e,Qi,!0,n);if(_!==a.SUCCESS||!u)return{code:_};const{rtcToken:l,entries:m}=this.codec.decode(ns.RtcViewerJoinedOutput,u),p=Date.now(),S=JSON.stringify(Object.assign(c.qualityJoinRoomReportData,{dur:p-((null===(s=c.joinRoomData)||void 0===s?void 0:s.start)||0),cod:_,rid:e,csnid:null===(o=c.clientData)||void 0===o?void 0:o.clientSessionId,snid:Ft(e,m).sessionId,time:p,uid:this.context.getCurrentId()}));return h(R.STATISTICS,A.L_QS_JOIN_ROOM_S,S,i.RTC),{code:_,data:{token:l,kvEntries:m}}}))}quitLivingRoomAsAudience(e){return v(this,void 0,void 0,(function*(){const t=this.codec.encode(ns.SetUserStatusInput,{status:0}),{code:r}=yield this.context.rtcSignaling(e,zi,!0,t);return r}))}rtcIdentityChange(e,t,r){return v(this,void 0,void 0,(function*(){const i=this.codec.encode(ns.RtcInput,{roomType:Ir.LIVE,broadcastType:r,identityChangeType:t,needSysChatroom:!1}),{code:s,buffer:o}=yield this.context.rtcSignaling(e,Xi,!0,i);if(s!==a.SUCCESS||!o)return{code:s};return{code:s,data:_s(this.codec,o)}}))}requestRoomPK(e){return v(this,void 0,void 0,(function*(){const{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,inviteTimeout:s,inviteInfo:o,roomId:n}=e,a=this.codec.encode(ns.RtcInviteInput,{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,timeoutTime:s,inviteInfo:o}),{code:c}=yield this.context.rtcSignaling(n,es,!0,a);return c}))}cancelRoomPK(e){return v(this,void 0,void 0,(function*(){const{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,inviteInfo:s,roomId:o}=e,n=this.codec.encode(ns.RtcCancelInviteInput,{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,inviteInfo:s}),{code:a}=yield this.context.rtcSignaling(o,ts,!0,n);return a}))}responseRoomPK(e){return v(this,void 0,void 0,(function*(){const{inviteUserId:t,inviteRoomId:r,inviteSessionId:i,content:s,key:o,value:n,agree:a,roomId:c}=e,d=this.codec.encode(ns.RtcInviteAnswerInput,{inviteUserId:t,inviteRoomId:r,inviteSessionId:i,content:s,key:o,value:n,answerCode:a?1:0}),{code:_}=yield this.context.rtcSignaling(c,rs,!0,d);return _}))}endRoomPK(e){return v(this,void 0,void 0,(function*(){const{endRoomId:t,sessionId:r,content:i,keys:s,roomId:o}=e,n=this.codec.encode(ns.RtcEndInviteInput,{inviteRoomId:t,inviteSessionId:r,inviteContent:i,inviteRoomKeys:s}),{code:a}=yield this.context.rtcSignaling(o,is,!0,n);return a}))}getRTCJoinedUserInfo(e){return v(this,void 0,void 0,(function*(){const t=this.codec.encode(ns.RtcQueryUserJoinedInput,{userId:e}),{code:r,buffer:i}=yield this.context.rtcSignaling("",ss,!0,t);if(r!==a.SUCCESS||!i)return{code:r};return{code:r,data:(this.codec.decode(ns.RtcQueryUserJoinedOutput,i).info||[]).map((e=>({deviceId:e.deviceId,roomId:e.roomId,joinTime:Kt(e.joinTime)})))}}))}pullRTCRoomEntry(e){return v(this,void 0,void 0,(function*(){const t=this.codec.encode(ns.RtcPullKV,{timestamp:0,roomId:e}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,Zi,!0,t);if(r!==a.SUCCESS)return{code:r};const s=this.codec.decode(ns.RtcKVOutput,i);let{entries:o,syncTime:n}=s;return o=(o||[]).map((e=>Object.assign(Object.assign({},e),{timestamp:Kt(e.timestamp)}))),{code:r,data:{kvEntries:o,syncTime:Kt(n)}}}))}decodeRtcNotify(e){const{time:t,type:r,roomId:i}=this.codec.decode(ns.RtcNotifyMsg,e);return{time:Kt(t),type:r,roomId:i}}getCurrentId(){return this.context.getCurrentId()}getNaviInfo(){return this.context.getNaviInfo()}getConnectionStatus(){return this.context.getConnectionStatus()}getAppkey(){return this.context.getAppkey()}rtcPing(e,t,r){return this.context.rtcPing(e,t,r)}sendMessage(e,t,r){return this.context.sendMessage(e,t,r)}registerRTCSignalListener(e){this.context.registerRTCSignalListener(e)}registerConnectionStateChangeListener(e){this.context.onconnectionstatechange=e}registerDisconnectListener(e){this.context.ondisconnect=e}registerDestroyListener(e){this.context.ondestroy=e}registerMessageListener(e){this.context.onmessage=e}getCoreVersion(){return this.context.getCoreVersion()}getPluginContext(){return this.context}reportSDKInfo(e){const t=this.codec.encode(ns.RtcReportSDKInput,{sdkInfo:JSON.stringify(e)});this.context.rtcSignaling("",os,!0,t)}}const ls={tag:"RCRTC",verify:e=>"browser"!==e.tag?(O.error(`RCRTC Plugin is not support the runtime '${e.tag}'`),!1):Et?(f.add("plugin-rtc","5.5.2"),!!f.validEngine("^5.5.5-beem")||(O.error(`The current engine version '${f.getInfo().engine}' error, plugin-rtc required engine version at least '^5.5.5-beem'.`),!1)):(O.error("Please use the https protocol or use `http://localhost` to open the page!"),!1),setup(e,t,i={}){var o,n,a,c,d,_,u,l;return r.init({localLogLevel:i.logLevel,customLogPrint:i.logStdout}),r.warn(A.L_INDEX_INSTALL_RTC_PLUGIN_O,{"RCRTC Version":"5.5.2",Commit:"ea199b763d6914e0ce5b491b97eba1ee5db53d3e","browserInfo.browser":Mt.browser,"browserInfo.supportsUnifiedPlan":Mt.supportsUnifiedPlan,"browserInfo.version":Mt.version}),O.setLogLevel(i.logLevel),O.setLogStdout(i.logStdout),O.warn("RCRTC Version: 5.5.2, Commit: ea199b763d6914e0ce5b491b97eba1ee5db53d3e"),O.warn(`browserInfo.browser -> ${Mt.browser}`),O.warn(`browserInfo.supportsUnifiedPlan -> ${Mt.supportsUnifiedPlan}`),O.warn(`browserInfo.version -> ${Mt.version}`),S("options.mediaServer",i.mediaServer,(e=>!(!C(e)||"https:"===location.protocol&&!/^https/.test(e)))),S("options.timeout",i.timeout,(e=>s(e)&&e>=5e3&&e<=3e4)),S("options.pingGap",i.pingGap,(e=>s(e)&&e>=3e3&&e<=1e4)),(null==i?void 0:i.audio)&&((null===(o=i.audio)||void 0===o?void 0:o.workletModule)&&(st.workletModule=null===(n=i.audio)||void 0===n?void 0:n.workletModule),(null===(a=i.audio)||void 0===a?void 0:a.workletWasm)&&(st.workletWasm=null===(c=i.audio)||void 0===c?void 0:c.workletWasm),(null===(d=i.audio)||void 0===d?void 0:d.workletModule)&&(null===(_=i.audio)||void 0===_?void 0:_.workletWasm)&&(st.isOpen=!0),void 0!==(null===(u=i.audio)||void 0===u?void 0:u.isOpen)&&(st.isOpen=null===(l=i.audio)||void 0===l?void 0:l.isOpen)),new wi(new us(e,e.createCodec(as,cs)),t,i)}},hs={DEFAULT:"RongCloudRTC"},Rs={transResolution:kt,transFrameRate:Pt,parseTrackId:Lt,ifSupportLocalFileTrack:xt,ifSupportScreenShare:wt};export{li as BackgroundPictureFillMode,hi as MixLayoutMode,Ri as MixVideoRenderMode,_i as RCAbstractRoom,ki as RCAudienceClient,Mi as RCAudienceLivingRoom,Xe as RCAudioBitrate,lt as RCCameraVideoTrack,Ke as RCFrameRate,Ui as RCInnerCDNPullIsHttps,yi as RCInnerCDNPullKind,Lr as RCKickReason,Ai as RCLivingRoom,Ti as RCLivingType,nt as RCLocalAudioTrack,_t as RCLocalFileAudioTrack,ct as RCLocalFileTrack,dt as RCLocalFileVideoTrack,ot as RCLocalTrack,at as RCLocalVideoTrack,Si as RCMCUConfigBuilder,xi as RCMediaStreamCapture,He as RCMediaType,ut as RCMicphoneAudioTrack,wi as RCRTCClient,L as RCRTCCode,mr as RCRTCLiveRole,Ht as RCRTCPingResult,Di as RCRTCRoom,pt as RCRemoteAudioTrack,mt as RCRemoteTrack,St as RCRemoteVideoTrack,je as RCResolution,Rt as RCScreenAudioTrack,ht as RCScreenVideoTrack,hs as RCTag,et as RCTrack,rt as RCVideoBitrate,Er as RTCJoinType,ze as device,Rs as helper,ls as installer};
|
|
15
|
+
***************************************************************************** */function v(e,t,r,i){return new(r||(r=Promise))((function(s,o){function n(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,a)}c((i=i.apply(e,t||[])).next())}))}const O=new e("RCRTC");var L,A,D;!function(e){e[e.SUCCESS=1e4]="SUCCESS",e[e.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",e[e.PARAMS_ERROR=50001]="PARAMS_ERROR",e[e.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",e[e.NOT_IN_ROOM=50003]="NOT_IN_ROOM",e[e.SERVICE_INVALID=50004]="SERVICE_INVALID",e[e.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",e[e.SIGNAL_ERROR=53001]="SIGNAL_ERROR",e[e.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",e[e.REQUEST_FAILED=53004]="REQUEST_FAILED",e[e.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",e[e.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",e[e.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",e[e.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",e[e.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",e[e.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",e[e.BROWSER_PERMISSION_DENIED=53012]="BROWSER_PERMISSION_DENIED",e[e.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",e[e.INVALID_TAGS=53014]="INVALID_TAGS",e[e.INVALID_USER_ID=53015]="INVALID_USER_ID",e[e.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",e[e.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",e[e.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",e[e.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",e[e.TRACK_NOT_READY=53020]="TRACK_NOT_READY",e[e.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",e[e.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",e[e.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",e[e.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",e[e.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",e[e.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",e[e.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",e[e.SIGNAL_JOIN_RTC_ROOM_REFUSED=53028]="SIGNAL_JOIN_RTC_ROOM_REFUSED",e[e.NO_PERMISSION_TO_USE_REQUESTED_DEVICE=53029]="NO_PERMISSION_TO_USE_REQUESTED_DEVICE",e[e.THE_FUNCTION_IS_DISABLED_IN_PKROOM=53030]="THE_FUNCTION_IS_DISABLED_IN_PKROOM",e[e.SOME_TRACKS_PUBLISH_FAILED=53031]="SOME_TRACKS_PUBLISH_FAILED",e[e.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO=53032]="MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO",e[e.JWT_TIME_OUT=1004]="JWT_TIME_OUT",e[e.SYSTEM_PERMISSION_DENIED=53033]="SYSTEM_PERMISSION_DENIED",e[e.PUBLISH_TRACKS_IS_INVALID=53034]="PUBLISH_TRACKS_IS_INVALID"}(L||(L={})),function(e){e.L_INDEX_INSTALL_RTC_PLUGIN_O="L-index_install_rtc_plugin-O",e.L_RTC_CLIENT_CONNECTION_STATE_S="L-rtc_client_connection_state-S",e.L_RTC_CLIENT_DISCONNECT_S="L-rtc_client_disconnect-S",e.L_RTC_CLIENT_MESSAGE_O="L-rtc_client_message-O",e.L_RTC_CLIENT_DESTROY_S="L-rtc_client_destroy-S",e.L_RTC_CLIENT_JOIN_RTC_ROOM_T="L-rtc_client_join_rtc_room-T",e.L_RTC_CLIENT_JOIN_RTC_ROOM_R="L-rtc_client_join_rtc_room-R",e.L_RTC_CLIENT_JOIN_LIVING_ROOM_T="L-rtc_client_join_living_room-T",e.L_RTC_CLIENT_JOIN_LIVING_ROOM_R="L-rtc_client_join_living_room-R",e.L_RTC_CLIENT_GET_AUDIENCE_CLIENT_O="L-rtc_client_get_audience_client-O",e.L_RTC_CLIENT_LEAVE_ROOM_T="L-rtc_client_leave_room-T",e.L_RTC_CLIENT_LEAVE_ROOM_R="L-rtc_client_leave-room-R",e.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O="L-rtc_client_create_microphone_audio_track-O",e.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O="L-rtc_client_create_camera_video_track-O",e.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O="L-rtc_client_create_microphone_and_camera_tracks-O",e.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O="L-rtc_client_create_screen_video_track-O",e.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_AND_AUDIO_TRACKS_O="L-rtc_client_create_screen_video_and_audio_tracks-O",e.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O="L-rtc_client_create_local_audio_track-O",e.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O="L-rtc_client_create_local_video_track-O",e.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O="L-rtc_client_create_local_file_tracks-O",e.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O="L-rtc_client_create_local_tracks-O",e.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_T="L-rtc_client_join_living_room_as_audience-T",e.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R="L-tcclient_join_living_room_as_audience_R",e.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_T="L-rtc_client_leave_living_room_as_audience-T",e.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R="L-rtc_client_leave_living_room_as_audience-R",e.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_T="L-rtc_client_upgrade_to_anchor_room-T",e.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R="L-rtc_client_upgrade_to_anchor_room-R",e.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_T="L-rtc_client_downgrade_to_audience_room-T",e.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R="L-rtc_client_downgrade_to_audience_room-R",e.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O="L-rtc_client_get_joined_room_info-O",e.L_AUDIENCE_CLIENT_SUBSCRIBE_T="L-audinence_client_subscribe-T",e.L_AUDIENCE_CLIENT_SUBSCRIBE_R="L-audinence_client_subscribe-R",e.L_AUDIENCE_CLIENT_UNSUBSCRIBE_T="L-audinence_client_unsubscribe-T",e.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R="L-audinence_client_unsubscribe-R",e.L_PINGER_START_O="L-pinger_start-O",e.L_PINGER_STOP_O="L-pinger_stop-O",e.L_PINGER_SEND_RTCPING_T="L-pinger_send_rtcping-T",e.L_PINGER_SEND_RTCPING_R="L-pinger_send_rtcping-R",e.L_ABSTRACT_ROOM_SEND_MESSAGE_T="L-abstract_room_send_message-T",e.L_ABSTRACT_ROOM_SEND_MESSAGE_R="L-abstract_room_send_message-R",e.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_T="L-abstract_room_set_room_attribute-T",e.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R="L-abstract_room_set_room_attribute_R",e.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_T="L-abstract_room_delete_room_attribute_T",e.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R="L-abstract_room_delete_room_attribute_R",e.L_ABSTRACT_ROOM_PUBLISH_T="L-abstract_room_publish-T",e.L_ABSTRACT_ROOM_PUBLISH_R="L-abstract_room_publish-R",e.L_ABSTRACT_ROOM_UNPUBLISH_T="L-abstract_room_unpublish-T",e.L_ABSTRACT_ROOM_UNPUBLISH_R="L-abstract_room_unpublish-R",e.L_ABSTRACT_ROOM_SUBSCRIBE_T="L-abstract_room_subscribe-T",e.L_ABSTRACT_ROOM_SUBSCRIBE_R="L-abstract_room_subscribe-R",e.L_ABSTRACT_ROOM_UNSUBSCRIBE_T="L-abstract_room_unsubscribe-T",e.L_ABSTRACT_ROOM_UNSUBSCRIBE_R="L-abstract_room_unsubscribe-R",e.L_ABSTRACT_ROOM_REGISTER_ROOM_EVENT_LISTENER_O="L-abstract_room_register_room_event_listener-O",e.L_ABSTRACT_ROOM_REGISTER_REPORT_LISTENER_O="L-abstract_room_register_report_listener-O",e.L_ABSTRACT_ROOM_AUDIO_LEVEL_O="L-abstract_room_audio_level-O",e.L_ABSTRACT_ROOM_RECONNECTED_T="L-abstract_room_reconnected-T",e.L_ABSTRACT_ROOM_RECONNECTED_R="L-abstract_room_reconnected-R",e.L_ABSTRACT_ROOM_CALL_APP_LISTENER_O="L-abstract_room_call_app_listener-O",e.L_LIVING_ROOM_RECONNECTED_T="L-living_room_reconnected-T",e.L_LIVING_ROOM_RECONNECTED_R="L-living_room_reconnected-R",e.L_LIVING_ROOM_ENABLE_INNER_CDN_T="L-living_room_enable_inner_cdn-T",e.L_LIVING_ROOM_ENABLE_INNER_CDN_R="L-living_room_enable_inner_cdn-R",e.L_LIVING_ROOM_SPREAD_CDN_INFO_T="L-living_room_spread_cdn_info-T",e.L_LIVING_ROOM_SPREAD_CDN_INFO_R="L-living_room_spread_cdn_info-R",e.L_LIVING_ROOM_JOINED_PK_ROOM_T="L-living_room_joined_pk_room-T",e.L_LIVING_ROOM_JOINED_PK_ROOM_R="L-living_room_joined_pk_room-R",e.L_LIVING_ROOM_LEAVE_PK_ROOM_T="L-living_room_leave_pk_room-T",e.L_LIVING_ROOM_LEAVE_PK_ROOM_R="L-living_room_leave_pk_room-R",e.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O="L-living_room_get_room_pk_handler-O",e.L_LIVING_ROOM_QUIT_ALL_PK_ROOM_O="L-living_room_quit_all_pk_room-O",e.L_LIVING_PK_HANDLER_REGISTER_ROOM_PK_EVENT_LISTENER_O="L-living_pk_handler_register_room_pk_event_listener-O",e.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_T="L-living_pk_handler_request_join_other_room-T",e.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R="L-living_pk_handler_request_join_other_room-R",e.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_T="L-living_pk_handler_cancel_request_join_other_room-T",e.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R="L-living_pk_handler_cancel_request_join_other_room-R",e.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_T="L-living_pk_handler_response_join_other_room-T",e.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R="L-living_pk_handler_response_join_other_room-R",e.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_T="L-living_pk_handler_join_other_room-T",e.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R="L-living_pk_handler_join_other_room-R",e.L_LIVING_PK_HANDLER_LEAVE_OTHER_ROOM_T="L-living_pk_handler_leave_other_room-T",e.L_LIVING_PK_HANDLER_LEAVE_OTHER_ROOM_R="L-living_pk_handler_leave_other_room-R",e.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_T="L-audience_living_room_singal_data_change-T",e.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R="L-audience_living_room_singal_data_change-R",e.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_T="L-audience_living_room_get_cdn_play_url-T",e.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R="L-audience_living_room_get_cdn_play_url-R",e.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_T="L-audience_living_room_subscribe-T",e.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R="L-audience_living_room_subscribe-R",e.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_T="L-audience_living_room_unsubscribe-T",e.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R="L-audience_living_room_unsubscribe-R",e.L_AUDIENCE_LIVING_ROOM_AUDIO_LEVEL_CHANGE_O="L-audience_living_room_audio_level_change-O",e.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O="L-mcu_config_builder_set_host_video_track-O",e.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O="L-mcu_config_builder_set_mix_layout_mode-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O="L-mcu_config_builder_set_output_video_resolution-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O="L-mcu_config_builder_set_output_video_fps-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O="L-mcu_config_builder_set_output_video_bitrate-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O="L-mcu_config_builder_set_output_tiny_video_resolution-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O="L-mcu_config_builder_set_output_tiny_video_fps-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O="L-mcu_config_builder_set_output_tiny_video_bitrate-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O="L-mcu_config_builder_set_output_video_render_mode-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O="L-mcu_config_builder_set_output_audio_bitrate-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O="L-mcu_config_builder_set_output_background_color-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O="L-mcu_config_builder_add_output_background_picture-O",e.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O="L-mcu_config_builder_remove_output_background_picture-O",e.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O="L-mcu_config_builder_clear_output_background_picture-O",e.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O="L-mcu_config_builder_set_output_background_picture-fill-mode-O",e.L_MCU_CONFIG_BUILDER_ADD_PUBLISH_STREAM_URLS_O="L-mcu_config_builder_add_publish_stream_urls-O",e.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O="L-mcu_config_builder_remove_publish_stream_urls-O",e.L_MCU_CONFIG_BUILDER_CLEAR_PUBLISH_STREAM_URLS_O="L-mcu_config_builder_clear_publish_stream_urls-O",e.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O="L-mcu_config_builder_add_customize_layout_video-O",e.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O="L-mcu_config_builder_remove_customize_layout_video-O",e.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_LAYOUT_VIDEO_O="L-mcu_config_builder_clear_customize_layout_video-O",e.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O="L-mcu_config_builder_set_customize_input_audio-O",e.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O="L-mcu_config_builder_add_customize_input_audio-O",e.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O="L-mcu_config_builder_remove_customize_input_audio-O",e.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_INPUT_AUDIO_O="L-mcu_config_builder_clear_customize_input_audio-O",e.L_MCU_CONFIG_BUILDER_RESET_O="L-mcu_config_builder_reset-O",e.L_MCU_CONFIG_BUILDER_FLUSH_O="L-mcu_config_builder_flush-O",e.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O="L-mcu_config_builder_add_single_water_mark-O",e.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O="L-mcu_config_builder_remove_single_water_mark-O",e.L_MCU_CONFIG_BUILDER_CLEAR_SINGLE_WATER_MARK_O="L-mcu_config_builder_clear_single_water_mark-O",e.L_MEDIA_SERVICE_SET_MCU_CONFIG_T="L-media_service_set_mcu_config-T",e.L_MEDIA_SERVICE_SET_MCU_CONFIG_R="L-media_service_set_mcu_config-R",e.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_T="L-media_service_get_cnd_resource_info-T",e.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R="L-media_service_get_cnd_resource_info-R",e.L_MEDIA_SERVICE_REQUEST_T="L-media_service_request-T",e.L_MEDIA_SERVICE_REQUEST_R="L-media_service_request-R",e.L_LOCAL_TRACK_INNER_SET_PUBLISHED_O="L-loacl_track_inner_set_published-O",e.L_LOCAL_TRACK_DESTROY_O="L-loacl_track_destroy-O",e.L_LOCAL_TRACK_SET_BITRATE_O="L-loacl_track_set_bitrate-O",e.L_LOCAL_TRACK_SET_LOCAL_MUTED_O="L-loacl_track_set_local_muted-O",e.L_TRACK_PLAY_T="L-track_play-T",e.L_TRACK_PLAY_R="L-track_play-R",e.L_TRACK_MUTE_O="L-track_mute-O",e.L_TRACK_UNMUTE_O="L-track_unmute-O",e.L_REMOTE_TRACK_INNER_SET_SUBSCRIBED_O="L-remote_track_inner_set_subscribed-O",e.L_ABSTRACT_STAT_PARSER_FORMAT_RTC_STATE_REPORT_O="L-abstract_stat_parser_format_rtc_state_report-O",e.L_A_SDP_STRATEGY_SET_SDP_SEMANTICS_O="L-a_sdp_strategy_set_sdp_semantics-O",e.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O="L-a_sdp_strategy_set_remote_answer-O",e.L_RTC_PEER_CONNECTION_GET_STATS_DATA_O="L-rtc_peer_connection_get_stats_data-O",e.L_RTC_PEER_CONNECTION_ADD_LOCAL_TRACK_O="L-rtc_peer_connection_add_local_track-O",e.L_RTC_PEER_CONNECTION_GET_LOCAL_TRACKS_O="L-rtc_peer_connection_get_local_tracks-O",e.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S="L-rtc_peer_connection_ice_connection_state-S",e.L_RTC_PEER_CONNECTION_CONNECTION_STATE_S="L-rtc_peer_connection_connection_state-S",e.L_RTC_PEER_CONNECTION_SET_BITRATE_O="L-rtc_peer_connection_set_bitrate-O",e.L_RTC_PEER_CONNECTION_CREATE_OFFER_O="L-rtc_peer_connection_create_offer-O",e.L_RTC_PEER_CONNECTION_SET_REMOTE_ANSWER_O="L-rtc_peer_connection_set_remote_answer-O",e.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O="L-rtc_peer_connection_remove_local_track_by_id-O",e.L_RTC_PEER_CONNECTION_REMOVE_ALL_LOCAL_TRACK_O="L-rtc_peer_connection_remove_all_local_track-O",e.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_O="L-rtc_peer_connection_remove_local_track-O",e.L_RTC_PEER_CONNECTION_UPDATE_SUB_REMOTE_TRACKS_O="L-rtc_peer_connection_update_sub_remote_tracks-O",e.L_RTC_PEER_CONNECTION_LOCAL_TRACK_MUTED_O="L-rtc_peer_connection_local_track_muted-O",e.L_RTC_PEER_CONNECTION_DESTROY_O="L-rtc_peer_connection_destroy-O",e.L_RTC_SET_RECOMMEND_BITRATE_O="L_rtc_set_recommend_bitrate_O",e.L_RTC_SDP_BITRATE_O="L_rtc_sdp_bitrate_O",e.L_RTC_3ANOISE_NODE_O="L_RTC_AAAnoiseNode_O",e.L_RTC_3ANOISE_NODE_E="L_RTC_AAAnoiseNode_E",e.L_RTC_3ANOISE_NODE_STOP_O="L_RTC_AAAnoiseNode_Stop_O",e.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_T="L_rtc_client_join_cross_rtc_room_T",e.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_R="L_rtc_client_join_cross_rtc_room_R",e.L_QS_CREATE_OFFER_O="L-qs_create_offer-O",e.L_QS_PUBLISH_EXCHANGE_O="L-qs_publish_exchange-O",e.L_QS_SUBSCRIBE_EXCHANGE_O="L-qs_subscribe_exchange-O",e.L_QS_GET_ANSWER_O="L-qs_get_answer-O",e.L_QS_SET_LOCAL_DESCRIPTION_O="L-qs_set_local_description-O",e.L_QS_GET_RESOURCES_O="L-qs_get_resources-O",e.L_QS_TRACK_READY_O="L-qs_track_ready-O",e.L_QS_JOIN_ROOM_S="RTC-joinRoomRtc-S",e.L_QS_SUBSCRIBE_S="RTC-subscribe-S",e.L_QS_UNSUBSCRIBE_S="RTC-unsubscribe-S",e.L_QS_PUBLISH_S="RTC-publishRtc-S",e.L_QS_UNPUBLISH_S="RTC-unpublishRtc-S",e.L_QS_ICE_STATUS_S="RTC-iceStatus-S",e.L_QS_KICKED_S="RTC-forcedOffline-S",e.L_QS_PUB_ICE_STATUS_S="RTC-pubIceConnected-S",e.L_QS_SUB_ICE_STATUS_S="RTC-subIceConnected-S",e.L_QS_RECV_PUB_MSG_S="RTC-recvPubMsg-S"}(A||(A={})),function(e){e.FAILED="fail",e.SUCCESSED="success",e.TIMEOUT="timeout",e.INFO="info"}(D||(D={}));let N=!0,b=!0;function k(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function y(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return s.apply(this,arguments);const o=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),s.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(r))return o.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"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 U(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(N=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function P(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(b=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function M(){if("object"==typeof window){if(N)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function x(e,t){b&&console.warn(e+" is deprecated, please use "+t+" instead.")}function w(e){return"[object Object]"===Object.prototype.toString.call(e)}function B(e){return w(e)?Object.keys(e).reduce((function(t,r){const i=w(e[r]),s=i?B(e[r]):e[r],o=i&&!Object.keys(s).length;return void 0===s||o?t:Object.assign(t,{[r]:s})}),{}):e}function V(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?V(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{V(e,e.get(t),r)}))})))}function $(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&V(e,r,s)}))})),s}const F=M;function G(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[s("min",r)]=i.ideal,t.optional.push(e),e={},e[s("max",r)]=i.ideal,t.optional.push(e)):(e[s("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const n=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||n)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{let n=(r=r.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!n&&r.length&&t.includes("back")&&(n=r[r.length-1]),n&&(e.video.deviceId=o.exact?{exact:n.deviceId}:{ideal:n.deviceId}),e.video=i(e.video),F("chrome: "+JSON.stringify(e)),s(e)}))}e.video=i(e.video)}return F("chrome: "+JSON.stringify(e)),s(e)},o=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(r.getUserMedia=function(e,t,i){s(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(o(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return s(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(o(e))))))}}}function K(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function j(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",(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const s=new Event("track");s.track=r.track,s.receiver=i,s.transceiver={receiver:i},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const s=new Event("track");s.track=r,s.receiver=i,s.transceiver={receiver:i},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else y(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function H(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 r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let s=r.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.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 J(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,i]=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 s=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const i=function(e){r(o(s(e)))};return t.apply(this,[i,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(o(s(t)))},r])})).then(r,i)}}function q(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 r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>$(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}),y(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>$(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,r,i;return this.getSenders().forEach((r=>{r.track===e&&(t?i=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?i=!0:r=t),t.track===e))),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function W(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,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=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();r.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function Y(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return W(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=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 r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],s=e._streams[i.id];r=r.replace(new RegExp(s.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function n(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],s=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.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,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[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 s=this.getSenders().find((e=>e.track===t));if(s)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[r.id];if(o)o.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=o(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=n(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:o(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((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Q(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function z(e,t){y(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var Z=Object.freeze({__proto__:null,shimMediaStream:K,shimOnTrack:j,shimGetSendersWithDtmf:H,shimGetStats:J,shimSenderReceiverGetStats:q,shimAddTrackRemoveTrackWithNative:W,shimAddTrackRemoveTrack:Y,shimPeerConnection:Q,fixNegotiationNeeded:z,shimGetUserMedia:G,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const i=r.video&&r.video.width,s=r.video&&r.video.height,o=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},i&&(r.video.mandatory.maxWidth=i),s&&(r.video.mandatory.maxHeight=s),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});var X,ee,te=(X=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 r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){var r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((function(e){return 0===e.indexOf(r)}))},t.parseCandidate=function(e){for(var t,r={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]},i=8;i<t.length;i+=2)switch(t[i]){case"raddr":r.relatedAddress=t[i+1];break;case"rport":r.relatedPort=parseInt(t[i+1],10);break;case"tcptype":r.tcpType=t[i+1];break;case"ufrag":r.ufrag=t[i+1],r.usernameFragment=t[i+1];break;default:r[t[i]]=t[i+1]}return r},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 r=e.type;return t.push("typ"),t.push(r),"host"!==r&&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(" "),r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\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,r={},i=e.substr(e.indexOf(" ")+1).split(";"),s=0;s<i.length;s++)r[(t=i[s].trim().split("="))[0].trim()]=t[1];return r},t.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var i=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.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="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r},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 r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substr(6)},t.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){var r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},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,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){var i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],s=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&s?{usernameFragment:i.substr(12),password:s.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 r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" "),s=3;s<i.length;s++){var o=i[s],n=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(n){var a=t.parseRtpMap(n),c=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(a.parameters=c.length?t.parseFmtp(c[0]):{},a.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),r.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(a.name.toUpperCase())}}}return t.matchPrefix(e,"a=extmap:").forEach((function(e){r.headerExtensions.push(t.parseExtmap(e))})),r},t.writeRtpDescription=function(e,r){var i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" UDP/TLS/RTP/SAVPF ",i+=r.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((function(e){i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));var s=0;return r.codecs.forEach((function(e){e.maxptime>s&&(s=e.maxptime)})),s>0&&(i+="a=maxptime:"+s+"\r\n"),i+="a=rtcp-mux\r\n",r.headerExtensions&&r.headerExtensions.forEach((function(e){i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){var r,i=[],s=t.parseRtpParameters(e),o=-1!==s.fecMechanisms.indexOf("RED"),n=-1!==s.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,d=t.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));d.length>0&&d[0].length>1&&d[0][0]===c&&(r=d[0][1]),s.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&r&&(t.rtx={ssrc:r}),i.push(t),o&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:n?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&c&&i.push({ssrc:c});var _=t.matchPrefix(e,"b=");return _.length&&(_=0===_[0].indexOf("b=TIAS:")?parseInt(_[0].substr(7),10):0===_[0].indexOf("b=AS:")?1e3*parseInt(_[0].substr(5),10)*.95-16e3:void 0,i.forEach((function(e){e.maxBitrate=_}))),i},t.parseRtcpParameters=function(e){var r={},i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);var s=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=s.length>0,r.compound=0===s.length;var o=t.matchPrefix(e,"a=rtcp-mux");return r.mux=o.length>0,r},t.parseMsid=function(e){var r,i=t.matchPrefix(e,"a=msid:");if(1===i.length)return{stream:(r=i[0].substr(7).split(" "))[0],track:r[1]};var s=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return s.length>0?{stream:(r=s[0].value.split(" "))[0],track:r[1]}:void 0},t.parseSctpDescription=function(e){var r,i=t.parseMLine(e),s=t.matchPrefix(e,"a=max-message-size:");s.length>0&&(r=parseInt(s[0].substr(19),10)),isNaN(r)&&(r=65536);var o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substr(12),10),protocol:i.fmt,maxMessageSize:r};if(t.matchPrefix(e,"a=sctpmap:").length>0){var n=t.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(n[0],10),protocol:n[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){var r=[];return r="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&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,r,i){var s=void 0!==r?r:2;return"v=0\r\no="+(i||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,r,i,s){var o=t.writeRtpDescription(e.kind,r);if(o+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),o+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===i?"actpass":"active"),o+="a=mid:"+e.mid+"\r\n",e.direction?o+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?o+="a=sendrecv\r\n":e.rtpSender?o+="a=sendonly\r\n":e.rtpReceiver?o+="a=recvonly\r\n":o+="a=inactive\r\n",e.rtpSender){var n="msid:"+s.id+" "+e.rtpSender.track.id+"\r\n";o+="a="+n,o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+n,e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+n,o+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+t.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+t.localCName+"\r\n"),o},t.getDirection=function(e,r){for(var i=t.splitLines(e),s=0;s<i.length;s++)switch(i[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[s].substr(2)}return r?t.getDirection(r):"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 r=t.splitLines(e)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){var r=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var r=t.splitLines(e),i=0;i<r.length;i++)if(r[i].length<2||"="!==r[i].charAt(1))return!1;return!0},e.exports=t},X(ee={exports:{}},ee.exports),ee.exports);function re(e,t,r,i,s){var o=te.writeRtpDescription(e.kind,t);if(o+=te.writeIceParameters(e.iceGatherer.getLocalParameters()),o+=te.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":s||"active"),o+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?o+="a=sendrecv\r\n":e.rtpSender?o+="a=sendonly\r\n":e.rtpReceiver?o+="a=recvonly\r\n":o+="a=inactive\r\n",e.rtpSender){var n=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=n;var a="msid:"+(i?i.id:"-")+" "+n+"\r\n";o+="a="+a,o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,o+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+te.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+te.localCName+"\r\n"),o}function ie(e,t){var r={codecs:[],headerExtensions:[],fecMechanisms:[]},i=function(e,t){e=parseInt(e,10);for(var r=0;r<t.length;r++)if(t[r].payloadType===e||t[r].preferredPayloadType===e)return t[r]},s=function(e,t,r,s){var o=i(e.parameters.apt,r),n=i(t.parameters.apt,s);return o&&n&&o.name.toLowerCase()===n.name.toLowerCase()};return e.codecs.forEach((function(i){for(var o=0;o<t.codecs.length;o++){var n=t.codecs[o];if(i.name.toLowerCase()===n.name.toLowerCase()&&i.clockRate===n.clockRate){if("rtx"===i.name.toLowerCase()&&i.parameters&&n.parameters.apt&&!s(i,n,e.codecs,t.codecs))continue;(n=JSON.parse(JSON.stringify(n))).numChannels=Math.min(i.numChannels,n.numChannels),r.codecs.push(n),n.rtcpFeedback=n.rtcpFeedback.filter((function(e){for(var t=0;t<i.rtcpFeedback.length;t++)if(i.rtcpFeedback[t].type===e.type&&i.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var i=0;i<t.headerExtensions.length;i++){var s=t.headerExtensions[i];if(e.uri===s.uri){r.headerExtensions.push(s);break}}})),r}function se(e,t,r){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(r)}function oe(e,t){var r=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 r||e.addRemoteCandidate(t),!r}function ne(e,t){var r=new Error(t);return r.name=e,r.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[e],r}var ae=function(e,t){function r(t,r){r.addTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function i(t,r,i,s){var o=new Event("track");o.track=r,o.receiver=i,o.transceiver={receiver:i},o.streams=s,e.setTimeout((function(){t._dispatchEvent("track",o)}))}var s=function(r){var i=this,s=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){i[e]=s[e].bind(s)})),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",r=JSON.parse(JSON.stringify(r||{})),this.usingBundle="max-bundle"===r.bundlePolicy,"negotiate"===r.rtcpMuxPolicy)throw ne("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var i=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var s="string"==typeof i;return s&&(i=[i]),i=i.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||r?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(r=!0,!0)})),delete e.url,e.urls=s?i[0]:i,!!i.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var o=r.iceCandidatePoolSize;o>0;o--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=te.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(s.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(s.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),s.prototype.onicecandidate=null,s.prototype.onaddstream=null,s.prototype.ontrack=null,s.prototype.onremovestream=null,s.prototype.onsignalingstatechange=null,s.prototype.oniceconnectionstatechange=null,s.prototype.onconnectionstatechange=null,s.prototype.onicegatheringstatechange=null,s.prototype.onnegotiationneeded=null,s.prototype.ondatachannel=null,s.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},s.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},s.prototype.getConfiguration=function(){return this._config},s.prototype.getLocalStreams=function(){return this.localStreams},s.prototype.getRemoteStreams=function(){return this.remoteStreams},s.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,i={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&&r)i.iceTransport=this.transceivers[0].iceTransport,i.dtlsTransport=this.transceivers[0].dtlsTransport;else{var s=this._createIceAndDtlsTransports();i.iceTransport=s.iceTransport,i.dtlsTransport=s.dtlsTransport}return t||this.transceivers.push(i),i},s.prototype.addTrack=function(t,r){if(this._isClosed)throw ne("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var i;if(this.transceivers.find((function(e){return e.track===t})))throw ne("InvalidAccessError","Track already exists.");for(var s=0;s<this.transceivers.length;s++)this.transceivers[s].track||this.transceivers[s].kind!==t.kind||(i=this.transceivers[s]);return i||(i=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),i.track=t,i.stream=r,i.rtpSender=new e.RTCRtpSender(t,i.dtlsTransport),i.rtpSender},s.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var i=e.clone();e.getTracks().forEach((function(e,t){var r=i.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),i.getTracks().forEach((function(e){r.addTrack(e,i)}))}},s.prototype.removeTrack=function(t){if(this._isClosed)throw ne("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 r=this.transceivers.find((function(e){return e.rtpSender===t}));if(!r)throw ne("InvalidAccessError","Sender was not created by this connection.");var i=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(i)&&this.localStreams.indexOf(i)>-1&&this.localStreams.splice(this.localStreams.indexOf(i),1),this._maybeFireNegotiationNeeded()},s.prototype.removeStream=function(e){var t=this;e.getTracks().forEach((function(e){var r=t.getSenders().find((function(t){return t.track===e}));r&&t.removeTrack(r)}))},s.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},s.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},s.prototype._createIceGatherer=function(t,r){var i=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var s=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(s,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(e){var r=!e.candidate||0===Object.keys(e.candidate).length;s.state=r?"completed":"gathering",null!==i.transceivers[t].bufferedCandidateEvents&&i.transceivers[t].bufferedCandidateEvents.push(e)},s.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),s},s.prototype._gather=function(t,r){var i=this,s=this.transceivers[r].iceGatherer;if(!s.onlocalcandidate){var o=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,s.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),s.onlocalcandidate=function(e){if(!(i.usingBundle&&r>0)){var o=new Event("icecandidate");o.candidate={sdpMid:t,sdpMLineIndex:r};var n=e.candidate,a=!n||0===Object.keys(n).length;if(a)"new"!==s.state&&"gathering"!==s.state||(s.state="completed");else{"new"===s.state&&(s.state="gathering"),n.component=1,n.ufrag=s.getLocalParameters().usernameFragment;var c=te.writeCandidate(n);o.candidate=Object.assign(o.candidate,te.parseCandidate(c)),o.candidate.candidate=c,o.candidate.toJSON=function(){return{candidate:o.candidate.candidate,sdpMid:o.candidate.sdpMid,sdpMLineIndex:o.candidate.sdpMLineIndex,usernameFragment:o.candidate.usernameFragment}}}var d=te.getMediaSections(i._localDescription.sdp);d[o.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+o.candidate.candidate+"\r\n",i._localDescription.sdp=te.getDescription(i._localDescription.sdp)+d.join("");var _=i.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==i.iceGatheringState&&(i.iceGatheringState="gathering",i._emitGatheringStateChange()),a||i._dispatchEvent("icecandidate",o),_&&(i._dispatchEvent("icecandidate",new Event("icecandidate")),i.iceGatheringState="complete",i._emitGatheringStateChange())}},e.setTimeout((function(){o.forEach((function(e){s.onlocalcandidate(e)}))}),0)}},s.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var i=new e.RTCDtlsTransport(r);return i.ondtlsstatechange=function(){t._updateConnectionState()},i.onerror=function(){Object.defineProperty(i,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:i}},s.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var r=this.transceivers[e].iceTransport;r&&(delete r.onicestatechange,delete this.transceivers[e].iceTransport);var i=this.transceivers[e].dtlsTransport;i&&(delete i.ondtlsstatechange,delete i.onerror,delete this.transceivers[e].dtlsTransport)},s.prototype._transceive=function(e,r,i){var s=ie(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(s.encodings=e.sendEncodingParameters,s.rtcp={cname:te.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(s.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(s)),i&&e.rtpReceiver&&s.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?s.encodings=e.recvEncodingParameters:s.encodings=[{}],s.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(s.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(s.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(s))},s.prototype.setLocalDescription=function(e){var t,r,i=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(ne("TypeError",'Unsupported type "'+e.type+'"'));if(!se("setLocalDescription",e.type,i.signalingState)||i._isClosed)return Promise.reject(ne("InvalidStateError","Can not set local "+e.type+" in state "+i.signalingState));if("offer"===e.type)t=te.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=te.parseRtpParameters(e);i.transceivers[t].localCapabilities=r})),i.transceivers.forEach((function(e,t){i._gather(e.mid,t)}));else if("answer"===e.type){t=te.splitSections(i._remoteDescription.sdp),r=t.shift();var s=te.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var o=i.transceivers[t],n=o.iceGatherer,a=o.iceTransport,c=o.dtlsTransport,d=o.localCapabilities,_=o.remoteCapabilities;if(!(te.isRejected(e)&&0===te.matchPrefix(e,"a=bundle-only").length)&&!o.rejected){var u=te.getIceParameters(e,r),l=te.getDtlsParameters(e,r);s&&(l.role="server"),i.usingBundle&&0!==t||(i._gather(o.mid,t),"new"===a.state&&a.start(n,u,s?"controlling":"controlled"),"new"===c.state&&c.start(l));var h=ie(d,_);i._transceive(o,h.codecs.length>0,!1)}}))}return i._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?i._updateSignalingState("have-local-offer"):i._updateSignalingState("stable"),Promise.resolve()},s.prototype.setRemoteDescription=function(s){var o=this;if(-1===["offer","answer"].indexOf(s.type))return Promise.reject(ne("TypeError",'Unsupported type "'+s.type+'"'));if(!se("setRemoteDescription",s.type,o.signalingState)||o._isClosed)return Promise.reject(ne("InvalidStateError","Can not set remote "+s.type+" in state "+o.signalingState));var n={};o.remoteStreams.forEach((function(e){n[e.id]=e}));var a=[],c=te.splitSections(s.sdp),d=c.shift(),_=te.matchPrefix(d,"a=ice-lite").length>0,u=te.matchPrefix(d,"a=group:BUNDLE ").length>0;o.usingBundle=u;var l=te.matchPrefix(d,"a=ice-options:")[0];return o.canTrickleIceCandidates=!!l&&l.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(i,c){var l=te.splitLines(i),h=te.getKind(i),R=te.isRejected(i)&&0===te.matchPrefix(i,"a=bundle-only").length,m=l[0].substr(2).split(" ")[2],p=te.getDirection(i,d),S=te.parseMsid(i),T=te.getMid(i)||te.generateIdentifier();if(R||"application"===h&&("DTLS/SCTP"===m||"UDP/DTLS/SCTP"===m))o.transceivers[c]={mid:T,kind:h,protocol:m,rejected:!0};else{var C,I,E,g,f,v,O,L,A;!R&&o.transceivers[c]&&o.transceivers[c].rejected&&(o.transceivers[c]=o._createTransceiver(h,!0));var D,N,b=te.parseRtpParameters(i);R||(D=te.getIceParameters(i,d),(N=te.getDtlsParameters(i,d)).role="client"),O=te.parseRtpEncodingParameters(i);var k=te.parseRtcpParameters(i),y=te.matchPrefix(i,"a=end-of-candidates",d).length>0,U=te.matchPrefix(i,"a=candidate:").map((function(e){return te.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===s.type||"answer"===s.type)&&!R&&u&&c>0&&o.transceivers[c]&&(o._disposeIceAndDtlsTransports(c),o.transceivers[c].iceGatherer=o.transceivers[0].iceGatherer,o.transceivers[c].iceTransport=o.transceivers[0].iceTransport,o.transceivers[c].dtlsTransport=o.transceivers[0].dtlsTransport,o.transceivers[c].rtpSender&&o.transceivers[c].rtpSender.setTransport(o.transceivers[0].dtlsTransport),o.transceivers[c].rtpReceiver&&o.transceivers[c].rtpReceiver.setTransport(o.transceivers[0].dtlsTransport)),"offer"!==s.type||R){if("answer"===s.type&&!R){I=(C=o.transceivers[c]).iceGatherer,E=C.iceTransport,g=C.dtlsTransport,f=C.rtpReceiver,v=C.sendEncodingParameters,L=C.localCapabilities,o.transceivers[c].recvEncodingParameters=O,o.transceivers[c].remoteCapabilities=b,o.transceivers[c].rtcpParameters=k,U.length&&"new"===E.state&&(!_&&!y||u&&0!==c?U.forEach((function(e){oe(C.iceTransport,e)})):E.setRemoteCandidates(U)),u&&0!==c||("new"===E.state&&E.start(I,D,"controlling"),"new"===g.state&&g.start(N)),!ie(C.localCapabilities,C.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&C.sendEncodingParameters[0].rtx&&delete C.sendEncodingParameters[0].rtx,o._transceive(C,"sendrecv"===p||"recvonly"===p,"sendrecv"===p||"sendonly"===p),!f||"sendrecv"!==p&&"sendonly"!==p?delete C.rtpReceiver:(A=f.track,S?(n[S.stream]||(n[S.stream]=new e.MediaStream),r(A,n[S.stream]),a.push([A,f,n[S.stream]])):(n.default||(n.default=new e.MediaStream),r(A,n.default),a.push([A,f,n.default])))}}else{(C=o.transceivers[c]||o._createTransceiver(h)).mid=T,C.iceGatherer||(C.iceGatherer=o._createIceGatherer(c,u)),U.length&&"new"===C.iceTransport.state&&(!y||u&&0!==c?U.forEach((function(e){oe(C.iceTransport,e)})):C.iceTransport.setRemoteCandidates(U)),L=e.RTCRtpReceiver.getCapabilities(h),t<15019&&(L.codecs=L.codecs.filter((function(e){return"rtx"!==e.name}))),v=C.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var P,M=!1;if("sendrecv"===p||"sendonly"===p){if(M=!C.rtpReceiver,f=C.rtpReceiver||new e.RTCRtpReceiver(C.dtlsTransport,h),M)A=f.track,S&&"-"===S.stream||(S?(n[S.stream]||(n[S.stream]=new e.MediaStream,Object.defineProperty(n[S.stream],"id",{get:function(){return S.stream}})),Object.defineProperty(A,"id",{get:function(){return S.track}}),P=n[S.stream]):(n.default||(n.default=new e.MediaStream),P=n.default)),P&&(r(A,P),C.associatedRemoteMediaStreams.push(P)),a.push([A,f,P])}else C.rtpReceiver&&C.rtpReceiver.track&&(C.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===C.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),C.associatedRemoteMediaStreams=[]);C.localCapabilities=L,C.remoteCapabilities=b,C.rtpReceiver=f,C.rtcpParameters=k,C.sendEncodingParameters=v,C.recvEncodingParameters=O,o._transceive(o.transceivers[c],!1,M)}}})),void 0===o._dtlsRole&&(o._dtlsRole="offer"===s.type?"active":"passive"),o._remoteDescription={type:s.type,sdp:s.sdp},"offer"===s.type?o._updateSignalingState("have-remote-offer"):o._updateSignalingState("stable"),Object.keys(n).forEach((function(t){var r=n[t];if(r.getTracks().length){if(-1===o.remoteStreams.indexOf(r)){o.remoteStreams.push(r);var s=new Event("addstream");s.stream=r,e.setTimeout((function(){o._dispatchEvent("addstream",s)}))}a.forEach((function(e){var t=e[0],s=e[1];r.id===e[2].id&&i(o,t,s,[r])}))}})),a.forEach((function(e){e[2]||i(o,e[0],e[1],[])})),e.setTimeout((function(){o&&o.transceivers&&o.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()},s.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")},s.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},s.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))},s.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 r=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",r)}},s.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 r=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",r)}},s.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(ne("InvalidStateError","Can not call createOffer after close"));var i=r.transceivers.filter((function(e){return"audio"===e.kind})).length,s=r.transceivers.filter((function(e){return"video"===e.kind})).length,o=arguments[0];if(o){if(o.mandatory||o.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==o.offerToReceiveAudio&&(i=!0===o.offerToReceiveAudio?1:!1===o.offerToReceiveAudio?0:o.offerToReceiveAudio),void 0!==o.offerToReceiveVideo&&(s=!0===o.offerToReceiveVideo?1:!1===o.offerToReceiveVideo?0:o.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--i<0&&(e.wantReceive=!1):"video"===e.kind&&--s<0&&(e.wantReceive=!1)}));i>0||s>0;)i>0&&(r._createTransceiver("audio"),i--),s>0&&(r._createTransceiver("video"),s--);var n=te.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(i,s){var o=i.track,n=i.kind,a=i.mid||te.generateIdentifier();i.mid=a,i.iceGatherer||(i.iceGatherer=r._createIceGatherer(s,r.usingBundle));var c=e.RTCRtpSender.getCapabilities(n);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"),i.remoteCapabilities&&i.remoteCapabilities.codecs&&i.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(i.remoteCapabilities&&i.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=i.sendEncodingParameters||[{ssrc:1001*(2*s+1)}];o&&t>=15019&&"video"===n&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),i.wantReceive&&(i.rtpReceiver=new e.RTCRtpReceiver(i.dtlsTransport,n)),i.localCapabilities=c,i.sendEncodingParameters=d})),"max-compat"!==r._config.bundlePolicy&&(n+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),n+="a=ice-options:trickle\r\n",r.transceivers.forEach((function(e,t){n+=re(e,e.localCapabilities,"offer",e.stream,r._dtlsRole),n+="a=rtcp-rsize\r\n",!e.iceGatherer||"new"===r.iceGatheringState||0!==t&&r.usingBundle||(e.iceGatherer.getLocalCandidates().forEach((function(e){e.component=1,n+="a="+te.writeCandidate(e)+"\r\n"})),"completed"===e.iceGatherer.state&&(n+="a=end-of-candidates\r\n"))}));var a=new e.RTCSessionDescription({type:"offer",sdp:n});return Promise.resolve(a)},s.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(ne("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(ne("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var i=te.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.usingBundle&&(i+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),i+="a=ice-options:trickle\r\n";var s=te.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,o){if(!(o+1>s)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?i+="m=application 0 DTLS/SCTP 5000\r\n":i+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?i+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(i+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(i+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var n;if(e.stream)"audio"===e.kind?n=e.stream.getAudioTracks()[0]:"video"===e.kind&&(n=e.stream.getVideoTracks()[0]),n&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1});var a=ie(e.localCapabilities,e.remoteCapabilities);!a.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,i+=re(e,a,"answer",e.stream,r._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(i+="a=rtcp-rsize\r\n")}}));var o=new e.RTCSessionDescription({type:"answer",sdp:i});return Promise.resolve(o)},s.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(i,s){if(!r._remoteDescription)return s(ne("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var o=e.sdpMLineIndex;if(e.sdpMid)for(var n=0;n<r.transceivers.length;n++)if(r.transceivers[n].mid===e.sdpMid){o=n;break}var a=r.transceivers[o];if(!a)return s(ne("OperationError","Can not add ICE candidate"));if(a.rejected)return i();var c=Object.keys(e.candidate).length>0?te.parseCandidate(e.candidate):{};if("tcp"===c.protocol&&(0===c.port||9===c.port))return i();if(c.component&&1!==c.component)return i();if((0===o||o>0&&a.iceTransport!==r.transceivers[0].iceTransport)&&!oe(a.iceTransport,c))return s(ne("OperationError","Can not add ICE candidate"));var d=e.candidate.trim();0===d.indexOf("a=")&&(d=d.substr(2)),(t=te.getMediaSections(r._remoteDescription.sdp))[o]+="a="+(c.type?d:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=te.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var _=0;_<r.transceivers.length&&(r.transceivers[_].rejected||(r.transceivers[_].iceTransport.addRemoteCandidate({}),(t=te.getMediaSections(r._remoteDescription.sdp))[_]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=te.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));_++);i()}))},s.prototype.getStats=function(t){if(t&&t instanceof e.MediaStreamTrack){var r=null;if(this.transceivers.forEach((function(e){e.rtpSender&&e.rtpSender.track===t?r=e.rtpSender:e.rtpReceiver&&e.rtpReceiver.track===t&&(r=e.rtpReceiver)})),!r)throw ne("InvalidAccessError","Invalid selector.");return r.getStats()}var i=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&i.push(e[t].getStats())}))})),Promise.all(i).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 r=e[t];if(r&&r.prototype&&r.prototype.getStats){var i=r.prototype.getStats;r.prototype.getStats=function(){return i.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var i;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(i=e[r]).type]||i.type,t.set(r,e[r])})),t}))}}}));var o=["createOffer","createAnswer"];return o.forEach((function(e){var t=s.prototype[e];s.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)}})),(o=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=s.prototype[e];s.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=s.prototype[e];s.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)}})),s};function ce(e){const t=e&&e.navigator,r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(e){return r(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 de(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 _e(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 r=new Event("enabled");r.enabled=e,this.dispatchEvent(r)}})}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 r=ae(e,t.version);e.RTCPeerConnection=function(e){return e&&e.iceServers&&(e.iceServers=function(e,t){let r=!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&&x("RTCIceServer.url","RTCIceServer.urls");const i="string"==typeof t;return i&&(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&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=i?t[0]:t,!!t.length}}))}(e.iceServers,t.version),M("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype}function ue(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var le=Object.freeze({__proto__:null,shimPeerConnection:_e,shimReplaceTrack:ue,shimGetUserMedia:ce,shimGetDisplayMedia:de});function he(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){x("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function Re(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 me(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 r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,o]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(s,o)}}function pe(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 r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.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 Se(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}),y(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Te(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){x("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Ce(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ie(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],r=e&&"sendEncodings"in e;r&&e.sendEncodings.forEach((e=>{if("rid"in e){if(!/^[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 i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function Ee(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 ge(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 fe(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 ve=Object.freeze({__proto__:null,shimOnTrack:Re,shimPeerConnection:me,shimSenderGetStats:pe,shimReceiverGetStats:Se,shimRemoveStream:Te,shimRTCDataChannel:Ce,shimAddTransceiver:Ie,shimGetParameters:Ee,shimCreateOffer:ge,shimCreateAnswer:fe,shimGetUserMedia:he,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})}});function Oe(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((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.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 r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function Le(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 r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function Ae(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,s=t.setLocalDescription,o=t.setRemoteDescription,n=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=r.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[r]);return t?(s.then(e,t),Promise.resolve()):s};let a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function De(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(Ne(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function Ne(e){return e&&void 0!==e.video?Object.assign({},e,{video:B(e.video)}):e}function be(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];!i.hasOwnProperty("urls")&&i.hasOwnProperty("url")?(x("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function ke(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 ye(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 r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video")}return t.apply(this,arguments)}}function Ue(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Pe=Object.freeze({__proto__:null,shimLocalStreamsAPI:Oe,shimRemoteStreamsAPI:Le,shimCallbacksAPI:Ae,shimGetUserMedia:De,shimConstraints:Ne,shimRTCIceServerUrls:be,shimTrackEventTransceiver:ke,shimCreateOfferLegacy:ye,shimAudioContext:Ue});function Me(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 r=new t(e),i=te.parseCandidate(e.candidate),s=Object.assign(r,i);return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,y(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function xe(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 r=function(e){if(!e||!e.sdp)return!1;const t=te.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=te.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},i=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r},s=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r},o=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const s=te.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?i=parseInt(s[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i},n=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(r(arguments[0])){const e=i(arguments[0]),t=s(e),r=o(arguments[0],e);let n;n=0===t&&0===r?Number.POSITIVE_INFINITY:0===t||0===r?Math.max(t,r):Math.min(t,r);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>n}),this._sctp=a}return n.apply(this,arguments)}}function we(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],s=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},y(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Be(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 r=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 r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function Ve(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=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:r}):t.sdp=r}return r.apply(this,arguments)}}function $e(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.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():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}var Fe=Object.freeze({__proto__:null,shimRTCIceCandidate:Me,shimMaxMessageSize:xe,shimSendThrowTypeError:we,shimConnectionState:Be,removeExtmapAllowMixed:Ve,shimAddIceCandidateNullOrEmpty:$e});const Ge=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=M,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=k(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=k(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=k(r.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=k(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:i,commonShim:Fe,extractVersion:k,disableLog:U,disableWarnings:P};switch(i.browser){case"chrome":if(!Z||!Q||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),s;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),s;r("adapter.js shimming chrome."),s.browserShim=Z,$e(e,i),G(e,i),K(e),Q(e,i),j(e),Y(e,i),H(e),J(e),q(e),z(e,i),Me(e),Be(e),xe(e,i),we(e),Ve(e,i);break;case"firefox":if(!ve||!me||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),s;r("adapter.js shimming firefox."),s.browserShim=ve,$e(e,i),he(e,i),me(e,i),Re(e),Te(e),pe(e),Se(e),Ce(e),Ie(e),Ee(e),ge(e),fe(e),Me(e),Be(e),xe(e,i),we(e);break;case"edge":if(!le||!_e||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),s;r("adapter.js shimming edge."),s.browserShim=le,ce(e),de(e),_e(e,i),ue(e),xe(e,i),we(e);break;case"safari":if(!Pe||!t.shimSafari)return r("Safari shim is not included in this adapter release."),s;r("adapter.js shimming safari."),s.browserShim=Pe,$e(e,i),be(e),ye(e),Ae(e),Oe(e),Le(e),ke(e),De(e),Ue(e),Me(e),xe(e,i),we(e),Ve(e,i);break;default:r("Unsupported browser!")}return s}({window:"undefined"==typeof window?void 0:window});var Ke,je,He;!function(e){e.FPS_10="FPS_10",e.FPS_15="FPS_15",e.FPS_24="FPS_24",e.FPS_30="FPS_30"}(Ke||(Ke={})),function(e){e.W176_H132="W176_H132",e.W176_H144="W176_H144",e.W180_H180="W180_H180",e.W240_H180="W240_H180",e.W240_H240="W240_H240",e.W256_H144="W256_H144",e.W320_H180="W320_H180",e.W320_H240="W320_H240",e.W360_H360="W360_H360",e.W480_H360="W480_H360",e.W480_H480="W480_H480",e.W640_H360="W640_H360",e.W640_H480="W640_H480",e.W720_H480="W720_H480",e.W848_H480="W848_H480",e.W960_H720="W960_H720",e.W1280_H720="W1280_H720",e.W1920_H1080="W1920_H1080"}(je||(je={})),function(e){e[e.AUDIO_ONLY=0]="AUDIO_ONLY",e[e.VIDEO_ONLY=1]="VIDEO_ONLY",e[e.AUDIO_VIDEO=2]="AUDIO_VIDEO"}(He||(He={}));const Je={[je.W176_H132]:{width:176,height:132,maxBitrate:150,minBitrate:80},[je.W176_H144]:{width:176,height:144,maxBitrate:150,minBitrate:80},[je.W180_H180]:{width:180,height:180,maxBitrate:200,minBitrate:100},[je.W240_H180]:{width:240,height:180,maxBitrate:240,minBitrate:120},[je.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[je.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[je.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[je.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[je.W360_H360]:{width:360,height:360,maxBitrate:520,minBitrate:140},[je.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[je.W480_H480]:{width:480,height:480,maxBitrate:800,minBitrate:180},[je.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[je.W640_H480]:{width:640,height:480,maxBitrate:900,minBitrate:200},[je.W720_H480]:{width:720,height:480,maxBitrate:1e3,minBitrate:200},[je.W848_H480]:{width:848,height:480,maxBitrate:1860,minBitrate:200},[je.W960_H720]:{width:960,height:720,maxBitrate:2e3,minBitrate:250},[je.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[je.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},qe=e=>{const t={192:180,368:360,1088:1080};return t[e]?t[e]:e},We=(e,t)=>{e=qe(e),t=qe(t);const r=Je[`W${e}_H${t}`];if(r)return r;const i=e*t;return Object.keys(Je).map((e=>Je[e])).sort(((e,t)=>e.height*e.width-t.width*t.height)).filter((e=>e.height*e.width>=i))[0]||Je.W1920_H1080},Ye={10:1,15:1,24:1.5,30:1.5},Qe=e=>{let t=Number.MAX_VALUE,r=1;for(const i in Ye){const s=Math.abs(e-parseInt(i));s<t&&(t=s,r=Ye[i])}return r},ze={getCameras:()=>v(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))})),getMicrophones:()=>v(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))})),getSpeakers:()=>v(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audiooutput"===e.kind))}))};var Ze,Xe;!function(e){e.AUDIO="audio",e.VIDEO="video"}(Ze||(Ze={}));class et extends t{constructor(e,t,r,i,s){super(),this._tag=e,this._userId=t,this._kind=r,this._isLocalTrack=i,this._roomId=s,this._localMuted=!1,this._remoteMuted=!1,this._streamId=[this._userId||this._roomId,this._tag].join("_"),this._id=[this._streamId,this.isAudioTrack()?0:1].join("_")}getStreamId(){return this._streamId}getTrackId(){return this._id}getUserId(){return this._userId}__innerGetMediaStreamTrack(){return this._msTrack}get streamTrack(){return this._msTrack}getTag(){return this._tag}isLocalTrack(){return this._isLocalTrack}isVideoTrack(){return"video"===this._kind}isAudioTrack(){return"audio"===this._kind}isReady(){var e;return"live"===(null===(e=this._msTrack)||void 0===e?void 0:e.readyState)}__innerSetMediaStreamTrack(e){this._msTrack=e,this._setLocalMuted(this._localMuted);const t=this._msStream=this._msStream||new MediaStream,r=t.getTracks()[0];r&&t.removeTrack(r),e?t.addTrack(e):this._element&&(this._element.pause(),this._element.srcObject=null)}_setLocalMuted(e){this._msTrack&&(this._msTrack.enabled=!e),this._localMuted=e}mute(){return O.info(`set ${this._id} enabled: false`),r.info(A.L_TRACK_MUTE_O,{status:D.SUCCESSED,id:this._id},{logSource:i.RTC}),this._setLocalMuted(!0)}unmute(){return O.info(`set ${this._id} enabled: true`),r.info(A.L_TRACK_UNMUTE_O,{status:D.SUCCESSED,id:this._id},{logSource:i.RTC}),this._setLocalMuted(!1)}isLocalMuted(){return this._localMuted}isMCUTrack(){return Boolean(this._roomId)}isOwnerMuted(){return this._remoteMuted}play(e,t){return v(this,void 0,void 0,(function*(){if(r.info(A.L_TRACK_PLAY_T,{element:e,options:t,msg:`start play trackId: ${this._id}`},{logSource:i.RTC}),!this._msTrack)return O.warn(`the track is not ready to play -> id: ${this._id}`),r.error(A.L_TRACK_PLAY_R,{status:D.FAILED,code:L.TRACK_NOT_READY,msg:`play error -> id: ${this._id}`},{logSource:i.RTC}),{code:L.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&(O.warn(`the track's readyState is 'ended' -> id: ${this._id}`),r.error(A.L_TRACK_PLAY_R,{status:D.FAILED,code:"",msg:`the track's readyState is ended -> id: ${this._id}`},{logSource:i.RTC})),null==t?void 0:t.volume){if(!s(null==t?void 0:t.volume))return O.error(`${null==t?void 0:t.volume} is not a number, the valid range of options.volume is 0-100`),r.error(A.L_TRACK_PLAY_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> options.volume不是数字"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};(null==t?void 0:t.volume)<0&&(t.volume=0,O.warn("the valid range of options.volume is 0-100, the value of volume has been set 0"),r.warn(A.L_TRACK_PLAY_R,{status:D.FAILED,code:"",msg:"params error -> options.volume < 0"},{logSource:i.RTC})),(null==t?void 0:t.volume)>100&&(t.volume=100,O.warn("the valid range of options.volume is 0-100, the value of volume has been set 100"),r.warn(A.L_TRACK_PLAY_R,{status:D.FAILED,code:"",msg:"params error -> options.volume > 100"},{logSource:i.RTC}))}if(null==t?void 0:t.audioDeviceId){if(!(yield ze.getSpeakers()).map((e=>e.deviceId)).includes(t.audioDeviceId))return O.error(`the options.audioDeviceId is invalid --\x3e ${t.audioDeviceId}`),r.error(A.L_TRACK_PLAY_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> options.audioDeviceId"},{logSource:i.RTC}),{code:L.PARAMS_ERROR}}const o=this.isVideoTrack();return!o||e&&(e instanceof HTMLVideoElement||this.__validateVideoNodeName(e))?(this._element=o?e:this._element||new Audio,this._localMuted&&this._setLocalMuted(!1),this._element.srcObject&&this._element.srcObject===this._msStream||this._element.pause(),this._element.onloadstart=e=>{var t,s;O.debug(`HTMLMediaElement onloadstart -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(A.L_TRACK_PLAY_R,{status:D.INFO,msg:`HTMLMediaElement onloadstart -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.ondurationchange=e=>{var t,s;O.debug(`HTMLMediaElement ondurationchange -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(A.L_TRACK_PLAY_R,{status:D.INFO,msg:`HTMLMediaElement ondurationchange -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onloadedmetadata=e=>{var t,s;O.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(A.L_TRACK_PLAY_R,{status:D.INFO,msg:`HTMLMediaElement onloadedmetadata -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onloadeddata=e=>{var t,s;O.debug(`HTMLMediaElement onloadeddata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(A.L_TRACK_PLAY_R,{status:D.INFO,msg:`HTMLMediaElement onloadeddata -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onabort=e=>{var t,s;O.info(`HTMLMediaElement onabort -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(A.L_TRACK_PLAY_R,{status:D.INFO,msg:`HTMLMediaElement onabort -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.oncanplay=e=>v(this,void 0,void 0,(function*(){var s,n,a;O.info(`HTMLMediaElement oncanplay -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`),r.info(A.L_TRACK_PLAY_R,{status:D.INFO,msg:`HTMLMediaElement oncanplay -> id: ${null===(n=e.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:i.RTC});try{yield null===(a=this._element)||void 0===a?void 0:a.play(),(null==t?void 0:t.audioDeviceId)&&!o&&(yield this._element.setSinkId(t.audioDeviceId))}catch(e){if("No permission to use requested device"===e.message)return O.error(`setSinkId failed -> ${e.message}`),void r.error(A.L_TRACK_PLAY_R,{status:D.FAILED,code:L.NO_PERMISSION_TO_USE_REQUESTED_DEVICE,msg:"No permission"},{logSource:i.RTC});O.error(e),r.error(A.L_TRACK_PLAY_R,{status:D.FAILED,code:L.TRACK_PLAY_ERROR,msg:"play error"},{logSource:i.RTC})}})),this._element.onvolumechange=e=>{var t,s;const o=Math.floor(100*(null===(t=e.target)||void 0===t?void 0:t.volume));O.info(`HTMLMediaElement onvolumechange -> volume: ${o}, trackId: ${this._id}`),r.info(A.L_TRACK_PLAY_R,{status:D.INFO,msg:`HTMLMediaElement onvolumechange -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.srcObject=this._msStream,this._element.autoplay=!0,o&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),o||!(null==t?void 0:t.volume)&&0!==(null==t?void 0:t.volume)||(this._element.volume=(null==t?void 0:t.volume)/100),r.info(A.L_TRACK_PLAY_R,{status:D.SUCCESSED,element:e,options:t},{logSource:i.RTC}),{code:L.SUCCESS}):(O.error(`the video track need an <video> to play -> id: ${this._id}`),r.error(A.L_TRACK_PLAY_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> element不是一个video标签"},{logSource:i.RTC}),{code:L.VIDEO_TRACK_MISS_MEDIA_ELEMENT})}))}__innerDestroy(){this.__innerSetMediaStreamTrack(void 0)}__releaseMediaElement(){this._element&&(this._element.remove(),this._element.srcObject=null)}__validateVideoNodeName(e){return e&&e.nodeName&&"VIDEO"===e.nodeName.toUpperCase()}}!function(e){e.Speech="Speech",e.Music="Music",e.MusicHigh="MusicHigh"}(Xe||(Xe={}));const tt={[Xe.Music]:{max:64,min:64},[Xe.MusicHigh]:{max:128,min:128},[Xe.Speech]:{max:32,min:32}};var rt;!function(e){e.LEVEL0="LEVEL0",e.LEVEL1="LEVEL1",e.LEVEL2="LEVEL2",e.LEVEL3="LEVEL3",e.LEVEL4="LEVEL4",e.LEVEL5="LEVEL5"}(rt||(rt={}));const it={[rt.LEVEL0]:{max:150,min:80},[rt.LEVEL1]:{max:280,min:120},[rt.LEVEL2]:{max:650,min:150},[rt.LEVEL3]:{max:1e3,min:200},[rt.LEVEL4]:{max:2200,min:250},[rt.LEVEL5]:{max:4e3,min:400}};class st{static setStatus(e=!0){st.isOpen=e}static setWroklet(e,t){st.workletModule=e,st.workletModule=t}static transformStreamTrack(e){var t;return v(this,void 0,void 0,(function*(){if(!st.isOpen)return new Promise((t=>{t({track:null==e?void 0:e.getAudioTracks()[0],stop:()=>{}})}));let r=new AudioContext({sampleRate:44100}),s=r.createMediaStreamSource(e),o=r.createMediaStreamDestination(),n=null,a=null;if(n=yield r.audioWorklet.addModule(st.workletModule).then((()=>(O.info(A.L_RTC_3ANOISE_NODE_O,{status:D.SUCCESSED,message:{msg:"addModule RC3AnoiseTrack.workletModule success"}},{logSource:i.RTC}),fetch(st.workletWasm,{cache:"force-cache",credentials:"same-origin"}).then((e=>e.arrayBuffer())).catch((e=>{throw new Error(e.message)}))))).then((e=>(a=new AudioWorkletNode(r,"process-worklet",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{binary:e}}),a))).catch((e=>{O.info(A.L_RTC_3ANOISE_NODE_E,{status:D.FAILED,message:{msg:e.message}},{logSource:i.RTC})})),!n)return new Promise((t=>{t({track:null==e?void 0:e.getAudioTracks()[0],stop:()=>{}})}));s.connect(n).connect(o);let c=null===(t=null==o?void 0:o.stream)||void 0===t?void 0:t.getAudioTracks()[0],d=()=>{O.info(A.L_RTC_3ANOISE_NODE_STOP_O,{status:D.SUCCESSED,message:{msg:"call stop RC3AnoiseTrack.workletModule"}},{logSource:i.RTC}),null==n||n.port.postMessage({type:"stop",msg:""}),setTimeout((()=>{const t=null==e?void 0:e.getAudioTracks()[0];null==t||t.stop(),r.suspend(),r.close(),o.disconnect(),n.disconnect(),s.disconnect(),r=null,n=null,o=null,s=null,a=null,e=null,null==c||c.stop(),c=null,d=null}),200)};return{track:c,stop:d}}))}}st.workletModule="https://cdn.ronghub.com/plugin-rtc/wasm/5.0.0-alpha.2/process-worklet.js",st.workletWasm="https://cdn.ronghub.com/plugin-rtc/wasm/5.0.0-alpha.2/AudioProcessing.wasm",st.isOpen=!1;class ot extends et{constructor(e,t,r,i){super(e,t,r,!0),this._isDestroyed=!1,this._isPublished=!1,this.__innerSetMediaStreamTrack(i),i.onended=()=>{i.onended=null,this.emit(ot.EVENT_LOCAL_TRACK_END,this),this.removeAll(ot.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(e){return new Promise(((t,s)=>{const o=this._localMuted!==e;super._setLocalMuted(e),this._remoteMuted=this._localMuted,o&&this.emit(ot.__INNER_EVENT_MUTED_CHANGE__,this,t),r.info(A.L_LOCAL_TRACK_SET_LOCAL_MUTED_O,{status:D.SUCCESSED,bool:e},{logSource:i.RTC})}))}__innerSetPublished(e){r.info(A.L_LOCAL_TRACK_INNER_SET_PUBLISHED_O,{status:D.SUCCESSED,bool:e},{logSource:i.RTC}),this._isPublished=e}isPublished(){return this._isPublished}destroy(){var e;O.info(`track is destroyed -> trackId: ${this.getTrackId()}`),this._isDestroyed=!0,null===(e=this._msTrack)||void 0===e||e.stop(),super.__innerDestroy(),this.isAudioTrack()&&super.__releaseMediaElement(),this.emit(ot.__INNER_EVENT_DESTROY__,this),r.info(A.L_LOCAL_TRACK_DESTROY_O,{status:D.SUCCESSED},{logSource:i.RTC})}isDestroyed(){return this._isDestroyed}setBitrate(e=0,t=0,o=0){if(!s(e)||!s(t)||!s(o)||e<=0||t<=0||e<t)return O.error("setBitrate params error ->"),void r.error(A.L_LOCAL_TRACK_SET_BITRATE_O,{status:D.FAILED,code:"",msg:`params error -> max: ${e},min: ${t}, start: ${o}`},{logSource:i.RTC});r.info(A.L_LOCAL_TRACK_SET_BITRATE_O,{status:D.SUCCESSED,max:e,min:t,start:o},{logSource:i.RTC}),this._bitrateInfo={max:e,min:t,start:o}}getBitrate(){var e,t,r,i,s,o,n;let{min:a,max:c,start:d}={min:0,max:0,start:0};return(null===(e=this._msTrack)||void 0===e?void 0:e.kind)===Ze.VIDEO?({min:a,max:c}=vt(this._msTrack)):(null===(t=this._msTrack)||void 0===t?void 0:t.kind)===Ze.AUDIO&&({min:a,max:c}={min:32,max:32}),(null===(r=this._bitrateInfo)||void 0===r?void 0:r.max)&&(d=.7*(null===(i=this._bitrateInfo)||void 0===i?void 0:i.max)),{min:(null===(s=this._bitrateInfo)||void 0===s?void 0:s.min)||a,max:(null===(o=this._bitrateInfo)||void 0===o?void 0:o.max)||c,start:(null===(n=this._bitrateInfo)||void 0===n?void 0:n.start)||d}}}ot.EVENT_LOCAL_TRACK_END="local-track-end",ot.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",ot.__INNER_EVENT_DESTROY__="inner-destroy";class nt extends ot{constructor(e,t,r){super(e,t,"audio",r),this._stopProcess=()=>{}}setRecommendBitrate(e){if(!o("livingType",e,(e=>e in Xe)))return void r.warn(A.L_RTC_SET_RECOMMEND_BITRATE_O,{status:D.FAILED,msg:"params error -> setRecommendBitrate Audio"},{logSource:i.RTC});const t=tt[e];this.setBitrate(t.max,t.min,t.start||.7*t.max)}setBitrate(e,...t){const[r=1,i=.7*e||1]=t;super.setBitrate(e,r,i)}__innerSetMediaStreamTrack(e){if(e)if(st.isOpen){const t=new MediaStream([e]);st.transformStreamTrack(t).then((({track:e,stop:t})=>{super.__innerSetMediaStreamTrack(e),this._stopProcess=t}))}else super.__innerSetMediaStreamTrack(e);else super.__innerSetMediaStreamTrack(e),this._stopProcess()}}class at extends ot{constructor(e,t,r,i=!1){super(e,t,"video",r),this._isTiny=i}__isTiny(){return this._isTiny}getStreamId(){const e=super.getStreamId();return this._isTiny?`${e}_tiny`:e}getTrackId(){const e=super.getTrackId();return this._isTiny?`${e}_tiny`:e}setRecommendBitrate(e){if(!o("livingType",e,(e=>e in rt)))return void r.warn(A.L_RTC_SET_RECOMMEND_BITRATE_O,{status:D.FAILED,msg:"params error -> setRecommendBitrate Video"},{logSource:i.RTC});const t=it[e];this.setBitrate(t.max,t.min,t.start||.7*t.max)}setBitrate(e,...t){const[r=1,i=.7*e||1]=t;super.setBitrate(e,r,i)}}class ct extends ot{constructor(e,t,r,i,s){super(e,t,r,i),this._resource=s,ct.__innerSetMapping(this.getTrackId(),s)}static __innerSetMapping(e,t){const r=this._mapping.get(t)||[];r.push(e),this._mapping.set(t,r)}static __innerRemoveMapping(e,t){var r,i;const s=null===(r=this._mapping.get(t))||void 0===r?void 0:r.filter((t=>t!==e));s&&s.length>0?this._mapping.set(t,s):(this._mapping.delete(t),t.pause(),t.src="",null===(i=t.parentNode)||void 0===i||i.removeChild(t))}destroy(){this.isAudioTrack()&&this.mute(),ct.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}ct._mapping=new Map;class dt extends ct{constructor(e,t,r,i){super(e,t,"video",r,i)}}class _t extends ct{constructor(e,t,r,i){super(e,t,"audio",r,i),this._stopProcess=()=>{}}_setLocalMuted(e){const t=Object.create(null,{_setLocalMuted:{get:()=>super._setLocalMuted}});return v(this,void 0,void 0,(function*(){return this._resource&&(this._resource.muted=e),t._setLocalMuted.call(this,e)}))}play(){return this._setLocalMuted(!1),Promise.resolve({code:L.SUCCESS})}__innerSetMediaStreamTrack(e){if(e)if(st.isOpen){const t=new MediaStream([e]);st.transformStreamTrack(t).then((({track:e,stop:t})=>{super.__innerSetMediaStreamTrack(e),this._stopProcess=t}))}else super.__innerSetMediaStreamTrack(e);else super.__innerSetMediaStreamTrack(e),this._stopProcess()}}class ut extends nt{}class lt extends at{}class ht extends at{}class Rt extends nt{}class mt extends et{constructor(e,t,r,i){super(e,t,r,!1,i),this._isSubscribed=!1}__innerSetRemoteMuted(e){this._remoteMuted=e}__innerSetSubscribed(e){this._isSubscribed=e,r.debug(A.L_REMOTE_TRACK_INNER_SET_SUBSCRIBED_O,{status:D.SUCCESSED,bool:e},{logSource:i.RTC})}isSubscribed(){return this._isSubscribed}}class pt extends mt{constructor(e,t,r){super(e,t,"audio",r)}}class St extends mt{constructor(e,t,r){super(e,t,"video",r),this._isSubTiny=!1}__innerSetIsTinyTrack(e){this._isSubTiny=e}isSubTiny(){return this._isSubTiny}}const Tt=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),Ct=e=>JSON.stringify(e),It=e=>/^[a-zA-Z\d-=]+$/g.test(e),Et="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),gt=e=>{if(void 0===e)return 0;if(s(e))return e;const t=e;return t.exact||t.ideal||t.max||0},ft=e=>{const t=e.getSettings(),r=e.getConstraints();return{width:gt(r.width)||t.width||0,height:gt(r.height)||t.height||0,frameRate:t.frameRate||gt(r.frameRate)}},vt=e=>{const{width:t,height:r,frameRate:i}=ft(e),s=We(t||1920,r||1080),o=Qe(i);return{min:s.minBitrate*o,max:s.maxBitrate*o}},Ot=e=>[e.msid,e.mediaType].join("_"),Lt=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},At=(e,t)=>[e,t].join("_"),Dt=e=>e.map((e=>Object.assign({},e))),Nt=(e,t,r=!1)=>{e=e.slice();const i=[],s=[],o=[];return t.forEach((t=>{const s=Ot(t);let n=e.findIndex((e=>Ot(e)===s));if(r&&(n=e.findIndex((e=>e.uri===t.uri))),-1===n)return void i.push(t);const a=e[n];a.uri!==t.uri?i.push(t):a.state!==t.state&&o.push(t),e.splice(n,1)})),s.push(...e),{publishedList:i,unpublishedList:s,modifiedList:o}},bt=()=>{let e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return e=`${e.replace(/-/g,"")}0`,e=parseInt(e,16),e=(e=>{const t="0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ+/".split(""),r=t.length+1;let i=+e;const s=[];do{const e=i%r;i=(i-e)/r,s.unshift(t[e])}while(i);return s.join("")})(e),e.length>22&&(e=e.slice(0,22)),e},kt=e=>{if(Je[e]){const{width:t,height:r}=Je[e];return{width:t,height:r}}const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},yt=e=>!!je[e],Ut=e=>!!Ke[e],Pt=e=>parseInt(e.replace("FPS_","")),Mt=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=Ge.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function xt(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function wt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const Bt=e=>"[object Null]"===Object.prototype.toString.call(e),Vt=e=>1===e.type,$t=(e,t)=>{const r={},i=Object.keys(e.users);return i.length&&i.forEach((i=>{const s=[],o=e.users[i];if(o.extra){const{roomId:e}=JSON.parse(o.extra);if(t!==e)return}if(o.uris)try{s.push(...JSON.parse(o.uris))}catch(e){O.warn(`invalid user data -> userId: ${i}, userData: ${o}`)}r[i]=s})),r},Ft=(e,t)=>{const r=t.filter((e=>"RC_RTC_SESSIONID"===e.key))[0],i=r?r.value:"",s=t.filter((e=>"RC_ANCHOR_LIST"===e.key)).map((e=>JSON.parse(e.value||"[]")))[0],o=t.filter((e=>e.key.includes("RC_RES_"))).map((e=>JSON.parse(e.value||"{}"))),n=o.length?JSON.parse(o[0].mcu_uris||"[]"):[],a=[];n.forEach((t=>{const{mediaType:r,tag:i}=t,s=r===He.AUDIO_ONLY?new pt(i,"",e):new St(i,"",e);a.push(s)}));const c=[],d=[];o.forEach((e=>{const t=JSON.parse(e.uris||"[]");c.push(...t),t.forEach((e=>{const{mediaType:t,tag:r,msid:i}=e,s=i.split("_")[0],o=t===He.AUDIO_ONLY?new pt(r,s):new St(r,s);d.push(o)}))}));const _=t.filter((e=>"RC_CDN"===e.key)).map((e=>{const t=JSON.parse(e.value||"[]");return JSON.parse(t.cdn_uris)[0]}))[0];return{sessionId:i,remoteUserIds:s||[],remoteRTCUris:c,remoteMUCUris:n,remoteRTCTracks:d,remoteMCUTracks:a,remoteTracks:[...d,...a],CDNUris:_||{}}},Gt=e=>e instanceof et?e.getTrackId():e.track.getTrackId(),Kt=e=>{if(!n(e)||void 0===e.low||void 0===e.high)return e;let{low:t}=e;t<0&&(t+=4294967296),t=t.toString(16);return parseInt(e.high.toString(16)+"00000000".replace(new RegExp(`0{${t.length}}$`),t),16)};var jt,Ht;!function(e){e.PUBLISH="RCRTC:PublishResource",e.UNPUBLISH="RCRTC:UnpublishResource",e.MODIFY="RCRTC:ModifyResource",e.TOTAL_CONTENT_RESOURCE="RCRTC:TotalContentResources",e.STATE="RCRTC:state",e.ROOM_NOTIFY="RCRTC:RoomNtf",e.USER_NOTIFY="RCRTC:UserNtf",e.KICK="RCRTC:kick",e.PK_INVITE="RCRTC:invite",e.PK_INVITE_TIMEOUT="RCRTC:inviteTimeout",e.PK_CANCEL_INVITE="RCRTC:cancelInvite",e.PK_INVITE_ANSWER="RCRTC:answerInvite",e.PK_END="RCRTC:endInvite",e.OTHER_ROOM_OFFLINE="RCRTC:otherRoomOffline",e.ROOM_TASK_FINISH="RCRTC:roomTaskFinish"}(jt||(jt={})),function(e){e.SUCCESS="Success",e.FAIL="Fail"}(Ht||(Ht={}));class Jt{constructor(e,t,r,i=5e3,s=6e4){this._roomId=e,this._roomMode=t,this._context=r,this._gap=i,this._offlineKickTime=s,this._latestTimestamp=Date.now(),this._started=!1,this._timer=null}start(){this._started||(O.info("rtcping start ->"),r.info(A.L_PINGER_START_O,{status:D.SUCCESSED,interval:this._gap},{logSource:i.RTC}),this._started=!0,this._checkAlive())}_sendPing(){return new Promise((e=>{this._context.rtcPing(this._roomId,this._roomMode).then(e).catch((t=>{O.error(`rtcping receive unknown error -> ${t}`),e(a.UNKNOWN)})),setTimeout(e,5e3,a.TIMEOUT)}))}_checkAlive(){var e,t,i;return v(this,void 0,void 0,(function*(){O.info("rtcping ->"),r.info(A.L_PINGER_SEND_RTCPING_T,{roomId:this._roomId,msg:"send rtcping"});const s=yield this._sendPing(),o=Date.now();return s===a.SUCCESS?(O.info("rtcping success ->"),r.info(A.L_PINGER_SEND_RTCPING_R,{roomId:this._roomId,msg:"send rtcping success"}),this._latestTimestamp=o,null===(e=this.onPingResult)||void 0===e||e.call(this,Ht.SUCCESS),void(this._timer=setTimeout((()=>this._checkAlive()),this._gap))):(r.info(A.L_PINGER_SEND_RTCPING_R,{roomId:this._roomId,msg:"send rtcping failed",code:s}),O.warn(`rtcping failed -> code: ${s}`),null===(t=this.onPingResult)||void 0===t||t.call(this,Ht.FAIL),40003===s||o-this._latestTimestamp>this._offlineKickTime?(this.stop(),void(null===(i=this.onFailed)||void 0===i||i.call(this,40003===s))):void(this._timer=setTimeout((()=>this._checkAlive()),500)))}))}stop(){this._started&&(O.info("rtcping stop ->"),r.info(A.L_PINGER_STOP_O,{status:D.SUCCESSED},{logSource:i.RTC}),this._started=!1,this._timer&&(clearTimeout(this._timer),this._timer=null))}}const qt=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),Wt=(e,t,r)=>v(void 0,void 0,void 0,(function*(){const i=[];return yield Promise.any(e.map((e=>v(void 0,void 0,void 0,(function*(){const s=`${e.detectorAddr.replace(/^(https?:\/\/)?/,"https://")}/rtc/detector/ping?t=${o=1e3,n=9999,o+Math.floor(Math.random()*(n-o))}`;var o,n;const a={jwt:r},d=yield t.httpReq({url:s,body:JSON.stringify(a),timeout:5e3,method:c.POST});if(O.info(`ping res => ${JSON.stringify({status:d.status,host:e})}`),200!==d.status)return Promise.reject();i.push(e.clusterId)}))))),i})),Yt=(e,t)=>v(void 0,void 0,void 0,(function*(){const r=(e=>{var t;if(!e)return"";let r;try{r=JSON.parse(e.voipCallInfo||'{ "strategy": 0 }')}catch(t){return O.warn(`parse \`voipCallInfo\` of navi failed: ${e.voipCallInfo}`),""}if(0===r.strategy)return"";const i=null===(t=r.callEngine)||void 0===t?void 0:t.filter((e=>4===e.engineType));if(!i||0===i.length)return"";const s=i[0];return s.detectorManager?s.detectorManager:""})(t),i=(s=t)&&s.jwt||"";var s;let o=null,n=120,a=0;const _={jwt:i};if(r&&i){const t=yield e.httpReq({url:`${r}/rtc/detector/servers`,body:JSON.stringify(_),headers:{"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${Mt.browser}|${Mt.version}`,ClientVersion:"5.5.3","Client-Session-Id":qt(),"Request-Id":Date.now().toString()},method:c.POST}),s=t.data&&JSON.parse(t.data).detectorAddrs;n=t.data&&JSON.parse(t.data).clientDetectMinute,a=t.data&&JSON.parse(t.data).resultCode,s&&d(s)&&(o=yield Wt(s,e,i))}return{fastMediaUrl:o,clientDetectMinute:n,status:a}}));class Qt{constructor(){}static getMemo(){return this._memo||(this._memo=new Qt),this._memo}static destroy(){this._memo={}}}const zt=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${Mt.browser}|${Mt.version}`,ClientVersion:"5.5.3","Client-Session-Id":qt(),"Request-Id":Date.now().toString()});class Zt{constructor(e,t,r,i=5e3){this._runtime=e,this._context=t,this._msUrl=r,this._timeout=i,this._msInNavi=[],this._failedMs=[],this._rtcFinger=void 0,this._clusterId="",this._configUrl="",this._msList=[],Zt.isDetector||t.getConnectionStatus()!==_.CONNECTED||this.detectorMediaSever()}detectorMediaSever(){if(this._msUrl)return;const e=Date.now(),t=Zt.detectValidMinute+Zt.detectorTime>e;Zt.isDetector=t,r.info(`set msInDetector => ${JSON.stringify(Zt.msInDetector)}`);const i=this._context.getNaviInfo();!t&&i&&u(i)&&(this._msList=[],this._getDetectorUrls(i))}_getDetectorUrls(e){return v(this,void 0,void 0,(function*(){if(Zt.isDetector)return;Zt.isDetector=!0;const{fastMediaUrl:t,clientDetectMinute:r,status:i}=yield Yt(this._runtime,e);if(i===L.JWT_TIME_OUT&&Zt.naviRefetchCount<5){this._context.getPluginContext().refetchNaviInfo().then((()=>{this.detectorMediaSever()})),++Zt.naviRefetchCount,O.info(`RCMediaService refetch navi count => ${Zt.naviRefetchCount}`)}Zt.msInDetector=t||[],Zt.detectorTime=Date.now(),Zt.detectValidMinute=60*r*1e3,O.info(`RCMediaService detectorTime => ${Zt.detectorTime}`),O.info(`RCMediaService detectValidMinute => ${Zt.detectValidMinute}`)}))}getNaviMS(){return this._msUrl?[this._msUrl]:(l(this._msList)&&!this._clusterId||(this._msList=this.setMediaServiceList()),this._msList)}setMediaServiceList(){let e=[],t=[];return this._clusterId&&(this._clusterId=this._clusterId.replace(/^(https?:\/\/)?/,"https://"),this._msList.push(this._clusterId)),O.info(`MediaServiceList _clusterId -> ${this._clusterId}`),l(Zt.msInDetector)&&(Zt.msInDetector=Zt.msInDetector.map((e=>e.replace(/^(https?:\/\/)?/,"https://"))),this._msList.push(Zt.msInDetector[0]),e=Zt.msInDetector.concat().splice(1,Zt.msInDetector.length-1)),O.info(`MediaServiceList msInDetector ->${JSON.stringify(Zt.msInDetector)}`),0===this._msInNavi.length&&(0===this._failedMs.length?this._msInNavi.push(...(e=>{var t;if(!e)return[];let r;try{r=JSON.parse(e.voipCallInfo||'{ "strategy": 0 }')}catch(t){return O.warn(`parse \`voipCallInfo\` of navi failed: ${e.voipCallInfo}`),[]}if(0===r.strategy)return[];const i=null===(t=r.callEngine)||void 0===t?void 0:t.filter((e=>4===e.engineType));if(!i||0===i.length)return[];const s=i[0],o=[];return s.mediaServer&&o.push(s.mediaServer.replace(/^(https?:\/\/)?/,"https://")),s.backupMediaServer&&s.backupMediaServer.forEach((e=>{o.push(e.replace(/^(https?:\/\/)?/,"https://"))})),o})(this._context.getNaviInfo())):(this._msInNavi.push(...this._failedMs),this._failedMs.length=0)),O.info(`MediaServiceList _msInNavi-> ${JSON.stringify(this._msInNavi)}`),t=this._msInNavi.concat().splice(1,this._msInNavi.length-1),this._msList.push(this._msInNavi[0]),this._msList=[...this._msList,...e,...t],this._msList=[...new Set(this._msList)],O.info(`MediaServiceList msList -> ${JSON.stringify(this._msList)}`),this._msList}_request(e,t,s){return v(this,void 0,void 0,(function*(){const o=Qt.getMemo();o.mediaService=[];const n=this.getNaviMS();if(0===n.length)return O.warn(`request '${e}' failed -> have no valid service address.`),r.error(A.L_MEDIA_SERVICE_REQUEST_R,{status:D.FAILED,code:L.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"invalid navi_url"},{logSource:i.RTC}),{code:L.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(s.rtcFinger=this._rtcFinger);for(let a=0;a<n.length;a+=1){const d=Date.now(),_=`${n[a]}${e}`,u=zt(),l=Object.assign(Object.assign({},u),t),h=JSON.stringify(s),R=u["Request-Id"];r.info(A.L_MEDIA_SERVICE_REQUEST_T,{path:e,headers:t,body:s,reqId:R},{logSource:i.RTC}),O.info(`request -> Request-Id: ${R}, url: ${_}, headers: ${JSON.stringify(l)}, body: ${h}, timeout: ${this._timeout}`);const{status:m,data:p}=yield this._runtime.httpReq({url:_,body:h,headers:l,method:c.POST,timeout:this._timeout});if(o.mediaService.push({start:d,end:Date.now(),reqId:R,status:m,url:_}),200===m){const e=JSON.parse(p);return e.rtcFinger&&(this._rtcFinger=e.rtcFinger),e.clusterId&&(this._clusterId=e.clusterId),O.info(`request success -> Request-Id: ${R}`),r.info(A.L_MEDIA_SERVICE_REQUEST_R,{status:D.SUCCESSED,url:_,reqId:R},{logSource:i.RTC}),{code:L.SUCCESS,data:e}}O.warn(`request failed -> Request-Id: ${R}, status: ${m}, url: ${_}`),this._failedMs.push(...this._msInNavi.splice(a,1)),r.error(A.L_MEDIA_SERVICE_REQUEST_R,{status:D.FAILED,code:"",reqId:R,url:_,msg:`request error -> Request-Id: ${R}, status: ${m}, url: ${_}`},{logSource:i.RTC})}return{code:L.REQUEST_FAILED}}))}exchange(e,t){var r;return v(this,void 0,void 0,(function*(){const i=yield this._request("/exchange",e,t);if(i.code===L.SUCCESS&&(null===(r=i.data)||void 0===r?void 0:r.resultCode)===L.SUCCESS){const{urls:e}=i.data;e&&(this._configUrl=e.configUrl)}return i}))}exit(e){return v(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/exit",e,{});return t}))}broadcastSubscribe(e,t){return this._request("/broadcast/subscribe",e,t)}broadcastExit(e){return v(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/broadcast/exit",e,{});return{code:t}}))}setMcuConfig(e,t){return v(this,void 0,void 0,(function*(){if(r.info(A.L_MEDIA_SERVICE_SET_MCU_CONFIG_T,{headers:e,body:t},{logSource:i.RTC}),!this._configUrl)return O.warn("RCMediaService.setMcuConfig failed -> RCRTCCode.MCU_SERVER_NOT_FOUND"),r.error(A.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:D.FAILED,code:L.MCU_SERVER_NOT_FOUND,msg:"MCU not found"},{logSource:i.RTC}),{code:L.MCU_SERVER_NOT_FOUND};const s=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,o=zt(),n=Object.assign(Object.assign({},o),e),a=JSON.stringify(t),d=o["Request-Id"];O.info(`request -> Request-Id: ${d}, url: ${s}, headers: ${JSON.stringify(n)}, body: ${a}`);const{status:_,data:u}=yield this._runtime.httpReq({url:s,headers:n,body:a,method:c.POST});if(200===_){O.info(`request success -> Request-Id: ${d}`);const e=JSON.parse(u);return r.info(A.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:D.SUCCESSED,reqId:d},{logSource:i.RTC}),{code:e.resultCode,res:e}}return O.warn(`request failed -> Request-Id: ${d}, status: ${_}, url: ${s}`),r.error(A.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:D.FAILED,code:L.REQUEST_FAILED,msg:`request error -> Request-Id: ${d}, status: ${_}, url: ${s}`},{logSource:i.RTC}),{code:L.REQUEST_FAILED}}))}getCDNResourceInfo(e,t){return v(this,void 0,void 0,(function*(){r.info(A.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_T,{headers:e,url:t},{logSource:i.RTC});const s=zt(),o=Object.assign(Object.assign({},s),e),n=s["Request-Id"];O.info(`request -> Request-Id: ${n}, url: ${t}, headers: ${JSON.stringify(o)}`);const{status:a,data:d}=yield this._runtime.httpReq({url:t,headers:o,method:c.GET});if(200===a){O.info(`request success -> Request-Id: ${s["Request-Id"]}`);const e=JSON.parse(d);return r.info(A.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:D.SUCCESSED,reqId:s["Request-Id"]},{logSource:i.RTC}),{code:e.resultCode,res:e}}return O.warn(`request failed -> Request-Id: ${s["Request-Id"]}, status: ${a}, url: ${t}`),r.info(A.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:D.FAILED,code:L.REQUEST_FAILED,msg:`request error -> Request-Id: ${s["Request-Id"]}, status: ${a}, url: ${t}`},{logSource:i.RTC}),{code:L.REQUEST_FAILED}}))}}var Xt;Zt.isDetector=!1,Zt.msInDetector=[],Zt.detectorTime=0,Zt.detectValidMinute=72e5,Zt.naviRefetchCount=0,function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(Xt||(Xt={}));const er=(e,t)=>Math.round(8*t/e),tr=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},rr=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.round(e*r)},ir=(e,t,r,i)=>{if(0===t)return 0;if(!r||!i)return tr(e/t,3);const s=t-i;if(0===s)return 0;const o=e-r;return o<0||s<0?0:tr(o/s,3)},sr=e=>{const{jitter:t,rtt:r,packetsLostRate:i}=e;return!Bt(t)||!Bt(r)||0!==i};class or{constructor(e,t,r){this._rtcPeerConn=e,this._sdpSemantics=t,this._currentUserId=r,this._latestPacketsSent={},this._latestBytesSent={},this._latestBytesRecv={},this._latestPacketsRecv={}}updateBytesSent(e,t,r){let i,s;if(this._latestBytesSent[e]&&t<this._latestBytesSent[e].bytesSent&&this.clearLatestpacketsSent([e]),this._latestBytesSent[e]){const{bytesSent:o,timestamp:n}=this._latestBytesSent[e];i=t-o,s=r-n,this._latestBytesSent[e]={bytesSent:t,timestamp:r}}else i=t,s=1e3,this._latestBytesSent[e]={bytesSent:t,timestamp:r};return er(s,i)}updateBytesRecv(e,t,r){let i,s;if(this._latestBytesRecv[e]&&t<this._latestBytesRecv[e].bytesRecv&&this.clearLatestPacketsRecv([e]),this._latestBytesRecv[e]){const{bytesRecv:o,timestamp:n}=this._latestBytesRecv[e];i=t-o,s=r-n,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r}}else i=t,s=1e3,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r};return er(s,i)}updateSenderPacketsLost(e,t,r){let i;if(Object.prototype.hasOwnProperty.call(this._latestPacketsSent[e],"packetsSent")){const{packetsLost:s,packetsSent:o}=this._latestPacketsSent[e];i=ir(t,r,s,o),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=s===t?o:r}else i=ir(t,r),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=r;return i}updateReceiverPacketsLost(e,t,r){let i;if(this._latestPacketsRecv[e]){const{packetsLost:s,packetsRecv:o}=this._latestPacketsRecv[e];i=ir(t,r+t,s,o+s)}else i=ir(t,r);return this._latestPacketsRecv[e]={packetsLost:t,packetsRecv:r},i}clearLatestpacketsSent(e){e.forEach((e=>{if(parseInt(e.split("_").pop())===He.VIDEO_ONLY){const t=`${e}_tiny`;delete this._latestPacketsSent[t],delete this._latestBytesSent[t]}delete this._latestPacketsSent[e],delete this._latestBytesSent[e]}))}clearLatestPacketsRecv(e){e.forEach((e=>{delete this._latestPacketsRecv[e],delete this._latestBytesRecv[e]}))}parseRTCStatsReport(e){const t={};for(const r of e.keys())r.includes("RTCCodec_")||(t[r]=e.get(r));return t}formatRCRTCStateReport(e){const t={senders:[],receivers:[]};return r.info(A.L_ABSTRACT_STAT_PARSER_FORMAT_RTC_STATE_REPORT_O,{status:D.SUCCESSED,stats:e,reports:t},{logSource:i.RTC}),t}getAudioLevelList(e){return[]}getResourceIdByParseSdp(e){var t,r;const{ssrc:i}=e,s=e.kind||e.mediaType,o=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,n=null===(r=this._rtcPeerConn.currentRemoteDescription)||void 0===r?void 0:r.sdp;let a;a="unified-plan"===this._sdpSemantics?new RegExp("a=msid:(.*?) "):new RegExp(`a=ssrc:${i} msid:(.*?) `);const c=null==o?void 0:o.split("\r\nm="),d=null==c?void 0:c.filter((e=>e.includes(`a=ssrc:${i}`)))[0],_=null==d?void 0:d.match(a);let u=_?_[1]:"";if(u){if("audio"===s)return`${u}_0`;const e=u.replace(`${this._currentUserId}_`,"").split("_");return e.length>1&&"tiny"===e[1]?`${this._currentUserId}_${e[0]}_1_tiny`:`${u}_1`}const l=null==n?void 0:n.split("\r\nm="),h=null==l?void 0:l.filter((e=>e.includes(`a=ssrc:${i}`)))[0],R=null==h?void 0:h.match(a);return u=R?R[1]:"",u?`${u}_${"video"===s?1:0}`:""}isValidSender(e){var t;const r=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}isValidReceiver(e){var t;const r=null===(t=this._rtcPeerConn.currentRemoteDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}}class nr extends or{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let s=0,o=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const n=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const{id:a,kind:c,transportId:d,mediaSourceId:_,remoteId:u,packetsSent:l,bytesSent:h,trackId:R,encoderImplementation:m,pliCount:p,nackCount:S,firCount:T}=n;if(!R)return;let{framesPerSecond:C,frameWidth:I,frameHeight:E}=n;"video"!==c||I||E||C||(I=e[R].frameWidth,E=e[R].frameHeight,C=_?e[_].framesPerSecond:null);const g=e[u];let f=null,v=null,O=0;g&&(f=g.jitter,v=g.roundTripTime,O=g.packetsLost),s+=O;const L=this.getResourceIdByParseSdp(n);if(!L)return;const A=_?e[_].audioLevel:e[R].audioLevel;let D=null;!this._latestPacketsSent[L]&&(this._latestPacketsSent[L]={}),g?D=this.updateSenderPacketsLost(L,O,l):this._latestPacketsSent[L].crtPacketsSent=l;let N=this.updateBytesSent(L,h,r);N<0&&(N=0),o+=N,t.senders.push({id:a,trackId:L,kind:c,packetsLostRate:D,remoteResource:!1,audioLevel:A||0===A?rr(A):null,frameWidth:I,frameHeight:E,frameRate:C,bitrate:N,jitter:f?Math.round(1e3*f):f,rtt:v,encoderImplementation:m,pliCount:p,nackCount:S,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));i.filter((e=>/RTCRemoteInboundRtp(Video|Audio)Stream_/.test(e))).forEach((r=>{const{localId:i,jitter:s,roundTripTime:o,packetsLost:n}=e[r],a=t.senders.filter((e=>e.id===i))[0];if(a&&!sr(a)){const t=this.getResourceIdByParseSdp(e[a.id]);a.jitter=Math.round(1e3*s),a.rtt=o;const r=this._latestPacketsSent[t].crtPacketsSent;a.packetsLostRate=this.updateSenderPacketsLost(t,n,r)}}));let n=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const o=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:_,bytesReceived:u,framesPerSecond:l,kind:h,codecImplementationName:R,nackCount:m,pliCount:p}=o;if(!a)return;let{frameWidth:S,frameHeight:T,audioLevel:C}=o;"video"===h?S||T||(S=e[a].frameWidth,T=e[a].frameHeight):C||(C=e[a].audioLevel),s+=c;const I=this.getResourceIdByParseSdp(o),E=this.updateReceiverPacketsLost(I,c,d);let g=this.updateBytesRecv(I,u,r);g<0&&(g=0),n+=g,t.receivers.push({trackId:I,kind:h,packetsLostRate:E,remoteResource:!0,audioLevel:C||0===C?rr(C):null,frameWidth:S,frameHeight:T,frameRate:l,bitrate:g,jitter:_?Math.round(1e3*_):0,codecImplementationName:R,nackCount:m,pliCount:p,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:_,remoteCandidateId:u}=r,l=e[_],{ip:h,port:R,networkType:m}=l,p=e[u],{ip:S,port:T,protocol:C}=p;t.iceCandidatePair={IP:h,port:R,networkType:m,remoteIP:S,remotePort:T,protocol:C,bitrateRecv:n,bitrateSend:o,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:s},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTPAudioStream_/.test(e))).forEach((r=>{var i;const s=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(s))return;const{mediaSourceId:o,trackId:n}=s,a=this.getResourceIdByParseSdp(s),c=o&&e[o]?e[o].audioLevel:(null===(i=e[n])||void 0===i?void 0:i.audioLevel)||null;t.push({trackId:a,audioLevel:c||0===c?rr(c):null})}));return r.filter((e=>/^RTCInboundRTPAudioStream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:s}=i,o=i.audioLevel||e[s].audioLevel,n=this.getResourceIdByParseSdp(i);t.push({trackId:n,audioLevel:o||0===o?rr(o):null})})),t}}class ar extends or{formatRCRTCStateReport(e){const t=+new Date,r={senders:[],receivers:[],timestamp:t};let i=0,s=0,o=0;for(const n in e){const a=e[n],{type:c}=a;if("outbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(a))continue;const{id:o,kind:n,bytesSent:c,packetsSent:d,bitrateMean:_,framerateMean:u,nackCount:l,pliCount:h,remoteId:R}=a,{jitter:m,roundTripTime:p,packetsLost:S}=R?e[R]:{jitter:null,roundTripTime:null,packetsLost:0},T=this.getResourceIdByParseSdp(a);i+=S;let C=null;!this._latestPacketsSent[T]&&(this._latestPacketsSent[T]={}),R?C=this.updateSenderPacketsLost(T,S,d):this._latestPacketsSent[T].crtPacketsSent=d;let I=0;"video"===n?_&&(I=Math.floor(_/1e3)):I=this.updateBytesSent(T,c,t),I<0&&(I=0),s+=I,r.senders.push({trackId:T,kind:n,packetsLostRate:C,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:I,jitter:m?Math.round(1e3*m):null,rtt:p,encoderImplementation:null,pliCount:h,nackCount:l,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}if("remote-inbound-rtp"===c){const{localId:t}=a,i=this.getResourceIdByParseSdp(e[t]),s=r.senders.filter((e=>e.trackId===i))[0];s&&sr(s)&&(s.jitter=Math.round(1e3*a.jitter),s.rtt=a.rtt,s.packetsLostRate=this.updateSenderPacketsLost(i,a.packetsLost,this._latestPacketsSent[i].crtPacketsSent))}if("inbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(a))continue;const{id:e,packetsLost:s,bytesReceived:n,packetsReceived:c,jitter:d,framerateMean:_,kind:u,bitrateMean:l,nackCount:h,pliCount:R}=a,m=this.getResourceIdByParseSdp(a);i+=s;const p=this.updateReceiverPacketsLost(m,s,c);let S=0;"video"===u?l&&(S=Math.floor(l/1e3)):S=this.updateBytesRecv(m,n,t),S<0&&(S=0),o+=S,r.receivers.push({trackId:m,kind:u,packetsLostRate:p,remoteResource:!0,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(_),bitrate:S,jitter:d?Math.round(1e3*d):null,codecImplementationName:null,nackCount:h,pliCount:R,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}if("candidate-pair"===c&&"succeeded"===a.state){const t=e[a.localCandidateId],{address:n,port:c}=t,d=e[a.remoteCandidateId],{address:_,port:u,protocol:l}=d;r.iceCandidatePair={IP:n,port:c,networkType:null,remoteIP:_,remotePort:u,protocol:l,bitrateRecv:o,bitrateSend:s,rtt:null,availableOutgoingBitrate:null,availableIncomingBitrate:null,totalPacketsLost:i}}}return r.iceCandidatePair&&(r.iceCandidatePair.bitrateSend=s),r.iceCandidatePair&&(r.iceCandidatePair.bitrateRecv=o),r}getAudioLevelList(e){const t=[];for(const r in e){const i=e[r],{type:s}=i;if("outbound-rtp"===s){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}if("inbound-rtp"===s){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}}return t}}class cr extends or{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let s=0,o=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const s=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(s))return;const n=this.getResourceIdByParseSdp(s),{mediaType:a,transportId:c,remoteId:d,packetsSent:_,bytesSent:u,trackId:l,encoderImplementation:h,pliCount:R,nackCount:m,firCount:p}=s;if(!l)return;const{audioLevel:S,frameHeight:T,frameWidth:C}=e[l];let I=this.updateBytesSent(n,u,r);I<0&&(I=0),o+=I,t.senders.push({trackId:n,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:S||0===S?rr(S):null,frameWidth:C,frameHeight:T,frameRate:null,bitrate:I,jitter:null,rtt:null,encoderImplementation:h,pliCount:R,nackCount:m,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));let n=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const o=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:_,bytesReceived:u,mediaType:l,nackCount:h,pliCount:R}=o,m=this.getResourceIdByParseSdp(o);if(!a)return;const{frameHeight:p,frameWidth:S,audioLevel:T}=e[a];s+=c;const C=this.updateReceiverPacketsLost(m,c,d);let I=this.updateBytesRecv(m,u,r);I<0&&(I=0),n+=I,t.receivers.push({trackId:m,kind:l,packetsLostRate:C,remoteResource:!0,audioLevel:T||0===T?rr(T):null,frameWidth:S,frameHeight:p,frameRate:null,bitrate:I,jitter:_,codecImplementationName:null,nackCount:h,pliCount:R,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:_,remoteCandidateId:u}=r,l=e[_],{address:h,port:R}=l,m=e[u],{address:p,port:S,protocol:T}=m;t.iceCandidatePair={IP:h||null,port:R,networkType:null,remoteIP:p,remotePort:S,protocol:T,bitrateRecv:n,bitrateSend:o,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:s},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const{trackId:s,mediaType:o}=i;if("video"===o)return;const n=this.getResourceIdByParseSdp(i),a=e[s];t.push({trackId:n,audioLevel:a||0===a?rr(a):null})}));return r.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:s,mediaType:o}=i;if(!s||"video"===o)return;const{audioLevel:n}=e[s],a=this.getResourceIdByParseSdp(i);t.push({trackId:a,audioLevel:n||0===n?rr(n):null})})),t}}class dr{constructor(e,t){this.SDP=e,this.type=t,this.SDPHeader="",this.videoStreams=[],this.audioStreams=[];const r=this.getStreamIndex();this.spliteStreams(r)}get videoSdps(){return this.videoStreams.slice()}get audioSdps(){return this.audioStreams.slice()}static trimBlankLine(e){return e.replace(/\n\r\s*\r\n/g,"\r\n").replace(/\s+\r\n/g,"\r\n")}getStreamIndex(){const e=new RegExp("m=(?:video|audio)","img"),t=new Set([0]);let r=e.exec(this.SDP);for(;null!==r;)t.add(null==r?void 0:r.index),r=e.exec(this.SDP);return t.add(this.SDP.length),[...t]}spliteStreams(e){this.SDPHeader=this.SDP.substring(e[0],e[1]).replace(/\r\ns=-/g,`\r\ns=${(new Date).valueOf()}`);for(let t=1;t<e.length;t++){const r=this.SDP.substring(e[t],e[t+1]);/^\bm=video\b/.test(r)?this.videoStreams.push(r):this.audioStreams.push(r)}}static clearInactiveOrRecvonly(e){return/\ba=(recvonly|inactive)\b/.test(e)?e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,""):e}setHeaderBitrate(e){this.SDPHeader=this.SDPHeader.replace(/(\r\ns=[^\r\n]+)/gi,`$1\r\nc=IN IP4 0.0.0.0\r\nb=AS:${e*dr.KBitrate}\r\nb=TIAS:${e*dr.KBitrate*850}`)}setAudiosBitrate(e){return O.info(A.L_RTC_SDP_BITRATE_O,{bitrate:e,msg:"SDP setAudiosBitrate"},{logSource:i.RTC}),this.audioStreams=this.audioStreams.map((t=>this.setAudioItemBitrate(t,e))),this}setAudioBitrateWithStreamId(e,t){return O.info(A.L_RTC_SDP_BITRATE_O,{bitrate:e,streamId:t,msg:"SDP setAudioBitrateWithStreamId"},{logSource:i.RTC}),this.audioStreams=this.audioStreams.map((r=>new RegExp(`\\bmsid:${t}\\b`,"ig").test(r)?this.setAudioItemBitrate(r,e):r)),this}setAudioBitrateWithMid(e,t){return O.info(A.L_RTC_SDP_BITRATE_O,{bitrate:e,mid:t,msg:"SDP setAudioBitrateWithMid"},{logSource:i.RTC}),this.audioStreams=this.audioStreams.map((r=>new RegExp(`\\bmid:${t}\\b`,"ig").test(r)?this.setAudioItemBitrate(r,e):r)),this}setAudioItemBitrate(e,t){if(0===t.max&&/\ba=inactive\b/gi.test(e))return e;if(!/\bmaxaveragebitrate\b/gi.test(e)){const r=["$1","maxaveragebitrate="+t.max*dr.KBitrate];e=e.replace(/(\buseinbandfec=[^\r\n]+)/gi,r.join(";"))}return this.addAudioBlineAS(e,t)}addAudioBlineAS(e,t){return/\bb=AS:\d+\b/gi.test(e)?e:e.replace(/(\bc=IN[^\r\n]+)/gi,`$1\r\nb=AS:${t.max*dr.KBitrate}\r\nb=TIAS:${t.max*dr.KBitrate*850}`)}setVideosBitrate(e){return O.info(A.L_RTC_SDP_BITRATE_O,{bitrate:e,msg:"SDP setVideosBitrate"},{logSource:i.RTC}),this.videoStreams=this.videoStreams.map((t=>this.setVideoItemBitrate(t,e))),this}setVideoBitrateWithStreamId(e,t){return O.info(A.L_RTC_SDP_BITRATE_O,{bitrate:e,streamId:t,msg:"SDP setVideoBitrateWithStreamId"},{logSource:i.RTC}),this.videoStreams=this.videoStreams.map((r=>new RegExp(`\\bmsid:${t}\\b`,"ig").test(r)?this.setVideoItemBitrate(r,e):r)),this}setVideoBitrateWithMid(e,t){return O.info(A.L_RTC_SDP_BITRATE_O,{bitrate:e,mid:t,msg:"SDP setVideoBitrateWithMid"},{logSource:i.RTC}),this.videoStreams=this.videoStreams.map((r=>new RegExp(`\\bmid:${t}\\b`,"ig").test(r)?this.setVideoItemBitrate(r,e):r)),this}setVideoItemBitrate(e,t){if(0===t.max&&/\ba=inactive\b/gi.test(e))return e;if(!/\bx-google-max-bitrate\b/.test(e)){console.log("old:",e);const r=["$1","x-google-max-bitrate="+t.max*dr.KBitrate,"x-google-min-bitrate="+t.min*dr.KBitrate,`x-google-start-bitrate=${t.start||t.max*dr.KBitrate*.7}`];e=e.replace(/(\bprofile-level-id=42[e0]01f\b)/gi,r.join(";"))}return this.addVideoBlineAS(e,t)}addVideoBlineAS(e,t){return/\bb=AS:\d+\b/gi.test(e)?e:e.replace(/(\bc=IN[^\r\n]+)/gi,`$1\r\nb=AS:${t.max*dr.KBitrate}\r\nb=TIAS:${t.max*dr.KBitrate*850}`)}clearnSsrcWithMid(e,t){return this.audioStreams=this.audioStreams.map((r=>new RegExp(`\\bmid:${e}\\b`,"ig").test(r)?this.clearSSRC(r,t):r)),this.videoStreams=this.videoStreams.map((r=>new RegExp(`\\bmid:${e}\\b`,"ig").test(r)?this.clearSSRC(r,t):r)),this}clearSSRC(e,t){if(t===ur.SENDONLY){if(/\ba=sendonly\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}if(t===ur.RECVONLY){if(/\ba=recvonly\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}if(t===ur.INACTIVE){if(/\ba=inactive\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}return e}}var _r,ur,lr,hr,Rr,mr,pr,Sr,Tr,Cr,Ir,Er,gr,fr,vr,Or,Lr;dr.KBitrate=1,function(e){e.PLANB="plan-b",e.UNIFIEDPLAN="unified-plan"}(_r||(_r={})),function(e){e.SENDONLY="sendonly",e.RECVONLY="recvonly",e.INACTIVE="inactive"}(ur||(ur={}));class Ar{constructor(e){this._peer=e,this._outboundStreams={}}static setSdpSemantics(e){r.info(A.L_A_SDP_STRATEGY_SET_SDP_SEMANTICS_O,{status:D.SUCCESSED,sdpSemantics:e},{logSource:i.RTC});const{browser:t,version:s,supportsUnifiedPlan:o}=Mt;r.debug(`sdpSemantics, browser: ${t}, version: ${s}, supportsUnifiedPlan: ${o}`),o?/chrome/i.test(t)?this._sdpSemantics=s>92?"unified-plan":s<72?"plan-b":e:/firefox/i.test(t)?this._sdpSemantics="unified-plan":/safari/i.test(t)?this._sdpSemantics=s<12?"plan-b":"unified-plan":this._sdpSemantics="unified-plan":this._sdpSemantics="plan-b"}static getSdpSemantics(){return Ar._sdpSemantics}getOutboundVideoInfo(){const e=[];for(const t in this._outboundStreams){const r=this._outboundStreams[t].getVideoTracks()[0];if(!r)continue;const i=/_tiny$/.test(t),{width:s,height:o}=ft(r);e.push({trackId:r.id,simulcast:i?Xt.TINY:Xt.NORMAL,resolution:`${s}x${o}`})}return e}setRemoteAnswer(e){return v(this,void 0,void 0,(function*(){e=dr.trimBlankLine(e),O.info(`set remote answer -> ${e}`);try{yield this._peer.setRemoteDescription({type:"answer",sdp:e})}catch(e){return O.error(e),r.info(A.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:D.FAILED,code:"",msg:e},{logSource:i.RTC}),L.SET_REMOTE_DESCRIPTION_FAILED}return r.info(A.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:D.SUCCESSED,sdp:e},{logSource:i.RTC}),L.SUCCESS}))}getStatParsr(e,t,r){return/chrome/i.test(Mt.browser)?new nr(e,t,r):/Firefox/i.test(Mt.browser)?new ar(e,t,r):/Safari/i.test(Mt.browser)?new cr(e,t,r):null}resetSdp(e){return dr.trimBlankLine(e)}}class Dr extends dr{constructor(e){super(e,_r.PLANB),this.SDP=e}stringify(){const e=[this.SDPHeader];[...this.audioStreams,...this.videoStreams].forEach((t=>{const r=t.match(/\ba=mid:(video|audio)\b/),i=dr.clearInactiveOrRecvonly(t);r&&r[1]===Ze.AUDIO&&(e[1]=i),r&&r[1]===Ze.VIDEO&&(e[2]=i)}));const t=e.join("");return dr.trimBlankLine(t)}setAudioBitrateWithStreamId(e,t){return O.warn("plan-b not support set Audio Bitrate With Stream Id"),this}setVideoBitrateWithStreamId(e,t){return O.warn("plan-b not support set Video Bitrate With Stream Id"),this}}class Nr extends Ar{constructor(){super(...arguments),this.senders={},this._localTracks=[]}addLocalTrack(e){this._localTracks.includes(e)||this._localTracks.push(e);const t=e.getStreamId(),r=e.__innerGetMediaStreamTrack(),i=this._outboundStreams[t]||(this._outboundStreams[t]=new MediaStream);i.getTracks().forEach((e=>{e.kind===r.kind&&i.removeTrack(e)})),i.addTrack(r);const s=e.getTrackId(),o=this.senders[s];o?o.replaceTrack(r):this.senders[s]=this._peer.addTrack(r,i)}removeLocalTrack(e){const t=this._localTracks.findIndex((t=>t===e));t>=0&&this._localTracks.splice(t,1);const r=e.getTrackId(),i=this.senders[r];i&&(i.replaceTrack(null),this._peer.removeTrack(i),delete this.senders[r])}updateSubRemoteTracks(e){}updateRecvTransceiverMap(e,t){}setBitrate(e,t,r){this._maxBitrate=e,this._minBitrate=t,this._startBitrate=r||.7*e}createOffer(e){return v(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0});for(const e in this._outboundStreams){const r=this._outboundStreams[e].id;t.sdp=t.sdp.replace(new RegExp(r,"g"),e)}t.sdp&&(t.sdp=dr.clearInactiveOrRecvonly(t.sdp));const s=Qt.getMemo();return r.info(A.L_QS_SET_LOCAL_DESCRIPTION_O,{identify:s.qualityStatusId},{logSource:i.RTC}),yield this._peer.setLocalDescription(t),{type:"offer",semantics:"plan-b",sdp:t.sdp}}))}setRemoteAnswer(e){return e=this.resetSdp(e),super.setRemoteAnswer(e)}resetSdp(e){const t=new Dr(e),r={max:0,min:0},i={max:0,min:0};return this._localTracks.forEach((e=>{const{min:t,max:s,start:o}=e.getBitrate();e.isAudioTrack()&&(i.max=i.max<s?s:i.max,i.min=i.min>t?t:i.min,i.max===s?i.start=o:i.start=.7*i.max),e.isVideoTrack()&&(r.max=r.max<s?s:r.max,r.min=r.min>t?t:r.min,r.max===s?r.start=o:r.start=.7*r.max)})),t.setAudiosBitrate(i),t.setVideosBitrate(r),t.stringify()}}class br extends dr{constructor(e){super(e,_r.UNIFIEDPLAN),this.SDP=e}stringify(){const e=[this.SDPHeader];[...this.audioStreams,...this.videoStreams].forEach((t=>{const r=t.match(/\ba=mid:(\d+)\b/);r&&r[1]&&(e[+r[1]+1]=t)})),this.SDPHeader="",this.videoStreams=[],this.audioStreams=[];const t=e.join("");return dr.trimBlankLine(t)}}class kr{static splitSections(e){return e.split("\nm=").map(((e,t)=>`${(t>0?`m=${e}`:e).trim()}\r\n`))}static getMediaSections(e){const t=kr.splitSections(e);return t.shift(),t}static parseExtmap(e){const t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}}static splitLines(e){return e.trim().split("\n").map((e=>e.trim()))}static parseMLine(e){const t=kr.splitLines(e)[0].substr(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}}static matchPrefix(e,t){return kr.splitLines(e).filter((e=>0===e.indexOf(t)))}static parseMsid(e){let t;const r=kr.matchPrefix(e,"a=msid:");if(1===r.length)return t=r[0].substr(7).split(" "),{stream:t[0],track:t[1]};const i=kr.matchPrefix(e,"a=ssrc:").map((e=>kr.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return i.length>0&&i[0].value?(t=i[0].value.split(" "),{stream:t[0],track:t[1]}):{stream:"",track:""}}static parseSsrcMedia(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r}static getMid(e){const t=kr.matchPrefix(e,"a=mid:")[0];if(t)return t.substr(6)}}class yr extends Ar{constructor(){super(...arguments),this._sendTransceiver={},this._localTracks={},this._recvAudio=[],this._recvVideo=[],this._recvTransceiver={},this._subedTracks=[],this.midMsid={}}setBitrate(e,t,r){O.warn("the interface named `setBitrate` is invalid while sdpSemantics value is `unified-plan`")}addLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId(),i=e.__innerGetMediaStreamTrack();this._localTracks[t]=e;const s=this._outboundStreams[r]||(this._outboundStreams[r]=new MediaStream);s.getTracks().forEach((e=>{e.kind===i.kind&&s.removeTrack(e)})),s.addTrack(i);const o=this._sendTransceiver[t];o?(o.sender.replaceTrack(i),o.direction="sendonly"):this._sendTransceiver[t]=this._peer.addTransceiver(i,{direction:"sendonly",streams:[s]})}removeLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId();e.__innerGetMediaStreamTrack(),delete this._localTracks[t];const i=this._sendTransceiver[t];if(!i)return;i.direction="inactive",this._peer.removeTrack(i.sender),i.sender.replaceTrack(null);const s=this._outboundStreams[r];(e.isAudioTrack()?s.getAudioTracks():s.getVideoTracks()).forEach((e=>s.removeTrack(e)));const o=this._sendTransceiver[`${t}_tiny`];if(!o||"inactive"===o.direction)return;o.direction="inactive";const{sender:n}=o,a=n.track;this._peer.removeTrack(n),n.replaceTrack(null);this._outboundStreams[`${r}_tiny`].removeTrack(a),a.stop()}updateRecvTransceiverMap(e,t){const{mediaType:r}=Lt(e);this._recvTransceiver[e]=t;const i=r===He.AUDIO_ONLY?this._recvAudio:this._recvVideo,s=i.findIndex((e=>e===t));s>=0&&i.splice(s,1)}updateSubRemoteTracks(e){const t=e.slice(),r=this._subedTracks.slice();this._subedTracks=e.slice();for(let e=t.length-1;e>=0;e-=1){const i=t[e],s=r.findIndex((e=>e===i));s>=0&&(t.splice(e,1),r.splice(s,1))}r.length&&r.forEach((e=>{const t=e.getTrackId();e.__innerSetMediaStreamTrack(void 0);const r=this._recvTransceiver[t];r&&(r.direction="inactive")}));const i={audio:0,video:0};t.length&&t.forEach((e=>{const t=e.isAudioTrack()?"audio":"video",r=this._recvTransceiver[e.getTrackId()];r?r.direction="recvonly":i[t]+=1}));for(let e=this._recvAudio.length;e<i.audio;e+=1)this._recvAudio.push(this._peer.addTransceiver("audio",{direction:"recvonly"}));for(let e=this._recvVideo.length;e<i.video;e+=1)this._recvVideo.push(this._peer.addTransceiver("video",{direction:"recvonly"}))}createOffer(e){return v(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e});let s=t.sdp;for(const e in this._outboundStreams){const t=this._outboundStreams[e].id;s=s.replace(new RegExp(t,"g"),e)}s=this.resetOfferSdp(s),s=s.replace(/(a=ice-options:trickle)/g,"$1\r\na=ice-options:renomination"),t.sdp=s;const o=Qt.getMemo();return r.info(A.L_QS_SET_LOCAL_DESCRIPTION_O,{identify:o.qualityStatusId},{logSource:i.RTC}),yield this._peer.setLocalDescription(t),{type:"offer",semantics:"unified-plan",sdp:s}}))}setRemoteAnswer(e){e=this.resetAnswerSdp(e);const t=/[\r\n]+\r\n[\r\n]+/g;return t.test(e)&&(O.warn(`answer sdp invalid -> ${JSON.stringify(e)}`),e=e.replace(t,"\r\n")),super.setRemoteAnswer(e)}resetOfferSdp(e){var t;const r=new br(e);for(const i in this._sendTransceiver){const s=this._sendTransceiver[i],o=null===(t=s.sender.track)||void 0===t?void 0:t.kind;let{direction:n,mid:a}=s;if(!a){kr.getMediaSections(e).forEach((e=>{kr.parseExtmap(e);const{kind:t}=kr.parseMLine(e);let{stream:r}=kr.parseMsid(e);const s=kr.getMid(e);"video"===o?/tiny$/.test(r)?r=r.replace(/tiny$/gi,"1_tiny"):r+="_1":r+="_0",r===i&&o===t&&s&&(a=s)}))}if(a){if(n===ur.SENDONLY){const e=this._localTracks[i],t=null==e?void 0:e.getBitrate();o===Ze.AUDIO&&t&&r.setAudioBitrateWithMid(t,a),o===Ze.VIDEO&&t&&r.setVideoBitrateWithMid(t,a)}n===ur.INACTIVE&&r.clearnSsrcWithMid(a,ur.INACTIVE)}}for(const e in this._recvTransceiver){const t=this._recvTransceiver[e],{direction:i,mid:s}=t;s&&i===ur.INACTIVE&&r.clearnSsrcWithMid(s,ur.RECVONLY)}return r.stringify()}resetAnswerSdp(e){var t;const r=new br(e);for(const e in this._sendTransceiver){const i=this._sendTransceiver[e],{mid:s}=i;if(s){const o=this._localTracks[e],n=null==o?void 0:o.getBitrate(),a=null===(t=i.sender.track)||void 0===t?void 0:t.kind;a===Ze.AUDIO&&n&&r.setAudioBitrateWithMid(n,s),a===Ze.VIDEO&&n&&r.setVideoBitrateWithMid(n,s)}}return r.stringify()}}!function(e){e[e.new=0]="new",e[e.checking=1]="checking",e[e.connected=2]="connected",e[e.completed=3]="completed",e[e.failed=4]="failed",e[e.disconnected=5]="disconnected",e[e.closed=6]="closed"}(lr||(lr={}));class Ur extends t{constructor(e,t,r,i){super(),this._pcName=e,this._reTryExchange=t,this._currentUserId=r,this._polarisReport=i,this.pubLocalTracks={},this._reTryExchangeTimer=null,this._reportStatsTimer=null,this._reportR3R4ToPolarisTimer=null,this._isDestroyed=!1,this._reportStatsData=null,this._originReportStatsData=null,this._reportListener=null;const s=Ar.getSdpSemantics(),o=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:s});this._sdpStrategy="plan-b"===s?new Nr(o):new yr(o),this._rtcPeerConn.oniceconnectionstatechange=this._onICEConnectionStateChange.bind(this),this._rtcPeerConn.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._rtcPeerConn.ontrack=this._onTrackReady.bind(this),this.reportParser=this._sdpStrategy.getStatParsr(this._rtcPeerConn,s,this._currentUserId)}getName(){return this._pcName}getLocalTracks(){return r.info(A.L_RTC_PEER_CONNECTION_GET_LOCAL_TRACKS_O,{status:D.SUCCESSED,trackIds:Object.keys(this.pubLocalTracks)},{logSource:i.RTC}),Object.values(this.pubLocalTracks)}_onConnectionStateChange(){O.info(`onconnectionstatechange -> ${this._rtcPeerConn.connectionState}, ${this._pcName}`),r.info(A.L_RTC_PEER_CONNECTION_CONNECTION_STATE_S,{status:D.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:i.RTC})}startAutoExecute(e=1e3){this._reportStatsTimer=setTimeout((()=>{this._reportHandle(e),this._reportStatsTimer=this.startAutoExecute()}),e)}stopAutoExecute(){clearTimeout(this._reportStatsTimer)}_onICEConnectionStateChange(){var e,t,s,o,n,a,c,d,_,u,l,m,p,S,T,C,I,E,g,f,v,L,N,b,k,y;const U=Date.now(),P=Qt.getMemo();P.iceStatusData||(P.iceStatusData={}),P.iceNewStatusData&&(P.iceOldStatusData=P.iceNewStatusData),P.iceNewStatusData={start:U,status:this._rtcPeerConn.iceConnectionState};const M={dur:0,pices:0,ices:0,rid:null===(e=P.joinRoomData)||void 0===e?void 0:e.roomId,csnid:null===(t=P.clientData)||void 0===t?void 0:t.clientSessionId,snid:"",time:0,rcdts:[],lcdts:[],cncdts:null,cr:"unknown",net:"unknown",uid:this._currentUserId};if(P.qualitySubscribeReportData=M,O.info(`oniceconnectionstatechange -> ${this._rtcPeerConn.iceConnectionState}, ${this._pcName}`),r.info(A.L_QS_SET_LOCAL_DESCRIPTION_O,{identify:P.qualityStatusId},{logSource:i.RTC}),"connected"===this._rtcPeerConn.iceConnectionState){if(!(null===(s=P.iceStatusData)||void 0===s?void 0:s.subscribeNotReport)&&(null===(o=P.iceStatusData)||void 0===o?void 0:o.subscribe)){P.iceStatusData.subscribeNotReport=!0;const e=P.iceStatusData.notFirst?0:(null===(n=P.iceNewStatusData)||void 0===n?void 0:n.start)-(null===(c=null===(a=P.iceStatusData)||void 0===a?void 0:a.subscribe)||void 0===c?void 0:c.time)||0,t=JSON.stringify(Object.assign(P.qualitySubscribeReportData,{dur:e,pices:lr[null===(d=P.iceOldStatusData)||void 0===d?void 0:d.status],ices:lr[null===(_=P.iceNewStatusData)||void 0===_?void 0:_.status],time:U}));h(R.STATISTICS,A.L_QS_SUB_ICE_STATUS_S,t,i.RTC)}if(!(null===(u=P.iceStatusData)||void 0===u?void 0:u.publishNotReport)&&(null===(l=P.iceStatusData)||void 0===l?void 0:l.publish)){P.iceStatusData.publishNotReport=!0;const e=P.iceStatusData.notFirst?0:(null===(m=P.iceNewStatusData)||void 0===m?void 0:m.start)-(null===(S=null===(p=P.iceStatusData)||void 0===p?void 0:p.publish)||void 0===S?void 0:S.time)||0,t=JSON.stringify(Object.assign(P.qualitySubscribeReportData,{dur:e,pices:lr[null===(T=P.iceOldStatusData)||void 0===T?void 0:T.status],ices:lr[null===(C=P.iceNewStatusData)||void 0===C?void 0:C.status],time:U}));h(R.STATISTICS,A.L_QS_PUB_ICE_STATUS_S,t,i.RTC)}P.iceStatusData.notFirst=!0;const e=JSON.stringify(Object.assign(P.qualitySubscribeReportData,{dur:(null===(I=P.iceNewStatusData)||void 0===I?void 0:I.start)-(null===(E=P.iceOldStatusData)||void 0===E?void 0:E.start),pices:lr[null===(g=P.iceOldStatusData)||void 0===g?void 0:g.status],ices:lr[null===(f=P.iceNewStatusData)||void 0===f?void 0:f.status],time:U,cncdts:[]}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,e,i.RTC),this._reportStatsTimer&&this.stopAutoExecute(),this.startAutoExecute()}if("failed"===this._rtcPeerConn.iceConnectionState||"disconnected"===this._rtcPeerConn.iceConnectionState){const e=JSON.stringify(Object.assign(P.qualitySubscribeReportData,{dur:(null===(v=P.iceNewStatusData)||void 0===v?void 0:v.start)-(null===(L=P.iceOldStatusData)||void 0===L?void 0:L.start),pices:lr[null===(N=P.iceOldStatusData)||void 0===N?void 0:N.status],ices:lr[null===(b=P.iceNewStatusData)||void 0===b?void 0:b.status],time:U}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,e,i.RTC),O.warn(`${this._pcName} iceconenction state is failed, exchange SDP to try again.`),r.error(A.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:D.FAILED,code:"",msg:`${this._pcName} iceconenction state is ${this._rtcPeerConn.iceConnectionState}, exchange SDP to try again.`},{logSource:i.RTC}),this._reTryExchange(),this._reTryExchangeTimer=setInterval(this._reTryExchange,15e3)}try{null===(y=null===(k=this._reportListener)||void 0===k?void 0:k.onICEConnectionStateChange)||void 0===y||y.call(k,this._rtcPeerConn.iceConnectionState,this._pcName)}catch(e){O.error("onICEConnectionStateChange error",e,this._pcName),r.error(A.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:D.FAILED,code:"",msg:`${this._pcName}, ${e}`},{logSource:i.RTC})}r.info(A.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:D.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:i.RTC})}_onTrackReady(e){if(!e.streams.length)return;const t=e.streams[0].id,{track:s}=e.receiver,o=[t,"audio"===s.kind?He.AUDIO_ONLY:He.VIDEO_ONLY].join("_");this._updateRecvTransceiverMap(o,e.transceiver);const n=Qt.getMemo();r.info(A.L_QS_TRACK_READY_O,{identify:n.qualityStatusId},{logSource:i.RTC}),this.emit(Ur.__INNER_EVENT_TRACK_READY__,e)}setBitrate(e,t,s){return v(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(e,t,s),r.info(A.L_RTC_PEER_CONNECTION_SET_BITRATE_O,{status:D.SUCCESSED,max:e,min:t,start:s},{logSource:i.RTC})}))}createOffer(e){return v(this,void 0,void 0,(function*(){const t=yield this._sdpStrategy.createOffer(e);return O.debug(`offer -> ${JSON.stringify(t.sdp)}`),r.info(A.L_RTC_PEER_CONNECTION_CREATE_OFFER_O,{status:D.SUCCESSED,offerSDP:t.sdp},{logSource:i.RTC}),t}))}setRemoteAnswer(e){return v(this,void 0,void 0,(function*(){return O.debug(`answer -> ${JSON.stringify(e)}`),r.info(A.L_RTC_PEER_CONNECTION_SET_REMOTE_ANSWER_O,{status:D.SUCCESSED,answer:e},{logSource:i.RTC}),this._sdpStrategy.setRemoteAnswer(e)}))}getLocalTrack(e){return this.pubLocalTracks[e]||null}addLocalTrack(e){this.pubLocalTracks[e.getTrackId()]=e,this._sdpStrategy.addLocalTrack(e),e.off(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.on(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.on(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),r.info(A.L_RTC_PEER_CONNECTION_ADD_LOCAL_TRACK_O,{status:D.SUCCESSED,trackId:e.getTrackId()},{logSource:i.RTC})}removeLocalTrackById(e){const t=this.getLocalTrack(e);t?(r.info(A.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:D.SUCCESSED,trackId:e},{logSource:i.RTC}),this.removeLocalTrack(t)):r.warn(A.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:D.FAILED,code:"",msg:"track not found"},{logSource:i.RTC})}removeAllLocalTrack(){Object.keys(this.pubLocalTracks).forEach((e=>{/_tiny$/.test(e)||this.removeLocalTrackById(e)})),r.info(A.L_RTC_PEER_CONNECTION_REMOVE_ALL_LOCAL_TRACK_O,{status:D.SUCCESSED},{logSource:i.RTC})}removeLocalTrack(e){const t=e.getTrackId();delete this.pubLocalTracks[t],this._sdpStrategy.removeLocalTrack(e),e.__innerSetPublished(!1),e.off(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this);const s=`${t}_tiny`,o=this.getLocalTrack(s);o&&(this._sdpStrategy.removeLocalTrack(o),delete this.pubLocalTracks[s],o.destroy()),r.info(A.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_O,{status:D.SUCCESSED,trackId:t},{logSource:i.RTC})}_updateRecvTransceiverMap(e,t){this._sdpStrategy.updateRecvTransceiverMap(e,t)}updateSubRemoteTracks(e){this._sdpStrategy.updateSubRemoteTracks(e),r.info(A.L_RTC_PEER_CONNECTION_UPDATE_SUB_REMOTE_TRACKS_O,{status:D.SUCCESSED,trackIds:e.map((e=>e.getTrackId()))},{logSource:i.RTC})}getOutboundVideoInfo(){return this._sdpStrategy.getOutboundVideoInfo()}_onLocalTrackMuted(e,t){const s=this.getLocalTrack(`${e.getTrackId()}_tiny`);s&&(s.__innerGetMediaStreamTrack().enabled=!e.isLocalMuted()),this.emit(ot.__INNER_EVENT_MUTED_CHANGE__,e,t),r.info(A.L_RTC_PEER_CONNECTION_LOCAL_TRACK_MUTED_O,{status:D.SUCCESSED,trackId:e.getTrackId()},{logSource:i.RTC})}_onLocalTrackDestroied(e){this.emit(ot.__INNER_EVENT_DESTROY__,e)}registerReportListener(e){this._reportListener=e}_createRCRTCStateReport(e){const{timestamp:t,iceCandidatePair:r,senders:i,receivers:s}=JSON.parse(JSON.stringify(e));null==r||delete r.totalPacketsLost;for(const e in r)Bt(r[e])&&delete r[e];return{timestamp:t,iceCandidatePair:r,senders:i.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),receivers:s.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),pcName:this._pcName}}_getStatsData(e=1e3){var t,r,i;return v(this,void 0,void 0,(function*(){let s=null;if((null===(t=this._originReportStatsData)||void 0===t?void 0:t.timestamp)&&this._originReportStatsData.timestamp>Date.now()-e)s=this._originReportStatsData.data;else{const e=yield this._rtcPeerConn.getStats();s=null===(r=this.reportParser)||void 0===r?void 0:r.parseRTCStatsReport(e),this._originReportStatsData={data:s,timestamp:Date.now()}}return null===(i=this.reportParser)||void 0===i?void 0:i.formatRCRTCStateReport(s)}))}getAudioLevelReportData(e=1e3){var t,r,i;return v(this,void 0,void 0,(function*(){let s=null;if((null===(t=this._originReportStatsData)||void 0===t?void 0:t.timestamp)&&this._originReportStatsData.timestamp>Date.now()-e)s=this._originReportStatsData.data;else{const e=yield this._rtcPeerConn.getStats();s=null===(r=this.reportParser)||void 0===r?void 0:r.parseRTCStatsReport(e),this._originReportStatsData={data:s,timestamp:Date.now()}}if(!s)return[];return null===(i=this.reportParser)||void 0===i?void 0:i.getAudioLevelList(s)}))}_reportHandle(e){var t,r;return v(this,void 0,void 0,(function*(){const i=yield this._getStatsData(e);if(!i)return;this._reportStatsData=i;const s=this._createRCRTCStateReport(i);null===(r=null===(t=this._reportListener)||void 0===t?void 0:t.onStateReport)||void 0===r||r.call(t,s)}))}_getCacheStatsData(){return this._reportStatsData}_sendR3R4Data(){var e;return v(this,void 0,void 0,(function*(){const t=this._getCacheStatsData();if(!t)return!0;if(t.senders.length||t.receivers.length){return yield null===(e=this._polarisReport)||void 0===e?void 0:e.sendR3R4Data(t)}}))}__reportR3R4ToPolaris(){return v(this,void 0,void 0,(function*(){clearTimeout(this._reportR3R4ToPolarisTimer),yield this._sendR3R4Data(),this._reportR3R4ToPolarisTimer=setTimeout((()=>{this.__reportR3R4ToPolaris()}),2e3)}))}getRTCPeerConn(){return this._rtcPeerConn}destroy(){this.clear(),this.clearReTryExchangeTimer(),clearTimeout(this._reportR3R4ToPolarisTimer),this._reportStatsTimer&&(this.stopAutoExecute(),this._reportStatsTimer=null),this.registerReportListener(null),this._rtcPeerConn.close(),this._isDestroyed=!0,this.reportParser=null,r.info(A.L_RTC_PEER_CONNECTION_DESTROY_O,{status:D.SUCCESSED},{logSource:i.RTC})}clearReTryExchangeTimer(){clearInterval(this._reTryExchangeTimer),this._reTryExchangeTimer=null}isDestroyed(){return this._isDestroyed}}Ur.__INNER_EVENT_TRACK_READY__="inner-track-ready",function(e){e[e.DISABLE=0]="DISABLE",e[e.ENABLE=1]="ENABLE"}(hr||(hr={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(Rr||(Rr={}));class Pr{constructor(e,t,r,i,s=Rr.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=i,this._userRole=s}_send(e){return v(this,void 0,void 0,(function*(){let t=!1;if(this._context.getConnectionStatus()!==_.CONNECTED)return t;return t=(yield this._context.setRTCState(this._roomId,e))===a.SUCCESS,t}))}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=bt(),this._runtime.localStorage.setItem(e,t)),t}_getRealResourceId(e){let t=e;const r=e.indexOf("_tiny");return r>-1&&(t=e.slice(0,r)),t}_getPolarisTrackId(e){let t="";const r=e.split("_");if(e.includes("_tiny")){const e=r.pop(),i=parseInt(r.pop())===He.AUDIO_ONLY?"audio":"video",s=r.pop();t=[r.join("_"),s,e,i].join("_")}else{const e=parseInt(r.pop())===He.AUDIO_ONLY?"audio":"video",i=r.pop();t=[r.join("_"),i,e].join("_")}return t}sendR3R4Data(e){return v(this,void 0,void 0,(function*(){const{iceCandidatePair:t,senders:r,receivers:i}=e,s=(null==t?void 0:t.bitrateSend)||-1,o=(null==t?void 0:t.bitrateRecv)||-1,n=(null==t?void 0:t.networkType)||"unknown",a=(null==t?void 0:t.rtt)||-1,c=`${(null==t?void 0:t.IP)||-1}:${null==t?void 0:t.port}`,d=(null==t||t.remoteIP,null==t||t.remotePort,(null==t?void 0:t.availableIncomingBitrate)||-1),_=(null==t?void 0:t.availableOutgoingBitrate)||-1,u=(null==t?void 0:t.totalPacketsLost)||-1,l=this._context.getCurrentId();let h=`R3\t${s}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${_}\t${u}\t${l}\r`,R=`R4\t${o}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${_}\t${u}\t${l}\r`;const m=r.map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:s,bitrate:o,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:_,jitter:u,nackCount:l,pliCount:h,rtt:R,googFirsSent:m,encoderImplementation:p}=e,S=this._getPolarisTrackId(r),T=this._getRealResourceId(r);return{trackId:S,googCodecName:p||String(-1),audioLevel:i||0===i?i:-1,bitrate:o||0===o?o:-1,packetsLostRate:n||0===n?n:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:h||0===h?h:-1,rtt:R||-1,googFirsSent:m,samplingRate:s,googRenderDelayMs:_,encoderImplementation:p||String(-1),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(T))||void 0===t?void 0:t.isLocalMuted())?hr.DISABLE:hr.ENABLE}})),p=i.filter((e=>!!e.trackId)).map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:s,bitrate:o,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:_,jitter:u,nackCount:l,pliCount:h,rtt:R,googFirsReceived:m,codecImplementationName:p}=e,S=this._getPolarisTrackId(r),T=this._getRealResourceId(r);return{trackId:S,googCodecName:p||String(-1),audioLevel:i||0===i?i:-1,bitrate:o||0===o?o:-1,packetsLostRate:n||0===n?n:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:h||0===h?h:-1,rtt:R||-1,googFirsReceived:m,samplingRate:s,googRenderDelayMs:_,codecImplementationName:p||String(-1),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(T))||void 0===t?void 0:t.isLocalMuted())?hr.DISABLE:hr.ENABLE}}));let S=!1;h+=m.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsSent}\t${e.encoderImplementation}\t${e.trackState}`)).join("\n"),e.senders.length&&(S=yield this._send(`${h}\r${this._userRole}`));let T=!1;return R+=p.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsReceived}\t${e.codecImplementationName}\t${e.trackState}`)).join("\n"),e.receivers.length&&(T=yield this._send(`${R}\r${this._userRole}`)),!(!S&&!T)}))}sendR1(){const e=`R1\t5.5.3\t${this._context.getCoreVersion()}\tweb\t${navigator.platform}\t-1\t${Mt.browser}\t${Mt.version}\t${this._getClientID()}\t${this._userRole}`;this._send(e)}sendR2(e,t,r){const i=`R2\t${e}\t${t}\t${this._getClientID()}\r${r.join("\t")}\r${this._userRole}`;this._send(i)}}class Mr{constructor(e){this._room=e,this._audioLevelChangeHandler=null,this._timer=null}_audioLevelReport(e){return v(this,void 0,void 0,(function*(){if(!this._audioLevelChangeHandler)return;const t=[],r=this._room.__getPC();for(let i=0;i<r.length;i++){const s=r[i];if("new"===s.getRTCPeerConn().iceConnectionState)return;const o=yield s.getAudioLevelReportData(e);null==o||o.forEach((e=>{const{userId:r}=Lt(e.trackId),i=this._room.getCrtUserId()===r?this._room.getLocalTrack(e.trackId):this._room.getRemoteTrack(e.trackId);i&&t.push({track:i,audioLevel:e.audioLevel||0})}))}this._audioLevelChangeHandler(t)}))}startAutoExecute(e=1e3){this._timer=setTimeout((()=>{this._audioLevelReport(e),this._timer=this.startAutoExecute(e)}),e)}stopAutoExecute(){clearTimeout(this._timer)}onAudioLevelChange(e,t){t<300||t>1e3?O.error('the valid range of onAudioLevelChange params "gap" is: > 300 && < 1000'):e?(this._audioLevelChangeHandler=e,this.startAutoExecute(t)):this._audioLevelChangeHandler=null}clearAudioLevelReportTimer(){this._timer&&(this.stopAutoExecute(),this._timer=null)}}!function(e){e[e.ANCHOR=1]="ANCHOR",e[e.AUDIENCE=2]="AUDIENCE"}(mr||(mr={}));class xr{constructor(e=!1,t,r,i,s){this._useMutilPeerC=e,this._roomId=t,this._reTryExchange=r,this._currentUserId=i,this._polarisReport=s,this._mutilPeerC={}}get useMutilPeerC(){return this._useMutilPeerC}_isPub(e){if(!e.length)return!1;const{track:t}=e[0]instanceof ot||e[0]instanceof mt?{track:e[0]}:e[0];return t.isLocalTrack()}_groupTracksByTag(e){const t={};return e.forEach((e=>{const{track:r}=e instanceof ot?{track:e}:e,i=r.getTag();t[i]?t[i].push(e):t[i]=[e]})),t}_genPCName(e,t){let r=null;return r=e?this._useMutilPeerC?`${this._roomId}_${t}`:`${this._roomId}_pub`:`${this._roomId}_sub`,r}_createOnePeerCItem(e,t){if(this._mutilPeerC[e]&&!this._mutilPeerC[e].pc.isDestroyed())this._mutilPeerC[e].tracks=t;else{const r=this._isPub(t),i=new Ur(e,(()=>this._reTryExchange(e,r)),this._currentUserId,this._polarisReport);this._mutilPeerC[e]={pc:i,tracks:t,isPub:r}}return Object.assign(Object.assign({},this._mutilPeerC[e]),{pcName:e})}createPeerCList(e){const t=[],r=this._isPub(e);if(!this._useMutilPeerC){const r=this._genPCName(!0);return t.push(this._createOnePeerCItem(r,e)),t}if(this._useMutilPeerC&&!r){const r=this._genPCName(!1);return t.push(this._createOnePeerCItem(r,e)),t}const i=this._groupTracksByTag(e);for(const e in i){const s=this._genPCName(r,e),o=i[e];t.push(this._createOnePeerCItem(s,o))}return t}_removeAllLocalTrack(){this.getPCList().forEach((e=>e.removeAllLocalTrack()))}destroyPeerC(e){this._mutilPeerC[e].pc.destroy()}_destroyAllPeerC(){this.getPCList().forEach((e=>e.destroy()))}getPCItemByPCName(e){return this._mutilPeerC[e]}getPCByTrackId(e,t=!0){const{tag:r}=Lt(e),i=this._genPCName(t,r);return this._mutilPeerC[i].pc}getPCList(){const e=[];for(const t in this._mutilPeerC)e.push(this._mutilPeerC[t].pc);return e}getMutilPeerCData(){return this._mutilPeerC}setPeerCData(e,t,r){}clear(){this._removeAllLocalTrack(),this._destroyAllPeerC()}}!function(e){e[e.Unknow=0]="Unknow",e[e.Publish=1]="Publish",e[e.UnPublish=2]="UnPublish",e[e.JoinRoom=3]="JoinRoom",e[e.LeaveRoom=4]="LeaveRoom",e[e.UpdateSubscribeTask=5]="UpdateSubscribeTask",e[e.SubscribedTask=6]="SubscribedTask",e[e.UnSubscribedTask=7]="UnSubscribedTask",e.AsyncCommand="AsyncCommand"}(pr||(pr={})),function(e){e.NORMAL="normal",e.MIDDLE="middle",e.TAIL="tail"}(Sr||(Sr={})),function(e){e[e.LOW=0]="LOW",e[e.NORMAL=1]="NORMAL",e[e.HIGH=2]="HIGH"}(Tr||(Tr={})),function(e){e[e.Destroy=40400]="Destroy"}(Cr||(Cr={}));class wr{get priority(){return Tr.LOW}get kind(){return pr.Unknow}}class Br extends wr{constructor(e=Sr.NORMAL){super(),this.state=e}get kind(){return pr.AsyncCommand}setState(e){this.state=e}pickoutSubscribed(e,t){const{unsubscribe:r,subscribe:i}=this.calcSubscribeList(e,t);return Br.AsyncSubscribeTasks=[],Br.AsyncUnsubscribeTasks=[],Br.AsyncUpdateSubscribeTasks=[],{subscribe:i,unsubscribe:r}}calcSubscribeList(e,t){const r=[],i=new Set,s=[],o=new Set,n=this.formateTrack(e),a=this.formateTrack(t);return a.forEach((e=>{const t=`${e.track.getTrackId()}_SUB_${e.subTiny?"0":"1"}`;this.trackInSubscribeList(e,n)||i.has(t)||(r.push(e),i.add(t))})),n.forEach((e=>{const t=`${e.track.getTrackId()}_SUB_${e.subTiny?"0":"1"}`;this.trackInSubscribeList(e,a)||o.has(t)||(s.push(e),o.add(t))})),{unsubscribe:r,subscribe:s}}formateTrack(e){return e.map((e=>e instanceof mt?{track:e,subTiny:!1}:Object.assign({subTiny:!1},e)))}trackInSubscribeList(e,t){if(0===t.length)return!1;return t.findIndex((t=>t.track.getTrackId()===e.track.getTrackId()&&t.subTiny===e.subTiny))>-1}}Br.AsyncSubscribeTasks=[],Br.AsyncUnsubscribeTasks=[],Br.AsyncUpdateSubscribeTasks=[];class Vr extends class{constructor(e,t,r,i,s,o,n,a,c){this.context=e,this.service=t,this.peerMgr=r,this.roomId=i,this.crtUserId=s,this.roomMode=o,this.polarisReport=n,this.isUpgrade=a,this.isMainRoom=c,this._remoteTracks={},this._subscribedList=[],this._collectSubscribeList=[],this._CDNUris=null,this._CDNEnable=!1,this._destroyed=!1}get useMutilPeerC(){return this.peerMgr.useMutilPeerC}getResourcesByUserId(e){return this._roomResources[e]}getRemoteTrack(e){return this._remoteTracks[e]}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getRemoteTracks(){return this._remoteTracks}getSessionId(){return this._sessionId}getAllUserIds(){return Object.keys(this._roomResources)}getRemoteUserIds(){return this.getAllUserIds().filter((e=>e!==this.crtUserId))}getSubscribedList(){return this._subscribedList}getCollectSubscribeList(){return this._collectSubscribeList}getPublishedResourceByTrackId(e){const{userId:t}=Lt(e);return this._roomResources[t].find((t=>Ot(t)===e))}getToken(){return this._token}getLocalTrack(e){return this.peerMgr.getPCByTrackId(e).getLocalTrack(e)}getLocalTracks(){const e=[];return this.peerMgr.getPCList().forEach((t=>{e.push(...t.getLocalTracks())})),e}getTrackState(e){var t;return(null===(t=this.getLocalTrack(e))||void 0===t?void 0:t.isLocalMuted())?0:1}getCDNEnable(){return this._CDNEnable}getCDNUris(){return this._CDNUris}}{_initRemoteTracks(){for(const e in this._roomResources){const t=this._roomResources[e];e!==this.crtUserId&&0!==t.length&&t.forEach((e=>{const t=Ot(e),{tag:r,userId:i,mediaType:s}=Lt(t),o=s===He.AUDIO_ONLY?new pt(r,i):new St(r,i);o.__innerSetRemoteMuted(0===e.state),this._remoteTracks[t]=o}))}}initWithRoomData(e){this._sessionId=e.sessionId,this._token=e.token,this.isUpgrade?this._roomResources={}:this._roomResources=$t(e,this.roomId),this._initRemoteTracks(),this.setResourcesByUserId(this.crtUserId,this.getResourcesByUserId(this.crtUserId)||[]),O.info(`room data -> ${JSON.stringify(this._roomResources)}`)}assignRoomData(e){Object.assign(this._roomResources,e)}setResourcesByUserId(e,t){this._roomResources[e]=t}removeRemoteTrack(e){delete this._remoteTracks[e]}removeResourcesByUserId(e){delete this._roomResources[e]}addRemoteTrack(e){this._remoteTracks[e.getTrackId()]=e}removeRemoteTracks(){const e=Object.values(this._remoteTracks);e.length&&(e.forEach((e=>{e.isAudioTrack()&&e.__releaseMediaElement()})),this._remoteTracks={})}setCDNEnabel(e){this._CDNEnable=e}setCDNUris(e){this._CDNUris=e}resetSubscribedList(e){this._subscribedList.splice(0,this._subscribedList.length,...e),this.resetCollectSubscribeList(e)}resetCollectSubscribeList(e){this._collectSubscribeList.splice(0,this._collectSubscribeList.length,...e)}}class $r extends class{constructor(e,t){this._store=e,this.abortCode=t,this._queue=[],this._busy=!1,this._isDestroyed=!1}_next(){this._busy=!1,this._execute()}_execute(){return v(this,void 0,void 0,(function*(){if(this._isDestroyed||this._busy||0===this._queue.length)return;this._busy=!0;const{command:e,resolve:t,reject:r}=this._queue.shift();let i;try{i=yield e.execute(this._store,this)}catch(e){return r(e),void this._next()}t(i),this._next()}))}push(e){return new Promise(((t,r)=>{if(this._isDestroyed)return;const{kind:i}=e;this._queue.length>0&&i===pr.AsyncCommand&&({command:e,resolve:t,reject:r}=this.commandOffset(e,t,r));const{priority:s}=e;if(s===Tr.LOW)this._queue.push({command:e,resolve:t,reject:r});else{const i=this._queue.findIndex((e=>e.command.priority<s)),o=-1===i?this._queue.length-1:i;this._queue.splice(o,0,{command:e,resolve:t,reject:r})}Promise.resolve().then((()=>{this._execute()}))}))}commandOffset(e,t,r){const i=this._queue.length-1;if(!(this._queue[i].command.kind===pr.AsyncCommand))return{command:e,resolve:t,reject:r};const[s]=this._queue.splice(i,1);s.command instanceof Br&&(s.command.setState(Sr.MIDDLE),e instanceof Br&&e.setState(Sr.TAIL));const o=e.execute;return e.execute=function(t,r){return v(this,void 0,void 0,(function*(){return s.command.execute.call(s.command,t,r),o.call(e,t,r)}))},{command:e,resolve:e=>{s.resolve.call(s,e),t(e)},reject:e=>{s.reject.call(s,e),r(e)}}}isDestroyed(){return this._isDestroyed}destroy(){this._isDestroyed||(this._isDestroyed=!0,this._queue.forEach((e=>{e.resolve({code:this.abortCode})})),this._queue.length=0)}}{constructor(e,t,r,i,s,o,n,a,c){super(new Vr(e,t,r,i,s,o,n,a,c),L.ROOM_HAS_BEEN_DESTROYED)}get store(){return this._store}destroy(){super.destroy(),this._store.removeRemoteTracks()}}class Fr extends wr{execute(e){return v(this,void 0,void 0,(function*(){const t=e.getResourcesByUserId(e.crtUserId),r=t.slice();t.length=0,O.info(`unpublish uris before rejoin -> ${JSON.stringify(r)}`);const i=yield e.context.setRTCTotalRes(e.roomId,Tt(jt.UNPUBLISH,r),Ct([]),jt.TOTAL_CONTENT_RESOURCE,Ct([]));i!==a.SUCCESS?O.error(`unpublish uris before rejoin failed -> code: ${i}`):O.info("unpublish uris before rejoin success")}))}}!function(e){e[e.RTC=0]="RTC",e[e.LIVE=2]="LIVE",e[e.CROSS_MUTI=7]="CROSS_MUTI",e[e.CROSS_LIVE=8]="CROSS_LIVE"}(Ir||(Ir={})),function(e){e[e.KICK=0]="KICK",e[e.REFUSE=1]="REFUSE",e[e.COEXIST=2]="COEXIST"}(Er||(Er={}));class Gr extends wr{constructor(e,t,r,i,s,o){super(),this.roomId=e,this.roomType=t,this.joinType=r,this.livingType=i,this.innerUserDatas=s,this.outerUserDatas=o}get kind(){return pr.JoinRoom}execute(e,t){var s,c,d,u,l,S;return v(this,void 0,void 0,(function*(){const T=Qt.getMemo(),C={dur:0,cod:0,rid:"",rtp:this.roomType,csnid:"",snid:"",time:0,cr:"unknown",net:"unknown",uid:""};T.qualityJoinRoomReportData=C,T.joinRoomData={start:Date.now()};const{context:I,service:E}=e;let g=A.L_RTC_CLIENT_JOIN_RTC_ROOM_R;if(this.roomType===Ir.LIVE?g=A.L_RTC_CLIENT_JOIN_LIVING_ROOM_R:this.roomType===Ir.CROSS_MUTI&&(g=A.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_R),I.getConnectionStatus()!==_.CONNECTED)return r.error(g,{status:D.FAILED,code:L.SIGNAL_DISCONNECTED,msg:"im not connected"},{logSource:i.RTC}),{code:L.SIGNAL_DISCONNECTED};if(E.detectorMediaSever(),Vt(I.getNaviInfo()))return r.error(g,{status:D.FAILED,code:L.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_usl error"},{logSource:i.RTC}),{code:L.PACKAGE_ENVIRONMENT_ERROR};if(!o("roomId",this.roomId,m,!0))return r.error(g,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(!o("roomType",this.roomType,(e=>void 0!==Ir[e])))return r.error(g,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> roomType"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(!o("outerUserDatas",this.outerUserDatas,n,!1))return r.error(g,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(this.outerUserDatas){if(!Object.keys(this.outerUserDatas).every((e=>o(`outerUserDatas.${e}`,this.outerUserDatas[e],p,!0))))return r.error(g,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:i.RTC}),{code:L.PARAMS_ERROR}}if(!E.getNaviMS().length)return r.error(g,{status:D.FAILED,code:L.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:i.RTC}),{code:L.NOT_OPEN_VIDEO_AUDIO_SERVER};O.info(`joinRoom -> roomId: ${this.roomId}; joinType: ${this.joinType||Er.KICK}`);const{code:f,data:v}=yield I.joinRTCRoom(this.roomId,this.roomType,this.livingType,this.joinType,this.innerUserDatas,this.outerUserDatas);if(f!==a.SUCCESS||!v){const t=Date.now(),o=JSON.stringify(Object.assign(T.qualityJoinRoomReportData,{dur:t-((null===(s=T.joinRoomData)||void 0===s?void 0:s.start)||0),cod:f,rid:this.roomId,csnid:null===(c=T.clientData)||void 0===c?void 0:c.clientSessionId,snid:e.getSessionId(),time:t,uid:e.crtUserId}));h(R.STATISTICS,A.L_QS_JOIN_ROOM_S,o,i.RTC),O.warn(`joinRoom failed -> code: ${f}`);const n=40032===f?L.SIGNAL_JOIN_RTC_ROOM_REFUSED:f;return r.error(g,{status:D.FAILED,code:n,msg:`joinRoom failed -> code: ${f}`},{logSource:i.RTC}),{code:n}}O.info(`joinRoom success -> userId: ${I.getCurrentId()}, roomId: ${this.roomId}, data: ${JSON.stringify(v)}`);const N=Date.now(),b=JSON.stringify(Object.assign(T.qualityJoinRoomReportData,{dur:N-((null===(d=T.joinRoomData)||void 0===d?void 0:d.start)||0),cod:f,rid:this.roomId,csnid:null===(u=T.clientData)||void 0===u?void 0:u.clientSessionId,snid:v.sessionId,time:N,uid:e.crtUserId}));h(R.STATISTICS,A.L_QS_JOIN_ROOM_S,b,i.RTC),T.joinRoomData={start:null===(l=T.joinRoomData)||void 0===l?void 0:l.start,roomId:this.roomId},e.initWithRoomData(v);e.getResourcesByUserId(e.crtUserId).length>0&&t.push(new Fr);const k=null===(S=v.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===S?void 0:S.value;return k&&e.setCDNUris(JSON.parse(k)[0]),r.info(g,{status:D.SUCCESSED,userId:e.crtUserId,roomId:this.roomId,data:v},{logSource:i.RTC}),{code:L.SUCCESS,data:v}}))}}function Kr(e,t,r,i){return v(this,void 0,void 0,(function*(){return{sdp:yield r.createOffer(t),extend:JSON.stringify({resolutionInfo:r.getOutboundVideoInfo()}),subscribeList:e.filter((e=>{const t=e.track.getTrackId(),{userId:r}=Lt(t),s=i.getResourcesByUserId(r);if(!s)return!1;const o=s.filter((e=>t===`${e.msid}_${e.mediaType}`)).length;return o})).map((e=>({simulcast:e.subTiny?Xt.TINY:Xt.NORMAL,resolution:"",uri:i.getPublishedResourceByTrackId(e.track.getTrackId()).uri}))),switchstream:!1}}))}function jr(e,t,r){return v(this,void 0,void 0,(function*(){const i=yield e.setRTCCDNUris(t,jt.TOTAL_CONTENT_RESOURCE,JSON.stringify([r]));return i!==a.SUCCESS?(O.error(`spreadCDNInfo failed -> code: ${i}`),{code:L.SIGNAL_ERROR}):(O.info("spreadCDNInfo succeed"),{code:L.SUCCESS})}))}function Hr(e,t,r){return v(this,void 0,void 0,(function*(){const i=yield e.setRTCData(t,"cdn_uris",JSON.stringify([r]),!0,Or.ROOM);return i!==a.SUCCESS?(O.error(`setRoomCDNInfo failed -> code: ${i}`),{code:L.SIGNAL_ERROR}):(O.info("setRoomCDNInfo succeed"),{code:L.SUCCESS})}))}function Jr(e){return v(this,void 0,void 0,(function*(){const{context:t}=e,{roomId:s}=e,o=Object.assign({},e.getCDNUris(),{enableInnerCDN:e.getCDNEnable()});r.info(A.L_LIVING_ROOM_SPREAD_CDN_INFO_T,{roomId:s,CDNUris:o},{logSource:i.RTC});const n=(yield Promise.all([jr(t,s,o),Hr(t,s,o)])).every((e=>e.code===L.SUCCESS));return n?r.info(A.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:D.SUCCESSED,CDNUris:o},{logSource:i.RTC}):r.error(A.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:D.FAILED,code:L.SIGNAL_ERROR,msg:"signal error"},{logSource:i.RTC}),n?{code:L.SUCCESS}:{code:L.SIGNAL_ERROR}}))}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(gr||(gr={})),function(e){e.BEGIN="begin",e.END="end"}(fr||(fr={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(vr||(vr={})),function(e){e[e.ROOM=1]="ROOM",e[e.PERSON=2]="PERSON"}(Or||(Or={}));class qr extends wr{constructor(e,t){super(),this.headers=e,this.reqBody=t}execute(e,t){var r,i;return v(this,void 0,void 0,(function*(){const t=yield e.service.exchange(this.headers,this.reqBody);if(e.roomMode!==Ir.LIVE)return t;const s=null===(i=null===(r=t.data)||void 0===r?void 0:r.urls)||void 0===i?void 0:i.pull_url;if(t.code!==L.SUCCESS||!s)return t;const o=JSON.parse(s);return e.setCDNUris(o),(null==o?void 0:o.broadcast)===vr.SPREAD&&(e.setCDNEnabel(!0),Jr(e)),t}))}}class Wr extends wr{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(e,t){var s,n;return v(this,void 0,void 0,(function*(){const{tracks:a,forceReq:c}=this,{roomId:_}=e;if(!o("tracks",a,(()=>d(a)&&a.every((e=>e instanceof mt||e.track instanceof mt))),!0))return O.warn(`update sublist failed, tracks is invalid -> roomId: ${_}`),{code:L.PARAMS_ERROR};O.info(`update subscribe list -> roomId: ${_}, forceReq: ${c}, tracks: ${a.map(Gt)}`);let u=a.map((e=>e instanceof mt?{track:e}:Object.assign({},e)));const l={};u=u.filter((t=>{const r=t.track.getTrackId();return e.getRemoteTrack(r)?!l[r]&&(l[r]=!0,!0):(O.warn(`track cannot found in room -> trackId: ${r}`),!1)})).map((e=>Object.assign({},e)));const m=e.getSubscribedList().map((e=>Object.assign({},e)));if(!c){let e=!1;if(u.forEach((t=>{const r=m.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);m.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),m.length&&(e=!0),!e)return{code:L.SUCCESS}}const{pc:p,pushOtherRooms:S,headers:T}=this.subhook(a);p.updateSubRemoteTracks(u.map((e=>e.track)));const C=Qt.getMemo();r.info(A.L_QS_CREATE_OFFER_O,{identify:C.qualityStatusId},{logSource:i.RTC});const I={dur:0,cod:0,rid:e.roomId,csnid:null===(s=C.clientData)||void 0===s?void 0:s.clientSessionId,snid:e.getSessionId(),rsid:"",msa:"",msas:[],time:0,resid:"",mtp:0,smct:1,cr:"unknown",net:"unknown",uid:"",stp:0};C.qualitySubscribeReportData=I,C.subscribeData={start:Date.now()};const E={dur:0,cod:0,rid:e.roomId,csnid:null===(n=C.clientData)||void 0===n?void 0:n.clientSessionId,snid:e.getSessionId(),rsid:"",msa:"",msas:[],time:0,resid:"",mtp:0,smct:1,uid:"",stp:0};C.qualityUnsubscribeReportData=E,C.unsubscribeData={start:Date.now()};const g=yield Kr(u,!1,p,e);S&&(g.pushOtherRooms=S),r.info(A.L_QS_SUBSCRIBE_EXCHANGE_O,{identify:C.qualityStatusId},{logSource:i.RTC});const f=yield new qr(T,g).execute(e,t),v=u.map((e=>e.track.getTrackId()));if(f.code!==L.SUCCESS){let e=[],t=Date.now();return C.mediaService.forEach((t=>{e.push({rsid:t.reqId,rsdur:t.end-t.start,msa:t.url,rscod:t.rscod})})),C.subscribeCommand&&(C.subscribeCommand=!1,u.forEach((r=>{var s,o;const n=JSON.stringify(Object.assign(C.qualitySubscribeReportData,{dur:t-((null===(s=C.subscribeData)||void 0===s?void 0:s.start)||0),cod:f.code,msas:e,time:t,resid:r.track.getTrackId(),mtp:Lt(r.track.getTrackId()).mediaType,smct:r.track instanceof at&&(null===(o=r.track)||void 0===o?void 0:o.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,n,i.RTC)}))),C.unsubscribeCommand&&(C.unsubscribeCommand=!1,u.forEach((r=>{var s,o;const n=JSON.stringify(Object.assign(C.qualityUnsubscribeReportData,{dur:t-((null===(s=C.unsubscribeData)||void 0===s?void 0:s.start)||0),cod:f.code,time:t,msas:e,resid:r.track.getTrackId(),mtp:Lt(r.track.getTrackId()).mediaType,smct:r.track instanceof at&&(null===(o=r.track)||void 0===o?void 0:o.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,n,i.RTC)}))),{code:f.code}}const{sdp:D,resultCode:N,message:b,subscribedList:k}=f.data;if(N!==L.SUCCESS){let e=[],t=Date.now();return C.mediaService.forEach((t=>{e.push({rsid:t.reqId,rsdur:t.end-t.start,msa:t.url,rscod:t.rscod})})),C.subscribeCommand&&(C.subscribeCommand=!1,u.forEach((r=>{var s,o;const n=JSON.stringify(Object.assign(C.qualitySubscribeReportData,{dur:t-((null===(s=C.subscribeData)||void 0===s?void 0:s.start)||0),cod:N,msas:e,time:t,resid:r.track.getTrackId(),mtp:Lt(r.track.getTrackId()).mediaType,smct:r.track instanceof at&&(null===(o=r.track)||void 0===o?void 0:o.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,n,i.RTC)}))),C.unsubscribeCommand&&(C.unsubscribeCommand=!1,u.forEach((r=>{var s,o;const n=JSON.stringify(Object.assign(C.qualityUnsubscribeReportData,{dur:t-((null===(s=C.unsubscribeData)||void 0===s?void 0:s.start)||0),cod:N,msas:e,time:t,resid:r.track.getTrackId(),mtp:Lt(r.track.getTrackId()).mediaType,smct:r.track instanceof at&&(null===(o=r.track)||void 0===o?void 0:o.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,n,i.RTC)}))),O.error(`change subscribe list failed: ${N}`),{code:N}}r.info(A.L_QS_GET_ANSWER_O,{identify:C.qualityStatusId},{logSource:i.RTC}),O.debug(`subscribe success: ${v.join(",")}`);const y=yield p.setRemoteAnswer(D.sdp);if(y!==L.SUCCESS){let e=[],t=Date.now();return C.mediaService.forEach((t=>{e.push({rsid:t.reqId,rsdur:t.end-t.start,msa:t.url,rscod:t.rscod})})),C.subscribeCommand&&(C.subscribeCommand=!1,u.forEach((r=>{var s,o;const n=JSON.stringify(Object.assign(C.qualitySubscribeReportData,{dur:t-((null===(s=C.subscribeData)||void 0===s?void 0:s.start)||0),cod:y,msas:e,time:t,resid:r.track.getTrackId(),mtp:Lt(r.track.getTrackId()).mediaType,smct:r.track instanceof at&&(null===(o=r.track)||void 0===o?void 0:o.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,n,i.RTC)}))),C.unsubscribeCommand&&(C.unsubscribeCommand=!1,u.forEach((r=>{var s,o;const n=JSON.stringify(Object.assign(C.qualityUnsubscribeReportData,{dur:t-((null===(s=C.unsubscribeData)||void 0===s?void 0:s.start)||0),cod:y,msas:e,time:t,resid:r.track.getTrackId(),mtp:Lt(r.track.getTrackId()).mediaType,smct:r.track instanceof at&&(null===(o=r.track)||void 0===o?void 0:o.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,n,i.RTC)}))),{code:y}}let U=[],P=Date.now();C.mediaService.forEach((e=>{U.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),C.subscribeCommand&&(C.subscribeCommand=!1,u.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(C.qualitySubscribeReportData,{dur:P-((null===(t=C.subscribeData)||void 0===t?void 0:t.start)||0),cod:y,msas:U,time:P,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,s,i.RTC)}))),C.unsubscribeCommand&&(C.unsubscribeCommand=!1,u.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(C.qualityUnsubscribeReportData,{dur:P-((null===(t=C.unsubscribeData)||void 0===t?void 0:t.start)||0),cod:y,msas:U,time:P,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,s,i.RTC)}))),C.iceStatusData?C.iceStatusData.subscribe={time:Date.now()}:C.iceStatusData={};const M=null==k?void 0:k.map((e=>`${e.msid}_${e.mediaType}`)),x=u.filter((e=>null==M?void 0:M.includes(e.track.getTrackId()))),w=u.filter((e=>!(null==M?void 0:M.includes(e.track.getTrackId())))),B=e.getRemoteTracks();for(const e in B){const t=x.some((t=>t.track.getTrackId()===e));B[e].__innerSetSubscribed(t);const r=x.some((t=>t.track.getTrackId()===e&&t.subTiny));B[e].isVideoTrack()&&B[e].__innerSetIsTinyTrack(r)}return e.resetSubscribedList(x),r.info(A.L_QS_GET_RESOURCES_O,{identify:C.qualityStatusId},{logSource:i.RTC}),w.length?{code:L.SUCCESS,failedList:w}:{code:L.SUCCESS}}))}}class Yr extends wr{constructor(e,t){super(),this.tracks=e,this.subhook=t}execute(e,t){return v(this,void 0,void 0,(function*(){const{tracks:s}=this,{roomId:n}=e;if(r.info(A.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:s.map(Gt)},{logSource:i.RTC}),!o("tracks",s,(()=>d(s)&&s.length>0&&s.every((e=>e instanceof mt))),!0))return O.warn(`unsubscribe failed, tracks is invalid -> roomId: ${n}`),r.warn(A.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};O.info(`unsubscribe -> roomId: ${n}, tracks: ${s.map(Gt)}`);const a=e.getSubscribedList().map((e=>Object.assign({},e))).filter((e=>!s.includes(e.track)));e.polarisReport.sendR2(gr.SUBSCRIBE,fr.END,s.map((e=>e.getTrackId()))),r.info(A.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:s.map(Gt),roomId:n},{logSource:i.RTC});return Qt.getMemo().unsubscribeCommand=!0,new Wr(a,this.subhook,!1).execute(e,t)}))}}class Qr extends wr{constructor(e,t){super(),this.msgContent=e,this.subhook=t}get priority(){return Tr.NORMAL}execute(e,t){return v(this,void 0,void 0,(function*(){const r=[],i=[],s=[],o=[],n={joined:r,left:i,upgrade:s,downgrade:o},{users:a}=this.msgContent;if(0===a.length)return n;for(let t=0;t<a.length;t++){const r=a[t];if(r.extra&&r.extra.roomId!==e.roomId)return n;if(1==+r.state&&!e.getRemoteUserIds().includes(r.userId))return n}a.forEach((t=>{const{userId:n}=t;if(0==+t.state){O.info(`user joined -> ${n}`);const i=e.getResourcesByUserId(n);i||(t.switchRoleType?s.push(n):r.push(n)),e.setResourcesByUserId(n,i||[])}else O.info(`user left -> ${n}`),t.switchRoleType?o.push(n):i.push(n)}));const c=[...i,...o];if(c.length){const r=[],i=[];c.forEach((t=>{r.push(...e.getRemoteTracksByUserId(t)),i.push(t)})),r.length&&(yield new Yr(r,this.subhook).execute(e,t),r.forEach((t=>e.removeRemoteTrack(t.getTrackId())))),i.length&&i.forEach((t=>e.removeResourcesByUserId(t)))}return n}))}}class zr extends wr{constructor(e,t,r){super(),this.subhook=e,this.tracks=t,this.onTrackUnpublish=r}execute(e,t){return v(this,void 0,void 0,(function*(){const{tracks:r}=this;yield new Yr(r,this.subhook).execute(e,t),r.forEach((t=>{t.__innerDestroy(),e.removeRemoteTrack(t.getTrackId())})),this.onTrackUnpublish(r)}))}}class Zr extends wr{constructor(e,t,r,i,s){super(),this.msgContent=e,this.messageType=t,this.senderId=r,this.subhook=i,this.callback=s}get priority(){return Tr.NORMAL}execute(e,t){var r,i;return v(this,void 0,void 0,(function*(){const{uris:s}=this.msgContent,o=[],n=[],a=[];let c;const d=this.senderId,{messageType:_}=this,u=e.getResourcesByUserId(d)||[];switch(e.setResourcesByUserId(d,u),_){case jt.MODIFY:a.push(...s);break;case jt.PUBLISH:o.push(...s);break;case jt.UNPUBLISH:n.push(...s);break;case jt.TOTAL_CONTENT_RESOURCE:c=Nt(u,s),o.push(...c.publishedList),n.push(...c.unpublishedList),a.push(...c.modifiedList)}if(o.length>0){const r=u.map(Ot),i=[],s=[];if(o.forEach((t=>{const o=Ot(t),n=r.indexOf(o),{userId:a,tag:c,mediaType:d}=Lt(o);n>-1?u[n]=t:u.push(t);let _=e.getRemoteTrack(o);_?_.isSubscribed()&&i.push(_):(_=d===He.AUDIO_ONLY?new pt(c,a):new St(c,a),e.addRemoteTrack(_),s.push(_)),_.__innerSetRemoteMuted(0===t.state)})),i.length){const r=i.map((e=>e.getTrackId()));O.debug(`resub tracks -> ${JSON.stringify(r)}`);const{code:s}=yield new Wr(i,this.subhook).execute(e,t);s!==L.SUCCESS&&O.error(`resub tracks failed -> code: ${s}, ids: ${JSON.stringify(r)}`)}this.callback.onTrackPublish(s)}if(n.length>0){const r=n.map(Ot);for(let e=u.length-1;e>=0;e-=1){const t=u[e];r.includes(Ot(t))&&u.splice(e,1)}const i=n.map((t=>{const r=Ot(t);return e.getRemoteTrack(r)}));yield new zr(this.subhook,i,this.callback.onTrackUnublish).execute(e,t)}if(a.length>0){const t=u.map(Ot);for(let r=0;r<a.length;r+=1){const i=a[r],s=Ot(i),o=t.indexOf(s);u[o].state=i.state;const n=e.getRemoteTrack(s);n.__innerSetRemoteMuted(0===i.state),n.isAudioTrack()?this.callback.onAudioMute(n):this.callback.onVideoMute(n)}}if(e.roomMode!==Ir.LIVE)return;const l=this.msgContent;if(!l.cdn_uris)return;const h=(null===(r=e.getCDNUris())||void 0===r?void 0:r.enableInnerCDN)!==l.cdn_uris[0].enableInnerCDN;e.setCDNUris(l.cdn_uris[0]),h&&this.callback.onCDNEnableChange(!!(null===(i=e.getCDNUris())||void 0===i?void 0:i.enableInnerCDN))}))}}class Xr extends wr{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(e,t){return v(this,void 0,void 0,(function*(){const{tracks:s,forceReq:n}=this,{roomId:a}=e;if(r.info(A.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:s.map(Gt),forceReq:n},{logSource:i.RTC}),!o("tracks",s,(()=>d(s)&&s.length>0&&s.every((e=>e instanceof mt||e.track instanceof mt))),!0))return O.warn(`subscribe failed, tracks is invalid -> roomId: ${a}`),r.error(A.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};O.info(`subscribe -> roomId: ${a}, tracks: ${s.map(Gt)}`);const c=e.getSubscribedList().map((e=>Object.assign({},e))),_=s.map((e=>e instanceof mt?{track:e}:e));let u=!1;const l=[];if(_.forEach((e=>{const t=e.track.getTrackId();l.push(t);const r=c.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:c.push(e),u=!0)})),!u&&!n)return r.warn(A.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:D.FAILED,code:"",msg:"repeat subscribe"},{logSource:i.RTC}),{code:L.SUCCESS};e.polarisReport.sendR2(gr.SUBSCRIBE,fr.BEGIN,l),r.info(A.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:s.map(Gt),roomId:a},{logSource:i.RTC});return Qt.getMemo().subscribeCommand=!0,new Wr(c,this.subhook,!0).execute(e,t)}))}}class ei extends wr{constructor(e,t){super(),this.tracks=e,this.pubhook=t}get kind(){return pr.Publish}_removePubFailedTracks(e,t){e.forEach((e=>{const r=e instanceof ot?e:e.track;O.debug(`remove pub failed track from peerconnection -> trackId: ${r.getTrackId()}`),t.removeLocalTrackById(r.getTrackId())}))}__publish(e,t,s,o,n){var a;return v(this,void 0,void 0,(function*(){const{pcName:c,pc:d,headers:_}=t,{roomId:u}=e,l=[];s.forEach((e=>{const{track:t}=e instanceof ot?{track:e}:e;l.push(t)})),s.sort(((e,t)=>{const{track:r}=e instanceof ot?{track:e}:e,{max:i}=r.getBitrate(),{track:s}=t instanceof ot?{track:t}:t,{max:o}=s.getBitrate();return i-o}));if(d.getLocalTracks().length+((e,t)=>{let r=0;return e.forEach((e=>{const i=e instanceof ot?e.getTrackId():e.track.getTrackId();t.getLocalTrack(i)||(e instanceof ot?r++:e.pubTiny&&e.track.isVideoTrack()&&(r+=2))})),r})(s,d)>10)return O.error(`publish failed, tracks limit exceeded -> roomId: ${u}`),{code:L.PUBLISH_TRACK_LIMIT_EXCEEDED,tracks:l};O.debug(`publish tracks -> roomId: ${u}, tracks: ${s.map(Gt)}`);for(let e=0;e<s.length;e++){const t=s[e],{track:r,pubTiny:i}=t instanceof ot?{pubTiny:!1,track:t}:t;if(r.isVideoTrack()&&i){let e;try{e=r.__innerGetMediaStreamTrack().clone();const t=i.frameRate||Ke.FPS_15,s=i.resolution||je.W176_H144,{width:o,height:n}=kt(s),a=Pt(t);yield e.applyConstraints({width:o,height:n,frameRate:a})}catch(t){null==e||e.stop(),O.warn(`pubTiny failed -> id: ${r.getTrackId()}, msg: ${t.message}`);break}d.addLocalTrack(new at(r.getTag(),r.getUserId(),e,!0))}d.addLocalTrack(r)}d.clearReTryExchangeTimer();const m=e.useMutilPeerC?[]:e.getSubscribedList(),p=`${Date.now()}`,S=Qt.getMemo();S.qualityStatus=p,r.info(A.L_QS_CREATE_OFFER_O,{identify:p},{logSource:i.RTC});const T={dur:0,cod:0,rid:e.roomId,csnid:null===(a=S.clientData)||void 0===a?void 0:a.clientSessionId,snid:e.getSessionId(),rsid:"",msa:"",msas:[],sigs:[],time:0,resid:"",mtp:0,smct:1,cr:"unknown",net:"unknown",uid:e.crtUserId,stp:0};S.qualityPublishReportData=T,S.publish={start:Date.now()};const C=yield Kr(m,!1,d,e);o&&(C.pushOtherRooms=o),r.info(A.L_QS_PUBLISH_EXCHANGE_O,{identify:p},{logSource:i.RTC});const I=yield new qr(_,C).execute(e,n);if(I.code!==L.SUCCESS){const e=Date.now();let t=[];return S.mediaService.forEach((e=>{t.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),l.forEach((r=>{var s;const o=JSON.stringify(Object.assign(S.qualityPublishReportData,{dur:e-((null===(s=S.publish)||void 0===s?void 0:s.start)||0),cod:I.code,msas:t,time:e,resid:r.getTrackId(),mtp:Lt(r.getTrackId()).mediaType,smct:r instanceof at&&r.__isTiny()?2:1}));h(R.STATISTICS,A.L_QS_PUBLISH_S,o,i.RTC)})),O.error(`publish failed -> roomId: ${u}, code: ${I.code}`),this._removePubFailedTracks(s,d),{code:I.code,tracks:l}}r.info(A.L_QS_GET_ANSWER_O,{status:D.SUCCESSED,identify:p},{logSource:i.RTC});const{sdp:E,resultCode:g,message:f}=I.data;if(g!==L.SUCCESS){const e=Date.now();let t=[];return S.mediaService.forEach((e=>{t.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),l.forEach((r=>{var s;const o=JSON.stringify(Object.assign(S.qualityPublishReportData,{dur:e-((null===(s=S.publish)||void 0===s?void 0:s.start)||0),cod:g,msas:t,time:e,resid:r.getTrackId(),mtp:Lt(r.getTrackId()).mediaType,smct:r instanceof at&&r.__isTiny()?2:1}));h(R.STATISTICS,A.L_QS_PUBLISH_S,o,i.RTC)})),O.error(`publish failed -> roomId: ${u}, code: ${g}, msg: ${f}`),this._removePubFailedTracks(s,d),{code:g,tracks:l}}const v=yield d.setRemoteAnswer(E.sdp);if(v!==L.SUCCESS){const e=Date.now();let t=[];return S.mediaService.forEach((e=>{t.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),l.forEach((r=>{var s;const o=JSON.stringify(Object.assign(S.qualityPublishReportData,{dur:e-((null===(s=S.publish)||void 0===s?void 0:s.start)||0),cod:v,msas:t,time:e,resid:r.getTrackId(),mtp:Lt(r.getTrackId()).mediaType,smct:r instanceof at&&r.__isTiny()?2:1}));h(R.STATISTICS,A.L_QS_PUBLISH_S,o,i.RTC)})),{code:v,tracks:l}}return Object.assign(Object.assign({},I),{tracks:l})}))}_mergePublishRes(e,t){return v(this,void 0,void 0,(function*(){const r=t.crtUserId,{roomId:s}=t;let o="";const n=[],c=t.getResourcesByUserId(r),d=[...c];let _=[];e.forEach((e=>{if(e.code!==L.SUCCESS){const{tracks:t}=e;return void n.push({code:e.code,tracks:t})}const{publishList:r,urls:i,mcuPublishList:s}=e.data;o=null==i?void 0:i.liveUrl;r.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:t.getTrackState(Ot(e))},e))).forEach((e=>{const{isInclude:t,index:r}=((e,t)=>{let r=!1,i=0;for(let s=0;s<t.length;s++){const o=t[s];if(`${e.msid}_${e.mediaType}`==`${o.msid}_${o.mediaType}`){r=!0,i=s;break}}return{isInclude:r,index:i}})(e,d);t?d.splice(r,1,e):d.push(e)}));const a=(null==s?void 0:s.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))))||[];_=a}));const{publishedList:u}=Nt(c,d),l=Qt.getMemo();l.publishSignalTotal={start:Date.now()};const m=yield t.context.setRTCTotalRes(s,Tt(jt.PUBLISH,u),Ct(d),jt.TOTAL_CONTENT_RESOURCE,Ct(_));if(m!==a.SUCCESS){const e=Date.now();let t=[];l.mediaService.forEach((e=>{t.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const r=[];return r.push({dur:Date.now()-(l.publishSignalTotal.start||0),cod:m}),d.forEach((s=>{var o;const n=JSON.stringify(Object.assign(l.qualityPublishReportData,{dur:e-((null===(o=l.publish)||void 0===o?void 0:o.start)||0),cod:m,msas:t,sigs:r,time:e,resid:Ot(s),mtp:s.mediaType,smct:s.simulcast}));h(R.STATISTICS,A.L_QS_PUBLISH_S,n,i.RTC)})),O.error(`send publish streams notification failed: ${m}`),{code:L.SIGNAL_ERROR}}const p=Date.now();let S=[];l.mediaService.forEach((e=>{S.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const T=[];T.push({dur:Date.now()-(l.publishSignalTotal.start||0),cod:m}),d.forEach((e=>{var t;const r=JSON.stringify(Object.assign(l.qualityPublishReportData,{dur:p-((null===(t=l.publish)||void 0===t?void 0:t.start)||0),cod:m,msas:S,sigs:T,time:p,resid:Ot(e),mtp:e.mediaType,smct:e.simulcast}));h(R.STATISTICS,A.L_QS_PUBLISH_S,r,i.RTC)})),l.iceStatusData?l.iceStatusData.publish={time:Date.now()}:l.iceStatusData={},t.setResourcesByUserId(r,d);const C=u.map((e=>Ot(e)));t.polarisReport&&t.polarisReport.sendR2(gr.PUBLISH,fr.BEGIN,C),u.forEach((e=>{const r=t.useMutilPeerC?`${s}_${(e=>{const t=e.split("_");return{tag:t.pop(),userId:t.join("_")}})(e.msid).tag}`:`${s}_pub`,{pc:i}=t.peerMgr.getPCItemByPCName(r);i.getLocalTrack(`${e.msid}_${e.mediaType}`).__innerSetPublished(!0)})),O.debug(`publish success: ${C.join(",")}`);const I={code:L.SUCCESS};return o&&(I.liveUrl=o),n.length&&(I.failedTracks=n,I.code=L.SOME_TRACKS_PUBLISH_FAILED),I}))}execute(e,t){return v(this,void 0,void 0,(function*(){let{tracks:s}=this;const{roomId:n}=e;if(r.info(A.L_ABSTRACT_ROOM_PUBLISH_T,{trackIds:s.map(Gt)},{logSource:i.RTC}),!o("tracks",s,(()=>d(s)&&s.length>0&&s.every((e=>e instanceof ot||e.track instanceof ot))),!0))return O.warn(`publish failed, tracks is invalid -> roomId: ${n}`),r.error(A.L_ABSTRACT_ROOM_PUBLISH_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(s=s.filter((e=>{const{track:t}=e instanceof ot?{track:e}:e,i=t.isDestroyed();return i&&r.warn(A.L_ABSTRACT_ROOM_PUBLISH_R,{status:D.FAILED,msg:`track -> ${t.getTrackId()} has beem destroyed`}),!i})),!s.length)return{code:L.PUBLISH_TRACKS_IS_INVALID};const a=[],{plist:c,pushOtherRooms:_}=this.pubhook(s);for(let r=0;r<c.length;r++){const i=c[r];a.push(this.__publish(e,i,i.tracks,_,t))}const u=yield Promise.all(a),l=yield this._mergePublishRes(u,e);return r.info(A.L_ABSTRACT_ROOM_PUBLISH_R,{status:D.SUCCESSED,roomId:n,trackIds:s.map(Gt)},{logSource:i.RTC}),l}))}}class ti extends wr{constructor(e,t){super(),this.tracks=e,this.unpubhook=t}get kind(){return pr.UnPublish}__unpublish(e,t,r,s){var o;return v(this,void 0,void 0,(function*(){const{pcName:n,pc:a}=r,c=s.map((e=>e.getTrackId()));if(0===c.map(e.getPublishedResourceByTrackId.bind(e)).filter((e=>!!e)).length)return{code:L.SUCCESS,tracks:s};c.forEach((e=>a.removeLocalTrackById(e))),e.polarisReport.sendR2(gr.PUBLISH,fr.END,c),a.clearReTryExchangeTimer();const d=e.useMutilPeerC?[]:e.getSubscribedList(),_=Qt.getMemo(),u={dur:0,cod:0,rid:e.roomId,csnid:null===(o=_.clientData)||void 0===o?void 0:o.clientSessionId,snid:e.getSessionId(),rsid:"",msa:"",msas:[],sigs:[],time:0,resid:"",mtp:0,smct:1,uid:e.crtUserId,stp:0};_.qualityUnpublishReportData=u,_.unpublish={start:Date.now()};const l=yield Kr(d,!1,a,e),{pushOtherRooms:m,headers:p}=this.unpubhook(s,n);m&&(l.pushOtherRooms=m);const S=yield new qr(p,l).execute(e,t);if(S.code!==L.SUCCESS){const e=Date.now();return s.forEach((t=>{var r;const s=t.getTrackId(),o=JSON.stringify(Object.assign(_.qualityUnpublishReportData,{dur:e-((null===(r=_.unpublish)||void 0===r?void 0:r.start)||0),cod:S.code,time:e,resid:s,mtp:Lt(s).mediaType,smct:t instanceof at&&t.__isTiny()?2:1}));h(R.STATISTICS,A.L_QS_UNPUBLISH_S,o,i.RTC)})),O.error(`exchange failed -> code: ${S.code}`),{code:S.code,tracks:s}}return Object.assign(Object.assign({},S),{tracks:s})}))}_mergeUnpublishRes(e,t){return v(this,void 0,void 0,(function*(){const r=e.context.getCurrentId(),{roomId:s}=e,o=Qt.getMemo(),n=[],c=[],d=[],_=[];let u=[];for(let r=0;r<t.length;r++){const s=t[r];if(s.code!==L.SUCCESS){const{tracks:e}=s;c.push({code:s.code,tracks:e});continue}const{resultCode:a,message:l,mcuPublishList:m}=s.data;if(a!==L.SUCCESS){const e=Date.now();let t=[];o.mediaService.forEach((e=>{t.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),d.forEach((r=>{var s;if(r){const n=JSON.stringify(Object.assign(o.qualityUnpublishReportData,{dur:e-((null===(s=o.publish)||void 0===s?void 0:s.start)||0),cod:a,msas:t,time:e,resid:Ot(r),mtp:r.mediaType,smct:r.simulcast}));h(R.STATISTICS,A.L_QS_UNPUBLISH_S,n,i.RTC)}})),O.error(`unpublish streams failed -> code: ${a}, msg: ${l}`)}const p=s.tracks.map((e=>e.getTrackId()));_.push(...p);const S=p.map(e.getPublishedResourceByTrackId.bind(e)).filter((e=>!!e));d.push(...S),n.push(s);const T=m?m.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[];u=T}const l=e.getResourcesByUserId(r),m=l.filter((e=>!d.includes(e)));o.unPublishSignalTotal={start:Date.now()};const p=yield e.context.setRTCTotalRes(s,Tt(jt.UNPUBLISH,d),Ct(m),jt.TOTAL_CONTENT_RESOURCE,Ct(u));if(p!==a.SUCCESS){const e=Date.now();let t=[];o.mediaService.forEach((e=>{t.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const r=[];return r.push({dur:Date.now()-(o.unPublishSignalTotal.start||0),cod:p}),l.forEach((s=>{var n;const a=JSON.stringify(Object.assign(o.qualityUnpublishReportData,{dur:e-((null===(n=o.publish)||void 0===n?void 0:n.start)||0),cod:p,msas:t,sigs:r,time:e,resid:Ot(s),mtp:s.mediaType,smct:s.simulcast}));h(R.STATISTICS,A.L_QS_UNPUBLISH_S,a,i.RTC)})),O.error("send unpublish notification failed:",p),{code:L.SIGNAL_ERROR}}O.debug(`unpublish success -> tracks: ${_.join(",")}`);const S=Date.now();let T=[];o.mediaService.forEach((e=>{T.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const C=[];C.push({dur:Date.now()-(o.unPublishSignalTotal.start||0),cod:p}),l.forEach((e=>{var t;const r=JSON.stringify(Object.assign(o.qualityUnpublishReportData,{dur:S-((null===(t=o.publish)||void 0===t?void 0:t.start)||0),cod:L.SUCCESS,msas:T,sigs:C,time:S,resid:Ot(e),mtp:e.mediaType,smct:e.simulcast}));h(R.STATISTICS,A.L_QS_UNPUBLISH_S,r,i.RTC)})),n.forEach((t=>v(this,void 0,void 0,(function*(){const{sdp:r}=t.data,{tracks:i}=t,s=e.peerMgr.getPCByTrackId(i[0].getTrackId());yield s.setRemoteAnswer(r.sdp)})))),e.setResourcesByUserId(r,m);const I={code:L.SUCCESS};return c.length&&(I.failedTracks=c,I.code=L.SOME_TRACKS_PUBLISH_FAILED),I}))}execute(e,t){return v(this,void 0,void 0,(function*(){const{crtUserId:s,roomId:n}=e,{tracks:a}=this;r.info(A.L_ABSTRACT_ROOM_UNPUBLISH_T,{trackIds:a.map(Gt)},{logSource:i.RTC});if(!o("tracks",a,(()=>a.every((e=>e.getUserId()===s&&e instanceof ot))),!0))return O.warn(`unpublish failed, tracks is invalid -> roomId: ${n}, tracks: ${a.map(Gt)}`),r.error(A.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};const c=e.peerMgr.createPeerCList(a),d=[];for(let r=0;r<c.length;r++){const{tracks:i}=c[r];d.push(this.__unpublish(e,t,c[r],i))}const _=yield Promise.all(d);let u=_.length;if(_.forEach((e=>{e.code!==L.SUCCESS||e.data||(u-=1)})),0===u)return{code:L.SUCCESS};const l=yield this._mergeUnpublishRes(e,_);return r.info(A.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:D.SUCCESSED,roomId:n,trackIds:a.map(Gt)},{logSource:i.RTC}),l}))}}class ri extends wr{constructor(e,t){super(),this.localTrack=e,this._recvSignalResultFn=t}execute(e,t){return v(this,void 0,void 0,(function*(){const{localTrack:t}=this,r=t.getTrackId(),{crtUserId:i,roomId:s}=e,o=[{resourceId:r,enabled:!t.isLocalMuted()}],n=e.getResourcesByUserId(i),c=[];for(let e=0;e<n.length;e+=1){const t=n[e],r=Ot(t),i=o.findIndex((e=>e.resourceId===r));if(i>=0){const{enabled:e}=o[i];t.state=e?1:0,c.push(t);break}}const d=yield e.context.setRTCTotalRes(s,Tt(jt.MODIFY,c),Ct(n),jt.TOTAL_CONTENT_RESOURCE);this._recvSignalResultFn(d),d!==a.SUCCESS&&O.error(`notice \`track.enabled\` change failed -> code: ${d}`)}))}}class ii extends wr{constructor(e,t,r){super(),this.pcName=e,this.isPub=t,this.retryHook=r}get priority(){return Tr.HIGH}execute(e,t){return v(this,void 0,void 0,(function*(){const{pcName:r,isPub:i}=this,{useMutilPeerC:s}=e,{pc:o}=e.peerMgr.getPCItemByPCName(r),n=i&&s?[]:e.getSubscribedList(),a=yield Kr(n,!0,o,e),{pushOtherRooms:c,headers:d}=this.retryHook(r);c&&(a.pushOtherRooms=c);const _=yield new qr(d,a).execute(e,t);if(_.code!==L.SUCCESS)return void O.error(`reTryExchange failed: ${_.code}, pcName: ${r}`);const{sdp:u,resultCode:l}=_.data;l===L.SUCCESS?(o.clearReTryExchangeTimer(),yield o.setRemoteAnswer(u.sdp)):O.error(`reTryExchange failed: ${l}, pcName: ${r}`)}))}}class si extends wr{constructor(e,t,r){super(),this.subhook=e,this.callbacks=t,this.livingType=r}get priority(){return Tr.HIGH}execute(e,t){return v(this,void 0,void 0,(function*(){const{livingType:s}=this,{roomId:o,crtUserId:n,roomMode:c}=e;r.info(A.L_ABSTRACT_ROOM_RECONNECTED_T,{livingType:s},{logSource:i.RTC});if(e.peerMgr.getPCList().some((e=>"closed"===e.getRTCPeerConn().connectionState)))return O.warn("RTCPeerConnection closed. Please rejoin room to restore services."),r.error(A.L_ABSTRACT_ROOM_RECONNECTED_R,{status:D.FAILED,code:"",msg:"RTCPeerConnection closed"},{logSource:i.RTC}),void this.callbacks.onPeerClosed();const{code:d,data:_}=yield e.context.joinRTCRoom(o,c,s);if(d!==a.SUCCESS)return O.error(`RTC __onReconnected getRTCRoomInfo failed: ${d}`),void r.error(A.L_ABSTRACT_ROOM_RECONNECTED_R,{status:D.FAILED,code:d,msg:""},{logSource:i.RTC});O.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(_)}`);const u=[],l={},h={},R={},m=$t(_,o),p=Object.keys(m),S=e.getAllUserIds();for(let t=p.length-1;t>=0;t-=1){const r=p[t],i=S.indexOf(r);if(-1===i){u.push(r),l[r]=Dt(m[r]);continue}const s=e.getResourcesByUserId(r),o=m[r],{publishedList:n,modifiedList:a,unpublishedList:c}=Nt(s,o,!0);l[r]=Dt(n),h[r]=Dt(c),R[r]=Dt(a),S.splice(i,1)}S.length&&S.forEach((t=>{e.removeResourcesByUserId(t)})),e.assignRoomData(m),S.length&&this.callbacks.onUserLeave(S),u.length&&this.callbacks.onUserJoin(u);for(const r in h){if(r===n)continue;const i=h[r];if(i.length){const r=i.map((t=>e.getRemoteTrack(Ot(t))));yield new zr(this.subhook,r,this.callbacks.onTrackUnpublish).execute(e,t)}}return Object.keys(l).forEach((t=>{const r=l[t];if(0===r.length)return;const i=r.map((t=>{const r=Ot(t),{userId:i,tag:s,mediaType:o}=Lt(r),n=o===He.AUDIO_ONLY?new pt(s,i):new St(s,i);return e.addRemoteTrack(n),n.__innerSetRemoteMuted(0===t.state),n}));this.callbacks.onTrackPublish(i)})),Object.keys(R).forEach((t=>{R[t].forEach((t=>{const r=Ot(t),i=e.getRemoteTrack(r);i.__innerSetRemoteMuted(0===t.state),i.isAudioTrack()?this.callbacks.onAudioMuteChange(i):this.callbacks.onVideoMuteChange(i)}))})),e.roomMode===Ir.LIVE&&this.executeInLivingRoom(e,_),r.info(A.L_ABSTRACT_ROOM_RECONNECTED_R,{status:D.SUCCESSED,roomData:_},{logSource:i.RTC}),{data:_}}))}executeInLivingRoom(e,t){var s,o;if(r.error(A.L_LIVING_ROOM_RECONNECTED_T,{roomData:t},{logSource:i.RTC}),!t)return void r.info(A.L_LIVING_ROOM_RECONNECTED_R,{status:D.FAILED,code:"",msg:"room not fond"},{logSource:i.RTC});const{roomInfo:n}=t,a=null===(s=n.filter((e=>"cdn_uris"===e.key))[0])||void 0===s?void 0:s.value;if(!a)return void r.error(A.L_LIVING_ROOM_RECONNECTED_R,{status:D.FAILED,code:"",msg:"cdn_uris not found"},{logSource:i.RTC});const c=JSON.parse(a),d=(null===(o=e.getCDNUris())||void 0===o?void 0:o.enableInnerCDN)!==c.enableInnerCDN;e.setCDNUris(c),r.info(A.L_LIVING_ROOM_RECONNECTED_R,{status:D.SUCCESSED,roomData:t},{logSource:i.RTC}),d&&this.callbacks.onCDNEnableChange(c.enableInnerCDN)}}class oi extends Br{constructor(e,t,r,i=Sr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var r,i,s;return v(this,void 0,void 0,(function*(){const{tracks:o}=this,{roomId:n}=e;if(O.info(`unsubscribe -> roomId: ${n}, tracks: ${o.map(Gt)}`),this.state===Sr.NORMAL){const i=e.getSubscribedList().slice(),{code:s,failedList:n}=yield new Wr(o,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,i);return null===(r=this.callbacks)||void 0===r||r.onTaskCompleted({code:s,subscribe:c,unsubscribe:d,failedList:n}),{code:s,failedList:n}}if(this.state===Sr.TAIL){const{code:r}=yield new oi(this.tracks,this.subhook,this.callbacks,Sr.MIDDLE).execute(e,t);if(r===L.SUCCESS){const r=e.getCollectSubscribeList().slice(0),o=e.getSubscribedList().slice(),{code:n,failedList:a}=yield new Wr(r,this.subhook).execute(e,t);if(n!==L.SUCCESS)return null===(i=this.callbacks)||void 0===i||i.onTaskCompleted({code:n,subscribe:[],unsubscribe:[],failedList:a}),{code:n,failedList:a};const c=e.getSubscribedList().slice(0),{subscribe:d,unsubscribe:_}=this.pickoutSubscribed(c,o);return null===(s=this.callbacks)||void 0===s||s.onTaskCompleted({code:n,subscribe:d,unsubscribe:_,failedList:a}),{code:n,failedList:a}}return{code:r}}return Br.AsyncUpdateSubscribeTasks.splice(Br.AsyncUpdateSubscribeTasks.length,0,...this.tracks),new Promise((t=>{const r=this.formateTrack(o);e.resetCollectSubscribeList(r),t({code:L.SUCCESS})}))}))}}class ni extends Br{constructor(e,t,r,i=Sr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var s;return v(this,void 0,void 0,(function*(){const{tracks:n}=this,{roomId:a}=e;if(this.state===Sr.NORMAL){const r=e.getSubscribedList().slice(),{code:i,failedList:o}=yield new Xr(n,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,r);return null===(s=this.callbacks)||void 0===s||s.onTaskCompleted({code:i,subscribe:c,unsubscribe:d,failedList:o}),{code:i,failedList:o}}if(r.info(A.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:n.map(Gt)},{logSource:i.RTC}),!o("tracks",n,(()=>d(n)&&n.length>0&&n.every((e=>e instanceof mt||e.track instanceof mt))),!0))return O.warn(`subscribe failed, tracks is invalid -> roomId: ${a}`),r.error(A.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};O.info(`subscribe -> roomId: ${a}, tracks: ${n.map(Gt)}`);const c=this.getSubscribedList(e).map((e=>Object.assign({},e))),_=n.map((e=>e instanceof mt?{track:e}:e)),u=[];if(_.forEach((e=>{const t=e.track.getTrackId();u.push(t);const r=c.find((e=>e.track.getTrackId()===t));if(r){if(r.subTiny===e.subTiny)return;r.subTiny=e.subTiny}else c.push(e)})),e.polarisReport.sendR2(gr.SUBSCRIBE,fr.BEGIN,u),r.info(A.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:n.map(Gt),roomId:a},{logSource:i.RTC}),this.state===Sr.TAIL){const{code:r}=yield new ni(this.tracks,this.subhook,this.callbacks,Sr.MIDDLE).execute(e,t);if(r===L.SUCCESS){const r=e.getCollectSubscribeList().slice(0);return new oi(r,this.subhook,this.callbacks).execute(e,t)}return{code:r}}return Br.AsyncSubscribeTasks.splice(Br.AsyncSubscribeTasks.length,0,...this.tracks),new Promise((t=>{e.resetCollectSubscribeList(c),t({code:L.SUCCESS})}))}))}getSubscribedList(e){return this.state===Sr.MIDDLE?e.getCollectSubscribeList():e.getSubscribedList()}}class ai extends Br{constructor(e,t,r,i=Sr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var s;return v(this,void 0,void 0,(function*(){const{tracks:n}=this,{roomId:a}=e;if(this.state===Sr.NORMAL){const r=e.getSubscribedList().slice(),{code:i,failedList:o}=yield new Yr(n,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,r);return null===(s=this.callbacks)||void 0===s||s.onTaskCompleted({code:i,subscribe:c,unsubscribe:d,failedList:o}),{code:i,failedList:o}}if(r.info(A.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:n.map(Gt)},{logSource:i.RTC}),!o("tracks",n,(()=>d(n)&&n.length>0&&n.every((e=>e instanceof mt))),!0))return O.warn(`unsubscribe failed, tracks is invalid -> roomId: ${a}`),r.warn(A.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};O.info(`unsubscribe -> roomId: ${a}, tracks: ${n.map(Gt)}`);const c=this.getSubscribedList(e).map((e=>Object.assign({},e))).filter((e=>!n.includes(e.track)));if(e.polarisReport.sendR2(gr.SUBSCRIBE,fr.END,n.map((e=>e.getTrackId()))),r.info(A.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:n.map(Gt),roomId:a},{logSource:i.RTC}),this.state===Sr.TAIL){const{code:r}=yield new ai(this.tracks,this.subhook,this.callbacks,Sr.MIDDLE).execute(e,t);if(r===L.SUCCESS){const r=e.getCollectSubscribeList().slice(0).map((e=>e.track));return new oi(r,this.subhook,this.callbacks).execute(e,t)}return{code:r}}return Br.AsyncUnsubscribeTasks.splice(Br.AsyncUnsubscribeTasks.length,0,...this.tracks),new Promise((t=>{e.resetCollectSubscribeList(c),t({code:L.SUCCESS})}))}))}getSubscribedList(e){return this.state===Sr.MIDDLE?e.getCollectSubscribeList():e.getSubscribedList()}}!function(e){e[e.SERVER_KICK=1]="SERVER_KICK",e[e.OTHER_KICK=2]="OTHER_KICK"}(Lr||(Lr={}));const ci={[Lr.SERVER_KICK]:1,[Lr.OTHER_KICK]:5},di="evt-leave";class _i extends t{constructor(e,t,r,i,s,o,n,a,c,d=qt()){super(),this._context=e,this._runtime=t,this._roomId=r,this._service=s,this._initOptions=o,this._useMutilPeerC=c,this._clientSessionId=d,this._appListener=null,this._reportListener=null,this._onRecvPKMsg=null,this._polarisReport=new Pr(this._context,this._runtime,this._roomId,this),this._peerCManager=new xr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._invoker=new $r(this._context,this._service,this._peerCManager,r,this._context.getCurrentId(),i,this._polarisReport,n,a),this._store=this._invoker.store}__innerInit(e,t,r,i,s){return v(this,void 0,void 0,(function*(){const{code:o,data:n}=yield this._invoker.push(new Gr(this._roomId,e,t,r,i,s));return o!==L.SUCCESS?{code:o}:(this._initWithRoomData(n.offlineKickTime),{code:o,data:n})}))}_initWithRoomData(e){var t;this._pinger=new Jt(this._store.roomId,this._store.roomMode,this._context,this._initOptions.pingGap,1e3*e),this._pinger.onFailed=this._kickoff.bind(this),this._pinger.onPingResult=this._handlePingResult.bind(this),this._pinger.start(),null===(t=this._polarisReport)||void 0===t||t.sendR1()}_handlePingResult(e){this._callAppListener("onPing",e)}setBitrate(e,t,r){if(this._useMutilPeerC)return void O.error("`RCAbstractRoom.setBitrate` is disabled, use `RCLocalTrack.setBitrate` instead.");O.warn("`RCAbstractRoom.setBitrate` will be deprecated, use `RCLocalTrack.setBitrate` instead."),S("max",e,(e=>s(e)&&e>Math.max(t||1,200)),!0),S("min",t,(t=>s(t)&&t>=1&&(!s(e)||t<e)),!0),S("start",r,(r=>s(r)&&r>t&&r<=e));this._peerCManager.getPCList().forEach((i=>{i.setBitrate(e,t,r)}))}_onTrackReady(e){const t=e.streams[0].id,{track:s}=e.receiver,o=[t,"audio"===s.kind?He.AUDIO_ONLY:He.VIDEO_ONLY].join("_"),n=this._store.getRemoteTrack(o);if(!n)return void O.warn(`cannot found remote track ${s.id}`);n.__innerSetMediaStreamTrack(s);const a=Qt.getMemo();r.info(A.L_QS_TRACK_READY_O,{identify:a.qualityStatusId},{logSource:i.RTC}),this._callAppListener("onTrackReady",n)}_callAppListener(e,...t){var s;"onPing"!==e&&r.info(A.L_ABSTRACT_ROOM_CALL_APP_LISTENER_O,{status:D.SUCCESSED,eventType:e,attrs:t},{logSource:i.RTC}),"onPing"!==e&&O.info(`${e} callback ->`,...t);const o=null===(s=this._appListener)||void 0===s?void 0:s[e];if(o)try{o(...t)}catch(e){O.error(e)}}_onTrackUnpublish(e){this._callAppListener("onTrackUnpublish",e)}__parseInnerMessage(e){var t;const{targetId:s,conversationType:o}=e;if(s!==this._roomId)return r.warn(A.L_RTC_CLIENT_MESSAGE_O,{status:D.FAILED,message:`roomId is different, msg roomId-> ${s}, this._roomId-> ${this._roomId} `},{logSource:i.RTC}),!0;O.info(`recv inner msg -> message: ${JSON.stringify(e)} | roomid: ${this._roomId}`);const{content:n}=e,a=Qt.getMemo();switch(e.messageType){case jt.KICK:this._kickoff(!0,n);break;case jt.STATE:this._stateHandle(n);break;case jt.MODIFY:case jt.PUBLISH:case jt.UNPUBLISH:case jt.TOTAL_CONTENT_RESOURCE:if(!a.messageData){a.messageData={sentTime:e.sentTime,senderUserId:e.senderUserId};const r=Date.now(),o={dur:r-e.sentTime,puid:e.senderUserId,rid:s,csnid:null===(t=a.clientData)||void 0===t?void 0:t.clientSessionId,snid:this.getSessionId(),time:r,cr:"unknown",net:"unknown",uid:this.getCrtUserId()},n=JSON.stringify(o);h(R.STATISTICS,A.L_QS_RECV_PUB_MSG_S,n,i.RTC)}this._resourceHandle(n,e.messageType,e.senderUserId);break;case jt.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",e.messageType,e.content);break;case jt.USER_NOTIFY:O.warn(`TODO: ${jt.USER_NOTIFY}`);break;case jt.PK_INVITE:case jt.PK_CANCEL_INVITE:case jt.PK_INVITE_TIMEOUT:case jt.PK_INVITE_ANSWER:case jt.PK_END:this._onRecvPKMsg&&this._onRecvPKMsg(e);break;case jt.OTHER_ROOM_OFFLINE:break;default:this._callAppListener("onMessageReceive",e.messageType,n,e.senderUserId,e.messageUId)}return!0}_kickoff(e,t){return v(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;let r,s;if(O.warn(`onKickOff -> byServer: ${e}`),this.emit(di),this._leaveHandle(!e),e){((null==t?void 0:t.users)||[]).forEach((e=>{e.userId===this._context.getCurrentId()&&(s=e.type,r=e.kickExtra)}));const e=Date.now(),o=JSON.stringify({cod:ci[s||1],rid:this._roomId,csnid:this.getClientSessionId(),snid:this.getSessionId(),time:e,cr:"unknown",net:"unknown",uid:this.getCrtUserId()});h(R.STATISTICS,A.L_QS_KICKED_S,o,i.RTC)}this._callAppListener("onKickOff",e,s,r)}))}_rtcpeerClosed(){this.emit(di),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,t,r){return v(this,void 0,void 0,(function*(){const{uris:i,ignore:s}=e;!s&&i&&this._invoker.push(new Zr(e,t,r,this._subhook.bind(this),{onAudioMute:this._onAudioMuteChange.bind(this),onVideoMute:this._onVideoMuteChange.bind(this),onTrackPublish:this._onTrackPublish.bind(this),onTrackUnublish:this._onTrackUnpublish.bind(this),onCDNEnableChange:this._callAppListener.bind(this,"onCDNEnableChange")}))}))}_onTrackPublish(e){this._callAppListener("onTrackPublish",e)}_stateHandle(e){var t;return v(this,void 0,void 0,(function*(){const{left:r,joined:i,upgrade:s,downgrade:o}=yield this._invoker.push(new Qr(e,this._subhook.bind(this)));if(null===(t=this._appListener)||void 0===t?void 0:t.onSwitchRole)return s.length&&s.forEach((e=>this._callAppListener("onSwitchRole",e,mr.ANCHOR))),o.length&&o.forEach((e=>this._callAppListener("onSwitchRole",e,mr.AUDIENCE))),i.length&&this._callAppListener("onUserJoin",i),void(r.length&&this._callAppListener("onUserLeave",r));const n=[...i,...s],a=[...r,...o];n.length&&this._callAppListener("onUserJoin",n),a.length&&this._callAppListener("onUserLeave",a)}))}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}__getPC(){return this._store.peerMgr.getPCList()}getRemoteUserIds(){return this._store.getRemoteUserIds()}getRemoteTracks(){const e=[];return this.getRemoteUserIds().forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),e}getRemoteTracksByUserId(e){return this._store.getRemoteTracksByUserId(e)}getSessionId(){return this._store.getSessionId()}sendMessage(e,t){return v(this,void 0,void 0,(function*(){r.info(A.L_ABSTRACT_ROOM_SEND_MESSAGE_T,{name:e,content:t},{logSource:i.RTC});const{code:s}=yield this._context.sendMessage(T.RTC_ROOM,this._roomId,{messageType:e,content:t,isStatusMessage:!0});return s!==a.SUCCESS?(O.error(`send message failed -> code: ${s}`),r.error(A.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:D.FAILED,code:s,msg:""},{logSource:i.RTC}),{code:L.SIGNAL_ERROR}):(r.info(A.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:D.SUCCESSED,name:e,content:t},{logSource:i.RTC}),{code:L.SUCCESS})}))}setRoomAttribute(e,t,s,o=!1){return v(this,void 0,void 0,(function*(){r.info(A.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_T,{roomId:this._roomId,key:e,value:t,message:s,isInner:o},{logSource:i.RTC});const n=yield this._context.setRTCData(this._roomId,e,t,o,Or.ROOM,s);return n!==a.SUCCESS?(O.error(`SetRoomAttributeValue Failed: ${n}`),r.error(A.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:D.FAILED,code:n,msg:""},{logSource:i.RTC}),{code:L.SIGNAL_ERROR}):(r.info(A.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:D.SUCCESSED,roomId:this._roomId,key:e,value:t,message:s,isInner:o},{logSource:i.RTC}),{code:L.SUCCESS})}))}deleteRoomAttributes(e,t,s=!1){return v(this,void 0,void 0,(function*(){r.info(A.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_T,{roomId:this._roomId,keys:e,message:t,isInner:s},{logSource:i.RTC});const o=yield this._context.removeRTCData(this._roomId,e,s,Or.ROOM,t);return o!==a.SUCCESS?(O.error(`DeleteRoomAttribute Failed: ${o}`),r.error(A.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:D.FAILED,code:o,msg:""},{logSource:i.RTC}),{code:L.SIGNAL_ERROR}):(r.info(A.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:D.SUCCESSED,roomId:this._roomId,keys:e,message:t,isInner:s},{logSource:i.RTC}),{code:L.SUCCESS})}))}getRoomAttributes(e=[],t=!1){return v(this,void 0,void 0,(function*(){const{code:r,data:i}=yield this._context.getRTCData(this._roomId,e,t,Or.ROOM);return r!==a.SUCCESS?(O.error(`GetRoomAttributes Failed: ${r}`),{code:L.SIGNAL_ERROR}):{code:L.SUCCESS,data:i}}))}_setUserAttributeValue(e,t,r){return this._context.setRTCData(this._roomId,e,t,!1,Or.PERSON,r)}_deleteUserAttributes(e,t){return this._context.removeRTCData(this._roomId,e,!1,Or.PERSON,t)}_getUserAttributes(e){return this._context.getRTCData(this._roomId,e,!1,Or.PERSON)}isDestroyed(){return this._invoker.isDestroyed()}__destroy(e){return this._leaveHandle(e)}_muteRemoteTracksBeforeQuit(){const e=Object.values(this._store.getRemoteTracks());e.length&&e.forEach((e=>e.mute()))}_leaveHandle(e){var t;return v(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;Qt.destroy(),this._invoker.destroy(),this._muteRemoteTracksBeforeQuit(),this._muteRemoteTracksBeforeQuit(),null===(t=this._audioLevelReport)||void 0===t||t.clearAudioLevelReportTimer(),e&&(yield this._context.quitRTCRoom(this._roomId)),this._store.isMainRoom&&(yield this._quitAllPKRoom()),this._pinger.stop();const r=[];Object.keys(this._peerCManager.getMutilPeerCData()).forEach((e=>{r.push(this._service.exit(this._getRTCReqestHeaders(e)))})),yield Promise.all(r),this._releasePCManager(),this._polarisReport=null}))}_releasePCManager(){const e=this._peerCManager.getPCList();null==e||e.forEach((e=>{e.off(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)})),this._peerCManager.clear(),this._peerCManager=null}_onLocalTrackDestroied(e){e instanceof at&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(e,t){return v(this,void 0,void 0,(function*(){this._invoker.push(new ri(e,t))}))}publish(e){return v(this,void 0,void 0,(function*(){return this._invoker.push(new ei(e,this._pubhook.bind(this)))}))}_getPushOtherRoomsParams(){return[]}_reTryExchange(e,t){return v(this,void 0,void 0,(function*(){this._invoker.push(new ii(e,t,(e=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(e)}))))}))}_getRTCReqestHeaders(e){return{"App-Key":this._context.getAppkey(),RoomId:this._roomId,Token:this._store.getToken(),RoomType:this._store.roomMode,UserId:this._context.getCurrentId(),"Client-Session-Id":this._clientSessionId,"Peer-Connection-Id":e}}unpublish(e){return v(this,void 0,void 0,(function*(){return this._invoker.push(new ti(e,((e,t)=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(t)}))))}))}_getResourceById(e){return this._store.getPublishedResourceByTrackId(e)}_isValidResourceId(e){var t;const{userId:r}=Lt(e);return!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>Ot(t)===e)))}_subhook(e){const{pc:t,pcName:r}=this._peerCManager.createPeerCList(e)[0];return t.on(Ur.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),t.__reportR3R4ToPolaris(),t.registerReportListener(this._reportListener),t.clearReTryExchangeTimer(),{pc:t,pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(r)}}_pubhook(e){return{plist:this._peerCManager.createPeerCList(e).map((e=>{const{pc:t,pcName:r}=e;return t.on(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.on(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),t.registerReportListener(this._reportListener),t.__reportR3R4ToPolaris(),Object.assign(Object.assign({},e),{headers:this._getRTCReqestHeaders(r)})})),pushOtherRooms:this._getPushOtherRoomsParams()}}subscribe(e){return v(this,void 0,void 0,(function*(){return this._invoker.push(new Xr(e,this._subhook.bind(this)))}))}addSubscribeTask(e){this._invoker.push(new ni(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}unsubscribe(e){return v(this,void 0,void 0,(function*(){return this._invoker.push(new Yr(e,this._subhook.bind(this)))}))}addUnsubscribeTask(e){this._invoker.push(new ai(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}updateSubList(e){return v(this,void 0,void 0,(function*(){return this._invoker.push(new Wr(e,this._subhook.bind(this)))}))}addUpdateSubscribeListTask(e){this._invoker.push(new oi(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}_onTaskCompleted(e){this._callAppListener("onTaskCompleted",e.code,e.subscribe,e.unsubscribe,e.failedList)}getLocalTrack(e){return this._store.getLocalTrack(e)}getLocalTracks(){return this._store.getLocalTracks()}getRemoteTrack(e){return this._store.getRemoteTrack(e)||null}get subscribedTracks(){return this._store.getSubscribedList().slice()}registerRoomEventListener(e){r.info(A.L_ABSTRACT_ROOM_REGISTER_ROOM_EVENT_LISTENER_O,{status:D.SUCCESSED,listener:e&&Object.keys(e)},{logSource:i.RTC}),this._appListener=e}registerReportListener(e){r.info(A.L_ABSTRACT_ROOM_REGISTER_REPORT_LISTENER_O,{status:D.SUCCESSED,listener:e&&Object.keys(e)},{logSource:i.RTC}),this._reportListener=e}onAudioLevelChange(e,t){var s;r.info(A.L_ABSTRACT_ROOM_AUDIO_LEVEL_O,{status:D.SUCCESSED,handler:null==e?void 0:e.name,gap:t},{logSource:i.RTC}),null===(s=this._audioLevelReport)||void 0===s||s.clearAudioLevelReportTimer(),this._audioLevelReport=new Mr(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}__onReconnected(e){return v(this,void 0,void 0,(function*(){return this._invoker.push(new si(this._subhook.bind(this),{onPeerClosed:this._rtcpeerClosed.bind(this),onAudioMuteChange:this._onAudioMuteChange.bind(this),onVideoMuteChange:this._onVideoMuteChange.bind(this),onUserJoin:this._callAppListener.bind(this,"onUserJoin"),onUserLeave:this._callAppListener.bind(this,"onUserLeave"),onTrackPublish:this._onTrackPublish.bind(this),onTrackUnpublish:this._onTrackUnpublish.bind(this),onCDNEnableChange:this._callAppListener.bind(this,"onCDNEnableChange")},e))}))}_onAudioMuteChange(e){this._callAppListener("onAudioMuteChange",e)}_onVideoMuteChange(e){this._callAppListener("onVideoMuteChange",e)}_registerPKMsgListener(e){this._onRecvPKMsg=e}_quitAllPKRoom(){}getClientSessionId(){return this._clientSessionId}}class ui extends wr{constructor(e,t){super(),this.data=e,this.cdnValues=t}execute(e,t){var r,i,s,o;return v(this,void 0,void 0,(function*(){const t={"App-Key":e.context.getAppkey(),Token:e.getToken(),RoomId:e.roomId,UserId:e.context.getCurrentId(),SessionId:e.getSessionId()},{code:n,res:a}=yield e.service.setMcuConfig(t,this.data);if(n!==L.SUCCESS)return O.error(`set MCU config failed: ${n}`),{code:n};O.info("set MCU config success"),a.pull_url&&e.setCDNUris(JSON.parse(a.pull_url));const c=this.cdnValues;return n===L.SUCCESS&&((null===(i=null===(r=c.output)||void 0===r?void 0:r.video.normal)||void 0===i?void 0:i.width)||(null===(o=null===(s=c.output)||void 0===s?void 0:s.video.normal)||void 0===o?void 0:o.fps))&&Jr(e),{code:n,res:a}}))}}var li,hi,Ri,mi;!function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(li||(li={})),function(e){e[e.CUSTOMIZE=1]="CUSTOMIZE",e[e.SUSPENSION=2]="SUSPENSION",e[e.ADAPTATION=3]="ADAPTATION"}(hi||(hi={})),function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(Ri||(Ri={})),function(e){e[e.AUDIO_VIDEO_ALL=0]="AUDIO_VIDEO_ALL",e[e.AUDIO_VIDEO_NO=1]="AUDIO_VIDEO_NO",e[e.AUDIO_ALL_VIDEO_NO=2]="AUDIO_ALL_VIDEO_NO",e[e.AUDIO_NO_VIDEO_ALL=3]="AUDIO_NO_VIDEO_ALL",e[e.AUDIO_VIDEO_INPUT=4]="AUDIO_VIDEO_INPUT",e[e.AUDIO_ALL_VIDEO_INPUT=5]="AUDIO_ALL_VIDEO_INPUT",e[e.AUDIO_NO_VIDEO_INPUT=6]="AUDIO_NO_VIDEO_INPUT",e[e.AUDIO_INPUT_VIDEO_ALL=7]="AUDIO_INPUT_VIDEO_ALL",e[e.AUDIO_INPUT_VIDEO_NO=8]="AUDIO_INPUT_VIDEO_NO",e[e.ROOM_AUDIO_VIDEO_APPEND=9]="ROOM_AUDIO_VIDEO_APPEND",e[e.ROOM_AUDIO_VIDEO_NOT_APPEND=10]="ROOM_AUDIO_VIDEO_NOT_APPEND",e[e.ROOM_AUDIO_APPEND=11]="ROOM_AUDIO_APPEND",e[e.ROOM_AUDIO_NOT_APPEND=12]="ROOM_AUDIO_NOT_APPEND",e[e.ROOM_VIDEO_APPEND=13]="ROOM_VIDEO_APPEND",e[e.ROOM_VIDEO_NOT_APPEND=14]="ROOM_VIDEO_NOT_APPEND"}(mi||(mi={}));const pi=()=>({version:2,mode:hi.SUSPENSION});class Si{constructor(e,t){this._invoker=e,this._isValidTrackId=t,this._values=pi()}setHostVideoTrack(e){if(O.info(`setHostVideoTrack -> videoTrackId: ${e}`),!this._isValidTrackId(e))return O.error(`setHostVideoTrack failed -> videoTrackId is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:D.FAILED,code:"",msg:"params error -> videoTrackId"},{logSource:i.RTC}),this;const{mediaType:t,tag:s,userId:o}=Lt(e);return t!==He.VIDEO_ONLY?(O.error(`setHostVideoTrack failed -> kind of resource is not 'video' -> ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:D.FAILED,code:"",msg:"not video"},{logSource:i.RTC}),this):(this._values.host_stream_id=At(o,s),r.info(A.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:D.SUCCESSED,videoTrackId:e},{logSource:i.RTC}),this)}setMixLayoutMode(e){O.info(`setMixLayoutMode -> mode: ${e}`);return[hi.CUSTOMIZE,hi.SUSPENSION,hi.ADAPTATION].includes(e)?(this._values.mode=e,r.info(A.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:D.SUCCESSED,mode:e},{logSource:i.RTC}),this):(O.error(`setMixLayoutMode failed -> mode is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:D.SUCCESSED,code:"",msg:`params error -> mode: ${e}`},{logSource:i.RTC}),this)}_addOutputValue(e,t,r="normal"){const i=this._values.output||(this._values.output={video:{normal:{width:640,height:480}}});if("cdn"===e)return void(i.cdn=t);if("audio"===e)return void(i.audio={bitrate:t});const{video:s}=i;if("normal"!==r&&"tiny"!==r)if("backgroundColor"!==r)if("exparams"!==r){if("backgroundPicture"===r){const e=s.backgroundPicture||(s.backgroundPicture={fillMode:li.CROP,picture:[]});Object.assign(e,t)}}else s.exparams={renderMode:t};else s.backgroundColor=t;else{const e=s[r]||(s[r]={});Object.assign(e,t)}}setOutputVideoResolution(e){if(O.info(`setOutputVideoResolution -> resolution: ${e}`),!yt(e))return O.error(`setOutputVideoResolution failed -> resolution is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:D.FAILED,code:"",msg:`params error -> resolution: ${e}`},{logSource:i.RTC}),this;const{width:t,height:s}=kt(e);return this._addOutputValue("video",{width:t,height:s},"normal"),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:D.SUCCESSED,resolution:e},{logSource:i.RTC}),this}setOutputVideoFPS(e){if(O.info(`setOutputVideoFPS -> fps: ${e}`),!Ut(e))return O.error(`setOutputVideoFPS failed -> fps is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:D.FAILED,code:"",msg:`params error -> fps: ${e}`},{logSource:i.RTC}),this;const t=Pt(e);return this._addOutputValue("video",{fps:t},"normal"),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:D.SUCCESSED,fps:e},{logSource:i.RTC}),this}setOutputVideoBitrate(e){return O.info(`setOutputVideoBitrate -> bitrate: ${e}`),!s(e)||e<=0?(O.error(`setOutputVideoBitrate failed -> bitrate is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:D.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:i.RTC})):this._addOutputValue("video",{bitrate:e},"normal"),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:D.SUCCESSED,bitrate:e},{logSource:i.RTC}),this}setOutputTinyVideoResolution(e){if(O.info(`setOutputTinyVideoResolution -> resolution: ${e}`),!yt(e))return O.error(`setOutputTinyVideoResolution failed -> resolution is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:D.FAILED,code:"",msg:`params error -> resolution: ${e}`},{logSource:i.RTC}),this;const{width:t,height:s}=kt(e);return this._addOutputValue("video",{width:t,height:s},"tiny"),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:D.SUCCESSED,resolution:e},{logSource:i.RTC}),this}setOutputTinyVideoFPS(e){if(O.info(`setOutputTinyVideoFPS -> fps: ${e}`),!Ut(e))return O.error(`setOutputTinyVideoFPS failed -> fps is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:D.FAILED,code:"",msg:`params error -> fps: ${e}`},{logSource:i.RTC}),this;const t=Pt(e);return this._addOutputValue("video",{fps:t},"tiny"),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:D.SUCCESSED,fps:e},{logSource:i.RTC}),this}setOutputTinyVideoBitrate(e){return O.info(`setOutputTinyVideoBitrate -> bitrate: ${e}`),!s(e)||e<=0?(O.error(`setOutputTinyVideoBitrate failed -> bitrate is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:D.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:i.RTC})):this._addOutputValue("video",{bitrate:e},"tiny"),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:D.SUCCESSED,bitrate:e},{logSource:i.RTC}),this}setOutputVideoRenderMode(e){return O.info(`setOutputVideoRenderMode -> renderMode: ${e}`),[Ri.CROP,Ri.WHOLE].includes(e)?this._addOutputValue("video",e,"exparams"):(O.error(`setOutputVideoRenderMode failed -> renderMode is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:D.FAILED,code:"",msg:`params error -> renderMode: ${e}`},{logSource:i.RTC})),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:D.SUCCESSED,renderMode:e},{logSource:i.RTC}),this}setOutputAudioBitrate(e){return O.info(`setOutputAudioBitrate -> bitrate: ${e}`),s(e)&&e>0?this._addOutputValue("audio",e):(O.error(`setOutputAudioBitrate failed -> bitrate is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:D.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:i.RTC})),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:D.SUCCESSED,bitrate:e},{logSource:i.RTC}),this}setOutputBackgroundColor(e){return O.info(`setOutputBackgroundColor -> color: ${e}`),/^0x[a-fA-F0-9]{6}$/.test(e)?this._addOutputValue("video",e,"backgroundColor"):(O.error(`setOutputBackgroundColor failed -> color is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:D.FAILED,code:"",msg:`params error -> color: ${e}`},{logSource:i.RTC})),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:D.SUCCESSED,color:e},{logSource:i.RTC}),this}addOutputBackgroundPicture(e,t,o,n,a){var c,d,_;if(O.info(`addOutputBackgroundPicture -> uri: ${e}, x: ${t}, y: ${o}, w: ${n}, h: ${a}`),!C(e))return O.error(`addOutputBackgroundPicture failed -> uri is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:D.FAILED,code:"",msg:`params error -> uri: ${e}`},{logSource:i.RTC}),this;if([t,o,n,a].some((e=>!s(e)||e<0||e>1)))return O.error(`addOutputBackgroundPicture failed -> some attrs of (x, y, w, h) is invalid: ${t}, ${o}, ${n}, ${a}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:D.FAILED,code:"",msg:`params error -> x: ${t}, y: ${o}, w: ${n}, h: ${a}`},{logSource:i.RTC}),this;const u=(null===(_=null===(d=null===(c=this._values.output)||void 0===c?void 0:c.video)||void 0===d?void 0:d.backgroundPicture)||void 0===_?void 0:_.picture)||[];return u.push({uri:e,w:n,h:a,x:t,y:o}),this._addOutputValue("video",{picture:u},"backgroundPicture"),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:D.SUCCESSED,uri:e,x:t,y:o,w:n,h:a},{logSource:i.RTC}),this}removeOutputBackgroundPicture(e){var t,s,o;if(O.info(`removeOutputBackgroundPicture -> uri: ${e}`),!C(e))return O.error(`removeOutputBackgroundPicture failed -> uri is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:D.FAILED,code:"",msg:`params error -> uri: ${e}`},{logSource:i.RTC}),this;let n=null===(o=null===(s=null===(t=this._values.output)||void 0===t?void 0:t.video)||void 0===s?void 0:s.backgroundPicture)||void 0===o?void 0:o.picture;return n&&(n=n.filter((t=>t.uri!==e)),this._addOutputValue("video",{pictures:n},"backgroundPicture")),r.info(A.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:D.SUCCESSED,uri:e},{logSource:i.RTC}),this}clearOutputBackgroundPicture(){return O.info("clearOutputBackgroundPicture ->"),this._addOutputValue("video",{pictures:[]},"backgroundPicture"),r.info(A.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:D.SUCCESSED},{logSource:i.RTC}),this}setOutputBackgroundPictureFillMode(e){return O.info(`setOutputBackgroundPictureFillMode -> fillMode: ${e}`),[li.CROP,li.WHOLE].includes(e)?this._addOutputValue("video",{fillMode:e},"backgroundPicture"):(O.error(`setOutputBackgroundPictureFillMode failed -> fillMode is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:D.FAILED,code:"",msg:`params error -> fillMode: ${e}`},{logSource:i.RTC})),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:D.SUCCESSED,fillMode:e},{logSource:i.RTC}),this}addPublishStreamUrls(e){var t,s;O.info(`addPublishStreamUrls -> urls: ${e.join(",")}`);const o=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!o.test(e))))return O.error(`addPublishStreamUrls failed -> urls is invalid: ${e.join(",")}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:D.FAILED,code:"",msg:`params error -> urls: ${e.join(",")}`},{logSource:i.RTC}),this;const n=(null===(s=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===s?void 0:s.concat())||[];let a=!1;return e.forEach((e=>{n.some((t=>t.pushurl===e))||(a=!0,n.push({pushurl:e}))})),n.length>5?(O.error("addPublishStreamUrls failed -> publish stream urls no more than 5!"),r.error(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:D.FAILED,code:"",msg:`params error -> publish stream urls no more than 5, length: ${e.length}`},{logSource:i.RTC}),this):(a&&this._addOutputValue("cdn",n),r.info(A.L_MCU_CONFIG_BUILDER_ADD_PUBLISH_STREAM_URLS_O,{status:D.SUCCESSED,urls:e},{logSource:i.RTC}),this)}removePublishStreamUrls(e){var t,s;O.info(`removePublishStreamUrls -> urls: ${e.join(",")}`);const o=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!o.test(e))))return O.error(`removePublishStreamUrls failed -> urls contain invalid items: ${e.join(",")}`),r.error(A.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:D.FAILED,code:"",msg:`params error -> urls: ${e.join(",")}`},{logSource:i.RTC}),this;const n=(null===(s=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===s?void 0:s.concat())||[];for(let t=n.length-1;t>=0;t-=1){const{pushurl:r}=n[t],i=e.indexOf(r);i>=0&&(e.splice(i,1),n.splice(t,1))}return this._addOutputValue("cdn",n),r.info(A.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:D.SUCCESSED,urls:e},{logSource:i.RTC}),this}clearPublishStreamUrls(){return O.info("clearPublishStreamUrls ->"),this._addOutputValue("cdn",[]),r.info(A.L_MCU_CONFIG_BUILDER_CLEAR_PUBLISH_STREAM_URLS_O,{status:D.SUCCESSED},{logSource:i.RTC}),this}addCustomizeLayoutVideo(e,t,o,n,a){if(O.info(`addCustomizeLayoutVideo -> trackId: ${e}, x: ${t}, y: ${o}, width: ${n}, height: ${a}`),!m(e)||!this._isValidTrackId(e))return O.error(`addCustomizeLayoutVideo failed -> trackId is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;if(!s(t)||!s(o))return O.error(`addCustomizeLayoutVideo failed -> some attrs of (x, y) is invalid: ${t}, ${o}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.FAILED,code:"",msg:`params error -> x: ${t}, y: ${o}`},{logSource:i.RTC}),this;if([n,a].some((e=>!s(e)||e<0)))return O.error(`addCustomizeLayoutVideo failed -> some attrs of (width, height) is invalid: ${n}, ${a}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.FAILED,code:"",msg:`params error -> width: ${n}, height: ${a}`},{logSource:i.RTC}),this;const{userId:c,tag:d,mediaType:_}=Lt(e);if(_!==He.VIDEO_ONLY)return O.error(`addCustomizeLayoutVideo failed -> kind of trackId is not 'video': ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}的资源不是视频`},{logSource:i.RTC}),this;const u=At(c,d),l=this._values.input||(this._values.input={}),h=l.video||(l.video=[]);return h.some((e=>e.height===a&&e.width===n&&e.stream_id===u&&e.user_id===c&&e.x===t&&e.y===o))?(r.warn(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.FAILED,code:"",msg:"Duplicate configuration item ignored"},{logSource:i.RTC}),this):(h.push({user_id:c,stream_id:u,x:t,y:o,width:n,height:a}),r.info(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.SUCCESSED,trackId:e,x:t,y:o,width:n,height:a},{logSource:i.RTC}),this)}removeCustomizeLayoutVideo(e){if(O.info(`clearCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return O.error(`clearCustomizeInputAudio failed -> trackId is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const{userId:t,tag:s,mediaType:o}=Lt(e);if(o!==He.VIDEO_ONLY)return O.error(`clearCustomizeInputAudio failed -> kind of trackId is not 'video': ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}的资源不是视频`},{logSource:i.RTC}),this;const n=At(t,s),{input:a}=this._values;return(null==a?void 0:a.video)&&a.video.length>0&&(a.video=a.video.filter((e=>e.stream_id===n))),r.info(A.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.SUCCESSED,trackId:e},{logSource:i.RTC}),this}clearCustomizeLayoutVideo(){O.info("clearCustomizeLayoutVideo ->");const{input:e}=this._values;return null==e||delete e.video,r.info(A.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_LAYOUT_VIDEO_O,{status:D.SUCCESSED},{logSource:i.RTC}),this}setCustomizeInputAudio(e){if(O.info(`setCustomizeInputAudio -> trackIds: ${e.join(",")}`),e.some((e=>this._isValidTrackId(e))))return O.warn(`setCustomizeInputAudio failed -> trackIds contain invalid items: $${e.join(",")}`),r.error(A.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:D.FAILED,code:"",msg:`params error -> trackIds: ${e.join(",")}`},{logSource:i.RTC}),this;return(this._values.input||(this._values.input={})).audio=e.map((e=>{const{userId:t,tag:r}=Lt(e);return{stream_id:At(t,r),user_id:t}})),this._values.inputFilterMode=mi.AUDIO_INPUT_VIDEO_ALL,r.info(A.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:D.SUCCESSED,trackIds:e},{logSource:i.RTC}),this}addCustomizeInputAudio(e){if(O.info(`addCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return O.warn(`addCustomizeInputAudio failed -> trackId is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const t=this._values.input||(this._values.input={}),s=t.audio||(t.audio=[]),{userId:o,tag:n}=Lt(e),a=At(o,n);return s.some((e=>e.stream_id===a&&e.user_id===o))?(r.warn(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:D.FAILED,code:"",msg:`trackId:${e} is exist`},{logSource:i.RTC}),this):(s.push({user_id:o,stream_id:a}),this._values.inputFilterMode=mi.AUDIO_INPUT_VIDEO_ALL,r.info(A.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:D.SUCCESSED,trackId:e},{logSource:i.RTC}),this)}removeCustomizeInputAudio(e){if(O.info(`removeCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return O.error(`removeCustomizeInputAudio failed -> trackId is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const{input:t}=this._values;if(!(null==t?void 0:t.audio)||0===t.audio.length)return r.error(A.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:D.FAILED,code:"",msg:"not audio"},{logSource:i.RTC}),this;const{userId:s,tag:o}=Lt(e),n=At(s,o);return t.audio=t.audio.filter((e=>s!==e.user_id||n!==e.stream_id)),r.info(A.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:D.SUCCESSED,trackId:e},{logSource:i.RTC}),this}clearCustomizeInputAudio(){O.info("clearCustomizeInputAudio ->");const{input:e}=this._values;return(null==e?void 0:e.audio)&&delete e.audio,this._values.inputFilterMode=mi.AUDIO_VIDEO_ALL,r.info(A.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_INPUT_AUDIO_O,{status:D.SUCCESSED},{logSource:i.RTC}),this}addPictureWaterMark(e,t,o,n,a,c){if(O.info(`addPictureWaterMark -> trackId: ${e} uri: ${t}, x: ${o}, y: ${n}, w: ${a}, h: ${c}`),!this._isValidTrackId(e))return O.warn(`addPictureWaterMark failed -> trackId is invalid: ${e}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;if(!C(t))return O.error(`addPictureWaterMark failed -> uri is invalid: ${t}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:D.FAILED,code:"",msg:`params error -> uri: ${t}`},{logSource:i.RTC}),this;if([o,n,a,c].some((e=>!s(e)||e<0||e>1)))return O.error(`addPictureWaterMark failed -> some attrs of (x, y, w, h) is invalid: ${o}, ${n}, ${a}, ${c}`),r.error(A.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:D.FAILED,code:"",msg:`params error -> x: ${o}, y: ${n}, w: ${a}, h: ${c}`},{logSource:i.RTC}),this;const{userId:d,tag:_}=Lt(e),u=At(d,_),l=this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]}),{singleScreen:h}=l;O.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(h)}`);const R=h.filter((e=>e.streamId===u))[0];return O.info(`addPictureWaterMark target-> : ${R}`),R?R.picture.push({uri:t,w:a,h:c,x:o,y:n}):h.push({streamId:u,picture:[{uri:t,w:a,h:c,x:o,y:n}]}),O.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(h)}`),this._values.waterMark.singleScreen=h,O.info(`addPictureWaterMark this._values.waterMark.singleScreen-> : ${JSON.stringify(this._values.waterMark.singleScreen)}`),r.info(A.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:D.SUCCESSED,trackId:e,uri:t,x:o,y:n,w:a,h:c},{logSource:i.RTC}),this}clearPictureWaterMark(){O.info("clearOutputBackgroundPicture ->");return(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen=[],r.info(A.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:D.SUCCESSED},{logSource:i.RTC}),this}removePictureWaterMark(e,t){if(!m(e)||!this._isValidTrackId(e))return r.error(A.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O,{status:D.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const{userId:s,tag:o}=Lt(e),n=At(s,o),a=this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]}),{singleScreen:c}=a;return c.forEach((e=>{e.streamId===n&&(e.picture=e.picture.filter((e=>e.uri!==t)))})),r.info(A.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O,{status:D.SUCCESSED,trackId:e,uri:t},{logSource:i.RTC}),this}reset(){return O.info("MCUConfigBuilder.reset ->"),this._values=pi(),r.info(A.L_MCU_CONFIG_BUILDER_RESET_O,{status:D.SUCCESSED},{logSource:i.RTC}),this}flush(e=!0){return v(this,void 0,void 0,(function*(){const t=JSON.parse(JSON.stringify(this._values)),{code:s}=yield this._invoker.push(new ui(t,this._values));return e&&(this._values=pi()),r.info(A.L_MCU_CONFIG_BUILDER_FLUSH_O,{status:D.SUCCESSED},{logSource:i.RTC}),{code:s}}))}__innerGetValues(){return JSON.parse(JSON.stringify(this._values))}}var Ti,Ci,Ii,Ei;!function(e){e[e.VIDEO=0]="VIDEO",e[e.AUDIO=1]="AUDIO"}(Ti||(Ti={})),function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(Ci||(Ci={}));class gi extends wr{constructor(e,t,r){super(),this.roomId=e,this.hooks=t,this.roomPKHandler=r}_exchangeWithPushOtherRoom(e,t){return v(this,void 0,void 0,(function*(){if(!e.getLocalTracks().length)return;const r=Object.values(e.peerMgr.getMutilPeerCData()),i=Object.keys(e.peerMgr.getMutilPeerCData());for(let s=0;s<r.length;s++){const{pc:o,isPub:n}=r[s],a=n&&e.useMutilPeerC?[]:e.getSubscribedList(),c=yield Kr(a,!1,o,e),{pushOtherRooms:d,headers:_}=this.hooks(i[s]);c.pushOtherRooms=d;const u=yield new qr(_,c).execute(e,t);if(u.code!==L.SUCCESS)return void O.error(`exchange with pushOtherRoom failed: ${u.code}`);const{sdp:l,resultCode:h}=u.data;if(h!==L.SUCCESS)return void O.error(`exchange with pushOtherRoom failed: ${h}`);o.setRemoteAnswer(l.sdp)}}))}execute(e,t){return v(this,void 0,void 0,(function*(){const{roomId:s}=this;if(r.info(A.L_LIVING_ROOM_JOINED_PK_ROOM_T,{roomId:s,userId:e.crtUserId},{logSource:i.RTC}),!this.roomPKHandler)return void r.error(A.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:D.FAILED,code:"",msg:"_roomPKHandler not exist"},{logSource:i.RTC});const o=this.roomPKHandler.getPKInfo(s);if(!o)return O.warn(`exchange to update pushOtherRoom cancel, pkInfo lost -> roomId: ${s}`),void r.error(A.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:D.FAILED,code:"",msg:"PKInfo not exist"},{logSource:i.RTC});yield this._exchangeWithPushOtherRoom(e,t),r.info(A.L_LIVING_ROOM_JOINED_PK_ROOM_T,{status:D.SUCCESSED,roomId:s,userId:e.crtUserId,PKInfo:o},{logSource:i.RTC})}))}}class fi extends wr{constructor(e,t,r,i,s,o){super(),this.pkHandler=e,this.room=t,this._PKInfo=r,this.hooks=i,this._joinedPKRooms=s,this.isQuitPK=o}get kind(){return pr.LeaveRoom}quitRoomPK(e,t){return v(this,void 0,void 0,(function*(){if(!this._PKInfo[e])return;const{inviterRoomId:r,inviteeRoomId:i,inviterUserId:s,inviteSessionId:o}=this._PKInfo[e],n={inviteeRoomId:i,inviterRoomId:r,userId:t.crtUserId},c={roomId:t.roomId,endRoomId:e,sessionId:o,content:JSON.stringify(n),keys:[`${r}|${s}`]};O.info(`quitRoomPK -> params: ${JSON.stringify(c)}`);const d=yield t.context.endRoomPK(c);return d!==a.SUCCESS?(O.error(`quitRoomPK failed: ${d}`),{code:L.SIGNAL_ERROR}):(O.info("quitRoomPK success"),delete this._PKInfo[e],{code:L.SUCCESS})}))}execute(e,t){return v(this,void 0,void 0,(function*(){const{room:s,isQuitPK:o}=this,n=s.getRoomId();return O.info(`leavePKRoom -> userId: ${e.crtUserId} , roomId: ${n}`),r.info(A.L_LIVING_ROOM_LEAVE_PK_ROOM_T,{roomId:n,userId:e.crtUserId,isQuitPK:o},{logSource:i.RTC}),yield s.__destroy(!0),delete this._joinedPKRooms[n],yield new gi(n,this.hooks,this.pkHandler).execute(e,t),o&&this.quitRoomPK(n,e),r.info(A.L_LIVING_ROOM_LEAVE_PK_ROOM_R,{status:D.SUCCESSED,roomId:n,userId:e.crtUserId,isQuitPK:o},{logSource:i.RTC}),{code:L.SUCCESS}}))}}class vi{constructor(e,t,r,i,s,o,n,a,c,d,_){this._invoker=e,this._PKInfo=t,this._hooks=r,this._context=i,this._runtime=s,this._service=o,this._initOptions=n,this._mainLivingRoom=a,this._registerPKMsgListener=c,this._onJoinedPKRoom=d,this._clientSessionId=_,this._inviteTimeout=30,this._appListener=null,this._joinedPKRooms={},this._registerPKMsgListener(this._onRecvPKMsg.bind(this)),this._mainRoomId=this._mainLivingRoom.getRoomId()}_callAppListener(e,...t){var r;O.info(`${e} callback ->`,...t);const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){O.error(e)}}_onInvite(e){const t=e.inviteInfo||{},{inviterRoomId:r,inviterUserId:i,extra:s}=t,o={inviterRoomId:r,inviterUserId:i,extra:s};this._PKInfo[r]=t,this._callAppListener("onRequestJoinOtherRoom",o)}_onCancelInvite(e){const{inviterRoomId:t,inviterUserId:r,extra:i}=e.inviteInfo||{},s={inviterRoomId:t,inviterUserId:r,extra:i};delete this._PKInfo[t],this._callAppListener("onCancelRequestOtherRoom",s)}_onInviteTimeout(e){}_onInviteAnswer(e){const{answerCode:t,inviteContent:r}=e,{inviteSessionId:i,inviterUserId:s,inviterRoomId:o,inviteeUserId:n,inviterUserAutoMix:a,inviteeUserAutoMix:c,inviteeRoomId:d,extra:_}=r,u={agree:1===t,inviterRoomId:o,inviterUserId:s,inviteeRoomId:d,inviteeUserId:n,extra:_};this._PKInfo[d]=this._PKInfo[d]||{inviteSessionId:i,inviterRoomId:o,inviterUserId:s,inviterUserAutoMix:a,inviteeRoomId:d},this._PKInfo[d].inviteeUserAutoMix=c,this._callAppListener("onResponseJoinOtherRoom",u)}createLeaveOtherRoomCommand(e,t){return new fi(this,e,this._PKInfo,this._hooks,this._joinedPKRooms,t)}_onPKEnd(e){return v(this,void 0,void 0,(function*(){const{inviteeRoomId:t,inviterRoomId:r,userId:i}=e.inviteInfo,s=r===this._mainRoomId?t:r,o={endRoomId:s,endUserId:i},n=this._joinedPKRooms[s];n&&(yield this._invoker.push(this.createLeaveOtherRoomCommand(n))),delete this._PKInfo[s],this._callAppListener("onFinishOtherRoom",o)}))}_onRecvPKMsg(e){const{targetId:t,content:r,messageType:i}=e;switch(i){case jt.PK_INVITE:this._onInvite(r);break;case jt.PK_CANCEL_INVITE:this._onCancelInvite(r);break;case jt.PK_INVITE_TIMEOUT:this._onInviteTimeout(r);break;case jt.PK_INVITE_ANSWER:this._onInviteAnswer(r);break;case jt.PK_END:this._onPKEnd(r)}}registerRoomPKEventListener(e){r.info(A.L_LIVING_PK_HANDLER_REGISTER_ROOM_PK_EVENT_LISTENER_O,{status:D.SUCCESSED,listener:e&&Object.keys(e)},{logSource:i.RTC}),this._appListener=e}requestJoinOtherRoom(e,t,s){return v(this,void 0,void 0,(function*(){if(r.info(A.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:e,inviteeUserId:t,options:s},{logSource:i.RTC}),!o("inviteeRoomId",e,m,!0)||!o("inviteeUserId",t,m,!0))return r.error(A.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> inviteeRoomId 或 inviteeUserId"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};O.info(`requestRoomPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; options: ${JSON.stringify(s||{})}`);const n=qt(),c=!I(null==s?void 0:s.autoMix)||(null==s?void 0:s.autoMix),d={inviteSessionId:n,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:c,inviteeRoomId:e,inviteeUserId:t,inviteeTimeoutTime:this._inviteTimeout,extra:(null==s?void 0:s.extra)||""},_={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteTimeout:this._inviteTimeout,inviteInfo:JSON.stringify(d),inviteSessionId:n};O.info(`requestRoomPK -> params: ${JSON.stringify(_)}`);const u=yield this._context.requestRoomPK(_);return u!==a.SUCCESS?(O.error(`requestRoomPK failed: ${u}`),r.error(A.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:u,msg:""},{logSource:i.RTC}),{code:u}):(O.info("requestRoomPK success"),this._PKInfo[e]={inviteSessionId:n,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:c,inviteeRoomId:e},r.info(A.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{inviteeRoomId:e,inviteeUserId:t,options:s},{logSource:i.RTC}),{code:L.SUCCESS})}))}cancelRequestJoinOtherRoom(e,t,s){return v(this,void 0,void 0,(function*(){if(r.info(A.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:e,inviteeUserId:t,extra:s,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),!o("inviteeRoomId",e,m,!0)||!o("inviteeUserId",t,m,!0))return r.error(A.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> inviteeRoomId or inviteeUserId"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(!this._PKInfo[e])return O.error(`The request to connect with ${t} user in room ${e} is not initiated`),r.error(A.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:`The request to connect with ${t} user in room ${e} is not initiated`},{logSource:i.RTC}),{code:L.PARAMS_ERROR};O.info(`canceRequestJoinPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; extra: ${s}`);const n={inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviteeRoomId:e,inviteeUserId:t,extra:s||""},c={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteSessionId:this._PKInfo[e].inviteSessionId,inviteInfo:JSON.stringify(n)};O.info(`canceRequestJoinPK -> params: ${JSON.stringify(c)}`);const d=yield this._context.cancelRoomPK(c);return d!==a.SUCCESS?(O.error(`canceRequestJoinPK failed: ${d}`),r.error(A.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:d,msg:`The request to connect with ${t} user in room ${e} is not initiated`},{logSource:i.RTC}),{code:d}):(O.info("canceRequestJoinPK success"),r.info(A.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:D.SUCCESSED,inviteeRoomId:e,inviteeUserId:t,extra:s},{logSource:i.RTC}),delete this._PKInfo[e],{code:L.SUCCESS})}))}responseJoinOtherRoom(e,t,s,n){return v(this,void 0,void 0,(function*(){if(r.info(A.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_T,{inviterRoomId:e,inviterUserId:t,agree:s,options:n,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),!o("inviterRoomId",e,m,!0)||!o("inviterUserId",t,m,!0))return r.error(A.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> inviterRoomId or inviterUserId"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(!this._PKInfo[e])return O.error(`User ${t} in room ${e} did not send a request for connection`),r.error(A.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:`User ${t} in room ${e} did not send a request for connection`},{logSource:i.RTC}),{code:L.PARAMS_ERROR};O.info(`responseRoomPK -> inviterRoomId: ${e}; inviterUserId: ${t}; agree: ${s}; options: ${JSON.stringify(n||{})}`);const{inviteSessionId:c,inviterUserAutoMix:d}=this._PKInfo[e],_=!I(null==n?void 0:n.autoMix)||(null==n?void 0:n.autoMix),u={inviteSessionId:c,inviterRoomId:e,inviterUserId:t,inviterUserAutoMix:d,inviteeRoomId:this._mainRoomId,inviteeUserId:this._context.getCurrentId(),inviteeUserAutoMix:_},l=Object.assign(u,{inviterUserAutoMix:d}),h=s?Object.assign(u,{MultiRoomKey:`${e}|${this._mainRoomId}`,MultiRoomValue:JSON.stringify(l)}):u;!E(null==n?void 0:n.extra)&&Object.assign(h,{extra:n.extra});const R={agree:s,roomId:this._mainRoomId,inviteSessionId:c,inviteRoomId:e,inviteUserId:t,content:JSON.stringify(h),key:`${e}|${this._mainRoomId}`,value:JSON.stringify(u)};O.info(`responseRoomPK -> params: ${JSON.stringify(R)}`);const p=yield this._context.responseRoomPK(R);return p!==a.SUCCESS?(O.error(`responseRoomPK failed: ${p}`),r.error(A.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:p,msg:""},{logSource:i.RTC}),{code:p}):(O.info("responseRoomPK success"),r.info(A.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:D.SUCCESSED,inviterRoomId:e,inviterUserId:t,agree:s,options:n,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),this._PKInfo[e].inviteeUserAutoMix=_,{code:L.SUCCESS})}))}joinOtherRoom(e){return v(this,void 0,void 0,(function*(){if(r.info(A.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_T,{roomId:e,userId:this._context.getCurrentId()},{logSource:i.RTC}),!o("roomId",e,m,!0))return r.error(A.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(this._context.getConnectionStatus()!==_.CONNECTED)return r.error(A.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.SIGNAL_DISCONNECTED,msg:"IM disconnected"},{logSource:i.RTC}),{code:L.SIGNAL_DISCONNECTED};if(O.info(`JoinPKRoom, roomId: ${e}`),this._joinedPKRooms[e])return r.warn(A.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:L.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:L.REPERT_JOIN_ROOM};const t=Ti.VIDEO,s={extra:`{"roomId": "${this._mainRoomId}"}`},n=new Ai(this._context,this._runtime,e,this._service,this._initOptions,t,!1,!1,!1,this._clientSessionId),{code:a,data:c}=yield n.__innerInit(Ir.LIVE,void 0,t,s);return a!==L.SUCCESS?(O.error(`JoinPKRoom failed -> code: ${a}`),r.error(A.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:D.FAILED,code:a,msg:""},{logSource:i.RTC}),{code:a}):(O.info(`JoinPKRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(c)}`),this._joinedPKRooms[e]=n,yield this._onJoinedPKRoom(e,n),r.info(A.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:D.SUCCESSED,roomId:e,userId:this._context.getCurrentId()},{logSource:i.RTC}),{room:n,code:L.SUCCESS,userIds:n.getRemoteUserIds(),tracks:n.getRemoteTracks()})}))}leaveOtherRoom(e,t){return v(this,void 0,void 0,(function*(){return this._invoker.push(this.createLeaveOtherRoomCommand(e,t))}))}getPKInfo(e){return this._PKInfo[e]}getAllPKInfo(){return this._PKInfo}getJoinedPKRooms(){return this._joinedPKRooms}}!function(e){e[e.OPEN=1]="OPEN",e[e.STOP=2]="STOP"}(Ii||(Ii={}));class Oi extends wr{constructor(e,t){super(),this.cdnValues=e,this.enable=t}execute(e,t){return v(this,void 0,void 0,(function*(){const{enable:s}=this;if(r.info(A.L_LIVING_ROOM_ENABLE_INNER_CDN_T,{roomId:e.roomId,enable:s},{logSource:i.RTC}),!e.isMainRoom)return O.error("the `enableInnerCDN` is disabled in PK room"),r.error(A.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:D.FAILED,code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!I(s))return O.error("`enable` is invalid"),r.error(A.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> enable"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};e.setCDNEnabel(s);const o={version:2,output:{inCDNModel:s?Ii.OPEN:Ii.STOP}},{code:n}=yield new ui(o,this.cdnValues).execute(e,t);if(n!==L.SUCCESS)return O.error(`enableInnerCDN failed -> code: ${n}`),r.error(A.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:D.FAILED,code:n,msg:"signal error"},{logSource:i.RTC}),{code:L.SIGNAL_ERROR};const a=e.getCDNUris();if(a&&a.broadcast!==vr.SPREAD)return O.info("enableInnerCDN succeed"),r.info(A.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:D.SUCCESSED,enable:s},{logSource:i.RTC}),{code:L.SUCCESS};const{code:c}=yield Jr(e);return c===L.SUCCESS?(O.info("enableInnerCDN succeed"),r.info(A.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:D.SUCCESSED,enable:s},{logSource:i.RTC}),{code:L.SUCCESS}):(O.error(`enableInnerCDN failed -> code: ${c}`),r.error(A.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:D.FAILED,code:c,msg:""},{logSource:i.RTC}),{code:c})}))}}!function(e){e[e.AnchorToViewer=1]="AnchorToViewer",e[e.ViewerToAnchor=2]="ViewerToAnchor"}(Ei||(Ei={}));class Li extends wr{constructor(e){super(),this.livingType=e}execute(e,t){var r;return v(this,void 0,void 0,(function*(){const{code:i,data:s}=yield e.context.rtcIdentityChange(e.roomId,Ei.ViewerToAnchor,this.livingType);if(i!==a.SUCCESS||!s)return{code:i};e.initWithRoomData(s);e.getResourcesByUserId(e.crtUserId).length>0&&t.push(new Fr);const o=null===(r=s.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===r?void 0:r.value;return o&&e.setCDNUris(JSON.parse(o)[0]),{code:i,data:s}}))}}class Ai extends _i{constructor(e,t,r,i,s,o,n,a,c,d){super(e,t,r,Ir.LIVE,i,s,n,a,c,d),this._livingType=o,this._mcuConfigBuilder=new Si(this._invoker,this._isValidResourceId.bind(this))}_initAfterCatchRoomData(e){if(this._store.isUpgrade&&this._afterChangedRole(e),this._store.isMainRoom){const t=((e,t)=>{const r={};return t.forEach((t=>{const i=JSON.parse(t.value),{inviterRoomId:s,inviteeRoomId:o}=i;r[e===s?o:s]=JSON.parse(t.value)})),r})(this._roomId,e.roomInfo);this._roomPKHandler=new vi(this._invoker,t,(e=>({headers:this._getRTCReqestHeaders(e),pushOtherRooms:this._getPushOtherRoomsParams()})),this._context,this._runtime,this._service,this._initOptions,this,super._registerPKMsgListener.bind(this),this._onJoinedPKRoom.bind(this),this._clientSessionId)}}__innerInit(e,t,s,n,a){const c=Object.create(null,{__innerInit:{get:()=>super.__innerInit}});return v(this,void 0,void 0,(function*(){if(!o("livingType",s,(e=>e===Ti.AUDIO||e===Ti.VIDEO)))return r.error(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> livingType"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};const{code:d,data:_}=yield c.__innerInit.call(this,e,t,s,n,a);return d===L.SUCCESS&&_&&this._initAfterCatchRoomData(_),{code:d,data:_}}))}__innerInitByIdentityChange(){return v(this,void 0,void 0,(function*(){const{code:e,data:t}=yield this._invoker.push(new Li(this._livingType));return e===a.SUCCESS&&t&&(this._initAfterCatchRoomData(t),this._initWithRoomData(t.offlineKickTime),r.info(A.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:D.SUCCESSED,roomData:t},{logSource:i.RTC})),e}))}publish(e){const t=Object.create(null,{publish:{get:()=>super.publish}});return v(this,void 0,void 0,(function*(){return this._store.isMainRoom?t.publish.call(this,e):(O.warn("the `publish` is disabled in PK room "),r.error(A.L_ABSTRACT_ROOM_PUBLISH_R,{status:D.FAILED,code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}unpublish(e){const t=Object.create(null,{unpublish:{get:()=>super.unpublish}});return v(this,void 0,void 0,(function*(){return this._store.isMainRoom?t.unpublish.call(this,e):(O.warn("the `unpublish` is disabled in PK room "),r.error(A.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:D.FAILED,code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}_isValidResourceId(e){var t;const{userId:r}=Lt(e),i=!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>Ot(t)===e)));let s=!1;const{code:o,roomPKHandler:n}=this.getRoomPKHandler();if(o!==L.SUCCESS||!n)return i;const a=n.getJoinedPKRooms(),c=[];return Object.values(a).forEach((e=>{c.push(...e.getRemoteTracks())})),s=c.some((t=>e===t.getTrackId())),i||s}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._store.isMainRoom?this._mcuConfigBuilder:(O.error("the `getMCUConfigBuilder` is disabled in PK room"),{code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}enableInnerCDN(e){return v(this,void 0,void 0,(function*(){return this._invoker.push(new Oi(this._mcuConfigBuilder.__innerGetValues(),e))}))}_resourceHandle(e,t,r){const i=Object.create(null,{_resourceHandle:{get:()=>super._resourceHandle}});return v(this,void 0,void 0,(function*(){i._resourceHandle.call(this,e,t,r)}))}_afterChangedRole(e){const t=$t(e,this._roomId),r=this._context.getCurrentId(),i=Object.keys(t);setTimeout((()=>{var s;const o=i.filter((e=>e!==r));o.length>0&&this._callAppListener("onUserJoin",o);for(const e in t)e!==r&&this._resourceHandle({uris:t[e]},jt.TOTAL_CONTENT_RESOURCE,e);if(!(null===(s=e.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===s?void 0:s.value))return;const n=this._store.getCDNUris();(null==n?void 0:n.push_mode)===Ci.MANUAL&&this._callAppListener("onCDNEnableChange",null==n?void 0:n.enableInnerCDN)}))}__getCDNEnable(){var e;return!!(null===(e=this._store.getCDNUris())||void 0===e?void 0:e.enableInnerCDN)}__getCDNPushMode(){var e;return null===(e=this._store.getCDNUris())||void 0===e?void 0:e.push_mode}_onJoinedPKRoom(e,t){return v(this,void 0,void 0,(function*(){this._invoker.push(new gi(e,(e=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(e)})),this._roomPKHandler))}))}_getPushOtherRoomsParams(){const e=[];if(!this.isMainRoom()||!this._roomPKHandler)return e;const t=this._roomPKHandler.getJoinedPKRooms();for(const r in t){const i=t[r].getSessionId(),s=this._roomPKHandler.getPKInfo(r);if(!s)continue;const{inviterUserAutoMix:o,inviteeUserAutoMix:n,inviterUserId:a}=s,c=this._context.getCurrentId()===a;e.push({roomId:r,sessionId:i,autoMix:c?!!o:!!n})}return e}getRoomPKHandler(){return this._store.isMainRoom?(r.info(A.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:D.SUCCESSED},{logSource:i.RTC}),{code:L.SUCCESS,roomPKHandler:this._roomPKHandler}):(O.error("the `getRoomPKHandler` is disabled in PK room"),r.error(A.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:D.SUCCESSED,code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}_quitAllPKRoom(){return v(this,void 0,void 0,(function*(){const e=this._roomPKHandler.getJoinedPKRooms();for(const t in e)this._roomPKHandler.leaveOtherRoom(e[t]);r.info(A.L_LIVING_ROOM_QUIT_ALL_PK_ROOM_O,{status:D.SUCCESSED,roomIds:Object.keys(e)},{logSource:i.RTC})}))}isMainRoom(){return this._store.isMainRoom}}class Di extends _i{constructor(e,t,r,i,s,o,n,a,c,d=Ir.RTC){super(e,t,r,d,i,s,o,n,a,c)}}const Ni=new class{constructor(){this.queue=[],this.locked=!1,this.taskCount=0}checkToStart(){return v(this,void 0,void 0,(function*(){if(0===this.queue.length||this.locked)return;this.locked=!0;const{resolve:e,task:t,reject:r}=this.queue.shift();let i;try{i=yield t(),e(i)}catch(e){r(e)}this.locked=!1,this.checkToStart()}))}push(e,t=""){const r=new Promise(((t,r)=>{this.queue.push({resolve:t,task:e,reject:r})}));return this.checkToStart(),r}},bi=(e,t="")=>Ni.push(e,t);class ki{constructor(e,t,r,i){this._context=e,this._useMutilPeerC=i,this._rtcToken="",this._liveUrl="",this._subTracks=[],this._clientSessionId=qt(),this._livingType=null,this._mediaType=null,this._subTiny=!1,this._fromRetry=!1,this._appListener=null,this._service=new Zt(t,e,r.mediaServer),this._peerCManager=new xr(this._useMutilPeerC,this._context.getCurrentId(),this._reTryExchange.bind(this),this._context.getCurrentId())}_getReqHeaders(e){return v(this,void 0,void 0,(function*(){const t=this._context.getCurrentId(),r=t;if(!this._rtcToken){const{code:t,data:i}=yield this._context.getRTCToken(r,Ir.LIVE,e);if(t!==a.SUCCESS)return O.error(`getRTCToken failed: ${t}`),{code:L.SIGNAL_ERROR};this._rtcToken=i.rtcToken}return{code:L.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:t,RoomId:r,RoomType:Ir.LIVE,Token:this._rtcToken,"Peer-Connection-Id":this._pcName,"Client-Session-Id":this._clientSessionId}}}))}_clearSubscribeInfo(){var e;this._liveUrl="",this._livingType=null,this._mediaType=null,this._subTiny=!1,this._subTracks.length=0,null===(e=this._pc)||void 0===e||e.destroy(),this._pc=null}_reTryExchange(){var e;return v(this,void 0,void 0,(function*(){this._fromRetry=!0;const{code:t}=yield this.subscribe(this._liveUrl,this._livingType,this._mediaType,this._subTiny);t===L.SUCCESS&&(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer())}))}subscribe(e,t,r,i=!1){return v(this,void 0,void 0,(function*(){return bi((()=>this.__subscribe(e,t,r,i)),"audience-client-sub")}))}__subscribe(e,t,s,o=!1){var n;return v(this,void 0,void 0,(function*(){r.info(A.L_AUDIENCE_CLIENT_SUBSCRIBE_T,{liveUrl:e,livingType:t,mediaType:s,subTiny:o},{logSource:i.RTC});const a=[];if(Vt(this._context.getNaviInfo()))return r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:L.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:i.RTC}),{code:L.PACKAGE_ENVIRONMENT_ERROR,tracks:a};if(!this._fromRetry&&(null===(n=this._pc)||void 0===n||n.clearReTryExchangeTimer()),this._fromRetry=!1,!p(e))return O.error(`liveUrl is invalid: ${e}`),r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:`params error -> liveUrl: ${e}`},{logSource:i.RTC}),{code:L.PARAMS_ERROR,tracks:a};if(![Ti.AUDIO,Ti.VIDEO].includes(t))return O.error(`livingType is invalid: ${t}`),r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:`params error -> livingType: ${t}`},{logSource:i.RTC}),{code:L.PARAMS_ERROR,tracks:a};if(![He.AUDIO_ONLY,He.VIDEO_ONLY,He.AUDIO_VIDEO].includes(s))return O.error(`mediaType is invalid: ${s}`),r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:`params error -> -> mediaType: ${s}`},{logSource:i.RTC}),{code:L.PARAMS_ERROR,tracks:a};if(this._liveUrl&&this._liveUrl!==e)return r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:L.BROADCAST_SUB_LIST_NOT_EMPTY,msg:"repeat subscribe"},{logSource:i.RTC}),{code:L.BROADCAST_SUB_LIST_NOT_EMPTY,tracks:a};if(!this._pc){const{pcName:e,pc:t}=this._peerCManager.createPeerCList(a)[0];this._pc=t,this._pcName=e,this._pc.on(Ur.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this._pc.registerReportListener(this._reportListener),this._pc.__reportR3R4ToPolaris()}this._liveUrl=e;const{code:c,headers:d}=yield this._getReqHeaders(t);if(c!==L.SUCCESS)return r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:c,msg:""},{logSource:i.RTC}),{code:c,tracks:a};const _=`rc_mcu_${Date.now()}`,u="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new pt(u,_),new St(u,_)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const l=`${Date.now()}`;Qt.getMemo().qualityStatus=l,r.info(A.L_QS_CREATE_OFFER_O,{identify:l},{logSource:i.RTC});const h={sdp:yield this._pc.createOffer(!0),liveUrl:e,mediaType:s,simulcast:o?Xt.TINY:Xt.NORMAL,switchstream:!1};r.info(A.L_QS_SUBSCRIBE_EXCHANGE_O,{identify:l},{logSource:i.RTC});const R=yield this._service.broadcastSubscribe(d,h);if(R.code!==L.SUCCESS)return O.error(`andience subscribe failed: ${R.code}`),r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:R.code,msg:""},{logSource:i.RTC}),{code:R.code,tracks:a};const m=R.data;if(m.resultCode!==L.SUCCESS)return O.error(`andience subscribe failed! code: ${m.resultCode}; message: ${m.message}`),r.error(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.FAILED,code:m.resultCode,msg:""},{logSource:i.RTC}),{code:m.resultCode,tracks:a};O.debug(`andience subscribe success: ${e}`),this._livingType=t,this._mediaType=s,this._subTiny=o;const{sdp:S,subscribedList:T}=m;r.info(A.L_QS_GET_ANSWER_O,{identify:l},{logSource:i.RTC});const C=[];return T.forEach((e=>{const{mediaType:t}=e,r=this._subTracks[t];C.push(r),r.__innerSetRemoteMuted(!0)})),r.info(A.L_QS_GET_RESOURCES_O,{identify:l},{logSource:i.RTC}),this._pc.setRemoteAnswer(S.sdp),r.info(A.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:D.SUCCESSED,liveUrl:e},{logSource:i.RTC}),{code:L.SUCCESS,tracks:C}}))}unsubscribe(){return v(this,void 0,void 0,(function*(){return bi((()=>this.__unsubscribe()),"audience-client-unsub")}))}__unsubscribe(){var e;return v(this,void 0,void 0,(function*(){if(r.info(A.L_AUDIENCE_CLIENT_UNSUBSCRIBE_T,{liveUrl:this._liveUrl},{logSource:i.RTC}),null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer(),!this._rtcToken||!this._liveUrl)return r.warn(A.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:D.FAILED,code:"",msg:"Address does not exist, without unsubscribe"},{logSource:i.RTC}),{code:L.SUCCESS};const{headers:t}=yield this._getReqHeaders(),{code:s}=yield this._service.broadcastExit(t);return s!==L.SUCCESS?(O.error(`broadcast unsubscribe failed: ${s}`),r.error(A.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:D.FAILED,code:s,msg:""},{logSource:i.RTC})):(O.debug("broadcast unsubscribe success"),r.info(A.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:D.SUCCESSED,liveUrl:this._liveUrl},{logSource:i.RTC})),this._clearSubscribeInfo(),{code:s}}))}registerReportListener(e){this._reportListener=e}registerTrackEventListener(e){this._appListener=e}_onTrackReady(e){var t,s;const{track:o}=e.receiver,n="audio"===o.kind?He.AUDIO_ONLY:He.VIDEO_ONLY,a=this._subTracks[n];a.__innerSetMediaStreamTrack(o);const c=Qt.getMemo();r.info(A.L_QS_CREATE_OFFER_O,{identify:c.qualityStatusId},{logSource:i.RTC});try{null===(s=null===(t=this._appListener)||void 0===t?void 0:t.onTrackReady)||void 0===s||s.call(t,a)}catch(e){O.error(e)}}}var yi,Ui;!function(e){e.RTMP="rtmp",e.FLV="flv",e.HLS="hls"}(yi||(yi={})),function(e){e[e.NOT_HTTPS=0]="NOT_HTTPS",e[e.HTTPS=1]="HTTPS"}(Ui||(Ui={}));const Pi=Object.assign(Object.assign({},kt(je.W176_H144)),{frameRate:Pt(Ke.FPS_15)});class Mi{constructor(e,t,r,i,s,o,n,a=qt()){this._context=e,this._runtime=t,this._initOptions=r,this._roomId=i,this._joinResData=s,this.livingType=o,this._useMutilPeerC=n,this._clientSessionId=a,this._roomAnchorList=[],this._roomRes={},this._roomAnchorRes={},this._remoteTracks={},this._appListener=null,this._pc=null,this._subscribedList=[],this._sessionId="",this._destroyed=!1,this._isPulling=!1,this._pullTime=0,this._reportListener=null,this._setInitData(),this._service=new Zt(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new Pr(this._context,this._runtime,this._roomId,this,Rr.Audience),this._polarisReport.sendR1(),this._peerCManager=new xr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._context.registerRTCSignalListener((e=>v(this,void 0,void 0,(function*(){const{time:t,type:r,roomId:i}=this._context.decodeRtcNotify(e);if(O.warn(`registerRTCSignalListener -> ${JSON.stringify({time:t,type:r,roomId:i})}`),1===r)this._startPull(i,t)}))))}_startPull(e,t){return v(this,void 0,void 0,(function*(){if(this._isPulling)return;this._isPulling=!0;if(this._pullTime>t)return void(this._isPulling=!1);const{code:r,data:i}=yield this._context.pullRTCRoomEntry(e);if(r===a.SUCCESS){this._isPulling=!1,this._pullTime=i.syncTime||0;const t=(null==i?void 0:i.kvEntries)||[];O.info(`_startPull -> ${JSON.stringify(t)}`),this.singalDataChange(t,e)}}))}_setInitData(){const{sessionId:e,remoteUserIds:t,remoteRTCUris:r,remoteMUCUris:i,remoteTracks:s,CDNUris:o}=Ft(this._roomId,this._joinResData.kvEntries);this._sessionId=e,this._roomAnchorList=t,s.forEach((e=>{this._remoteTracks[e.getTrackId()]=e})),this._CDNUris=o,r.forEach((e=>{const t=e.msid.split("_")[0];this._roomAnchorRes[t]?this._roomAnchorRes[t].push(e):this._roomAnchorRes[t]=[e]})),i.forEach((e=>{const{mediaType:t,tag:r}=e,i=[this._roomId,r,t].join("_");this._roomRes[i]=e})),r.forEach((e=>{const t=Ot(e);this._roomRes[t]=e}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinLivingRoomAsAudience` to catch another instance.";return O.warn(e),L.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(e,t){var s;if(r.info(A.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_T,{singalData:e,roomId:t,userId:this._context.getCurrentId()},{logSource:i.RTC}),t!==this._roomId)return O.warn(`singalDataChange -> not the current room data: data roomId: ${t}, current roomId: ${this._roomId}`),void r.error(A.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:D.FAILED,code:"",msg:`id inconsistency -> params id:${t},current id:${this._roomId}`},{logSource:i.RTC});O.debug("singalDataChange -> singalData:",JSON.stringify(e||{}));const o=[],n=null===(s=e.filter((e=>"RC_CDN"===e.key))[0])||void 0===s?void 0:s.value;n&&this._diffCDNUris(JSON.parse(JSON.parse(n).cdn_uris)[0]),e.forEach((e=>{const{key:t,value:r,timestamp:i,uid:s}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),i=JSON.parse(e.uris||"[]");return o.push(...t),void this._diffAnchorResource(i,s)}if("RC_ANCHOR_LIST"===t){const e=JSON.parse(r||"[]"),{joinUserIds:t,leftUserIds:i}=this._diffAnchorList(e);t.length>0&&this._handleNewJoinedAnchor(t),i.length>0&&this._handleLeftedAnchor(i)}})),this._diffRoomResource(o),r.info(A.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:D.SUCCESSED,singalData:e,roomId:t,userId:this._context.getCurrentId()},{logSource:i.RTC})}_diffAnchorList(e){const t=e.filter((e=>this._roomAnchorList.indexOf(e)<0));return{leftUserIds:this._roomAnchorList.filter((t=>e.indexOf(t)<0)),joinUserIds:t}}_handleNewJoinedAnchor(e){this._roomAnchorList.push(...e),this._callAppListener("onAnchorJoin",e)}_handleLeftedAnchor(e){return v(this,void 0,void 0,(function*(){this._roomAnchorList=this._roomAnchorList.filter((t=>!(e.indexOf(t)>-1)));const t=[];e.forEach((e=>{t.push(...this.getRemoteTracksByUserId(e)),delete this._roomAnchorRes[e]})),t.length&&(yield this.unsubscribe(t),t.forEach((e=>delete this._remoteTracks[e.getTrackId()]))),this._callAppListener("onAnchorLeave",e)}))}_diffRoomResource(e){return v(this,void 0,void 0,(function*(){const t=[],r=[],i=[];e.forEach((e=>{const r=Ot(e),{userId:s,tag:o,mediaType:n}=Lt(r),a=[this._roomId,o,n].join("_");if(!this._remoteTracks[a]){const r=n===He.AUDIO_ONLY?new pt(o,"",this._roomId):new St(o,"",this._roomId);t.push(r),this._remoteTracks[a]=r,this._roomRes[r.getTrackId()]=e}i.push(a)})),Object.keys(this._remoteTracks).forEach((e=>{i.indexOf(e)<0&&this._remoteTracks[e].isMCUTrack()&&r.push(this._remoteTracks[e])})),t.length>0&&this._callAppListener("onTrackPublish",t),r.length>0&&this._onUserUnpublish(r,"onTrackUnpublish")}))}_diffAnchorResource(e,t){return v(this,void 0,void 0,(function*(){const r=this._roomAnchorRes[t]||(this._roomAnchorRes[t]=[]),{publishedList:i,unpublishedList:s,modifiedList:o}=Nt(r,e);if(i.length){const e=r.map(Ot),t=[],s=[];if(i.forEach((i=>{const o=Ot(i),n=e.indexOf(o),{userId:a,tag:c,mediaType:d}=Lt(o);n>-1?r[n]=i:r.push(i);let _=this._remoteTracks[o];this._roomRes[o]=i,_?_.isSubscribed()&&t.push(_):(_=d===He.AUDIO_ONLY?new pt(c,a):new St(c,a),this._remoteTracks[o]=_,s.push(_)),_.__innerSetRemoteMuted(0===i.state)})),t.length){const e=t.map((e=>e.getTrackId()));O.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:r}=yield bi((()=>this._subscribeHandle(t,!0)));r!==L.SUCCESS&&O.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(e)}`)}this._callAppListener("onAnchorTrackPublish",s)}if(s.length){const e=s.map(Ot);for(let t=r.length-1;t>=0;t-=1){const i=r[t];e.includes(Ot(i))&&r.splice(t,1)}const t=s.map((e=>{const t=Ot(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t,"onAnchorTrackUnpublish")}if(o.length){const e=r.map(Ot);for(let t=0;t<o.length;t++){const i=o[t],s=Ot(i),n=e.indexOf(s);r[n].state=i.state;const a=this._remoteTracks[s];a.__innerSetRemoteMuted(0===i.state),a.isAudioTrack()?this._callAppListener("onAudioMuteChange",a):this._callAppListener("onVideoMuteChange",a)}}}))}_onUserUnpublish(e,t){return v(this,void 0,void 0,(function*(){yield this.unsubscribe(e),e.forEach((e=>{this._subscribedList=this._subscribedList.filter((t=>t.track.getTrackId()!==e.getTrackId())),delete this._roomRes[e.getTrackId()],e.__innerDestroy(),delete this._remoteTracks[e.getTrackId()]})),this._callAppListener(t,e)}))}_callAppListener(e,...t){var r;O.info(`${e} callback ->`,...t);const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){O.error(e)}}_reTryExchange(){return v(this,void 0,void 0,(function*(){bi((()=>v(this,void 0,void 0,(function*(){var e;const{reqBody:t}=yield this._createSubscribeParams(this._subscribedList,{},!0),r=yield this._exchangeHandle(t);if(r.code!==L.SUCCESS)return O.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:s}=r.data;if(s!==L.SUCCESS)return O.error(`reTryExchange failed: ${s}`),{code:s};this._pc.clearReTryExchangeTimer();const o=this._subscribedList.filter((e=>e.track.isMCUTrack()));if(o.length>0){const t=o[0].track.getTrackId(),r=null===(e=this._roomRes[t])||void 0===e?void 0:e.msid,s=[this._roomId,"RongCloudRTC"].join("_");i.sdp=i.sdp.replace(new RegExp(r,"g"),s)}const n=yield this._pc.setRemoteAnswer(i.sdp);return n!==L.SUCCESS?{code:n}:void 0}))),"audience-retry-exchange")}))}_createSubscribeParams(e,t,r){return v(this,void 0,void 0,(function*(){const i=yield this._pc.createOffer(r),s={resolutionInfo:[]},o={min:0,max:0};Object.keys(t).forEach((e=>{const{mediaStream:r,tinyStream:n}=t[e];[r,n].forEach(((t,r)=>{var n;const a=1===r?[e,"tiny"].join("_"):e;i.sdp=null===(n=i.sdp)||void 0===n?void 0:n.replace(new RegExp(t.id,"g"),a);const c=t.getVideoTracks()[0];if(!c)return;const d=0===r,{width:_,height:u,frameRate:l}=d?ft(c):Pi;s.resolutionInfo.push({trackId:c.id,simulcast:d?Xt.NORMAL:Xt.TINY,resolution:`${_}x${u}`});const h=We(_,u),R=Qe(l);o.min+=h.minBitrate*R,o.max+=h.maxBitrate*R}))}));return{reqBody:{sdp:i,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?Xt.TINY:Xt.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:o,offer:i}}))}_subscribeHandle(e,t=!1){var s;return v(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return r.error(A.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:D.FAILED,code:L.ROOM_HAS_BEEN_DESTROYED,msg:"room destroyed"},{logSource:i.RTC}),{code:L.ROOM_HAS_BEEN_DESTROYED};if(!o("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof mt||e.track instanceof mt))),!0))return r.error(A.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};const{pc:n,pcName:a}=this._peerCManager.createPeerCList(e)[0];this._pc=n,this._pc.__reportR3R4ToPolaris(),this._pcName=a,this._pc.registerReportListener(this._reportListener),this._addPeerCEvent();const c=this._subscribedList.map((e=>Object.assign({},e))),_=e.map((e=>e instanceof mt?{track:e}:e));let u=!1;const l=[];return _.forEach((e=>{const t=e.track.getTrackId();l.push(t);const r=c.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:c.push(e),u=!0)})),u||t?(null===(s=this._polarisReport)||void 0===s||s.sendR2(gr.SUBSCRIBE,fr.BEGIN,l),r.info(A.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:D.SUCCESSED,trackIds:e.map(Gt),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:t},{logSource:i.RTC}),this._updateSubListHandle(c,!0)):(r.warn(A.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:D.FAILED,code:"",msg:"repeat subscribe"},{logSource:i.RTC}),{code:L.SUCCESS})}))}_addPeerCEvent(){this._pc.on(Ur.__INNER_EVENT_TRACK_READY__,(e=>{const t=e.streams[0].id,{track:s}=e.receiver,o=[t,"audio"===s.kind?He.AUDIO_ONLY:He.VIDEO_ONLY].join("_"),n=this._remoteTracks[o];if(!n)return void O.warn("cannot found RCRemoteTrack:",s.id);n.__innerSetMediaStreamTrack(s);const a=Qt.getMemo();r.info(A.L_QS_TRACK_READY_O,{identify:a.qualityStatusId},{logSource:i.RTC}),this._callAppListener("onTrackReady",n)}))}_getReqHeaders(){const e=this._context.getCurrentId();return{"App-Key":this._context.getAppkey(),RoomId:e,Token:this._joinResData.token,RoomType:Ir.LIVE,UserId:e,"Session-Id":this._sessionId,"Peer-Connection-Id":this._pcName,"Client-Session-Id":this._clientSessionId}}_exchangeHandle(e){return this._service.broadcastSubscribe(this._getReqHeaders(),e)}_updateSubListHandle(e,t=!1){var s;return v(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:L.ROOM_HAS_BEEN_DESTROYED};if(!o("resources",e,(()=>d(e)&&e.every((e=>e instanceof mt||e.track instanceof mt))),!0))return{code:L.PARAMS_ERROR};let n=e.map((e=>e instanceof mt?{track:e}:Object.assign({},e)));const a={};n=n.filter((e=>{const t=e.track.getTrackId();return!a[t]&&(a[t]=!0,!0)})).map((e=>Object.assign({},e)));const c=this._subscribedList.map((e=>Object.assign({},e)));if(!t){let e=!1;if(n.forEach((t=>{const r=c.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);c.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),c.length&&(e=!0),!e)return{code:L.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(n.map((e=>e.track)));const _=Qt.getMemo(),u={dur:0,cod:0,rid:this._roomId,csnid:this._clientSessionId,snid:this._sessionId,rsid:"",msa:"",msas:[],time:0,resid:"",mtp:0,smct:1,cr:"unknown",net:"unknown",uid:"",stp:0};_.qualitySubscribeReportData=u,_.subscribeData={start:Date.now()};const l={dur:0,cod:0,rid:this._roomId,csnid:this._clientSessionId,snid:this._sessionId,rsid:"",msa:"",msas:[],time:0,resid:"",mtp:0,smct:1,uid:"",stp:0};_.qualityUnsubscribeReportData=l,_.unsubscribeData={start:Date.now()},r.info(A.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_T,{trackIds:e.map(Gt),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:t},{logSource:i.RTC});const{reqBody:m}=yield this._createSubscribeParams(n,{},!1),p=yield this._exchangeHandle(m);let S=[],T=Date.now();if(_.mediaService.forEach((e=>{S.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),c.length){const e=[];c.forEach((t=>{e.push(t.track.getTrackId())})),null===(s=this._pc.reportParser)||void 0===s||s.clearLatestPacketsRecv(e)}if(p.code!==L.SUCCESS)return _.subscribeCommand&&(_.subscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualitySubscribeReportData,{dur:T-((null===(t=_.subscribeData)||void 0===t?void 0:t.start)||0),cod:p.code,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,s,i.RTC)}))),_.unsubscribeCommand&&(_.unsubscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualityUnsubscribeReportData,{dur:T-((null===(t=_.unsubscribeData)||void 0===t?void 0:t.start)||0),cod:p.code,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,s,i.RTC)}))),{code:p.code};const{sdp:C,resultCode:I,message:E,subscribedList:g}=p.data;if(I!==L.SUCCESS)return _.subscribeCommand&&(_.subscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualitySubscribeReportData,{dur:T-((null===(t=_.subscribeData)||void 0===t?void 0:t.start)||0),cod:I,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,s,i.RTC)}))),_.unsubscribeCommand&&(_.unsubscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualityUnsubscribeReportData,{dur:T-((null===(t=_.unsubscribeData)||void 0===t?void 0:t.start)||0),cod:I,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,s,i.RTC)}))),O.error("change subscribe list failed:",E,I),{code:I};n.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:i}=Lt(t.getTrackId()),s=[i,r].join("_");C.sdp=C.sdp.replace(new RegExp(e,"g"),s)}}));const f=yield this._pc.setRemoteAnswer(C.sdp);if(f!==L.SUCCESS)return _.subscribeCommand&&(_.subscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualitySubscribeReportData,{dur:T-((null===(t=_.subscribeData)||void 0===t?void 0:t.start)||0),cod:f,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,s,i.RTC)}))),_.unsubscribeCommand&&(_.unsubscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualityUnsubscribeReportData,{dur:T-((null===(t=_.unsubscribeData)||void 0===t?void 0:t.start)||0),cod:f,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,s,i.RTC)}))),{code:f};_.subscribeCommand&&(_.subscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualitySubscribeReportData,{dur:T-((null===(t=_.subscribeData)||void 0===t?void 0:t.start)||0),cod:f,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_SUBSCRIBE_S,s,i.RTC)}))),_.unsubscribeCommand&&(_.unsubscribeCommand=!1,n.forEach((e=>{var t,r;const s=JSON.stringify(Object.assign(_.qualityUnsubscribeReportData,{dur:T-((null===(t=_.unsubscribeData)||void 0===t?void 0:t.start)||0),cod:f,msas:S,time:T,resid:e.track.getTrackId(),mtp:Lt(e.track.getTrackId()).mediaType,smct:e.track instanceof at&&(null===(r=e.track)||void 0===r?void 0:r.__isTiny())?2:1}));h(R.STATISTICS,A.L_QS_UNSUBSCRIBE_S,s,i.RTC)})));const v=null==g?void 0:g.map((e=>`${e.msid}_${e.mediaType}`)),D=n.filter((e=>{if(e.track.isMCUTrack()){const t=this._roomRes[e.track.getTrackId()],r=`${t.msid}_${t.mediaType}`;return v.includes(r)}return null==v?void 0:v.includes(e.track.getTrackId())})),N=null==D?void 0:D.map((e=>`${e.track.getTrackId()}`)),b=n.filter((e=>!(null==N?void 0:N.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=D.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...D),b.length?{code:L.SUCCESS,failedList:b}:{code:L.SUCCESS}}))}_diffCDNUris(e){return v(this,void 0,void 0,(function*(){if(this._CDNUris.url&&!e.url)return this._callAppListener("onCDNInfoDisable"),void(this._CDNUris=e);(!this._CDNUris||!this._CDNUris.url&&e.url)&&this._callAppListener("onCDNInfoEnable",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`});const t=this._CDNUris.w&&e.w&&this._CDNUris.w!==e.w,r=this._CDNUris.h&&e.h&&this._CDNUris.h!==e.h,i=this._CDNUris.fps&&e.fps&&this._CDNUris.fps!==e.fps;(t||r||i)&&this._callAppListener("onCDNInfoChange",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`}),this._CDNUris=e}))}_getCDNPlayUrl(e){return v(this,void 0,void 0,(function*(){const{w:t,h:r,fps:i}=e,s=this._initOptions.pullInnerCDNProtocol||yi.FLV,o=this._initOptions.pullInnerCDNUseHttps===Ui.NOT_HTTPS?Ui.NOT_HTTPS:Ui.HTTPS;if(!this._CDNUris.url)return O.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${L.CDN_RESOURCE_IS_EMPTY}`),{code:L.CDN_RESOURCE_IS_EMPTY};const n={"App-Key":this._context.getAppkey(),Token:this._joinResData.token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},a=[],{w:c=0,h:d=1}=this._CDNUris;c/d>1?(t&&a.push(`w=${t}`),r&&a.push(`h=${r}`)):(t&&a.push(`h=${t}`),r&&a.push(`w=${r}`)),i&&a.push(`fps=${i}`),a.push(`kind=${s}`),a.push(`is_https=${o}`);const _=a.join("&");let u=`${this._CDNUris.url}?`;_&&(u+=_);const{code:l,res:h}=yield this._service.getCDNResourceInfo(n,u);return l!==L.SUCCESS?(O.error(`getCDNPlayUrl failed: ${l}`),{code:l}):(O.info(`getCDNPlayUrl success: ${null==h?void 0:h.data.pull_url}`),{code:l,CDNPlayUrl:null==h?void 0:h.data.pull_url})}))}getCDNPlayUrl(e,t){return v(this,void 0,void 0,(function*(){if(r.info(A.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_T,{resolution:e,fps:t},{logSource:i.RTC}),e&&!yt(e))return O.error("`resolution` is invalid"),r.error(A.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> resolution"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(t&&!Ut(t))return O.error("`fps` is invalid"),r.error(A.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> fps"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};const{width:s,height:o}=e?kt(e):{width:null,height:null},n=t?Pt(t):null,a={};return s&&(a.w=s),o&&(a.h=o),n&&(a.fps=n),r.info(A.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:D.SUCCESSED,resolution:e,fps:t},{logSource:i.RTC}),this._getCDNPlayUrl(a)}))}subscribe(e){return v(this,void 0,void 0,(function*(){return Qt.getMemo().subscribeCommand=!0,bi((()=>this._subscribeHandle(e,!1)),"audience-sub")}))}addSubscribeTask(e){return v(this,void 0,void 0,(function*(){return Qt.getMemo().subscribeCommand=!0,bi((()=>this._subscribeHandle(e,!1)),"audience-sub")}))}__unsubscribe(e){var t;return v(this,void 0,void 0,(function*(){if(r.info(A.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_T,{trackIds:e.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:i.RTC}),!o("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof mt))),!0))return O.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),r.error(A.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};const s=this._subscribedList.map((e=>Object.assign({},e))).filter((t=>!e.includes(t.track)));null===(t=this._polarisReport)||void 0===t||t.sendR2(gr.SUBSCRIBE,fr.END,e.map((e=>e.getTrackId()))),r.info(A.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:D.SUCCESSED,trackIds:e.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:i.RTC});return Qt.getMemo().unsubscribeCommand=!0,this._updateSubListHandle(s,!1)}))}unsubscribe(e){return v(this,void 0,void 0,(function*(){return bi((()=>this.__unsubscribe(e)),"audience-unsub")}))}addUnsubscribeTask(e){return v(this,void 0,void 0,(function*(){return bi((()=>this.__unsubscribe(e)),"audience-unsub")}))}__destroy(e){var t,r;return v(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(t=this._audioLevelReport)||void 0===t||t.clearAudioLevelReportTimer(),e&&(yield this._context.quitLivingRoomAsAudience(this._roomId)),yield this._service.broadcastExit(this._getReqHeaders()),null===(r=this._pc)||void 0===r||r.destroy(),Qt.destroy(),this._polarisReport=null,this._context.registerRTCSignalListener(void 0))}))}getRemoteTrack(e){return this._remoteTracks[e]}__getPC(){return this._peerCManager.getPCList()}getLocalTrack(e){return{}}__onReconnected(){return v(this,void 0,void 0,(function*(){const{code:e}=yield this._context.joinLivingRoomAsAudience(this._roomId,Ir.LIVE);e!==a.SUCCESS&&O.error("join living room error when on reconnected")}))}registerRoomEventListener(e){this._appListener=e}onAudioLevelChange(e,t){var s;null===(s=this._audioLevelReport)||void 0===s||s.clearAudioLevelReportTimer(),this._audioLevelReport=new Mr(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3),r.info(A.L_AUDIENCE_LIVING_ROOM_AUDIO_LEVEL_CHANGE_O,{status:D.SUCCESSED,handler:null==e?void 0:e.name,gap:t},{logSource:i.RTC})}registerReportListener(e){this._reportListener=e}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}getSessionId(){return this._sessionId}getRemoteUserIds(){return this._roomAnchorList}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getRemoteTracks(){const e=[],t=[];for(const e in this._remoteTracks){if(2===t.length)break;const r=this._remoteTracks[e];r.isMCUTrack()&&t.push(r)}return this._roomAnchorList.forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),[...t,...e]}getRemoteRTCTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()||e.push(r)}return e}getRemoteMCUTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()&&e.push(r)}return e}getCDNInfo(){return this._CDNUris.w?{resolution:`W${this._CDNUris.w}_H${this._CDNUris.h}`,fps:`FPS_${this._CDNUris.fps}`,CDNEnable:this._CDNUris.enableInnerCDN}:{CDNEnable:!1}}getClientSessionId(){return this._clientSessionId}}class xi{constructor(e){this._context=e,this._isElectron=/Electron/.test(navigator.userAgent)}_getMediaStream(e,t="getUserMedia"){return v(this,void 0,void 0,(function*(){try{const r=this.setConstraintsConfig(e),i=yield navigator.mediaDevices[t](r);return{code:L.SUCCESS,stream:i}}catch(e){if("Permission denied"===e.message)return{code:L.BROWSER_PERMISSION_DENIED};if("Permission denied by system"===e.message)return{code:L.SYSTEM_PERMISSION_DENIED};O.error(`get user media failed -> ${e.message}`)}return{code:"getUserMedia"===t?L.GET_USER_MEDIA_FAILED:L.GET_DISPLAY_MEDIA_FAILED}}))}setConstraintsConfig(e){if((null==e?void 0:e.audio)&&!this._isElectron){"boolean"==typeof e.audio&&(e.audio={});const t=navigator.mediaDevices.getSupportedConstraints();t.noiseSuppression&&(e.audio.noiseSuppression=!!t.noiseSuppression),t.autoGainControl&&(e.audio.autoGainControl=!!t.autoGainControl),t.echoCancellation&&(e.audio.echoCancellation=!!t.echoCancellation),O.info(`browser supported -> ${JSON.stringify(t)}`)}return e}createMicrophoneAudioTrack(e="RongCloudRTC",t){return v(this,void 0,void 0,(function*(){if(!It(e))return r.error(A.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS};const s=this._context.getCurrentId();if(!s)return r.error(A.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID};const{stream:o,code:n}=yield this._getMediaStream({audio:{deviceId:null==t?void 0:t.micphoneId,sampleRate:null==t?void 0:t.sampleRate}});if(n!==L.SUCCESS)return r.error(A.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:D.FAILED,code:n,msg:"Failed to get microphone audio stream"},{logSource:i.RTC}),{code:n};const a=o.getAudioTracks()[0],c=new ut(e,s,a);return r.info(A.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:D.SUCCESSED,trackId:c.getTrackId()},{logSource:i.RTC}),{code:n,track:c}}))}createCameraVideoTrack(e="RongCloudRTC",t){return v(this,void 0,void 0,(function*(){if(!It(e))return r.error(A.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS};const s=this._context.getCurrentId();if(!s)return r.error(A.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID};const o=yt(null==t?void 0:t.resolution)?t.resolution:je.W640_H480,{width:n,height:a}=kt(o),{stream:c,code:d}=yield this._getMediaStream({video:{deviceId:null==t?void 0:t.cameraId,frameRate:Pt((null==t?void 0:t.frameRate)||Ke.FPS_15),width:n,height:a,facingMode:null==t?void 0:t.faceMode}});if(d!==L.SUCCESS)return r.error(A.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"Failed to get camera video stream"},{logSource:i.RTC}),{code:d};const _=c.getVideoTracks()[0],u=new lt(e,s,_);return r.info(A.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:D.SUCCESSED,trackId:u.getTrackId()},{logSource:i.RTC}),{code:d,track:u}}))}createMicrophoneAndCameraTracks(e="RongCloudRTC",t){var s,o,n,a,c,d;return v(this,void 0,void 0,(function*(){const _=[];if(!It(e))return r.error(A.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS,tracks:_};const u=this._context.getCurrentId();if(!u)return r.error(A.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID,tracks:_};const l=yt(null===(s=null==t?void 0:t.video)||void 0===s?void 0:s.resolution)?t.video.resolution:je.W640_H480,{width:h,height:R}=kt(l),{stream:m,code:p}=yield this._getMediaStream({video:{deviceId:null===(o=null==t?void 0:t.video)||void 0===o?void 0:o.cameraId,frameRate:Pt((null===(n=null==t?void 0:t.video)||void 0===n?void 0:n.frameRate)||Ke.FPS_15),width:h,height:R,facingMode:null===(a=null==t?void 0:t.video)||void 0===a?void 0:a.faceMode},audio:{deviceId:null===(c=null==t?void 0:t.audio)||void 0===c?void 0:c.micphoneId,sampleRate:null===(d=null==t?void 0:t.audio)||void 0===d?void 0:d.sampleRate}});return p!==L.SUCCESS?(r.error(A.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:D.FAILED,code:p,msg:"Failed to get audio and video stream of camera and microphone"},{logSource:i.RTC}),{code:p,tracks:_}):(m.getTracks().forEach((t=>{"video"===t.kind?_.push(new lt(e,u,t)):_.unshift(new ut(e,u,t))})),r.info(A.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:D.SUCCESSED,trackIds:_.map((e=>e.getTrackId()))},{logSource:i.RTC}),{code:p,tracks:_})}))}createScreenVideoTrack(e="screenshare",t){return v(this,void 0,void 0,(function*(){const r=yield this._createScreenTracks(e,!1,A.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,t);return r.code===L.SUCCESS?{code:r.code,track:r.tracks[0]}:r}))}createScreenWithAudioTracks(e="screenshare",t){return v(this,void 0,void 0,(function*(){return this._createScreenTracks(e,!0,A.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_AND_AUDIO_TRACKS_O,t)}))}_createScreenTracks(e,t,s,o){var n,a;return v(this,void 0,void 0,(function*(){if(!It(e))return r.error(s,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS};const c=this._context.getCurrentId();if(!c)return r.error(s,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID};if(!wt())return r.error(A.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:D.FAILED,code:L.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:i.RTC}),{code:L.BROWSER_NOT_SUPPORT};const d=/macintosh|mac os x/i.test(navigator.userAgent);this._isElectron&&d&&t&&r.warn(s,{status:D.INFO,code:L.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO,msg:"mac in electron not support screen share with audio"});const _=(!this._isElectron||!d)&&t;if(this._isElectron&&!E(null==o?void 0:o.chromeMediaSourceId)&&!p(null==o?void 0:o.chromeMediaSourceId))return r.error(s,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> options.chromeMediaSourceId type is string"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};const u=yt(null==o?void 0:o.resolution)?o.resolution:je.W1280_H720,{width:l,height:h}=kt(u),R=this._isElectron?{mandatory:{chromeMediaSourceId:null==o?void 0:o.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:l,maxWidth:l,minHeight:h,maxHeight:h}}:{frameRate:Pt((null==o?void 0:o.frameRate)||Ke.FPS_15),width:l,height:h};!(null==o?void 0:o.chromeMediaSourceId)&&this._isElectron&&(null===(n=R.mandatory)||void 0===n||delete n.chromeMediaSourceId);let m=null;_&&this._isElectron&&(null===(a=R.mandatory)||void 0===a||delete a.chromeMediaSourceId,m={mandatory:{chromeMediaSource:"desktop"}});const{stream:S,code:T}=yield this._getMediaStream({video:R,audio:m||_},this._isElectron?"getUserMedia":"getDisplayMedia");if(T!==L.SUCCESS)return r.error(s,{status:D.FAILED,code:T,msg:"Failed to get shared screen video stream"},{logSource:i.RTC}),{code:T};const C=S.getVideoTracks()[0],I=[new ht(e,c,C)];if(_){const t=S.getAudioTracks()[0];t&&I.push(new Rt(e,c,t))}return r.info(s,{status:D.SUCCESSED,trackIds:I.map((e=>e.getTrackId()))},{logSource:i.RTC}),{code:T,tracks:I}}))}createLocalAudioTrack(e,t){return v(this,void 0,void 0,(function*(){if(!It(e))return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"audio"!==t.kind)return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"Failed to create custom stream"},{logSource:i.RTC}),{code:L.CREATE_CUSTOM_TRACK_FAILED};const s=this._context.getCurrentId();if(!s)return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID};const o=new nt(e,s,t);return r.info(A.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:D.SUCCESSED,trackId:o.getTrackId()},{logSource:i.RTC}),{code:L.SUCCESS,track:o}}))}createLocalVideoTrack(e,t){return v(this,void 0,void 0,(function*(){if(!It(e))return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"video"!==t.kind)return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:D.FAILED,code:L.CREATE_CUSTOM_TRACK_FAILED,msg:"Failed to create custom stream"},{logSource:i.RTC}),{code:L.CREATE_CUSTOM_TRACK_FAILED};const s=this._context.getCurrentId();if(!s)return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID};const o=new at(e,s,t);return r.info(A.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:D.SUCCESSED,trackId:o.getTrackId()},{logSource:i.RTC}),{code:L.SUCCESS,track:o}}))}createLocalFileTracks(e,t,s){return v(this,void 0,void 0,(function*(){if(!It(e))return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS,tracks:[]};if(!xt())return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:D.FAILED,code:L.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:i.RTC}),{code:L.BROWSER_NOT_SUPPORT,tracks:[]};const o=t instanceof File?URL.createObjectURL(t):t;if(!C(o)&&!/^blob:/.test(o))return O.warn(`createLocalFileTracks failed: params error -> url: ${o}`),r.error(A.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> file"},{logSource:i.RTC}),{code:L.PARAMS_ERROR,tracks:[]};const n=this._context.getCurrentId();return n?new Promise((t=>{const a=document.createElement("video");(null==s?void 0:s.withoutAudio)&&(a.muted=!0),a.onloadedmetadata=()=>{const c=[];let d;try{const e=a.mozCaptureStream?"mozCaptureStream":"captureStream";d=a[e]()}catch(e){O.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${o}`),O.error(e),r.error(A.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:D.FAILED,code:L.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:i.RTC}),t({code:L.CREATE_FILE_TRACK_FAILED,tracks:c})}const[_,u]=xi.getTracksWithOptions(d,s);_&&c.push(new _t(e,n,_,a)),u&&c.push(new dt(e,n,u,a)),0===c.length&&(a.pause(),a.src=""),a.onerror=null,r.info(A.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:D.SUCCESSED,trackIds:c.map((e=>e.getTrackId()))},{logSource:i.RTC}),t({code:L.SUCCESS,tracks:c})},a.onerror=()=>{O.error(`create RCLocalFileTrack failed -> url: ${o}`),r.error(A.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:D.FAILED,code:L.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:i.RTC}),t({code:L.CREATE_FILE_TRACK_FAILED,tracks:[]})},a.src=o,a.loop=!0,a.play()})):(r.error(A.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID,tracks:[]})}))}createLocalTracks(e,t,s){return v(this,void 0,void 0,(function*(){const o=[];if(!It(e))return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:D.FAILED,code:L.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:L.INVALID_TAGS,tracks:o};if(!(t instanceof MediaStream))return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> stream"},{logSource:i.RTC}),{code:L.PARAMS_ERROR,tracks:o};const n=this._context.getCurrentId();if(!n)return r.error(A.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:D.FAILED,code:L.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:L.INVALID_USER_ID,tracks:o};const[a,c]=xi.getTracksWithOptions(t,s);return a&&o.push(new nt(e,n,a)),c&&o.push(new at(e,n,c)),r.info(A.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:D.SUCCESSED,trackIds:o.map((e=>e.getTrackId()))},{logSource:i.RTC}),{code:L.SUCCESS,tracks:o}}))}static getTracksWithOptions(e,t){const r=[];return r[0]=(null==t?void 0:t.withoutAudio)?void 0:e.getAudioTracks()[0],r[1]=(null==t?void 0:t.withoutVideo)?void 0:e.getVideoTracks()[0],r}}class wi extends xi{constructor(e,t,r){super(e),this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,Ar.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new Zt(this._runtime,this._context,this._options.mediaServer,this._options.timeout),this._context.registerConnectionStateChangeListener(this._onIMStatusChange.bind(this)),this._context.registerDisconnectListener(this._onIMDisconnect.bind(this)),this._context.registerDestroyListener(this._onIMUninit.bind(this)),this._context.registerMessageListener(this._handleMessage.bind(this)),this._context.getPluginContext().onnavidatachange=this.naviDataChange.bind(this)}_handleMessage(e){if(e.conversationType!==T.RTC_ROOM)return!1;if(this._crtRoom instanceof Ai){this._getJoinedPKRoomList().forEach((t=>{t.__parseInnerMessage(e)}))}return r.info(A.L_RTC_CLIENT_MESSAGE_O,{status:D.SUCCESSED,message:e},{logSource:i.RTC}),this._crtRoom?(this._crtRoom.__parseInnerMessage(e),!0):(r.warn(A.L_RTC_CLIENT_MESSAGE_O,{status:D.FAILED,message:"the crtRoom is empty"},{logSource:i.RTC}),!0)}naviDataChange(e){r.info(`on navi change data => ${JSON.stringify(e)}`),this._service.detectorMediaSever()}_getJoinedPKRoomList(){const{code:e,roomPKHandler:t}=this._crtRoom.getRoomPKHandler();if(e===L.SUCCESS&&t){const e=t.getJoinedPKRooms()||{};return Object.values(e)}return[]}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(e,t,s,o,n=Ir.RTC){return v(this,void 0,void 0,(function*(){if(r.info(A.L_RTC_CLIENT_JOIN_RTC_ROOM_T,{roomId:e,joinType:t,outerUserDatas:s,useMutilPeerC:o,roomType:n},{logSource:i.RTC}),this._crtRoom)return r.error(A.L_RTC_CLIENT_JOIN_RTC_ROOM_R,{status:D.FAILED,code:L.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:L.REPERT_JOIN_ROOM};const a=this._crtRoom=new Di(this._context,this._runtime,e,this._service,this._options,!1,!1,o,qt()),{code:c}=yield a.__innerInit(n,t,void 0,void 0,s);return c!==L.SUCCESS?(this._crtRoom=null,{code:c}):(a.once(di,(()=>{this._crtRoom=null})),{code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()})}))}joinCrossRTCRoom(e,t,s,o,n=Ir.CROSS_MUTI){return v(this,void 0,void 0,(function*(){if(r.info(A.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_T,{roomId:e,joinType:t,outerUserDatas:s,useMutilPeerC:o,roomType:n},{logSource:i.RTC}),this._crtRoom)return r.error(A.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_R,{status:D.FAILED,code:L.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:L.REPERT_JOIN_ROOM};const a=this._crtRoom=new Di(this._context,this._runtime,e,this._service,this._options,!1,!1,o,qt(),n),{code:c}=yield a.__innerInit(n,t,void 0,void 0,s);return c!==L.SUCCESS?(this._crtRoom=null,{code:c}):(a.once(di,(()=>{this._crtRoom=null})),{code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()})}))}joinLivingRoom(e,t,s,o,n){return v(this,void 0,void 0,(function*(){if(r.info(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_T,{roomId:e,livingType:t,joinType:s,outerUserDatas:o,useMutilPeerC:n},{logSource:i.RTC}),this._crtRoom)return r.error(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:D.FAILED,code:L.REPERT_JOIN_ROOM,msg:`Join the room repeatedly -> roomId: ${e}`},{logSource:i.RTC}),{code:L.REPERT_JOIN_ROOM};const a=this._crtRoom=new Ai(this._context,this._runtime,e,this._service,this._options,t,!1,!0,n),{code:c}=yield a.__innerInit(Ir.LIVE,s,t,void 0,o);if(c!==L.SUCCESS)return this._crtRoom=null,{code:c};a.once(di,(()=>{this._crtRoom=null}));const d={code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()};return a.__getCDNPushMode()===Ci.MANUAL&&Object.assign(d,{CDNEnable:a.__getCDNEnable()}),d}))}getAudienceClient(e){return this._audience||(this._audience=new ki(this._context,this._runtime,this._options,e)),r.info(A.L_RTC_CLIENT_GET_AUDIENCE_CLIENT_O,{status:D.SUCCESSED},{logSource:i.RTC}),this._audience}_onIMStatusChange(e){if(O.debug(`signal server connection state change: ${e}`),r.info(A.L_RTC_CLIENT_CONNECTION_STATE_S,{status:D.SUCCESSED,data:e},{logSource:i.RTC}),e===_.CONNECTED){if(this._service.detectorMediaSever(),this._crtRoom instanceof Ai){this._getJoinedPKRoomList().forEach((e=>{e.__onReconnected()}))}this._crtRoom&&this._crtRoom.__onReconnected()}}_onIMDisconnect(){r.info(A.L_RTC_CLIENT_DISCONNECT_S,{status:D.SUCCESSED},{logSource:i.RTC}),O.debug("TODO -> on IM disconnect")}_onIMUninit(){r.info(A.L_RTC_CLIENT_DESTROY_S,{status:D.SUCCESSED},{logSource:i.RTC}),O.debug("TODO -> on IM client ondestroy")}leaveRoom(e){var t,s;return v(this,void 0,void 0,(function*(){return r.info(A.L_RTC_CLIENT_LEAVE_ROOM_T,{userId:this._context.getCurrentId(),roomId:null===(t=this._crtRoom)||void 0===t?void 0:t.getRoomId()},{logSource:i.RTC}),this._crtRoom?(yield this._crtRoom.__destroy(!0),O.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),this._service.detectorMediaSever(),r.info(A.L_RTC_CLIENT_LEAVE_ROOM_R,{status:D.SUCCESSED,userId:this._context.getCurrentId(),roomId:null===(s=this._crtRoom)||void 0===s?void 0:s.getRoomId()},{logSource:i.RTC}),this._crtRoom=null,{code:L.SUCCESS}):(r.warn(A.L_RTC_CLIENT_LEAVE_ROOM_R,{status:D.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:i.RTC}),{code:L.SUCCESS})}))}joinLivingRoomAsAudience(e,t,s){return v(this,void 0,void 0,(function*(){if(r.info(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_T,{roomId:e,livingType:t,useMutilPeerC:s},{logSource:i.RTC}),this._service.detectorMediaSever(),Vt(this._context.getNaviInfo()))return r.error(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:D.FAILED,code:L.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:i.RTC}),{code:L.PACKAGE_ENVIRONMENT_ERROR};if(!o("roomId",e,m,!0)||!o("livingType",t,(e=>e===Ti.AUDIO||e===Ti.VIDEO)))return r.error(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:D.FAILED,code:L.PACKAGE_ENVIRONMENT_ERROR,msg:"params error -> roomId or livingType"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return r.error(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:D.FAILED,code:L.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:L.REPERT_JOIN_ROOM};if(!this._service.getNaviMS().length)return r.error(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:D.FAILED,code:L.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:i.RTC}),{code:L.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:n,data:c}=yield this._context.joinLivingRoomAsAudience(e,Ir.LIVE,t);if(n!==a.SUCCESS)return O.error("audienceJoinLivingRoomError:",n),r.error(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:D.FAILED,code:L.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED,msg:"signal error -> audience join room"},{logSource:i.RTC}),{code:L.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};O.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(c)}`);const d=qt();Qt.getMemo().clientData={clientSessionId:d};const _=new Mi(this._context,this._runtime,this._options,e,c,t,s,d);return this._crtAudienceLivingRoom=_,r.info(A.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:D.SUCCESSED,roomData:c},{logSource:i.RTC}),{room:_,code:L.SUCCESS,userIds:_.getRemoteUserIds(),RTCTracks:_.getRemoteRTCTracks(),MCUTracks:_.getRemoteMCUTracks(),CDNUris:_.getCDNInfo()}}))}leaveLivingRoomAsAudience(e){return v(this,void 0,void 0,(function*(){return r.info(A.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_T,{roomId:e.getRoomId(),userId:this._context.getCurrentId()},{logSource:i.RTC}),this._crtAudienceLivingRoom?this._crtAudienceLivingRoom!==e?(r.error(A.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> room"},{logSource:i.RTC}),{code:L.PARAMS_ERROR}):(yield this._crtAudienceLivingRoom.__destroy(!0),this._crtAudienceLivingRoom=null,r.info(A.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:D.SUCCESSED,roomId:e.getRoomId(),userId:this._context.getCurrentId()},{logSource:i.RTC}),{code:L.SUCCESS}):(r.warn(A.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:D.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:i.RTC}),{code:L.SUCCESS})}))}upgradeToAnchorRoom(e){return v(this,void 0,void 0,(function*(){if(!o("room",e,(()=>e instanceof Mi),!0))return r.error(A.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> room"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(r.info(A.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_T,{roomId:e.getRoomId(),userId:this._context.getCurrentId()},{logSource:i.RTC}),this._crtRoom)return r.error(A.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:D.FAILED,code:L.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:L.REPERT_JOIN_ROOM};const t=e.getRoomId(),s=this._crtRoom=new Ai(this._context,this._runtime,t,this._service,this._options,e.livingType,!0,!0,!1,e.getClientSessionId()),n=yield s.__innerInitByIdentityChange();return n!==a.SUCCESS?(O.warn(`change room identity failed -> code: ${n}`),this._crtRoom=null,r.error(A.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:D.FAILED,code:L.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:i.RTC}),{code:L.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):(s.once(di,(()=>{this._crtRoom=null})),yield this._crtAudienceLivingRoom.__destroy(!1),this._crtAudienceLivingRoom=null,{room:s,code:L.SUCCESS,userIds:s.getRemoteUserIds(),tracks:s.getRemoteTracks()})}))}downgradeToAudienceRoom(e){return v(this,void 0,void 0,(function*(){if(r.info(A.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_T,{roomId:e._roomId,userId:this._context.getCurrentId()},{logSource:i.RTC}),!e.isMainRoom())return O.error("the `downgradeToAudienceRoom` is disabled in PK room"),r.error(A.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:D.FAILED,code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:L.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!o("room._roomId",e._roomId,m,!0))return r.error(A.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:D.FAILED,code:L.PARAMS_ERROR,msg:"params error -> room._roomId"},{logSource:i.RTC}),{code:L.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return r.error(A.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:D.FAILED,code:L.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:L.REPERT_JOIN_ROOM};const{code:t,data:s}=yield this._context.rtcIdentityChange(e._roomId,Ei.AnchorToViewer,e.getLivingType());if(t!==a.SUCCESS)return O.error("change room identity error",t),r.error(A.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:D.FAILED,code:L.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:i.RTC}),{code:L.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};O.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(s)}`),r.info(A.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:D.SUCCESSED,roomData:s},{logSource:i.RTC});const n=e.getClientSessionId(),c=new Mi(this._context,this._runtime,this._options,e._roomId,s,e.getLivingType(),!1,n);return this._crtAudienceLivingRoom=c,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:c,code:L.SUCCESS,userIds:c.getRemoteUserIds(),RTCTracks:c.getRemoteRTCTracks(),MCUTracks:c.getRemoteMCUTracks(),CDNUris:c.getCDNInfo()}}))}getJoinedRoomInfo(){return v(this,void 0,void 0,(function*(){const{code:e,data:t}=yield this._context.getRTCJoinedUserInfo(this._context.getCurrentId());return e!==a.SUCCESS?(O.error("getJoinedUserInfo error",e),r.error(A.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:D.FAILED,code:e,msg:"Switch identity error"},{logSource:i.RTC}),{code:e}):(r.info(A.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:D.SUCCESSED,roomInfo:t},{logSource:i.RTC}),{code:L.SUCCESS,data:t})}))}reportSDKInfo(){this._context.reportSDKInfo({"plugin-rtc":"5.5.3"})}}const Bi="rtcRJoin_data",Vi="rtcRExit",$i="rtcRInfo",Fi="rtcUData",Gi="rtcUDel",Ki="rtcSetData",ji="userSetData",Hi="rtcQryData",Ji="rtcDelData",qi="rtcToken",Wi="rtcUserState",Yi="rtcUList",Qi="viewerJoinR",zi="viewerExitR",Zi="rtcPullKv",Xi="rtcIdentityChange",es="rtcInvite",ts="rtcCancelInvite",rs="rtcInviteAnswer",is="rtcEndInvite",ss="rtcQueryJoined",os="reportsdk";var ns;!function(e){e.RtcInput="RtcInput",e.RtcUserListOutput="RtcUserListOutput",e.SetUserStatusInput="SetUserStatusInput",e.RtcSetDataInput="RtcSetDataInput",e.RtcUserSetDataInput="RtcUserSetDataInput",e.RtcDataInput="RtcDataInput",e.RtcSetOutDataInput="RtcSetOutDataInput",e.MCFollowInput="MCFollowInput",e.RtcTokenOutput="RtcTokenOutput",e.RtcQryOutput="RtcQryOutput",e.RtcQryUserOutDataInput="RtcQryUserOutDataInput",e.RtcUserOutDataOutput="RtcUserOutDataOutput",e.RtcQueryListInput="RtcQueryListInput",e.RtcRoomInfoOutput="RtcRoomInfoOutput",e.RtcValueInfo="RtcValueInfo",e.RtcKeyDeleteInput="RtcKeyDeleteInput",e.RtcNotifyMsg="RtcNotifyMsg",e.RtcPullKV="RtcPullKV",e.RtcKVOutput="RtcKVOutput",e.RtcQueryUserJoinedInput="RtcQueryUserJoinedInput",e.RtcQueryUserJoinedOutput="RtcQueryUserJoinedOutput",e.RtcViewerJoinedOutput="RtcViewerJoinedOutput",e.RtcInviteInput="RtcInviteInput",e.RtcCancelInviteInput="RtcCancelInviteInput",e.RtcInviteAnswerInput="RtcInviteAnswerInput",e.RtcEndInviteInput="RtcEndInviteInput",e.RtcReportSDKInput="RtcReportSDKInput"}(ns||(ns={}));const as={[ns.RtcInput]:["roomType","broadcastType","extraInnerData","needSysChatroom","identityChangeType","joinType","innerDatas","outerDatas"],[ns.RtcUserListOutput]:["users","token","sessionId","roomInfo"],[ns.SetUserStatusInput]:["status"],[ns.RtcSetDataInput]:["interior","target","key","value","objectName","content"],[ns.RtcUserSetDataInput]:["valueInfo","objectName","content"],[ns.RtcDataInput]:["interior","target","key","objectName","content"],[ns.RtcSetOutDataInput]:["target","valueInfo","objectName","content"],[ns.MCFollowInput]:["state"],[ns.RtcTokenOutput]:["rtcToken"],[ns.RtcQryOutput]:["outInfo"],[ns.RtcQryUserOutDataInput]:["userId"],[ns.RtcUserOutDataOutput]:["user"],[ns.RtcQueryListInput]:["order"],[ns.RtcRoomInfoOutput]:["roomId","roomData","userCount","list"],[ns.RtcValueInfo]:["key","value"],[ns.RtcKeyDeleteInput]:["key"],[ns.RtcNotifyMsg]:["type","time","roomId"],[ns.RtcPullKV]:["timestamp","roomId"],[ns.RtcKVOutput]:["entries","bFullUpdate","syncTime"],[ns.RtcQueryUserJoinedInput]:["userId"],[ns.RtcQueryUserJoinedOutput]:["info"],[ns.RtcInviteInput]:["invitedUserId","timeoutTime","invitedRoomId","inviteInfo","inviteSessionId"],[ns.RtcCancelInviteInput]:["invitedUserId","invitedRoomId","inviteInfo","inviteSessionId"],[ns.RtcInviteAnswerInput]:["inviteUserId","answerCode","inviteRoomId","inviteSessionId","content","key","value"],[ns.RtcEndInviteInput]:["inviteRoomId","inviteSessionId","inviteContent","inviteRoomKeys"],[ns.RtcReportSDKInput]:["sdkInfo"]},cs=`\npackage Modules;\nmessage probuf {\n enum JoinType {\n KICK = 0; //踢前一个设备\n REFUSE = 1; //当前加入拒绝\n COEXIST = 2; //两个设备共存\n }\n enum targetType {\n ROOM =1 ;\n PERSON = 2;\n }\n message ${ns.SetUserStatusInput}\n {\n optional int32 status=1;\n }\n message ${ns.MCFollowInput}\n {\n required string state = 1;\n }\n message ${ns.RtcQueryListInput}{\n optional int32 order=1;\n }\n message ${ns.RtcKeyDeleteInput}{\n repeated string key=1;\n }\n message ${ns.RtcValueInfo}{\n required string key=1;\n required string value=2;\n }\n message RtcUserInfo{\n required string userId=1;\n repeated ${ns.RtcValueInfo} userData=2; //用户资源信息\n }\n message ${ns.RtcUserListOutput}{\n repeated RtcUserInfo users=1;\n optional string token=2;\n optional string sessionId=3;\n repeated RtcValueInfo roomInfo = 4; //房间key value\n repeated RtcKVEntity entries = 5;//直播KV属性对象集合\n optional int64 syncTime = 6;//所有属性的最大时间戳(下次拉取KV时用)。\n optional int32 offlineKickTime = 7;//server超时踢人时间,默认60s\n }\n message RtcRoomInfoOutput{\n optional string roomId = 1;\n repeated ${ns.RtcValueInfo} roomData = 2;\n optional int32 userCount = 3;\n repeated RtcUserInfo list=4;\n }\n message ${ns.RtcInput}{\n required int32 roomType=1;\n optional int32 broadcastType=2;\n optional RtcValueInfo extraInnerData = 3;\n optional bool needSysChatroom = 4; //是否需要同步聊天室\n optional IdentityChangeType identityChangeType = 5; //身份变更类型\n optional JoinType joinType = 6; // 加入房间类型\n repeated ${ns.RtcValueInfo} innerDatas = 7; //用户内部inner数据,角色或者连麦信息等\n repeated ${ns.RtcValueInfo} outerDatas = 8; //用户内部outer数据,自定义数据结构RtcInput。\n }\n message ${ns.RtcQryOutput}{\n repeated ${ns.RtcValueInfo} outInfo=1;\n }\n message ${ns.RtcDataInput}{\n required bool interior=1;\n required targetType target=2;\n repeated string key=3;\n optional string objectName=4;\n optional string content=5;\n }\n message ${ns.RtcSetDataInput}{\n required bool interior=1;\n required targetType target=2;\n required string key=3;\n required string value=4;\n optional string objectName=5;\n optional string content=6;\n }\n message ${ns.RtcUserSetDataInput} {\n repeated ${ns.RtcValueInfo} valueInfo = 1;\n required string objectName = 2;\n repeated ${ns.RtcValueInfo} content = 3;\n }\n message RtcQryInput{\n required bool isInterior=1;\n required targetType target=2;\n repeated string key=3;\n }\n message RtcDelDataInput{\n repeated string key=1;\n required bool isInterior=2;\n required targetType target=3;\n }\n message RtcOutput\n {\n optional int32 nothing=1;\n }\n message ${ns.RtcTokenOutput}{\n required string rtcToken=1;\n }\n message ${ns.RtcSetOutDataInput}{\n required targetType target=1;\n repeated ${ns.RtcValueInfo} valueInfo=2;\n optional string objectName=3;\n optional string content=4;\n }\n message ${ns.RtcQryUserOutDataInput}{\n repeated string userId = 1;\n }\n message ${ns.RtcUserOutDataOutput}{\n repeated RtcUserInfo user = 1;\n }\n message ${ns.RtcNotifyMsg} \n {\n required int32 type= 1; //(通知类型 1:rtc房间状态KV变更通知)\n optional int64 time= 2; //消息产生时间\n optional string roomId=3; //主播房间id\n }\n message ${ns.RtcPullKV}\n {\n required int64 timestamp = 1;\n required string roomId = 2;\n }\n message RtcKVEntity \n {\n required string key = 1;\n required string value = 2;\n optional int32 status = 3;\n optional int64 timestamp = 4;\n optional string uid = 5;\n }\n message ${ns.RtcKVOutput}\n {\n repeated RtcKVEntity entries = 1;\n optional bool bFullUpdate = 2;\n optional int64 syncTime = 3; \n }\n enum IdentityChangeType \n {\n AnchorToViewer = 1; //1为主播变观众\n ViewerToAnchor = 2; //2为观众变主播\n }\n message ${ns.RtcQueryUserJoinedInput}\n {\n required string userId = 1;\n }\n message RtcJoinedInfo\n {\n required string deviceId = 1; //设备ID\n required string roomId = 2; //加入的房间ID\n optional int64 joinTime = 3; //加入的时间\n }\n message ${ns.RtcQueryUserJoinedOutput}\n {\n repeated RtcJoinedInfo info = 1;\n }\n message ${ns.RtcViewerJoinedOutput}\n {\n required string rtcToken=1;\n repeated RtcKVEntity entries = 2;//KV属性对象集合\n optional int64 syncTime = 3;//所有属性的最大时间戳(下次拉取KV时用)。\n }\n message ${ns.RtcInviteInput}\n {\n required string invitedUserId=1; //被邀请的人的uid\n optional int32 timeoutTime=2; //邀请超时时间(秒),默认三十秒\n required string invitedRoomId=3; //被邀请的房间\n required string inviteInfo=4; //邀请的信息(包含邀请人,被邀请人,各自userid)客户端定义好.协议栈和server透传\n required string inviteSessionId= 5; //客户端保证唯一性(建议roomid_userid_时间戳_随机数)\n }\n message ${ns.RtcCancelInviteInput}\n {\n required string invitedUserId=1; //被邀请的人的uid\n required string invitedRoomId=2; //被邀请的房间\n required string inviteInfo=3; //取消邀请的信息(包含邀请人,被邀请人,各自userid)客户端定义好.协议栈和server透传\n required string inviteSessionId=4; //邀请的sessionId,客户端发起邀请时产生\n }\n message ${ns.RtcInviteAnswerInput}\n {\n required string inviteUserId=1; //邀请的人的uid\n required int32 answerCode=2; //是否接受连麦邀请.0为拒绝,1为接受\n required string inviteRoomId=3; //邀请的房间\n required string inviteSessionId=4; //邀请的sessionId\n required string content=5; //需要转发的content\n optional string key=6; //如果接受的话,需要加这个字段,放在room级别的k和v,新加入房间的能拉取到\n optional string value=7; //如果接受的话,需要加这个字段,放在room级别的k和v,新加入房间的能拉取到\n }\n message ${ns.RtcEndInviteInput}\n {\n required string inviteRoomId=1; //邀请的房间\n required string inviteSessionId=2; //邀请的sessionId\n required string inviteContent=3; //结束连麦的信息(需要透传给房间内其他人)\n repeated string inviteRoomKeys=4; //需要删除连麦的信息的key\n }\n message ${ns.RtcReportSDKInput} {\n required string sdkInfo=1; // 用户集成的 sdk 信息,json 格式 {"web-rtc": "4.0.3.7"}\n }\n}\n`,ds=(e,t,r,i,s,o)=>{const n=s?Object.keys(s).map((t=>e.encode(ns.RtcValueInfo,{key:t,value:s[t]},!0))):void 0,a=o?Object.keys(o).map((t=>e.encode(ns.RtcValueInfo,{key:t,value:o[t]},!0))):void 0;return e.encode(ns.RtcInput,{roomType:t,broadcastType:r,joinType:i,innerDatas:n,outerDatas:a})},_s=(e,t)=>{const r=e.decode(ns.RtcUserListOutput,t),{users:i,token:s,sessionId:o,roomInfo:n,entries:a,offlineKickTime:c}=r,d={};return g(i,(e=>{const{userId:t,userData:r}=e,i={};g(r,(e=>{const{key:t,value:r}=e;i[t]=r})),d[t]=i})),{users:d,token:s,sessionId:o,roomInfo:n,kvEntries:a,offlineKickTime:c}};class us{constructor(e,t){this.context=e,this.codec=t}joinRTCRoom(e,t,r,i,s,o){return v(this,void 0,void 0,(function*(){const n=ds(this.codec,t,r,i,s,o),{code:c,buffer:d}=yield this.context.rtcSignaling(e,Bi,!0,n);let _;return c===a.SUCCESS&&d&&(_=_s(this.codec,d)),{code:c,data:_}}))}quitRTCRoom(e){return v(this,void 0,void 0,(function*(){const t=this.codec.encode(ns.SetUserStatusInput,{status:0}),{code:r}=yield this.context.rtcSignaling(e,Vi,!0,t);return r}))}getRTCRoomInfo(e){return v(this,void 0,void 0,(function*(){const t=this.codec.encode(ns.RtcQueryListInput,{order:2}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,$i,!0,t);let s;return r===a.SUCCESS&&i&&(s=this.codec.decode(ns.RtcRoomInfoOutput,i)),{code:r,data:s}}))}getRTCUserInfoList(e){return v(this,void 0,void 0,(function*(){const t=this.codec.encode(ns.RtcQueryListInput,{order:2}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,Fi,!0,t);let s;if(r===a.SUCCESS&&i){s={users:_s(this.codec,i).users}}return{code:r,data:s}}))}getRTCUserInfo(e){throw new Error("Method not implemented.")}removeRTCUserInfo(e,t){return v(this,void 0,void 0,(function*(){const r=this.codec.encode(ns.RtcKeyDeleteInput,{key:t}),{code:i}=yield this.context.rtcSignaling(e,Gi,!1,r);return i}))}setRTCData(e,t,r,i,s,o){return v(this,void 0,void 0,(function*(){const n=this.codec.encode(ns.RtcSetDataInput,{interior:i,target:s,key:t,value:r,objectName:null==o?void 0:o.name,content:null==o?void 0:o.content}),{code:a}=yield this.context.rtcSignaling(e,Ki,!1,n);return a}))}setRTCTotalRes(e,t,r,i,s=""){return v(this,void 0,void 0,(function*(){const o={objectName:i,content:this.codec.encode(ns.RtcValueInfo,{key:t.name,value:t.content},!0),valueInfo:[this.codec.encode(ns.RtcValueInfo,{key:"uris",value:r},!0),this.codec.encode(ns.RtcValueInfo,{key:"mcu_uris",value:s},!0)]},n=this.codec.encode(ns.RtcUserSetDataInput,o),{code:a}=yield this.context.rtcSignaling(e,ji,!0,n);return a}))}setRTCCDNUris(e,t,r){return v(this,void 0,void 0,(function*(){const i=this.codec.encode(ns.RtcUserSetDataInput,{objectName:t,valueInfo:this.codec.encode(ns.RtcValueInfo,{key:"cdn_uris",value:r},!0)}),{code:s}=yield this.context.rtcSignaling(e,ji,!0,i);return s}))}getRTCData(e,t,r,i){return v(this,void 0,void 0,(function*(){const s=this.codec.encode(ns.RtcDataInput,{interior:r,target:i,key:t}),{code:o,buffer:n}=yield this.context.rtcSignaling(e,Hi,!0,s);if(o!==a.SUCCESS||!n)return{code:o};const{outInfo:c}=this.codec.decode(ns.RtcQryOutput,n),d={};return c.forEach((e=>{d[e.key]=e.value})),{code:o,data:d}}))}removeRTCData(e,t,r,i,s){return v(this,void 0,void 0,(function*(){const o=this.codec.encode(ns.RtcDataInput,{interior:r,target:i,key:t,objectName:(null==s?void 0:s.name)||"",content:(null==s?void 0:s.content)||""}),{code:n}=yield this.context.rtcSignaling(e,Ji,!1,o);return n}))}setRTCOutData(e,t,r,i){return v(this,void 0,void 0,(function*(){throw new Error("JSEngine's method not implemented.")}))}getRTCOutData(e,t){return v(this,void 0,void 0,(function*(){throw new Error("JSEngine's method not implemented.")}))}getRTCToken(e,t,r){return v(this,void 0,void 0,(function*(){const i=ds(this.codec,t,r),{code:s,buffer:o}=yield this.context.rtcSignaling(e,qi,!0,i);if(s!==a.SUCCESS||!o)return{code:s};const{rtcToken:n}=this.codec.decode(ns.RtcTokenOutput,o);return{code:s,data:{rtcToken:n}}}))}setRTCState(e,t){return v(this,void 0,void 0,(function*(){const r=this.codec.encode(ns.MCFollowInput,{state:t}),{code:i}=yield this.context.rtcSignaling(e,Wi,!0,r);return i}))}getRTCUserList(e){return v(this,void 0,void 0,(function*(){const t=this.codec.encode(ns.RtcQueryListInput,{order:2}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,Yi,!0,t);if(r!==a.SUCCESS||!i)return{code:r};return{code:r,data:_s(this.codec,i)}}))}joinLivingRoomAsAudience(e,t,r){var s,o;return v(this,void 0,void 0,(function*(){const n=ds(this.codec,t,r),c=Qt.getMemo(),d={dur:0,cod:0,rid:"",rtp:t,csnid:"",snid:"",time:0,cr:"unknown",net:"unknown",uid:""};c.qualityJoinRoomReportData=d,c.joinRoomData={start:Date.now()};const{code:_,buffer:u}=yield this.context.rtcSignaling(e,Qi,!0,n);if(_!==a.SUCCESS||!u)return{code:_};const{rtcToken:l,entries:m}=this.codec.decode(ns.RtcViewerJoinedOutput,u),p=Date.now(),S=JSON.stringify(Object.assign(c.qualityJoinRoomReportData,{dur:p-((null===(s=c.joinRoomData)||void 0===s?void 0:s.start)||0),cod:_,rid:e,csnid:null===(o=c.clientData)||void 0===o?void 0:o.clientSessionId,snid:Ft(e,m).sessionId,time:p,uid:this.context.getCurrentId()}));return h(R.STATISTICS,A.L_QS_JOIN_ROOM_S,S,i.RTC),{code:_,data:{token:l,kvEntries:m}}}))}quitLivingRoomAsAudience(e){return v(this,void 0,void 0,(function*(){const t=this.codec.encode(ns.SetUserStatusInput,{status:0}),{code:r}=yield this.context.rtcSignaling(e,zi,!0,t);return r}))}rtcIdentityChange(e,t,r){return v(this,void 0,void 0,(function*(){const i=this.codec.encode(ns.RtcInput,{roomType:Ir.LIVE,broadcastType:r,identityChangeType:t,needSysChatroom:!1}),{code:s,buffer:o}=yield this.context.rtcSignaling(e,Xi,!0,i);if(s!==a.SUCCESS||!o)return{code:s};return{code:s,data:_s(this.codec,o)}}))}requestRoomPK(e){return v(this,void 0,void 0,(function*(){const{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,inviteTimeout:s,inviteInfo:o,roomId:n}=e,a=this.codec.encode(ns.RtcInviteInput,{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,timeoutTime:s,inviteInfo:o}),{code:c}=yield this.context.rtcSignaling(n,es,!0,a);return c}))}cancelRoomPK(e){return v(this,void 0,void 0,(function*(){const{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,inviteInfo:s,roomId:o}=e,n=this.codec.encode(ns.RtcCancelInviteInput,{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,inviteInfo:s}),{code:a}=yield this.context.rtcSignaling(o,ts,!0,n);return a}))}responseRoomPK(e){return v(this,void 0,void 0,(function*(){const{inviteUserId:t,inviteRoomId:r,inviteSessionId:i,content:s,key:o,value:n,agree:a,roomId:c}=e,d=this.codec.encode(ns.RtcInviteAnswerInput,{inviteUserId:t,inviteRoomId:r,inviteSessionId:i,content:s,key:o,value:n,answerCode:a?1:0}),{code:_}=yield this.context.rtcSignaling(c,rs,!0,d);return _}))}endRoomPK(e){return v(this,void 0,void 0,(function*(){const{endRoomId:t,sessionId:r,content:i,keys:s,roomId:o}=e,n=this.codec.encode(ns.RtcEndInviteInput,{inviteRoomId:t,inviteSessionId:r,inviteContent:i,inviteRoomKeys:s}),{code:a}=yield this.context.rtcSignaling(o,is,!0,n);return a}))}getRTCJoinedUserInfo(e){return v(this,void 0,void 0,(function*(){const t=this.codec.encode(ns.RtcQueryUserJoinedInput,{userId:e}),{code:r,buffer:i}=yield this.context.rtcSignaling("",ss,!0,t);if(r!==a.SUCCESS||!i)return{code:r};return{code:r,data:(this.codec.decode(ns.RtcQueryUserJoinedOutput,i).info||[]).map((e=>({deviceId:e.deviceId,roomId:e.roomId,joinTime:Kt(e.joinTime)})))}}))}pullRTCRoomEntry(e){return v(this,void 0,void 0,(function*(){const t=this.codec.encode(ns.RtcPullKV,{timestamp:0,roomId:e}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,Zi,!0,t);if(r!==a.SUCCESS)return{code:r};const s=this.codec.decode(ns.RtcKVOutput,i);let{entries:o,syncTime:n}=s;return o=(o||[]).map((e=>Object.assign(Object.assign({},e),{timestamp:Kt(e.timestamp)}))),{code:r,data:{kvEntries:o,syncTime:Kt(n)}}}))}decodeRtcNotify(e){const{time:t,type:r,roomId:i}=this.codec.decode(ns.RtcNotifyMsg,e);return{time:Kt(t),type:r,roomId:i}}getCurrentId(){return this.context.getCurrentId()}getNaviInfo(){return this.context.getNaviInfo()}getConnectionStatus(){return this.context.getConnectionStatus()}getAppkey(){return this.context.getAppkey()}rtcPing(e,t,r){return this.context.rtcPing(e,t,r)}sendMessage(e,t,r){return this.context.sendMessage(e,t,r)}registerRTCSignalListener(e){this.context.registerRTCSignalListener(e)}registerConnectionStateChangeListener(e){this.context.onconnectionstatechange=e}registerDisconnectListener(e){this.context.ondisconnect=e}registerDestroyListener(e){this.context.ondestroy=e}registerMessageListener(e){this.context.onmessage=e}getCoreVersion(){return this.context.getCoreVersion()}getPluginContext(){return this.context}reportSDKInfo(e){const t=this.codec.encode(ns.RtcReportSDKInput,{sdkInfo:JSON.stringify(e)});this.context.rtcSignaling("",os,!0,t)}}const ls={tag:"RCRTC",verify:e=>"browser"!==e.tag?(O.error(`RCRTC Plugin is not support the runtime '${e.tag}'`),!1):Et?(f.add("plugin-rtc","5.5.3"),!!f.validEngine("^5.5.5-beem")||(O.error(`The current engine version '${f.getInfo().engine}' error, plugin-rtc required engine version at least '^5.5.5-beem'.`),!1)):(O.error("Please use the https protocol or use `http://localhost` to open the page!"),!1),setup(e,t,i={}){var o,n,a,c,d,_,u,l;return r.init({localLogLevel:i.logLevel,customLogPrint:i.logStdout}),r.warn(A.L_INDEX_INSTALL_RTC_PLUGIN_O,{"RCRTC Version":"5.5.3",Commit:"07c9cc6a285a9f5cd59a94126514dc54495a17c2","browserInfo.browser":Mt.browser,"browserInfo.supportsUnifiedPlan":Mt.supportsUnifiedPlan,"browserInfo.version":Mt.version}),O.setLogLevel(i.logLevel),O.setLogStdout(i.logStdout),O.warn("RCRTC Version: 5.5.3, Commit: 07c9cc6a285a9f5cd59a94126514dc54495a17c2"),O.warn(`browserInfo.browser -> ${Mt.browser}`),O.warn(`browserInfo.supportsUnifiedPlan -> ${Mt.supportsUnifiedPlan}`),O.warn(`browserInfo.version -> ${Mt.version}`),S("options.mediaServer",i.mediaServer,(e=>!(!C(e)||"https:"===location.protocol&&!/^https/.test(e)))),S("options.timeout",i.timeout,(e=>s(e)&&e>=5e3&&e<=3e4)),S("options.pingGap",i.pingGap,(e=>s(e)&&e>=3e3&&e<=1e4)),(null==i?void 0:i.audio)&&((null===(o=i.audio)||void 0===o?void 0:o.workletModule)&&(st.workletModule=null===(n=i.audio)||void 0===n?void 0:n.workletModule),(null===(a=i.audio)||void 0===a?void 0:a.workletWasm)&&(st.workletWasm=null===(c=i.audio)||void 0===c?void 0:c.workletWasm),(null===(d=i.audio)||void 0===d?void 0:d.workletModule)&&(null===(_=i.audio)||void 0===_?void 0:_.workletWasm)&&(st.isOpen=!0),void 0!==(null===(u=i.audio)||void 0===u?void 0:u.isOpen)&&(st.isOpen=null===(l=i.audio)||void 0===l?void 0:l.isOpen)),new wi(new us(e,e.createCodec(as,cs)),t,i)}},hs={DEFAULT:"RongCloudRTC"},Rs={transResolution:kt,transFrameRate:Pt,parseTrackId:Lt,ifSupportLocalFileTrack:xt,ifSupportScreenShare:wt};export{li as BackgroundPictureFillMode,hi as MixLayoutMode,Ri as MixVideoRenderMode,_i as RCAbstractRoom,ki as RCAudienceClient,Mi as RCAudienceLivingRoom,Xe as RCAudioBitrate,lt as RCCameraVideoTrack,Ke as RCFrameRate,Ui as RCInnerCDNPullIsHttps,yi as RCInnerCDNPullKind,Lr as RCKickReason,Ai as RCLivingRoom,Ti as RCLivingType,nt as RCLocalAudioTrack,_t as RCLocalFileAudioTrack,ct as RCLocalFileTrack,dt as RCLocalFileVideoTrack,ot as RCLocalTrack,at as RCLocalVideoTrack,Si as RCMCUConfigBuilder,xi as RCMediaStreamCapture,He as RCMediaType,ut as RCMicphoneAudioTrack,wi as RCRTCClient,L as RCRTCCode,mr as RCRTCLiveRole,Ht as RCRTCPingResult,Di as RCRTCRoom,pt as RCRemoteAudioTrack,mt as RCRemoteTrack,St as RCRemoteVideoTrack,je as RCResolution,Rt as RCScreenAudioTrack,ht as RCScreenVideoTrack,hs as RCTag,et as RCTrack,rt as RCVideoBitrate,Er as RTCJoinType,ze as device,Rs as helper,ls as installer};
|