@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.umd.js
CHANGED
|
@@ -12,4 +12,4 @@
|
|
|
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 r(e,t,r,o){return new(r||(r=Promise))((function(i,s){function n(e){try{c(o.next(e))}catch(e){s(e)}}function a(e){try{c(o.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,a)}c((o=o.apply(e,t||[])).next())}))}const o=new t.Logger("RCRTC");var i,s,n;e.RCRTCCode=void 0,(i=e.RCRTCCode||(e.RCRTCCode={}))[i.SUCCESS=1e4]="SUCCESS",i[i.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",i[i.PARAMS_ERROR=50001]="PARAMS_ERROR",i[i.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",i[i.NOT_IN_ROOM=50003]="NOT_IN_ROOM",i[i.SERVICE_INVALID=50004]="SERVICE_INVALID",i[i.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",i[i.SIGNAL_ERROR=53001]="SIGNAL_ERROR",i[i.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",i[i.REQUEST_FAILED=53004]="REQUEST_FAILED",i[i.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",i[i.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",i[i.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",i[i.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",i[i.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",i[i.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",i[i.BROWSER_PERMISSION_DENIED=53012]="BROWSER_PERMISSION_DENIED",i[i.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",i[i.INVALID_TAGS=53014]="INVALID_TAGS",i[i.INVALID_USER_ID=53015]="INVALID_USER_ID",i[i.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",i[i.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",i[i.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",i[i.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",i[i.TRACK_NOT_READY=53020]="TRACK_NOT_READY",i[i.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",i[i.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",i[i.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",i[i.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",i[i.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",i[i.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",i[i.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",i[i.SIGNAL_JOIN_RTC_ROOM_REFUSED=53028]="SIGNAL_JOIN_RTC_ROOM_REFUSED",i[i.NO_PERMISSION_TO_USE_REQUESTED_DEVICE=53029]="NO_PERMISSION_TO_USE_REQUESTED_DEVICE",i[i.THE_FUNCTION_IS_DISABLED_IN_PKROOM=53030]="THE_FUNCTION_IS_DISABLED_IN_PKROOM",i[i.SOME_TRACKS_PUBLISH_FAILED=53031]="SOME_TRACKS_PUBLISH_FAILED",i[i.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO=53032]="MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO",i[i.JWT_TIME_OUT=1004]="JWT_TIME_OUT",i[i.SYSTEM_PERMISSION_DENIED=53033]="SYSTEM_PERMISSION_DENIED",i[i.PUBLISH_TRACKS_IS_INVALID=53034]="PUBLISH_TRACKS_IS_INVALID",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"}(s||(s={})),function(e){e.FAILED="fail",e.SUCCESSED="success",e.TIMEOUT="timeout",e.INFO="info"}(n||(n={}));let a=!0,c=!0;function d(e,t,r){const o=e.match(t);return o&&o.length>=r&&parseInt(o[r],10)}function u(e,t,r){if(!e.RTCPeerConnection)return;const o=e.RTCPeerConnection.prototype,i=o.addEventListener;o.addEventListener=function(e,o){if(e!==t)return i.apply(this,arguments);const s=e=>{const t=r(e);t&&(o.handleEvent?o.handleEvent(t):o(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(o,s),i.apply(this,[e,s])};const s=o.removeEventListener;o.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const o=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,s.apply(this,[e,o])},Object.defineProperty(o,"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 _(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(a=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function l(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(c=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function R(){if("object"==typeof window){if(a)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function C(e,t){c&&console.warn(e+" is deprecated, please use "+t+" instead.")}function h(e){return"[object Object]"===Object.prototype.toString.call(e)}function g(e){return h(e)?Object.keys(e).reduce((function(t,r){const o=h(e[r]),i=o?g(e[r]):e[r],s=o&&!Object.keys(i).length;return void 0===i||s?t:Object.assign(t,{[r]:i})}),{}):e}function p(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((o=>{o.endsWith("Id")?p(e,e.get(t[o]),r):o.endsWith("Ids")&&t[o].forEach((t=>{p(e,e.get(t),r)}))})))}function S(e,t,r){const o=r?"outbound-rtp":"inbound-rtp",i=new Map;if(null===t)return i;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===o&&r.trackId===t.id&&p(e,r,i)}))})),i}const m=R;function T(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const o=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 o="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==o.exact&&"number"==typeof o.exact&&(o.min=o.max=o.exact);const i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==o.ideal){t.optional=t.optional||[];let e={};"number"==typeof o.ideal?(e[i("min",r)]=o.ideal,t.optional.push(e),e={},e[i("max",r)]=o.ideal,t.optional.push(e)):(e[i("",r)]=o.ideal,t.optional.push(e))}void 0!==o.exact&&"number"!=typeof o.exact?(t.mandatory=t.mandatory||{},t.mandatory[i("",r)]=o.exact):["min","max"].forEach((e=>{void 0!==o[e]&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,r)]=o[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(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=o(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const n=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||n)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return 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=s.exact?{exact:n.deviceId}:{ideal:n.deviceId}),e.video=o(e.video),m("chrome: "+JSON.stringify(e)),i(e)}))}e.video=o(e.video)}return m("chrome: "+JSON.stringify(e)),i(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,o){i(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{o&&o(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return i(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function I(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function E(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 o;o=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const i=new Event("track");i.track=r.track,i.receiver=o,i.transceiver={receiver:o},i.streams=[t.stream],this.dispatchEvent(i)})),t.stream.getTracks().forEach((r=>{let o;o=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const i=new Event("track");i.track=r,i.receiver=o,i.transceiver={receiver:o},i.streams=[t.stream],this.dispatchEvent(i)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else u(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function f(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,o){let i=r.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};const o=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){o.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 o=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],o.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 L(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,o]=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 i=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},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const o=function(e){r(s(i(e)))};return t.apply(this,[o,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(s(i(t)))},r])})).then(r,o)}}function v(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=>S(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}),u(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>S(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,o;return this.getSenders().forEach((r=>{r.track===e&&(t?o=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?o=!0:r=t),t.track===e))),o||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 O(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 o=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(o)&&this._shimmedLocalStreams[r.id].push(o):this._shimmedLocalStreams[r.id]=[r,o],o};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 o=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(o)};const o=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],o.apply(this,arguments)};const i=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]})),i.apply(this,arguments)}}function A(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return O(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 o=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}o.apply(this,[t])};const i=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const o=e._reverseStreams[t],i=e._streams[o.id];r=r.replace(new RegExp(i.id,"g"),o.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function n(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const o=e._reverseStreams[t],i=e._streams[o.id];r=r.replace(new RegExp(o.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.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 o=[].slice.call(arguments,1);if(1!==o.length||!o[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 i=this.getSenders().find((e=>e.track===t));if(i)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[r.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const o=new e.MediaStream([t]);this._streams[r.id]=o,this._reverseStreams[o.id]=r,this.addStream(o)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],o={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=o[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:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((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 D(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],o={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=o[t]}))}function N(e,t){u(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var b=Object.freeze({__proto__:null,shimMediaStream:I,shimOnTrack:E,shimGetSendersWithDtmf:f,shimGetStats:L,shimSenderReceiverGetStats:v,shimAddTrackRemoveTrackWithNative:O,shimAddTrackRemoveTrack:A,shimPeerConnection:D,fixNegotiationNeeded:N,shimGetUserMedia:T,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 o=r.video&&r.video.width,i=r.video&&r.video.height,s=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},o&&(r.video.mandatory.maxWidth=o),i&&(r.video.mandatory.maxHeight=i),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});var y=function(e){var t={exports:{}};return e(t,t.exports),t.exports}((function(e){var t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},t.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},t.getDescription=function(e){var 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]},o=8;o<t.length;o+=2)switch(t[o]){case"raddr":r.relatedAddress=t[o+1];break;case"rport":r.relatedPort=parseInt(t[o+1],10);break;case"tcptype":r.tcpType=t[o+1];break;case"ufrag":r.ufrag=t[o+1],r.usernameFragment=t[o+1];break;default:r[t[o]]=t[o+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={},o=e.substr(e.indexOf(" ")+1).split(";"),i=0;i<o.length;i++)r[(t=o[i].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 o=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?o.push(t+"="+e.parameters[t]):o.push(t)})),t+="a=fmtp:"+r+" "+o.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)},o=e.indexOf(":",t);return o>-1?(r.attribute=e.substr(t+1,o-t-1),r.value=e.substr(o+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 o=t.matchPrefix(e+r,"a=ice-ufrag:")[0],i=t.matchPrefix(e+r,"a=ice-pwd:")[0];return o&&i?{usernameFragment:o.substr(12),password:i.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:[]},o=t.splitLines(e)[0].split(" "),i=3;i<o.length;i++){var s=o[i],n=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(n){var a=t.parseRtpMap(n),c=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(a.parameters=c.length?t.parseFmtp(c[0]):{},a.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),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 o="";o+="m="+e+" ",o+=r.codecs.length>0?"9":"0",o+=" UDP/TLS/RTP/SAVPF ",o+=r.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",o+="c=IN IP4 0.0.0.0\r\n",o+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((function(e){o+=t.writeRtpMap(e),o+=t.writeFmtp(e),o+=t.writeRtcpFb(e)}));var i=0;return r.codecs.forEach((function(e){e.maxptime>i&&(i=e.maxptime)})),i>0&&(o+="a=maxptime:"+i+"\r\n"),o+="a=rtcp-mux\r\n",r.headerExtensions&&r.headerExtensions.forEach((function(e){o+=t.writeExtmap(e)})),o},t.parseRtpEncodingParameters=function(e){var r,o=[],i=t.parseRtpParameters(e),s=-1!==i.fecMechanisms.indexOf("RED"),n=-1!==i.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]),i.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}),o.push(t),s&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:n?"red+ulpfec":"red"},o.push(t))}})),0===o.length&&c&&o.push({ssrc:c});var u=t.matchPrefix(e,"b=");return u.length&&(u=0===u[0].indexOf("b=TIAS:")?parseInt(u[0].substr(7),10):0===u[0].indexOf("b=AS:")?1e3*parseInt(u[0].substr(5),10)*.95-16e3:void 0,o.forEach((function(e){e.maxBitrate=u}))),o},t.parseRtcpParameters=function(e){var r={},o=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];o&&(r.cname=o.value,r.ssrc=o.ssrc);var i=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=i.length>0,r.compound=0===i.length;var s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.parseMsid=function(e){var r,o=t.matchPrefix(e,"a=msid:");if(1===o.length)return{stream:(r=o[0].substr(7).split(" "))[0],track:r[1]};var i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return i.length>0?{stream:(r=i[0].value.split(" "))[0],track:r[1]}:void 0},t.parseSctpDescription=function(e){var r,o=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");i.length>0&&(r=parseInt(i[0].substr(19),10)),isNaN(r)&&(r=65536);var s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substr(12),10),protocol:o.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,o){var i=void 0!==r?r:2;return"v=0\r\no="+(o||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+i+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,r,o,i){var s=t.writeRtpDescription(e.kind,r);if(s+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===o?"actpass":"active"),s+="a=mid:"+e.mid+"\r\n",e.direction?s+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var n="msid:"+i.id+" "+e.rtpSender.track.id+"\r\n";s+="a="+n,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+n,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+n,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+t.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+t.localCName+"\r\n"),s},t.getDirection=function(e,r){for(var o=t.splitLines(e),i=0;i<o.length;i++)switch(o[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return o[i].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),o=0;o<r.length;o++)if(r[o].length<2||"="!==r[o].charAt(1))return!1;return!0},e.exports=t}));function k(e,t,r,o,i){var s=y.writeRtpDescription(e.kind,t);if(s+=y.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=y.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":i||"active"),s+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var n=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=n;var a="msid:"+(o?o.id:"-")+" "+n+"\r\n";s+="a="+a,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+y.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+y.localCName+"\r\n"),s}function U(e,t){var r={codecs:[],headerExtensions:[],fecMechanisms:[]},o=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]},i=function(e,t,r,i){var s=o(e.parameters.apt,r),n=o(t.parameters.apt,i);return s&&n&&s.name.toLowerCase()===n.name.toLowerCase()};return e.codecs.forEach((function(o){for(var s=0;s<t.codecs.length;s++){var n=t.codecs[s];if(o.name.toLowerCase()===n.name.toLowerCase()&&o.clockRate===n.clockRate){if("rtx"===o.name.toLowerCase()&&o.parameters&&n.parameters.apt&&!i(o,n,e.codecs,t.codecs))continue;(n=JSON.parse(JSON.stringify(n))).numChannels=Math.min(o.numChannels,n.numChannels),r.codecs.push(n),n.rtcpFeedback=n.rtcpFeedback.filter((function(e){for(var t=0;t<o.rtcpFeedback.length;t++)if(o.rtcpFeedback[t].type===e.type&&o.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var o=0;o<t.headerExtensions.length;o++){var i=t.headerExtensions[o];if(e.uri===i.uri){r.headerExtensions.push(i);break}}})),r}function P(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 M(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 x(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 w=function(e,t){function r(t,r){r.addTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function o(t,r,o,i){var s=new Event("track");s.track=r,s.receiver=o,s.transceiver={receiver:o},s.streams=i,e.setTimeout((function(){t._dispatchEvent("track",s)}))}var i=function(r){var o=this,i=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){o[e]=i[e].bind(i)})),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 x("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 o=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var i="string"==typeof o;return i&&(o=[o]),o=o.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=i?o[0]:o,!!o.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var s=r.iceCandidatePoolSize;s>0;s--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=y.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(i.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(i.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),i.prototype.onicecandidate=null,i.prototype.onaddstream=null,i.prototype.ontrack=null,i.prototype.onremovestream=null,i.prototype.onsignalingstatechange=null,i.prototype.oniceconnectionstatechange=null,i.prototype.onconnectionstatechange=null,i.prototype.onicegatheringstatechange=null,i.prototype.onnegotiationneeded=null,i.prototype.ondatachannel=null,i.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},i.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},i.prototype.getConfiguration=function(){return this._config},i.prototype.getLocalStreams=function(){return this.localStreams},i.prototype.getRemoteStreams=function(){return this.remoteStreams},i.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,o={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)o.iceTransport=this.transceivers[0].iceTransport,o.dtlsTransport=this.transceivers[0].dtlsTransport;else{var i=this._createIceAndDtlsTransports();o.iceTransport=i.iceTransport,o.dtlsTransport=i.dtlsTransport}return t||this.transceivers.push(o),o},i.prototype.addTrack=function(t,r){if(this._isClosed)throw x("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var o;if(this.transceivers.find((function(e){return e.track===t})))throw x("InvalidAccessError","Track already exists.");for(var i=0;i<this.transceivers.length;i++)this.transceivers[i].track||this.transceivers[i].kind!==t.kind||(o=this.transceivers[i]);return o||(o=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),o.track=t,o.stream=r,o.rtpSender=new e.RTCRtpSender(t,o.dtlsTransport),o.rtpSender},i.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var o=e.clone();e.getTracks().forEach((function(e,t){var r=o.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),o.getTracks().forEach((function(e){r.addTrack(e,o)}))}},i.prototype.removeTrack=function(t){if(this._isClosed)throw x("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 x("InvalidAccessError","Sender was not created by this connection.");var o=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(o)&&this.localStreams.indexOf(o)>-1&&this.localStreams.splice(this.localStreams.indexOf(o),1),this._maybeFireNegotiationNeeded()},i.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)}))},i.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},i.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},i.prototype._createIceGatherer=function(t,r){var o=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var i=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(i,"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;i.state=r?"completed":"gathering",null!==o.transceivers[t].bufferedCandidateEvents&&o.transceivers[t].bufferedCandidateEvents.push(e)},i.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),i},i.prototype._gather=function(t,r){var o=this,i=this.transceivers[r].iceGatherer;if(!i.onlocalcandidate){var s=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,i.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),i.onlocalcandidate=function(e){if(!(o.usingBundle&&r>0)){var s=new Event("icecandidate");s.candidate={sdpMid:t,sdpMLineIndex:r};var n=e.candidate,a=!n||0===Object.keys(n).length;if(a)"new"!==i.state&&"gathering"!==i.state||(i.state="completed");else{"new"===i.state&&(i.state="gathering"),n.component=1,n.ufrag=i.getLocalParameters().usernameFragment;var c=y.writeCandidate(n);s.candidate=Object.assign(s.candidate,y.parseCandidate(c)),s.candidate.candidate=c,s.candidate.toJSON=function(){return{candidate:s.candidate.candidate,sdpMid:s.candidate.sdpMid,sdpMLineIndex:s.candidate.sdpMLineIndex,usernameFragment:s.candidate.usernameFragment}}}var d=y.getMediaSections(o._localDescription.sdp);d[s.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",o._localDescription.sdp=y.getDescription(o._localDescription.sdp)+d.join("");var u=o.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==o.iceGatheringState&&(o.iceGatheringState="gathering",o._emitGatheringStateChange()),a||o._dispatchEvent("icecandidate",s),u&&(o._dispatchEvent("icecandidate",new Event("icecandidate")),o.iceGatheringState="complete",o._emitGatheringStateChange())}},e.setTimeout((function(){s.forEach((function(e){i.onlocalcandidate(e)}))}),0)}},i.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var o=new e.RTCDtlsTransport(r);return o.ondtlsstatechange=function(){t._updateConnectionState()},o.onerror=function(){Object.defineProperty(o,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:o}},i.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 o=this.transceivers[e].dtlsTransport;o&&(delete o.ondtlsstatechange,delete o.onerror,delete this.transceivers[e].dtlsTransport)},i.prototype._transceive=function(e,r,o){var i=U(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(i.encodings=e.sendEncodingParameters,i.rtcp={cname:y.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(i.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(i)),o&&e.rtpReceiver&&i.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?i.encodings=e.recvEncodingParameters:i.encodings=[{}],i.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(i.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(i.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(i))},i.prototype.setLocalDescription=function(e){var t,r,o=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(x("TypeError",'Unsupported type "'+e.type+'"'));if(!P("setLocalDescription",e.type,o.signalingState)||o._isClosed)return Promise.reject(x("InvalidStateError","Can not set local "+e.type+" in state "+o.signalingState));if("offer"===e.type)t=y.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=y.parseRtpParameters(e);o.transceivers[t].localCapabilities=r})),o.transceivers.forEach((function(e,t){o._gather(e.mid,t)}));else if("answer"===e.type){t=y.splitSections(o._remoteDescription.sdp),r=t.shift();var i=y.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var s=o.transceivers[t],n=s.iceGatherer,a=s.iceTransport,c=s.dtlsTransport,d=s.localCapabilities,u=s.remoteCapabilities;if(!(y.isRejected(e)&&0===y.matchPrefix(e,"a=bundle-only").length)&&!s.rejected){var _=y.getIceParameters(e,r),l=y.getDtlsParameters(e,r);i&&(l.role="server"),o.usingBundle&&0!==t||(o._gather(s.mid,t),"new"===a.state&&a.start(n,_,i?"controlling":"controlled"),"new"===c.state&&c.start(l));var R=U(d,u);o._transceive(s,R.codecs.length>0,!1)}}))}return o._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?o._updateSignalingState("have-local-offer"):o._updateSignalingState("stable"),Promise.resolve()},i.prototype.setRemoteDescription=function(i){var s=this;if(-1===["offer","answer"].indexOf(i.type))return Promise.reject(x("TypeError",'Unsupported type "'+i.type+'"'));if(!P("setRemoteDescription",i.type,s.signalingState)||s._isClosed)return Promise.reject(x("InvalidStateError","Can not set remote "+i.type+" in state "+s.signalingState));var n={};s.remoteStreams.forEach((function(e){n[e.id]=e}));var a=[],c=y.splitSections(i.sdp),d=c.shift(),u=y.matchPrefix(d,"a=ice-lite").length>0,_=y.matchPrefix(d,"a=group:BUNDLE ").length>0;s.usingBundle=_;var l=y.matchPrefix(d,"a=ice-options:")[0];return s.canTrickleIceCandidates=!!l&&l.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(o,c){var l=y.splitLines(o),R=y.getKind(o),C=y.isRejected(o)&&0===y.matchPrefix(o,"a=bundle-only").length,h=l[0].substr(2).split(" ")[2],g=y.getDirection(o,d),p=y.parseMsid(o),S=y.getMid(o)||y.generateIdentifier();if(C||"application"===R&&("DTLS/SCTP"===h||"UDP/DTLS/SCTP"===h))s.transceivers[c]={mid:S,kind:R,protocol:h,rejected:!0};else{var m,T,I,E,f,L,v,O,A;!C&&s.transceivers[c]&&s.transceivers[c].rejected&&(s.transceivers[c]=s._createTransceiver(R,!0));var D,N,b=y.parseRtpParameters(o);C||(D=y.getIceParameters(o,d),(N=y.getDtlsParameters(o,d)).role="client"),v=y.parseRtpEncodingParameters(o);var k=y.parseRtcpParameters(o),P=y.matchPrefix(o,"a=end-of-candidates",d).length>0,x=y.matchPrefix(o,"a=candidate:").map((function(e){return y.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===i.type||"answer"===i.type)&&!C&&_&&c>0&&s.transceivers[c]&&(s._disposeIceAndDtlsTransports(c),s.transceivers[c].iceGatherer=s.transceivers[0].iceGatherer,s.transceivers[c].iceTransport=s.transceivers[0].iceTransport,s.transceivers[c].dtlsTransport=s.transceivers[0].dtlsTransport,s.transceivers[c].rtpSender&&s.transceivers[c].rtpSender.setTransport(s.transceivers[0].dtlsTransport),s.transceivers[c].rtpReceiver&&s.transceivers[c].rtpReceiver.setTransport(s.transceivers[0].dtlsTransport)),"offer"!==i.type||C){if("answer"===i.type&&!C){T=(m=s.transceivers[c]).iceGatherer,I=m.iceTransport,E=m.dtlsTransport,f=m.rtpReceiver,L=m.sendEncodingParameters,O=m.localCapabilities,s.transceivers[c].recvEncodingParameters=v,s.transceivers[c].remoteCapabilities=b,s.transceivers[c].rtcpParameters=k,x.length&&"new"===I.state&&(!u&&!P||_&&0!==c?x.forEach((function(e){M(m.iceTransport,e)})):I.setRemoteCandidates(x)),_&&0!==c||("new"===I.state&&I.start(T,D,"controlling"),"new"===E.state&&E.start(N)),!U(m.localCapabilities,m.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&m.sendEncodingParameters[0].rtx&&delete m.sendEncodingParameters[0].rtx,s._transceive(m,"sendrecv"===g||"recvonly"===g,"sendrecv"===g||"sendonly"===g),!f||"sendrecv"!==g&&"sendonly"!==g?delete m.rtpReceiver:(A=f.track,p?(n[p.stream]||(n[p.stream]=new e.MediaStream),r(A,n[p.stream]),a.push([A,f,n[p.stream]])):(n.default||(n.default=new e.MediaStream),r(A,n.default),a.push([A,f,n.default])))}}else{(m=s.transceivers[c]||s._createTransceiver(R)).mid=S,m.iceGatherer||(m.iceGatherer=s._createIceGatherer(c,_)),x.length&&"new"===m.iceTransport.state&&(!P||_&&0!==c?x.forEach((function(e){M(m.iceTransport,e)})):m.iceTransport.setRemoteCandidates(x)),O=e.RTCRtpReceiver.getCapabilities(R),t<15019&&(O.codecs=O.codecs.filter((function(e){return"rtx"!==e.name}))),L=m.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var w,B=!1;if("sendrecv"===g||"sendonly"===g){if(B=!m.rtpReceiver,f=m.rtpReceiver||new e.RTCRtpReceiver(m.dtlsTransport,R),B)A=f.track,p&&"-"===p.stream||(p?(n[p.stream]||(n[p.stream]=new e.MediaStream,Object.defineProperty(n[p.stream],"id",{get:function(){return p.stream}})),Object.defineProperty(A,"id",{get:function(){return p.track}}),w=n[p.stream]):(n.default||(n.default=new e.MediaStream),w=n.default)),w&&(r(A,w),m.associatedRemoteMediaStreams.push(w)),a.push([A,f,w])}else m.rtpReceiver&&m.rtpReceiver.track&&(m.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===m.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),m.associatedRemoteMediaStreams=[]);m.localCapabilities=O,m.remoteCapabilities=b,m.rtpReceiver=f,m.rtcpParameters=k,m.sendEncodingParameters=L,m.recvEncodingParameters=v,s._transceive(s.transceivers[c],!1,B)}}})),void 0===s._dtlsRole&&(s._dtlsRole="offer"===i.type?"active":"passive"),s._remoteDescription={type:i.type,sdp:i.sdp},"offer"===i.type?s._updateSignalingState("have-remote-offer"):s._updateSignalingState("stable"),Object.keys(n).forEach((function(t){var r=n[t];if(r.getTracks().length){if(-1===s.remoteStreams.indexOf(r)){s.remoteStreams.push(r);var i=new Event("addstream");i.stream=r,e.setTimeout((function(){s._dispatchEvent("addstream",i)}))}a.forEach((function(e){var t=e[0],i=e[1];r.id===e[2].id&&o(s,t,i,[r])}))}})),a.forEach((function(e){e[2]||o(s,e[0],e[1],[])})),e.setTimeout((function(){s&&s.transceivers&&s.transceivers.forEach((function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},i.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")},i.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},i.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))},i.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)}},i.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)}},i.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(x("InvalidStateError","Can not call createOffer after close"));var o=r.transceivers.filter((function(e){return"audio"===e.kind})).length,i=r.transceivers.filter((function(e){return"video"===e.kind})).length,s=arguments[0];if(s){if(s.mandatory||s.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==s.offerToReceiveAudio&&(o=!0===s.offerToReceiveAudio?1:!1===s.offerToReceiveAudio?0:s.offerToReceiveAudio),void 0!==s.offerToReceiveVideo&&(i=!0===s.offerToReceiveVideo?1:!1===s.offerToReceiveVideo?0:s.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--o<0&&(e.wantReceive=!1):"video"===e.kind&&--i<0&&(e.wantReceive=!1)}));o>0||i>0;)o>0&&(r._createTransceiver("audio"),o--),i>0&&(r._createTransceiver("video"),i--);var n=y.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(o,i){var s=o.track,n=o.kind,a=o.mid||y.generateIdentifier();o.mid=a,o.iceGatherer||(o.iceGatherer=r._createIceGatherer(i,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"),o.remoteCapabilities&&o.remoteCapabilities.codecs&&o.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(o.remoteCapabilities&&o.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=o.sendEncodingParameters||[{ssrc:1001*(2*i+1)}];s&&t>=15019&&"video"===n&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),o.wantReceive&&(o.rtpReceiver=new e.RTCRtpReceiver(o.dtlsTransport,n)),o.localCapabilities=c,o.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+=k(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="+y.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)},i.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(x("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(x("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var o=y.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.usingBundle&&(o+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),o+="a=ice-options:trickle\r\n";var i=y.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,s){if(!(s+1>i)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?o+="m=application 0 DTLS/SCTP 5000\r\n":o+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?o+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(o+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(o+="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=U(e.localCapabilities,e.remoteCapabilities);!a.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,o+=k(e,a,"answer",e.stream,r._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(o+="a=rtcp-rsize\r\n")}}));var s=new e.RTCSessionDescription({type:"answer",sdp:o});return Promise.resolve(s)},i.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(o,i){if(!r._remoteDescription)return i(x("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var s=e.sdpMLineIndex;if(e.sdpMid)for(var n=0;n<r.transceivers.length;n++)if(r.transceivers[n].mid===e.sdpMid){s=n;break}var a=r.transceivers[s];if(!a)return i(x("OperationError","Can not add ICE candidate"));if(a.rejected)return o();var c=Object.keys(e.candidate).length>0?y.parseCandidate(e.candidate):{};if("tcp"===c.protocol&&(0===c.port||9===c.port))return o();if(c.component&&1!==c.component)return o();if((0===s||s>0&&a.iceTransport!==r.transceivers[0].iceTransport)&&!M(a.iceTransport,c))return i(x("OperationError","Can not add ICE candidate"));var d=e.candidate.trim();0===d.indexOf("a=")&&(d=d.substr(2)),(t=y.getMediaSections(r._remoteDescription.sdp))[s]+="a="+(c.type?d:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=y.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var u=0;u<r.transceivers.length&&(r.transceivers[u].rejected||(r.transceivers[u].iceTransport.addRemoteCandidate({}),(t=y.getMediaSections(r._remoteDescription.sdp))[u]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=y.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));u++);o()}))},i.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 x("InvalidAccessError","Invalid selector.");return r.getStats()}var o=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&o.push(e[t].getStats())}))})),Promise.all(o).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 o=r.prototype.getStats;r.prototype.getStats=function(){return o.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var o;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(o=e[r]).type]||o.type,t.set(r,e[r])})),t}))}}}));var s=["createOffer","createAnswer"];return s.forEach((function(e){var t=i.prototype[e];i.prototype[e]=function(){var e=arguments;return"function"==typeof e[0]||"function"==typeof e[1]?t.apply(this,[arguments[2]]).then((function(t){"function"==typeof e[0]&&e[0].apply(null,[t])}),(function(t){"function"==typeof e[1]&&e[1].apply(null,[t])})):t.apply(this,arguments)}})),(s=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=i.prototype[e];i.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=i.prototype[e];i.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)}})),i};function B(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 V(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,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=w(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&&C("RTCIceServer.url","RTCIceServer.urls");const o="string"==typeof t;return o&&(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=o?t[0]:t,!!t.length}}))}(e.iceServers,t.version),R("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype}function F(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var G=Object.freeze({__proto__:null,shimPeerConnection:$,shimReplaceTrack:F,shimGetUserMedia:B,shimGetDisplayMedia:V});function K(e,t){const r=e&&e.navigator,o=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,o){C("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,o)},!(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)},o&&o.prototype.getSettings){const t=o.prototype.getSettings;o.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(o&&o.prototype.applyConstraints){const t=o.prototype.applyConstraints;o.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 H(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 j(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],o={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=o[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},o=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,s]=arguments;return o.apply(this,[e||null]).then((e=>{if(t.version<53&&!i)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,o)=>{e.set(o,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(i,s)}}function J(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 q(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}),u(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function W(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){C("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Y(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Q(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 o=t.apply(this,arguments);if(r){const{sender:t}=o,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 o})}function z(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 Z(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 X(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 ee=Object.freeze({__proto__:null,shimOnTrack:H,shimPeerConnection:j,shimSenderGetStats:J,shimReceiverGetStats:q,shimRemoveStream:W,shimRTCDataChannel:Y,shimAddTransceiver:Q,shimGetParameters:z,shimCreateOffer:Z,shimCreateAnswer:X,shimGetUserMedia:K,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 te(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 re(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 oe(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,o=t.createAnswer,i=t.setLocalDescription,s=t.setRemoteDescription,n=t.addIceCandidate;t.createOffer=function(e,t){const o=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[o]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],i=o.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i};let a=function(e,t,r){const o=i.apply(this,[e]);return r?(o.then(t,r),Promise.resolve()):o};t.setLocalDescription=a,a=function(e,t,r){const o=s.apply(this,[e]);return r?(o.then(t,r),Promise.resolve()):o},t.setRemoteDescription=a,a=function(e,t,r){const o=n.apply(this,[e]);return r?(o.then(t,r),Promise.resolve()):o},t.addIceCandidate=a}function ie(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(se(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,o){t.mediaDevices.getUserMedia(e).then(r,o)}.bind(t))}function se(e){return e&&void 0!==e.video?Object.assign({},e,{video:g(e.video)}):e}function ne(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 o=e.iceServers[r];!o.hasOwnProperty("urls")&&o.hasOwnProperty("url")?(C("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,t.push(o)):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 ae(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 ce(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 de(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ue=Object.freeze({__proto__:null,shimLocalStreamsAPI:te,shimRemoteStreamsAPI:re,shimCallbacksAPI:oe,shimGetUserMedia:ie,shimConstraints:se,shimRTCIceServerUrls:ne,shimTrackEventTransceiver:ae,shimCreateOfferLegacy:ce,shimAudioContext:de});function _e(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),o=y.parseCandidate(e.candidate),i=Object.assign(r,o);return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,u(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function le(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=y.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=y.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},o=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},i=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},s=function(e,r){let o=65536;"firefox"===t.browser&&57===t.version&&(o=65535);const i=y.matchPrefix(e.sdp,"a=max-message-size:");return i.length>0?o=parseInt(i[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(o=2147483637),o},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=o(arguments[0]),t=i(e),r=s(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 Re(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const o=arguments[0],i=o.length||o.size||o.byteLength;if("open"===e.readyState&&t.sctp&&i>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},u(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Ce(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 he(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 ge(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 pe=Object.freeze({__proto__:null,shimRTCIceCandidate:_e,shimMaxMessageSize:le,shimSendThrowTypeError:Re,shimConnectionState:Ce,removeExtmapAllowMixed:he,shimAddIceCandidateNullOrEmpty:ge});const Se=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=R,o=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=d(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=d(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=d(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=d(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),i={browserDetails:o,commonShim:pe,extractVersion:d,disableLog:_,disableWarnings:l};switch(o.browser){case"chrome":if(!b||!D||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),i;if(null===o.version)return r("Chrome shim can not determine version, not shimming."),i;r("adapter.js shimming chrome."),i.browserShim=b,ge(e,o),T(e,o),I(e),D(e,o),E(e),A(e,o),f(e),L(e),v(e),N(e,o),_e(e),Ce(e),le(e,o),Re(e),he(e,o);break;case"firefox":if(!ee||!j||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=ee,ge(e,o),K(e,o),j(e,o),H(e),W(e),J(e),q(e),Y(e),Q(e),z(e),Z(e),X(e),_e(e),Ce(e),le(e,o),Re(e);break;case"edge":if(!G||!$||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),i;r("adapter.js shimming edge."),i.browserShim=G,B(e),V(e),$(e,o),F(e),le(e,o),Re(e);break;case"safari":if(!ue||!t.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=ue,ge(e,o),ne(e),ce(e),oe(e),te(e),re(e),ae(e),ie(e),de(e),_e(e),le(e,o),Re(e),he(e,o);break;default:r("Unsupported browser!")}return i}({window:"undefined"==typeof window?void 0:window});var me,Te,Ie;e.RCFrameRate=void 0,(me=e.RCFrameRate||(e.RCFrameRate={})).FPS_10="FPS_10",me.FPS_15="FPS_15",me.FPS_24="FPS_24",me.FPS_30="FPS_30",e.RCResolution=void 0,(Te=e.RCResolution||(e.RCResolution={})).W176_H132="W176_H132",Te.W176_H144="W176_H144",Te.W180_H180="W180_H180",Te.W240_H180="W240_H180",Te.W240_H240="W240_H240",Te.W256_H144="W256_H144",Te.W320_H180="W320_H180",Te.W320_H240="W320_H240",Te.W360_H360="W360_H360",Te.W480_H360="W480_H360",Te.W480_H480="W480_H480",Te.W640_H360="W640_H360",Te.W640_H480="W640_H480",Te.W720_H480="W720_H480",Te.W848_H480="W848_H480",Te.W960_H720="W960_H720",Te.W1280_H720="W1280_H720",Te.W1920_H1080="W1920_H1080",e.RCMediaType=void 0,(Ie=e.RCMediaType||(e.RCMediaType={}))[Ie.AUDIO_ONLY=0]="AUDIO_ONLY",Ie[Ie.VIDEO_ONLY=1]="VIDEO_ONLY",Ie[Ie.AUDIO_VIDEO=2]="AUDIO_VIDEO";const Ee={[e.RCResolution.W176_H132]:{width:176,height:132,maxBitrate:150,minBitrate:80},[e.RCResolution.W176_H144]:{width:176,height:144,maxBitrate:150,minBitrate:80},[e.RCResolution.W180_H180]:{width:180,height:180,maxBitrate:200,minBitrate:100},[e.RCResolution.W240_H180]:{width:240,height:180,maxBitrate:240,minBitrate:120},[e.RCResolution.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[e.RCResolution.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[e.RCResolution.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[e.RCResolution.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[e.RCResolution.W360_H360]:{width:360,height:360,maxBitrate:520,minBitrate:140},[e.RCResolution.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[e.RCResolution.W480_H480]:{width:480,height:480,maxBitrate:800,minBitrate:180},[e.RCResolution.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[e.RCResolution.W640_H480]:{width:640,height:480,maxBitrate:900,minBitrate:200},[e.RCResolution.W720_H480]:{width:720,height:480,maxBitrate:1e3,minBitrate:200},[e.RCResolution.W848_H480]:{width:848,height:480,maxBitrate:1860,minBitrate:200},[e.RCResolution.W960_H720]:{width:960,height:720,maxBitrate:2e3,minBitrate:250},[e.RCResolution.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[e.RCResolution.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},fe=e=>{const t={192:180,368:360,1088:1080};return t[e]?t[e]:e},Le=(e,t)=>{e=fe(e),t=fe(t);const r=Ee[`W${e}_H${t}`];if(r)return r;const o=e*t;return Object.keys(Ee).map((e=>Ee[e])).sort(((e,t)=>e.height*e.width-t.width*t.height)).filter((e=>e.height*e.width>=o))[0]||Ee.W1920_H1080},ve={10:1,15:1,24:1.5,30:1.5},Oe=e=>{let t=Number.MAX_VALUE,r=1;for(const o in ve){const i=Math.abs(e-parseInt(o));i<t&&(t=i,r=ve[o])}return r},Ae={getCameras:()=>r(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))})),getMicrophones:()=>r(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))})),getSpeakers:()=>r(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audiooutput"===e.kind))}))};var De,Ne;!function(e){e.AUDIO="audio",e.VIDEO="video"}(De||(De={}));class be extends t.EventEmitter{constructor(e,t,r,o,i){super(),this._tag=e,this._userId=t,this._kind=r,this._isLocalTrack=o,this._roomId=i,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`),t.logger.info(s.L_TRACK_MUTE_O,{status:n.SUCCESSED,id:this._id},{logSource:t.LogSource.RTC}),this._setLocalMuted(!0)}unmute(){return o.info(`set ${this._id} enabled: true`),t.logger.info(s.L_TRACK_UNMUTE_O,{status:n.SUCCESSED,id:this._id},{logSource:t.LogSource.RTC}),this._setLocalMuted(!1)}isLocalMuted(){return this._localMuted}isMCUTrack(){return Boolean(this._roomId)}isOwnerMuted(){return this._remoteMuted}play(i,a){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_TRACK_PLAY_T,{element:i,options:a,msg:`start play trackId: ${this._id}`},{logSource:t.LogSource.RTC}),!this._msTrack)return o.warn(`the track is not ready to play -> id: ${this._id}`),t.logger.error(s.L_TRACK_PLAY_R,{status:n.FAILED,code:e.RCRTCCode.TRACK_NOT_READY,msg:`play error -> id: ${this._id}`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&(o.warn(`the track's readyState is 'ended' -> id: ${this._id}`),t.logger.error(s.L_TRACK_PLAY_R,{status:n.FAILED,code:"",msg:`the track's readyState is ended -> id: ${this._id}`},{logSource:t.LogSource.RTC})),null==a?void 0:a.volume){if(!t.isNumber(null==a?void 0:a.volume))return o.error(`${null==a?void 0:a.volume} is not a number, the valid range of options.volume is 0-100`),t.logger.error(s.L_TRACK_PLAY_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> options.volume不是数字"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};(null==a?void 0:a.volume)<0&&(a.volume=0,o.warn("the valid range of options.volume is 0-100, the value of volume has been set 0"),t.logger.warn(s.L_TRACK_PLAY_R,{status:n.FAILED,code:"",msg:"params error -> options.volume < 0"},{logSource:t.LogSource.RTC})),(null==a?void 0:a.volume)>100&&(a.volume=100,o.warn("the valid range of options.volume is 0-100, the value of volume has been set 100"),t.logger.warn(s.L_TRACK_PLAY_R,{status:n.FAILED,code:"",msg:"params error -> options.volume > 100"},{logSource:t.LogSource.RTC}))}if(null==a?void 0:a.audioDeviceId){if(!(yield Ae.getSpeakers()).map((e=>e.deviceId)).includes(a.audioDeviceId))return o.error(`the options.audioDeviceId is invalid --\x3e ${a.audioDeviceId}`),t.logger.error(s.L_TRACK_PLAY_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> options.audioDeviceId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR}}const c=this.isVideoTrack();return!c||i&&(i instanceof HTMLVideoElement||this.__validateVideoNodeName(i))?(this._element=c?i: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 r,i;o.debug(`HTMLMediaElement onloadstart -> id: ${null===(r=e.target)||void 0===r?void 0:r.id}, trackId: ${this._id}`),t.logger.info(s.L_TRACK_PLAY_R,{status:n.INFO,msg:`HTMLMediaElement onloadstart -> id: ${null===(i=e.target)||void 0===i?void 0:i.id}, trackId: ${this._id}`},{logSource:t.LogSource.RTC})},this._element.ondurationchange=e=>{var r,i;o.debug(`HTMLMediaElement ondurationchange -> id: ${null===(r=e.target)||void 0===r?void 0:r.id}, trackId: ${this._id}`),t.logger.info(s.L_TRACK_PLAY_R,{status:n.INFO,msg:`HTMLMediaElement ondurationchange -> id: ${null===(i=e.target)||void 0===i?void 0:i.id}, trackId: ${this._id}`},{logSource:t.LogSource.RTC})},this._element.onloadedmetadata=e=>{var r,i;o.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(r=e.target)||void 0===r?void 0:r.id}, trackId: ${this._id}`),t.logger.info(s.L_TRACK_PLAY_R,{status:n.INFO,msg:`HTMLMediaElement onloadedmetadata -> id: ${null===(i=e.target)||void 0===i?void 0:i.id}, trackId: ${this._id}`},{logSource:t.LogSource.RTC})},this._element.onloadeddata=e=>{var r,i;o.debug(`HTMLMediaElement onloadeddata -> id: ${null===(r=e.target)||void 0===r?void 0:r.id}, trackId: ${this._id}`),t.logger.info(s.L_TRACK_PLAY_R,{status:n.INFO,msg:`HTMLMediaElement onloadeddata -> id: ${null===(i=e.target)||void 0===i?void 0:i.id}, trackId: ${this._id}`},{logSource:t.LogSource.RTC})},this._element.onabort=e=>{var r,i;o.info(`HTMLMediaElement onabort -> id: ${null===(r=e.target)||void 0===r?void 0:r.id}, trackId: ${this._id}`),t.logger.info(s.L_TRACK_PLAY_R,{status:n.INFO,msg:`HTMLMediaElement onabort -> id: ${null===(i=e.target)||void 0===i?void 0:i.id}, trackId: ${this._id}`},{logSource:t.LogSource.RTC})},this._element.oncanplay=i=>r(this,void 0,void 0,(function*(){var r,d,u;o.info(`HTMLMediaElement oncanplay -> id: ${null===(r=i.target)||void 0===r?void 0:r.id}, trackId: ${this._id}`),t.logger.info(s.L_TRACK_PLAY_R,{status:n.INFO,msg:`HTMLMediaElement oncanplay -> id: ${null===(d=i.target)||void 0===d?void 0:d.id}, trackId: ${this._id}`},{logSource:t.LogSource.RTC});try{yield null===(u=this._element)||void 0===u?void 0:u.play(),(null==a?void 0:a.audioDeviceId)&&!c&&(yield this._element.setSinkId(a.audioDeviceId))}catch(r){if("No permission to use requested device"===r.message)return o.error(`setSinkId failed -> ${r.message}`),void t.logger.error(s.L_TRACK_PLAY_R,{status:n.FAILED,code:e.RCRTCCode.NO_PERMISSION_TO_USE_REQUESTED_DEVICE,msg:"No permission"},{logSource:t.LogSource.RTC});o.error(r),t.logger.error(s.L_TRACK_PLAY_R,{status:n.FAILED,code:e.RCRTCCode.TRACK_PLAY_ERROR,msg:"play error"},{logSource:t.LogSource.RTC})}})),this._element.onvolumechange=e=>{var r,i;const a=Math.floor(100*(null===(r=e.target)||void 0===r?void 0:r.volume));o.info(`HTMLMediaElement onvolumechange -> volume: ${a}, trackId: ${this._id}`),t.logger.info(s.L_TRACK_PLAY_R,{status:n.INFO,msg:`HTMLMediaElement onvolumechange -> id: ${null===(i=e.target)||void 0===i?void 0:i.id}, trackId: ${this._id}`},{logSource:t.LogSource.RTC})},this._element.srcObject=this._msStream,this._element.autoplay=!0,c&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),c||!(null==a?void 0:a.volume)&&0!==(null==a?void 0:a.volume)||(this._element.volume=(null==a?void 0:a.volume)/100),t.logger.info(s.L_TRACK_PLAY_R,{status:n.SUCCESSED,element:i,options:a},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS}):(o.error(`the video track need an <video> to play -> id: ${this._id}`),t.logger.error(s.L_TRACK_PLAY_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> element不是一个video标签"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.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()}}e.RCAudioBitrate=void 0,(Ne=e.RCAudioBitrate||(e.RCAudioBitrate={})).Speech="Speech",Ne.Music="Music",Ne.MusicHigh="MusicHigh";const ye={[e.RCAudioBitrate.Music]:{max:64,min:64},[e.RCAudioBitrate.MusicHigh]:{max:128,min:128},[e.RCAudioBitrate.Speech]:{max:32,min:32}};var ke;e.RCVideoBitrate=void 0,(ke=e.RCVideoBitrate||(e.RCVideoBitrate={})).LEVEL0="LEVEL0",ke.LEVEL1="LEVEL1",ke.LEVEL2="LEVEL2",ke.LEVEL3="LEVEL3",ke.LEVEL4="LEVEL4",ke.LEVEL5="LEVEL5";const Ue={[e.RCVideoBitrate.LEVEL0]:{max:150,min:80},[e.RCVideoBitrate.LEVEL1]:{max:280,min:120},[e.RCVideoBitrate.LEVEL2]:{max:650,min:150},[e.RCVideoBitrate.LEVEL3]:{max:1e3,min:200},[e.RCVideoBitrate.LEVEL4]:{max:2200,min:250},[e.RCVideoBitrate.LEVEL5]:{max:4e3,min:400}};class Pe{static setStatus(e=!0){Pe.isOpen=e}static setWroklet(e,t){Pe.workletModule=e,Pe.workletModule=t}static transformStreamTrack(e){var i;return r(this,void 0,void 0,(function*(){if(!Pe.isOpen)return new Promise((t=>{t({track:null==e?void 0:e.getAudioTracks()[0],stop:()=>{}})}));let r=new AudioContext({sampleRate:44100}),a=r.createMediaStreamSource(e),c=r.createMediaStreamDestination(),d=null,u=null;if(d=yield r.audioWorklet.addModule(Pe.workletModule).then((()=>(o.info(s.L_RTC_3ANOISE_NODE_O,{status:n.SUCCESSED,message:{msg:"addModule RC3AnoiseTrack.workletModule success"}},{logSource:t.LogSource.RTC}),fetch(Pe.workletWasm,{cache:"force-cache",credentials:"same-origin"}).then((e=>e.arrayBuffer())).catch((e=>{throw new Error(e.message)}))))).then((e=>(u=new AudioWorkletNode(r,"process-worklet",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{binary:e}}),u))).catch((e=>{o.info(s.L_RTC_3ANOISE_NODE_E,{status:n.FAILED,message:{msg:e.message}},{logSource:t.LogSource.RTC})})),!d)return new Promise((t=>{t({track:null==e?void 0:e.getAudioTracks()[0],stop:()=>{}})}));a.connect(d).connect(c);let _=null===(i=null==c?void 0:c.stream)||void 0===i?void 0:i.getAudioTracks()[0],l=()=>{o.info(s.L_RTC_3ANOISE_NODE_STOP_O,{status:n.SUCCESSED,message:{msg:"call stop RC3AnoiseTrack.workletModule"}},{logSource:t.LogSource.RTC}),null==d||d.port.postMessage({type:"stop",msg:""}),setTimeout((()=>{const t=null==e?void 0:e.getAudioTracks()[0];null==t||t.stop(),r.suspend(),r.close(),c.disconnect(),d.disconnect(),a.disconnect(),r=null,d=null,c=null,a=null,u=null,e=null,null==_||_.stop(),_=null,l=null}),200)};return{track:_,stop:l}}))}}Pe.workletModule="https://cdn.ronghub.com/plugin-rtc/wasm/5.0.0-alpha.2/process-worklet.js",Pe.workletWasm="https://cdn.ronghub.com/plugin-rtc/wasm/5.0.0-alpha.2/AudioProcessing.wasm",Pe.isOpen=!1;class Me extends be{constructor(e,t,r,o){super(e,t,r,!0),this._isDestroyed=!1,this._isPublished=!1,this.__innerSetMediaStreamTrack(o),o.onended=()=>{o.onended=null,this.emit(Me.EVENT_LOCAL_TRACK_END,this),this.removeAll(Me.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(e){return new Promise(((r,o)=>{const i=this._localMuted!==e;super._setLocalMuted(e),this._remoteMuted=this._localMuted,i&&this.emit(Me.__INNER_EVENT_MUTED_CHANGE__,this,r),t.logger.info(s.L_LOCAL_TRACK_SET_LOCAL_MUTED_O,{status:n.SUCCESSED,bool:e},{logSource:t.LogSource.RTC})}))}__innerSetPublished(e){t.logger.info(s.L_LOCAL_TRACK_INNER_SET_PUBLISHED_O,{status:n.SUCCESSED,bool:e},{logSource:t.LogSource.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(Me.__INNER_EVENT_DESTROY__,this),t.logger.info(s.L_LOCAL_TRACK_DESTROY_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC})}isDestroyed(){return this._isDestroyed}setBitrate(e=0,r=0,i=0){if(!t.isNumber(e)||!t.isNumber(r)||!t.isNumber(i)||e<=0||r<=0||e<r)return o.error("setBitrate params error ->"),void t.logger.error(s.L_LOCAL_TRACK_SET_BITRATE_O,{status:n.FAILED,code:"",msg:`params error -> max: ${e},min: ${r}, start: ${i}`},{logSource:t.LogSource.RTC});t.logger.info(s.L_LOCAL_TRACK_SET_BITRATE_O,{status:n.SUCCESSED,max:e,min:r,start:i},{logSource:t.LogSource.RTC}),this._bitrateInfo={max:e,min:r,start:i}}getBitrate(){var e,t,r,o,i,s,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)===De.VIDEO?({min:a,max:c}=et(this._msTrack)):(null===(t=this._msTrack)||void 0===t?void 0:t.kind)===De.AUDIO&&({min:a,max:c}={min:32,max:32}),(null===(r=this._bitrateInfo)||void 0===r?void 0:r.max)&&(d=.7*(null===(o=this._bitrateInfo)||void 0===o?void 0:o.max)),{min:(null===(i=this._bitrateInfo)||void 0===i?void 0:i.min)||a,max:(null===(s=this._bitrateInfo)||void 0===s?void 0:s.max)||c,start:(null===(n=this._bitrateInfo)||void 0===n?void 0:n.start)||d}}}Me.EVENT_LOCAL_TRACK_END="local-track-end",Me.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",Me.__INNER_EVENT_DESTROY__="inner-destroy";class xe extends Me{constructor(e,t,r){super(e,t,"audio",r),this._stopProcess=()=>{}}setRecommendBitrate(r){if(!t.validate("livingType",r,(t=>t in e.RCAudioBitrate)))return void t.logger.warn(s.L_RTC_SET_RECOMMEND_BITRATE_O,{status:n.FAILED,msg:"params error -> setRecommendBitrate Audio"},{logSource:t.LogSource.RTC});const o=ye[r];this.setBitrate(o.max,o.min,o.start||.7*o.max)}setBitrate(e,...t){const[r=1,o=.7*e||1]=t;super.setBitrate(e,r,o)}__innerSetMediaStreamTrack(e){if(e)if(Pe.isOpen){const t=new MediaStream([e]);Pe.transformStreamTrack(t).then((({track:e,stop:t})=>{super.__innerSetMediaStreamTrack(e),this._stopProcess=t}))}else super.__innerSetMediaStreamTrack(e);else super.__innerSetMediaStreamTrack(e),this._stopProcess()}}class we extends Me{constructor(e,t,r,o=!1){super(e,t,"video",r),this._isTiny=o}__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(r){if(!t.validate("livingType",r,(t=>t in e.RCVideoBitrate)))return void t.logger.warn(s.L_RTC_SET_RECOMMEND_BITRATE_O,{status:n.FAILED,msg:"params error -> setRecommendBitrate Video"},{logSource:t.LogSource.RTC});const o=Ue[r];this.setBitrate(o.max,o.min,o.start||.7*o.max)}setBitrate(e,...t){const[r=1,o=.7*e||1]=t;super.setBitrate(e,r,o)}}class Be extends Me{constructor(e,t,r,o,i){super(e,t,r,o),this._resource=i,Be.__innerSetMapping(this.getTrackId(),i)}static __innerSetMapping(e,t){const r=this._mapping.get(t)||[];r.push(e),this._mapping.set(t,r)}static __innerRemoveMapping(e,t){var r,o;const i=null===(r=this._mapping.get(t))||void 0===r?void 0:r.filter((t=>t!==e));i&&i.length>0?this._mapping.set(t,i):(this._mapping.delete(t),t.pause(),t.src="",null===(o=t.parentNode)||void 0===o||o.removeChild(t))}destroy(){this.isAudioTrack()&&this.mute(),Be.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}Be._mapping=new Map;class Ve extends Be{constructor(e,t,r,o){super(e,t,"video",r,o)}}class $e extends Be{constructor(e,t,r,o){super(e,t,"audio",r,o),this._stopProcess=()=>{}}_setLocalMuted(e){const t=Object.create(null,{_setLocalMuted:{get:()=>super._setLocalMuted}});return r(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:e.RCRTCCode.SUCCESS})}__innerSetMediaStreamTrack(e){if(e)if(Pe.isOpen){const t=new MediaStream([e]);Pe.transformStreamTrack(t).then((({track:e,stop:t})=>{super.__innerSetMediaStreamTrack(e),this._stopProcess=t}))}else super.__innerSetMediaStreamTrack(e);else super.__innerSetMediaStreamTrack(e),this._stopProcess()}}class Fe extends xe{}class Ge extends we{}class Ke extends we{}class He extends xe{}class je extends be{constructor(e,t,r,o){super(e,t,r,!1,o),this._isSubscribed=!1}__innerSetRemoteMuted(e){this._remoteMuted=e}__innerSetSubscribed(e){this._isSubscribed=e,t.logger.debug(s.L_REMOTE_TRACK_INNER_SET_SUBSCRIBED_O,{status:n.SUCCESSED,bool:e},{logSource:t.LogSource.RTC})}isSubscribed(){return this._isSubscribed}}class Je extends je{constructor(e,t,r){super(e,t,"audio",r)}}class qe extends je{constructor(e,t,r){super(e,t,"video",r),this._isSubTiny=!1}__innerSetIsTinyTrack(e){this._isSubTiny=e}isSubTiny(){return this._isSubTiny}}const We=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),Ye=e=>JSON.stringify(e),Qe=e=>/^[a-zA-Z\d-=]+$/g.test(e),ze="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),Ze=e=>{if(void 0===e)return 0;if(t.isNumber(e))return e;const r=e;return r.exact||r.ideal||r.max||0},Xe=e=>{const t=e.getSettings(),r=e.getConstraints();return{width:Ze(r.width)||t.width||0,height:Ze(r.height)||t.height||0,frameRate:t.frameRate||Ze(r.frameRate)}},et=e=>{const{width:t,height:r,frameRate:o}=Xe(e),i=Le(t||1920,r||1080),s=Oe(o);return{min:i.minBitrate*s,max:i.maxBitrate*s}},tt=e=>[e.msid,e.mediaType].join("_"),rt=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},ot=(e,t)=>[e,t].join("_"),it=e=>e.map((e=>Object.assign({},e))),st=(e,t,r=!1)=>{e=e.slice();const o=[],i=[],s=[];return t.forEach((t=>{const i=tt(t);let n=e.findIndex((e=>tt(e)===i));if(r&&(n=e.findIndex((e=>e.uri===t.uri))),-1===n)return void o.push(t);const a=e[n];a.uri!==t.uri?o.push(t):a.state!==t.state&&s.push(t),e.splice(n,1)})),i.push(...e),{publishedList:o,unpublishedList:i,modifiedList:s}},nt=()=>{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 o=+e;const i=[];do{const e=o%r;o=(o-e)/r,i.unshift(t[e])}while(o);return i.join("")})(e),e.length>22&&(e=e.slice(0,22)),e},at=e=>{if(Ee[e]){const{width:t,height:r}=Ee[e];return{width:t,height:r}}const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},ct=t=>!!e.RCResolution[t],dt=t=>!!e.RCFrameRate[t],ut=e=>parseInt(e.replace("FPS_","")),_t=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=Se.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function lt(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function Rt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const Ct=e=>"[object Null]"===Object.prototype.toString.call(e),ht=e=>1===e.type,gt=(e,t)=>{const r={},i=Object.keys(e.users);return i.length&&i.forEach((i=>{const s=[],n=e.users[i];if(n.extra){const{roomId:e}=JSON.parse(n.extra);if(t!==e)return}if(n.uris)try{s.push(...JSON.parse(n.uris))}catch(e){o.warn(`invalid user data -> userId: ${i}, userData: ${n}`)}r[i]=s})),r},pt=(t,r)=>{const o=r.filter((e=>"RC_RTC_SESSIONID"===e.key))[0],i=o?o.value:"",s=r.filter((e=>"RC_ANCHOR_LIST"===e.key)).map((e=>JSON.parse(e.value||"[]")))[0],n=r.filter((e=>e.key.includes("RC_RES_"))).map((e=>JSON.parse(e.value||"{}"))),a=n.length?JSON.parse(n[0].mcu_uris||"[]"):[],c=[];a.forEach((r=>{const{mediaType:o,tag:i}=r,s=o===e.RCMediaType.AUDIO_ONLY?new Je(i,"",t):new qe(i,"",t);c.push(s)}));const d=[],u=[];n.forEach((t=>{const r=JSON.parse(t.uris||"[]");d.push(...r),r.forEach((t=>{const{mediaType:r,tag:o,msid:i}=t,s=i.split("_")[0],n=r===e.RCMediaType.AUDIO_ONLY?new Je(o,s):new qe(o,s);u.push(n)}))}));const _=r.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:d,remoteMUCUris:a,remoteRTCTracks:u,remoteMCUTracks:c,remoteTracks:[...u,...c],CDNUris:_||{}}},St=e=>e instanceof be?e.getTrackId():e.track.getTrackId(),mt=e=>{if(!t.isObject(e)||void 0===e.low||void 0===e.high)return e;let{low:r}=e;r<0&&(r+=4294967296),r=r.toString(16);return parseInt(e.high.toString(16)+"00000000".replace(new RegExp(`0{${r.length}}$`),r),16)};var Tt,It;!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"}(Tt||(Tt={})),e.RCRTCPingResult=void 0,(It=e.RCRTCPingResult||(e.RCRTCPingResult={})).SUCCESS="Success",It.FAIL="Fail";class Et{constructor(e,t,r,o=5e3,i=6e4){this._roomId=e,this._roomMode=t,this._context=r,this._gap=o,this._offlineKickTime=i,this._latestTimestamp=Date.now(),this._started=!1,this._timer=null}start(){this._started||(o.info("rtcping start ->"),t.logger.info(s.L_PINGER_START_O,{status:n.SUCCESSED,interval:this._gap},{logSource:t.LogSource.RTC}),this._started=!0,this._checkAlive())}_sendPing(){return new Promise((e=>{this._context.rtcPing(this._roomId,this._roomMode).then(e).catch((r=>{o.error(`rtcping receive unknown error -> ${r}`),e(t.ErrorCode.UNKNOWN)})),setTimeout(e,5e3,t.ErrorCode.TIMEOUT)}))}_checkAlive(){var i,n,a;return r(this,void 0,void 0,(function*(){o.info("rtcping ->"),t.logger.info(s.L_PINGER_SEND_RTCPING_T,{roomId:this._roomId,msg:"send rtcping"});const r=yield this._sendPing(),c=Date.now();return r===t.ErrorCode.SUCCESS?(o.info("rtcping success ->"),t.logger.info(s.L_PINGER_SEND_RTCPING_R,{roomId:this._roomId,msg:"send rtcping success"}),this._latestTimestamp=c,null===(i=this.onPingResult)||void 0===i||i.call(this,e.RCRTCPingResult.SUCCESS),void(this._timer=setTimeout((()=>this._checkAlive()),this._gap))):(t.logger.info(s.L_PINGER_SEND_RTCPING_R,{roomId:this._roomId,msg:"send rtcping failed",code:r}),o.warn(`rtcping failed -> code: ${r}`),null===(n=this.onPingResult)||void 0===n||n.call(this,e.RCRTCPingResult.FAIL),40003===r||c-this._latestTimestamp>this._offlineKickTime?(this.stop(),void(null===(a=this.onFailed)||void 0===a||a.call(this,40003===r))):void(this._timer=setTimeout((()=>this._checkAlive()),500)))}))}stop(){this._started&&(o.info("rtcping stop ->"),t.logger.info(s.L_PINGER_STOP_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),this._started=!1,this._timer&&(clearTimeout(this._timer),this._timer=null))}}const ft=-1,Lt=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),vt=(e,i,s)=>r(void 0,void 0,void 0,(function*(){const n=[];return yield Promise.any(e.map((e=>r(void 0,void 0,void 0,(function*(){const r=`${e.detectorAddr.replace(/^(https?:\/\/)?/,"https://")}/rtc/detector/ping?t=${a=1e3,c=9999,a+Math.floor(Math.random()*(c-a))}`;var a,c;const d={jwt:s},u=yield i.httpReq({url:r,body:JSON.stringify(d),timeout:5e3,method:t.HttpMethod.POST});if(o.info(`ping res => ${JSON.stringify({status:u.status,host:e})}`),200!==u.status)return Promise.reject();n.push(e.clusterId)}))))),n})),Ot=(e,i)=>r(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:""})(i),s=(n=i)&&n.jwt||"";var n;let a=null,c=120,d=0;const u={jwt:s};if(r&&s){const o=yield e.httpReq({url:`${r}/rtc/detector/servers`,body:JSON.stringify(u),headers:{"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${_t.browser}|${_t.version}`,ClientVersion:"5.5.2","Client-Session-Id":Lt(),"Request-Id":Date.now().toString()},method:t.HttpMethod.POST}),i=o.data&&JSON.parse(o.data).detectorAddrs;c=o.data&&JSON.parse(o.data).clientDetectMinute,d=o.data&&JSON.parse(o.data).resultCode,i&&t.isArray(i)&&(a=yield vt(i,e,s))}return{fastMediaUrl:a,clientDetectMinute:c,status:d}}));class At{constructor(){}static getMemo(){return this._memo||(this._memo=new At),this._memo}static destroy(){this._memo={}}}const Dt=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${_t.browser}|${_t.version}`,ClientVersion:"5.5.2","Client-Session-Id":Lt(),"Request-Id":Date.now().toString()});class Nt{constructor(e,r,o,i=5e3){this._runtime=e,this._context=r,this._msUrl=o,this._timeout=i,this._msInNavi=[],this._failedMs=[],this._rtcFinger=void 0,this._clusterId="",this._configUrl="",this._msList=[],Nt.isDetector||r.getConnectionStatus()!==t.ConnectionStatus.CONNECTED||this.detectorMediaSever()}detectorMediaSever(){if(this._msUrl)return;const e=Date.now(),r=Nt.detectValidMinute+Nt.detectorTime>e;Nt.isDetector=r,t.logger.info(`set msInDetector => ${JSON.stringify(Nt.msInDetector)}`);const o=this._context.getNaviInfo();!r&&o&&t.notEmptyObject(o)&&(this._msList=[],this._getDetectorUrls(o))}_getDetectorUrls(t){return r(this,void 0,void 0,(function*(){if(Nt.isDetector)return;Nt.isDetector=!0;const{fastMediaUrl:r,clientDetectMinute:i,status:s}=yield Ot(this._runtime,t);if(s===e.RCRTCCode.JWT_TIME_OUT&&Nt.naviRefetchCount<5){this._context.getPluginContext().refetchNaviInfo().then((()=>{this.detectorMediaSever()})),++Nt.naviRefetchCount,o.info(`RCMediaService refetch navi count => ${Nt.naviRefetchCount}`)}Nt.msInDetector=r||[],Nt.detectorTime=Date.now(),Nt.detectValidMinute=60*i*1e3,o.info(`RCMediaService detectorTime => ${Nt.detectorTime}`),o.info(`RCMediaService detectValidMinute => ${Nt.detectValidMinute}`)}))}getNaviMS(){return this._msUrl?[this._msUrl]:(t.notEmptyArray(this._msList)&&!this._clusterId||(this._msList=this.setMediaServiceList()),this._msList)}setMediaServiceList(){let e=[],r=[];return this._clusterId&&(this._clusterId=this._clusterId.replace(/^(https?:\/\/)?/,"https://"),this._msList.push(this._clusterId)),o.info(`MediaServiceList _clusterId -> ${this._clusterId}`),t.notEmptyArray(Nt.msInDetector)&&(Nt.msInDetector=Nt.msInDetector.map((e=>e.replace(/^(https?:\/\/)?/,"https://"))),this._msList.push(Nt.msInDetector[0]),e=Nt.msInDetector.concat().splice(1,Nt.msInDetector.length-1)),o.info(`MediaServiceList msInDetector ->${JSON.stringify(Nt.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],n=[];return s.mediaServer&&n.push(s.mediaServer.replace(/^(https?:\/\/)?/,"https://")),s.backupMediaServer&&s.backupMediaServer.forEach((e=>{n.push(e.replace(/^(https?:\/\/)?/,"https://"))})),n})(this._context.getNaviInfo())):(this._msInNavi.push(...this._failedMs),this._failedMs.length=0)),o.info(`MediaServiceList _msInNavi-> ${JSON.stringify(this._msInNavi)}`),r=this._msInNavi.concat().splice(1,this._msInNavi.length-1),this._msList.push(this._msInNavi[0]),this._msList=[...this._msList,...e,...r],this._msList=[...new Set(this._msList)],o.info(`MediaServiceList msList -> ${JSON.stringify(this._msList)}`),this._msList}_request(i,a,c){return r(this,void 0,void 0,(function*(){const r=At.getMemo();r.mediaService=[];const d=this.getNaviMS();if(0===d.length)return o.warn(`request '${i}' failed -> have no valid service address.`),t.logger.error(s.L_MEDIA_SERVICE_REQUEST_R,{status:n.FAILED,code:e.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"invalid navi_url"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(c.rtcFinger=this._rtcFinger);for(let u=0;u<d.length;u+=1){const _=Date.now(),l=`${d[u]}${i}`,R=Dt(),C=Object.assign(Object.assign({},R),a),h=JSON.stringify(c),g=R["Request-Id"];t.logger.info(s.L_MEDIA_SERVICE_REQUEST_T,{path:i,headers:a,body:c,reqId:g},{logSource:t.LogSource.RTC}),o.info(`request -> Request-Id: ${g}, url: ${l}, headers: ${JSON.stringify(C)}, body: ${h}, timeout: ${this._timeout}`);const{status:p,data:S}=yield this._runtime.httpReq({url:l,body:h,headers:C,method:t.HttpMethod.POST,timeout:this._timeout});if(r.mediaService.push({start:_,end:Date.now(),reqId:g,status:p,url:l}),200===p){const r=JSON.parse(S);return r.rtcFinger&&(this._rtcFinger=r.rtcFinger),r.clusterId&&(this._clusterId=r.clusterId),o.info(`request success -> Request-Id: ${g}`),t.logger.info(s.L_MEDIA_SERVICE_REQUEST_R,{status:n.SUCCESSED,url:l,reqId:g},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,data:r}}o.warn(`request failed -> Request-Id: ${g}, status: ${p}, url: ${l}`),this._failedMs.push(...this._msInNavi.splice(u,1)),t.logger.error(s.L_MEDIA_SERVICE_REQUEST_R,{status:n.FAILED,code:"",reqId:g,url:l,msg:`request error -> Request-Id: ${g}, status: ${p}, url: ${l}`},{logSource:t.LogSource.RTC})}return{code:e.RCRTCCode.REQUEST_FAILED}}))}exchange(t,o){var i;return r(this,void 0,void 0,(function*(){const r=yield this._request("/exchange",t,o);if(r.code===e.RCRTCCode.SUCCESS&&(null===(i=r.data)||void 0===i?void 0:i.resultCode)===e.RCRTCCode.SUCCESS){const{urls:e}=r.data;e&&(this._configUrl=e.configUrl)}return r}))}exit(e){return r(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 r(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/broadcast/exit",e,{});return{code:t}}))}setMcuConfig(i,a){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_MEDIA_SERVICE_SET_MCU_CONFIG_T,{headers:i,body:a},{logSource:t.LogSource.RTC}),!this._configUrl)return o.warn("RCMediaService.setMcuConfig failed -> RCRTCCode.MCU_SERVER_NOT_FOUND"),t.logger.error(s.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:n.FAILED,code:e.RCRTCCode.MCU_SERVER_NOT_FOUND,msg:"MCU not found"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.MCU_SERVER_NOT_FOUND};const r=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,c=Dt(),d=Object.assign(Object.assign({},c),i),u=JSON.stringify(a),_=c["Request-Id"];o.info(`request -> Request-Id: ${_}, url: ${r}, headers: ${JSON.stringify(d)}, body: ${u}`);const{status:l,data:R}=yield this._runtime.httpReq({url:r,headers:d,body:u,method:t.HttpMethod.POST});if(200===l){o.info(`request success -> Request-Id: ${_}`);const e=JSON.parse(R);return t.logger.info(s.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:n.SUCCESSED,reqId:_},{logSource:t.LogSource.RTC}),{code:e.resultCode,res:e}}return o.warn(`request failed -> Request-Id: ${_}, status: ${l}, url: ${r}`),t.logger.error(s.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:n.FAILED,code:e.RCRTCCode.REQUEST_FAILED,msg:`request error -> Request-Id: ${_}, status: ${l}, url: ${r}`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REQUEST_FAILED}}))}getCDNResourceInfo(i,a){return r(this,void 0,void 0,(function*(){t.logger.info(s.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_T,{headers:i,url:a},{logSource:t.LogSource.RTC});const r=Dt(),c=Object.assign(Object.assign({},r),i),d=r["Request-Id"];o.info(`request -> Request-Id: ${d}, url: ${a}, headers: ${JSON.stringify(c)}`);const{status:u,data:_}=yield this._runtime.httpReq({url:a,headers:c,method:t.HttpMethod.GET});if(200===u){o.info(`request success -> Request-Id: ${r["Request-Id"]}`);const e=JSON.parse(_);return t.logger.info(s.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:n.SUCCESSED,reqId:r["Request-Id"]},{logSource:t.LogSource.RTC}),{code:e.resultCode,res:e}}return o.warn(`request failed -> Request-Id: ${r["Request-Id"]}, status: ${u}, url: ${a}`),t.logger.info(s.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:n.FAILED,code:e.RCRTCCode.REQUEST_FAILED,msg:`request error -> Request-Id: ${r["Request-Id"]}, status: ${u}, url: ${a}`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REQUEST_FAILED}}))}}var bt;Nt.isDetector=!1,Nt.msInDetector=[],Nt.detectorTime=0,Nt.detectValidMinute=72e5,Nt.naviRefetchCount=0,function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(bt||(bt={}));const yt=(e,t)=>Math.round(8*t/e),kt=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},Ut=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.round(e*r)},Pt=(e,t,r,o)=>{if(0===t)return 0;if(!r||!o)return kt(e/t,3);const i=t-o;if(0===i)return 0;const s=e-r;return s<0||i<0?0:kt(s/i,3)},Mt=e=>{const{jitter:t,rtt:r,packetsLostRate:o}=e;return!Ct(t)||!Ct(r)||0!==o};class xt{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 o,i;if(this._latestBytesSent[e]&&t<this._latestBytesSent[e].bytesSent&&this.clearLatestpacketsSent([e]),this._latestBytesSent[e]){const{bytesSent:s,timestamp:n}=this._latestBytesSent[e];o=t-s,i=r-n,this._latestBytesSent[e]={bytesSent:t,timestamp:r}}else o=t,i=1e3,this._latestBytesSent[e]={bytesSent:t,timestamp:r};return yt(i,o)}updateBytesRecv(e,t,r){let o,i;if(this._latestBytesRecv[e]&&t<this._latestBytesRecv[e].bytesRecv&&this.clearLatestPacketsRecv([e]),this._latestBytesRecv[e]){const{bytesRecv:s,timestamp:n}=this._latestBytesRecv[e];o=t-s,i=r-n,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r}}else o=t,i=1e3,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r};return yt(i,o)}updateSenderPacketsLost(e,t,r){let o;if(Object.prototype.hasOwnProperty.call(this._latestPacketsSent[e],"packetsSent")){const{packetsLost:i,packetsSent:s}=this._latestPacketsSent[e];o=Pt(t,r,i,s),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=i===t?s:r}else o=Pt(t,r),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=r;return o}updateReceiverPacketsLost(e,t,r){let o;if(this._latestPacketsRecv[e]){const{packetsLost:i,packetsRecv:s}=this._latestPacketsRecv[e];o=Pt(t,r+t,i,s+i)}else o=Pt(t,r);return this._latestPacketsRecv[e]={packetsLost:t,packetsRecv:r},o}clearLatestpacketsSent(t){t.forEach((t=>{if(parseInt(t.split("_").pop())===e.RCMediaType.VIDEO_ONLY){const e=`${t}_tiny`;delete this._latestPacketsSent[e],delete this._latestBytesSent[e]}delete this._latestPacketsSent[t],delete this._latestBytesSent[t]}))}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 r={senders:[],receivers:[]};return t.logger.info(s.L_ABSTRACT_STAT_PARSER_FORMAT_RTC_STATE_REPORT_O,{status:n.SUCCESSED,stats:e,reports:r},{logSource:t.LogSource.RTC}),r}getAudioLevelList(e){return[]}getResourceIdByParseSdp(e){var t,r;const{ssrc:o}=e,i=e.kind||e.mediaType,s=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:${o} msid:(.*?) `);const c=null==s?void 0:s.split("\r\nm="),d=null==c?void 0:c.filter((e=>e.includes(`a=ssrc:${o}`)))[0],u=null==d?void 0:d.match(a);let _=u?u[1]:"";if(_){if("audio"===i)return`${_}_0`;const e=_.replace(`${this._currentUserId}_`,"").split("_");return e.length>1&&"tiny"===e[1]?`${this._currentUserId}_${e[0]}_1_tiny`:`${_}_1`}const l=null==n?void 0:n.split("\r\nm="),R=null==l?void 0:l.filter((e=>e.includes(`a=ssrc:${o}`)))[0],C=null==R?void 0:R.match(a);return _=C?C[1]:"",_?`${_}_${"video"===i?1:0}`:""}isValidSender(e){var t;const r=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,{ssrc:o}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(o)&&e.includes("a=inactive"))))}isValidReceiver(e){var t;const r=null===(t=this._rtcPeerConn.currentRemoteDescription)||void 0===t?void 0:t.sdp,{ssrc:o}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(o)&&e.includes("a=inactive"))))}}class wt extends xt{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const o=Object.keys(e);let i=0,s=0;o.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const n=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const{id:a,kind:c,transportId:d,mediaSourceId:u,remoteId:_,packetsSent:l,bytesSent:R,trackId:C,encoderImplementation:h,pliCount:g,nackCount:p,firCount:S}=n;if(!C)return;let{framesPerSecond:m,frameWidth:T,frameHeight:I}=n;"video"!==c||T||I||m||(T=e[C].frameWidth,I=e[C].frameHeight,m=u?e[u].framesPerSecond:null);const E=e[_];let f=null,L=null,v=0;E&&(f=E.jitter,L=E.roundTripTime,v=E.packetsLost),i+=v;const O=this.getResourceIdByParseSdp(n);if(!O)return;const A=u?e[u].audioLevel:e[C].audioLevel;let D=null;!this._latestPacketsSent[O]&&(this._latestPacketsSent[O]={}),E?D=this.updateSenderPacketsLost(O,v,l):this._latestPacketsSent[O].crtPacketsSent=l;let N=this.updateBytesSent(O,R,r);N<0&&(N=0),s+=N,t.senders.push({id:a,trackId:O,kind:c,packetsLostRate:D,remoteResource:!1,audioLevel:A||0===A?Ut(A):null,frameWidth:T,frameHeight:I,frameRate:m,bitrate:N,jitter:f?Math.round(1e3*f):f,rtt:L,encoderImplementation:h,pliCount:g,nackCount:p,googFirsSent:ft,samplingRate:ft,googRenderDelayMs:ft,trackState:ft})}));o.filter((e=>/RTCRemoteInboundRtp(Video|Audio)Stream_/.test(e))).forEach((r=>{const{localId:o,jitter:i,roundTripTime:s,packetsLost:n}=e[r],a=t.senders.filter((e=>e.id===o))[0];if(a&&!Mt(a)){const t=this.getResourceIdByParseSdp(e[a.id]);a.jitter=Math.round(1e3*i),a.rtt=s;const r=this._latestPacketsSent[t].crtPacketsSent;a.packetsLostRate=this.updateSenderPacketsLost(t,n,r)}}));let n=0;o.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const s=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:u,bytesReceived:_,framesPerSecond:l,kind:R,codecImplementationName:C,nackCount:h,pliCount:g}=s;if(!a)return;let{frameWidth:p,frameHeight:S,audioLevel:m}=s;"video"===R?p||S||(p=e[a].frameWidth,S=e[a].frameHeight):m||(m=e[a].audioLevel),i+=c;const T=this.getResourceIdByParseSdp(s),I=this.updateReceiverPacketsLost(T,c,d);let E=this.updateBytesRecv(T,_,r);E<0&&(E=0),n+=E,t.receivers.push({trackId:T,kind:R,packetsLostRate:I,remoteResource:!0,audioLevel:m||0===m?Ut(m):null,frameWidth:p,frameHeight:S,frameRate:l,bitrate:E,jitter:u?Math.round(1e3*u):0,codecImplementationName:C,nackCount:h,pliCount:g,rtt:null,samplingRate:ft,googFirsReceived:ft,googRenderDelayMs:ft,trackState:ft})}));const a=o.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:o}=r;if(o){const r=e[o],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:u,remoteCandidateId:_}=r,l=e[u],{ip:R,port:C,networkType:h}=l,g=e[_],{ip:p,port:S,protocol:m}=g;t.iceCandidatePair={IP:R,port:C,networkType:h,remoteIP:p,remotePort:S,protocol:m,bitrateRecv:n,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:i},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 o;const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const{mediaSourceId:s,trackId:n}=i,a=this.getResourceIdByParseSdp(i),c=s&&e[s]?e[s].audioLevel:(null===(o=e[n])||void 0===o?void 0:o.audioLevel)||null;t.push({trackId:a,audioLevel:c||0===c?Ut(c):null})}));return r.filter((e=>/^RTCInboundRTPAudioStream_/.test(e))).forEach((r=>{const o=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:i}=o,s=o.audioLevel||e[i].audioLevel,n=this.getResourceIdByParseSdp(o);t.push({trackId:n,audioLevel:s||0===s?Ut(s):null})})),t}}class Bt extends xt{formatRCRTCStateReport(e){const t=+new Date,r={senders:[],receivers:[],timestamp:t};let o=0,i=0,s=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:s,kind:n,bytesSent:c,packetsSent:d,bitrateMean:u,framerateMean:_,nackCount:l,pliCount:R,remoteId:C}=a,{jitter:h,roundTripTime:g,packetsLost:p}=C?e[C]:{jitter:null,roundTripTime:null,packetsLost:0},S=this.getResourceIdByParseSdp(a);o+=p;let m=null;!this._latestPacketsSent[S]&&(this._latestPacketsSent[S]={}),C?m=this.updateSenderPacketsLost(S,p,d):this._latestPacketsSent[S].crtPacketsSent=d;let T=0;"video"===n?u&&(T=Math.floor(u/1e3)):T=this.updateBytesSent(S,c,t),T<0&&(T=0),i+=T,r.senders.push({trackId:S,kind:n,packetsLostRate:m,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(_),bitrate:T,jitter:h?Math.round(1e3*h):null,rtt:g,encoderImplementation:null,pliCount:R,nackCount:l,googFirsSent:ft,samplingRate:ft,googRenderDelayMs:ft,trackState:ft})}if("remote-inbound-rtp"===c){const{localId:t}=a,o=this.getResourceIdByParseSdp(e[t]),i=r.senders.filter((e=>e.trackId===o))[0];i&&Mt(i)&&(i.jitter=Math.round(1e3*a.jitter),i.rtt=a.rtt,i.packetsLostRate=this.updateSenderPacketsLost(o,a.packetsLost,this._latestPacketsSent[o].crtPacketsSent))}if("inbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(a))continue;const{id:e,packetsLost:i,bytesReceived:n,packetsReceived:c,jitter:d,framerateMean:u,kind:_,bitrateMean:l,nackCount:R,pliCount:C}=a,h=this.getResourceIdByParseSdp(a);o+=i;const g=this.updateReceiverPacketsLost(h,i,c);let p=0;"video"===_?l&&(p=Math.floor(l/1e3)):p=this.updateBytesRecv(h,n,t),p<0&&(p=0),s+=p,r.receivers.push({trackId:h,kind:_,packetsLostRate:g,remoteResource:!0,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:p,jitter:d?Math.round(1e3*d):null,codecImplementationName:null,nackCount:R,pliCount:C,rtt:null,samplingRate:ft,googFirsReceived:ft,googRenderDelayMs:ft,trackState:ft})}if("candidate-pair"===c&&"succeeded"===a.state){const t=e[a.localCandidateId],{address:n,port:c}=t,d=e[a.remoteCandidateId],{address:u,port:_,protocol:l}=d;r.iceCandidatePair={IP:n,port:c,networkType:null,remoteIP:u,remotePort:_,protocol:l,bitrateRecv:s,bitrateSend:i,rtt:null,availableOutgoingBitrate:null,availableIncomingBitrate:null,totalPacketsLost:o}}}return r.iceCandidatePair&&(r.iceCandidatePair.bitrateSend=i),r.iceCandidatePair&&(r.iceCandidatePair.bitrateRecv=s),r}getAudioLevelList(e){const t=[];for(const r in e){const o=e[r],{type:i}=o;if("outbound-rtp"===i){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))continue;const{kind:e}=o;if("video"===e)continue;const r=this.getResourceIdByParseSdp(o);t.push({trackId:r,audioLevel:null})}if("inbound-rtp"===i){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))continue;const{kind:e}=o;if("video"===e)continue;const r=this.getResourceIdByParseSdp(o);t.push({trackId:r,audioLevel:null})}}return t}}class Vt extends xt{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const o=Object.keys(e);let i=0,s=0;o.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const i=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const n=this.getResourceIdByParseSdp(i),{mediaType:a,transportId:c,remoteId:d,packetsSent:u,bytesSent:_,trackId:l,encoderImplementation:R,pliCount:C,nackCount:h,firCount:g}=i;if(!l)return;const{audioLevel:p,frameHeight:S,frameWidth:m}=e[l];let T=this.updateBytesSent(n,_,r);T<0&&(T=0),s+=T,t.senders.push({trackId:n,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:p||0===p?Ut(p):null,frameWidth:m,frameHeight:S,frameRate:null,bitrate:T,jitter:null,rtt:null,encoderImplementation:R,pliCount:C,nackCount:h,googFirsSent:ft,samplingRate:ft,googRenderDelayMs:ft,trackState:ft})}));let n=0;o.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const s=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:u,bytesReceived:_,mediaType:l,nackCount:R,pliCount:C}=s,h=this.getResourceIdByParseSdp(s);if(!a)return;const{frameHeight:g,frameWidth:p,audioLevel:S}=e[a];i+=c;const m=this.updateReceiverPacketsLost(h,c,d);let T=this.updateBytesRecv(h,_,r);T<0&&(T=0),n+=T,t.receivers.push({trackId:h,kind:l,packetsLostRate:m,remoteResource:!0,audioLevel:S||0===S?Ut(S):null,frameWidth:p,frameHeight:g,frameRate:null,bitrate:T,jitter:u,codecImplementationName:null,nackCount:R,pliCount:C,rtt:null,samplingRate:ft,googFirsReceived:ft,googRenderDelayMs:ft,trackState:ft})}));const a=o.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:o}=r;if(o){const r=e[o],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:u,remoteCandidateId:_}=r,l=e[u],{address:R,port:C}=l,h=e[_],{address:g,port:p,protocol:S}=h;t.iceCandidatePair={IP:R||null,port:C,networkType:null,remoteIP:g,remotePort:p,protocol:S,bitrateRecv:n,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:i},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 o=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))return;const{trackId:i,mediaType:s}=o;if("video"===s)return;const n=this.getResourceIdByParseSdp(o),a=e[i];t.push({trackId:n,audioLevel:a||0===a?Ut(a):null})}));return r.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const o=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:i,mediaType:s}=o;if(!i||"video"===s)return;const{audioLevel:n}=e[i],a=this.getResourceIdByParseSdp(o);t.push({trackId:a,audioLevel:n||0===n?Ut(n):null})})),t}}class $t{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*$t.KBitrate}\r\nb=TIAS:${e*$t.KBitrate*850}`)}setAudiosBitrate(e){return o.info(s.L_RTC_SDP_BITRATE_O,{bitrate:e,msg:"SDP setAudiosBitrate"},{logSource:t.LogSource.RTC}),this.audioStreams=this.audioStreams.map((t=>this.setAudioItemBitrate(t,e))),this}setAudioBitrateWithStreamId(e,r){return o.info(s.L_RTC_SDP_BITRATE_O,{bitrate:e,streamId:r,msg:"SDP setAudioBitrateWithStreamId"},{logSource:t.LogSource.RTC}),this.audioStreams=this.audioStreams.map((t=>new RegExp(`\\bmsid:${r}\\b`,"ig").test(t)?this.setAudioItemBitrate(t,e):t)),this}setAudioBitrateWithMid(e,r){return o.info(s.L_RTC_SDP_BITRATE_O,{bitrate:e,mid:r,msg:"SDP setAudioBitrateWithMid"},{logSource:t.LogSource.RTC}),this.audioStreams=this.audioStreams.map((t=>new RegExp(`\\bmid:${r}\\b`,"ig").test(t)?this.setAudioItemBitrate(t,e):t)),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*$t.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*$t.KBitrate}\r\nb=TIAS:${t.max*$t.KBitrate*850}`)}setVideosBitrate(e){return o.info(s.L_RTC_SDP_BITRATE_O,{bitrate:e,msg:"SDP setVideosBitrate"},{logSource:t.LogSource.RTC}),this.videoStreams=this.videoStreams.map((t=>this.setVideoItemBitrate(t,e))),this}setVideoBitrateWithStreamId(e,r){return o.info(s.L_RTC_SDP_BITRATE_O,{bitrate:e,streamId:r,msg:"SDP setVideoBitrateWithStreamId"},{logSource:t.LogSource.RTC}),this.videoStreams=this.videoStreams.map((t=>new RegExp(`\\bmsid:${r}\\b`,"ig").test(t)?this.setVideoItemBitrate(t,e):t)),this}setVideoBitrateWithMid(e,r){return o.info(s.L_RTC_SDP_BITRATE_O,{bitrate:e,mid:r,msg:"SDP setVideoBitrateWithMid"},{logSource:t.LogSource.RTC}),this.videoStreams=this.videoStreams.map((t=>new RegExp(`\\bmid:${r}\\b`,"ig").test(t)?this.setVideoItemBitrate(t,e):t)),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*$t.KBitrate,"x-google-min-bitrate="+t.min*$t.KBitrate,`x-google-start-bitrate=${t.start||t.max*$t.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*$t.KBitrate}\r\nb=TIAS:${t.max*$t.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===Gt.SENDONLY){if(/\ba=sendonly\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}if(t===Gt.RECVONLY){if(/\ba=recvonly\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}if(t===Gt.INACTIVE){if(/\ba=inactive\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}return e}}var Ft,Gt,Kt,Ht,jt,Jt,qt,Wt,Yt,Qt,zt,Zt,Xt,er,tr,rr,or;$t.KBitrate=1,function(e){e.PLANB="plan-b",e.UNIFIEDPLAN="unified-plan"}(Ft||(Ft={})),function(e){e.SENDONLY="sendonly",e.RECVONLY="recvonly",e.INACTIVE="inactive"}(Gt||(Gt={}));class ir{constructor(e){this._peer=e,this._outboundStreams={}}static setSdpSemantics(e){t.logger.info(s.L_A_SDP_STRATEGY_SET_SDP_SEMANTICS_O,{status:n.SUCCESSED,sdpSemantics:e},{logSource:t.LogSource.RTC});const{browser:r,version:o,supportsUnifiedPlan:i}=_t;t.logger.debug(`sdpSemantics, browser: ${r}, version: ${o}, supportsUnifiedPlan: ${i}`),i?/chrome/i.test(r)?this._sdpSemantics=o>92?"unified-plan":o<72?"plan-b":e:/firefox/i.test(r)?this._sdpSemantics="unified-plan":/safari/i.test(r)?this._sdpSemantics=o<12?"plan-b":"unified-plan":this._sdpSemantics="unified-plan":this._sdpSemantics="plan-b"}static getSdpSemantics(){return ir._sdpSemantics}getOutboundVideoInfo(){const e=[];for(const t in this._outboundStreams){const r=this._outboundStreams[t].getVideoTracks()[0];if(!r)continue;const o=/_tiny$/.test(t),{width:i,height:s}=Xe(r);e.push({trackId:r.id,simulcast:o?bt.TINY:bt.NORMAL,resolution:`${i}x${s}`})}return e}setRemoteAnswer(i){return r(this,void 0,void 0,(function*(){i=$t.trimBlankLine(i),o.info(`set remote answer -> ${i}`);try{yield this._peer.setRemoteDescription({type:"answer",sdp:i})}catch(r){return o.error(r),t.logger.info(s.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:n.FAILED,code:"",msg:r},{logSource:t.LogSource.RTC}),e.RCRTCCode.SET_REMOTE_DESCRIPTION_FAILED}return t.logger.info(s.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:n.SUCCESSED,sdp:i},{logSource:t.LogSource.RTC}),e.RCRTCCode.SUCCESS}))}getStatParsr(e,t,r){return/chrome/i.test(_t.browser)?new wt(e,t,r):/Firefox/i.test(_t.browser)?new Bt(e,t,r):/Safari/i.test(_t.browser)?new Vt(e,t,r):null}resetSdp(e){return $t.trimBlankLine(e)}}class sr extends $t{constructor(e){super(e,Ft.PLANB),this.SDP=e}stringify(){const e=[this.SDPHeader];[...this.audioStreams,...this.videoStreams].forEach((t=>{const r=t.match(/\ba=mid:(video|audio)\b/),o=$t.clearInactiveOrRecvonly(t);r&&r[1]===De.AUDIO&&(e[1]=o),r&&r[1]===De.VIDEO&&(e[2]=o)}));const t=e.join("");return $t.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 ir{constructor(){super(...arguments),this.senders={},this._localTracks=[]}addLocalTrack(e){this._localTracks.includes(e)||this._localTracks.push(e);const t=e.getStreamId(),r=e.__innerGetMediaStreamTrack(),o=this._outboundStreams[t]||(this._outboundStreams[t]=new MediaStream);o.getTracks().forEach((e=>{e.kind===r.kind&&o.removeTrack(e)})),o.addTrack(r);const i=e.getTrackId(),s=this.senders[i];s?s.replaceTrack(r):this.senders[i]=this._peer.addTrack(r,o)}removeLocalTrack(e){const t=this._localTracks.findIndex((t=>t===e));t>=0&&this._localTracks.splice(t,1);const r=e.getTrackId(),o=this.senders[r];o&&(o.replaceTrack(null),this._peer.removeTrack(o),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 r(this,void 0,void 0,(function*(){const r=yield this._peer.createOffer({iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0});for(const e in this._outboundStreams){const t=this._outboundStreams[e].id;r.sdp=r.sdp.replace(new RegExp(t,"g"),e)}r.sdp&&(r.sdp=$t.clearInactiveOrRecvonly(r.sdp));const o=At.getMemo();return t.logger.info(s.L_QS_SET_LOCAL_DESCRIPTION_O,{identify:o.qualityStatusId},{logSource:t.LogSource.RTC}),yield this._peer.setLocalDescription(r),{type:"offer",semantics:"plan-b",sdp:r.sdp}}))}setRemoteAnswer(e){return e=this.resetSdp(e),super.setRemoteAnswer(e)}resetSdp(e){const t=new sr(e),r={max:0,min:0},o={max:0,min:0};return this._localTracks.forEach((e=>{const{min:t,max:i,start:s}=e.getBitrate();e.isAudioTrack()&&(o.max=o.max<i?i:o.max,o.min=o.min>t?t:o.min,o.max===i?o.start=s:o.start=.7*o.max),e.isVideoTrack()&&(r.max=r.max<i?i:r.max,r.min=r.min>t?t:r.min,r.max===i?r.start=s:r.start=.7*r.max)})),t.setAudiosBitrate(o),t.setVideosBitrate(r),t.stringify()}}class ar extends $t{constructor(e){super(e,Ft.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 $t.trimBlankLine(t)}}class cr{static splitSections(e){return e.split("\nm=").map(((e,t)=>`${(t>0?`m=${e}`:e).trim()}\r\n`))}static getMediaSections(e){const t=cr.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=cr.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 cr.splitLines(e).filter((e=>0===e.indexOf(t)))}static parseMsid(e){let t;const r=cr.matchPrefix(e,"a=msid:");if(1===r.length)return t=r[0].substr(7).split(" "),{stream:t[0],track:t[1]};const o=cr.matchPrefix(e,"a=ssrc:").map((e=>cr.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return o.length>0&&o[0].value?(t=o[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)},o=e.indexOf(":",t);return o>-1?(r.attribute=e.substr(t+1,o-t-1),r.value=e.substr(o+1)):r.attribute=e.substr(t+1),r}static getMid(e){const t=cr.matchPrefix(e,"a=mid:")[0];if(t)return t.substr(6)}}class dr extends ir{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(),o=e.__innerGetMediaStreamTrack();this._localTracks[t]=e;const i=this._outboundStreams[r]||(this._outboundStreams[r]=new MediaStream);i.getTracks().forEach((e=>{e.kind===o.kind&&i.removeTrack(e)})),i.addTrack(o);const s=this._sendTransceiver[t];s?(s.sender.replaceTrack(o),s.direction="sendonly"):this._sendTransceiver[t]=this._peer.addTransceiver(o,{direction:"sendonly",streams:[i]})}removeLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId();e.__innerGetMediaStreamTrack(),delete this._localTracks[t];const o=this._sendTransceiver[t];if(!o)return;o.direction="inactive",this._peer.removeTrack(o.sender),o.sender.replaceTrack(null);const i=this._outboundStreams[r];(e.isAudioTrack()?i.getAudioTracks():i.getVideoTracks()).forEach((e=>i.removeTrack(e)));const s=this._sendTransceiver[`${t}_tiny`];if(!s||"inactive"===s.direction)return;s.direction="inactive";const{sender:n}=s,a=n.track;this._peer.removeTrack(n),n.replaceTrack(null);this._outboundStreams[`${r}_tiny`].removeTrack(a),a.stop()}updateRecvTransceiverMap(t,r){const{mediaType:o}=rt(t);this._recvTransceiver[t]=r;const i=o===e.RCMediaType.AUDIO_ONLY?this._recvAudio:this._recvVideo,s=i.findIndex((e=>e===r));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 o=t[e],i=r.findIndex((e=>e===o));i>=0&&(t.splice(e,1),r.splice(i,1))}r.length&&r.forEach((e=>{const t=e.getTrackId();e.__innerSetMediaStreamTrack(void 0);const r=this._recvTransceiver[t];r&&(r.direction="inactive")}));const o={audio:0,video:0};t.length&&t.forEach((e=>{const t=e.isAudioTrack()?"audio":"video",r=this._recvTransceiver[e.getTrackId()];r?r.direction="recvonly":o[t]+=1}));for(let e=this._recvAudio.length;e<o.audio;e+=1)this._recvAudio.push(this._peer.addTransceiver("audio",{direction:"recvonly"}));for(let e=this._recvVideo.length;e<o.video;e+=1)this._recvVideo.push(this._peer.addTransceiver("video",{direction:"recvonly"}))}createOffer(e){return r(this,void 0,void 0,(function*(){const r=yield this._peer.createOffer({iceRestart:e});let o=r.sdp;for(const e in this._outboundStreams){const t=this._outboundStreams[e].id;o=o.replace(new RegExp(t,"g"),e)}o=this.resetOfferSdp(o),o=o.replace(/(a=ice-options:trickle)/g,"$1\r\na=ice-options:renomination"),r.sdp=o;const i=At.getMemo();return t.logger.info(s.L_QS_SET_LOCAL_DESCRIPTION_O,{identify:i.qualityStatusId},{logSource:t.LogSource.RTC}),yield this._peer.setLocalDescription(r),{type:"offer",semantics:"unified-plan",sdp:o}}))}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 ar(e);for(const o in this._sendTransceiver){const i=this._sendTransceiver[o],s=null===(t=i.sender.track)||void 0===t?void 0:t.kind;let{direction:n,mid:a}=i;if(!a){cr.getMediaSections(e).forEach((e=>{cr.parseExtmap(e);const{kind:t}=cr.parseMLine(e);let{stream:r}=cr.parseMsid(e);const i=cr.getMid(e);"video"===s?/tiny$/.test(r)?r=r.replace(/tiny$/gi,"1_tiny"):r+="_1":r+="_0",r===o&&s===t&&i&&(a=i)}))}if(a){if(n===Gt.SENDONLY){const e=this._localTracks[o],t=null==e?void 0:e.getBitrate();s===De.AUDIO&&t&&r.setAudioBitrateWithMid(t,a),s===De.VIDEO&&t&&r.setVideoBitrateWithMid(t,a)}n===Gt.INACTIVE&&r.clearnSsrcWithMid(a,Gt.INACTIVE)}}for(const e in this._recvTransceiver){const t=this._recvTransceiver[e],{direction:o,mid:i}=t;i&&o===Gt.INACTIVE&&r.clearnSsrcWithMid(i,Gt.RECVONLY)}return r.stringify()}resetAnswerSdp(e){var t;const r=new ar(e);for(const e in this._sendTransceiver){const o=this._sendTransceiver[e],{mid:i}=o;if(i){const s=this._localTracks[e],n=null==s?void 0:s.getBitrate(),a=null===(t=o.sender.track)||void 0===t?void 0:t.kind;a===De.AUDIO&&n&&r.setAudioBitrateWithMid(n,i),a===De.VIDEO&&n&&r.setVideoBitrateWithMid(n,i)}}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"}(Kt||(Kt={}));class ur extends t.EventEmitter{constructor(e,t,r,o){super(),this._pcName=e,this._reTryExchange=t,this._currentUserId=r,this._polarisReport=o,this.pubLocalTracks={},this._reTryExchangeTimer=null,this._reportStatsTimer=null,this._reportR3R4ToPolarisTimer=null,this._isDestroyed=!1,this._reportStatsData=null,this._originReportStatsData=null,this._reportListener=null;const i=ir.getSdpSemantics(),s=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:i});this._sdpStrategy="plan-b"===i?new nr(s):new dr(s),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,i,this._currentUserId)}getName(){return this._pcName}getLocalTracks(){return t.logger.info(s.L_RTC_PEER_CONNECTION_GET_LOCAL_TRACKS_O,{status:n.SUCCESSED,trackIds:Object.keys(this.pubLocalTracks)},{logSource:t.LogSource.RTC}),Object.values(this.pubLocalTracks)}_onConnectionStateChange(){o.info(`onconnectionstatechange -> ${this._rtcPeerConn.connectionState}, ${this._pcName}`),t.logger.info(s.L_RTC_PEER_CONNECTION_CONNECTION_STATE_S,{status:n.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:t.LogSource.RTC})}startAutoExecute(e=1e3){this._reportStatsTimer=setTimeout((()=>{this._reportHandle(e),this._reportStatsTimer=this.startAutoExecute()}),e)}stopAutoExecute(){clearTimeout(this._reportStatsTimer)}_onICEConnectionStateChange(){var e,r,i,a,c,d,u,_,l,R,C,h,g,p,S,m,T,I,E,f,L,v,O,A,D,N;const b=Date.now(),y=At.getMemo();y.iceStatusData||(y.iceStatusData={}),y.iceNewStatusData&&(y.iceOldStatusData=y.iceNewStatusData),y.iceNewStatusData={start:b,status:this._rtcPeerConn.iceConnectionState};const k={dur:0,pices:0,ices:0,rid:null===(e=y.joinRoomData)||void 0===e?void 0:e.roomId,csnid:null===(r=y.clientData)||void 0===r?void 0:r.clientSessionId,snid:"",time:0,rcdts:[],lcdts:[],cncdts:null,cr:"unknown",net:"unknown",uid:this._currentUserId};if(y.qualitySubscribeReportData=k,o.info(`oniceconnectionstatechange -> ${this._rtcPeerConn.iceConnectionState}, ${this._pcName}`),t.logger.info(s.L_QS_SET_LOCAL_DESCRIPTION_O,{identify:y.qualityStatusId},{logSource:t.LogSource.RTC}),"connected"===this._rtcPeerConn.iceConnectionState){if(!(null===(i=y.iceStatusData)||void 0===i?void 0:i.subscribeNotReport)&&(null===(a=y.iceStatusData)||void 0===a?void 0:a.subscribe)){y.iceStatusData.subscribeNotReport=!0;const e=y.iceStatusData.notFirst?0:(null===(c=y.iceNewStatusData)||void 0===c?void 0:c.start)-(null===(u=null===(d=y.iceStatusData)||void 0===d?void 0:d.subscribe)||void 0===u?void 0:u.time)||0,r=JSON.stringify(Object.assign(y.qualitySubscribeReportData,{dur:e,pices:Kt[null===(_=y.iceOldStatusData)||void 0===_?void 0:_.status],ices:Kt[null===(l=y.iceNewStatusData)||void 0===l?void 0:l.status],time:b}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUB_ICE_STATUS_S,r,t.LogSource.RTC)}if(!(null===(R=y.iceStatusData)||void 0===R?void 0:R.publishNotReport)&&(null===(C=y.iceStatusData)||void 0===C?void 0:C.publish)){y.iceStatusData.publishNotReport=!0;const e=y.iceStatusData.notFirst?0:(null===(h=y.iceNewStatusData)||void 0===h?void 0:h.start)-(null===(p=null===(g=y.iceStatusData)||void 0===g?void 0:g.publish)||void 0===p?void 0:p.time)||0,r=JSON.stringify(Object.assign(y.qualitySubscribeReportData,{dur:e,pices:Kt[null===(S=y.iceOldStatusData)||void 0===S?void 0:S.status],ices:Kt[null===(m=y.iceNewStatusData)||void 0===m?void 0:m.status],time:b}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_PUB_ICE_STATUS_S,r,t.LogSource.RTC)}y.iceStatusData.notFirst=!0;const e=JSON.stringify(Object.assign(y.qualitySubscribeReportData,{dur:(null===(T=y.iceNewStatusData)||void 0===T?void 0:T.start)-(null===(I=y.iceOldStatusData)||void 0===I?void 0:I.start),pices:Kt[null===(E=y.iceOldStatusData)||void 0===E?void 0:E.status],ices:Kt[null===(f=y.iceNewStatusData)||void 0===f?void 0:f.status],time:b,cncdts:[]}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,e,t.LogSource.RTC),this._reportStatsTimer&&this.stopAutoExecute(),this.startAutoExecute()}if("failed"===this._rtcPeerConn.iceConnectionState||"disconnected"===this._rtcPeerConn.iceConnectionState){const e=JSON.stringify(Object.assign(y.qualitySubscribeReportData,{dur:(null===(L=y.iceNewStatusData)||void 0===L?void 0:L.start)-(null===(v=y.iceOldStatusData)||void 0===v?void 0:v.start),pices:Kt[null===(O=y.iceOldStatusData)||void 0===O?void 0:O.status],ices:Kt[null===(A=y.iceNewStatusData)||void 0===A?void 0:A.status],time:b}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,e,t.LogSource.RTC),o.warn(`${this._pcName} iceconenction state is failed, exchange SDP to try again.`),t.logger.error(s.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:n.FAILED,code:"",msg:`${this._pcName} iceconenction state is ${this._rtcPeerConn.iceConnectionState}, exchange SDP to try again.`},{logSource:t.LogSource.RTC}),this._reTryExchange(),this._reTryExchangeTimer=setInterval(this._reTryExchange,15e3)}try{null===(N=null===(D=this._reportListener)||void 0===D?void 0:D.onICEConnectionStateChange)||void 0===N||N.call(D,this._rtcPeerConn.iceConnectionState,this._pcName)}catch(e){o.error("onICEConnectionStateChange error",e,this._pcName),t.logger.error(s.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:n.FAILED,code:"",msg:`${this._pcName}, ${e}`},{logSource:t.LogSource.RTC})}t.logger.info(s.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:n.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:t.LogSource.RTC})}_onTrackReady(r){if(!r.streams.length)return;const o=r.streams[0].id,{track:i}=r.receiver,n=[o,"audio"===i.kind?e.RCMediaType.AUDIO_ONLY:e.RCMediaType.VIDEO_ONLY].join("_");this._updateRecvTransceiverMap(n,r.transceiver);const a=At.getMemo();t.logger.info(s.L_QS_TRACK_READY_O,{identify:a.qualityStatusId},{logSource:t.LogSource.RTC}),this.emit(ur.__INNER_EVENT_TRACK_READY__,r)}setBitrate(e,o,i){return r(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(e,o,i),t.logger.info(s.L_RTC_PEER_CONNECTION_SET_BITRATE_O,{status:n.SUCCESSED,max:e,min:o,start:i},{logSource:t.LogSource.RTC})}))}createOffer(e){return r(this,void 0,void 0,(function*(){const r=yield this._sdpStrategy.createOffer(e);return o.debug(`offer -> ${JSON.stringify(r.sdp)}`),t.logger.info(s.L_RTC_PEER_CONNECTION_CREATE_OFFER_O,{status:n.SUCCESSED,offerSDP:r.sdp},{logSource:t.LogSource.RTC}),r}))}setRemoteAnswer(e){return r(this,void 0,void 0,(function*(){return o.debug(`answer -> ${JSON.stringify(e)}`),t.logger.info(s.L_RTC_PEER_CONNECTION_SET_REMOTE_ANSWER_O,{status:n.SUCCESSED,answer:e},{logSource:t.LogSource.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(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Me.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.on(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.on(Me.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),t.logger.info(s.L_RTC_PEER_CONNECTION_ADD_LOCAL_TRACK_O,{status:n.SUCCESSED,trackId:e.getTrackId()},{logSource:t.LogSource.RTC})}removeLocalTrackById(e){const r=this.getLocalTrack(e);r?(t.logger.info(s.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:n.SUCCESSED,trackId:e},{logSource:t.LogSource.RTC}),this.removeLocalTrack(r)):t.logger.warn(s.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:n.FAILED,code:"",msg:"track not found"},{logSource:t.LogSource.RTC})}removeAllLocalTrack(){Object.keys(this.pubLocalTracks).forEach((e=>{/_tiny$/.test(e)||this.removeLocalTrackById(e)})),t.logger.info(s.L_RTC_PEER_CONNECTION_REMOVE_ALL_LOCAL_TRACK_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC})}removeLocalTrack(e){const r=e.getTrackId();delete this.pubLocalTracks[r],this._sdpStrategy.removeLocalTrack(e),e.__innerSetPublished(!1),e.off(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Me.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this);const o=`${r}_tiny`,i=this.getLocalTrack(o);i&&(this._sdpStrategy.removeLocalTrack(i),delete this.pubLocalTracks[o],i.destroy()),t.logger.info(s.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_O,{status:n.SUCCESSED,trackId:r},{logSource:t.LogSource.RTC})}_updateRecvTransceiverMap(e,t){this._sdpStrategy.updateRecvTransceiverMap(e,t)}updateSubRemoteTracks(e){this._sdpStrategy.updateSubRemoteTracks(e),t.logger.info(s.L_RTC_PEER_CONNECTION_UPDATE_SUB_REMOTE_TRACKS_O,{status:n.SUCCESSED,trackIds:e.map((e=>e.getTrackId()))},{logSource:t.LogSource.RTC})}getOutboundVideoInfo(){return this._sdpStrategy.getOutboundVideoInfo()}_onLocalTrackMuted(e,r){const o=this.getLocalTrack(`${e.getTrackId()}_tiny`);o&&(o.__innerGetMediaStreamTrack().enabled=!e.isLocalMuted()),this.emit(Me.__INNER_EVENT_MUTED_CHANGE__,e,r),t.logger.info(s.L_RTC_PEER_CONNECTION_LOCAL_TRACK_MUTED_O,{status:n.SUCCESSED,trackId:e.getTrackId()},{logSource:t.LogSource.RTC})}_onLocalTrackDestroied(e){this.emit(Me.__INNER_EVENT_DESTROY__,e)}registerReportListener(e){this._reportListener=e}_createRCRTCStateReport(e){const{timestamp:t,iceCandidatePair:r,senders:o,receivers:i}=JSON.parse(JSON.stringify(e));null==r||delete r.totalPacketsLost;for(const e in r)Ct(r[e])&&delete r[e];return{timestamp:t,iceCandidatePair:r,senders:o.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: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})),pcName:this._pcName}}_getStatsData(e=1e3){var t,o,i;return r(this,void 0,void 0,(function*(){let r=null;if((null===(t=this._originReportStatsData)||void 0===t?void 0:t.timestamp)&&this._originReportStatsData.timestamp>Date.now()-e)r=this._originReportStatsData.data;else{const e=yield this._rtcPeerConn.getStats();r=null===(o=this.reportParser)||void 0===o?void 0:o.parseRTCStatsReport(e),this._originReportStatsData={data:r,timestamp:Date.now()}}return null===(i=this.reportParser)||void 0===i?void 0:i.formatRCRTCStateReport(r)}))}getAudioLevelReportData(e=1e3){var t,o,i;return r(this,void 0,void 0,(function*(){let r=null;if((null===(t=this._originReportStatsData)||void 0===t?void 0:t.timestamp)&&this._originReportStatsData.timestamp>Date.now()-e)r=this._originReportStatsData.data;else{const e=yield this._rtcPeerConn.getStats();r=null===(o=this.reportParser)||void 0===o?void 0:o.parseRTCStatsReport(e),this._originReportStatsData={data:r,timestamp:Date.now()}}if(!r)return[];return null===(i=this.reportParser)||void 0===i?void 0:i.getAudioLevelList(r)}))}_reportHandle(e){var t,o;return r(this,void 0,void 0,(function*(){const r=yield this._getStatsData(e);if(!r)return;this._reportStatsData=r;const i=this._createRCRTCStateReport(r);null===(o=null===(t=this._reportListener)||void 0===t?void 0:t.onStateReport)||void 0===o||o.call(t,i)}))}_getCacheStatsData(){return this._reportStatsData}_sendR3R4Data(){var e;return r(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 r(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,t.logger.info(s.L_RTC_PEER_CONNECTION_DESTROY_O,{status:n.SUCCESSED},{logSource:t.LogSource.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"}(Ht||(Ht={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(jt||(jt={}));class _r{constructor(e,t,r,o,i=jt.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=o,this._userRole=i}_send(e){return r(this,void 0,void 0,(function*(){let r=!1;if(this._context.getConnectionStatus()!==t.ConnectionStatus.CONNECTED)return r;return r=(yield this._context.setRTCState(this._roomId,e))===t.ErrorCode.SUCCESS,r}))}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=nt(),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(t){let r="";const o=t.split("_");if(t.includes("_tiny")){const t=o.pop(),i=parseInt(o.pop())===e.RCMediaType.AUDIO_ONLY?"audio":"video",s=o.pop();r=[o.join("_"),s,t,i].join("_")}else{const t=parseInt(o.pop())===e.RCMediaType.AUDIO_ONLY?"audio":"video",i=o.pop();r=[o.join("_"),i,t].join("_")}return r}sendR3R4Data(e){return r(this,void 0,void 0,(function*(){const{iceCandidatePair:t,senders:r,receivers:o}=e,i=(null==t?void 0:t.bitrateSend)||ft,s=(null==t?void 0:t.bitrateRecv)||ft,n=(null==t?void 0:t.networkType)||"unknown",a=(null==t?void 0:t.rtt)||ft,c=`${(null==t?void 0:t.IP)||ft}:${null==t?void 0:t.port}`,d=(null==t||t.remoteIP,null==t||t.remotePort,(null==t?void 0:t.availableIncomingBitrate)||ft),u=(null==t?void 0:t.availableOutgoingBitrate)||ft,_=(null==t?void 0:t.totalPacketsLost)||ft,l=this._context.getCurrentId();let R=`R3\t${i}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${u}\t${_}\t${l}\r`,C=`R4\t${s}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${u}\t${_}\t${l}\r`;const h=r.map((e=>{var t;const{trackId:r,audioLevel:o,samplingRate:i,bitrate:s,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:u,jitter:_,nackCount:l,pliCount:R,rtt:C,googFirsSent:h,encoderImplementation:g}=e,p=this._getPolarisTrackId(r),S=this._getRealResourceId(r);return{trackId:p,googCodecName:g||String(ft),audioLevel:o||0===o?o:ft,bitrate:s||0===s?s:ft,packetsLostRate:n||0===n?n:ft,frameRate:a||ft,resolution:c&&d?`${c} * ${d}`:"-1",jitter:_||ft,nackCount:l||0===l?l:ft,pliCount:R||0===R?R:ft,rtt:C||ft,googFirsSent:h,samplingRate:i,googRenderDelayMs:u,encoderImplementation:g||String(ft),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(S))||void 0===t?void 0:t.isLocalMuted())?Ht.DISABLE:Ht.ENABLE}})),g=o.filter((e=>!!e.trackId)).map((e=>{var t;const{trackId:r,audioLevel:o,samplingRate:i,bitrate:s,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:u,jitter:_,nackCount:l,pliCount:R,rtt:C,googFirsReceived:h,codecImplementationName:g}=e,p=this._getPolarisTrackId(r),S=this._getRealResourceId(r);return{trackId:p,googCodecName:g||String(ft),audioLevel:o||0===o?o:ft,bitrate:s||0===s?s:ft,packetsLostRate:n||0===n?n:ft,frameRate:a||ft,resolution:c&&d?`${c} * ${d}`:"-1",jitter:_||ft,nackCount:l||0===l?l:ft,pliCount:R||0===R?R:ft,rtt:C||ft,googFirsReceived:h,samplingRate:i,googRenderDelayMs:u,codecImplementationName:g||String(ft),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(S))||void 0===t?void 0:t.isLocalMuted())?Ht.DISABLE:Ht.ENABLE}}));let p=!1;R+=h.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&&(p=yield this._send(`${R}\r${this._userRole}`));let S=!1;return C+=g.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&&(S=yield this._send(`${C}\r${this._userRole}`)),!(!p&&!S)}))}sendR1(){const e=this._context.getCoreVersion(),t=navigator.platform,r=`R1\t5.5.2\t${e}\tweb\t${t}\t-1\t${_t.browser}\t${_t.version}\t${this._getClientID()}\t${this._userRole}`;this._send(r)}sendR2(e,t,r){const o=`R2\t${e}\t${t}\t${this._getClientID()}\r${r.join("\t")}\r${this._userRole}`;this._send(o)}}class lr{constructor(e){this._room=e,this._audioLevelChangeHandler=null,this._timer=null}_audioLevelReport(e){return r(this,void 0,void 0,(function*(){if(!this._audioLevelChangeHandler)return;const t=[],r=this._room.__getPC();for(let o=0;o<r.length;o++){const i=r[o];if("new"===i.getRTCPeerConn().iceConnectionState)return;const s=yield i.getAudioLevelReportData(e);null==s||s.forEach((e=>{const{userId:r}=rt(e.trackId),o=this._room.getCrtUserId()===r?this._room.getLocalTrack(e.trackId):this._room.getRemoteTrack(e.trackId);o&&t.push({track:o,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)}}e.RCRTCLiveRole=void 0,(Jt=e.RCRTCLiveRole||(e.RCRTCLiveRole={}))[Jt.ANCHOR=1]="ANCHOR",Jt[Jt.AUDIENCE=2]="AUDIENCE";class Rr{constructor(e=!1,t,r,o,i){this._useMutilPeerC=e,this._roomId=t,this._reTryExchange=r,this._currentUserId=o,this._polarisReport=i,this._mutilPeerC={}}get useMutilPeerC(){return this._useMutilPeerC}_isPub(e){if(!e.length)return!1;const{track:t}=e[0]instanceof Me||e[0]instanceof je?{track:e[0]}:e[0];return t.isLocalTrack()}_groupTracksByTag(e){const t={};return e.forEach((e=>{const{track:r}=e instanceof Me?{track:e}:e,o=r.getTag();t[o]?t[o].push(e):t[o]=[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),o=new ur(e,(()=>this._reTryExchange(e,r)),this._currentUserId,this._polarisReport);this._mutilPeerC[e]={pc:o,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 o=this._groupTracksByTag(e);for(const e in o){const i=this._genPCName(r,e),s=o[e];t.push(this._createOnePeerCItem(i,s))}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}=rt(e),o=this._genPCName(t,r);return this._mutilPeerC[o].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"}(qt||(qt={})),function(e){e.NORMAL="normal",e.MIDDLE="middle",e.TAIL="tail"}(Wt||(Wt={})),function(e){e[e.LOW=0]="LOW",e[e.NORMAL=1]="NORMAL",e[e.HIGH=2]="HIGH"}(Yt||(Yt={})),function(e){e[e.Destroy=40400]="Destroy"}(Qt||(Qt={}));class Cr{get priority(){return Yt.LOW}get kind(){return qt.Unknow}}class hr extends Cr{constructor(e=Wt.NORMAL){super(),this.state=e}get kind(){return qt.AsyncCommand}setState(e){this.state=e}pickoutSubscribed(e,t){const{unsubscribe:r,subscribe:o}=this.calcSubscribeList(e,t);return hr.AsyncSubscribeTasks=[],hr.AsyncUnsubscribeTasks=[],hr.AsyncUpdateSubscribeTasks=[],{subscribe:o,unsubscribe:r}}calcSubscribeList(e,t){const r=[],o=new Set,i=[],s=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)||o.has(t)||(r.push(e),o.add(t))})),n.forEach((e=>{const t=`${e.track.getTrackId()}_SUB_${e.subTiny?"0":"1"}`;this.trackInSubscribeList(e,a)||s.has(t)||(i.push(e),s.add(t))})),{unsubscribe:r,subscribe:i}}formateTrack(e){return e.map((e=>e instanceof je?{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}}hr.AsyncSubscribeTasks=[],hr.AsyncUnsubscribeTasks=[],hr.AsyncUpdateSubscribeTasks=[];class gr extends class{constructor(e,t,r,o,i,s,n,a,c){this.context=e,this.service=t,this.peerMgr=r,this.roomId=o,this.crtUserId=i,this.roomMode=s,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 o=this._remoteTracks[r];o.getUserId()===e&&t.push(o)}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}=rt(e);return this._roomResources[t].find((t=>tt(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 t in this._roomResources){const r=this._roomResources[t];t!==this.crtUserId&&0!==r.length&&r.forEach((t=>{const r=tt(t),{tag:o,userId:i,mediaType:s}=rt(r),n=s===e.RCMediaType.AUDIO_ONLY?new Je(o,i):new qe(o,i);n.__innerSetRemoteMuted(0===t.state),this._remoteTracks[r]=n}))}}initWithRoomData(e){this._sessionId=e.sessionId,this._token=e.token,this.isUpgrade?this._roomResources={}:this._roomResources=gt(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 pr 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 r(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 o;try{o=yield e.execute(this._store,this)}catch(e){return r(e),void this._next()}t(o),this._next()}))}push(e){return new Promise(((t,r)=>{if(this._isDestroyed)return;const{kind:o}=e;this._queue.length>0&&o===qt.AsyncCommand&&({command:e,resolve:t,reject:r}=this.commandOffset(e,t,r));const{priority:i}=e;if(i===Yt.LOW)this._queue.push({command:e,resolve:t,reject:r});else{const o=this._queue.findIndex((e=>e.command.priority<i)),s=-1===o?this._queue.length-1:o;this._queue.splice(s,0,{command:e,resolve:t,reject:r})}Promise.resolve().then((()=>{this._execute()}))}))}commandOffset(e,t,o){const i=this._queue.length-1;if(!(this._queue[i].command.kind===qt.AsyncCommand))return{command:e,resolve:t,reject:o};const[s]=this._queue.splice(i,1);s.command instanceof hr&&(s.command.setState(Wt.MIDDLE),e instanceof hr&&e.setState(Wt.TAIL));const n=e.execute;return e.execute=function(t,o){return r(this,void 0,void 0,(function*(){return s.command.execute.call(s.command,t,o),n.call(e,t,o)}))},{command:e,resolve:e=>{s.resolve.call(s,e),t(e)},reject:e=>{s.reject.call(s,e),o(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(t,r,o,i,s,n,a,c,d){super(new gr(t,r,o,i,s,n,a,c,d),e.RCRTCCode.ROOM_HAS_BEEN_DESTROYED)}get store(){return this._store}destroy(){super.destroy(),this._store.removeRemoteTracks()}}class Sr extends Cr{execute(e){return r(this,void 0,void 0,(function*(){const r=e.getResourcesByUserId(e.crtUserId),i=r.slice();r.length=0,o.info(`unpublish uris before rejoin -> ${JSON.stringify(i)}`);const s=yield e.context.setRTCTotalRes(e.roomId,We(Tt.UNPUBLISH,i),Ye([]),Tt.TOTAL_CONTENT_RESOURCE,Ye([]));s!==t.ErrorCode.SUCCESS?o.error(`unpublish uris before rejoin failed -> code: ${s}`):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"}(zt||(zt={})),e.RTCJoinType=void 0,(Zt=e.RTCJoinType||(e.RTCJoinType={}))[Zt.KICK=0]="KICK",Zt[Zt.REFUSE=1]="REFUSE",Zt[Zt.COEXIST=2]="COEXIST";class mr extends Cr{constructor(e,t,r,o,i,s){super(),this.roomId=e,this.roomType=t,this.joinType=r,this.livingType=o,this.innerUserDatas=i,this.outerUserDatas=s}get kind(){return qt.JoinRoom}execute(i,a){var c,d,u,_,l,R;return r(this,void 0,void 0,(function*(){const r=At.getMemo(),C={dur:0,cod:0,rid:"",rtp:this.roomType,csnid:"",snid:"",time:0,cr:"unknown",net:"unknown",uid:""};r.qualityJoinRoomReportData=C,r.joinRoomData={start:Date.now()};const{context:h,service:g}=i;let p=s.L_RTC_CLIENT_JOIN_RTC_ROOM_R;if(this.roomType===zt.LIVE?p=s.L_RTC_CLIENT_JOIN_LIVING_ROOM_R:this.roomType===zt.CROSS_MUTI&&(p=s.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_R),h.getConnectionStatus()!==t.ConnectionStatus.CONNECTED)return t.logger.error(p,{status:n.FAILED,code:e.RCRTCCode.SIGNAL_DISCONNECTED,msg:"im not connected"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_DISCONNECTED};if(g.detectorMediaSever(),ht(h.getNaviInfo()))return t.logger.error(p,{status:n.FAILED,code:e.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_usl error"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR};if(!t.validate("roomId",this.roomId,t.notEmptyString,!0))return t.logger.error(p,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(!t.validate("roomType",this.roomType,(e=>void 0!==zt[e])))return t.logger.error(p,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> roomType"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(!t.validate("outerUserDatas",this.outerUserDatas,t.isObject,!1))return t.logger.error(p,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(this.outerUserDatas){if(!Object.keys(this.outerUserDatas).every((e=>t.validate(`outerUserDatas.${e}`,this.outerUserDatas[e],t.isString,!0))))return t.logger.error(p,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR}}if(!g.getNaviMS().length)return t.logger.error(p,{status:n.FAILED,code:e.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};o.info(`joinRoom -> roomId: ${this.roomId}; joinType: ${this.joinType||e.RTCJoinType.KICK}`);const{code:S,data:m}=yield h.joinRTCRoom(this.roomId,this.roomType,this.livingType,this.joinType,this.innerUserDatas,this.outerUserDatas);if(S!==t.ErrorCode.SUCCESS||!m){const a=Date.now(),u=JSON.stringify(Object.assign(r.qualityJoinRoomReportData,{dur:a-((null===(c=r.joinRoomData)||void 0===c?void 0:c.start)||0),cod:S,rid:this.roomId,csnid:null===(d=r.clientData)||void 0===d?void 0:d.clientSessionId,snid:i.getSessionId(),time:a,uid:i.crtUserId}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_JOIN_ROOM_S,u,t.LogSource.RTC),o.warn(`joinRoom failed -> code: ${S}`);const _=40032===S?e.RCRTCCode.SIGNAL_JOIN_RTC_ROOM_REFUSED:S;return t.logger.error(p,{status:n.FAILED,code:_,msg:`joinRoom failed -> code: ${S}`},{logSource:t.LogSource.RTC}),{code:_}}o.info(`joinRoom success -> userId: ${h.getCurrentId()}, roomId: ${this.roomId}, data: ${JSON.stringify(m)}`);const T=Date.now(),I=JSON.stringify(Object.assign(r.qualityJoinRoomReportData,{dur:T-((null===(u=r.joinRoomData)||void 0===u?void 0:u.start)||0),cod:S,rid:this.roomId,csnid:null===(_=r.clientData)||void 0===_?void 0:_.clientSessionId,snid:m.sessionId,time:T,uid:i.crtUserId}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_JOIN_ROOM_S,I,t.LogSource.RTC),r.joinRoomData={start:null===(l=r.joinRoomData)||void 0===l?void 0:l.start,roomId:this.roomId},i.initWithRoomData(m);i.getResourcesByUserId(i.crtUserId).length>0&&a.push(new Sr);const E=null===(R=m.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===R?void 0:R.value;return E&&i.setCDNUris(JSON.parse(E)[0]),t.logger.info(p,{status:n.SUCCESSED,userId:i.crtUserId,roomId:this.roomId,data:m},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,data:m}}))}}function Tr(e,t,o,i){return r(this,void 0,void 0,(function*(){return{sdp:yield o.createOffer(t),extend:JSON.stringify({resolutionInfo:o.getOutboundVideoInfo()}),subscribeList:e.filter((e=>{const t=e.track.getTrackId(),{userId:r}=rt(t),o=i.getResourcesByUserId(r);if(!o)return!1;const s=o.filter((e=>t===`${e.msid}_${e.mediaType}`)).length;return s})).map((e=>({simulcast:e.subTiny?bt.TINY:bt.NORMAL,resolution:"",uri:i.getPublishedResourceByTrackId(e.track.getTrackId()).uri}))),switchstream:!1}}))}function Ir(i,s,n){return r(this,void 0,void 0,(function*(){const r=yield i.setRTCCDNUris(s,Tt.TOTAL_CONTENT_RESOURCE,JSON.stringify([n]));return r!==t.ErrorCode.SUCCESS?(o.error(`spreadCDNInfo failed -> code: ${r}`),{code:e.RCRTCCode.SIGNAL_ERROR}):(o.info("spreadCDNInfo succeed"),{code:e.RCRTCCode.SUCCESS})}))}function Er(i,s,n){return r(this,void 0,void 0,(function*(){const r=yield i.setRTCData(s,"cdn_uris",JSON.stringify([n]),!0,rr.ROOM);return r!==t.ErrorCode.SUCCESS?(o.error(`setRoomCDNInfo failed -> code: ${r}`),{code:e.RCRTCCode.SIGNAL_ERROR}):(o.info("setRoomCDNInfo succeed"),{code:e.RCRTCCode.SUCCESS})}))}function fr(o){return r(this,void 0,void 0,(function*(){const{context:r}=o,{roomId:i}=o,a=Object.assign({},o.getCDNUris(),{enableInnerCDN:o.getCDNEnable()});t.logger.info(s.L_LIVING_ROOM_SPREAD_CDN_INFO_T,{roomId:i,CDNUris:a},{logSource:t.LogSource.RTC});const c=(yield Promise.all([Ir(r,i,a),Er(r,i,a)])).every((t=>t.code===e.RCRTCCode.SUCCESS));return c?t.logger.info(s.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:n.SUCCESSED,CDNUris:a},{logSource:t.LogSource.RTC}):t.logger.error(s.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:n.FAILED,code:e.RCRTCCode.SIGNAL_ERROR,msg:"signal error"},{logSource:t.LogSource.RTC}),c?{code:e.RCRTCCode.SUCCESS}:{code:e.RCRTCCode.SIGNAL_ERROR}}))}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(Xt||(Xt={})),function(e){e.BEGIN="begin",e.END="end"}(er||(er={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(tr||(tr={})),function(e){e[e.ROOM=1]="ROOM",e[e.PERSON=2]="PERSON"}(rr||(rr={}));class Lr extends Cr{constructor(e,t){super(),this.headers=e,this.reqBody=t}execute(t,o){var i,s;return r(this,void 0,void 0,(function*(){const r=yield t.service.exchange(this.headers,this.reqBody);if(t.roomMode!==zt.LIVE)return r;const o=null===(s=null===(i=r.data)||void 0===i?void 0:i.urls)||void 0===s?void 0:s.pull_url;if(r.code!==e.RCRTCCode.SUCCESS||!o)return r;const n=JSON.parse(o);return t.setCDNUris(n),(null==n?void 0:n.broadcast)===tr.SPREAD&&(t.setCDNEnabel(!0),fr(t)),r}))}}class vr extends Cr{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(i,n){var a,c;return r(this,void 0,void 0,(function*(){const{tracks:r,forceReq:d}=this,{roomId:u}=i;if(!t.validate("tracks",r,(()=>t.isArray(r)&&r.every((e=>e instanceof je||e.track instanceof je))),!0))return o.warn(`update sublist failed, tracks is invalid -> roomId: ${u}`),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`update subscribe list -> roomId: ${u}, forceReq: ${d}, tracks: ${r.map(St)}`);let _=r.map((e=>e instanceof je?{track:e}:Object.assign({},e)));const l={};_=_.filter((e=>{const t=e.track.getTrackId();return i.getRemoteTrack(t)?!l[t]&&(l[t]=!0,!0):(o.warn(`track cannot found in room -> trackId: ${t}`),!1)})).map((e=>Object.assign({},e)));const R=i.getSubscribedList().map((e=>Object.assign({},e)));if(!d){let t=!1;if(_.forEach((e=>{const r=R.findIndex((t=>t.track===e.track));if(-1===r)return void(t=!0);R.splice(r,1)[0].subTiny!==e.subTiny&&(t=!0)})),R.length&&(t=!0),!t)return{code:e.RCRTCCode.SUCCESS}}const{pc:C,pushOtherRooms:h,headers:g}=this.subhook(r);C.updateSubRemoteTracks(_.map((e=>e.track)));const p=At.getMemo();t.logger.info(s.L_QS_CREATE_OFFER_O,{identify:p.qualityStatusId},{logSource:t.LogSource.RTC});const S={dur:0,cod:0,rid:i.roomId,csnid:null===(a=p.clientData)||void 0===a?void 0:a.clientSessionId,snid:i.getSessionId(),rsid:"",msa:"",msas:[],time:0,resid:"",mtp:0,smct:1,cr:"unknown",net:"unknown",uid:"",stp:0};p.qualitySubscribeReportData=S,p.subscribeData={start:Date.now()};const m={dur:0,cod:0,rid:i.roomId,csnid:null===(c=p.clientData)||void 0===c?void 0:c.clientSessionId,snid:i.getSessionId(),rsid:"",msa:"",msas:[],time:0,resid:"",mtp:0,smct:1,uid:"",stp:0};p.qualityUnsubscribeReportData=m,p.unsubscribeData={start:Date.now()};const T=yield Tr(_,!1,C,i);h&&(T.pushOtherRooms=h),t.logger.info(s.L_QS_SUBSCRIBE_EXCHANGE_O,{identify:p.qualityStatusId},{logSource:t.LogSource.RTC});const I=yield new Lr(g,T).execute(i,n),E=_.map((e=>e.track.getTrackId()));if(I.code!==e.RCRTCCode.SUCCESS){let e=[],r=Date.now();return p.mediaService.forEach((t=>{e.push({rsid:t.reqId,rsdur:t.end-t.start,msa:t.url,rscod:t.rscod})})),p.subscribeCommand&&(p.subscribeCommand=!1,_.forEach((o=>{var i,n;const a=JSON.stringify(Object.assign(p.qualitySubscribeReportData,{dur:r-((null===(i=p.subscribeData)||void 0===i?void 0:i.start)||0),cod:I.code,msas:e,time:r,resid:o.track.getTrackId(),mtp:rt(o.track.getTrackId()).mediaType,smct:o.track instanceof we&&(null===(n=o.track)||void 0===n?void 0:n.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,a,t.LogSource.RTC)}))),p.unsubscribeCommand&&(p.unsubscribeCommand=!1,_.forEach((o=>{var i,n;const a=JSON.stringify(Object.assign(p.qualityUnsubscribeReportData,{dur:r-((null===(i=p.unsubscribeData)||void 0===i?void 0:i.start)||0),cod:I.code,time:r,msas:e,resid:o.track.getTrackId(),mtp:rt(o.track.getTrackId()).mediaType,smct:o.track instanceof we&&(null===(n=o.track)||void 0===n?void 0:n.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,a,t.LogSource.RTC)}))),{code:I.code}}const{sdp:f,resultCode:L,message:v,subscribedList:O}=I.data;if(L!==e.RCRTCCode.SUCCESS){let e=[],r=Date.now();return p.mediaService.forEach((t=>{e.push({rsid:t.reqId,rsdur:t.end-t.start,msa:t.url,rscod:t.rscod})})),p.subscribeCommand&&(p.subscribeCommand=!1,_.forEach((o=>{var i,n;const a=JSON.stringify(Object.assign(p.qualitySubscribeReportData,{dur:r-((null===(i=p.subscribeData)||void 0===i?void 0:i.start)||0),cod:L,msas:e,time:r,resid:o.track.getTrackId(),mtp:rt(o.track.getTrackId()).mediaType,smct:o.track instanceof we&&(null===(n=o.track)||void 0===n?void 0:n.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,a,t.LogSource.RTC)}))),p.unsubscribeCommand&&(p.unsubscribeCommand=!1,_.forEach((o=>{var i,n;const a=JSON.stringify(Object.assign(p.qualityUnsubscribeReportData,{dur:r-((null===(i=p.unsubscribeData)||void 0===i?void 0:i.start)||0),cod:L,msas:e,time:r,resid:o.track.getTrackId(),mtp:rt(o.track.getTrackId()).mediaType,smct:o.track instanceof we&&(null===(n=o.track)||void 0===n?void 0:n.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,a,t.LogSource.RTC)}))),o.error(`change subscribe list failed: ${L}`),{code:L}}t.logger.info(s.L_QS_GET_ANSWER_O,{identify:p.qualityStatusId},{logSource:t.LogSource.RTC}),o.debug(`subscribe success: ${E.join(",")}`);const A=yield C.setRemoteAnswer(f.sdp);if(A!==e.RCRTCCode.SUCCESS){let e=[],r=Date.now();return p.mediaService.forEach((t=>{e.push({rsid:t.reqId,rsdur:t.end-t.start,msa:t.url,rscod:t.rscod})})),p.subscribeCommand&&(p.subscribeCommand=!1,_.forEach((o=>{var i,n;const a=JSON.stringify(Object.assign(p.qualitySubscribeReportData,{dur:r-((null===(i=p.subscribeData)||void 0===i?void 0:i.start)||0),cod:A,msas:e,time:r,resid:o.track.getTrackId(),mtp:rt(o.track.getTrackId()).mediaType,smct:o.track instanceof we&&(null===(n=o.track)||void 0===n?void 0:n.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,a,t.LogSource.RTC)}))),p.unsubscribeCommand&&(p.unsubscribeCommand=!1,_.forEach((o=>{var i,n;const a=JSON.stringify(Object.assign(p.qualityUnsubscribeReportData,{dur:r-((null===(i=p.unsubscribeData)||void 0===i?void 0:i.start)||0),cod:A,msas:e,time:r,resid:o.track.getTrackId(),mtp:rt(o.track.getTrackId()).mediaType,smct:o.track instanceof we&&(null===(n=o.track)||void 0===n?void 0:n.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,a,t.LogSource.RTC)}))),{code:A}}let D=[],N=Date.now();p.mediaService.forEach((e=>{D.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),p.subscribeCommand&&(p.subscribeCommand=!1,_.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(p.qualitySubscribeReportData,{dur:N-((null===(r=p.subscribeData)||void 0===r?void 0:r.start)||0),cod:A,msas:D,time:N,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,i,t.LogSource.RTC)}))),p.unsubscribeCommand&&(p.unsubscribeCommand=!1,_.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(p.qualityUnsubscribeReportData,{dur:N-((null===(r=p.unsubscribeData)||void 0===r?void 0:r.start)||0),cod:A,msas:D,time:N,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,i,t.LogSource.RTC)}))),p.iceStatusData?p.iceStatusData.subscribe={time:Date.now()}:p.iceStatusData={};const b=null==O?void 0:O.map((e=>`${e.msid}_${e.mediaType}`)),y=_.filter((e=>null==b?void 0:b.includes(e.track.getTrackId()))),k=_.filter((e=>!(null==b?void 0:b.includes(e.track.getTrackId())))),U=i.getRemoteTracks();for(const e in U){const t=y.some((t=>t.track.getTrackId()===e));U[e].__innerSetSubscribed(t);const r=y.some((t=>t.track.getTrackId()===e&&t.subTiny));U[e].isVideoTrack()&&U[e].__innerSetIsTinyTrack(r)}return i.resetSubscribedList(y),t.logger.info(s.L_QS_GET_RESOURCES_O,{identify:p.qualityStatusId},{logSource:t.LogSource.RTC}),k.length?{code:e.RCRTCCode.SUCCESS,failedList:k}:{code:e.RCRTCCode.SUCCESS}}))}}class Or extends Cr{constructor(e,t){super(),this.tracks=e,this.subhook=t}execute(i,a){return r(this,void 0,void 0,(function*(){const{tracks:r}=this,{roomId:c}=i;if(t.logger.info(s.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:r.map(St)},{logSource:t.LogSource.RTC}),!t.validate("tracks",r,(()=>t.isArray(r)&&r.length>0&&r.every((e=>e instanceof je))),!0))return o.warn(`unsubscribe failed, tracks is invalid -> roomId: ${c}`),t.logger.warn(s.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`unsubscribe -> roomId: ${c}, tracks: ${r.map(St)}`);const d=i.getSubscribedList().map((e=>Object.assign({},e))).filter((e=>!r.includes(e.track)));i.polarisReport.sendR2(Xt.SUBSCRIBE,er.END,r.map((e=>e.getTrackId()))),t.logger.info(s.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:r.map(St),roomId:c},{logSource:t.LogSource.RTC});return At.getMemo().unsubscribeCommand=!0,new vr(d,this.subhook,!1).execute(i,a)}))}}class Ar extends Cr{constructor(e,t){super(),this.msgContent=e,this.subhook=t}get priority(){return Yt.NORMAL}execute(e,t){return r(this,void 0,void 0,(function*(){const r=[],i=[],s=[],n=[],a={joined:r,left:i,upgrade:s,downgrade:n},{users:c}=this.msgContent;if(0===c.length)return a;for(let t=0;t<c.length;t++){const r=c[t];if(r.extra&&r.extra.roomId!==e.roomId)return a;if(1==+r.state&&!e.getRemoteUserIds().includes(r.userId))return a}c.forEach((t=>{const{userId:a}=t;if(0==+t.state){o.info(`user joined -> ${a}`);const i=e.getResourcesByUserId(a);i||(t.switchRoleType?s.push(a):r.push(a)),e.setResourcesByUserId(a,i||[])}else o.info(`user left -> ${a}`),t.switchRoleType?n.push(a):i.push(a)}));const d=[...i,...n];if(d.length){const r=[],o=[];d.forEach((t=>{r.push(...e.getRemoteTracksByUserId(t)),o.push(t)})),r.length&&(yield new Or(r,this.subhook).execute(e,t),r.forEach((t=>e.removeRemoteTrack(t.getTrackId())))),o.length&&o.forEach((t=>e.removeResourcesByUserId(t)))}return a}))}}class Dr extends Cr{constructor(e,t,r){super(),this.subhook=e,this.tracks=t,this.onTrackUnpublish=r}execute(e,t){return r(this,void 0,void 0,(function*(){const{tracks:r}=this;yield new Or(r,this.subhook).execute(e,t),r.forEach((t=>{t.__innerDestroy(),e.removeRemoteTrack(t.getTrackId())})),this.onTrackUnpublish(r)}))}}class Nr extends Cr{constructor(e,t,r,o,i){super(),this.msgContent=e,this.messageType=t,this.senderId=r,this.subhook=o,this.callback=i}get priority(){return Yt.NORMAL}execute(t,i){var s,n;return r(this,void 0,void 0,(function*(){const{uris:r}=this.msgContent,a=[],c=[],d=[];let u;const _=this.senderId,{messageType:l}=this,R=t.getResourcesByUserId(_)||[];switch(t.setResourcesByUserId(_,R),l){case Tt.MODIFY:d.push(...r);break;case Tt.PUBLISH:a.push(...r);break;case Tt.UNPUBLISH:c.push(...r);break;case Tt.TOTAL_CONTENT_RESOURCE:u=st(R,r),a.push(...u.publishedList),c.push(...u.unpublishedList),d.push(...u.modifiedList)}if(a.length>0){const r=R.map(tt),s=[],n=[];if(a.forEach((o=>{const i=tt(o),a=r.indexOf(i),{userId:c,tag:d,mediaType:u}=rt(i);a>-1?R[a]=o:R.push(o);let _=t.getRemoteTrack(i);_?_.isSubscribed()&&s.push(_):(_=u===e.RCMediaType.AUDIO_ONLY?new Je(d,c):new qe(d,c),t.addRemoteTrack(_),n.push(_)),_.__innerSetRemoteMuted(0===o.state)})),s.length){const r=s.map((e=>e.getTrackId()));o.debug(`resub tracks -> ${JSON.stringify(r)}`);const{code:n}=yield new vr(s,this.subhook).execute(t,i);n!==e.RCRTCCode.SUCCESS&&o.error(`resub tracks failed -> code: ${n}, ids: ${JSON.stringify(r)}`)}this.callback.onTrackPublish(n)}if(c.length>0){const e=c.map(tt);for(let t=R.length-1;t>=0;t-=1){const r=R[t];e.includes(tt(r))&&R.splice(t,1)}const r=c.map((e=>{const r=tt(e);return t.getRemoteTrack(r)}));yield new Dr(this.subhook,r,this.callback.onTrackUnublish).execute(t,i)}if(d.length>0){const e=R.map(tt);for(let r=0;r<d.length;r+=1){const o=d[r],i=tt(o),s=e.indexOf(i);R[s].state=o.state;const n=t.getRemoteTrack(i);n.__innerSetRemoteMuted(0===o.state),n.isAudioTrack()?this.callback.onAudioMute(n):this.callback.onVideoMute(n)}}if(t.roomMode!==zt.LIVE)return;const C=this.msgContent;if(!C.cdn_uris)return;const h=(null===(s=t.getCDNUris())||void 0===s?void 0:s.enableInnerCDN)!==C.cdn_uris[0].enableInnerCDN;t.setCDNUris(C.cdn_uris[0]),h&&this.callback.onCDNEnableChange(!!(null===(n=t.getCDNUris())||void 0===n?void 0:n.enableInnerCDN))}))}}class br extends Cr{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(i,a){return r(this,void 0,void 0,(function*(){const{tracks:r,forceReq:c}=this,{roomId:d}=i;if(t.logger.info(s.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:r.map(St),forceReq:c},{logSource:t.LogSource.RTC}),!t.validate("tracks",r,(()=>t.isArray(r)&&r.length>0&&r.every((e=>e instanceof je||e.track instanceof je))),!0))return o.warn(`subscribe failed, tracks is invalid -> roomId: ${d}`),t.logger.error(s.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`subscribe -> roomId: ${d}, tracks: ${r.map(St)}`);const u=i.getSubscribedList().map((e=>Object.assign({},e))),_=r.map((e=>e instanceof je?{track:e}:e));let l=!1;const R=[];if(_.forEach((e=>{const t=e.track.getTrackId();R.push(t);const r=u.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:u.push(e),l=!0)})),!l&&!c)return t.logger.warn(s.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:n.FAILED,code:"",msg:"repeat subscribe"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS};i.polarisReport.sendR2(Xt.SUBSCRIBE,er.BEGIN,R),t.logger.info(s.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:r.map(St),roomId:d},{logSource:t.LogSource.RTC});return At.getMemo().subscribeCommand=!0,new vr(u,this.subhook,!0).execute(i,a)}))}}class yr extends Cr{constructor(e,t){super(),this.tracks=e,this.pubhook=t}get kind(){return qt.Publish}_removePubFailedTracks(e,t){e.forEach((e=>{const r=e instanceof Me?e:e.track;o.debug(`remove pub failed track from peerconnection -> trackId: ${r.getTrackId()}`),t.removeLocalTrackById(r.getTrackId())}))}__publish(i,a,c,d,u){var _;return r(this,void 0,void 0,(function*(){const{pcName:r,pc:l,headers:R}=a,{roomId:C}=i,h=[];c.forEach((e=>{const{track:t}=e instanceof Me?{track:e}:e;h.push(t)})),c.sort(((e,t)=>{const{track:r}=e instanceof Me?{track:e}:e,{max:o}=r.getBitrate(),{track:i}=t instanceof Me?{track:t}:t,{max:s}=i.getBitrate();return o-s}));if(l.getLocalTracks().length+((e,t)=>{let r=0;return e.forEach((e=>{const o=e instanceof Me?e.getTrackId():e.track.getTrackId();t.getLocalTrack(o)||(e instanceof Me?r++:e.pubTiny&&e.track.isVideoTrack()&&(r+=2))})),r})(c,l)>10)return o.error(`publish failed, tracks limit exceeded -> roomId: ${C}`),{code:e.RCRTCCode.PUBLISH_TRACK_LIMIT_EXCEEDED,tracks:h};o.debug(`publish tracks -> roomId: ${C}, tracks: ${c.map(St)}`);for(let t=0;t<c.length;t++){const r=c[t],{track:i,pubTiny:s}=r instanceof Me?{pubTiny:!1,track:r}:r;if(i.isVideoTrack()&&s){let t;try{t=i.__innerGetMediaStreamTrack().clone();const r=s.frameRate||e.RCFrameRate.FPS_15,o=s.resolution||e.RCResolution.W176_H144,{width:n,height:a}=at(o),c=ut(r);yield t.applyConstraints({width:n,height:a,frameRate:c})}catch(e){null==t||t.stop(),o.warn(`pubTiny failed -> id: ${i.getTrackId()}, msg: ${e.message}`);break}l.addLocalTrack(new we(i.getTag(),i.getUserId(),t,!0))}l.addLocalTrack(i)}l.clearReTryExchangeTimer();const g=i.useMutilPeerC?[]:i.getSubscribedList(),p=`${Date.now()}`,S=At.getMemo();S.qualityStatus=p,t.logger.info(s.L_QS_CREATE_OFFER_O,{identify:p},{logSource:t.LogSource.RTC});const m={dur:0,cod:0,rid:i.roomId,csnid:null===(_=S.clientData)||void 0===_?void 0:_.clientSessionId,snid:i.getSessionId(),rsid:"",msa:"",msas:[],sigs:[],time:0,resid:"",mtp:0,smct:1,cr:"unknown",net:"unknown",uid:i.crtUserId,stp:0};S.qualityPublishReportData=m,S.publish={start:Date.now()};const T=yield Tr(g,!1,l,i);d&&(T.pushOtherRooms=d),t.logger.info(s.L_QS_PUBLISH_EXCHANGE_O,{identify:p},{logSource:t.LogSource.RTC});const I=yield new Lr(R,T).execute(i,u);if(I.code!==e.RCRTCCode.SUCCESS){const e=Date.now();let r=[];return S.mediaService.forEach((e=>{r.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),h.forEach((o=>{var i;const n=JSON.stringify(Object.assign(S.qualityPublishReportData,{dur:e-((null===(i=S.publish)||void 0===i?void 0:i.start)||0),cod:I.code,msas:r,time:e,resid:o.getTrackId(),mtp:rt(o.getTrackId()).mediaType,smct:o instanceof we&&o.__isTiny()?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_PUBLISH_S,n,t.LogSource.RTC)})),o.error(`publish failed -> roomId: ${C}, code: ${I.code}`),this._removePubFailedTracks(c,l),{code:I.code,tracks:h}}t.logger.info(s.L_QS_GET_ANSWER_O,{status:n.SUCCESSED,identify:p},{logSource:t.LogSource.RTC});const{sdp:E,resultCode:f,message:L}=I.data;if(f!==e.RCRTCCode.SUCCESS){const e=Date.now();let r=[];return S.mediaService.forEach((e=>{r.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),h.forEach((o=>{var i;const n=JSON.stringify(Object.assign(S.qualityPublishReportData,{dur:e-((null===(i=S.publish)||void 0===i?void 0:i.start)||0),cod:f,msas:r,time:e,resid:o.getTrackId(),mtp:rt(o.getTrackId()).mediaType,smct:o instanceof we&&o.__isTiny()?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_PUBLISH_S,n,t.LogSource.RTC)})),o.error(`publish failed -> roomId: ${C}, code: ${f}, msg: ${L}`),this._removePubFailedTracks(c,l),{code:f,tracks:h}}const v=yield l.setRemoteAnswer(E.sdp);if(v!==e.RCRTCCode.SUCCESS){const e=Date.now();let r=[];return S.mediaService.forEach((e=>{r.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),h.forEach((o=>{var i;const n=JSON.stringify(Object.assign(S.qualityPublishReportData,{dur:e-((null===(i=S.publish)||void 0===i?void 0:i.start)||0),cod:v,msas:r,time:e,resid:o.getTrackId(),mtp:rt(o.getTrackId()).mediaType,smct:o instanceof we&&o.__isTiny()?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_PUBLISH_S,n,t.LogSource.RTC)})),{code:v,tracks:h}}return Object.assign(Object.assign({},I),{tracks:h})}))}_mergePublishRes(i,n){return r(this,void 0,void 0,(function*(){const r=n.crtUserId,{roomId:a}=n;let c="";const d=[],u=n.getResourcesByUserId(r),_=[...u];let l=[];i.forEach((t=>{if(t.code!==e.RCRTCCode.SUCCESS){const{tracks:e}=t;return void d.push({code:t.code,tracks:e})}const{publishList:r,urls:o,mcuPublishList:i}=t.data;c=null==o?void 0:o.liveUrl;r.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:n.getTrackState(tt(e))},e))).forEach((e=>{const{isInclude:t,index:r}=((e,t)=>{let r=!1,o=0;for(let i=0;i<t.length;i++){const s=t[i];if(`${e.msid}_${e.mediaType}`==`${s.msid}_${s.mediaType}`){r=!0,o=i;break}}return{isInclude:r,index:o}})(e,_);t?_.splice(r,1,e):_.push(e)}));const s=(null==i?void 0:i.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))))||[];l=s}));const{publishedList:R}=st(u,_),C=At.getMemo();C.publishSignalTotal={start:Date.now()};const h=yield n.context.setRTCTotalRes(a,We(Tt.PUBLISH,R),Ye(_),Tt.TOTAL_CONTENT_RESOURCE,Ye(l));if(h!==t.ErrorCode.SUCCESS){const r=Date.now();let i=[];C.mediaService.forEach((e=>{i.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const n=[];return n.push({dur:Date.now()-(C.publishSignalTotal.start||0),cod:h}),_.forEach((e=>{var o;const a=JSON.stringify(Object.assign(C.qualityPublishReportData,{dur:r-((null===(o=C.publish)||void 0===o?void 0:o.start)||0),cod:h,msas:i,sigs:n,time:r,resid:tt(e),mtp:e.mediaType,smct:e.simulcast}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_PUBLISH_S,a,t.LogSource.RTC)})),o.error(`send publish streams notification failed: ${h}`),{code:e.RCRTCCode.SIGNAL_ERROR}}const g=Date.now();let p=[];C.mediaService.forEach((e=>{p.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const S=[];S.push({dur:Date.now()-(C.publishSignalTotal.start||0),cod:h}),_.forEach((e=>{var r;const o=JSON.stringify(Object.assign(C.qualityPublishReportData,{dur:g-((null===(r=C.publish)||void 0===r?void 0:r.start)||0),cod:h,msas:p,sigs:S,time:g,resid:tt(e),mtp:e.mediaType,smct:e.simulcast}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_PUBLISH_S,o,t.LogSource.RTC)})),C.iceStatusData?C.iceStatusData.publish={time:Date.now()}:C.iceStatusData={},n.setResourcesByUserId(r,_);const m=R.map((e=>tt(e)));n.polarisReport&&n.polarisReport.sendR2(Xt.PUBLISH,er.BEGIN,m),R.forEach((e=>{const t=n.useMutilPeerC?`${a}_${(e=>{const t=e.split("_");return{tag:t.pop(),userId:t.join("_")}})(e.msid).tag}`:`${a}_pub`,{pc:r}=n.peerMgr.getPCItemByPCName(t);r.getLocalTrack(`${e.msid}_${e.mediaType}`).__innerSetPublished(!0)})),o.debug(`publish success: ${m.join(",")}`);const T={code:e.RCRTCCode.SUCCESS};return c&&(T.liveUrl=c),d.length&&(T.failedTracks=d,T.code=e.RCRTCCode.SOME_TRACKS_PUBLISH_FAILED),T}))}execute(i,a){return r(this,void 0,void 0,(function*(){let{tracks:r}=this;const{roomId:c}=i;if(t.logger.info(s.L_ABSTRACT_ROOM_PUBLISH_T,{trackIds:r.map(St)},{logSource:t.LogSource.RTC}),!t.validate("tracks",r,(()=>t.isArray(r)&&r.length>0&&r.every((e=>e instanceof Me||e.track instanceof Me))),!0))return o.warn(`publish failed, tracks is invalid -> roomId: ${c}`),t.logger.error(s.L_ABSTRACT_ROOM_PUBLISH_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(r=r.filter((e=>{const{track:r}=e instanceof Me?{track:e}:e,o=r.isDestroyed();return o&&t.logger.warn(s.L_ABSTRACT_ROOM_PUBLISH_R,{status:n.FAILED,msg:`track -> ${r.getTrackId()} has beem destroyed`}),!o})),!r.length)return{code:e.RCRTCCode.PUBLISH_TRACKS_IS_INVALID};const d=[],{plist:u,pushOtherRooms:_}=this.pubhook(r);for(let e=0;e<u.length;e++){const t=u[e];d.push(this.__publish(i,t,t.tracks,_,a))}const l=yield Promise.all(d),R=yield this._mergePublishRes(l,i);return t.logger.info(s.L_ABSTRACT_ROOM_PUBLISH_R,{status:n.SUCCESSED,roomId:c,trackIds:r.map(St)},{logSource:t.LogSource.RTC}),R}))}}class kr extends Cr{constructor(e,t){super(),this.tracks=e,this.unpubhook=t}get kind(){return qt.UnPublish}__unpublish(i,n,a,c){var d;return r(this,void 0,void 0,(function*(){const{pcName:r,pc:u}=a,_=c.map((e=>e.getTrackId()));if(0===_.map(i.getPublishedResourceByTrackId.bind(i)).filter((e=>!!e)).length)return{code:e.RCRTCCode.SUCCESS,tracks:c};_.forEach((e=>u.removeLocalTrackById(e))),i.polarisReport.sendR2(Xt.PUBLISH,er.END,_),u.clearReTryExchangeTimer();const l=i.useMutilPeerC?[]:i.getSubscribedList(),R=At.getMemo(),C={dur:0,cod:0,rid:i.roomId,csnid:null===(d=R.clientData)||void 0===d?void 0:d.clientSessionId,snid:i.getSessionId(),rsid:"",msa:"",msas:[],sigs:[],time:0,resid:"",mtp:0,smct:1,uid:i.crtUserId,stp:0};R.qualityUnpublishReportData=C,R.unpublish={start:Date.now()};const h=yield Tr(l,!1,u,i),{pushOtherRooms:g,headers:p}=this.unpubhook(c,r);g&&(h.pushOtherRooms=g);const S=yield new Lr(p,h).execute(i,n);if(S.code!==e.RCRTCCode.SUCCESS){const e=Date.now();return c.forEach((r=>{var o;const i=r.getTrackId(),n=JSON.stringify(Object.assign(R.qualityUnpublishReportData,{dur:e-((null===(o=R.unpublish)||void 0===o?void 0:o.start)||0),cod:S.code,time:e,resid:i,mtp:rt(i).mediaType,smct:r instanceof we&&r.__isTiny()?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNPUBLISH_S,n,t.LogSource.RTC)})),o.error(`exchange failed -> code: ${S.code}`),{code:S.code,tracks:c}}return Object.assign(Object.assign({},S),{tracks:c})}))}_mergeUnpublishRes(i,n){return r(this,void 0,void 0,(function*(){const a=i.context.getCurrentId(),{roomId:c}=i,d=At.getMemo(),u=[],_=[],l=[],R=[];let C=[];for(let r=0;r<n.length;r++){const a=n[r];if(a.code!==e.RCRTCCode.SUCCESS){const{tracks:e}=a;_.push({code:a.code,tracks:e});continue}const{resultCode:c,message:h,mcuPublishList:g}=a.data;if(c!==e.RCRTCCode.SUCCESS){const e=Date.now();let r=[];d.mediaService.forEach((e=>{r.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),l.forEach((o=>{var i;if(o){const n=JSON.stringify(Object.assign(d.qualityUnpublishReportData,{dur:e-((null===(i=d.publish)||void 0===i?void 0:i.start)||0),cod:c,msas:r,time:e,resid:tt(o),mtp:o.mediaType,smct:o.simulcast}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNPUBLISH_S,n,t.LogSource.RTC)}})),o.error(`unpublish streams failed -> code: ${c}, msg: ${h}`)}const p=a.tracks.map((e=>e.getTrackId()));R.push(...p);const S=p.map(i.getPublishedResourceByTrackId.bind(i)).filter((e=>!!e));l.push(...S),u.push(a);const m=g?g.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[];C=m}const h=i.getResourcesByUserId(a),g=h.filter((e=>!l.includes(e)));d.unPublishSignalTotal={start:Date.now()};const p=yield i.context.setRTCTotalRes(c,We(Tt.UNPUBLISH,l),Ye(g),Tt.TOTAL_CONTENT_RESOURCE,Ye(C));if(p!==t.ErrorCode.SUCCESS){const r=Date.now();let i=[];d.mediaService.forEach((e=>{i.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const n=[];return n.push({dur:Date.now()-(d.unPublishSignalTotal.start||0),cod:p}),h.forEach((e=>{var o;const a=JSON.stringify(Object.assign(d.qualityUnpublishReportData,{dur:r-((null===(o=d.publish)||void 0===o?void 0:o.start)||0),cod:p,msas:i,sigs:n,time:r,resid:tt(e),mtp:e.mediaType,smct:e.simulcast}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNPUBLISH_S,a,t.LogSource.RTC)})),o.error("send unpublish notification failed:",p),{code:e.RCRTCCode.SIGNAL_ERROR}}o.debug(`unpublish success -> tracks: ${R.join(",")}`);const S=Date.now();let m=[];d.mediaService.forEach((e=>{m.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const T=[];T.push({dur:Date.now()-(d.unPublishSignalTotal.start||0),cod:p}),h.forEach((r=>{var o;const i=JSON.stringify(Object.assign(d.qualityUnpublishReportData,{dur:S-((null===(o=d.publish)||void 0===o?void 0:o.start)||0),cod:e.RCRTCCode.SUCCESS,msas:m,sigs:T,time:S,resid:tt(r),mtp:r.mediaType,smct:r.simulcast}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNPUBLISH_S,i,t.LogSource.RTC)})),u.forEach((e=>r(this,void 0,void 0,(function*(){const{sdp:t}=e.data,{tracks:r}=e,o=i.peerMgr.getPCByTrackId(r[0].getTrackId());yield o.setRemoteAnswer(t.sdp)})))),i.setResourcesByUserId(a,g);const I={code:e.RCRTCCode.SUCCESS};return _.length&&(I.failedTracks=_,I.code=e.RCRTCCode.SOME_TRACKS_PUBLISH_FAILED),I}))}execute(i,a){return r(this,void 0,void 0,(function*(){const{crtUserId:r,roomId:c}=i,{tracks:d}=this;t.logger.info(s.L_ABSTRACT_ROOM_UNPUBLISH_T,{trackIds:d.map(St)},{logSource:t.LogSource.RTC});if(!t.validate("tracks",d,(()=>d.every((e=>e.getUserId()===r&&e instanceof Me))),!0))return o.warn(`unpublish failed, tracks is invalid -> roomId: ${c}, tracks: ${d.map(St)}`),t.logger.error(s.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};const u=i.peerMgr.createPeerCList(d),_=[];for(let e=0;e<u.length;e++){const{tracks:t}=u[e];_.push(this.__unpublish(i,a,u[e],t))}const l=yield Promise.all(_);let R=l.length;if(l.forEach((t=>{t.code!==e.RCRTCCode.SUCCESS||t.data||(R-=1)})),0===R)return{code:e.RCRTCCode.SUCCESS};const C=yield this._mergeUnpublishRes(i,l);return t.logger.info(s.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:n.SUCCESSED,roomId:c,trackIds:d.map(St)},{logSource:t.LogSource.RTC}),C}))}}class Ur extends Cr{constructor(e,t){super(),this.localTrack=e,this._recvSignalResultFn=t}execute(e,i){return r(this,void 0,void 0,(function*(){const{localTrack:r}=this,i=r.getTrackId(),{crtUserId:s,roomId:n}=e,a=[{resourceId:i,enabled:!r.isLocalMuted()}],c=e.getResourcesByUserId(s),d=[];for(let e=0;e<c.length;e+=1){const t=c[e],r=tt(t),o=a.findIndex((e=>e.resourceId===r));if(o>=0){const{enabled:e}=a[o];t.state=e?1:0,d.push(t);break}}const u=yield e.context.setRTCTotalRes(n,We(Tt.MODIFY,d),Ye(c),Tt.TOTAL_CONTENT_RESOURCE);this._recvSignalResultFn(u),u!==t.ErrorCode.SUCCESS&&o.error(`notice \`track.enabled\` change failed -> code: ${u}`)}))}}class Pr extends Cr{constructor(e,t,r){super(),this.pcName=e,this.isPub=t,this.retryHook=r}get priority(){return Yt.HIGH}execute(t,i){return r(this,void 0,void 0,(function*(){const{pcName:r,isPub:s}=this,{useMutilPeerC:n}=t,{pc:a}=t.peerMgr.getPCItemByPCName(r),c=s&&n?[]:t.getSubscribedList(),d=yield Tr(c,!0,a,t),{pushOtherRooms:u,headers:_}=this.retryHook(r);u&&(d.pushOtherRooms=u);const l=yield new Lr(_,d).execute(t,i);if(l.code!==e.RCRTCCode.SUCCESS)return void o.error(`reTryExchange failed: ${l.code}, pcName: ${r}`);const{sdp:R,resultCode:C}=l.data;C===e.RCRTCCode.SUCCESS?(a.clearReTryExchangeTimer(),yield a.setRemoteAnswer(R.sdp)):o.error(`reTryExchange failed: ${C}, pcName: ${r}`)}))}}class Mr extends Cr{constructor(e,t,r){super(),this.subhook=e,this.callbacks=t,this.livingType=r}get priority(){return Yt.HIGH}execute(i,a){return r(this,void 0,void 0,(function*(){const{livingType:r}=this,{roomId:c,crtUserId:d,roomMode:u}=i;t.logger.info(s.L_ABSTRACT_ROOM_RECONNECTED_T,{livingType:r},{logSource:t.LogSource.RTC});if(i.peerMgr.getPCList().some((e=>"closed"===e.getRTCPeerConn().connectionState)))return o.warn("RTCPeerConnection closed. Please rejoin room to restore services."),t.logger.error(s.L_ABSTRACT_ROOM_RECONNECTED_R,{status:n.FAILED,code:"",msg:"RTCPeerConnection closed"},{logSource:t.LogSource.RTC}),void this.callbacks.onPeerClosed();const{code:_,data:l}=yield i.context.joinRTCRoom(c,u,r);if(_!==t.ErrorCode.SUCCESS)return o.error(`RTC __onReconnected getRTCRoomInfo failed: ${_}`),void t.logger.error(s.L_ABSTRACT_ROOM_RECONNECTED_R,{status:n.FAILED,code:_,msg:""},{logSource:t.LogSource.RTC});o.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(l)}`);const R=[],C={},h={},g={},p=gt(l,c),S=Object.keys(p),m=i.getAllUserIds();for(let e=S.length-1;e>=0;e-=1){const t=S[e],r=m.indexOf(t);if(-1===r){R.push(t),C[t]=it(p[t]);continue}const o=i.getResourcesByUserId(t),s=p[t],{publishedList:n,modifiedList:a,unpublishedList:c}=st(o,s,!0);C[t]=it(n),h[t]=it(c),g[t]=it(a),m.splice(r,1)}m.length&&m.forEach((e=>{i.removeResourcesByUserId(e)})),i.assignRoomData(p),m.length&&this.callbacks.onUserLeave(m),R.length&&this.callbacks.onUserJoin(R);for(const e in h){if(e===d)continue;const t=h[e];if(t.length){const e=t.map((e=>i.getRemoteTrack(tt(e))));yield new Dr(this.subhook,e,this.callbacks.onTrackUnpublish).execute(i,a)}}return Object.keys(C).forEach((t=>{const r=C[t];if(0===r.length)return;const o=r.map((t=>{const r=tt(t),{userId:o,tag:s,mediaType:n}=rt(r),a=n===e.RCMediaType.AUDIO_ONLY?new Je(s,o):new qe(s,o);return i.addRemoteTrack(a),a.__innerSetRemoteMuted(0===t.state),a}));this.callbacks.onTrackPublish(o)})),Object.keys(g).forEach((e=>{g[e].forEach((e=>{const t=tt(e),r=i.getRemoteTrack(t);r.__innerSetRemoteMuted(0===e.state),r.isAudioTrack()?this.callbacks.onAudioMuteChange(r):this.callbacks.onVideoMuteChange(r)}))})),i.roomMode===zt.LIVE&&this.executeInLivingRoom(i,l),t.logger.info(s.L_ABSTRACT_ROOM_RECONNECTED_R,{status:n.SUCCESSED,roomData:l},{logSource:t.LogSource.RTC}),{data:l}}))}executeInLivingRoom(e,r){var o,i;if(t.logger.error(s.L_LIVING_ROOM_RECONNECTED_T,{roomData:r},{logSource:t.LogSource.RTC}),!r)return void t.logger.info(s.L_LIVING_ROOM_RECONNECTED_R,{status:n.FAILED,code:"",msg:"room not fond"},{logSource:t.LogSource.RTC});const{roomInfo:a}=r,c=null===(o=a.filter((e=>"cdn_uris"===e.key))[0])||void 0===o?void 0:o.value;if(!c)return void t.logger.error(s.L_LIVING_ROOM_RECONNECTED_R,{status:n.FAILED,code:"",msg:"cdn_uris not found"},{logSource:t.LogSource.RTC});const d=JSON.parse(c),u=(null===(i=e.getCDNUris())||void 0===i?void 0:i.enableInnerCDN)!==d.enableInnerCDN;e.setCDNUris(d),t.logger.info(s.L_LIVING_ROOM_RECONNECTED_R,{status:n.SUCCESSED,roomData:r},{logSource:t.LogSource.RTC}),u&&this.callbacks.onCDNEnableChange(d.enableInnerCDN)}}class xr extends hr{constructor(e,t,r,o=Wt.NORMAL){super(o),this.tracks=e,this.subhook=t,this.callbacks=r}execute(t,i){var s,n,a;return r(this,void 0,void 0,(function*(){const{tracks:r}=this,{roomId:c}=t;if(o.info(`unsubscribe -> roomId: ${c}, tracks: ${r.map(St)}`),this.state===Wt.NORMAL){const e=t.getSubscribedList().slice(),{code:o,failedList:n}=yield new vr(r,this.subhook).execute(t,i),a=t.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,e);return null===(s=this.callbacks)||void 0===s||s.onTaskCompleted({code:o,subscribe:c,unsubscribe:d,failedList:n}),{code:o,failedList:n}}if(this.state===Wt.TAIL){const{code:r}=yield new xr(this.tracks,this.subhook,this.callbacks,Wt.MIDDLE).execute(t,i);if(r===e.RCRTCCode.SUCCESS){const r=t.getCollectSubscribeList().slice(0),o=t.getSubscribedList().slice(),{code:s,failedList:c}=yield new vr(r,this.subhook).execute(t,i);if(s!==e.RCRTCCode.SUCCESS)return null===(n=this.callbacks)||void 0===n||n.onTaskCompleted({code:s,subscribe:[],unsubscribe:[],failedList:c}),{code:s,failedList:c};const d=t.getSubscribedList().slice(0),{subscribe:u,unsubscribe:_}=this.pickoutSubscribed(d,o);return null===(a=this.callbacks)||void 0===a||a.onTaskCompleted({code:s,subscribe:u,unsubscribe:_,failedList:c}),{code:s,failedList:c}}return{code:r}}return hr.AsyncUpdateSubscribeTasks.splice(hr.AsyncUpdateSubscribeTasks.length,0,...this.tracks),new Promise((o=>{const i=this.formateTrack(r);t.resetCollectSubscribeList(i),o({code:e.RCRTCCode.SUCCESS})}))}))}}class wr extends hr{constructor(e,t,r,o=Wt.NORMAL){super(o),this.tracks=e,this.subhook=t,this.callbacks=r}execute(i,a){var c;return r(this,void 0,void 0,(function*(){const{tracks:r}=this,{roomId:d}=i;if(this.state===Wt.NORMAL){const e=i.getSubscribedList().slice(),{code:t,failedList:o}=yield new br(r,this.subhook).execute(i,a),s=i.getSubscribedList().slice(),{subscribe:n,unsubscribe:d}=this.pickoutSubscribed(s,e);return null===(c=this.callbacks)||void 0===c||c.onTaskCompleted({code:t,subscribe:n,unsubscribe:d,failedList:o}),{code:t,failedList:o}}if(t.logger.info(s.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:r.map(St)},{logSource:t.LogSource.RTC}),!t.validate("tracks",r,(()=>t.isArray(r)&&r.length>0&&r.every((e=>e instanceof je||e.track instanceof je))),!0))return o.warn(`subscribe failed, tracks is invalid -> roomId: ${d}`),t.logger.error(s.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`subscribe -> roomId: ${d}, tracks: ${r.map(St)}`);const u=this.getSubscribedList(i).map((e=>Object.assign({},e))),_=r.map((e=>e instanceof je?{track:e}:e)),l=[];if(_.forEach((e=>{const t=e.track.getTrackId();l.push(t);const r=u.find((e=>e.track.getTrackId()===t));if(r){if(r.subTiny===e.subTiny)return;r.subTiny=e.subTiny}else u.push(e)})),i.polarisReport.sendR2(Xt.SUBSCRIBE,er.BEGIN,l),t.logger.info(s.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:r.map(St),roomId:d},{logSource:t.LogSource.RTC}),this.state===Wt.TAIL){const{code:t}=yield new wr(this.tracks,this.subhook,this.callbacks,Wt.MIDDLE).execute(i,a);if(t===e.RCRTCCode.SUCCESS){const e=i.getCollectSubscribeList().slice(0);return new xr(e,this.subhook,this.callbacks).execute(i,a)}return{code:t}}return hr.AsyncSubscribeTasks.splice(hr.AsyncSubscribeTasks.length,0,...this.tracks),new Promise((t=>{i.resetCollectSubscribeList(u),t({code:e.RCRTCCode.SUCCESS})}))}))}getSubscribedList(e){return this.state===Wt.MIDDLE?e.getCollectSubscribeList():e.getSubscribedList()}}class Br extends hr{constructor(e,t,r,o=Wt.NORMAL){super(o),this.tracks=e,this.subhook=t,this.callbacks=r}execute(i,a){var c;return r(this,void 0,void 0,(function*(){const{tracks:r}=this,{roomId:d}=i;if(this.state===Wt.NORMAL){const e=i.getSubscribedList().slice(),{code:t,failedList:o}=yield new Or(r,this.subhook).execute(i,a),s=i.getSubscribedList().slice(),{subscribe:n,unsubscribe:d}=this.pickoutSubscribed(s,e);return null===(c=this.callbacks)||void 0===c||c.onTaskCompleted({code:t,subscribe:n,unsubscribe:d,failedList:o}),{code:t,failedList:o}}if(t.logger.info(s.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:r.map(St)},{logSource:t.LogSource.RTC}),!t.validate("tracks",r,(()=>t.isArray(r)&&r.length>0&&r.every((e=>e instanceof je))),!0))return o.warn(`unsubscribe failed, tracks is invalid -> roomId: ${d}`),t.logger.warn(s.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`unsubscribe -> roomId: ${d}, tracks: ${r.map(St)}`);const u=this.getSubscribedList(i).map((e=>Object.assign({},e))).filter((e=>!r.includes(e.track)));if(i.polarisReport.sendR2(Xt.SUBSCRIBE,er.END,r.map((e=>e.getTrackId()))),t.logger.info(s.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:r.map(St),roomId:d},{logSource:t.LogSource.RTC}),this.state===Wt.TAIL){const{code:t}=yield new Br(this.tracks,this.subhook,this.callbacks,Wt.MIDDLE).execute(i,a);if(t===e.RCRTCCode.SUCCESS){const e=i.getCollectSubscribeList().slice(0).map((e=>e.track));return new xr(e,this.subhook,this.callbacks).execute(i,a)}return{code:t}}return hr.AsyncUnsubscribeTasks.splice(hr.AsyncUnsubscribeTasks.length,0,...this.tracks),new Promise((t=>{i.resetCollectSubscribeList(u),t({code:e.RCRTCCode.SUCCESS})}))}))}getSubscribedList(e){return this.state===Wt.MIDDLE?e.getCollectSubscribeList():e.getSubscribedList()}}e.RCKickReason=void 0,(or=e.RCKickReason||(e.RCKickReason={}))[or.SERVER_KICK=1]="SERVER_KICK",or[or.OTHER_KICK=2]="OTHER_KICK";const Vr={[e.RCKickReason.SERVER_KICK]:1,[e.RCKickReason.OTHER_KICK]:5},$r="evt-leave";class Fr extends t.EventEmitter{constructor(e,t,r,o,i,s,n,a,c,d=Lt()){super(),this._context=e,this._runtime=t,this._roomId=r,this._service=i,this._initOptions=s,this._useMutilPeerC=c,this._clientSessionId=d,this._appListener=null,this._reportListener=null,this._onRecvPKMsg=null,this._polarisReport=new _r(this._context,this._runtime,this._roomId,this),this._peerCManager=new Rr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._invoker=new pr(this._context,this._service,this._peerCManager,r,this._context.getCurrentId(),o,this._polarisReport,n,a),this._store=this._invoker.store}__innerInit(t,o,i,s,n){return r(this,void 0,void 0,(function*(){const{code:r,data:a}=yield this._invoker.push(new mr(this._roomId,t,o,i,s,n));return r!==e.RCRTCCode.SUCCESS?{code:r}:(this._initWithRoomData(a.offlineKickTime),{code:r,data:a})}))}_initWithRoomData(e){var t;this._pinger=new Et(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,r,i){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."),t.assert("max",e,(e=>t.isNumber(e)&&e>Math.max(r||1,200)),!0),t.assert("min",r,(r=>t.isNumber(r)&&r>=1&&(!t.isNumber(e)||r<e)),!0),t.assert("start",i,(o=>t.isNumber(o)&&o>r&&o<=e));this._peerCManager.getPCList().forEach((t=>{t.setBitrate(e,r,i)}))}_onTrackReady(r){const i=r.streams[0].id,{track:n}=r.receiver,a=[i,"audio"===n.kind?e.RCMediaType.AUDIO_ONLY:e.RCMediaType.VIDEO_ONLY].join("_"),c=this._store.getRemoteTrack(a);if(!c)return void o.warn(`cannot found remote track ${n.id}`);c.__innerSetMediaStreamTrack(n);const d=At.getMemo();t.logger.info(s.L_QS_TRACK_READY_O,{identify:d.qualityStatusId},{logSource:t.LogSource.RTC}),this._callAppListener("onTrackReady",c)}_callAppListener(e,...r){var i;"onPing"!==e&&t.logger.info(s.L_ABSTRACT_ROOM_CALL_APP_LISTENER_O,{status:n.SUCCESSED,eventType:e,attrs:r},{logSource:t.LogSource.RTC}),"onPing"!==e&&o.info(`${e} callback ->`,...r);const a=null===(i=this._appListener)||void 0===i?void 0:i[e];if(a)try{a(...r)}catch(e){o.error(e)}}_onTrackUnpublish(e){this._callAppListener("onTrackUnpublish",e)}__parseInnerMessage(e){var r;const{targetId:i,conversationType:a}=e;if(i!==this._roomId)return t.logger.warn(s.L_RTC_CLIENT_MESSAGE_O,{status:n.FAILED,message:`roomId is different, msg roomId-> ${i}, this._roomId-> ${this._roomId} `},{logSource:t.LogSource.RTC}),!0;o.info(`recv inner msg -> message: ${JSON.stringify(e)} | roomid: ${this._roomId}`);const{content:c}=e,d=At.getMemo();switch(e.messageType){case Tt.KICK:this._kickoff(!0,c);break;case Tt.STATE:this._stateHandle(c);break;case Tt.MODIFY:case Tt.PUBLISH:case Tt.UNPUBLISH:case Tt.TOTAL_CONTENT_RESOURCE:if(!d.messageData){d.messageData={sentTime:e.sentTime,senderUserId:e.senderUserId};const o=Date.now(),n={dur:o-e.sentTime,puid:e.senderUserId,rid:i,csnid:null===(r=d.clientData)||void 0===r?void 0:r.clientSessionId,snid:this.getSessionId(),time:o,cr:"unknown",net:"unknown",uid:this.getCrtUserId()},a=JSON.stringify(n);t.reportLog(t.LogLevel.STATISTICS,s.L_QS_RECV_PUB_MSG_S,a,t.LogSource.RTC)}this._resourceHandle(c,e.messageType,e.senderUserId);break;case Tt.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",e.messageType,e.content);break;case Tt.USER_NOTIFY:o.warn(`TODO: ${Tt.USER_NOTIFY}`);break;case Tt.PK_INVITE:case Tt.PK_CANCEL_INVITE:case Tt.PK_INVITE_TIMEOUT:case Tt.PK_INVITE_ANSWER:case Tt.PK_END:this._onRecvPKMsg&&this._onRecvPKMsg(e);break;case Tt.OTHER_ROOM_OFFLINE:break;default:this._callAppListener("onMessageReceive",e.messageType,c,e.senderUserId,e.messageUId)}return!0}_kickoff(e,i){return r(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;let r,n;if(o.warn(`onKickOff -> byServer: ${e}`),this.emit($r),this._leaveHandle(!e),e){((null==i?void 0:i.users)||[]).forEach((e=>{e.userId===this._context.getCurrentId()&&(n=e.type,r=e.kickExtra)}));const e=Date.now(),o=JSON.stringify({cod:Vr[n||1],rid:this._roomId,csnid:this.getClientSessionId(),snid:this.getSessionId(),time:e,cr:"unknown",net:"unknown",uid:this.getCrtUserId()});t.reportLog(t.LogLevel.STATISTICS,s.L_QS_KICKED_S,o,t.LogSource.RTC)}this._callAppListener("onKickOff",e,n,r)}))}_rtcpeerClosed(){this.emit($r),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,t,o){return r(this,void 0,void 0,(function*(){const{uris:r,ignore:i}=e;!i&&r&&this._invoker.push(new Nr(e,t,o,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(t){var o;return r(this,void 0,void 0,(function*(){const{left:r,joined:i,upgrade:s,downgrade:n}=yield this._invoker.push(new Ar(t,this._subhook.bind(this)));if(null===(o=this._appListener)||void 0===o?void 0:o.onSwitchRole)return s.length&&s.forEach((t=>this._callAppListener("onSwitchRole",t,e.RCRTCLiveRole.ANCHOR))),n.length&&n.forEach((t=>this._callAppListener("onSwitchRole",t,e.RCRTCLiveRole.AUDIENCE))),i.length&&this._callAppListener("onUserJoin",i),void(r.length&&this._callAppListener("onUserLeave",r));const a=[...i,...s],c=[...r,...n];a.length&&this._callAppListener("onUserJoin",a),c.length&&this._callAppListener("onUserLeave",c)}))}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(i,a){return r(this,void 0,void 0,(function*(){t.logger.info(s.L_ABSTRACT_ROOM_SEND_MESSAGE_T,{name:i,content:a},{logSource:t.LogSource.RTC});const{code:r}=yield this._context.sendMessage(t.ConversationType.RTC_ROOM,this._roomId,{messageType:i,content:a,isStatusMessage:!0});return r!==t.ErrorCode.SUCCESS?(o.error(`send message failed -> code: ${r}`),t.logger.error(s.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:n.FAILED,code:r,msg:""},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_ERROR}):(t.logger.info(s.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:n.SUCCESSED,name:i,content:a},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS})}))}setRoomAttribute(i,a,c,d=!1){return r(this,void 0,void 0,(function*(){t.logger.info(s.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_T,{roomId:this._roomId,key:i,value:a,message:c,isInner:d},{logSource:t.LogSource.RTC});const r=yield this._context.setRTCData(this._roomId,i,a,d,rr.ROOM,c);return r!==t.ErrorCode.SUCCESS?(o.error(`SetRoomAttributeValue Failed: ${r}`),t.logger.error(s.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:n.FAILED,code:r,msg:""},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_ERROR}):(t.logger.info(s.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:n.SUCCESSED,roomId:this._roomId,key:i,value:a,message:c,isInner:d},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS})}))}deleteRoomAttributes(i,a,c=!1){return r(this,void 0,void 0,(function*(){t.logger.info(s.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_T,{roomId:this._roomId,keys:i,message:a,isInner:c},{logSource:t.LogSource.RTC});const r=yield this._context.removeRTCData(this._roomId,i,c,rr.ROOM,a);return r!==t.ErrorCode.SUCCESS?(o.error(`DeleteRoomAttribute Failed: ${r}`),t.logger.error(s.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:n.FAILED,code:r,msg:""},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_ERROR}):(t.logger.info(s.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:n.SUCCESSED,roomId:this._roomId,keys:i,message:a,isInner:c},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS})}))}getRoomAttributes(i=[],s=!1){return r(this,void 0,void 0,(function*(){const{code:r,data:n}=yield this._context.getRTCData(this._roomId,i,s,rr.ROOM);return r!==t.ErrorCode.SUCCESS?(o.error(`GetRoomAttributes Failed: ${r}`),{code:e.RCRTCCode.SIGNAL_ERROR}):{code:e.RCRTCCode.SUCCESS,data:n}}))}_setUserAttributeValue(e,t,r){return this._context.setRTCData(this._roomId,e,t,!1,rr.PERSON,r)}_deleteUserAttributes(e,t){return this._context.removeRTCData(this._roomId,e,!1,rr.PERSON,t)}_getUserAttributes(e){return this._context.getRTCData(this._roomId,e,!1,rr.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 r(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;At.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(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Me.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)})),this._peerCManager.clear(),this._peerCManager=null}_onLocalTrackDestroied(e){e instanceof we&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(e,t){return r(this,void 0,void 0,(function*(){this._invoker.push(new Ur(e,t))}))}publish(e){return r(this,void 0,void 0,(function*(){return this._invoker.push(new yr(e,this._pubhook.bind(this)))}))}_getPushOtherRoomsParams(){return[]}_reTryExchange(e,t){return r(this,void 0,void 0,(function*(){this._invoker.push(new Pr(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 r(this,void 0,void 0,(function*(){return this._invoker.push(new kr(e,((e,t)=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(t)}))))}))}_getResourceById(e){return this._store.getPublishedResourceByTrackId(e)}_isValidResourceId(e){var t;const{userId:r}=rt(e);return!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>tt(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(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.on(Me.__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 r(this,void 0,void 0,(function*(){return this._invoker.push(new br(e,this._subhook.bind(this)))}))}addSubscribeTask(e){this._invoker.push(new wr(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}unsubscribe(e){return r(this,void 0,void 0,(function*(){return this._invoker.push(new Or(e,this._subhook.bind(this)))}))}addUnsubscribeTask(e){this._invoker.push(new Br(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}updateSubList(e){return r(this,void 0,void 0,(function*(){return this._invoker.push(new vr(e,this._subhook.bind(this)))}))}addUpdateSubscribeListTask(e){this._invoker.push(new xr(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){t.logger.info(s.L_ABSTRACT_ROOM_REGISTER_ROOM_EVENT_LISTENER_O,{status:n.SUCCESSED,listener:e&&Object.keys(e)},{logSource:t.LogSource.RTC}),this._appListener=e}registerReportListener(e){t.logger.info(s.L_ABSTRACT_ROOM_REGISTER_REPORT_LISTENER_O,{status:n.SUCCESSED,listener:e&&Object.keys(e)},{logSource:t.LogSource.RTC}),this._reportListener=e}onAudioLevelChange(e,r){var o;t.logger.info(s.L_ABSTRACT_ROOM_AUDIO_LEVEL_O,{status:n.SUCCESSED,handler:null==e?void 0:e.name,gap:r},{logSource:t.LogSource.RTC}),null===(o=this._audioLevelReport)||void 0===o||o.clearAudioLevelReportTimer(),this._audioLevelReport=new lr(this),this._audioLevelReport.onAudioLevelChange(e,r||1e3)}__onReconnected(e){return r(this,void 0,void 0,(function*(){return this._invoker.push(new Mr(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 Gr extends Cr{constructor(e,t){super(),this.data=e,this.cdnValues=t}execute(t,i){var s,n,a,c;return r(this,void 0,void 0,(function*(){const r={"App-Key":t.context.getAppkey(),Token:t.getToken(),RoomId:t.roomId,UserId:t.context.getCurrentId(),SessionId:t.getSessionId()},{code:i,res:d}=yield t.service.setMcuConfig(r,this.data);if(i!==e.RCRTCCode.SUCCESS)return o.error(`set MCU config failed: ${i}`),{code:i};o.info("set MCU config success"),d.pull_url&&t.setCDNUris(JSON.parse(d.pull_url));const u=this.cdnValues;return i===e.RCRTCCode.SUCCESS&&((null===(n=null===(s=u.output)||void 0===s?void 0:s.video.normal)||void 0===n?void 0:n.width)||(null===(c=null===(a=u.output)||void 0===a?void 0:a.video.normal)||void 0===c?void 0:c.fps))&&fr(t),{code:i,res:d}}))}}var Kr,Hr,jr,Jr;e.BackgroundPictureFillMode=void 0,(Kr=e.BackgroundPictureFillMode||(e.BackgroundPictureFillMode={}))[Kr.CROP=1]="CROP",Kr[Kr.WHOLE=2]="WHOLE",e.MixLayoutMode=void 0,(Hr=e.MixLayoutMode||(e.MixLayoutMode={}))[Hr.CUSTOMIZE=1]="CUSTOMIZE",Hr[Hr.SUSPENSION=2]="SUSPENSION",Hr[Hr.ADAPTATION=3]="ADAPTATION",e.MixVideoRenderMode=void 0,(jr=e.MixVideoRenderMode||(e.MixVideoRenderMode={}))[jr.CROP=1]="CROP",jr[jr.WHOLE=2]="WHOLE",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"}(Jr||(Jr={}));const qr=()=>({version:2,mode:e.MixLayoutMode.SUSPENSION});class Wr{constructor(e,t){this._invoker=e,this._isValidTrackId=t,this._values=qr()}setHostVideoTrack(r){if(o.info(`setHostVideoTrack -> videoTrackId: ${r}`),!this._isValidTrackId(r))return o.error(`setHostVideoTrack failed -> videoTrackId is invalid: ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:n.FAILED,code:"",msg:"params error -> videoTrackId"},{logSource:t.LogSource.RTC}),this;const{mediaType:i,tag:a,userId:c}=rt(r);return i!==e.RCMediaType.VIDEO_ONLY?(o.error(`setHostVideoTrack failed -> kind of resource is not 'video' -> ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:n.FAILED,code:"",msg:"not video"},{logSource:t.LogSource.RTC}),this):(this._values.host_stream_id=ot(c,a),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:n.SUCCESSED,videoTrackId:r},{logSource:t.LogSource.RTC}),this)}setMixLayoutMode(r){o.info(`setMixLayoutMode -> mode: ${r}`);return[e.MixLayoutMode.CUSTOMIZE,e.MixLayoutMode.SUSPENSION,e.MixLayoutMode.ADAPTATION].includes(r)?(this._values.mode=r,t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:n.SUCCESSED,mode:r},{logSource:t.LogSource.RTC}),this):(o.error(`setMixLayoutMode failed -> mode is invalid: ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:n.SUCCESSED,code:"",msg:`params error -> mode: ${r}`},{logSource:t.LogSource.RTC}),this)}_addOutputValue(t,r,o="normal"){const i=this._values.output||(this._values.output={video:{normal:{width:640,height:480}}});if("cdn"===t)return void(i.cdn=r);if("audio"===t)return void(i.audio={bitrate:r});const{video:s}=i;if("normal"!==o&&"tiny"!==o)if("backgroundColor"!==o)if("exparams"!==o){if("backgroundPicture"===o){const t=s.backgroundPicture||(s.backgroundPicture={fillMode:e.BackgroundPictureFillMode.CROP,picture:[]});Object.assign(t,r)}}else s.exparams={renderMode:r};else s.backgroundColor=r;else{const e=s[o]||(s[o]={});Object.assign(e,r)}}setOutputVideoResolution(e){if(o.info(`setOutputVideoResolution -> resolution: ${e}`),!ct(e))return o.error(`setOutputVideoResolution failed -> resolution is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:n.FAILED,code:"",msg:`params error -> resolution: ${e}`},{logSource:t.LogSource.RTC}),this;const{width:r,height:i}=at(e);return this._addOutputValue("video",{width:r,height:i},"normal"),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:n.SUCCESSED,resolution:e},{logSource:t.LogSource.RTC}),this}setOutputVideoFPS(e){if(o.info(`setOutputVideoFPS -> fps: ${e}`),!dt(e))return o.error(`setOutputVideoFPS failed -> fps is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:n.FAILED,code:"",msg:`params error -> fps: ${e}`},{logSource:t.LogSource.RTC}),this;const r=ut(e);return this._addOutputValue("video",{fps:r},"normal"),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:n.SUCCESSED,fps:e},{logSource:t.LogSource.RTC}),this}setOutputVideoBitrate(e){return o.info(`setOutputVideoBitrate -> bitrate: ${e}`),!t.isNumber(e)||e<=0?(o.error(`setOutputVideoBitrate failed -> bitrate is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:n.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:t.LogSource.RTC})):this._addOutputValue("video",{bitrate:e},"normal"),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:n.SUCCESSED,bitrate:e},{logSource:t.LogSource.RTC}),this}setOutputTinyVideoResolution(e){if(o.info(`setOutputTinyVideoResolution -> resolution: ${e}`),!ct(e))return o.error(`setOutputTinyVideoResolution failed -> resolution is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:n.FAILED,code:"",msg:`params error -> resolution: ${e}`},{logSource:t.LogSource.RTC}),this;const{width:r,height:i}=at(e);return this._addOutputValue("video",{width:r,height:i},"tiny"),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:n.SUCCESSED,resolution:e},{logSource:t.LogSource.RTC}),this}setOutputTinyVideoFPS(e){if(o.info(`setOutputTinyVideoFPS -> fps: ${e}`),!dt(e))return o.error(`setOutputTinyVideoFPS failed -> fps is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:n.FAILED,code:"",msg:`params error -> fps: ${e}`},{logSource:t.LogSource.RTC}),this;const r=ut(e);return this._addOutputValue("video",{fps:r},"tiny"),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:n.SUCCESSED,fps:e},{logSource:t.LogSource.RTC}),this}setOutputTinyVideoBitrate(e){return o.info(`setOutputTinyVideoBitrate -> bitrate: ${e}`),!t.isNumber(e)||e<=0?(o.error(`setOutputTinyVideoBitrate failed -> bitrate is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:n.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:t.LogSource.RTC})):this._addOutputValue("video",{bitrate:e},"tiny"),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:n.SUCCESSED,bitrate:e},{logSource:t.LogSource.RTC}),this}setOutputVideoRenderMode(r){return o.info(`setOutputVideoRenderMode -> renderMode: ${r}`),[e.MixVideoRenderMode.CROP,e.MixVideoRenderMode.WHOLE].includes(r)?this._addOutputValue("video",r,"exparams"):(o.error(`setOutputVideoRenderMode failed -> renderMode is invalid: ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:n.FAILED,code:"",msg:`params error -> renderMode: ${r}`},{logSource:t.LogSource.RTC})),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:n.SUCCESSED,renderMode:r},{logSource:t.LogSource.RTC}),this}setOutputAudioBitrate(e){return o.info(`setOutputAudioBitrate -> bitrate: ${e}`),t.isNumber(e)&&e>0?this._addOutputValue("audio",e):(o.error(`setOutputAudioBitrate failed -> bitrate is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:n.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:t.LogSource.RTC})),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:n.SUCCESSED,bitrate:e},{logSource:t.LogSource.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}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:n.FAILED,code:"",msg:`params error -> color: ${e}`},{logSource:t.LogSource.RTC})),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:n.SUCCESSED,color:e},{logSource:t.LogSource.RTC}),this}addOutputBackgroundPicture(e,r,i,a,c){var d,u,_;if(o.info(`addOutputBackgroundPicture -> uri: ${e}, x: ${r}, y: ${i}, w: ${a}, h: ${c}`),!t.isHttpUrl(e))return o.error(`addOutputBackgroundPicture failed -> uri is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:n.FAILED,code:"",msg:`params error -> uri: ${e}`},{logSource:t.LogSource.RTC}),this;if([r,i,a,c].some((e=>!t.isNumber(e)||e<0||e>1)))return o.error(`addOutputBackgroundPicture failed -> some attrs of (x, y, w, h) is invalid: ${r}, ${i}, ${a}, ${c}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:n.FAILED,code:"",msg:`params error -> x: ${r}, y: ${i}, w: ${a}, h: ${c}`},{logSource:t.LogSource.RTC}),this;const l=(null===(_=null===(u=null===(d=this._values.output)||void 0===d?void 0:d.video)||void 0===u?void 0:u.backgroundPicture)||void 0===_?void 0:_.picture)||[];return l.push({uri:e,w:a,h:c,x:r,y:i}),this._addOutputValue("video",{picture:l},"backgroundPicture"),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:n.SUCCESSED,uri:e,x:r,y:i,w:a,h:c},{logSource:t.LogSource.RTC}),this}removeOutputBackgroundPicture(e){var r,i,a;if(o.info(`removeOutputBackgroundPicture -> uri: ${e}`),!t.isHttpUrl(e))return o.error(`removeOutputBackgroundPicture failed -> uri is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:n.FAILED,code:"",msg:`params error -> uri: ${e}`},{logSource:t.LogSource.RTC}),this;let c=null===(a=null===(i=null===(r=this._values.output)||void 0===r?void 0:r.video)||void 0===i?void 0:i.backgroundPicture)||void 0===a?void 0:a.picture;return c&&(c=c.filter((t=>t.uri!==e)),this._addOutputValue("video",{pictures:c},"backgroundPicture")),t.logger.info(s.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:n.SUCCESSED,uri:e},{logSource:t.LogSource.RTC}),this}clearOutputBackgroundPicture(){return o.info("clearOutputBackgroundPicture ->"),this._addOutputValue("video",{pictures:[]},"backgroundPicture"),t.logger.info(s.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),this}setOutputBackgroundPictureFillMode(r){return o.info(`setOutputBackgroundPictureFillMode -> fillMode: ${r}`),[e.BackgroundPictureFillMode.CROP,e.BackgroundPictureFillMode.WHOLE].includes(r)?this._addOutputValue("video",{fillMode:r},"backgroundPicture"):(o.error(`setOutputBackgroundPictureFillMode failed -> fillMode is invalid: ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:n.FAILED,code:"",msg:`params error -> fillMode: ${r}`},{logSource:t.LogSource.RTC})),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:n.SUCCESSED,fillMode:r},{logSource:t.LogSource.RTC}),this}addPublishStreamUrls(e){var r,i;o.info(`addPublishStreamUrls -> urls: ${e.join(",")}`);const a=/^rtmp:\/\/.+/;if(!t.isArray(e)||0===e.length||e.some((e=>!a.test(e))))return o.error(`addPublishStreamUrls failed -> urls is invalid: ${e.join(",")}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:n.FAILED,code:"",msg:`params error -> urls: ${e.join(",")}`},{logSource:t.LogSource.RTC}),this;const c=(null===(i=null===(r=this._values.output)||void 0===r?void 0:r.cdn)||void 0===i?void 0:i.concat())||[];let d=!1;return e.forEach((e=>{c.some((t=>t.pushurl===e))||(d=!0,c.push({pushurl:e}))})),c.length>5?(o.error("addPublishStreamUrls failed -> publish stream urls no more than 5!"),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:n.FAILED,code:"",msg:`params error -> publish stream urls no more than 5, length: ${e.length}`},{logSource:t.LogSource.RTC}),this):(d&&this._addOutputValue("cdn",c),t.logger.info(s.L_MCU_CONFIG_BUILDER_ADD_PUBLISH_STREAM_URLS_O,{status:n.SUCCESSED,urls:e},{logSource:t.LogSource.RTC}),this)}removePublishStreamUrls(e){var r,i;o.info(`removePublishStreamUrls -> urls: ${e.join(",")}`);const a=/^rtmp:\/\/.+/;if(!t.isArray(e)||0===e.length||e.some((e=>!a.test(e))))return o.error(`removePublishStreamUrls failed -> urls contain invalid items: ${e.join(",")}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:n.FAILED,code:"",msg:`params error -> urls: ${e.join(",")}`},{logSource:t.LogSource.RTC}),this;const c=(null===(i=null===(r=this._values.output)||void 0===r?void 0:r.cdn)||void 0===i?void 0:i.concat())||[];for(let t=c.length-1;t>=0;t-=1){const{pushurl:r}=c[t],o=e.indexOf(r);o>=0&&(e.splice(o,1),c.splice(t,1))}return this._addOutputValue("cdn",c),t.logger.info(s.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:n.SUCCESSED,urls:e},{logSource:t.LogSource.RTC}),this}clearPublishStreamUrls(){return o.info("clearPublishStreamUrls ->"),this._addOutputValue("cdn",[]),t.logger.info(s.L_MCU_CONFIG_BUILDER_CLEAR_PUBLISH_STREAM_URLS_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),this}addCustomizeLayoutVideo(r,i,a,c,d){if(o.info(`addCustomizeLayoutVideo -> trackId: ${r}, x: ${i}, y: ${a}, width: ${c}, height: ${d}`),!t.notEmptyString(r)||!this._isValidTrackId(r))return o.error(`addCustomizeLayoutVideo failed -> trackId is invalid: ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${r}`},{logSource:t.LogSource.RTC}),this;if(!t.isNumber(i)||!t.isNumber(a))return o.error(`addCustomizeLayoutVideo failed -> some attrs of (x, y) is invalid: ${i}, ${a}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.FAILED,code:"",msg:`params error -> x: ${i}, y: ${a}`},{logSource:t.LogSource.RTC}),this;if([c,d].some((e=>!t.isNumber(e)||e<0)))return o.error(`addCustomizeLayoutVideo failed -> some attrs of (width, height) is invalid: ${c}, ${d}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.FAILED,code:"",msg:`params error -> width: ${c}, height: ${d}`},{logSource:t.LogSource.RTC}),this;const{userId:u,tag:_,mediaType:l}=rt(r);if(l!==e.RCMediaType.VIDEO_ONLY)return o.error(`addCustomizeLayoutVideo failed -> kind of trackId is not 'video': ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${r}的资源不是视频`},{logSource:t.LogSource.RTC}),this;const R=ot(u,_),C=this._values.input||(this._values.input={}),h=C.video||(C.video=[]);return h.some((e=>e.height===d&&e.width===c&&e.stream_id===R&&e.user_id===u&&e.x===i&&e.y===a))?(t.logger.warn(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.FAILED,code:"",msg:"Duplicate configuration item ignored"},{logSource:t.LogSource.RTC}),this):(h.push({user_id:u,stream_id:R,x:i,y:a,width:c,height:d}),t.logger.info(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.SUCCESSED,trackId:r,x:i,y:a,width:c,height:d},{logSource:t.LogSource.RTC}),this)}removeCustomizeLayoutVideo(r){if(o.info(`clearCustomizeInputAudio -> trackId: ${r}`),!this._isValidTrackId(r))return o.error(`clearCustomizeInputAudio failed -> trackId is invalid: ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${r}`},{logSource:t.LogSource.RTC}),this;const{userId:i,tag:a,mediaType:c}=rt(r);if(c!==e.RCMediaType.VIDEO_ONLY)return o.error(`clearCustomizeInputAudio failed -> kind of trackId is not 'video': ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${r}的资源不是视频`},{logSource:t.LogSource.RTC}),this;const d=ot(i,a),{input:u}=this._values;return(null==u?void 0:u.video)&&u.video.length>0&&(u.video=u.video.filter((e=>e.stream_id===d))),t.logger.info(s.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.SUCCESSED,trackId:r},{logSource:t.LogSource.RTC}),this}clearCustomizeLayoutVideo(){o.info("clearCustomizeLayoutVideo ->");const{input:e}=this._values;return null==e||delete e.video,t.logger.info(s.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.SUCCESSED},{logSource:t.LogSource.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(",")}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:n.FAILED,code:"",msg:`params error -> trackIds: ${e.join(",")}`},{logSource:t.LogSource.RTC}),this;return(this._values.input||(this._values.input={})).audio=e.map((e=>{const{userId:t,tag:r}=rt(e);return{stream_id:ot(t,r),user_id:t}})),this._values.inputFilterMode=Jr.AUDIO_INPUT_VIDEO_ALL,t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:n.SUCCESSED,trackIds:e},{logSource:t.LogSource.RTC}),this}addCustomizeInputAudio(e){if(o.info(`addCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return o.warn(`addCustomizeInputAudio failed -> trackId is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:t.LogSource.RTC}),this;const r=this._values.input||(this._values.input={}),i=r.audio||(r.audio=[]),{userId:a,tag:c}=rt(e),d=ot(a,c);return i.some((e=>e.stream_id===d&&e.user_id===a))?(t.logger.warn(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:n.FAILED,code:"",msg:`trackId:${e} is exist`},{logSource:t.LogSource.RTC}),this):(i.push({user_id:a,stream_id:d}),this._values.inputFilterMode=Jr.AUDIO_INPUT_VIDEO_ALL,t.logger.info(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:n.SUCCESSED,trackId:e},{logSource:t.LogSource.RTC}),this)}removeCustomizeInputAudio(e){if(o.info(`removeCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return o.error(`removeCustomizeInputAudio failed -> trackId is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:t.LogSource.RTC}),this;const{input:r}=this._values;if(!(null==r?void 0:r.audio)||0===r.audio.length)return t.logger.error(s.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:n.FAILED,code:"",msg:"not audio"},{logSource:t.LogSource.RTC}),this;const{userId:i,tag:a}=rt(e),c=ot(i,a);return r.audio=r.audio.filter((e=>i!==e.user_id||c!==e.stream_id)),t.logger.info(s.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:n.SUCCESSED,trackId:e},{logSource:t.LogSource.RTC}),this}clearCustomizeInputAudio(){o.info("clearCustomizeInputAudio ->");const{input:e}=this._values;return(null==e?void 0:e.audio)&&delete e.audio,this._values.inputFilterMode=Jr.AUDIO_VIDEO_ALL,t.logger.info(s.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_INPUT_AUDIO_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),this}addPictureWaterMark(e,r,i,a,c,d){if(o.info(`addPictureWaterMark -> trackId: ${e} uri: ${r}, x: ${i}, y: ${a}, w: ${c}, h: ${d}`),!this._isValidTrackId(e))return o.warn(`addPictureWaterMark failed -> trackId is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:t.LogSource.RTC}),this;if(!t.isHttpUrl(r))return o.error(`addPictureWaterMark failed -> uri is invalid: ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:n.FAILED,code:"",msg:`params error -> uri: ${r}`},{logSource:t.LogSource.RTC}),this;if([i,a,c,d].some((e=>!t.isNumber(e)||e<0||e>1)))return o.error(`addPictureWaterMark failed -> some attrs of (x, y, w, h) is invalid: ${i}, ${a}, ${c}, ${d}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:n.FAILED,code:"",msg:`params error -> x: ${i}, y: ${a}, w: ${c}, h: ${d}`},{logSource:t.LogSource.RTC}),this;const{userId:u,tag:_}=rt(e),l=ot(u,_),R=this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]}),{singleScreen:C}=R;o.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(C)}`);const h=C.filter((e=>e.streamId===l))[0];return o.info(`addPictureWaterMark target-> : ${h}`),h?h.picture.push({uri:r,w:c,h:d,x:i,y:a}):C.push({streamId:l,picture:[{uri:r,w:c,h:d,x:i,y:a}]}),o.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(C)}`),this._values.waterMark.singleScreen=C,o.info(`addPictureWaterMark this._values.waterMark.singleScreen-> : ${JSON.stringify(this._values.waterMark.singleScreen)}`),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:n.SUCCESSED,trackId:e,uri:r,x:i,y:a,w:c,h:d},{logSource:t.LogSource.RTC}),this}clearPictureWaterMark(){o.info("clearOutputBackgroundPicture ->");return(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen=[],t.logger.info(s.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),this}removePictureWaterMark(e,r){if(!t.notEmptyString(e)||!this._isValidTrackId(e))return t.logger.error(s.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:t.LogSource.RTC}),this;const{userId:o,tag:i}=rt(e),a=ot(o,i),c=this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]}),{singleScreen:d}=c;return d.forEach((e=>{e.streamId===a&&(e.picture=e.picture.filter((e=>e.uri!==r)))})),t.logger.info(s.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O,{status:n.SUCCESSED,trackId:e,uri:r},{logSource:t.LogSource.RTC}),this}reset(){return o.info("MCUConfigBuilder.reset ->"),this._values=qr(),t.logger.info(s.L_MCU_CONFIG_BUILDER_RESET_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),this}flush(e=!0){return r(this,void 0,void 0,(function*(){const r=JSON.parse(JSON.stringify(this._values)),{code:o}=yield this._invoker.push(new Gr(r,this._values));return e&&(this._values=qr()),t.logger.info(s.L_MCU_CONFIG_BUILDER_FLUSH_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),{code:o}}))}__innerGetValues(){return JSON.parse(JSON.stringify(this._values))}}var Yr,Qr,zr,Zr;e.RCLivingType=void 0,(Yr=e.RCLivingType||(e.RCLivingType={}))[Yr.VIDEO=0]="VIDEO",Yr[Yr.AUDIO=1]="AUDIO",function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(Qr||(Qr={}));class Xr extends Cr{constructor(e,t,r){super(),this.roomId=e,this.hooks=t,this.roomPKHandler=r}_exchangeWithPushOtherRoom(t,i){return r(this,void 0,void 0,(function*(){if(!t.getLocalTracks().length)return;const r=Object.values(t.peerMgr.getMutilPeerCData()),s=Object.keys(t.peerMgr.getMutilPeerCData());for(let n=0;n<r.length;n++){const{pc:a,isPub:c}=r[n],d=c&&t.useMutilPeerC?[]:t.getSubscribedList(),u=yield Tr(d,!1,a,t),{pushOtherRooms:_,headers:l}=this.hooks(s[n]);u.pushOtherRooms=_;const R=yield new Lr(l,u).execute(t,i);if(R.code!==e.RCRTCCode.SUCCESS)return void o.error(`exchange with pushOtherRoom failed: ${R.code}`);const{sdp:C,resultCode:h}=R.data;if(h!==e.RCRTCCode.SUCCESS)return void o.error(`exchange with pushOtherRoom failed: ${h}`);a.setRemoteAnswer(C.sdp)}}))}execute(e,i){return r(this,void 0,void 0,(function*(){const{roomId:r}=this;if(t.logger.info(s.L_LIVING_ROOM_JOINED_PK_ROOM_T,{roomId:r,userId:e.crtUserId},{logSource:t.LogSource.RTC}),!this.roomPKHandler)return void t.logger.error(s.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:n.FAILED,code:"",msg:"_roomPKHandler not exist"},{logSource:t.LogSource.RTC});const a=this.roomPKHandler.getPKInfo(r);if(!a)return o.warn(`exchange to update pushOtherRoom cancel, pkInfo lost -> roomId: ${r}`),void t.logger.error(s.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:n.FAILED,code:"",msg:"PKInfo not exist"},{logSource:t.LogSource.RTC});yield this._exchangeWithPushOtherRoom(e,i),t.logger.info(s.L_LIVING_ROOM_JOINED_PK_ROOM_T,{status:n.SUCCESSED,roomId:r,userId:e.crtUserId,PKInfo:a},{logSource:t.LogSource.RTC})}))}}class eo extends Cr{constructor(e,t,r,o,i,s){super(),this.pkHandler=e,this.room=t,this._PKInfo=r,this.hooks=o,this._joinedPKRooms=i,this.isQuitPK=s}get kind(){return qt.LeaveRoom}quitRoomPK(i,s){return r(this,void 0,void 0,(function*(){if(!this._PKInfo[i])return;const{inviterRoomId:r,inviteeRoomId:n,inviterUserId:a,inviteSessionId:c}=this._PKInfo[i],d={inviteeRoomId:n,inviterRoomId:r,userId:s.crtUserId},u={roomId:s.roomId,endRoomId:i,sessionId:c,content:JSON.stringify(d),keys:[`${r}|${a}`]};o.info(`quitRoomPK -> params: ${JSON.stringify(u)}`);const _=yield s.context.endRoomPK(u);return _!==t.ErrorCode.SUCCESS?(o.error(`quitRoomPK failed: ${_}`),{code:e.RCRTCCode.SIGNAL_ERROR}):(o.info("quitRoomPK success"),delete this._PKInfo[i],{code:e.RCRTCCode.SUCCESS})}))}execute(i,a){return r(this,void 0,void 0,(function*(){const{room:r,isQuitPK:c}=this,d=r.getRoomId();return o.info(`leavePKRoom -> userId: ${i.crtUserId} , roomId: ${d}`),t.logger.info(s.L_LIVING_ROOM_LEAVE_PK_ROOM_T,{roomId:d,userId:i.crtUserId,isQuitPK:c},{logSource:t.LogSource.RTC}),yield r.__destroy(!0),delete this._joinedPKRooms[d],yield new Xr(d,this.hooks,this.pkHandler).execute(i,a),c&&this.quitRoomPK(d,i),t.logger.info(s.L_LIVING_ROOM_LEAVE_PK_ROOM_R,{status:n.SUCCESSED,roomId:d,userId:i.crtUserId,isQuitPK:c},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS}}))}}class to{constructor(e,t,r,o,i,s,n,a,c,d,u){this._invoker=e,this._PKInfo=t,this._hooks=r,this._context=o,this._runtime=i,this._service=s,this._initOptions=n,this._mainLivingRoom=a,this._registerPKMsgListener=c,this._onJoinedPKRoom=d,this._clientSessionId=u,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:o,extra:i}=t,s={inviterRoomId:r,inviterUserId:o,extra:i};this._PKInfo[r]=t,this._callAppListener("onRequestJoinOtherRoom",s)}_onCancelInvite(e){const{inviterRoomId:t,inviterUserId:r,extra:o}=e.inviteInfo||{},i={inviterRoomId:t,inviterUserId:r,extra:o};delete this._PKInfo[t],this._callAppListener("onCancelRequestOtherRoom",i)}_onInviteTimeout(e){}_onInviteAnswer(e){const{answerCode:t,inviteContent:r}=e,{inviteSessionId:o,inviterUserId:i,inviterRoomId:s,inviteeUserId:n,inviterUserAutoMix:a,inviteeUserAutoMix:c,inviteeRoomId:d,extra:u}=r,_={agree:1===t,inviterRoomId:s,inviterUserId:i,inviteeRoomId:d,inviteeUserId:n,extra:u};this._PKInfo[d]=this._PKInfo[d]||{inviteSessionId:o,inviterRoomId:s,inviterUserId:i,inviterUserAutoMix:a,inviteeRoomId:d},this._PKInfo[d].inviteeUserAutoMix=c,this._callAppListener("onResponseJoinOtherRoom",_)}createLeaveOtherRoomCommand(e,t){return new eo(this,e,this._PKInfo,this._hooks,this._joinedPKRooms,t)}_onPKEnd(e){return r(this,void 0,void 0,(function*(){const{inviteeRoomId:t,inviterRoomId:r,userId:o}=e.inviteInfo,i=r===this._mainRoomId?t:r,s={endRoomId:i,endUserId:o},n=this._joinedPKRooms[i];n&&(yield this._invoker.push(this.createLeaveOtherRoomCommand(n))),delete this._PKInfo[i],this._callAppListener("onFinishOtherRoom",s)}))}_onRecvPKMsg(e){const{targetId:t,content:r,messageType:o}=e;switch(o){case Tt.PK_INVITE:this._onInvite(r);break;case Tt.PK_CANCEL_INVITE:this._onCancelInvite(r);break;case Tt.PK_INVITE_TIMEOUT:this._onInviteTimeout(r);break;case Tt.PK_INVITE_ANSWER:this._onInviteAnswer(r);break;case Tt.PK_END:this._onPKEnd(r)}}registerRoomPKEventListener(e){t.logger.info(s.L_LIVING_PK_HANDLER_REGISTER_ROOM_PK_EVENT_LISTENER_O,{status:n.SUCCESSED,listener:e&&Object.keys(e)},{logSource:t.LogSource.RTC}),this._appListener=e}requestJoinOtherRoom(i,a,c){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:i,inviteeUserId:a,options:c},{logSource:t.LogSource.RTC}),!t.validate("inviteeRoomId",i,t.notEmptyString,!0)||!t.validate("inviteeUserId",a,t.notEmptyString,!0))return t.logger.error(s.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> inviteeRoomId 或 inviteeUserId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`requestRoomPK -> inviteeRoomId: ${i}; inviteeUserId: ${a}; options: ${JSON.stringify(c||{})}`);const r=Lt(),d=!t.isBoolean(null==c?void 0:c.autoMix)||(null==c?void 0:c.autoMix),u={inviteSessionId:r,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:d,inviteeRoomId:i,inviteeUserId:a,inviteeTimeoutTime:this._inviteTimeout,extra:(null==c?void 0:c.extra)||""},_={roomId:this._mainRoomId,invitedRoomId:i,invitedUserId:a,inviteTimeout:this._inviteTimeout,inviteInfo:JSON.stringify(u),inviteSessionId:r};o.info(`requestRoomPK -> params: ${JSON.stringify(_)}`);const l=yield this._context.requestRoomPK(_);return l!==t.ErrorCode.SUCCESS?(o.error(`requestRoomPK failed: ${l}`),t.logger.error(s.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:l,msg:""},{logSource:t.LogSource.RTC}),{code:l}):(o.info("requestRoomPK success"),this._PKInfo[i]={inviteSessionId:r,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:d,inviteeRoomId:i},t.logger.info(s.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{inviteeRoomId:i,inviteeUserId:a,options:c},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS})}))}cancelRequestJoinOtherRoom(i,a,c){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:i,inviteeUserId:a,extra:c,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:t.LogSource.RTC}),!t.validate("inviteeRoomId",i,t.notEmptyString,!0)||!t.validate("inviteeUserId",a,t.notEmptyString,!0))return t.logger.error(s.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> inviteeRoomId or inviteeUserId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(!this._PKInfo[i])return o.error(`The request to connect with ${a} user in room ${i} is not initiated`),t.logger.error(s.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:`The request to connect with ${a} user in room ${i} is not initiated`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`canceRequestJoinPK -> inviteeRoomId: ${i}; inviteeUserId: ${a}; extra: ${c}`);const r={inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviteeRoomId:i,inviteeUserId:a,extra:c||""},d={roomId:this._mainRoomId,invitedRoomId:i,invitedUserId:a,inviteSessionId:this._PKInfo[i].inviteSessionId,inviteInfo:JSON.stringify(r)};o.info(`canceRequestJoinPK -> params: ${JSON.stringify(d)}`);const u=yield this._context.cancelRoomPK(d);return u!==t.ErrorCode.SUCCESS?(o.error(`canceRequestJoinPK failed: ${u}`),t.logger.error(s.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:u,msg:`The request to connect with ${a} user in room ${i} is not initiated`},{logSource:t.LogSource.RTC}),{code:u}):(o.info("canceRequestJoinPK success"),t.logger.info(s.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:n.SUCCESSED,inviteeRoomId:i,inviteeUserId:a,extra:c},{logSource:t.LogSource.RTC}),delete this._PKInfo[i],{code:e.RCRTCCode.SUCCESS})}))}responseJoinOtherRoom(i,a,c,d){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_T,{inviterRoomId:i,inviterUserId:a,agree:c,options:d,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:t.LogSource.RTC}),!t.validate("inviterRoomId",i,t.notEmptyString,!0)||!t.validate("inviterUserId",a,t.notEmptyString,!0))return t.logger.error(s.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> inviterRoomId or inviterUserId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(!this._PKInfo[i])return o.error(`User ${a} in room ${i} did not send a request for connection`),t.logger.error(s.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:`User ${a} in room ${i} did not send a request for connection`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`responseRoomPK -> inviterRoomId: ${i}; inviterUserId: ${a}; agree: ${c}; options: ${JSON.stringify(d||{})}`);const{inviteSessionId:r,inviterUserAutoMix:u}=this._PKInfo[i],_=!t.isBoolean(null==d?void 0:d.autoMix)||(null==d?void 0:d.autoMix),l={inviteSessionId:r,inviterRoomId:i,inviterUserId:a,inviterUserAutoMix:u,inviteeRoomId:this._mainRoomId,inviteeUserId:this._context.getCurrentId(),inviteeUserAutoMix:_},R=Object.assign(l,{inviterUserAutoMix:u}),C=c?Object.assign(l,{MultiRoomKey:`${i}|${this._mainRoomId}`,MultiRoomValue:JSON.stringify(R)}):l;!t.isUndefined(null==d?void 0:d.extra)&&Object.assign(C,{extra:d.extra});const h={agree:c,roomId:this._mainRoomId,inviteSessionId:r,inviteRoomId:i,inviteUserId:a,content:JSON.stringify(C),key:`${i}|${this._mainRoomId}`,value:JSON.stringify(l)};o.info(`responseRoomPK -> params: ${JSON.stringify(h)}`);const g=yield this._context.responseRoomPK(h);return g!==t.ErrorCode.SUCCESS?(o.error(`responseRoomPK failed: ${g}`),t.logger.error(s.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:g,msg:""},{logSource:t.LogSource.RTC}),{code:g}):(o.info("responseRoomPK success"),t.logger.info(s.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:n.SUCCESSED,inviterRoomId:i,inviterUserId:a,agree:c,options:d,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:t.LogSource.RTC}),this._PKInfo[i].inviteeUserAutoMix=_,{code:e.RCRTCCode.SUCCESS})}))}joinOtherRoom(i){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_T,{roomId:i,userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),!t.validate("roomId",i,t.notEmptyString,!0))return t.logger.error(s.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(this._context.getConnectionStatus()!==t.ConnectionStatus.CONNECTED)return t.logger.error(s.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.SIGNAL_DISCONNECTED,msg:"IM disconnected"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_DISCONNECTED};if(o.info(`JoinPKRoom, roomId: ${i}`),this._joinedPKRooms[i])return t.logger.warn(s.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REPERT_JOIN_ROOM};const r=e.RCLivingType.VIDEO,a={extra:`{"roomId": "${this._mainRoomId}"}`},c=new io(this._context,this._runtime,i,this._service,this._initOptions,r,!1,!1,!1,this._clientSessionId),{code:d,data:u}=yield c.__innerInit(zt.LIVE,void 0,r,a);return d!==e.RCRTCCode.SUCCESS?(o.error(`JoinPKRoom failed -> code: ${d}`),t.logger.error(s.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:d,msg:""},{logSource:t.LogSource.RTC}),{code:d}):(o.info(`JoinPKRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${i}, data: ${JSON.stringify(u)}`),this._joinedPKRooms[i]=c,yield this._onJoinedPKRoom(i,c),t.logger.info(s.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:n.SUCCESSED,roomId:i,userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),{room:c,code:e.RCRTCCode.SUCCESS,userIds:c.getRemoteUserIds(),tracks:c.getRemoteTracks()})}))}leaveOtherRoom(e,t){return r(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"}(zr||(zr={}));class ro extends Cr{constructor(e,t){super(),this.cdnValues=e,this.enable=t}execute(i,a){return r(this,void 0,void 0,(function*(){const{enable:r}=this;if(t.logger.info(s.L_LIVING_ROOM_ENABLE_INNER_CDN_T,{roomId:i.roomId,enable:r},{logSource:t.LogSource.RTC}),!i.isMainRoom)return o.error("the `enableInnerCDN` is disabled in PK room"),t.logger.error(s.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:n.FAILED,code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!t.isBoolean(r))return o.error("`enable` is invalid"),t.logger.error(s.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> enable"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};i.setCDNEnabel(r);const c={version:2,output:{inCDNModel:r?zr.OPEN:zr.STOP}},{code:d}=yield new Gr(c,this.cdnValues).execute(i,a);if(d!==e.RCRTCCode.SUCCESS)return o.error(`enableInnerCDN failed -> code: ${d}`),t.logger.error(s.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:n.FAILED,code:d,msg:"signal error"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_ERROR};const u=i.getCDNUris();if(u&&u.broadcast!==tr.SPREAD)return o.info("enableInnerCDN succeed"),t.logger.info(s.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:n.SUCCESSED,enable:r},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS};const{code:_}=yield fr(i);return _===e.RCRTCCode.SUCCESS?(o.info("enableInnerCDN succeed"),t.logger.info(s.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:n.SUCCESSED,enable:r},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS}):(o.error(`enableInnerCDN failed -> code: ${_}`),t.logger.error(s.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:n.FAILED,code:_,msg:""},{logSource:t.LogSource.RTC}),{code:_})}))}}!function(e){e[e.AnchorToViewer=1]="AnchorToViewer",e[e.ViewerToAnchor=2]="ViewerToAnchor"}(Zr||(Zr={}));class oo extends Cr{constructor(e){super(),this.livingType=e}execute(e,o){var i;return r(this,void 0,void 0,(function*(){const{code:r,data:s}=yield e.context.rtcIdentityChange(e.roomId,Zr.ViewerToAnchor,this.livingType);if(r!==t.ErrorCode.SUCCESS||!s)return{code:r};e.initWithRoomData(s);e.getResourcesByUserId(e.crtUserId).length>0&&o.push(new Sr);const n=null===(i=s.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===i?void 0:i.value;return n&&e.setCDNUris(JSON.parse(n)[0]),{code:r,data:s}}))}}class io extends Fr{constructor(e,t,r,o,i,s,n,a,c,d){super(e,t,r,zt.LIVE,o,i,n,a,c,d),this._livingType=s,this._mcuConfigBuilder=new Wr(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 o=JSON.parse(t.value),{inviterRoomId:i,inviteeRoomId:s}=o;r[e===i?s:i]=JSON.parse(t.value)})),r})(this._roomId,e.roomInfo);this._roomPKHandler=new to(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(o,i,a,c,d){const u=Object.create(null,{__innerInit:{get:()=>super.__innerInit}});return r(this,void 0,void 0,(function*(){if(!t.validate("livingType",a,(t=>t===e.RCLivingType.AUDIO||t===e.RCLivingType.VIDEO)))return t.logger.error(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> livingType"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};const{code:r,data:_}=yield u.__innerInit.call(this,o,i,a,c,d);return r===e.RCRTCCode.SUCCESS&&_&&this._initAfterCatchRoomData(_),{code:r,data:_}}))}__innerInitByIdentityChange(){return r(this,void 0,void 0,(function*(){const{code:e,data:r}=yield this._invoker.push(new oo(this._livingType));return e===t.ErrorCode.SUCCESS&&r&&(this._initAfterCatchRoomData(r),this._initWithRoomData(r.offlineKickTime),t.logger.info(s.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:n.SUCCESSED,roomData:r},{logSource:t.LogSource.RTC})),e}))}publish(i){const a=Object.create(null,{publish:{get:()=>super.publish}});return r(this,void 0,void 0,(function*(){return this._store.isMainRoom?a.publish.call(this,i):(o.warn("the `publish` is disabled in PK room "),t.logger.error(s.L_ABSTRACT_ROOM_PUBLISH_R,{status:n.FAILED,code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}unpublish(i){const a=Object.create(null,{unpublish:{get:()=>super.unpublish}});return r(this,void 0,void 0,(function*(){return this._store.isMainRoom?a.unpublish.call(this,i):(o.warn("the `unpublish` is disabled in PK room "),t.logger.error(s.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:n.FAILED,code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}_isValidResourceId(t){var r;const{userId:o}=rt(t),i=!!(null===(r=this._store.getResourcesByUserId(o))||void 0===r?void 0:r.find((e=>tt(e)===t)));let s=!1;const{code:n,roomPKHandler:a}=this.getRoomPKHandler();if(n!==e.RCRTCCode.SUCCESS||!a)return i;const c=a.getJoinedPKRooms(),d=[];return Object.values(c).forEach((e=>{d.push(...e.getRemoteTracks())})),s=d.some((e=>t===e.getTrackId())),i||s}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._store.isMainRoom?this._mcuConfigBuilder:(o.error("the `getMCUConfigBuilder` is disabled in PK room"),{code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}enableInnerCDN(e){return r(this,void 0,void 0,(function*(){return this._invoker.push(new ro(this._mcuConfigBuilder.__innerGetValues(),e))}))}_resourceHandle(e,t,o){const i=Object.create(null,{_resourceHandle:{get:()=>super._resourceHandle}});return r(this,void 0,void 0,(function*(){i._resourceHandle.call(this,e,t,o)}))}_afterChangedRole(e){const t=gt(e,this._roomId),r=this._context.getCurrentId(),o=Object.keys(t);setTimeout((()=>{var i;const s=o.filter((e=>e!==r));s.length>0&&this._callAppListener("onUserJoin",s);for(const e in t)e!==r&&this._resourceHandle({uris:t[e]},Tt.TOTAL_CONTENT_RESOURCE,e);if(!(null===(i=e.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===i?void 0:i.value))return;const n=this._store.getCDNUris();(null==n?void 0:n.push_mode)===Qr.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 r(this,void 0,void 0,(function*(){this._invoker.push(new Xr(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 o=t[r].getSessionId(),i=this._roomPKHandler.getPKInfo(r);if(!i)continue;const{inviterUserAutoMix:s,inviteeUserAutoMix:n,inviterUserId:a}=i,c=this._context.getCurrentId()===a;e.push({roomId:r,sessionId:o,autoMix:c?!!s:!!n})}return e}getRoomPKHandler(){return this._store.isMainRoom?(t.logger.info(s.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,roomPKHandler:this._roomPKHandler}):(o.error("the `getRoomPKHandler` is disabled in PK room"),t.logger.error(s.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:n.SUCCESSED,code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}_quitAllPKRoom(){return r(this,void 0,void 0,(function*(){const e=this._roomPKHandler.getJoinedPKRooms();for(const t in e)this._roomPKHandler.leaveOtherRoom(e[t]);t.logger.info(s.L_LIVING_ROOM_QUIT_ALL_PK_ROOM_O,{status:n.SUCCESSED,roomIds:Object.keys(e)},{logSource:t.LogSource.RTC})}))}isMainRoom(){return this._store.isMainRoom}}class so extends Fr{constructor(e,t,r,o,i,s,n,a,c,d=zt.RTC){super(e,t,r,d,o,i,s,n,a,c)}}const no=new class{constructor(){this.queue=[],this.locked=!1,this.taskCount=0}checkToStart(){return r(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 o;try{o=yield t(),e(o)}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}},ao=(e,t="")=>no.push(e,t);class co{constructor(e,t,r,o){this._context=e,this._useMutilPeerC=o,this._rtcToken="",this._liveUrl="",this._subTracks=[],this._clientSessionId=Lt(),this._livingType=null,this._mediaType=null,this._subTiny=!1,this._fromRetry=!1,this._appListener=null,this._service=new Nt(t,e,r.mediaServer),this._peerCManager=new Rr(this._useMutilPeerC,this._context.getCurrentId(),this._reTryExchange.bind(this),this._context.getCurrentId())}_getReqHeaders(i){return r(this,void 0,void 0,(function*(){const r=this._context.getCurrentId(),s=r;if(!this._rtcToken){const{code:r,data:n}=yield this._context.getRTCToken(s,zt.LIVE,i);if(r!==t.ErrorCode.SUCCESS)return o.error(`getRTCToken failed: ${r}`),{code:e.RCRTCCode.SIGNAL_ERROR};this._rtcToken=n.rtcToken}return{code:e.RCRTCCode.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:r,RoomId:s,RoomType:zt.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 t;return r(this,void 0,void 0,(function*(){this._fromRetry=!0;const{code:r}=yield this.subscribe(this._liveUrl,this._livingType,this._mediaType,this._subTiny);r===e.RCRTCCode.SUCCESS&&(null===(t=this._pc)||void 0===t||t.clearReTryExchangeTimer())}))}subscribe(e,t,o,i=!1){return r(this,void 0,void 0,(function*(){return ao((()=>this.__subscribe(e,t,o,i)),"audience-client-sub")}))}__subscribe(i,a,c,d=!1){var u;return r(this,void 0,void 0,(function*(){t.logger.info(s.L_AUDIENCE_CLIENT_SUBSCRIBE_T,{liveUrl:i,livingType:a,mediaType:c,subTiny:d},{logSource:t.LogSource.RTC});const r=[];if(ht(this._context.getNaviInfo()))return t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,tracks:r};if(!this._fromRetry&&(null===(u=this._pc)||void 0===u||u.clearReTryExchangeTimer()),this._fromRetry=!1,!t.isString(i))return o.error(`liveUrl is invalid: ${i}`),t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:`params error -> liveUrl: ${i}`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR,tracks:r};if(![e.RCLivingType.AUDIO,e.RCLivingType.VIDEO].includes(a))return o.error(`livingType is invalid: ${a}`),t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:`params error -> livingType: ${a}`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR,tracks:r};if(![e.RCMediaType.AUDIO_ONLY,e.RCMediaType.VIDEO_ONLY,e.RCMediaType.AUDIO_VIDEO].includes(c))return o.error(`mediaType is invalid: ${c}`),t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:`params error -> -> mediaType: ${c}`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR,tracks:r};if(this._liveUrl&&this._liveUrl!==i)return t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.BROADCAST_SUB_LIST_NOT_EMPTY,msg:"repeat subscribe"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.BROADCAST_SUB_LIST_NOT_EMPTY,tracks:r};if(!this._pc){const{pcName:e,pc:t}=this._peerCManager.createPeerCList(r)[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=i;const{code:_,headers:l}=yield this._getReqHeaders(a);if(_!==e.RCRTCCode.SUCCESS)return t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:_,msg:""},{logSource:t.LogSource.RTC}),{code:_,tracks:r};const R=`rc_mcu_${Date.now()}`,C="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new Je(C,R),new qe(C,R)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const h=`${Date.now()}`;At.getMemo().qualityStatus=h,t.logger.info(s.L_QS_CREATE_OFFER_O,{identify:h},{logSource:t.LogSource.RTC});const g={sdp:yield this._pc.createOffer(!0),liveUrl:i,mediaType:c,simulcast:d?bt.TINY:bt.NORMAL,switchstream:!1};t.logger.info(s.L_QS_SUBSCRIBE_EXCHANGE_O,{identify:h},{logSource:t.LogSource.RTC});const p=yield this._service.broadcastSubscribe(l,g);if(p.code!==e.RCRTCCode.SUCCESS)return o.error(`andience subscribe failed: ${p.code}`),t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:p.code,msg:""},{logSource:t.LogSource.RTC}),{code:p.code,tracks:r};const S=p.data;if(S.resultCode!==e.RCRTCCode.SUCCESS)return o.error(`andience subscribe failed! code: ${S.resultCode}; message: ${S.message}`),t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:S.resultCode,msg:""},{logSource:t.LogSource.RTC}),{code:S.resultCode,tracks:r};o.debug(`andience subscribe success: ${i}`),this._livingType=a,this._mediaType=c,this._subTiny=d;const{sdp:m,subscribedList:T}=S;t.logger.info(s.L_QS_GET_ANSWER_O,{identify:h},{logSource:t.LogSource.RTC});const I=[];return T.forEach((e=>{const{mediaType:t}=e,r=this._subTracks[t];I.push(r),r.__innerSetRemoteMuted(!0)})),t.logger.info(s.L_QS_GET_RESOURCES_O,{identify:h},{logSource:t.LogSource.RTC}),this._pc.setRemoteAnswer(m.sdp),t.logger.info(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.SUCCESSED,liveUrl:i},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,tracks:I}}))}unsubscribe(){return r(this,void 0,void 0,(function*(){return ao((()=>this.__unsubscribe()),"audience-client-unsub")}))}__unsubscribe(){var i;return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_AUDIENCE_CLIENT_UNSUBSCRIBE_T,{liveUrl:this._liveUrl},{logSource:t.LogSource.RTC}),null===(i=this._pc)||void 0===i||i.clearReTryExchangeTimer(),!this._rtcToken||!this._liveUrl)return t.logger.warn(s.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:n.FAILED,code:"",msg:"Address does not exist, without unsubscribe"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS};const{headers:r}=yield this._getReqHeaders(),{code:a}=yield this._service.broadcastExit(r);return a!==e.RCRTCCode.SUCCESS?(o.error(`broadcast unsubscribe failed: ${a}`),t.logger.error(s.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:n.FAILED,code:a,msg:""},{logSource:t.LogSource.RTC})):(o.debug("broadcast unsubscribe success"),t.logger.info(s.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:n.SUCCESSED,liveUrl:this._liveUrl},{logSource:t.LogSource.RTC})),this._clearSubscribeInfo(),{code:a}}))}registerReportListener(e){this._reportListener=e}registerTrackEventListener(e){this._appListener=e}_onTrackReady(r){var i,n;const{track:a}=r.receiver,c="audio"===a.kind?e.RCMediaType.AUDIO_ONLY:e.RCMediaType.VIDEO_ONLY,d=this._subTracks[c];d.__innerSetMediaStreamTrack(a);const u=At.getMemo();t.logger.info(s.L_QS_CREATE_OFFER_O,{identify:u.qualityStatusId},{logSource:t.LogSource.RTC});try{null===(n=null===(i=this._appListener)||void 0===i?void 0:i.onTrackReady)||void 0===n||n.call(i,d)}catch(e){o.error(e)}}}var uo,_o;e.RCInnerCDNPullKind=void 0,(uo=e.RCInnerCDNPullKind||(e.RCInnerCDNPullKind={})).RTMP="rtmp",uo.FLV="flv",uo.HLS="hls",e.RCInnerCDNPullIsHttps=void 0,(_o=e.RCInnerCDNPullIsHttps||(e.RCInnerCDNPullIsHttps={}))[_o.NOT_HTTPS=0]="NOT_HTTPS",_o[_o.HTTPS=1]="HTTPS";const lo=Object.assign(Object.assign({},at(e.RCResolution.W176_H144)),{frameRate:ut(e.RCFrameRate.FPS_15)});class Ro{constructor(e,t,i,s,n,a,c,d=Lt()){this._context=e,this._runtime=t,this._initOptions=i,this._roomId=s,this._joinResData=n,this.livingType=a,this._useMutilPeerC=c,this._clientSessionId=d,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 Nt(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new _r(this._context,this._runtime,this._roomId,this,jt.Audience),this._polarisReport.sendR1(),this._peerCManager=new Rr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._context.registerRTCSignalListener((e=>r(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,i){return r(this,void 0,void 0,(function*(){if(this._isPulling)return;this._isPulling=!0;if(this._pullTime>i)return void(this._isPulling=!1);const{code:r,data:s}=yield this._context.pullRTCRoomEntry(e);if(r===t.ErrorCode.SUCCESS){this._isPulling=!1,this._pullTime=s.syncTime||0;const t=(null==s?void 0:s.kvEntries)||[];o.info(`_startPull -> ${JSON.stringify(t)}`),this.singalDataChange(t,e)}}))}_setInitData(){const{sessionId:e,remoteUserIds:t,remoteRTCUris:r,remoteMUCUris:o,remoteTracks:i,CDNUris:s}=pt(this._roomId,this._joinResData.kvEntries);this._sessionId=e,this._roomAnchorList=t,i.forEach((e=>{this._remoteTracks[e.getTrackId()]=e})),this._CDNUris=s,r.forEach((e=>{const t=e.msid.split("_")[0];this._roomAnchorRes[t]?this._roomAnchorRes[t].push(e):this._roomAnchorRes[t]=[e]})),o.forEach((e=>{const{mediaType:t,tag:r}=e,o=[this._roomId,r,t].join("_");this._roomRes[o]=e})),r.forEach((e=>{const t=tt(e);this._roomRes[t]=e}))}_assertRoomDestroyed(){if(this._destroyed){const t="This room has been destroyed. Please use `RCRTCClient.joinLivingRoomAsAudience` to catch another instance.";return o.warn(t),e.RCRTCCode.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(e,r){var i;if(t.logger.info(s.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_T,{singalData:e,roomId:r,userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),r!==this._roomId)return o.warn(`singalDataChange -> not the current room data: data roomId: ${r}, current roomId: ${this._roomId}`),void t.logger.error(s.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:n.FAILED,code:"",msg:`id inconsistency -> params id:${r},current id:${this._roomId}`},{logSource:t.LogSource.RTC});o.debug("singalDataChange -> singalData:",JSON.stringify(e||{}));const a=[],c=null===(i=e.filter((e=>"RC_CDN"===e.key))[0])||void 0===i?void 0:i.value;c&&this._diffCDNUris(JSON.parse(JSON.parse(c).cdn_uris)[0]),e.forEach((e=>{const{key:t,value:r,timestamp:o,uid:i}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),o=JSON.parse(e.uris||"[]");return a.push(...t),void this._diffAnchorResource(o,i)}if("RC_ANCHOR_LIST"===t){const e=JSON.parse(r||"[]"),{joinUserIds:t,leftUserIds:o}=this._diffAnchorList(e);t.length>0&&this._handleNewJoinedAnchor(t),o.length>0&&this._handleLeftedAnchor(o)}})),this._diffRoomResource(a),t.logger.info(s.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:n.SUCCESSED,singalData:e,roomId:r,userId:this._context.getCurrentId()},{logSource:t.LogSource.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 r(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(t){return r(this,void 0,void 0,(function*(){const r=[],o=[],i=[];t.forEach((t=>{const o=tt(t),{userId:s,tag:n,mediaType:a}=rt(o),c=[this._roomId,n,a].join("_");if(!this._remoteTracks[c]){const o=a===e.RCMediaType.AUDIO_ONLY?new Je(n,"",this._roomId):new qe(n,"",this._roomId);r.push(o),this._remoteTracks[c]=o,this._roomRes[o.getTrackId()]=t}i.push(c)})),Object.keys(this._remoteTracks).forEach((e=>{i.indexOf(e)<0&&this._remoteTracks[e].isMCUTrack()&&o.push(this._remoteTracks[e])})),r.length>0&&this._callAppListener("onTrackPublish",r),o.length>0&&this._onUserUnpublish(o,"onTrackUnpublish")}))}_diffAnchorResource(t,i){return r(this,void 0,void 0,(function*(){const r=this._roomAnchorRes[i]||(this._roomAnchorRes[i]=[]),{publishedList:s,unpublishedList:n,modifiedList:a}=st(r,t);if(s.length){const t=r.map(tt),i=[],n=[];if(s.forEach((o=>{const s=tt(o),a=t.indexOf(s),{userId:c,tag:d,mediaType:u}=rt(s);a>-1?r[a]=o:r.push(o);let _=this._remoteTracks[s];this._roomRes[s]=o,_?_.isSubscribed()&&i.push(_):(_=u===e.RCMediaType.AUDIO_ONLY?new Je(d,c):new qe(d,c),this._remoteTracks[s]=_,n.push(_)),_.__innerSetRemoteMuted(0===o.state)})),i.length){const t=i.map((e=>e.getTrackId()));o.debug(`resub tracks -> ${JSON.stringify(t)}`);const{code:r}=yield ao((()=>this._subscribeHandle(i,!0)));r!==e.RCRTCCode.SUCCESS&&o.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(t)}`)}this._callAppListener("onAnchorTrackPublish",n)}if(n.length){const e=n.map(tt);for(let t=r.length-1;t>=0;t-=1){const o=r[t];e.includes(tt(o))&&r.splice(t,1)}const t=n.map((e=>{const t=tt(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t,"onAnchorTrackUnpublish")}if(a.length){const e=r.map(tt);for(let t=0;t<a.length;t++){const o=a[t],i=tt(o),s=e.indexOf(i);r[s].state=o.state;const n=this._remoteTracks[i];n.__innerSetRemoteMuted(0===o.state),n.isAudioTrack()?this._callAppListener("onAudioMuteChange",n):this._callAppListener("onVideoMuteChange",n)}}}))}_onUserUnpublish(e,t){return r(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 r(this,void 0,void 0,(function*(){ao((()=>r(this,void 0,void 0,(function*(){var t;const{reqBody:r}=yield this._createSubscribeParams(this._subscribedList,{},!0),i=yield this._exchangeHandle(r);if(i.code!==e.RCRTCCode.SUCCESS)return o.error(`reTryExchange failed: ${i.code}`),{code:i.code};const{sdp:s,resultCode:n}=i.data;if(n!==e.RCRTCCode.SUCCESS)return o.error(`reTryExchange failed: ${n}`),{code:n};this._pc.clearReTryExchangeTimer();const a=this._subscribedList.filter((e=>e.track.isMCUTrack()));if(a.length>0){const e=a[0].track.getTrackId(),r=null===(t=this._roomRes[e])||void 0===t?void 0:t.msid,o=[this._roomId,"RongCloudRTC"].join("_");s.sdp=s.sdp.replace(new RegExp(r,"g"),o)}const c=yield this._pc.setRemoteAnswer(s.sdp);return c!==e.RCRTCCode.SUCCESS?{code:c}:void 0}))),"audience-retry-exchange")}))}_createSubscribeParams(e,t,o){return r(this,void 0,void 0,(function*(){const r=yield this._pc.createOffer(o),i={resolutionInfo:[]},s={min:0,max:0};Object.keys(t).forEach((e=>{const{mediaStream:o,tinyStream:n}=t[e];[o,n].forEach(((t,o)=>{var n;const a=1===o?[e,"tiny"].join("_"):e;r.sdp=null===(n=r.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===o,{width:u,height:_,frameRate:l}=d?Xe(c):lo;i.resolutionInfo.push({trackId:c.id,simulcast:d?bt.NORMAL:bt.TINY,resolution:`${u}x${_}`});const R=Le(u,_),C=Oe(l);s.min+=R.minBitrate*C,s.max+=R.maxBitrate*C}))}));return{reqBody:{sdp:r,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?bt.TINY:bt.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:s,offer:r}}))}_subscribeHandle(o,i=!1){var a;return r(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return t.logger.error(s.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.ROOM_HAS_BEEN_DESTROYED,msg:"room destroyed"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!t.validate("tracks",o,(()=>t.isArray(o)&&o.length>0&&o.every((e=>e instanceof je||e.track instanceof je))),!0))return t.logger.error(s.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};const{pc:r,pcName:c}=this._peerCManager.createPeerCList(o)[0];this._pc=r,this._pc.__reportR3R4ToPolaris(),this._pcName=c,this._pc.registerReportListener(this._reportListener),this._addPeerCEvent();const d=this._subscribedList.map((e=>Object.assign({},e))),u=o.map((e=>e instanceof je?{track:e}:e));let _=!1;const l=[];return u.forEach((e=>{const t=e.track.getTrackId();l.push(t);const r=d.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:d.push(e),_=!0)})),_||i?(null===(a=this._polarisReport)||void 0===a||a.sendR2(Xt.SUBSCRIBE,er.BEGIN,l),t.logger.info(s.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:n.SUCCESSED,trackIds:o.map(St),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:i},{logSource:t.LogSource.RTC}),this._updateSubListHandle(d,!0)):(t.logger.warn(s.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:n.FAILED,code:"",msg:"repeat subscribe"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS})}))}_addPeerCEvent(){this._pc.on(ur.__INNER_EVENT_TRACK_READY__,(r=>{const i=r.streams[0].id,{track:n}=r.receiver,a=[i,"audio"===n.kind?e.RCMediaType.AUDIO_ONLY:e.RCMediaType.VIDEO_ONLY].join("_"),c=this._remoteTracks[a];if(!c)return void o.warn("cannot found RCRemoteTrack:",n.id);c.__innerSetMediaStreamTrack(n);const d=At.getMemo();t.logger.info(s.L_QS_TRACK_READY_O,{identify:d.qualityStatusId},{logSource:t.LogSource.RTC}),this._callAppListener("onTrackReady",c)}))}_getReqHeaders(){const e=this._context.getCurrentId();return{"App-Key":this._context.getAppkey(),RoomId:e,Token:this._joinResData.token,RoomType:zt.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(i,n=!1){var a;return r(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:e.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!t.validate("resources",i,(()=>t.isArray(i)&&i.every((e=>e instanceof je||e.track instanceof je))),!0))return{code:e.RCRTCCode.PARAMS_ERROR};let r=i.map((e=>e instanceof je?{track:e}:Object.assign({},e)));const c={};r=r.filter((e=>{const t=e.track.getTrackId();return!c[t]&&(c[t]=!0,!0)})).map((e=>Object.assign({},e)));const d=this._subscribedList.map((e=>Object.assign({},e)));if(!n){let t=!1;if(r.forEach((e=>{const r=d.findIndex((t=>t.track===e.track));if(-1===r)return void(t=!0);d.splice(r,1)[0].subTiny!==e.subTiny&&(t=!0)})),d.length&&(t=!0),!t)return{code:e.RCRTCCode.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(r.map((e=>e.track)));const u=At.getMemo(),_={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};u.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};u.qualityUnsubscribeReportData=l,u.unsubscribeData={start:Date.now()},t.logger.info(s.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_T,{trackIds:i.map(St),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:n},{logSource:t.LogSource.RTC});const{reqBody:R}=yield this._createSubscribeParams(r,{},!1),C=yield this._exchangeHandle(R);let h=[],g=Date.now();if(u.mediaService.forEach((e=>{h.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),d.length){const e=[];d.forEach((t=>{e.push(t.track.getTrackId())})),null===(a=this._pc.reportParser)||void 0===a||a.clearLatestPacketsRecv(e)}if(C.code!==e.RCRTCCode.SUCCESS)return u.subscribeCommand&&(u.subscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualitySubscribeReportData,{dur:g-((null===(r=u.subscribeData)||void 0===r?void 0:r.start)||0),cod:C.code,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,i,t.LogSource.RTC)}))),u.unsubscribeCommand&&(u.unsubscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualityUnsubscribeReportData,{dur:g-((null===(r=u.unsubscribeData)||void 0===r?void 0:r.start)||0),cod:C.code,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,i,t.LogSource.RTC)}))),{code:C.code};const{sdp:p,resultCode:S,message:m,subscribedList:T}=C.data;if(S!==e.RCRTCCode.SUCCESS)return u.subscribeCommand&&(u.subscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualitySubscribeReportData,{dur:g-((null===(r=u.subscribeData)||void 0===r?void 0:r.start)||0),cod:S,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,i,t.LogSource.RTC)}))),u.unsubscribeCommand&&(u.unsubscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualityUnsubscribeReportData,{dur:g-((null===(r=u.unsubscribeData)||void 0===r?void 0:r.start)||0),cod:S,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,i,t.LogSource.RTC)}))),o.error("change subscribe list failed:",m,S),{code:S};r.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:o}=rt(t.getTrackId()),i=[o,r].join("_");p.sdp=p.sdp.replace(new RegExp(e,"g"),i)}}));const I=yield this._pc.setRemoteAnswer(p.sdp);if(I!==e.RCRTCCode.SUCCESS)return u.subscribeCommand&&(u.subscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualitySubscribeReportData,{dur:g-((null===(r=u.subscribeData)||void 0===r?void 0:r.start)||0),cod:I,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,i,t.LogSource.RTC)}))),u.unsubscribeCommand&&(u.unsubscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualityUnsubscribeReportData,{dur:g-((null===(r=u.unsubscribeData)||void 0===r?void 0:r.start)||0),cod:I,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,i,t.LogSource.RTC)}))),{code:I};u.subscribeCommand&&(u.subscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualitySubscribeReportData,{dur:g-((null===(r=u.subscribeData)||void 0===r?void 0:r.start)||0),cod:I,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,i,t.LogSource.RTC)}))),u.unsubscribeCommand&&(u.unsubscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualityUnsubscribeReportData,{dur:g-((null===(r=u.unsubscribeData)||void 0===r?void 0:r.start)||0),cod:I,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,i,t.LogSource.RTC)})));const E=null==T?void 0:T.map((e=>`${e.msid}_${e.mediaType}`)),f=r.filter((e=>{if(e.track.isMCUTrack()){const t=this._roomRes[e.track.getTrackId()],r=`${t.msid}_${t.mediaType}`;return E.includes(r)}return null==E?void 0:E.includes(e.track.getTrackId())})),L=null==f?void 0:f.map((e=>`${e.track.getTrackId()}`)),v=r.filter((e=>!(null==L?void 0:L.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=f.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...f),v.length?{code:e.RCRTCCode.SUCCESS,failedList:v}:{code:e.RCRTCCode.SUCCESS}}))}_diffCDNUris(e){return r(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,o=this._CDNUris.fps&&e.fps&&this._CDNUris.fps!==e.fps;(t||r||o)&&this._callAppListener("onCDNInfoChange",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`}),this._CDNUris=e}))}_getCDNPlayUrl(t){return r(this,void 0,void 0,(function*(){const{w:r,h:i,fps:s}=t,n=this._initOptions.pullInnerCDNProtocol||e.RCInnerCDNPullKind.FLV,a=this._initOptions.pullInnerCDNUseHttps===e.RCInnerCDNPullIsHttps.NOT_HTTPS?e.RCInnerCDNPullIsHttps.NOT_HTTPS:e.RCInnerCDNPullIsHttps.HTTPS;if(!this._CDNUris.url)return o.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${e.RCRTCCode.CDN_RESOURCE_IS_EMPTY}`),{code:e.RCRTCCode.CDN_RESOURCE_IS_EMPTY};const c={"App-Key":this._context.getAppkey(),Token:this._joinResData.token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},d=[],{w:u=0,h:_=1}=this._CDNUris;u/_>1?(r&&d.push(`w=${r}`),i&&d.push(`h=${i}`)):(r&&d.push(`h=${r}`),i&&d.push(`w=${i}`)),s&&d.push(`fps=${s}`),d.push(`kind=${n}`),d.push(`is_https=${a}`);const l=d.join("&");let R=`${this._CDNUris.url}?`;l&&(R+=l);const{code:C,res:h}=yield this._service.getCDNResourceInfo(c,R);return C!==e.RCRTCCode.SUCCESS?(o.error(`getCDNPlayUrl failed: ${C}`),{code:C}):(o.info(`getCDNPlayUrl success: ${null==h?void 0:h.data.pull_url}`),{code:C,CDNPlayUrl:null==h?void 0:h.data.pull_url})}))}getCDNPlayUrl(i,a){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_T,{resolution:i,fps:a},{logSource:t.LogSource.RTC}),i&&!ct(i))return o.error("`resolution` is invalid"),t.logger.error(s.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> resolution"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(a&&!dt(a))return o.error("`fps` is invalid"),t.logger.error(s.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> fps"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};const{width:r,height:c}=i?at(i):{width:null,height:null},d=a?ut(a):null,u={};return r&&(u.w=r),c&&(u.h=c),d&&(u.fps=d),t.logger.info(s.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:n.SUCCESSED,resolution:i,fps:a},{logSource:t.LogSource.RTC}),this._getCDNPlayUrl(u)}))}subscribe(e){return r(this,void 0,void 0,(function*(){return At.getMemo().subscribeCommand=!0,ao((()=>this._subscribeHandle(e,!1)),"audience-sub")}))}addSubscribeTask(e){return r(this,void 0,void 0,(function*(){return At.getMemo().subscribeCommand=!0,ao((()=>this._subscribeHandle(e,!1)),"audience-sub")}))}__unsubscribe(i){var a;return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_T,{trackIds:i.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),!t.validate("tracks",i,(()=>t.isArray(i)&&i.length>0&&i.every((e=>e instanceof je))),!0))return o.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),t.logger.error(s.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};const r=this._subscribedList.map((e=>Object.assign({},e))).filter((e=>!i.includes(e.track)));null===(a=this._polarisReport)||void 0===a||a.sendR2(Xt.SUBSCRIBE,er.END,i.map((e=>e.getTrackId()))),t.logger.info(s.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:n.SUCCESSED,trackIds:i.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC});return At.getMemo().unsubscribeCommand=!0,this._updateSubListHandle(r,!1)}))}unsubscribe(e){return r(this,void 0,void 0,(function*(){return ao((()=>this.__unsubscribe(e)),"audience-unsub")}))}addUnsubscribeTask(e){return r(this,void 0,void 0,(function*(){return ao((()=>this.__unsubscribe(e)),"audience-unsub")}))}__destroy(e){var t,o;return r(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===(o=this._pc)||void 0===o||o.destroy(),At.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 r(this,void 0,void 0,(function*(){const{code:e}=yield this._context.joinLivingRoomAsAudience(this._roomId,zt.LIVE);e!==t.ErrorCode.SUCCESS&&o.error("join living room error when on reconnected")}))}registerRoomEventListener(e){this._appListener=e}onAudioLevelChange(e,r){var o;null===(o=this._audioLevelReport)||void 0===o||o.clearAudioLevelReportTimer(),this._audioLevelReport=new lr(this),this._audioLevelReport.onAudioLevelChange(e,r||1e3),t.logger.info(s.L_AUDIENCE_LIVING_ROOM_AUDIO_LEVEL_CHANGE_O,{status:n.SUCCESSED,handler:null==e?void 0:e.name,gap:r},{logSource:t.LogSource.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 o=this._remoteTracks[r];o.getUserId()===e&&t.push(o)}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 Co{constructor(e){this._context=e,this._isElectron=/Electron/.test(navigator.userAgent)}_getMediaStream(t,i="getUserMedia"){return r(this,void 0,void 0,(function*(){try{const r=this.setConstraintsConfig(t),o=yield navigator.mediaDevices[i](r);return{code:e.RCRTCCode.SUCCESS,stream:o}}catch(t){if("Permission denied"===t.message)return{code:e.RCRTCCode.BROWSER_PERMISSION_DENIED};if("Permission denied by system"===t.message)return{code:e.RCRTCCode.SYSTEM_PERMISSION_DENIED};o.error(`get user media failed -> ${t.message}`)}return{code:"getUserMedia"===i?e.RCRTCCode.GET_USER_MEDIA_FAILED:e.RCRTCCode.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(o="RongCloudRTC",i){return r(this,void 0,void 0,(function*(){if(!Qe(o))return t.logger.error(s.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return t.logger.error(s.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID};const{stream:a,code:c}=yield this._getMediaStream({audio:{deviceId:null==i?void 0:i.micphoneId,sampleRate:null==i?void 0:i.sampleRate}});if(c!==e.RCRTCCode.SUCCESS)return t.logger.error(s.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:n.FAILED,code:c,msg:"Failed to get microphone audio stream"},{logSource:t.LogSource.RTC}),{code:c};const d=a.getAudioTracks()[0],u=new Fe(o,r,d);return t.logger.info(s.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:n.SUCCESSED,trackId:u.getTrackId()},{logSource:t.LogSource.RTC}),{code:c,track:u}}))}createCameraVideoTrack(o="RongCloudRTC",i){return r(this,void 0,void 0,(function*(){if(!Qe(o))return t.logger.error(s.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return t.logger.error(s.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID};const a=ct(null==i?void 0:i.resolution)?i.resolution:e.RCResolution.W640_H480,{width:c,height:d}=at(a),{stream:u,code:_}=yield this._getMediaStream({video:{deviceId:null==i?void 0:i.cameraId,frameRate:ut((null==i?void 0:i.frameRate)||e.RCFrameRate.FPS_15),width:c,height:d,facingMode:null==i?void 0:i.faceMode}});if(_!==e.RCRTCCode.SUCCESS)return t.logger.error(s.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"Failed to get camera video stream"},{logSource:t.LogSource.RTC}),{code:_};const l=u.getVideoTracks()[0],R=new Ge(o,r,l);return t.logger.info(s.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:n.SUCCESSED,trackId:R.getTrackId()},{logSource:t.LogSource.RTC}),{code:_,track:R}}))}createMicrophoneAndCameraTracks(o="RongCloudRTC",i){var a,c,d,u,_,l;return r(this,void 0,void 0,(function*(){const r=[];if(!Qe(o))return t.logger.error(s.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS,tracks:r};const R=this._context.getCurrentId();if(!R)return t.logger.error(s.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID,tracks:r};const C=ct(null===(a=null==i?void 0:i.video)||void 0===a?void 0:a.resolution)?i.video.resolution:e.RCResolution.W640_H480,{width:h,height:g}=at(C),{stream:p,code:S}=yield this._getMediaStream({video:{deviceId:null===(c=null==i?void 0:i.video)||void 0===c?void 0:c.cameraId,frameRate:ut((null===(d=null==i?void 0:i.video)||void 0===d?void 0:d.frameRate)||e.RCFrameRate.FPS_15),width:h,height:g,facingMode:null===(u=null==i?void 0:i.video)||void 0===u?void 0:u.faceMode},audio:{deviceId:null===(_=null==i?void 0:i.audio)||void 0===_?void 0:_.micphoneId,sampleRate:null===(l=null==i?void 0:i.audio)||void 0===l?void 0:l.sampleRate}});return S!==e.RCRTCCode.SUCCESS?(t.logger.error(s.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:n.FAILED,code:S,msg:"Failed to get audio and video stream of camera and microphone"},{logSource:t.LogSource.RTC}),{code:S,tracks:r}):(p.getTracks().forEach((e=>{"video"===e.kind?r.push(new Ge(o,R,e)):r.unshift(new Fe(o,R,e))})),t.logger.info(s.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:n.SUCCESSED,trackIds:r.map((e=>e.getTrackId()))},{logSource:t.LogSource.RTC}),{code:S,tracks:r})}))}createScreenVideoTrack(t="screenshare",o){return r(this,void 0,void 0,(function*(){const r=yield this._createScreenTracks(t,!1,s.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,o);return r.code===e.RCRTCCode.SUCCESS?{code:r.code,track:r.tracks[0]}:r}))}createScreenWithAudioTracks(e="screenshare",t){return r(this,void 0,void 0,(function*(){return this._createScreenTracks(e,!0,s.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_AND_AUDIO_TRACKS_O,t)}))}_createScreenTracks(o,i,a,c){var d,u;return r(this,void 0,void 0,(function*(){if(!Qe(o))return t.logger.error(a,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return t.logger.error(a,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID};if(!Rt())return t.logger.error(s.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.BROWSER_NOT_SUPPORT};const _=/macintosh|mac os x/i.test(navigator.userAgent);this._isElectron&&_&&i&&t.logger.warn(a,{status:n.INFO,code:e.RCRTCCode.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO,msg:"mac in electron not support screen share with audio"});const l=(!this._isElectron||!_)&&i;if(this._isElectron&&!t.isUndefined(null==c?void 0:c.chromeMediaSourceId)&&!t.isString(null==c?void 0:c.chromeMediaSourceId))return t.logger.error(a,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> options.chromeMediaSourceId type is string"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};const R=ct(null==c?void 0:c.resolution)?c.resolution:e.RCResolution.W1280_H720,{width:C,height:h}=at(R),g=this._isElectron?{mandatory:{chromeMediaSourceId:null==c?void 0:c.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:C,maxWidth:C,minHeight:h,maxHeight:h}}:{frameRate:ut((null==c?void 0:c.frameRate)||e.RCFrameRate.FPS_15),width:C,height:h};!(null==c?void 0:c.chromeMediaSourceId)&&this._isElectron&&(null===(d=g.mandatory)||void 0===d||delete d.chromeMediaSourceId);let p=null;l&&this._isElectron&&(null===(u=g.mandatory)||void 0===u||delete u.chromeMediaSourceId,p={mandatory:{chromeMediaSource:"desktop"}});const{stream:S,code:m}=yield this._getMediaStream({video:g,audio:p||l},this._isElectron?"getUserMedia":"getDisplayMedia");if(m!==e.RCRTCCode.SUCCESS)return t.logger.error(a,{status:n.FAILED,code:m,msg:"Failed to get shared screen video stream"},{logSource:t.LogSource.RTC}),{code:m};const T=S.getVideoTracks()[0],I=[new Ke(o,r,T)];if(l){const e=S.getAudioTracks()[0];e&&I.push(new He(o,r,e))}return t.logger.info(a,{status:n.SUCCESSED,trackIds:I.map((e=>e.getTrackId()))},{logSource:t.LogSource.RTC}),{code:m,tracks:I}}))}createLocalAudioTrack(o,i){return r(this,void 0,void 0,(function*(){if(!Qe(o))return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS};if(!i||"[object MediaStreamTrack]"!==i.toString()||"audio"!==i.kind)return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"Failed to create custom stream"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED};const r=this._context.getCurrentId();if(!r)return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID};const a=new xe(o,r,i);return t.logger.info(s.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:n.SUCCESSED,trackId:a.getTrackId()},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,track:a}}))}createLocalVideoTrack(o,i){return r(this,void 0,void 0,(function*(){if(!Qe(o))return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS};if(!i||"[object MediaStreamTrack]"!==i.toString()||"video"!==i.kind)return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED,msg:"Failed to create custom stream"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED};const r=this._context.getCurrentId();if(!r)return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID};const a=new we(o,r,i);return t.logger.info(s.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:n.SUCCESSED,trackId:a.getTrackId()},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,track:a}}))}createLocalFileTracks(i,a,c){return r(this,void 0,void 0,(function*(){if(!Qe(i))return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS,tracks:[]};if(!lt())return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.BROWSER_NOT_SUPPORT,tracks:[]};const r=a instanceof File?URL.createObjectURL(a):a;if(!t.isHttpUrl(r)&&!/^blob:/.test(r))return o.warn(`createLocalFileTracks failed: params error -> url: ${r}`),t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> file"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR,tracks:[]};const d=this._context.getCurrentId();return d?new Promise((a=>{const u=document.createElement("video");(null==c?void 0:c.withoutAudio)&&(u.muted=!0),u.onloadedmetadata=()=>{const _=[];let l;try{const e=u.mozCaptureStream?"mozCaptureStream":"captureStream";l=u[e]()}catch(i){o.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${r}`),o.error(i),t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:t.LogSource.RTC}),a({code:e.RCRTCCode.CREATE_FILE_TRACK_FAILED,tracks:_})}const[R,C]=Co.getTracksWithOptions(l,c);R&&_.push(new $e(i,d,R,u)),C&&_.push(new Ve(i,d,C,u)),0===_.length&&(u.pause(),u.src=""),u.onerror=null,t.logger.info(s.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:n.SUCCESSED,trackIds:_.map((e=>e.getTrackId()))},{logSource:t.LogSource.RTC}),a({code:e.RCRTCCode.SUCCESS,tracks:_})},u.onerror=()=>{o.error(`create RCLocalFileTrack failed -> url: ${r}`),t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:t.LogSource.RTC}),a({code:e.RCRTCCode.CREATE_FILE_TRACK_FAILED,tracks:[]})},u.src=r,u.loop=!0,u.play()})):(t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID,tracks:[]})}))}createLocalTracks(o,i,a){return r(this,void 0,void 0,(function*(){const r=[];if(!Qe(o))return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS,tracks:r};if(!(i instanceof MediaStream))return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> stream"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR,tracks:r};const c=this._context.getCurrentId();if(!c)return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID,tracks:r};const[d,u]=Co.getTracksWithOptions(i,a);return d&&r.push(new xe(o,c,d)),u&&r.push(new we(o,c,u)),t.logger.info(s.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:n.SUCCESSED,trackIds:r.map((e=>e.getTrackId()))},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,tracks:r}}))}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 ho extends Co{constructor(e,t,r){super(e),this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,ir.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new Nt(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.ConversationType.RTC_ROOM)return!1;if(this._crtRoom instanceof io){this._getJoinedPKRoomList().forEach((t=>{t.__parseInnerMessage(e)}))}return t.logger.info(s.L_RTC_CLIENT_MESSAGE_O,{status:n.SUCCESSED,message:e},{logSource:t.LogSource.RTC}),this._crtRoom?(this._crtRoom.__parseInnerMessage(e),!0):(t.logger.warn(s.L_RTC_CLIENT_MESSAGE_O,{status:n.FAILED,message:"the crtRoom is empty"},{logSource:t.LogSource.RTC}),!0)}naviDataChange(e){t.logger.info(`on navi change data => ${JSON.stringify(e)}`),this._service.detectorMediaSever()}_getJoinedPKRoomList(){const{code:t,roomPKHandler:r}=this._crtRoom.getRoomPKHandler();if(t===e.RCRTCCode.SUCCESS&&r){const e=r.getJoinedPKRooms()||{};return Object.values(e)}return[]}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(o,i,a,c,d=zt.RTC){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_RTC_CLIENT_JOIN_RTC_ROOM_T,{roomId:o,joinType:i,outerUserDatas:a,useMutilPeerC:c,roomType:d},{logSource:t.LogSource.RTC}),this._crtRoom)return t.logger.error(s.L_RTC_CLIENT_JOIN_RTC_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REPERT_JOIN_ROOM};const r=this._crtRoom=new so(this._context,this._runtime,o,this._service,this._options,!1,!1,c,Lt()),{code:u}=yield r.__innerInit(d,i,void 0,void 0,a);return u!==e.RCRTCCode.SUCCESS?(this._crtRoom=null,{code:u}):(r.once($r,(()=>{this._crtRoom=null})),{code:u,room:r,userIds:r.getRemoteUserIds(),tracks:r.getRemoteTracks()})}))}joinCrossRTCRoom(o,i,a,c,d=zt.CROSS_MUTI){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_T,{roomId:o,joinType:i,outerUserDatas:a,useMutilPeerC:c,roomType:d},{logSource:t.LogSource.RTC}),this._crtRoom)return t.logger.error(s.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REPERT_JOIN_ROOM};const r=this._crtRoom=new so(this._context,this._runtime,o,this._service,this._options,!1,!1,c,Lt(),d),{code:u}=yield r.__innerInit(d,i,void 0,void 0,a);return u!==e.RCRTCCode.SUCCESS?(this._crtRoom=null,{code:u}):(r.once($r,(()=>{this._crtRoom=null})),{code:u,room:r,userIds:r.getRemoteUserIds(),tracks:r.getRemoteTracks()})}))}joinLivingRoom(o,i,a,c,d){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_T,{roomId:o,livingType:i,joinType:a,outerUserDatas:c,useMutilPeerC:d},{logSource:t.LogSource.RTC}),this._crtRoom)return t.logger.error(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.REPERT_JOIN_ROOM,msg:`Join the room repeatedly -> roomId: ${o}`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REPERT_JOIN_ROOM};const r=this._crtRoom=new io(this._context,this._runtime,o,this._service,this._options,i,!1,!0,d),{code:u}=yield r.__innerInit(zt.LIVE,a,i,void 0,c);if(u!==e.RCRTCCode.SUCCESS)return this._crtRoom=null,{code:u};r.once($r,(()=>{this._crtRoom=null}));const _={code:u,room:r,userIds:r.getRemoteUserIds(),tracks:r.getRemoteTracks()};return r.__getCDNPushMode()===Qr.MANUAL&&Object.assign(_,{CDNEnable:r.__getCDNEnable()}),_}))}getAudienceClient(e){return this._audience||(this._audience=new co(this._context,this._runtime,this._options,e)),t.logger.info(s.L_RTC_CLIENT_GET_AUDIENCE_CLIENT_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),this._audience}_onIMStatusChange(e){if(o.debug(`signal server connection state change: ${e}`),t.logger.info(s.L_RTC_CLIENT_CONNECTION_STATE_S,{status:n.SUCCESSED,data:e},{logSource:t.LogSource.RTC}),e===t.ConnectionStatus.CONNECTED){if(this._service.detectorMediaSever(),this._crtRoom instanceof io){this._getJoinedPKRoomList().forEach((e=>{e.__onReconnected()}))}this._crtRoom&&this._crtRoom.__onReconnected()}}_onIMDisconnect(){t.logger.info(s.L_RTC_CLIENT_DISCONNECT_S,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),o.debug("TODO -> on IM disconnect")}_onIMUninit(){t.logger.info(s.L_RTC_CLIENT_DESTROY_S,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),o.debug("TODO -> on IM client ondestroy")}leaveRoom(i){var a,c;return r(this,void 0,void 0,(function*(){return t.logger.info(s.L_RTC_CLIENT_LEAVE_ROOM_T,{userId:this._context.getCurrentId(),roomId:null===(a=this._crtRoom)||void 0===a?void 0:a.getRoomId()},{logSource:t.LogSource.RTC}),this._crtRoom?(yield this._crtRoom.__destroy(!0),o.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),this._service.detectorMediaSever(),t.logger.info(s.L_RTC_CLIENT_LEAVE_ROOM_R,{status:n.SUCCESSED,userId:this._context.getCurrentId(),roomId:null===(c=this._crtRoom)||void 0===c?void 0:c.getRoomId()},{logSource:t.LogSource.RTC}),this._crtRoom=null,{code:e.RCRTCCode.SUCCESS}):(t.logger.warn(s.L_RTC_CLIENT_LEAVE_ROOM_R,{status:n.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS})}))}joinLivingRoomAsAudience(i,a,c){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_T,{roomId:i,livingType:a,useMutilPeerC:c},{logSource:t.LogSource.RTC}),this._service.detectorMediaSever(),ht(this._context.getNaviInfo()))return t.logger.error(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:n.FAILED,code:e.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR};if(!t.validate("roomId",i,t.notEmptyString,!0)||!t.validate("livingType",a,(t=>t===e.RCLivingType.AUDIO||t===e.RCLivingType.VIDEO)))return t.logger.error(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:n.FAILED,code:e.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"params error -> roomId or livingType"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return t.logger.error(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:n.FAILED,code:e.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REPERT_JOIN_ROOM};if(!this._service.getNaviMS().length)return t.logger.error(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:n.FAILED,code:e.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:r,data:d}=yield this._context.joinLivingRoomAsAudience(i,zt.LIVE,a);if(r!==t.ErrorCode.SUCCESS)return o.error("audienceJoinLivingRoomError:",r),t.logger.error(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:n.FAILED,code:e.RCRTCCode.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED,msg:"signal error -> audience join room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};o.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(d)}`);const u=Lt();At.getMemo().clientData={clientSessionId:u};const _=new Ro(this._context,this._runtime,this._options,i,d,a,c,u);return this._crtAudienceLivingRoom=_,t.logger.info(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:n.SUCCESSED,roomData:d},{logSource:t.LogSource.RTC}),{room:_,code:e.RCRTCCode.SUCCESS,userIds:_.getRemoteUserIds(),RTCTracks:_.getRemoteRTCTracks(),MCUTracks:_.getRemoteMCUTracks(),CDNUris:_.getCDNInfo()}}))}leaveLivingRoomAsAudience(o){return r(this,void 0,void 0,(function*(){return t.logger.info(s.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_T,{roomId:o.getRoomId(),userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),this._crtAudienceLivingRoom?this._crtAudienceLivingRoom!==o?(t.logger.error(s.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR}):(yield this._crtAudienceLivingRoom.__destroy(!0),this._crtAudienceLivingRoom=null,t.logger.info(s.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:n.SUCCESSED,roomId:o.getRoomId(),userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS}):(t.logger.warn(s.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:n.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS})}))}upgradeToAnchorRoom(i){return r(this,void 0,void 0,(function*(){if(!t.validate("room",i,(()=>i instanceof Ro),!0))return t.logger.error(s.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(t.logger.info(s.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_T,{roomId:i.getRoomId(),userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),this._crtRoom)return t.logger.error(s.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REPERT_JOIN_ROOM};const r=i.getRoomId(),a=this._crtRoom=new io(this._context,this._runtime,r,this._service,this._options,i.livingType,!0,!0,!1,i.getClientSessionId()),c=yield a.__innerInitByIdentityChange();return c!==t.ErrorCode.SUCCESS?(o.warn(`change room identity failed -> code: ${c}`),this._crtRoom=null,t.logger.error(s.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):(a.once($r,(()=>{this._crtRoom=null})),yield this._crtAudienceLivingRoom.__destroy(!1),this._crtAudienceLivingRoom=null,{room:a,code:e.RCRTCCode.SUCCESS,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()})}))}downgradeToAudienceRoom(i){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_T,{roomId:i._roomId,userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),!i.isMainRoom())return o.error("the `downgradeToAudienceRoom` is disabled in PK room"),t.logger.error(s.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!t.validate("room._roomId",i._roomId,t.notEmptyString,!0))return t.logger.error(s.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> room._roomId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return t.logger.error(s.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REPERT_JOIN_ROOM};const{code:r,data:a}=yield this._context.rtcIdentityChange(i._roomId,Zr.AnchorToViewer,i.getLivingType());if(r!==t.ErrorCode.SUCCESS)return o.error("change room identity error",r),t.logger.error(s.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};o.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(a)}`),t.logger.info(s.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:n.SUCCESSED,roomData:a},{logSource:t.LogSource.RTC});const c=i.getClientSessionId(),d=new Ro(this._context,this._runtime,this._options,i._roomId,a,i.getLivingType(),!1,c);return this._crtAudienceLivingRoom=d,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:d,code:e.RCRTCCode.SUCCESS,userIds:d.getRemoteUserIds(),RTCTracks:d.getRemoteRTCTracks(),MCUTracks:d.getRemoteMCUTracks(),CDNUris:d.getCDNInfo()}}))}getJoinedRoomInfo(){return r(this,void 0,void 0,(function*(){const{code:r,data:i}=yield this._context.getRTCJoinedUserInfo(this._context.getCurrentId());return r!==t.ErrorCode.SUCCESS?(o.error("getJoinedUserInfo error",r),t.logger.error(s.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:n.FAILED,code:r,msg:"Switch identity error"},{logSource:t.LogSource.RTC}),{code:r}):(t.logger.info(s.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:n.SUCCESSED,roomInfo:i},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,data:i})}))}reportSDKInfo(){this._context.reportSDKInfo({"plugin-rtc":"5.5.2"})}}const go="rtcRJoin_data",po="rtcRExit",So="rtcRInfo",mo="rtcUData",To="rtcUDel",Io="rtcSetData",Eo="userSetData",fo="rtcQryData",Lo="rtcDelData",vo="rtcToken",Oo="rtcUserState",Ao="rtcUList",Do="viewerJoinR",No="viewerExitR",bo="rtcPullKv",yo="rtcIdentityChange",ko="rtcInvite",Uo="rtcCancelInvite",Po="rtcInviteAnswer",Mo="rtcEndInvite",xo="rtcQueryJoined",wo="reportsdk";var Bo;!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"}(Bo||(Bo={}));const Vo={[Bo.RtcInput]:["roomType","broadcastType","extraInnerData","needSysChatroom","identityChangeType","joinType","innerDatas","outerDatas"],[Bo.RtcUserListOutput]:["users","token","sessionId","roomInfo"],[Bo.SetUserStatusInput]:["status"],[Bo.RtcSetDataInput]:["interior","target","key","value","objectName","content"],[Bo.RtcUserSetDataInput]:["valueInfo","objectName","content"],[Bo.RtcDataInput]:["interior","target","key","objectName","content"],[Bo.RtcSetOutDataInput]:["target","valueInfo","objectName","content"],[Bo.MCFollowInput]:["state"],[Bo.RtcTokenOutput]:["rtcToken"],[Bo.RtcQryOutput]:["outInfo"],[Bo.RtcQryUserOutDataInput]:["userId"],[Bo.RtcUserOutDataOutput]:["user"],[Bo.RtcQueryListInput]:["order"],[Bo.RtcRoomInfoOutput]:["roomId","roomData","userCount","list"],[Bo.RtcValueInfo]:["key","value"],[Bo.RtcKeyDeleteInput]:["key"],[Bo.RtcNotifyMsg]:["type","time","roomId"],[Bo.RtcPullKV]:["timestamp","roomId"],[Bo.RtcKVOutput]:["entries","bFullUpdate","syncTime"],[Bo.RtcQueryUserJoinedInput]:["userId"],[Bo.RtcQueryUserJoinedOutput]:["info"],[Bo.RtcInviteInput]:["invitedUserId","timeoutTime","invitedRoomId","inviteInfo","inviteSessionId"],[Bo.RtcCancelInviteInput]:["invitedUserId","invitedRoomId","inviteInfo","inviteSessionId"],[Bo.RtcInviteAnswerInput]:["inviteUserId","answerCode","inviteRoomId","inviteSessionId","content","key","value"],[Bo.RtcEndInviteInput]:["inviteRoomId","inviteSessionId","inviteContent","inviteRoomKeys"],[Bo.RtcReportSDKInput]:["sdkInfo"]},$o=`\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 ${Bo.SetUserStatusInput}\n {\n optional int32 status=1;\n }\n message ${Bo.MCFollowInput}\n {\n required string state = 1;\n }\n message ${Bo.RtcQueryListInput}{\n optional int32 order=1;\n }\n message ${Bo.RtcKeyDeleteInput}{\n repeated string key=1;\n }\n message ${Bo.RtcValueInfo}{\n required string key=1;\n required string value=2;\n }\n message RtcUserInfo{\n required string userId=1;\n repeated ${Bo.RtcValueInfo} userData=2; //用户资源信息\n }\n message ${Bo.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 ${Bo.RtcValueInfo} roomData = 2;\n optional int32 userCount = 3;\n repeated RtcUserInfo list=4;\n }\n message ${Bo.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 ${Bo.RtcValueInfo} innerDatas = 7; //用户内部inner数据,角色或者连麦信息等\n repeated ${Bo.RtcValueInfo} outerDatas = 8; //用户内部outer数据,自定义数据结构RtcInput。\n }\n message ${Bo.RtcQryOutput}{\n repeated ${Bo.RtcValueInfo} outInfo=1;\n }\n message ${Bo.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 ${Bo.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 ${Bo.RtcUserSetDataInput} {\n repeated ${Bo.RtcValueInfo} valueInfo = 1;\n required string objectName = 2;\n repeated ${Bo.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 ${Bo.RtcTokenOutput}{\n required string rtcToken=1;\n }\n message ${Bo.RtcSetOutDataInput}{\n required targetType target=1;\n repeated ${Bo.RtcValueInfo} valueInfo=2;\n optional string objectName=3;\n optional string content=4;\n }\n message ${Bo.RtcQryUserOutDataInput}{\n repeated string userId = 1;\n }\n message ${Bo.RtcUserOutDataOutput}{\n repeated RtcUserInfo user = 1;\n }\n message ${Bo.RtcNotifyMsg} \n {\n required int32 type= 1; //(通知类型 1:rtc房间状态KV变更通知)\n optional int64 time= 2; //消息产生时间\n optional string roomId=3; //主播房间id\n }\n message ${Bo.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 ${Bo.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 ${Bo.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 ${Bo.RtcQueryUserJoinedOutput}\n {\n repeated RtcJoinedInfo info = 1;\n }\n message ${Bo.RtcViewerJoinedOutput}\n {\n required string rtcToken=1;\n repeated RtcKVEntity entries = 2;//KV属性对象集合\n optional int64 syncTime = 3;//所有属性的最大时间戳(下次拉取KV时用)。\n }\n message ${Bo.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 ${Bo.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 ${Bo.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 ${Bo.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 ${Bo.RtcReportSDKInput} {\n required string sdkInfo=1; // 用户集成的 sdk 信息,json 格式 {"web-rtc": "4.0.3.7"}\n }\n}\n`,Fo=(e,t,r,o,i,s)=>{const n=i?Object.keys(i).map((t=>e.encode(Bo.RtcValueInfo,{key:t,value:i[t]},!0))):void 0,a=s?Object.keys(s).map((t=>e.encode(Bo.RtcValueInfo,{key:t,value:s[t]},!0))):void 0;return e.encode(Bo.RtcInput,{roomType:t,broadcastType:r,joinType:o,innerDatas:n,outerDatas:a})},Go=(e,r)=>{const o=e.decode(Bo.RtcUserListOutput,r),{users:i,token:s,sessionId:n,roomInfo:a,entries:c,offlineKickTime:d}=o,u={};return t.forEach(i,(e=>{const{userId:r,userData:o}=e,i={};t.forEach(o,(e=>{const{key:t,value:r}=e;i[t]=r})),u[r]=i})),{users:u,token:s,sessionId:n,roomInfo:a,kvEntries:c,offlineKickTime:d}};class Ko{constructor(e,t){this.context=e,this.codec=t}joinRTCRoom(e,o,i,s,n,a){return r(this,void 0,void 0,(function*(){const r=Fo(this.codec,o,i,s,n,a),{code:c,buffer:d}=yield this.context.rtcSignaling(e,go,!0,r);let u;return c===t.ErrorCode.SUCCESS&&d&&(u=Go(this.codec,d)),{code:c,data:u}}))}quitRTCRoom(e){return r(this,void 0,void 0,(function*(){const t=this.codec.encode(Bo.SetUserStatusInput,{status:0}),{code:r}=yield this.context.rtcSignaling(e,po,!0,t);return r}))}getRTCRoomInfo(e){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcQueryListInput,{order:2}),{code:o,buffer:i}=yield this.context.rtcSignaling(e,So,!0,r);let s;return o===t.ErrorCode.SUCCESS&&i&&(s=this.codec.decode(Bo.RtcRoomInfoOutput,i)),{code:o,data:s}}))}getRTCUserInfoList(e){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcQueryListInput,{order:2}),{code:o,buffer:i}=yield this.context.rtcSignaling(e,mo,!0,r);let s;if(o===t.ErrorCode.SUCCESS&&i){s={users:Go(this.codec,i).users}}return{code:o,data:s}}))}getRTCUserInfo(e){throw new Error("Method not implemented.")}removeRTCUserInfo(e,t){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcKeyDeleteInput,{key:t}),{code:o}=yield this.context.rtcSignaling(e,To,!1,r);return o}))}setRTCData(e,t,o,i,s,n){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcSetDataInput,{interior:i,target:s,key:t,value:o,objectName:null==n?void 0:n.name,content:null==n?void 0:n.content}),{code:a}=yield this.context.rtcSignaling(e,Io,!1,r);return a}))}setRTCTotalRes(e,t,o,i,s){return r(this,void 0,void 0,(function*(){const r={objectName:i,content:this.codec.encode(Bo.RtcValueInfo,{key:t.name,value:t.content},!0),valueInfo:[this.codec.encode(Bo.RtcValueInfo,{key:"uris",value:o},!0),this.codec.encode(Bo.RtcValueInfo,{key:"mcu_uris",value:s},!0)]},n=this.codec.encode(Bo.RtcUserSetDataInput,r),{code:a}=yield this.context.rtcSignaling(e,Eo,!0,n);return a}))}setRTCCDNUris(e,t,o){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcUserSetDataInput,{objectName:t,valueInfo:this.codec.encode(Bo.RtcValueInfo,{key:"cdn_uris",value:o},!0)}),{code:i}=yield this.context.rtcSignaling(e,Eo,!0,r);return i}))}getRTCData(e,o,i,s){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcDataInput,{interior:i,target:s,key:o}),{code:n,buffer:a}=yield this.context.rtcSignaling(e,fo,!0,r);if(n!==t.ErrorCode.SUCCESS||!a)return{code:n};const{outInfo:c}=this.codec.decode(Bo.RtcQryOutput,a),d={};return c.forEach((e=>{d[e.key]=e.value})),{code:n,data:d}}))}removeRTCData(e,t,o,i,s){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcDataInput,{interior:o,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,Lo,!1,r);return n}))}setRTCOutData(e,t,o,i){return r(this,void 0,void 0,(function*(){throw new Error("JSEngine's method not implemented.")}))}getRTCOutData(e,t){return r(this,void 0,void 0,(function*(){throw new Error("JSEngine's method not implemented.")}))}getRTCToken(e,o,i){return r(this,void 0,void 0,(function*(){const r=Fo(this.codec,o,i),{code:s,buffer:n}=yield this.context.rtcSignaling(e,vo,!0,r);if(s!==t.ErrorCode.SUCCESS||!n)return{code:s};const{rtcToken:a}=this.codec.decode(Bo.RtcTokenOutput,n);return{code:s,data:{rtcToken:a}}}))}setRTCState(e,t){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.MCFollowInput,{state:t}),{code:o}=yield this.context.rtcSignaling(e,Oo,!0,r);return o}))}getRTCUserList(e){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcQueryListInput,{order:2}),{code:o,buffer:i}=yield this.context.rtcSignaling(e,Ao,!0,r);if(o!==t.ErrorCode.SUCCESS||!i)return{code:o};return{code:o,data:Go(this.codec,i)}}))}joinLivingRoomAsAudience(e,o,i){var n,a;return r(this,void 0,void 0,(function*(){const r=Fo(this.codec,o,i),c=At.getMemo(),d={dur:0,cod:0,rid:"",rtp:o,csnid:"",snid:"",time:0,cr:"unknown",net:"unknown",uid:""};c.qualityJoinRoomReportData=d,c.joinRoomData={start:Date.now()};const{code:u,buffer:_}=yield this.context.rtcSignaling(e,Do,!0,r);if(u!==t.ErrorCode.SUCCESS||!_)return{code:u};const{rtcToken:l,entries:R}=this.codec.decode(Bo.RtcViewerJoinedOutput,_),C=Date.now(),h=JSON.stringify(Object.assign(c.qualityJoinRoomReportData,{dur:C-((null===(n=c.joinRoomData)||void 0===n?void 0:n.start)||0),cod:u,rid:e,csnid:null===(a=c.clientData)||void 0===a?void 0:a.clientSessionId,snid:pt(e,R).sessionId,time:C,uid:this.context.getCurrentId()}));return t.reportLog(t.LogLevel.STATISTICS,s.L_QS_JOIN_ROOM_S,h,t.LogSource.RTC),{code:u,data:{token:l,kvEntries:R}}}))}quitLivingRoomAsAudience(e){return r(this,void 0,void 0,(function*(){const t=this.codec.encode(Bo.SetUserStatusInput,{status:0}),{code:r}=yield this.context.rtcSignaling(e,No,!0,t);return r}))}rtcIdentityChange(e,o,i){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcInput,{roomType:zt.LIVE,broadcastType:i,identityChangeType:o,needSysChatroom:!1}),{code:s,buffer:n}=yield this.context.rtcSignaling(e,yo,!0,r);if(s!==t.ErrorCode.SUCCESS||!n)return{code:s};return{code:s,data:Go(this.codec,n)}}))}requestRoomPK(e){return r(this,void 0,void 0,(function*(){const{invitedRoomId:t,invitedUserId:r,inviteSessionId:o,inviteTimeout:i,inviteInfo:s,roomId:n}=e,a=this.codec.encode(Bo.RtcInviteInput,{invitedRoomId:t,invitedUserId:r,inviteSessionId:o,timeoutTime:i,inviteInfo:s}),{code:c}=yield this.context.rtcSignaling(n,ko,!0,a);return c}))}cancelRoomPK(e){return r(this,void 0,void 0,(function*(){const{invitedRoomId:t,invitedUserId:r,inviteSessionId:o,inviteInfo:i,roomId:s}=e,n=this.codec.encode(Bo.RtcCancelInviteInput,{invitedRoomId:t,invitedUserId:r,inviteSessionId:o,inviteInfo:i}),{code:a}=yield this.context.rtcSignaling(s,Uo,!0,n);return a}))}responseRoomPK(e){return r(this,void 0,void 0,(function*(){const{inviteUserId:t,inviteRoomId:r,inviteSessionId:o,content:i,key:s,value:n,agree:a,roomId:c}=e,d=this.codec.encode(Bo.RtcInviteAnswerInput,{inviteUserId:t,inviteRoomId:r,inviteSessionId:o,content:i,key:s,value:n,answerCode:a?1:0}),{code:u}=yield this.context.rtcSignaling(c,Po,!0,d);return u}))}endRoomPK(e){return r(this,void 0,void 0,(function*(){const{endRoomId:t,sessionId:r,content:o,keys:i,roomId:s}=e,n=this.codec.encode(Bo.RtcEndInviteInput,{inviteRoomId:t,inviteSessionId:r,inviteContent:o,inviteRoomKeys:i}),{code:a}=yield this.context.rtcSignaling(s,Mo,!0,n);return a}))}getRTCJoinedUserInfo(e){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcQueryUserJoinedInput,{userId:e}),{code:o,buffer:i}=yield this.context.rtcSignaling("",xo,!0,r);if(o!==t.ErrorCode.SUCCESS||!i)return{code:o};return{code:o,data:(this.codec.decode(Bo.RtcQueryUserJoinedOutput,i).info||[]).map((e=>({deviceId:e.deviceId,roomId:e.roomId,joinTime:mt(e.joinTime)})))}}))}pullRTCRoomEntry(e){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcPullKV,{timestamp:0,roomId:e}),{code:o,buffer:i}=yield this.context.rtcSignaling(e,bo,!0,r);if(o!==t.ErrorCode.SUCCESS)return{code:o};const s=this.codec.decode(Bo.RtcKVOutput,i);let{entries:n,syncTime:a}=s;return n=(n||[]).map((e=>Object.assign(Object.assign({},e),{timestamp:mt(e.timestamp)}))),{code:o,data:{kvEntries:n,syncTime:mt(a)}}}))}decodeRtcNotify(e){const{time:t,type:r,roomId:o}=this.codec.decode(Bo.RtcNotifyMsg,e);return{time:mt(t),type:r,roomId:o}}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(Bo.RtcReportSDKInput,{sdkInfo:JSON.stringify(e)});this.context.rtcSignaling("",wo,!0,t)}}const Ho={tag:"RCRTC",verify:e=>"browser"!==e.tag?(o.error(`RCRTC Plugin is not support the runtime '${e.tag}'`),!1):ze?(t.VersionManage.add("plugin-rtc","5.5.2"),!!t.VersionManage.validEngine("^5.5.5-beem")||(o.error(`The current engine version '${t.VersionManage.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,r,i={}){var n,a,c,d,u,_,l,R;return t.logger.init({localLogLevel:i.logLevel,customLogPrint:i.logStdout}),t.logger.warn(s.L_INDEX_INSTALL_RTC_PLUGIN_O,{"RCRTC Version":"5.5.2",Commit:"ea199b763d6914e0ce5b491b97eba1ee5db53d3e","browserInfo.browser":_t.browser,"browserInfo.supportsUnifiedPlan":_t.supportsUnifiedPlan,"browserInfo.version":_t.version}),o.setLogLevel(i.logLevel),o.setLogStdout(i.logStdout),o.warn("RCRTC Version: 5.5.2, Commit: ea199b763d6914e0ce5b491b97eba1ee5db53d3e"),o.warn(`browserInfo.browser -> ${_t.browser}`),o.warn(`browserInfo.supportsUnifiedPlan -> ${_t.supportsUnifiedPlan}`),o.warn(`browserInfo.version -> ${_t.version}`),t.assert("options.mediaServer",i.mediaServer,(e=>!(!t.isHttpUrl(e)||"https:"===location.protocol&&!/^https/.test(e)))),t.assert("options.timeout",i.timeout,(e=>t.isNumber(e)&&e>=5e3&&e<=3e4)),t.assert("options.pingGap",i.pingGap,(e=>t.isNumber(e)&&e>=3e3&&e<=1e4)),(null==i?void 0:i.audio)&&((null===(n=i.audio)||void 0===n?void 0:n.workletModule)&&(Pe.workletModule=null===(a=i.audio)||void 0===a?void 0:a.workletModule),(null===(c=i.audio)||void 0===c?void 0:c.workletWasm)&&(Pe.workletWasm=null===(d=i.audio)||void 0===d?void 0:d.workletWasm),(null===(u=i.audio)||void 0===u?void 0:u.workletModule)&&(null===(_=i.audio)||void 0===_?void 0:_.workletWasm)&&(Pe.isOpen=!0),void 0!==(null===(l=i.audio)||void 0===l?void 0:l.isOpen)&&(Pe.isOpen=null===(R=i.audio)||void 0===R?void 0:R.isOpen)),new ho(new Ko(e,e.createCodec(Vo,$o)),r,i)}},jo={transResolution:at,transFrameRate:ut,parseTrackId:rt,ifSupportLocalFileTrack:lt,ifSupportScreenShare:Rt};e.RCAbstractRoom=Fr,e.RCAudienceClient=co,e.RCAudienceLivingRoom=Ro,e.RCCameraVideoTrack=Ge,e.RCLivingRoom=io,e.RCLocalAudioTrack=xe,e.RCLocalFileAudioTrack=$e,e.RCLocalFileTrack=Be,e.RCLocalFileVideoTrack=Ve,e.RCLocalTrack=Me,e.RCLocalVideoTrack=we,e.RCMCUConfigBuilder=Wr,e.RCMediaStreamCapture=Co,e.RCMicphoneAudioTrack=Fe,e.RCRTCClient=ho,e.RCRTCRoom=so,e.RCRemoteAudioTrack=Je,e.RCRemoteTrack=je,e.RCRemoteVideoTrack=qe,e.RCScreenAudioTrack=He,e.RCScreenVideoTrack=Ke,e.RCTag={DEFAULT:"RongCloudRTC"},e.RCTrack=be,e.device=Ae,e.helper=jo,e.installer=Ho,Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
15
|
+
***************************************************************************** */function r(e,t,r,o){return new(r||(r=Promise))((function(i,s){function n(e){try{c(o.next(e))}catch(e){s(e)}}function a(e){try{c(o.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,a)}c((o=o.apply(e,t||[])).next())}))}const o=new t.Logger("RCRTC");var i,s,n;e.RCRTCCode=void 0,(i=e.RCRTCCode||(e.RCRTCCode={}))[i.SUCCESS=1e4]="SUCCESS",i[i.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",i[i.PARAMS_ERROR=50001]="PARAMS_ERROR",i[i.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",i[i.NOT_IN_ROOM=50003]="NOT_IN_ROOM",i[i.SERVICE_INVALID=50004]="SERVICE_INVALID",i[i.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",i[i.SIGNAL_ERROR=53001]="SIGNAL_ERROR",i[i.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",i[i.REQUEST_FAILED=53004]="REQUEST_FAILED",i[i.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",i[i.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",i[i.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",i[i.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",i[i.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",i[i.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",i[i.BROWSER_PERMISSION_DENIED=53012]="BROWSER_PERMISSION_DENIED",i[i.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",i[i.INVALID_TAGS=53014]="INVALID_TAGS",i[i.INVALID_USER_ID=53015]="INVALID_USER_ID",i[i.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",i[i.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",i[i.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",i[i.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",i[i.TRACK_NOT_READY=53020]="TRACK_NOT_READY",i[i.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",i[i.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",i[i.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",i[i.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",i[i.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",i[i.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",i[i.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",i[i.SIGNAL_JOIN_RTC_ROOM_REFUSED=53028]="SIGNAL_JOIN_RTC_ROOM_REFUSED",i[i.NO_PERMISSION_TO_USE_REQUESTED_DEVICE=53029]="NO_PERMISSION_TO_USE_REQUESTED_DEVICE",i[i.THE_FUNCTION_IS_DISABLED_IN_PKROOM=53030]="THE_FUNCTION_IS_DISABLED_IN_PKROOM",i[i.SOME_TRACKS_PUBLISH_FAILED=53031]="SOME_TRACKS_PUBLISH_FAILED",i[i.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO=53032]="MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO",i[i.JWT_TIME_OUT=1004]="JWT_TIME_OUT",i[i.SYSTEM_PERMISSION_DENIED=53033]="SYSTEM_PERMISSION_DENIED",i[i.PUBLISH_TRACKS_IS_INVALID=53034]="PUBLISH_TRACKS_IS_INVALID",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"}(s||(s={})),function(e){e.FAILED="fail",e.SUCCESSED="success",e.TIMEOUT="timeout",e.INFO="info"}(n||(n={}));let a=!0,c=!0;function d(e,t,r){const o=e.match(t);return o&&o.length>=r&&parseInt(o[r],10)}function u(e,t,r){if(!e.RTCPeerConnection)return;const o=e.RTCPeerConnection.prototype,i=o.addEventListener;o.addEventListener=function(e,o){if(e!==t)return i.apply(this,arguments);const s=e=>{const t=r(e);t&&(o.handleEvent?o.handleEvent(t):o(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(o,s),i.apply(this,[e,s])};const s=o.removeEventListener;o.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const o=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,s.apply(this,[e,o])},Object.defineProperty(o,"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 _(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(a=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function l(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(c=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function R(){if("object"==typeof window){if(a)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function C(e,t){c&&console.warn(e+" is deprecated, please use "+t+" instead.")}function h(e){return"[object Object]"===Object.prototype.toString.call(e)}function g(e){return h(e)?Object.keys(e).reduce((function(t,r){const o=h(e[r]),i=o?g(e[r]):e[r],s=o&&!Object.keys(i).length;return void 0===i||s?t:Object.assign(t,{[r]:i})}),{}):e}function p(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((o=>{o.endsWith("Id")?p(e,e.get(t[o]),r):o.endsWith("Ids")&&t[o].forEach((t=>{p(e,e.get(t),r)}))})))}function S(e,t,r){const o=r?"outbound-rtp":"inbound-rtp",i=new Map;if(null===t)return i;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===o&&r.trackId===t.id&&p(e,r,i)}))})),i}const m=R;function T(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const o=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 o="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==o.exact&&"number"==typeof o.exact&&(o.min=o.max=o.exact);const i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==o.ideal){t.optional=t.optional||[];let e={};"number"==typeof o.ideal?(e[i("min",r)]=o.ideal,t.optional.push(e),e={},e[i("max",r)]=o.ideal,t.optional.push(e)):(e[i("",r)]=o.ideal,t.optional.push(e))}void 0!==o.exact&&"number"!=typeof o.exact?(t.mandatory=t.mandatory||{},t.mandatory[i("",r)]=o.exact):["min","max"].forEach((e=>{void 0!==o[e]&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,r)]=o[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(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=o(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const n=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||n)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return 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=s.exact?{exact:n.deviceId}:{ideal:n.deviceId}),e.video=o(e.video),m("chrome: "+JSON.stringify(e)),i(e)}))}e.video=o(e.video)}return m("chrome: "+JSON.stringify(e)),i(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,o){i(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{o&&o(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return i(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function I(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function E(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 o;o=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const i=new Event("track");i.track=r.track,i.receiver=o,i.transceiver={receiver:o},i.streams=[t.stream],this.dispatchEvent(i)})),t.stream.getTracks().forEach((r=>{let o;o=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const i=new Event("track");i.track=r,i.receiver=o,i.transceiver={receiver:o},i.streams=[t.stream],this.dispatchEvent(i)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else u(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function f(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,o){let i=r.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};const o=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){o.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 o=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],o.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 L(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,o]=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 i=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},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const o=function(e){r(s(i(e)))};return t.apply(this,[o,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(s(i(t)))},r])})).then(r,o)}}function v(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=>S(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}),u(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>S(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,o;return this.getSenders().forEach((r=>{r.track===e&&(t?o=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?o=!0:r=t),t.track===e))),o||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 O(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 o=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(o)&&this._shimmedLocalStreams[r.id].push(o):this._shimmedLocalStreams[r.id]=[r,o],o};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 o=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(o)};const o=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],o.apply(this,arguments)};const i=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]})),i.apply(this,arguments)}}function A(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return O(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 o=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}o.apply(this,[t])};const i=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const o=e._reverseStreams[t],i=e._streams[o.id];r=r.replace(new RegExp(i.id,"g"),o.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function n(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const o=e._reverseStreams[t],i=e._streams[o.id];r=r.replace(new RegExp(o.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.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 o=[].slice.call(arguments,1);if(1!==o.length||!o[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 i=this.getSenders().find((e=>e.track===t));if(i)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[r.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const o=new e.MediaStream([t]);this._streams[r.id]=o,this._reverseStreams[o.id]=r,this.addStream(o)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],o={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=o[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:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((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 D(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],o={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=o[t]}))}function N(e,t){u(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var y=Object.freeze({__proto__:null,shimMediaStream:I,shimOnTrack:E,shimGetSendersWithDtmf:f,shimGetStats:L,shimSenderReceiverGetStats:v,shimAddTrackRemoveTrackWithNative:O,shimAddTrackRemoveTrack:A,shimPeerConnection:D,fixNegotiationNeeded:N,shimGetUserMedia:T,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 o=r.video&&r.video.width,i=r.video&&r.video.height,s=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},o&&(r.video.mandatory.maxWidth=o),i&&(r.video.mandatory.maxHeight=i),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});var b=function(e){var t={exports:{}};return e(t,t.exports),t.exports}((function(e){var t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},t.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},t.getDescription=function(e){var 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]},o=8;o<t.length;o+=2)switch(t[o]){case"raddr":r.relatedAddress=t[o+1];break;case"rport":r.relatedPort=parseInt(t[o+1],10);break;case"tcptype":r.tcpType=t[o+1];break;case"ufrag":r.ufrag=t[o+1],r.usernameFragment=t[o+1];break;default:r[t[o]]=t[o+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={},o=e.substr(e.indexOf(" ")+1).split(";"),i=0;i<o.length;i++)r[(t=o[i].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 o=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?o.push(t+"="+e.parameters[t]):o.push(t)})),t+="a=fmtp:"+r+" "+o.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)},o=e.indexOf(":",t);return o>-1?(r.attribute=e.substr(t+1,o-t-1),r.value=e.substr(o+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 o=t.matchPrefix(e+r,"a=ice-ufrag:")[0],i=t.matchPrefix(e+r,"a=ice-pwd:")[0];return o&&i?{usernameFragment:o.substr(12),password:i.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:[]},o=t.splitLines(e)[0].split(" "),i=3;i<o.length;i++){var s=o[i],n=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(n){var a=t.parseRtpMap(n),c=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(a.parameters=c.length?t.parseFmtp(c[0]):{},a.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),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 o="";o+="m="+e+" ",o+=r.codecs.length>0?"9":"0",o+=" UDP/TLS/RTP/SAVPF ",o+=r.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",o+="c=IN IP4 0.0.0.0\r\n",o+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((function(e){o+=t.writeRtpMap(e),o+=t.writeFmtp(e),o+=t.writeRtcpFb(e)}));var i=0;return r.codecs.forEach((function(e){e.maxptime>i&&(i=e.maxptime)})),i>0&&(o+="a=maxptime:"+i+"\r\n"),o+="a=rtcp-mux\r\n",r.headerExtensions&&r.headerExtensions.forEach((function(e){o+=t.writeExtmap(e)})),o},t.parseRtpEncodingParameters=function(e){var r,o=[],i=t.parseRtpParameters(e),s=-1!==i.fecMechanisms.indexOf("RED"),n=-1!==i.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]),i.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}),o.push(t),s&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:n?"red+ulpfec":"red"},o.push(t))}})),0===o.length&&c&&o.push({ssrc:c});var u=t.matchPrefix(e,"b=");return u.length&&(u=0===u[0].indexOf("b=TIAS:")?parseInt(u[0].substr(7),10):0===u[0].indexOf("b=AS:")?1e3*parseInt(u[0].substr(5),10)*.95-16e3:void 0,o.forEach((function(e){e.maxBitrate=u}))),o},t.parseRtcpParameters=function(e){var r={},o=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];o&&(r.cname=o.value,r.ssrc=o.ssrc);var i=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=i.length>0,r.compound=0===i.length;var s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.parseMsid=function(e){var r,o=t.matchPrefix(e,"a=msid:");if(1===o.length)return{stream:(r=o[0].substr(7).split(" "))[0],track:r[1]};var i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return i.length>0?{stream:(r=i[0].value.split(" "))[0],track:r[1]}:void 0},t.parseSctpDescription=function(e){var r,o=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");i.length>0&&(r=parseInt(i[0].substr(19),10)),isNaN(r)&&(r=65536);var s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substr(12),10),protocol:o.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,o){var i=void 0!==r?r:2;return"v=0\r\no="+(o||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+i+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,r,o,i){var s=t.writeRtpDescription(e.kind,r);if(s+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===o?"actpass":"active"),s+="a=mid:"+e.mid+"\r\n",e.direction?s+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var n="msid:"+i.id+" "+e.rtpSender.track.id+"\r\n";s+="a="+n,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+n,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+n,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+t.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+t.localCName+"\r\n"),s},t.getDirection=function(e,r){for(var o=t.splitLines(e),i=0;i<o.length;i++)switch(o[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return o[i].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),o=0;o<r.length;o++)if(r[o].length<2||"="!==r[o].charAt(1))return!1;return!0},e.exports=t}));function k(e,t,r,o,i){var s=b.writeRtpDescription(e.kind,t);if(s+=b.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=b.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":i||"active"),s+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var n=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=n;var a="msid:"+(o?o.id:"-")+" "+n+"\r\n";s+="a="+a,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+b.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+b.localCName+"\r\n"),s}function U(e,t){var r={codecs:[],headerExtensions:[],fecMechanisms:[]},o=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]},i=function(e,t,r,i){var s=o(e.parameters.apt,r),n=o(t.parameters.apt,i);return s&&n&&s.name.toLowerCase()===n.name.toLowerCase()};return e.codecs.forEach((function(o){for(var s=0;s<t.codecs.length;s++){var n=t.codecs[s];if(o.name.toLowerCase()===n.name.toLowerCase()&&o.clockRate===n.clockRate){if("rtx"===o.name.toLowerCase()&&o.parameters&&n.parameters.apt&&!i(o,n,e.codecs,t.codecs))continue;(n=JSON.parse(JSON.stringify(n))).numChannels=Math.min(o.numChannels,n.numChannels),r.codecs.push(n),n.rtcpFeedback=n.rtcpFeedback.filter((function(e){for(var t=0;t<o.rtcpFeedback.length;t++)if(o.rtcpFeedback[t].type===e.type&&o.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var o=0;o<t.headerExtensions.length;o++){var i=t.headerExtensions[o];if(e.uri===i.uri){r.headerExtensions.push(i);break}}})),r}function P(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 M(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 x(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 w=function(e,t){function r(t,r){r.addTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function o(t,r,o,i){var s=new Event("track");s.track=r,s.receiver=o,s.transceiver={receiver:o},s.streams=i,e.setTimeout((function(){t._dispatchEvent("track",s)}))}var i=function(r){var o=this,i=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){o[e]=i[e].bind(i)})),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 x("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 o=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var i="string"==typeof o;return i&&(o=[o]),o=o.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=i?o[0]:o,!!o.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var s=r.iceCandidatePoolSize;s>0;s--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=b.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(i.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(i.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),i.prototype.onicecandidate=null,i.prototype.onaddstream=null,i.prototype.ontrack=null,i.prototype.onremovestream=null,i.prototype.onsignalingstatechange=null,i.prototype.oniceconnectionstatechange=null,i.prototype.onconnectionstatechange=null,i.prototype.onicegatheringstatechange=null,i.prototype.onnegotiationneeded=null,i.prototype.ondatachannel=null,i.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},i.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},i.prototype.getConfiguration=function(){return this._config},i.prototype.getLocalStreams=function(){return this.localStreams},i.prototype.getRemoteStreams=function(){return this.remoteStreams},i.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,o={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)o.iceTransport=this.transceivers[0].iceTransport,o.dtlsTransport=this.transceivers[0].dtlsTransport;else{var i=this._createIceAndDtlsTransports();o.iceTransport=i.iceTransport,o.dtlsTransport=i.dtlsTransport}return t||this.transceivers.push(o),o},i.prototype.addTrack=function(t,r){if(this._isClosed)throw x("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var o;if(this.transceivers.find((function(e){return e.track===t})))throw x("InvalidAccessError","Track already exists.");for(var i=0;i<this.transceivers.length;i++)this.transceivers[i].track||this.transceivers[i].kind!==t.kind||(o=this.transceivers[i]);return o||(o=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),o.track=t,o.stream=r,o.rtpSender=new e.RTCRtpSender(t,o.dtlsTransport),o.rtpSender},i.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var o=e.clone();e.getTracks().forEach((function(e,t){var r=o.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),o.getTracks().forEach((function(e){r.addTrack(e,o)}))}},i.prototype.removeTrack=function(t){if(this._isClosed)throw x("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 x("InvalidAccessError","Sender was not created by this connection.");var o=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(o)&&this.localStreams.indexOf(o)>-1&&this.localStreams.splice(this.localStreams.indexOf(o),1),this._maybeFireNegotiationNeeded()},i.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)}))},i.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},i.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},i.prototype._createIceGatherer=function(t,r){var o=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var i=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(i,"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;i.state=r?"completed":"gathering",null!==o.transceivers[t].bufferedCandidateEvents&&o.transceivers[t].bufferedCandidateEvents.push(e)},i.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),i},i.prototype._gather=function(t,r){var o=this,i=this.transceivers[r].iceGatherer;if(!i.onlocalcandidate){var s=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,i.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),i.onlocalcandidate=function(e){if(!(o.usingBundle&&r>0)){var s=new Event("icecandidate");s.candidate={sdpMid:t,sdpMLineIndex:r};var n=e.candidate,a=!n||0===Object.keys(n).length;if(a)"new"!==i.state&&"gathering"!==i.state||(i.state="completed");else{"new"===i.state&&(i.state="gathering"),n.component=1,n.ufrag=i.getLocalParameters().usernameFragment;var c=b.writeCandidate(n);s.candidate=Object.assign(s.candidate,b.parseCandidate(c)),s.candidate.candidate=c,s.candidate.toJSON=function(){return{candidate:s.candidate.candidate,sdpMid:s.candidate.sdpMid,sdpMLineIndex:s.candidate.sdpMLineIndex,usernameFragment:s.candidate.usernameFragment}}}var d=b.getMediaSections(o._localDescription.sdp);d[s.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",o._localDescription.sdp=b.getDescription(o._localDescription.sdp)+d.join("");var u=o.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==o.iceGatheringState&&(o.iceGatheringState="gathering",o._emitGatheringStateChange()),a||o._dispatchEvent("icecandidate",s),u&&(o._dispatchEvent("icecandidate",new Event("icecandidate")),o.iceGatheringState="complete",o._emitGatheringStateChange())}},e.setTimeout((function(){s.forEach((function(e){i.onlocalcandidate(e)}))}),0)}},i.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var o=new e.RTCDtlsTransport(r);return o.ondtlsstatechange=function(){t._updateConnectionState()},o.onerror=function(){Object.defineProperty(o,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:o}},i.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 o=this.transceivers[e].dtlsTransport;o&&(delete o.ondtlsstatechange,delete o.onerror,delete this.transceivers[e].dtlsTransport)},i.prototype._transceive=function(e,r,o){var i=U(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(i.encodings=e.sendEncodingParameters,i.rtcp={cname:b.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(i.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(i)),o&&e.rtpReceiver&&i.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?i.encodings=e.recvEncodingParameters:i.encodings=[{}],i.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(i.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(i.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(i))},i.prototype.setLocalDescription=function(e){var t,r,o=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(x("TypeError",'Unsupported type "'+e.type+'"'));if(!P("setLocalDescription",e.type,o.signalingState)||o._isClosed)return Promise.reject(x("InvalidStateError","Can not set local "+e.type+" in state "+o.signalingState));if("offer"===e.type)t=b.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=b.parseRtpParameters(e);o.transceivers[t].localCapabilities=r})),o.transceivers.forEach((function(e,t){o._gather(e.mid,t)}));else if("answer"===e.type){t=b.splitSections(o._remoteDescription.sdp),r=t.shift();var i=b.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var s=o.transceivers[t],n=s.iceGatherer,a=s.iceTransport,c=s.dtlsTransport,d=s.localCapabilities,u=s.remoteCapabilities;if(!(b.isRejected(e)&&0===b.matchPrefix(e,"a=bundle-only").length)&&!s.rejected){var _=b.getIceParameters(e,r),l=b.getDtlsParameters(e,r);i&&(l.role="server"),o.usingBundle&&0!==t||(o._gather(s.mid,t),"new"===a.state&&a.start(n,_,i?"controlling":"controlled"),"new"===c.state&&c.start(l));var R=U(d,u);o._transceive(s,R.codecs.length>0,!1)}}))}return o._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?o._updateSignalingState("have-local-offer"):o._updateSignalingState("stable"),Promise.resolve()},i.prototype.setRemoteDescription=function(i){var s=this;if(-1===["offer","answer"].indexOf(i.type))return Promise.reject(x("TypeError",'Unsupported type "'+i.type+'"'));if(!P("setRemoteDescription",i.type,s.signalingState)||s._isClosed)return Promise.reject(x("InvalidStateError","Can not set remote "+i.type+" in state "+s.signalingState));var n={};s.remoteStreams.forEach((function(e){n[e.id]=e}));var a=[],c=b.splitSections(i.sdp),d=c.shift(),u=b.matchPrefix(d,"a=ice-lite").length>0,_=b.matchPrefix(d,"a=group:BUNDLE ").length>0;s.usingBundle=_;var l=b.matchPrefix(d,"a=ice-options:")[0];return s.canTrickleIceCandidates=!!l&&l.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(o,c){var l=b.splitLines(o),R=b.getKind(o),C=b.isRejected(o)&&0===b.matchPrefix(o,"a=bundle-only").length,h=l[0].substr(2).split(" ")[2],g=b.getDirection(o,d),p=b.parseMsid(o),S=b.getMid(o)||b.generateIdentifier();if(C||"application"===R&&("DTLS/SCTP"===h||"UDP/DTLS/SCTP"===h))s.transceivers[c]={mid:S,kind:R,protocol:h,rejected:!0};else{var m,T,I,E,f,L,v,O,A;!C&&s.transceivers[c]&&s.transceivers[c].rejected&&(s.transceivers[c]=s._createTransceiver(R,!0));var D,N,y=b.parseRtpParameters(o);C||(D=b.getIceParameters(o,d),(N=b.getDtlsParameters(o,d)).role="client"),v=b.parseRtpEncodingParameters(o);var k=b.parseRtcpParameters(o),P=b.matchPrefix(o,"a=end-of-candidates",d).length>0,x=b.matchPrefix(o,"a=candidate:").map((function(e){return b.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===i.type||"answer"===i.type)&&!C&&_&&c>0&&s.transceivers[c]&&(s._disposeIceAndDtlsTransports(c),s.transceivers[c].iceGatherer=s.transceivers[0].iceGatherer,s.transceivers[c].iceTransport=s.transceivers[0].iceTransport,s.transceivers[c].dtlsTransport=s.transceivers[0].dtlsTransport,s.transceivers[c].rtpSender&&s.transceivers[c].rtpSender.setTransport(s.transceivers[0].dtlsTransport),s.transceivers[c].rtpReceiver&&s.transceivers[c].rtpReceiver.setTransport(s.transceivers[0].dtlsTransport)),"offer"!==i.type||C){if("answer"===i.type&&!C){T=(m=s.transceivers[c]).iceGatherer,I=m.iceTransport,E=m.dtlsTransport,f=m.rtpReceiver,L=m.sendEncodingParameters,O=m.localCapabilities,s.transceivers[c].recvEncodingParameters=v,s.transceivers[c].remoteCapabilities=y,s.transceivers[c].rtcpParameters=k,x.length&&"new"===I.state&&(!u&&!P||_&&0!==c?x.forEach((function(e){M(m.iceTransport,e)})):I.setRemoteCandidates(x)),_&&0!==c||("new"===I.state&&I.start(T,D,"controlling"),"new"===E.state&&E.start(N)),!U(m.localCapabilities,m.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&m.sendEncodingParameters[0].rtx&&delete m.sendEncodingParameters[0].rtx,s._transceive(m,"sendrecv"===g||"recvonly"===g,"sendrecv"===g||"sendonly"===g),!f||"sendrecv"!==g&&"sendonly"!==g?delete m.rtpReceiver:(A=f.track,p?(n[p.stream]||(n[p.stream]=new e.MediaStream),r(A,n[p.stream]),a.push([A,f,n[p.stream]])):(n.default||(n.default=new e.MediaStream),r(A,n.default),a.push([A,f,n.default])))}}else{(m=s.transceivers[c]||s._createTransceiver(R)).mid=S,m.iceGatherer||(m.iceGatherer=s._createIceGatherer(c,_)),x.length&&"new"===m.iceTransport.state&&(!P||_&&0!==c?x.forEach((function(e){M(m.iceTransport,e)})):m.iceTransport.setRemoteCandidates(x)),O=e.RTCRtpReceiver.getCapabilities(R),t<15019&&(O.codecs=O.codecs.filter((function(e){return"rtx"!==e.name}))),L=m.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var w,B=!1;if("sendrecv"===g||"sendonly"===g){if(B=!m.rtpReceiver,f=m.rtpReceiver||new e.RTCRtpReceiver(m.dtlsTransport,R),B)A=f.track,p&&"-"===p.stream||(p?(n[p.stream]||(n[p.stream]=new e.MediaStream,Object.defineProperty(n[p.stream],"id",{get:function(){return p.stream}})),Object.defineProperty(A,"id",{get:function(){return p.track}}),w=n[p.stream]):(n.default||(n.default=new e.MediaStream),w=n.default)),w&&(r(A,w),m.associatedRemoteMediaStreams.push(w)),a.push([A,f,w])}else m.rtpReceiver&&m.rtpReceiver.track&&(m.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===m.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),m.associatedRemoteMediaStreams=[]);m.localCapabilities=O,m.remoteCapabilities=y,m.rtpReceiver=f,m.rtcpParameters=k,m.sendEncodingParameters=L,m.recvEncodingParameters=v,s._transceive(s.transceivers[c],!1,B)}}})),void 0===s._dtlsRole&&(s._dtlsRole="offer"===i.type?"active":"passive"),s._remoteDescription={type:i.type,sdp:i.sdp},"offer"===i.type?s._updateSignalingState("have-remote-offer"):s._updateSignalingState("stable"),Object.keys(n).forEach((function(t){var r=n[t];if(r.getTracks().length){if(-1===s.remoteStreams.indexOf(r)){s.remoteStreams.push(r);var i=new Event("addstream");i.stream=r,e.setTimeout((function(){s._dispatchEvent("addstream",i)}))}a.forEach((function(e){var t=e[0],i=e[1];r.id===e[2].id&&o(s,t,i,[r])}))}})),a.forEach((function(e){e[2]||o(s,e[0],e[1],[])})),e.setTimeout((function(){s&&s.transceivers&&s.transceivers.forEach((function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},i.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")},i.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},i.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))},i.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)}},i.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)}},i.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(x("InvalidStateError","Can not call createOffer after close"));var o=r.transceivers.filter((function(e){return"audio"===e.kind})).length,i=r.transceivers.filter((function(e){return"video"===e.kind})).length,s=arguments[0];if(s){if(s.mandatory||s.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==s.offerToReceiveAudio&&(o=!0===s.offerToReceiveAudio?1:!1===s.offerToReceiveAudio?0:s.offerToReceiveAudio),void 0!==s.offerToReceiveVideo&&(i=!0===s.offerToReceiveVideo?1:!1===s.offerToReceiveVideo?0:s.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--o<0&&(e.wantReceive=!1):"video"===e.kind&&--i<0&&(e.wantReceive=!1)}));o>0||i>0;)o>0&&(r._createTransceiver("audio"),o--),i>0&&(r._createTransceiver("video"),i--);var n=b.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(o,i){var s=o.track,n=o.kind,a=o.mid||b.generateIdentifier();o.mid=a,o.iceGatherer||(o.iceGatherer=r._createIceGatherer(i,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"),o.remoteCapabilities&&o.remoteCapabilities.codecs&&o.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(o.remoteCapabilities&&o.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=o.sendEncodingParameters||[{ssrc:1001*(2*i+1)}];s&&t>=15019&&"video"===n&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),o.wantReceive&&(o.rtpReceiver=new e.RTCRtpReceiver(o.dtlsTransport,n)),o.localCapabilities=c,o.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+=k(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="+b.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)},i.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(x("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(x("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var o=b.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.usingBundle&&(o+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),o+="a=ice-options:trickle\r\n";var i=b.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,s){if(!(s+1>i)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?o+="m=application 0 DTLS/SCTP 5000\r\n":o+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?o+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(o+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(o+="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=U(e.localCapabilities,e.remoteCapabilities);!a.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,o+=k(e,a,"answer",e.stream,r._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(o+="a=rtcp-rsize\r\n")}}));var s=new e.RTCSessionDescription({type:"answer",sdp:o});return Promise.resolve(s)},i.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(o,i){if(!r._remoteDescription)return i(x("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var s=e.sdpMLineIndex;if(e.sdpMid)for(var n=0;n<r.transceivers.length;n++)if(r.transceivers[n].mid===e.sdpMid){s=n;break}var a=r.transceivers[s];if(!a)return i(x("OperationError","Can not add ICE candidate"));if(a.rejected)return o();var c=Object.keys(e.candidate).length>0?b.parseCandidate(e.candidate):{};if("tcp"===c.protocol&&(0===c.port||9===c.port))return o();if(c.component&&1!==c.component)return o();if((0===s||s>0&&a.iceTransport!==r.transceivers[0].iceTransport)&&!M(a.iceTransport,c))return i(x("OperationError","Can not add ICE candidate"));var d=e.candidate.trim();0===d.indexOf("a=")&&(d=d.substr(2)),(t=b.getMediaSections(r._remoteDescription.sdp))[s]+="a="+(c.type?d:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=b.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var u=0;u<r.transceivers.length&&(r.transceivers[u].rejected||(r.transceivers[u].iceTransport.addRemoteCandidate({}),(t=b.getMediaSections(r._remoteDescription.sdp))[u]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=b.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));u++);o()}))},i.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 x("InvalidAccessError","Invalid selector.");return r.getStats()}var o=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&o.push(e[t].getStats())}))})),Promise.all(o).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 o=r.prototype.getStats;r.prototype.getStats=function(){return o.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var o;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(o=e[r]).type]||o.type,t.set(r,e[r])})),t}))}}}));var s=["createOffer","createAnswer"];return s.forEach((function(e){var t=i.prototype[e];i.prototype[e]=function(){var e=arguments;return"function"==typeof e[0]||"function"==typeof e[1]?t.apply(this,[arguments[2]]).then((function(t){"function"==typeof e[0]&&e[0].apply(null,[t])}),(function(t){"function"==typeof e[1]&&e[1].apply(null,[t])})):t.apply(this,arguments)}})),(s=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=i.prototype[e];i.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=i.prototype[e];i.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)}})),i};function B(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 V(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,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=w(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&&C("RTCIceServer.url","RTCIceServer.urls");const o="string"==typeof t;return o&&(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=o?t[0]:t,!!t.length}}))}(e.iceServers,t.version),R("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype}function F(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var G=Object.freeze({__proto__:null,shimPeerConnection:$,shimReplaceTrack:F,shimGetUserMedia:B,shimGetDisplayMedia:V});function K(e,t){const r=e&&e.navigator,o=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,o){C("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,o)},!(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)},o&&o.prototype.getSettings){const t=o.prototype.getSettings;o.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(o&&o.prototype.applyConstraints){const t=o.prototype.applyConstraints;o.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 H(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 j(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],o={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=o[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},o=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,s]=arguments;return o.apply(this,[e||null]).then((e=>{if(t.version<53&&!i)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,o)=>{e.set(o,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(i,s)}}function J(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 q(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}),u(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function W(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){C("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Y(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Q(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 o=t.apply(this,arguments);if(r){const{sender:t}=o,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 o})}function z(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 Z(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 X(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 ee=Object.freeze({__proto__:null,shimOnTrack:H,shimPeerConnection:j,shimSenderGetStats:J,shimReceiverGetStats:q,shimRemoveStream:W,shimRTCDataChannel:Y,shimAddTransceiver:Q,shimGetParameters:z,shimCreateOffer:Z,shimCreateAnswer:X,shimGetUserMedia:K,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 te(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 re(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 oe(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,o=t.createAnswer,i=t.setLocalDescription,s=t.setRemoteDescription,n=t.addIceCandidate;t.createOffer=function(e,t){const o=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[o]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],i=o.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i};let a=function(e,t,r){const o=i.apply(this,[e]);return r?(o.then(t,r),Promise.resolve()):o};t.setLocalDescription=a,a=function(e,t,r){const o=s.apply(this,[e]);return r?(o.then(t,r),Promise.resolve()):o},t.setRemoteDescription=a,a=function(e,t,r){const o=n.apply(this,[e]);return r?(o.then(t,r),Promise.resolve()):o},t.addIceCandidate=a}function ie(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(se(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,o){t.mediaDevices.getUserMedia(e).then(r,o)}.bind(t))}function se(e){return e&&void 0!==e.video?Object.assign({},e,{video:g(e.video)}):e}function ne(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 o=e.iceServers[r];!o.hasOwnProperty("urls")&&o.hasOwnProperty("url")?(C("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,t.push(o)):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 ae(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 ce(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 de(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ue=Object.freeze({__proto__:null,shimLocalStreamsAPI:te,shimRemoteStreamsAPI:re,shimCallbacksAPI:oe,shimGetUserMedia:ie,shimConstraints:se,shimRTCIceServerUrls:ne,shimTrackEventTransceiver:ae,shimCreateOfferLegacy:ce,shimAudioContext:de});function _e(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),o=b.parseCandidate(e.candidate),i=Object.assign(r,o);return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,u(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function le(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=b.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=b.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},o=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},i=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},s=function(e,r){let o=65536;"firefox"===t.browser&&57===t.version&&(o=65535);const i=b.matchPrefix(e.sdp,"a=max-message-size:");return i.length>0?o=parseInt(i[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(o=2147483637),o},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=o(arguments[0]),t=i(e),r=s(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 Re(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const o=arguments[0],i=o.length||o.size||o.byteLength;if("open"===e.readyState&&t.sctp&&i>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},u(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Ce(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 he(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 ge(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 pe=Object.freeze({__proto__:null,shimRTCIceCandidate:_e,shimMaxMessageSize:le,shimSendThrowTypeError:Re,shimConnectionState:Ce,removeExtmapAllowMixed:he,shimAddIceCandidateNullOrEmpty:ge});const Se=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=R,o=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=d(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=d(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=d(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=d(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),i={browserDetails:o,commonShim:pe,extractVersion:d,disableLog:_,disableWarnings:l};switch(o.browser){case"chrome":if(!y||!D||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),i;if(null===o.version)return r("Chrome shim can not determine version, not shimming."),i;r("adapter.js shimming chrome."),i.browserShim=y,ge(e,o),T(e,o),I(e),D(e,o),E(e),A(e,o),f(e),L(e),v(e),N(e,o),_e(e),Ce(e),le(e,o),Re(e),he(e,o);break;case"firefox":if(!ee||!j||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=ee,ge(e,o),K(e,o),j(e,o),H(e),W(e),J(e),q(e),Y(e),Q(e),z(e),Z(e),X(e),_e(e),Ce(e),le(e,o),Re(e);break;case"edge":if(!G||!$||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),i;r("adapter.js shimming edge."),i.browserShim=G,B(e),V(e),$(e,o),F(e),le(e,o),Re(e);break;case"safari":if(!ue||!t.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=ue,ge(e,o),ne(e),ce(e),oe(e),te(e),re(e),ae(e),ie(e),de(e),_e(e),le(e,o),Re(e),he(e,o);break;default:r("Unsupported browser!")}return i}({window:"undefined"==typeof window?void 0:window});var me,Te,Ie;e.RCFrameRate=void 0,(me=e.RCFrameRate||(e.RCFrameRate={})).FPS_10="FPS_10",me.FPS_15="FPS_15",me.FPS_24="FPS_24",me.FPS_30="FPS_30",e.RCResolution=void 0,(Te=e.RCResolution||(e.RCResolution={})).W176_H132="W176_H132",Te.W176_H144="W176_H144",Te.W180_H180="W180_H180",Te.W240_H180="W240_H180",Te.W240_H240="W240_H240",Te.W256_H144="W256_H144",Te.W320_H180="W320_H180",Te.W320_H240="W320_H240",Te.W360_H360="W360_H360",Te.W480_H360="W480_H360",Te.W480_H480="W480_H480",Te.W640_H360="W640_H360",Te.W640_H480="W640_H480",Te.W720_H480="W720_H480",Te.W848_H480="W848_H480",Te.W960_H720="W960_H720",Te.W1280_H720="W1280_H720",Te.W1920_H1080="W1920_H1080",e.RCMediaType=void 0,(Ie=e.RCMediaType||(e.RCMediaType={}))[Ie.AUDIO_ONLY=0]="AUDIO_ONLY",Ie[Ie.VIDEO_ONLY=1]="VIDEO_ONLY",Ie[Ie.AUDIO_VIDEO=2]="AUDIO_VIDEO";const Ee={[e.RCResolution.W176_H132]:{width:176,height:132,maxBitrate:150,minBitrate:80},[e.RCResolution.W176_H144]:{width:176,height:144,maxBitrate:150,minBitrate:80},[e.RCResolution.W180_H180]:{width:180,height:180,maxBitrate:200,minBitrate:100},[e.RCResolution.W240_H180]:{width:240,height:180,maxBitrate:240,minBitrate:120},[e.RCResolution.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[e.RCResolution.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[e.RCResolution.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[e.RCResolution.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[e.RCResolution.W360_H360]:{width:360,height:360,maxBitrate:520,minBitrate:140},[e.RCResolution.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[e.RCResolution.W480_H480]:{width:480,height:480,maxBitrate:800,minBitrate:180},[e.RCResolution.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[e.RCResolution.W640_H480]:{width:640,height:480,maxBitrate:900,minBitrate:200},[e.RCResolution.W720_H480]:{width:720,height:480,maxBitrate:1e3,minBitrate:200},[e.RCResolution.W848_H480]:{width:848,height:480,maxBitrate:1860,minBitrate:200},[e.RCResolution.W960_H720]:{width:960,height:720,maxBitrate:2e3,minBitrate:250},[e.RCResolution.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[e.RCResolution.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},fe=e=>{const t={192:180,368:360,1088:1080};return t[e]?t[e]:e},Le=(e,t)=>{e=fe(e),t=fe(t);const r=Ee[`W${e}_H${t}`];if(r)return r;const o=e*t;return Object.keys(Ee).map((e=>Ee[e])).sort(((e,t)=>e.height*e.width-t.width*t.height)).filter((e=>e.height*e.width>=o))[0]||Ee.W1920_H1080},ve={10:1,15:1,24:1.5,30:1.5},Oe=e=>{let t=Number.MAX_VALUE,r=1;for(const o in ve){const i=Math.abs(e-parseInt(o));i<t&&(t=i,r=ve[o])}return r},Ae={getCameras:()=>r(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))})),getMicrophones:()=>r(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))})),getSpeakers:()=>r(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audiooutput"===e.kind))}))};var De,Ne;!function(e){e.AUDIO="audio",e.VIDEO="video"}(De||(De={}));class ye extends t.EventEmitter{constructor(e,t,r,o,i){super(),this._tag=e,this._userId=t,this._kind=r,this._isLocalTrack=o,this._roomId=i,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`),t.logger.info(s.L_TRACK_MUTE_O,{status:n.SUCCESSED,id:this._id},{logSource:t.LogSource.RTC}),this._setLocalMuted(!0)}unmute(){return o.info(`set ${this._id} enabled: true`),t.logger.info(s.L_TRACK_UNMUTE_O,{status:n.SUCCESSED,id:this._id},{logSource:t.LogSource.RTC}),this._setLocalMuted(!1)}isLocalMuted(){return this._localMuted}isMCUTrack(){return Boolean(this._roomId)}isOwnerMuted(){return this._remoteMuted}play(i,a){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_TRACK_PLAY_T,{element:i,options:a,msg:`start play trackId: ${this._id}`},{logSource:t.LogSource.RTC}),!this._msTrack)return o.warn(`the track is not ready to play -> id: ${this._id}`),t.logger.error(s.L_TRACK_PLAY_R,{status:n.FAILED,code:e.RCRTCCode.TRACK_NOT_READY,msg:`play error -> id: ${this._id}`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&(o.warn(`the track's readyState is 'ended' -> id: ${this._id}`),t.logger.error(s.L_TRACK_PLAY_R,{status:n.FAILED,code:"",msg:`the track's readyState is ended -> id: ${this._id}`},{logSource:t.LogSource.RTC})),null==a?void 0:a.volume){if(!t.isNumber(null==a?void 0:a.volume))return o.error(`${null==a?void 0:a.volume} is not a number, the valid range of options.volume is 0-100`),t.logger.error(s.L_TRACK_PLAY_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> options.volume不是数字"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};(null==a?void 0:a.volume)<0&&(a.volume=0,o.warn("the valid range of options.volume is 0-100, the value of volume has been set 0"),t.logger.warn(s.L_TRACK_PLAY_R,{status:n.FAILED,code:"",msg:"params error -> options.volume < 0"},{logSource:t.LogSource.RTC})),(null==a?void 0:a.volume)>100&&(a.volume=100,o.warn("the valid range of options.volume is 0-100, the value of volume has been set 100"),t.logger.warn(s.L_TRACK_PLAY_R,{status:n.FAILED,code:"",msg:"params error -> options.volume > 100"},{logSource:t.LogSource.RTC}))}if(null==a?void 0:a.audioDeviceId){if(!(yield Ae.getSpeakers()).map((e=>e.deviceId)).includes(a.audioDeviceId))return o.error(`the options.audioDeviceId is invalid --\x3e ${a.audioDeviceId}`),t.logger.error(s.L_TRACK_PLAY_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> options.audioDeviceId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR}}const c=this.isVideoTrack();return!c||i&&(i instanceof HTMLVideoElement||this.__validateVideoNodeName(i))?(this._element=c?i: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 r,i;o.debug(`HTMLMediaElement onloadstart -> id: ${null===(r=e.target)||void 0===r?void 0:r.id}, trackId: ${this._id}`),t.logger.info(s.L_TRACK_PLAY_R,{status:n.INFO,msg:`HTMLMediaElement onloadstart -> id: ${null===(i=e.target)||void 0===i?void 0:i.id}, trackId: ${this._id}`},{logSource:t.LogSource.RTC})},this._element.ondurationchange=e=>{var r,i;o.debug(`HTMLMediaElement ondurationchange -> id: ${null===(r=e.target)||void 0===r?void 0:r.id}, trackId: ${this._id}`),t.logger.info(s.L_TRACK_PLAY_R,{status:n.INFO,msg:`HTMLMediaElement ondurationchange -> id: ${null===(i=e.target)||void 0===i?void 0:i.id}, trackId: ${this._id}`},{logSource:t.LogSource.RTC})},this._element.onloadedmetadata=e=>{var r,i;o.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(r=e.target)||void 0===r?void 0:r.id}, trackId: ${this._id}`),t.logger.info(s.L_TRACK_PLAY_R,{status:n.INFO,msg:`HTMLMediaElement onloadedmetadata -> id: ${null===(i=e.target)||void 0===i?void 0:i.id}, trackId: ${this._id}`},{logSource:t.LogSource.RTC})},this._element.onloadeddata=e=>{var r,i;o.debug(`HTMLMediaElement onloadeddata -> id: ${null===(r=e.target)||void 0===r?void 0:r.id}, trackId: ${this._id}`),t.logger.info(s.L_TRACK_PLAY_R,{status:n.INFO,msg:`HTMLMediaElement onloadeddata -> id: ${null===(i=e.target)||void 0===i?void 0:i.id}, trackId: ${this._id}`},{logSource:t.LogSource.RTC})},this._element.onabort=e=>{var r,i;o.info(`HTMLMediaElement onabort -> id: ${null===(r=e.target)||void 0===r?void 0:r.id}, trackId: ${this._id}`),t.logger.info(s.L_TRACK_PLAY_R,{status:n.INFO,msg:`HTMLMediaElement onabort -> id: ${null===(i=e.target)||void 0===i?void 0:i.id}, trackId: ${this._id}`},{logSource:t.LogSource.RTC})},this._element.oncanplay=i=>r(this,void 0,void 0,(function*(){var r,d,u;o.info(`HTMLMediaElement oncanplay -> id: ${null===(r=i.target)||void 0===r?void 0:r.id}, trackId: ${this._id}`),t.logger.info(s.L_TRACK_PLAY_R,{status:n.INFO,msg:`HTMLMediaElement oncanplay -> id: ${null===(d=i.target)||void 0===d?void 0:d.id}, trackId: ${this._id}`},{logSource:t.LogSource.RTC});try{yield null===(u=this._element)||void 0===u?void 0:u.play(),(null==a?void 0:a.audioDeviceId)&&!c&&(yield this._element.setSinkId(a.audioDeviceId))}catch(r){if("No permission to use requested device"===r.message)return o.error(`setSinkId failed -> ${r.message}`),void t.logger.error(s.L_TRACK_PLAY_R,{status:n.FAILED,code:e.RCRTCCode.NO_PERMISSION_TO_USE_REQUESTED_DEVICE,msg:"No permission"},{logSource:t.LogSource.RTC});o.error(r),t.logger.error(s.L_TRACK_PLAY_R,{status:n.FAILED,code:e.RCRTCCode.TRACK_PLAY_ERROR,msg:"play error"},{logSource:t.LogSource.RTC})}})),this._element.onvolumechange=e=>{var r,i;const a=Math.floor(100*(null===(r=e.target)||void 0===r?void 0:r.volume));o.info(`HTMLMediaElement onvolumechange -> volume: ${a}, trackId: ${this._id}`),t.logger.info(s.L_TRACK_PLAY_R,{status:n.INFO,msg:`HTMLMediaElement onvolumechange -> id: ${null===(i=e.target)||void 0===i?void 0:i.id}, trackId: ${this._id}`},{logSource:t.LogSource.RTC})},this._element.srcObject=this._msStream,this._element.autoplay=!0,c&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),c||!(null==a?void 0:a.volume)&&0!==(null==a?void 0:a.volume)||(this._element.volume=(null==a?void 0:a.volume)/100),t.logger.info(s.L_TRACK_PLAY_R,{status:n.SUCCESSED,element:i,options:a},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS}):(o.error(`the video track need an <video> to play -> id: ${this._id}`),t.logger.error(s.L_TRACK_PLAY_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> element不是一个video标签"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.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()}}e.RCAudioBitrate=void 0,(Ne=e.RCAudioBitrate||(e.RCAudioBitrate={})).Speech="Speech",Ne.Music="Music",Ne.MusicHigh="MusicHigh";const be={[e.RCAudioBitrate.Music]:{max:64,min:64},[e.RCAudioBitrate.MusicHigh]:{max:128,min:128},[e.RCAudioBitrate.Speech]:{max:32,min:32}};var ke;e.RCVideoBitrate=void 0,(ke=e.RCVideoBitrate||(e.RCVideoBitrate={})).LEVEL0="LEVEL0",ke.LEVEL1="LEVEL1",ke.LEVEL2="LEVEL2",ke.LEVEL3="LEVEL3",ke.LEVEL4="LEVEL4",ke.LEVEL5="LEVEL5";const Ue={[e.RCVideoBitrate.LEVEL0]:{max:150,min:80},[e.RCVideoBitrate.LEVEL1]:{max:280,min:120},[e.RCVideoBitrate.LEVEL2]:{max:650,min:150},[e.RCVideoBitrate.LEVEL3]:{max:1e3,min:200},[e.RCVideoBitrate.LEVEL4]:{max:2200,min:250},[e.RCVideoBitrate.LEVEL5]:{max:4e3,min:400}};class Pe{static setStatus(e=!0){Pe.isOpen=e}static setWroklet(e,t){Pe.workletModule=e,Pe.workletModule=t}static transformStreamTrack(e){var i;return r(this,void 0,void 0,(function*(){if(!Pe.isOpen)return new Promise((t=>{t({track:null==e?void 0:e.getAudioTracks()[0],stop:()=>{}})}));let r=new AudioContext({sampleRate:44100}),a=r.createMediaStreamSource(e),c=r.createMediaStreamDestination(),d=null,u=null;if(d=yield r.audioWorklet.addModule(Pe.workletModule).then((()=>(o.info(s.L_RTC_3ANOISE_NODE_O,{status:n.SUCCESSED,message:{msg:"addModule RC3AnoiseTrack.workletModule success"}},{logSource:t.LogSource.RTC}),fetch(Pe.workletWasm,{cache:"force-cache",credentials:"same-origin"}).then((e=>e.arrayBuffer())).catch((e=>{throw new Error(e.message)}))))).then((e=>(u=new AudioWorkletNode(r,"process-worklet",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{binary:e}}),u))).catch((e=>{o.info(s.L_RTC_3ANOISE_NODE_E,{status:n.FAILED,message:{msg:e.message}},{logSource:t.LogSource.RTC})})),!d)return new Promise((t=>{t({track:null==e?void 0:e.getAudioTracks()[0],stop:()=>{}})}));a.connect(d).connect(c);let _=null===(i=null==c?void 0:c.stream)||void 0===i?void 0:i.getAudioTracks()[0],l=()=>{o.info(s.L_RTC_3ANOISE_NODE_STOP_O,{status:n.SUCCESSED,message:{msg:"call stop RC3AnoiseTrack.workletModule"}},{logSource:t.LogSource.RTC}),null==d||d.port.postMessage({type:"stop",msg:""}),setTimeout((()=>{const t=null==e?void 0:e.getAudioTracks()[0];null==t||t.stop(),r.suspend(),r.close(),c.disconnect(),d.disconnect(),a.disconnect(),r=null,d=null,c=null,a=null,u=null,e=null,null==_||_.stop(),_=null,l=null}),200)};return{track:_,stop:l}}))}}Pe.workletModule="https://cdn.ronghub.com/plugin-rtc/wasm/5.0.0-alpha.2/process-worklet.js",Pe.workletWasm="https://cdn.ronghub.com/plugin-rtc/wasm/5.0.0-alpha.2/AudioProcessing.wasm",Pe.isOpen=!1;class Me extends ye{constructor(e,t,r,o){super(e,t,r,!0),this._isDestroyed=!1,this._isPublished=!1,this.__innerSetMediaStreamTrack(o),o.onended=()=>{o.onended=null,this.emit(Me.EVENT_LOCAL_TRACK_END,this),this.removeAll(Me.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(e){return new Promise(((r,o)=>{const i=this._localMuted!==e;super._setLocalMuted(e),this._remoteMuted=this._localMuted,i&&this.emit(Me.__INNER_EVENT_MUTED_CHANGE__,this,r),t.logger.info(s.L_LOCAL_TRACK_SET_LOCAL_MUTED_O,{status:n.SUCCESSED,bool:e},{logSource:t.LogSource.RTC})}))}__innerSetPublished(e){t.logger.info(s.L_LOCAL_TRACK_INNER_SET_PUBLISHED_O,{status:n.SUCCESSED,bool:e},{logSource:t.LogSource.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(Me.__INNER_EVENT_DESTROY__,this),t.logger.info(s.L_LOCAL_TRACK_DESTROY_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC})}isDestroyed(){return this._isDestroyed}setBitrate(e=0,r=0,i=0){if(!t.isNumber(e)||!t.isNumber(r)||!t.isNumber(i)||e<=0||r<=0||e<r)return o.error("setBitrate params error ->"),void t.logger.error(s.L_LOCAL_TRACK_SET_BITRATE_O,{status:n.FAILED,code:"",msg:`params error -> max: ${e},min: ${r}, start: ${i}`},{logSource:t.LogSource.RTC});t.logger.info(s.L_LOCAL_TRACK_SET_BITRATE_O,{status:n.SUCCESSED,max:e,min:r,start:i},{logSource:t.LogSource.RTC}),this._bitrateInfo={max:e,min:r,start:i}}getBitrate(){var e,t,r,o,i,s,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)===De.VIDEO?({min:a,max:c}=et(this._msTrack)):(null===(t=this._msTrack)||void 0===t?void 0:t.kind)===De.AUDIO&&({min:a,max:c}={min:32,max:32}),(null===(r=this._bitrateInfo)||void 0===r?void 0:r.max)&&(d=.7*(null===(o=this._bitrateInfo)||void 0===o?void 0:o.max)),{min:(null===(i=this._bitrateInfo)||void 0===i?void 0:i.min)||a,max:(null===(s=this._bitrateInfo)||void 0===s?void 0:s.max)||c,start:(null===(n=this._bitrateInfo)||void 0===n?void 0:n.start)||d}}}Me.EVENT_LOCAL_TRACK_END="local-track-end",Me.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",Me.__INNER_EVENT_DESTROY__="inner-destroy";class xe extends Me{constructor(e,t,r){super(e,t,"audio",r),this._stopProcess=()=>{}}setRecommendBitrate(r){if(!t.validate("livingType",r,(t=>t in e.RCAudioBitrate)))return void t.logger.warn(s.L_RTC_SET_RECOMMEND_BITRATE_O,{status:n.FAILED,msg:"params error -> setRecommendBitrate Audio"},{logSource:t.LogSource.RTC});const o=be[r];this.setBitrate(o.max,o.min,o.start||.7*o.max)}setBitrate(e,...t){const[r=1,o=.7*e||1]=t;super.setBitrate(e,r,o)}__innerSetMediaStreamTrack(e){if(e)if(Pe.isOpen){const t=new MediaStream([e]);Pe.transformStreamTrack(t).then((({track:e,stop:t})=>{super.__innerSetMediaStreamTrack(e),this._stopProcess=t}))}else super.__innerSetMediaStreamTrack(e);else super.__innerSetMediaStreamTrack(e),this._stopProcess()}}class we extends Me{constructor(e,t,r,o=!1){super(e,t,"video",r),this._isTiny=o}__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(r){if(!t.validate("livingType",r,(t=>t in e.RCVideoBitrate)))return void t.logger.warn(s.L_RTC_SET_RECOMMEND_BITRATE_O,{status:n.FAILED,msg:"params error -> setRecommendBitrate Video"},{logSource:t.LogSource.RTC});const o=Ue[r];this.setBitrate(o.max,o.min,o.start||.7*o.max)}setBitrate(e,...t){const[r=1,o=.7*e||1]=t;super.setBitrate(e,r,o)}}class Be extends Me{constructor(e,t,r,o,i){super(e,t,r,o),this._resource=i,Be.__innerSetMapping(this.getTrackId(),i)}static __innerSetMapping(e,t){const r=this._mapping.get(t)||[];r.push(e),this._mapping.set(t,r)}static __innerRemoveMapping(e,t){var r,o;const i=null===(r=this._mapping.get(t))||void 0===r?void 0:r.filter((t=>t!==e));i&&i.length>0?this._mapping.set(t,i):(this._mapping.delete(t),t.pause(),t.src="",null===(o=t.parentNode)||void 0===o||o.removeChild(t))}destroy(){this.isAudioTrack()&&this.mute(),Be.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}Be._mapping=new Map;class Ve extends Be{constructor(e,t,r,o){super(e,t,"video",r,o)}}class $e extends Be{constructor(e,t,r,o){super(e,t,"audio",r,o),this._stopProcess=()=>{}}_setLocalMuted(e){const t=Object.create(null,{_setLocalMuted:{get:()=>super._setLocalMuted}});return r(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:e.RCRTCCode.SUCCESS})}__innerSetMediaStreamTrack(e){if(e)if(Pe.isOpen){const t=new MediaStream([e]);Pe.transformStreamTrack(t).then((({track:e,stop:t})=>{super.__innerSetMediaStreamTrack(e),this._stopProcess=t}))}else super.__innerSetMediaStreamTrack(e);else super.__innerSetMediaStreamTrack(e),this._stopProcess()}}class Fe extends xe{}class Ge extends we{}class Ke extends we{}class He extends xe{}class je extends ye{constructor(e,t,r,o){super(e,t,r,!1,o),this._isSubscribed=!1}__innerSetRemoteMuted(e){this._remoteMuted=e}__innerSetSubscribed(e){this._isSubscribed=e,t.logger.debug(s.L_REMOTE_TRACK_INNER_SET_SUBSCRIBED_O,{status:n.SUCCESSED,bool:e},{logSource:t.LogSource.RTC})}isSubscribed(){return this._isSubscribed}}class Je extends je{constructor(e,t,r){super(e,t,"audio",r)}}class qe extends je{constructor(e,t,r){super(e,t,"video",r),this._isSubTiny=!1}__innerSetIsTinyTrack(e){this._isSubTiny=e}isSubTiny(){return this._isSubTiny}}const We=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),Ye=e=>JSON.stringify(e),Qe=e=>/^[a-zA-Z\d-=]+$/g.test(e),ze="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),Ze=e=>{if(void 0===e)return 0;if(t.isNumber(e))return e;const r=e;return r.exact||r.ideal||r.max||0},Xe=e=>{const t=e.getSettings(),r=e.getConstraints();return{width:Ze(r.width)||t.width||0,height:Ze(r.height)||t.height||0,frameRate:t.frameRate||Ze(r.frameRate)}},et=e=>{const{width:t,height:r,frameRate:o}=Xe(e),i=Le(t||1920,r||1080),s=Oe(o);return{min:i.minBitrate*s,max:i.maxBitrate*s}},tt=e=>[e.msid,e.mediaType].join("_"),rt=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},ot=(e,t)=>[e,t].join("_"),it=e=>e.map((e=>Object.assign({},e))),st=(e,t,r=!1)=>{e=e.slice();const o=[],i=[],s=[];return t.forEach((t=>{const i=tt(t);let n=e.findIndex((e=>tt(e)===i));if(r&&(n=e.findIndex((e=>e.uri===t.uri))),-1===n)return void o.push(t);const a=e[n];a.uri!==t.uri?o.push(t):a.state!==t.state&&s.push(t),e.splice(n,1)})),i.push(...e),{publishedList:o,unpublishedList:i,modifiedList:s}},nt=()=>{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 o=+e;const i=[];do{const e=o%r;o=(o-e)/r,i.unshift(t[e])}while(o);return i.join("")})(e),e.length>22&&(e=e.slice(0,22)),e},at=e=>{if(Ee[e]){const{width:t,height:r}=Ee[e];return{width:t,height:r}}const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},ct=t=>!!e.RCResolution[t],dt=t=>!!e.RCFrameRate[t],ut=e=>parseInt(e.replace("FPS_","")),_t=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=Se.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function lt(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function Rt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const Ct=e=>"[object Null]"===Object.prototype.toString.call(e),ht=e=>1===e.type,gt=(e,t)=>{const r={},i=Object.keys(e.users);return i.length&&i.forEach((i=>{const s=[],n=e.users[i];if(n.extra){const{roomId:e}=JSON.parse(n.extra);if(t!==e)return}if(n.uris)try{s.push(...JSON.parse(n.uris))}catch(e){o.warn(`invalid user data -> userId: ${i}, userData: ${n}`)}r[i]=s})),r},pt=(t,r)=>{const o=r.filter((e=>"RC_RTC_SESSIONID"===e.key))[0],i=o?o.value:"",s=r.filter((e=>"RC_ANCHOR_LIST"===e.key)).map((e=>JSON.parse(e.value||"[]")))[0],n=r.filter((e=>e.key.includes("RC_RES_"))).map((e=>JSON.parse(e.value||"{}"))),a=n.length?JSON.parse(n[0].mcu_uris||"[]"):[],c=[];a.forEach((r=>{const{mediaType:o,tag:i}=r,s=o===e.RCMediaType.AUDIO_ONLY?new Je(i,"",t):new qe(i,"",t);c.push(s)}));const d=[],u=[];n.forEach((t=>{const r=JSON.parse(t.uris||"[]");d.push(...r),r.forEach((t=>{const{mediaType:r,tag:o,msid:i}=t,s=i.split("_")[0],n=r===e.RCMediaType.AUDIO_ONLY?new Je(o,s):new qe(o,s);u.push(n)}))}));const _=r.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:d,remoteMUCUris:a,remoteRTCTracks:u,remoteMCUTracks:c,remoteTracks:[...u,...c],CDNUris:_||{}}},St=e=>e instanceof ye?e.getTrackId():e.track.getTrackId(),mt=e=>{if(!t.isObject(e)||void 0===e.low||void 0===e.high)return e;let{low:r}=e;r<0&&(r+=4294967296),r=r.toString(16);return parseInt(e.high.toString(16)+"00000000".replace(new RegExp(`0{${r.length}}$`),r),16)};var Tt,It;!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"}(Tt||(Tt={})),e.RCRTCPingResult=void 0,(It=e.RCRTCPingResult||(e.RCRTCPingResult={})).SUCCESS="Success",It.FAIL="Fail";class Et{constructor(e,t,r,o=5e3,i=6e4){this._roomId=e,this._roomMode=t,this._context=r,this._gap=o,this._offlineKickTime=i,this._latestTimestamp=Date.now(),this._started=!1,this._timer=null}start(){this._started||(o.info("rtcping start ->"),t.logger.info(s.L_PINGER_START_O,{status:n.SUCCESSED,interval:this._gap},{logSource:t.LogSource.RTC}),this._started=!0,this._checkAlive())}_sendPing(){return new Promise((e=>{this._context.rtcPing(this._roomId,this._roomMode).then(e).catch((r=>{o.error(`rtcping receive unknown error -> ${r}`),e(t.ErrorCode.UNKNOWN)})),setTimeout(e,5e3,t.ErrorCode.TIMEOUT)}))}_checkAlive(){var i,n,a;return r(this,void 0,void 0,(function*(){o.info("rtcping ->"),t.logger.info(s.L_PINGER_SEND_RTCPING_T,{roomId:this._roomId,msg:"send rtcping"});const r=yield this._sendPing(),c=Date.now();return r===t.ErrorCode.SUCCESS?(o.info("rtcping success ->"),t.logger.info(s.L_PINGER_SEND_RTCPING_R,{roomId:this._roomId,msg:"send rtcping success"}),this._latestTimestamp=c,null===(i=this.onPingResult)||void 0===i||i.call(this,e.RCRTCPingResult.SUCCESS),void(this._timer=setTimeout((()=>this._checkAlive()),this._gap))):(t.logger.info(s.L_PINGER_SEND_RTCPING_R,{roomId:this._roomId,msg:"send rtcping failed",code:r}),o.warn(`rtcping failed -> code: ${r}`),null===(n=this.onPingResult)||void 0===n||n.call(this,e.RCRTCPingResult.FAIL),40003===r||c-this._latestTimestamp>this._offlineKickTime?(this.stop(),void(null===(a=this.onFailed)||void 0===a||a.call(this,40003===r))):void(this._timer=setTimeout((()=>this._checkAlive()),500)))}))}stop(){this._started&&(o.info("rtcping stop ->"),t.logger.info(s.L_PINGER_STOP_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),this._started=!1,this._timer&&(clearTimeout(this._timer),this._timer=null))}}const ft=-1,Lt=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),vt=(e,i,s)=>r(void 0,void 0,void 0,(function*(){const n=[];return yield Promise.any(e.map((e=>r(void 0,void 0,void 0,(function*(){const r=`${e.detectorAddr.replace(/^(https?:\/\/)?/,"https://")}/rtc/detector/ping?t=${a=1e3,c=9999,a+Math.floor(Math.random()*(c-a))}`;var a,c;const d={jwt:s},u=yield i.httpReq({url:r,body:JSON.stringify(d),timeout:5e3,method:t.HttpMethod.POST});if(o.info(`ping res => ${JSON.stringify({status:u.status,host:e})}`),200!==u.status)return Promise.reject();n.push(e.clusterId)}))))),n})),Ot=(e,i)=>r(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:""})(i),s=(n=i)&&n.jwt||"";var n;let a=null,c=120,d=0;const u={jwt:s};if(r&&s){const o=yield e.httpReq({url:`${r}/rtc/detector/servers`,body:JSON.stringify(u),headers:{"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${_t.browser}|${_t.version}`,ClientVersion:"5.5.3","Client-Session-Id":Lt(),"Request-Id":Date.now().toString()},method:t.HttpMethod.POST}),i=o.data&&JSON.parse(o.data).detectorAddrs;c=o.data&&JSON.parse(o.data).clientDetectMinute,d=o.data&&JSON.parse(o.data).resultCode,i&&t.isArray(i)&&(a=yield vt(i,e,s))}return{fastMediaUrl:a,clientDetectMinute:c,status:d}}));class At{constructor(){}static getMemo(){return this._memo||(this._memo=new At),this._memo}static destroy(){this._memo={}}}const Dt=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${_t.browser}|${_t.version}`,ClientVersion:"5.5.3","Client-Session-Id":Lt(),"Request-Id":Date.now().toString()});class Nt{constructor(e,r,o,i=5e3){this._runtime=e,this._context=r,this._msUrl=o,this._timeout=i,this._msInNavi=[],this._failedMs=[],this._rtcFinger=void 0,this._clusterId="",this._configUrl="",this._msList=[],Nt.isDetector||r.getConnectionStatus()!==t.ConnectionStatus.CONNECTED||this.detectorMediaSever()}detectorMediaSever(){if(this._msUrl)return;const e=Date.now(),r=Nt.detectValidMinute+Nt.detectorTime>e;Nt.isDetector=r,t.logger.info(`set msInDetector => ${JSON.stringify(Nt.msInDetector)}`);const o=this._context.getNaviInfo();!r&&o&&t.notEmptyObject(o)&&(this._msList=[],this._getDetectorUrls(o))}_getDetectorUrls(t){return r(this,void 0,void 0,(function*(){if(Nt.isDetector)return;Nt.isDetector=!0;const{fastMediaUrl:r,clientDetectMinute:i,status:s}=yield Ot(this._runtime,t);if(s===e.RCRTCCode.JWT_TIME_OUT&&Nt.naviRefetchCount<5){this._context.getPluginContext().refetchNaviInfo().then((()=>{this.detectorMediaSever()})),++Nt.naviRefetchCount,o.info(`RCMediaService refetch navi count => ${Nt.naviRefetchCount}`)}Nt.msInDetector=r||[],Nt.detectorTime=Date.now(),Nt.detectValidMinute=60*i*1e3,o.info(`RCMediaService detectorTime => ${Nt.detectorTime}`),o.info(`RCMediaService detectValidMinute => ${Nt.detectValidMinute}`)}))}getNaviMS(){return this._msUrl?[this._msUrl]:(t.notEmptyArray(this._msList)&&!this._clusterId||(this._msList=this.setMediaServiceList()),this._msList)}setMediaServiceList(){let e=[],r=[];return this._clusterId&&(this._clusterId=this._clusterId.replace(/^(https?:\/\/)?/,"https://"),this._msList.push(this._clusterId)),o.info(`MediaServiceList _clusterId -> ${this._clusterId}`),t.notEmptyArray(Nt.msInDetector)&&(Nt.msInDetector=Nt.msInDetector.map((e=>e.replace(/^(https?:\/\/)?/,"https://"))),this._msList.push(Nt.msInDetector[0]),e=Nt.msInDetector.concat().splice(1,Nt.msInDetector.length-1)),o.info(`MediaServiceList msInDetector ->${JSON.stringify(Nt.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],n=[];return s.mediaServer&&n.push(s.mediaServer.replace(/^(https?:\/\/)?/,"https://")),s.backupMediaServer&&s.backupMediaServer.forEach((e=>{n.push(e.replace(/^(https?:\/\/)?/,"https://"))})),n})(this._context.getNaviInfo())):(this._msInNavi.push(...this._failedMs),this._failedMs.length=0)),o.info(`MediaServiceList _msInNavi-> ${JSON.stringify(this._msInNavi)}`),r=this._msInNavi.concat().splice(1,this._msInNavi.length-1),this._msList.push(this._msInNavi[0]),this._msList=[...this._msList,...e,...r],this._msList=[...new Set(this._msList)],o.info(`MediaServiceList msList -> ${JSON.stringify(this._msList)}`),this._msList}_request(i,a,c){return r(this,void 0,void 0,(function*(){const r=At.getMemo();r.mediaService=[];const d=this.getNaviMS();if(0===d.length)return o.warn(`request '${i}' failed -> have no valid service address.`),t.logger.error(s.L_MEDIA_SERVICE_REQUEST_R,{status:n.FAILED,code:e.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"invalid navi_url"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(c.rtcFinger=this._rtcFinger);for(let u=0;u<d.length;u+=1){const _=Date.now(),l=`${d[u]}${i}`,R=Dt(),C=Object.assign(Object.assign({},R),a),h=JSON.stringify(c),g=R["Request-Id"];t.logger.info(s.L_MEDIA_SERVICE_REQUEST_T,{path:i,headers:a,body:c,reqId:g},{logSource:t.LogSource.RTC}),o.info(`request -> Request-Id: ${g}, url: ${l}, headers: ${JSON.stringify(C)}, body: ${h}, timeout: ${this._timeout}`);const{status:p,data:S}=yield this._runtime.httpReq({url:l,body:h,headers:C,method:t.HttpMethod.POST,timeout:this._timeout});if(r.mediaService.push({start:_,end:Date.now(),reqId:g,status:p,url:l}),200===p){const r=JSON.parse(S);return r.rtcFinger&&(this._rtcFinger=r.rtcFinger),r.clusterId&&(this._clusterId=r.clusterId),o.info(`request success -> Request-Id: ${g}`),t.logger.info(s.L_MEDIA_SERVICE_REQUEST_R,{status:n.SUCCESSED,url:l,reqId:g},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,data:r}}o.warn(`request failed -> Request-Id: ${g}, status: ${p}, url: ${l}`),this._failedMs.push(...this._msInNavi.splice(u,1)),t.logger.error(s.L_MEDIA_SERVICE_REQUEST_R,{status:n.FAILED,code:"",reqId:g,url:l,msg:`request error -> Request-Id: ${g}, status: ${p}, url: ${l}`},{logSource:t.LogSource.RTC})}return{code:e.RCRTCCode.REQUEST_FAILED}}))}exchange(t,o){var i;return r(this,void 0,void 0,(function*(){const r=yield this._request("/exchange",t,o);if(r.code===e.RCRTCCode.SUCCESS&&(null===(i=r.data)||void 0===i?void 0:i.resultCode)===e.RCRTCCode.SUCCESS){const{urls:e}=r.data;e&&(this._configUrl=e.configUrl)}return r}))}exit(e){return r(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 r(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/broadcast/exit",e,{});return{code:t}}))}setMcuConfig(i,a){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_MEDIA_SERVICE_SET_MCU_CONFIG_T,{headers:i,body:a},{logSource:t.LogSource.RTC}),!this._configUrl)return o.warn("RCMediaService.setMcuConfig failed -> RCRTCCode.MCU_SERVER_NOT_FOUND"),t.logger.error(s.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:n.FAILED,code:e.RCRTCCode.MCU_SERVER_NOT_FOUND,msg:"MCU not found"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.MCU_SERVER_NOT_FOUND};const r=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,c=Dt(),d=Object.assign(Object.assign({},c),i),u=JSON.stringify(a),_=c["Request-Id"];o.info(`request -> Request-Id: ${_}, url: ${r}, headers: ${JSON.stringify(d)}, body: ${u}`);const{status:l,data:R}=yield this._runtime.httpReq({url:r,headers:d,body:u,method:t.HttpMethod.POST});if(200===l){o.info(`request success -> Request-Id: ${_}`);const e=JSON.parse(R);return t.logger.info(s.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:n.SUCCESSED,reqId:_},{logSource:t.LogSource.RTC}),{code:e.resultCode,res:e}}return o.warn(`request failed -> Request-Id: ${_}, status: ${l}, url: ${r}`),t.logger.error(s.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:n.FAILED,code:e.RCRTCCode.REQUEST_FAILED,msg:`request error -> Request-Id: ${_}, status: ${l}, url: ${r}`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REQUEST_FAILED}}))}getCDNResourceInfo(i,a){return r(this,void 0,void 0,(function*(){t.logger.info(s.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_T,{headers:i,url:a},{logSource:t.LogSource.RTC});const r=Dt(),c=Object.assign(Object.assign({},r),i),d=r["Request-Id"];o.info(`request -> Request-Id: ${d}, url: ${a}, headers: ${JSON.stringify(c)}`);const{status:u,data:_}=yield this._runtime.httpReq({url:a,headers:c,method:t.HttpMethod.GET});if(200===u){o.info(`request success -> Request-Id: ${r["Request-Id"]}`);const e=JSON.parse(_);return t.logger.info(s.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:n.SUCCESSED,reqId:r["Request-Id"]},{logSource:t.LogSource.RTC}),{code:e.resultCode,res:e}}return o.warn(`request failed -> Request-Id: ${r["Request-Id"]}, status: ${u}, url: ${a}`),t.logger.info(s.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:n.FAILED,code:e.RCRTCCode.REQUEST_FAILED,msg:`request error -> Request-Id: ${r["Request-Id"]}, status: ${u}, url: ${a}`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REQUEST_FAILED}}))}}var yt;Nt.isDetector=!1,Nt.msInDetector=[],Nt.detectorTime=0,Nt.detectValidMinute=72e5,Nt.naviRefetchCount=0,function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(yt||(yt={}));const bt=(e,t)=>Math.round(8*t/e),kt=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},Ut=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.round(e*r)},Pt=(e,t,r,o)=>{if(0===t)return 0;if(!r||!o)return kt(e/t,3);const i=t-o;if(0===i)return 0;const s=e-r;return s<0||i<0?0:kt(s/i,3)},Mt=e=>{const{jitter:t,rtt:r,packetsLostRate:o}=e;return!Ct(t)||!Ct(r)||0!==o};class xt{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 o,i;if(this._latestBytesSent[e]&&t<this._latestBytesSent[e].bytesSent&&this.clearLatestpacketsSent([e]),this._latestBytesSent[e]){const{bytesSent:s,timestamp:n}=this._latestBytesSent[e];o=t-s,i=r-n,this._latestBytesSent[e]={bytesSent:t,timestamp:r}}else o=t,i=1e3,this._latestBytesSent[e]={bytesSent:t,timestamp:r};return bt(i,o)}updateBytesRecv(e,t,r){let o,i;if(this._latestBytesRecv[e]&&t<this._latestBytesRecv[e].bytesRecv&&this.clearLatestPacketsRecv([e]),this._latestBytesRecv[e]){const{bytesRecv:s,timestamp:n}=this._latestBytesRecv[e];o=t-s,i=r-n,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r}}else o=t,i=1e3,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r};return bt(i,o)}updateSenderPacketsLost(e,t,r){let o;if(Object.prototype.hasOwnProperty.call(this._latestPacketsSent[e],"packetsSent")){const{packetsLost:i,packetsSent:s}=this._latestPacketsSent[e];o=Pt(t,r,i,s),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=i===t?s:r}else o=Pt(t,r),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=r;return o}updateReceiverPacketsLost(e,t,r){let o;if(this._latestPacketsRecv[e]){const{packetsLost:i,packetsRecv:s}=this._latestPacketsRecv[e];o=Pt(t,r+t,i,s+i)}else o=Pt(t,r);return this._latestPacketsRecv[e]={packetsLost:t,packetsRecv:r},o}clearLatestpacketsSent(t){t.forEach((t=>{if(parseInt(t.split("_").pop())===e.RCMediaType.VIDEO_ONLY){const e=`${t}_tiny`;delete this._latestPacketsSent[e],delete this._latestBytesSent[e]}delete this._latestPacketsSent[t],delete this._latestBytesSent[t]}))}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 r={senders:[],receivers:[]};return t.logger.info(s.L_ABSTRACT_STAT_PARSER_FORMAT_RTC_STATE_REPORT_O,{status:n.SUCCESSED,stats:e,reports:r},{logSource:t.LogSource.RTC}),r}getAudioLevelList(e){return[]}getResourceIdByParseSdp(e){var t,r;const{ssrc:o}=e,i=e.kind||e.mediaType,s=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:${o} msid:(.*?) `);const c=null==s?void 0:s.split("\r\nm="),d=null==c?void 0:c.filter((e=>e.includes(`a=ssrc:${o}`)))[0],u=null==d?void 0:d.match(a);let _=u?u[1]:"";if(_){if("audio"===i)return`${_}_0`;const e=_.replace(`${this._currentUserId}_`,"").split("_");return e.length>1&&"tiny"===e[1]?`${this._currentUserId}_${e[0]}_1_tiny`:`${_}_1`}const l=null==n?void 0:n.split("\r\nm="),R=null==l?void 0:l.filter((e=>e.includes(`a=ssrc:${o}`)))[0],C=null==R?void 0:R.match(a);return _=C?C[1]:"",_?`${_}_${"video"===i?1:0}`:""}isValidSender(e){var t;const r=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,{ssrc:o}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(o)&&e.includes("a=inactive"))))}isValidReceiver(e){var t;const r=null===(t=this._rtcPeerConn.currentRemoteDescription)||void 0===t?void 0:t.sdp,{ssrc:o}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(o)&&e.includes("a=inactive"))))}}class wt extends xt{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const o=Object.keys(e);let i=0,s=0;o.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const n=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const{id:a,kind:c,transportId:d,mediaSourceId:u,remoteId:_,packetsSent:l,bytesSent:R,trackId:C,encoderImplementation:h,pliCount:g,nackCount:p,firCount:S}=n;if(!C)return;let{framesPerSecond:m,frameWidth:T,frameHeight:I}=n;"video"!==c||T||I||m||(T=e[C].frameWidth,I=e[C].frameHeight,m=u?e[u].framesPerSecond:null);const E=e[_];let f=null,L=null,v=0;E&&(f=E.jitter,L=E.roundTripTime,v=E.packetsLost),i+=v;const O=this.getResourceIdByParseSdp(n);if(!O)return;const A=u?e[u].audioLevel:e[C].audioLevel;let D=null;!this._latestPacketsSent[O]&&(this._latestPacketsSent[O]={}),E?D=this.updateSenderPacketsLost(O,v,l):this._latestPacketsSent[O].crtPacketsSent=l;let N=this.updateBytesSent(O,R,r);N<0&&(N=0),s+=N,t.senders.push({id:a,trackId:O,kind:c,packetsLostRate:D,remoteResource:!1,audioLevel:A||0===A?Ut(A):null,frameWidth:T,frameHeight:I,frameRate:m,bitrate:N,jitter:f?Math.round(1e3*f):f,rtt:L,encoderImplementation:h,pliCount:g,nackCount:p,googFirsSent:ft,samplingRate:ft,googRenderDelayMs:ft,trackState:ft})}));o.filter((e=>/RTCRemoteInboundRtp(Video|Audio)Stream_/.test(e))).forEach((r=>{const{localId:o,jitter:i,roundTripTime:s,packetsLost:n}=e[r],a=t.senders.filter((e=>e.id===o))[0];if(a&&!Mt(a)){const t=this.getResourceIdByParseSdp(e[a.id]);a.jitter=Math.round(1e3*i),a.rtt=s;const r=this._latestPacketsSent[t].crtPacketsSent;a.packetsLostRate=this.updateSenderPacketsLost(t,n,r)}}));let n=0;o.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const s=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:u,bytesReceived:_,framesPerSecond:l,kind:R,codecImplementationName:C,nackCount:h,pliCount:g}=s;if(!a)return;let{frameWidth:p,frameHeight:S,audioLevel:m}=s;"video"===R?p||S||(p=e[a].frameWidth,S=e[a].frameHeight):m||(m=e[a].audioLevel),i+=c;const T=this.getResourceIdByParseSdp(s),I=this.updateReceiverPacketsLost(T,c,d);let E=this.updateBytesRecv(T,_,r);E<0&&(E=0),n+=E,t.receivers.push({trackId:T,kind:R,packetsLostRate:I,remoteResource:!0,audioLevel:m||0===m?Ut(m):null,frameWidth:p,frameHeight:S,frameRate:l,bitrate:E,jitter:u?Math.round(1e3*u):0,codecImplementationName:C,nackCount:h,pliCount:g,rtt:null,samplingRate:ft,googFirsReceived:ft,googRenderDelayMs:ft,trackState:ft})}));const a=o.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:o}=r;if(o){const r=e[o],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:u,remoteCandidateId:_}=r,l=e[u],{ip:R,port:C,networkType:h}=l,g=e[_],{ip:p,port:S,protocol:m}=g;t.iceCandidatePair={IP:R,port:C,networkType:h,remoteIP:p,remotePort:S,protocol:m,bitrateRecv:n,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:i},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 o;const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const{mediaSourceId:s,trackId:n}=i,a=this.getResourceIdByParseSdp(i),c=s&&e[s]?e[s].audioLevel:(null===(o=e[n])||void 0===o?void 0:o.audioLevel)||null;t.push({trackId:a,audioLevel:c||0===c?Ut(c):null})}));return r.filter((e=>/^RTCInboundRTPAudioStream_/.test(e))).forEach((r=>{const o=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:i}=o,s=o.audioLevel||e[i].audioLevel,n=this.getResourceIdByParseSdp(o);t.push({trackId:n,audioLevel:s||0===s?Ut(s):null})})),t}}class Bt extends xt{formatRCRTCStateReport(e){const t=+new Date,r={senders:[],receivers:[],timestamp:t};let o=0,i=0,s=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:s,kind:n,bytesSent:c,packetsSent:d,bitrateMean:u,framerateMean:_,nackCount:l,pliCount:R,remoteId:C}=a,{jitter:h,roundTripTime:g,packetsLost:p}=C?e[C]:{jitter:null,roundTripTime:null,packetsLost:0},S=this.getResourceIdByParseSdp(a);o+=p;let m=null;!this._latestPacketsSent[S]&&(this._latestPacketsSent[S]={}),C?m=this.updateSenderPacketsLost(S,p,d):this._latestPacketsSent[S].crtPacketsSent=d;let T=0;"video"===n?u&&(T=Math.floor(u/1e3)):T=this.updateBytesSent(S,c,t),T<0&&(T=0),i+=T,r.senders.push({trackId:S,kind:n,packetsLostRate:m,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(_),bitrate:T,jitter:h?Math.round(1e3*h):null,rtt:g,encoderImplementation:null,pliCount:R,nackCount:l,googFirsSent:ft,samplingRate:ft,googRenderDelayMs:ft,trackState:ft})}if("remote-inbound-rtp"===c){const{localId:t}=a,o=this.getResourceIdByParseSdp(e[t]),i=r.senders.filter((e=>e.trackId===o))[0];i&&Mt(i)&&(i.jitter=Math.round(1e3*a.jitter),i.rtt=a.rtt,i.packetsLostRate=this.updateSenderPacketsLost(o,a.packetsLost,this._latestPacketsSent[o].crtPacketsSent))}if("inbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(a))continue;const{id:e,packetsLost:i,bytesReceived:n,packetsReceived:c,jitter:d,framerateMean:u,kind:_,bitrateMean:l,nackCount:R,pliCount:C}=a,h=this.getResourceIdByParseSdp(a);o+=i;const g=this.updateReceiverPacketsLost(h,i,c);let p=0;"video"===_?l&&(p=Math.floor(l/1e3)):p=this.updateBytesRecv(h,n,t),p<0&&(p=0),s+=p,r.receivers.push({trackId:h,kind:_,packetsLostRate:g,remoteResource:!0,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:p,jitter:d?Math.round(1e3*d):null,codecImplementationName:null,nackCount:R,pliCount:C,rtt:null,samplingRate:ft,googFirsReceived:ft,googRenderDelayMs:ft,trackState:ft})}if("candidate-pair"===c&&"succeeded"===a.state){const t=e[a.localCandidateId],{address:n,port:c}=t,d=e[a.remoteCandidateId],{address:u,port:_,protocol:l}=d;r.iceCandidatePair={IP:n,port:c,networkType:null,remoteIP:u,remotePort:_,protocol:l,bitrateRecv:s,bitrateSend:i,rtt:null,availableOutgoingBitrate:null,availableIncomingBitrate:null,totalPacketsLost:o}}}return r.iceCandidatePair&&(r.iceCandidatePair.bitrateSend=i),r.iceCandidatePair&&(r.iceCandidatePair.bitrateRecv=s),r}getAudioLevelList(e){const t=[];for(const r in e){const o=e[r],{type:i}=o;if("outbound-rtp"===i){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))continue;const{kind:e}=o;if("video"===e)continue;const r=this.getResourceIdByParseSdp(o);t.push({trackId:r,audioLevel:null})}if("inbound-rtp"===i){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))continue;const{kind:e}=o;if("video"===e)continue;const r=this.getResourceIdByParseSdp(o);t.push({trackId:r,audioLevel:null})}}return t}}class Vt extends xt{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const o=Object.keys(e);let i=0,s=0;o.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const i=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const n=this.getResourceIdByParseSdp(i),{mediaType:a,transportId:c,remoteId:d,packetsSent:u,bytesSent:_,trackId:l,encoderImplementation:R,pliCount:C,nackCount:h,firCount:g}=i;if(!l)return;const{audioLevel:p,frameHeight:S,frameWidth:m}=e[l];let T=this.updateBytesSent(n,_,r);T<0&&(T=0),s+=T,t.senders.push({trackId:n,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:p||0===p?Ut(p):null,frameWidth:m,frameHeight:S,frameRate:null,bitrate:T,jitter:null,rtt:null,encoderImplementation:R,pliCount:C,nackCount:h,googFirsSent:ft,samplingRate:ft,googRenderDelayMs:ft,trackState:ft})}));let n=0;o.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const s=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:u,bytesReceived:_,mediaType:l,nackCount:R,pliCount:C}=s,h=this.getResourceIdByParseSdp(s);if(!a)return;const{frameHeight:g,frameWidth:p,audioLevel:S}=e[a];i+=c;const m=this.updateReceiverPacketsLost(h,c,d);let T=this.updateBytesRecv(h,_,r);T<0&&(T=0),n+=T,t.receivers.push({trackId:h,kind:l,packetsLostRate:m,remoteResource:!0,audioLevel:S||0===S?Ut(S):null,frameWidth:p,frameHeight:g,frameRate:null,bitrate:T,jitter:u,codecImplementationName:null,nackCount:R,pliCount:C,rtt:null,samplingRate:ft,googFirsReceived:ft,googRenderDelayMs:ft,trackState:ft})}));const a=o.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:o}=r;if(o){const r=e[o],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:u,remoteCandidateId:_}=r,l=e[u],{address:R,port:C}=l,h=e[_],{address:g,port:p,protocol:S}=h;t.iceCandidatePair={IP:R||null,port:C,networkType:null,remoteIP:g,remotePort:p,protocol:S,bitrateRecv:n,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:i},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 o=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))return;const{trackId:i,mediaType:s}=o;if("video"===s)return;const n=this.getResourceIdByParseSdp(o),a=e[i];t.push({trackId:n,audioLevel:a||0===a?Ut(a):null})}));return r.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const o=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:i,mediaType:s}=o;if(!i||"video"===s)return;const{audioLevel:n}=e[i],a=this.getResourceIdByParseSdp(o);t.push({trackId:a,audioLevel:n||0===n?Ut(n):null})})),t}}class $t{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*$t.KBitrate}\r\nb=TIAS:${e*$t.KBitrate*850}`)}setAudiosBitrate(e){return o.info(s.L_RTC_SDP_BITRATE_O,{bitrate:e,msg:"SDP setAudiosBitrate"},{logSource:t.LogSource.RTC}),this.audioStreams=this.audioStreams.map((t=>this.setAudioItemBitrate(t,e))),this}setAudioBitrateWithStreamId(e,r){return o.info(s.L_RTC_SDP_BITRATE_O,{bitrate:e,streamId:r,msg:"SDP setAudioBitrateWithStreamId"},{logSource:t.LogSource.RTC}),this.audioStreams=this.audioStreams.map((t=>new RegExp(`\\bmsid:${r}\\b`,"ig").test(t)?this.setAudioItemBitrate(t,e):t)),this}setAudioBitrateWithMid(e,r){return o.info(s.L_RTC_SDP_BITRATE_O,{bitrate:e,mid:r,msg:"SDP setAudioBitrateWithMid"},{logSource:t.LogSource.RTC}),this.audioStreams=this.audioStreams.map((t=>new RegExp(`\\bmid:${r}\\b`,"ig").test(t)?this.setAudioItemBitrate(t,e):t)),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*$t.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*$t.KBitrate}\r\nb=TIAS:${t.max*$t.KBitrate*850}`)}setVideosBitrate(e){return o.info(s.L_RTC_SDP_BITRATE_O,{bitrate:e,msg:"SDP setVideosBitrate"},{logSource:t.LogSource.RTC}),this.videoStreams=this.videoStreams.map((t=>this.setVideoItemBitrate(t,e))),this}setVideoBitrateWithStreamId(e,r){return o.info(s.L_RTC_SDP_BITRATE_O,{bitrate:e,streamId:r,msg:"SDP setVideoBitrateWithStreamId"},{logSource:t.LogSource.RTC}),this.videoStreams=this.videoStreams.map((t=>new RegExp(`\\bmsid:${r}\\b`,"ig").test(t)?this.setVideoItemBitrate(t,e):t)),this}setVideoBitrateWithMid(e,r){return o.info(s.L_RTC_SDP_BITRATE_O,{bitrate:e,mid:r,msg:"SDP setVideoBitrateWithMid"},{logSource:t.LogSource.RTC}),this.videoStreams=this.videoStreams.map((t=>new RegExp(`\\bmid:${r}\\b`,"ig").test(t)?this.setVideoItemBitrate(t,e):t)),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*$t.KBitrate,"x-google-min-bitrate="+t.min*$t.KBitrate,`x-google-start-bitrate=${t.start||t.max*$t.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*$t.KBitrate}\r\nb=TIAS:${t.max*$t.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===Gt.SENDONLY){if(/\ba=sendonly\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}if(t===Gt.RECVONLY){if(/\ba=recvonly\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}if(t===Gt.INACTIVE){if(/\ba=inactive\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}return e}}var Ft,Gt,Kt,Ht,jt,Jt,qt,Wt,Yt,Qt,zt,Zt,Xt,er,tr,rr,or;$t.KBitrate=1,function(e){e.PLANB="plan-b",e.UNIFIEDPLAN="unified-plan"}(Ft||(Ft={})),function(e){e.SENDONLY="sendonly",e.RECVONLY="recvonly",e.INACTIVE="inactive"}(Gt||(Gt={}));class ir{constructor(e){this._peer=e,this._outboundStreams={}}static setSdpSemantics(e){t.logger.info(s.L_A_SDP_STRATEGY_SET_SDP_SEMANTICS_O,{status:n.SUCCESSED,sdpSemantics:e},{logSource:t.LogSource.RTC});const{browser:r,version:o,supportsUnifiedPlan:i}=_t;t.logger.debug(`sdpSemantics, browser: ${r}, version: ${o}, supportsUnifiedPlan: ${i}`),i?/chrome/i.test(r)?this._sdpSemantics=o>92?"unified-plan":o<72?"plan-b":e:/firefox/i.test(r)?this._sdpSemantics="unified-plan":/safari/i.test(r)?this._sdpSemantics=o<12?"plan-b":"unified-plan":this._sdpSemantics="unified-plan":this._sdpSemantics="plan-b"}static getSdpSemantics(){return ir._sdpSemantics}getOutboundVideoInfo(){const e=[];for(const t in this._outboundStreams){const r=this._outboundStreams[t].getVideoTracks()[0];if(!r)continue;const o=/_tiny$/.test(t),{width:i,height:s}=Xe(r);e.push({trackId:r.id,simulcast:o?yt.TINY:yt.NORMAL,resolution:`${i}x${s}`})}return e}setRemoteAnswer(i){return r(this,void 0,void 0,(function*(){i=$t.trimBlankLine(i),o.info(`set remote answer -> ${i}`);try{yield this._peer.setRemoteDescription({type:"answer",sdp:i})}catch(r){return o.error(r),t.logger.info(s.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:n.FAILED,code:"",msg:r},{logSource:t.LogSource.RTC}),e.RCRTCCode.SET_REMOTE_DESCRIPTION_FAILED}return t.logger.info(s.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:n.SUCCESSED,sdp:i},{logSource:t.LogSource.RTC}),e.RCRTCCode.SUCCESS}))}getStatParsr(e,t,r){return/chrome/i.test(_t.browser)?new wt(e,t,r):/Firefox/i.test(_t.browser)?new Bt(e,t,r):/Safari/i.test(_t.browser)?new Vt(e,t,r):null}resetSdp(e){return $t.trimBlankLine(e)}}class sr extends $t{constructor(e){super(e,Ft.PLANB),this.SDP=e}stringify(){const e=[this.SDPHeader];[...this.audioStreams,...this.videoStreams].forEach((t=>{const r=t.match(/\ba=mid:(video|audio)\b/),o=$t.clearInactiveOrRecvonly(t);r&&r[1]===De.AUDIO&&(e[1]=o),r&&r[1]===De.VIDEO&&(e[2]=o)}));const t=e.join("");return $t.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 ir{constructor(){super(...arguments),this.senders={},this._localTracks=[]}addLocalTrack(e){this._localTracks.includes(e)||this._localTracks.push(e);const t=e.getStreamId(),r=e.__innerGetMediaStreamTrack(),o=this._outboundStreams[t]||(this._outboundStreams[t]=new MediaStream);o.getTracks().forEach((e=>{e.kind===r.kind&&o.removeTrack(e)})),o.addTrack(r);const i=e.getTrackId(),s=this.senders[i];s?s.replaceTrack(r):this.senders[i]=this._peer.addTrack(r,o)}removeLocalTrack(e){const t=this._localTracks.findIndex((t=>t===e));t>=0&&this._localTracks.splice(t,1);const r=e.getTrackId(),o=this.senders[r];o&&(o.replaceTrack(null),this._peer.removeTrack(o),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 r(this,void 0,void 0,(function*(){const r=yield this._peer.createOffer({iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0});for(const e in this._outboundStreams){const t=this._outboundStreams[e].id;r.sdp=r.sdp.replace(new RegExp(t,"g"),e)}r.sdp&&(r.sdp=$t.clearInactiveOrRecvonly(r.sdp));const o=At.getMemo();return t.logger.info(s.L_QS_SET_LOCAL_DESCRIPTION_O,{identify:o.qualityStatusId},{logSource:t.LogSource.RTC}),yield this._peer.setLocalDescription(r),{type:"offer",semantics:"plan-b",sdp:r.sdp}}))}setRemoteAnswer(e){return e=this.resetSdp(e),super.setRemoteAnswer(e)}resetSdp(e){const t=new sr(e),r={max:0,min:0},o={max:0,min:0};return this._localTracks.forEach((e=>{const{min:t,max:i,start:s}=e.getBitrate();e.isAudioTrack()&&(o.max=o.max<i?i:o.max,o.min=o.min>t?t:o.min,o.max===i?o.start=s:o.start=.7*o.max),e.isVideoTrack()&&(r.max=r.max<i?i:r.max,r.min=r.min>t?t:r.min,r.max===i?r.start=s:r.start=.7*r.max)})),t.setAudiosBitrate(o),t.setVideosBitrate(r),t.stringify()}}class ar extends $t{constructor(e){super(e,Ft.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 $t.trimBlankLine(t)}}class cr{static splitSections(e){return e.split("\nm=").map(((e,t)=>`${(t>0?`m=${e}`:e).trim()}\r\n`))}static getMediaSections(e){const t=cr.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=cr.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 cr.splitLines(e).filter((e=>0===e.indexOf(t)))}static parseMsid(e){let t;const r=cr.matchPrefix(e,"a=msid:");if(1===r.length)return t=r[0].substr(7).split(" "),{stream:t[0],track:t[1]};const o=cr.matchPrefix(e,"a=ssrc:").map((e=>cr.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return o.length>0&&o[0].value?(t=o[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)},o=e.indexOf(":",t);return o>-1?(r.attribute=e.substr(t+1,o-t-1),r.value=e.substr(o+1)):r.attribute=e.substr(t+1),r}static getMid(e){const t=cr.matchPrefix(e,"a=mid:")[0];if(t)return t.substr(6)}}class dr extends ir{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(),o=e.__innerGetMediaStreamTrack();this._localTracks[t]=e;const i=this._outboundStreams[r]||(this._outboundStreams[r]=new MediaStream);i.getTracks().forEach((e=>{e.kind===o.kind&&i.removeTrack(e)})),i.addTrack(o);const s=this._sendTransceiver[t];s?(s.sender.replaceTrack(o),s.direction="sendonly"):this._sendTransceiver[t]=this._peer.addTransceiver(o,{direction:"sendonly",streams:[i]})}removeLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId();e.__innerGetMediaStreamTrack(),delete this._localTracks[t];const o=this._sendTransceiver[t];if(!o)return;o.direction="inactive",this._peer.removeTrack(o.sender),o.sender.replaceTrack(null);const i=this._outboundStreams[r];(e.isAudioTrack()?i.getAudioTracks():i.getVideoTracks()).forEach((e=>i.removeTrack(e)));const s=this._sendTransceiver[`${t}_tiny`];if(!s||"inactive"===s.direction)return;s.direction="inactive";const{sender:n}=s,a=n.track;this._peer.removeTrack(n),n.replaceTrack(null);this._outboundStreams[`${r}_tiny`].removeTrack(a),a.stop()}updateRecvTransceiverMap(t,r){const{mediaType:o}=rt(t);this._recvTransceiver[t]=r;const i=o===e.RCMediaType.AUDIO_ONLY?this._recvAudio:this._recvVideo,s=i.findIndex((e=>e===r));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 o=t[e],i=r.findIndex((e=>e===o));i>=0&&(t.splice(e,1),r.splice(i,1))}r.length&&r.forEach((e=>{const t=e.getTrackId();e.__innerSetMediaStreamTrack(void 0);const r=this._recvTransceiver[t];r&&(r.direction="inactive")}));const o={audio:0,video:0};t.length&&t.forEach((e=>{const t=e.isAudioTrack()?"audio":"video",r=this._recvTransceiver[e.getTrackId()];r?r.direction="recvonly":o[t]+=1}));for(let e=this._recvAudio.length;e<o.audio;e+=1)this._recvAudio.push(this._peer.addTransceiver("audio",{direction:"recvonly"}));for(let e=this._recvVideo.length;e<o.video;e+=1)this._recvVideo.push(this._peer.addTransceiver("video",{direction:"recvonly"}))}createOffer(e){return r(this,void 0,void 0,(function*(){const r=yield this._peer.createOffer({iceRestart:e});let o=r.sdp;for(const e in this._outboundStreams){const t=this._outboundStreams[e].id;o=o.replace(new RegExp(t,"g"),e)}o=this.resetOfferSdp(o),o=o.replace(/(a=ice-options:trickle)/g,"$1\r\na=ice-options:renomination"),r.sdp=o;const i=At.getMemo();return t.logger.info(s.L_QS_SET_LOCAL_DESCRIPTION_O,{identify:i.qualityStatusId},{logSource:t.LogSource.RTC}),yield this._peer.setLocalDescription(r),{type:"offer",semantics:"unified-plan",sdp:o}}))}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 ar(e);for(const o in this._sendTransceiver){const i=this._sendTransceiver[o],s=null===(t=i.sender.track)||void 0===t?void 0:t.kind;let{direction:n,mid:a}=i;if(!a){cr.getMediaSections(e).forEach((e=>{cr.parseExtmap(e);const{kind:t}=cr.parseMLine(e);let{stream:r}=cr.parseMsid(e);const i=cr.getMid(e);"video"===s?/tiny$/.test(r)?r=r.replace(/tiny$/gi,"1_tiny"):r+="_1":r+="_0",r===o&&s===t&&i&&(a=i)}))}if(a){if(n===Gt.SENDONLY){const e=this._localTracks[o],t=null==e?void 0:e.getBitrate();s===De.AUDIO&&t&&r.setAudioBitrateWithMid(t,a),s===De.VIDEO&&t&&r.setVideoBitrateWithMid(t,a)}n===Gt.INACTIVE&&r.clearnSsrcWithMid(a,Gt.INACTIVE)}}for(const e in this._recvTransceiver){const t=this._recvTransceiver[e],{direction:o,mid:i}=t;i&&o===Gt.INACTIVE&&r.clearnSsrcWithMid(i,Gt.RECVONLY)}return r.stringify()}resetAnswerSdp(e){var t;const r=new ar(e);for(const e in this._sendTransceiver){const o=this._sendTransceiver[e],{mid:i}=o;if(i){const s=this._localTracks[e],n=null==s?void 0:s.getBitrate(),a=null===(t=o.sender.track)||void 0===t?void 0:t.kind;a===De.AUDIO&&n&&r.setAudioBitrateWithMid(n,i),a===De.VIDEO&&n&&r.setVideoBitrateWithMid(n,i)}}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"}(Kt||(Kt={}));class ur extends t.EventEmitter{constructor(e,t,r,o){super(),this._pcName=e,this._reTryExchange=t,this._currentUserId=r,this._polarisReport=o,this.pubLocalTracks={},this._reTryExchangeTimer=null,this._reportStatsTimer=null,this._reportR3R4ToPolarisTimer=null,this._isDestroyed=!1,this._reportStatsData=null,this._originReportStatsData=null,this._reportListener=null;const i=ir.getSdpSemantics(),s=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:i});this._sdpStrategy="plan-b"===i?new nr(s):new dr(s),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,i,this._currentUserId)}getName(){return this._pcName}getLocalTracks(){return t.logger.info(s.L_RTC_PEER_CONNECTION_GET_LOCAL_TRACKS_O,{status:n.SUCCESSED,trackIds:Object.keys(this.pubLocalTracks)},{logSource:t.LogSource.RTC}),Object.values(this.pubLocalTracks)}_onConnectionStateChange(){o.info(`onconnectionstatechange -> ${this._rtcPeerConn.connectionState}, ${this._pcName}`),t.logger.info(s.L_RTC_PEER_CONNECTION_CONNECTION_STATE_S,{status:n.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:t.LogSource.RTC})}startAutoExecute(e=1e3){this._reportStatsTimer=setTimeout((()=>{this._reportHandle(e),this._reportStatsTimer=this.startAutoExecute()}),e)}stopAutoExecute(){clearTimeout(this._reportStatsTimer)}_onICEConnectionStateChange(){var e,r,i,a,c,d,u,_,l,R,C,h,g,p,S,m,T,I,E,f,L,v,O,A,D,N;const y=Date.now(),b=At.getMemo();b.iceStatusData||(b.iceStatusData={}),b.iceNewStatusData&&(b.iceOldStatusData=b.iceNewStatusData),b.iceNewStatusData={start:y,status:this._rtcPeerConn.iceConnectionState};const k={dur:0,pices:0,ices:0,rid:null===(e=b.joinRoomData)||void 0===e?void 0:e.roomId,csnid:null===(r=b.clientData)||void 0===r?void 0:r.clientSessionId,snid:"",time:0,rcdts:[],lcdts:[],cncdts:null,cr:"unknown",net:"unknown",uid:this._currentUserId};if(b.qualitySubscribeReportData=k,o.info(`oniceconnectionstatechange -> ${this._rtcPeerConn.iceConnectionState}, ${this._pcName}`),t.logger.info(s.L_QS_SET_LOCAL_DESCRIPTION_O,{identify:b.qualityStatusId},{logSource:t.LogSource.RTC}),"connected"===this._rtcPeerConn.iceConnectionState){if(!(null===(i=b.iceStatusData)||void 0===i?void 0:i.subscribeNotReport)&&(null===(a=b.iceStatusData)||void 0===a?void 0:a.subscribe)){b.iceStatusData.subscribeNotReport=!0;const e=b.iceStatusData.notFirst?0:(null===(c=b.iceNewStatusData)||void 0===c?void 0:c.start)-(null===(u=null===(d=b.iceStatusData)||void 0===d?void 0:d.subscribe)||void 0===u?void 0:u.time)||0,r=JSON.stringify(Object.assign(b.qualitySubscribeReportData,{dur:e,pices:Kt[null===(_=b.iceOldStatusData)||void 0===_?void 0:_.status],ices:Kt[null===(l=b.iceNewStatusData)||void 0===l?void 0:l.status],time:y}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUB_ICE_STATUS_S,r,t.LogSource.RTC)}if(!(null===(R=b.iceStatusData)||void 0===R?void 0:R.publishNotReport)&&(null===(C=b.iceStatusData)||void 0===C?void 0:C.publish)){b.iceStatusData.publishNotReport=!0;const e=b.iceStatusData.notFirst?0:(null===(h=b.iceNewStatusData)||void 0===h?void 0:h.start)-(null===(p=null===(g=b.iceStatusData)||void 0===g?void 0:g.publish)||void 0===p?void 0:p.time)||0,r=JSON.stringify(Object.assign(b.qualitySubscribeReportData,{dur:e,pices:Kt[null===(S=b.iceOldStatusData)||void 0===S?void 0:S.status],ices:Kt[null===(m=b.iceNewStatusData)||void 0===m?void 0:m.status],time:y}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_PUB_ICE_STATUS_S,r,t.LogSource.RTC)}b.iceStatusData.notFirst=!0;const e=JSON.stringify(Object.assign(b.qualitySubscribeReportData,{dur:(null===(T=b.iceNewStatusData)||void 0===T?void 0:T.start)-(null===(I=b.iceOldStatusData)||void 0===I?void 0:I.start),pices:Kt[null===(E=b.iceOldStatusData)||void 0===E?void 0:E.status],ices:Kt[null===(f=b.iceNewStatusData)||void 0===f?void 0:f.status],time:y,cncdts:[]}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,e,t.LogSource.RTC),this._reportStatsTimer&&this.stopAutoExecute(),this.startAutoExecute()}if("failed"===this._rtcPeerConn.iceConnectionState||"disconnected"===this._rtcPeerConn.iceConnectionState){const e=JSON.stringify(Object.assign(b.qualitySubscribeReportData,{dur:(null===(L=b.iceNewStatusData)||void 0===L?void 0:L.start)-(null===(v=b.iceOldStatusData)||void 0===v?void 0:v.start),pices:Kt[null===(O=b.iceOldStatusData)||void 0===O?void 0:O.status],ices:Kt[null===(A=b.iceNewStatusData)||void 0===A?void 0:A.status],time:y}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,e,t.LogSource.RTC),o.warn(`${this._pcName} iceconenction state is failed, exchange SDP to try again.`),t.logger.error(s.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:n.FAILED,code:"",msg:`${this._pcName} iceconenction state is ${this._rtcPeerConn.iceConnectionState}, exchange SDP to try again.`},{logSource:t.LogSource.RTC}),this._reTryExchange(),this._reTryExchangeTimer=setInterval(this._reTryExchange,15e3)}try{null===(N=null===(D=this._reportListener)||void 0===D?void 0:D.onICEConnectionStateChange)||void 0===N||N.call(D,this._rtcPeerConn.iceConnectionState,this._pcName)}catch(e){o.error("onICEConnectionStateChange error",e,this._pcName),t.logger.error(s.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:n.FAILED,code:"",msg:`${this._pcName}, ${e}`},{logSource:t.LogSource.RTC})}t.logger.info(s.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:n.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:t.LogSource.RTC})}_onTrackReady(r){if(!r.streams.length)return;const o=r.streams[0].id,{track:i}=r.receiver,n=[o,"audio"===i.kind?e.RCMediaType.AUDIO_ONLY:e.RCMediaType.VIDEO_ONLY].join("_");this._updateRecvTransceiverMap(n,r.transceiver);const a=At.getMemo();t.logger.info(s.L_QS_TRACK_READY_O,{identify:a.qualityStatusId},{logSource:t.LogSource.RTC}),this.emit(ur.__INNER_EVENT_TRACK_READY__,r)}setBitrate(e,o,i){return r(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(e,o,i),t.logger.info(s.L_RTC_PEER_CONNECTION_SET_BITRATE_O,{status:n.SUCCESSED,max:e,min:o,start:i},{logSource:t.LogSource.RTC})}))}createOffer(e){return r(this,void 0,void 0,(function*(){const r=yield this._sdpStrategy.createOffer(e);return o.debug(`offer -> ${JSON.stringify(r.sdp)}`),t.logger.info(s.L_RTC_PEER_CONNECTION_CREATE_OFFER_O,{status:n.SUCCESSED,offerSDP:r.sdp},{logSource:t.LogSource.RTC}),r}))}setRemoteAnswer(e){return r(this,void 0,void 0,(function*(){return o.debug(`answer -> ${JSON.stringify(e)}`),t.logger.info(s.L_RTC_PEER_CONNECTION_SET_REMOTE_ANSWER_O,{status:n.SUCCESSED,answer:e},{logSource:t.LogSource.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(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Me.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.on(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.on(Me.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),t.logger.info(s.L_RTC_PEER_CONNECTION_ADD_LOCAL_TRACK_O,{status:n.SUCCESSED,trackId:e.getTrackId()},{logSource:t.LogSource.RTC})}removeLocalTrackById(e){const r=this.getLocalTrack(e);r?(t.logger.info(s.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:n.SUCCESSED,trackId:e},{logSource:t.LogSource.RTC}),this.removeLocalTrack(r)):t.logger.warn(s.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:n.FAILED,code:"",msg:"track not found"},{logSource:t.LogSource.RTC})}removeAllLocalTrack(){Object.keys(this.pubLocalTracks).forEach((e=>{/_tiny$/.test(e)||this.removeLocalTrackById(e)})),t.logger.info(s.L_RTC_PEER_CONNECTION_REMOVE_ALL_LOCAL_TRACK_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC})}removeLocalTrack(e){const r=e.getTrackId();delete this.pubLocalTracks[r],this._sdpStrategy.removeLocalTrack(e),e.__innerSetPublished(!1),e.off(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Me.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this);const o=`${r}_tiny`,i=this.getLocalTrack(o);i&&(this._sdpStrategy.removeLocalTrack(i),delete this.pubLocalTracks[o],i.destroy()),t.logger.info(s.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_O,{status:n.SUCCESSED,trackId:r},{logSource:t.LogSource.RTC})}_updateRecvTransceiverMap(e,t){this._sdpStrategy.updateRecvTransceiverMap(e,t)}updateSubRemoteTracks(e){this._sdpStrategy.updateSubRemoteTracks(e),t.logger.info(s.L_RTC_PEER_CONNECTION_UPDATE_SUB_REMOTE_TRACKS_O,{status:n.SUCCESSED,trackIds:e.map((e=>e.getTrackId()))},{logSource:t.LogSource.RTC})}getOutboundVideoInfo(){return this._sdpStrategy.getOutboundVideoInfo()}_onLocalTrackMuted(e,r){const o=this.getLocalTrack(`${e.getTrackId()}_tiny`);o&&(o.__innerGetMediaStreamTrack().enabled=!e.isLocalMuted()),this.emit(Me.__INNER_EVENT_MUTED_CHANGE__,e,r),t.logger.info(s.L_RTC_PEER_CONNECTION_LOCAL_TRACK_MUTED_O,{status:n.SUCCESSED,trackId:e.getTrackId()},{logSource:t.LogSource.RTC})}_onLocalTrackDestroied(e){this.emit(Me.__INNER_EVENT_DESTROY__,e)}registerReportListener(e){this._reportListener=e}_createRCRTCStateReport(e){const{timestamp:t,iceCandidatePair:r,senders:o,receivers:i}=JSON.parse(JSON.stringify(e));null==r||delete r.totalPacketsLost;for(const e in r)Ct(r[e])&&delete r[e];return{timestamp:t,iceCandidatePair:r,senders:o.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: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})),pcName:this._pcName}}_getStatsData(e=1e3){var t,o,i;return r(this,void 0,void 0,(function*(){let r=null;if((null===(t=this._originReportStatsData)||void 0===t?void 0:t.timestamp)&&this._originReportStatsData.timestamp>Date.now()-e)r=this._originReportStatsData.data;else{const e=yield this._rtcPeerConn.getStats();r=null===(o=this.reportParser)||void 0===o?void 0:o.parseRTCStatsReport(e),this._originReportStatsData={data:r,timestamp:Date.now()}}return null===(i=this.reportParser)||void 0===i?void 0:i.formatRCRTCStateReport(r)}))}getAudioLevelReportData(e=1e3){var t,o,i;return r(this,void 0,void 0,(function*(){let r=null;if((null===(t=this._originReportStatsData)||void 0===t?void 0:t.timestamp)&&this._originReportStatsData.timestamp>Date.now()-e)r=this._originReportStatsData.data;else{const e=yield this._rtcPeerConn.getStats();r=null===(o=this.reportParser)||void 0===o?void 0:o.parseRTCStatsReport(e),this._originReportStatsData={data:r,timestamp:Date.now()}}if(!r)return[];return null===(i=this.reportParser)||void 0===i?void 0:i.getAudioLevelList(r)}))}_reportHandle(e){var t,o;return r(this,void 0,void 0,(function*(){const r=yield this._getStatsData(e);if(!r)return;this._reportStatsData=r;const i=this._createRCRTCStateReport(r);null===(o=null===(t=this._reportListener)||void 0===t?void 0:t.onStateReport)||void 0===o||o.call(t,i)}))}_getCacheStatsData(){return this._reportStatsData}_sendR3R4Data(){var e;return r(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 r(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,t.logger.info(s.L_RTC_PEER_CONNECTION_DESTROY_O,{status:n.SUCCESSED},{logSource:t.LogSource.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"}(Ht||(Ht={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(jt||(jt={}));class _r{constructor(e,t,r,o,i=jt.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=o,this._userRole=i}_send(e){return r(this,void 0,void 0,(function*(){let r=!1;if(this._context.getConnectionStatus()!==t.ConnectionStatus.CONNECTED)return r;return r=(yield this._context.setRTCState(this._roomId,e))===t.ErrorCode.SUCCESS,r}))}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=nt(),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(t){let r="";const o=t.split("_");if(t.includes("_tiny")){const t=o.pop(),i=parseInt(o.pop())===e.RCMediaType.AUDIO_ONLY?"audio":"video",s=o.pop();r=[o.join("_"),s,t,i].join("_")}else{const t=parseInt(o.pop())===e.RCMediaType.AUDIO_ONLY?"audio":"video",i=o.pop();r=[o.join("_"),i,t].join("_")}return r}sendR3R4Data(e){return r(this,void 0,void 0,(function*(){const{iceCandidatePair:t,senders:r,receivers:o}=e,i=(null==t?void 0:t.bitrateSend)||ft,s=(null==t?void 0:t.bitrateRecv)||ft,n=(null==t?void 0:t.networkType)||"unknown",a=(null==t?void 0:t.rtt)||ft,c=`${(null==t?void 0:t.IP)||ft}:${null==t?void 0:t.port}`,d=(null==t||t.remoteIP,null==t||t.remotePort,(null==t?void 0:t.availableIncomingBitrate)||ft),u=(null==t?void 0:t.availableOutgoingBitrate)||ft,_=(null==t?void 0:t.totalPacketsLost)||ft,l=this._context.getCurrentId();let R=`R3\t${i}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${u}\t${_}\t${l}\r`,C=`R4\t${s}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${u}\t${_}\t${l}\r`;const h=r.map((e=>{var t;const{trackId:r,audioLevel:o,samplingRate:i,bitrate:s,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:u,jitter:_,nackCount:l,pliCount:R,rtt:C,googFirsSent:h,encoderImplementation:g}=e,p=this._getPolarisTrackId(r),S=this._getRealResourceId(r);return{trackId:p,googCodecName:g||String(ft),audioLevel:o||0===o?o:ft,bitrate:s||0===s?s:ft,packetsLostRate:n||0===n?n:ft,frameRate:a||ft,resolution:c&&d?`${c} * ${d}`:"-1",jitter:_||ft,nackCount:l||0===l?l:ft,pliCount:R||0===R?R:ft,rtt:C||ft,googFirsSent:h,samplingRate:i,googRenderDelayMs:u,encoderImplementation:g||String(ft),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(S))||void 0===t?void 0:t.isLocalMuted())?Ht.DISABLE:Ht.ENABLE}})),g=o.filter((e=>!!e.trackId)).map((e=>{var t;const{trackId:r,audioLevel:o,samplingRate:i,bitrate:s,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:u,jitter:_,nackCount:l,pliCount:R,rtt:C,googFirsReceived:h,codecImplementationName:g}=e,p=this._getPolarisTrackId(r),S=this._getRealResourceId(r);return{trackId:p,googCodecName:g||String(ft),audioLevel:o||0===o?o:ft,bitrate:s||0===s?s:ft,packetsLostRate:n||0===n?n:ft,frameRate:a||ft,resolution:c&&d?`${c} * ${d}`:"-1",jitter:_||ft,nackCount:l||0===l?l:ft,pliCount:R||0===R?R:ft,rtt:C||ft,googFirsReceived:h,samplingRate:i,googRenderDelayMs:u,codecImplementationName:g||String(ft),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(S))||void 0===t?void 0:t.isLocalMuted())?Ht.DISABLE:Ht.ENABLE}}));let p=!1;R+=h.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&&(p=yield this._send(`${R}\r${this._userRole}`));let S=!1;return C+=g.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&&(S=yield this._send(`${C}\r${this._userRole}`)),!(!p&&!S)}))}sendR1(){const e=this._context.getCoreVersion(),t=navigator.platform,r=`R1\t5.5.3\t${e}\tweb\t${t}\t-1\t${_t.browser}\t${_t.version}\t${this._getClientID()}\t${this._userRole}`;this._send(r)}sendR2(e,t,r){const o=`R2\t${e}\t${t}\t${this._getClientID()}\r${r.join("\t")}\r${this._userRole}`;this._send(o)}}class lr{constructor(e){this._room=e,this._audioLevelChangeHandler=null,this._timer=null}_audioLevelReport(e){return r(this,void 0,void 0,(function*(){if(!this._audioLevelChangeHandler)return;const t=[],r=this._room.__getPC();for(let o=0;o<r.length;o++){const i=r[o];if("new"===i.getRTCPeerConn().iceConnectionState)return;const s=yield i.getAudioLevelReportData(e);null==s||s.forEach((e=>{const{userId:r}=rt(e.trackId),o=this._room.getCrtUserId()===r?this._room.getLocalTrack(e.trackId):this._room.getRemoteTrack(e.trackId);o&&t.push({track:o,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)}}e.RCRTCLiveRole=void 0,(Jt=e.RCRTCLiveRole||(e.RCRTCLiveRole={}))[Jt.ANCHOR=1]="ANCHOR",Jt[Jt.AUDIENCE=2]="AUDIENCE";class Rr{constructor(e=!1,t,r,o,i){this._useMutilPeerC=e,this._roomId=t,this._reTryExchange=r,this._currentUserId=o,this._polarisReport=i,this._mutilPeerC={}}get useMutilPeerC(){return this._useMutilPeerC}_isPub(e){if(!e.length)return!1;const{track:t}=e[0]instanceof Me||e[0]instanceof je?{track:e[0]}:e[0];return t.isLocalTrack()}_groupTracksByTag(e){const t={};return e.forEach((e=>{const{track:r}=e instanceof Me?{track:e}:e,o=r.getTag();t[o]?t[o].push(e):t[o]=[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),o=new ur(e,(()=>this._reTryExchange(e,r)),this._currentUserId,this._polarisReport);this._mutilPeerC[e]={pc:o,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 o=this._groupTracksByTag(e);for(const e in o){const i=this._genPCName(r,e),s=o[e];t.push(this._createOnePeerCItem(i,s))}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}=rt(e),o=this._genPCName(t,r);return this._mutilPeerC[o].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"}(qt||(qt={})),function(e){e.NORMAL="normal",e.MIDDLE="middle",e.TAIL="tail"}(Wt||(Wt={})),function(e){e[e.LOW=0]="LOW",e[e.NORMAL=1]="NORMAL",e[e.HIGH=2]="HIGH"}(Yt||(Yt={})),function(e){e[e.Destroy=40400]="Destroy"}(Qt||(Qt={}));class Cr{get priority(){return Yt.LOW}get kind(){return qt.Unknow}}class hr extends Cr{constructor(e=Wt.NORMAL){super(),this.state=e}get kind(){return qt.AsyncCommand}setState(e){this.state=e}pickoutSubscribed(e,t){const{unsubscribe:r,subscribe:o}=this.calcSubscribeList(e,t);return hr.AsyncSubscribeTasks=[],hr.AsyncUnsubscribeTasks=[],hr.AsyncUpdateSubscribeTasks=[],{subscribe:o,unsubscribe:r}}calcSubscribeList(e,t){const r=[],o=new Set,i=[],s=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)||o.has(t)||(r.push(e),o.add(t))})),n.forEach((e=>{const t=`${e.track.getTrackId()}_SUB_${e.subTiny?"0":"1"}`;this.trackInSubscribeList(e,a)||s.has(t)||(i.push(e),s.add(t))})),{unsubscribe:r,subscribe:i}}formateTrack(e){return e.map((e=>e instanceof je?{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}}hr.AsyncSubscribeTasks=[],hr.AsyncUnsubscribeTasks=[],hr.AsyncUpdateSubscribeTasks=[];class gr extends class{constructor(e,t,r,o,i,s,n,a,c){this.context=e,this.service=t,this.peerMgr=r,this.roomId=o,this.crtUserId=i,this.roomMode=s,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 o=this._remoteTracks[r];o.getUserId()===e&&t.push(o)}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}=rt(e);return this._roomResources[t].find((t=>tt(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 t in this._roomResources){const r=this._roomResources[t];t!==this.crtUserId&&0!==r.length&&r.forEach((t=>{const r=tt(t),{tag:o,userId:i,mediaType:s}=rt(r),n=s===e.RCMediaType.AUDIO_ONLY?new Je(o,i):new qe(o,i);n.__innerSetRemoteMuted(0===t.state),this._remoteTracks[r]=n}))}}initWithRoomData(e){this._sessionId=e.sessionId,this._token=e.token,this.isUpgrade?this._roomResources={}:this._roomResources=gt(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 pr 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 r(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 o;try{o=yield e.execute(this._store,this)}catch(e){return r(e),void this._next()}t(o),this._next()}))}push(e){return new Promise(((t,r)=>{if(this._isDestroyed)return;const{kind:o}=e;this._queue.length>0&&o===qt.AsyncCommand&&({command:e,resolve:t,reject:r}=this.commandOffset(e,t,r));const{priority:i}=e;if(i===Yt.LOW)this._queue.push({command:e,resolve:t,reject:r});else{const o=this._queue.findIndex((e=>e.command.priority<i)),s=-1===o?this._queue.length-1:o;this._queue.splice(s,0,{command:e,resolve:t,reject:r})}Promise.resolve().then((()=>{this._execute()}))}))}commandOffset(e,t,o){const i=this._queue.length-1;if(!(this._queue[i].command.kind===qt.AsyncCommand))return{command:e,resolve:t,reject:o};const[s]=this._queue.splice(i,1);s.command instanceof hr&&(s.command.setState(Wt.MIDDLE),e instanceof hr&&e.setState(Wt.TAIL));const n=e.execute;return e.execute=function(t,o){return r(this,void 0,void 0,(function*(){return s.command.execute.call(s.command,t,o),n.call(e,t,o)}))},{command:e,resolve:e=>{s.resolve.call(s,e),t(e)},reject:e=>{s.reject.call(s,e),o(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(t,r,o,i,s,n,a,c,d){super(new gr(t,r,o,i,s,n,a,c,d),e.RCRTCCode.ROOM_HAS_BEEN_DESTROYED)}get store(){return this._store}destroy(){super.destroy(),this._store.removeRemoteTracks()}}class Sr extends Cr{execute(e){return r(this,void 0,void 0,(function*(){const r=e.getResourcesByUserId(e.crtUserId),i=r.slice();r.length=0,o.info(`unpublish uris before rejoin -> ${JSON.stringify(i)}`);const s=yield e.context.setRTCTotalRes(e.roomId,We(Tt.UNPUBLISH,i),Ye([]),Tt.TOTAL_CONTENT_RESOURCE,Ye([]));s!==t.ErrorCode.SUCCESS?o.error(`unpublish uris before rejoin failed -> code: ${s}`):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"}(zt||(zt={})),e.RTCJoinType=void 0,(Zt=e.RTCJoinType||(e.RTCJoinType={}))[Zt.KICK=0]="KICK",Zt[Zt.REFUSE=1]="REFUSE",Zt[Zt.COEXIST=2]="COEXIST";class mr extends Cr{constructor(e,t,r,o,i,s){super(),this.roomId=e,this.roomType=t,this.joinType=r,this.livingType=o,this.innerUserDatas=i,this.outerUserDatas=s}get kind(){return qt.JoinRoom}execute(i,a){var c,d,u,_,l,R;return r(this,void 0,void 0,(function*(){const r=At.getMemo(),C={dur:0,cod:0,rid:"",rtp:this.roomType,csnid:"",snid:"",time:0,cr:"unknown",net:"unknown",uid:""};r.qualityJoinRoomReportData=C,r.joinRoomData={start:Date.now()};const{context:h,service:g}=i;let p=s.L_RTC_CLIENT_JOIN_RTC_ROOM_R;if(this.roomType===zt.LIVE?p=s.L_RTC_CLIENT_JOIN_LIVING_ROOM_R:this.roomType===zt.CROSS_MUTI&&(p=s.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_R),h.getConnectionStatus()!==t.ConnectionStatus.CONNECTED)return t.logger.error(p,{status:n.FAILED,code:e.RCRTCCode.SIGNAL_DISCONNECTED,msg:"im not connected"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_DISCONNECTED};if(g.detectorMediaSever(),ht(h.getNaviInfo()))return t.logger.error(p,{status:n.FAILED,code:e.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_usl error"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR};if(!t.validate("roomId",this.roomId,t.notEmptyString,!0))return t.logger.error(p,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(!t.validate("roomType",this.roomType,(e=>void 0!==zt[e])))return t.logger.error(p,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> roomType"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(!t.validate("outerUserDatas",this.outerUserDatas,t.isObject,!1))return t.logger.error(p,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(this.outerUserDatas){if(!Object.keys(this.outerUserDatas).every((e=>t.validate(`outerUserDatas.${e}`,this.outerUserDatas[e],t.isString,!0))))return t.logger.error(p,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR}}if(!g.getNaviMS().length)return t.logger.error(p,{status:n.FAILED,code:e.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};o.info(`joinRoom -> roomId: ${this.roomId}; joinType: ${this.joinType||e.RTCJoinType.KICK}`);const{code:S,data:m}=yield h.joinRTCRoom(this.roomId,this.roomType,this.livingType,this.joinType,this.innerUserDatas,this.outerUserDatas);if(S!==t.ErrorCode.SUCCESS||!m){const a=Date.now(),u=JSON.stringify(Object.assign(r.qualityJoinRoomReportData,{dur:a-((null===(c=r.joinRoomData)||void 0===c?void 0:c.start)||0),cod:S,rid:this.roomId,csnid:null===(d=r.clientData)||void 0===d?void 0:d.clientSessionId,snid:i.getSessionId(),time:a,uid:i.crtUserId}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_JOIN_ROOM_S,u,t.LogSource.RTC),o.warn(`joinRoom failed -> code: ${S}`);const _=40032===S?e.RCRTCCode.SIGNAL_JOIN_RTC_ROOM_REFUSED:S;return t.logger.error(p,{status:n.FAILED,code:_,msg:`joinRoom failed -> code: ${S}`},{logSource:t.LogSource.RTC}),{code:_}}o.info(`joinRoom success -> userId: ${h.getCurrentId()}, roomId: ${this.roomId}, data: ${JSON.stringify(m)}`);const T=Date.now(),I=JSON.stringify(Object.assign(r.qualityJoinRoomReportData,{dur:T-((null===(u=r.joinRoomData)||void 0===u?void 0:u.start)||0),cod:S,rid:this.roomId,csnid:null===(_=r.clientData)||void 0===_?void 0:_.clientSessionId,snid:m.sessionId,time:T,uid:i.crtUserId}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_JOIN_ROOM_S,I,t.LogSource.RTC),r.joinRoomData={start:null===(l=r.joinRoomData)||void 0===l?void 0:l.start,roomId:this.roomId},i.initWithRoomData(m);i.getResourcesByUserId(i.crtUserId).length>0&&a.push(new Sr);const E=null===(R=m.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===R?void 0:R.value;return E&&i.setCDNUris(JSON.parse(E)[0]),t.logger.info(p,{status:n.SUCCESSED,userId:i.crtUserId,roomId:this.roomId,data:m},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,data:m}}))}}function Tr(e,t,o,i){return r(this,void 0,void 0,(function*(){return{sdp:yield o.createOffer(t),extend:JSON.stringify({resolutionInfo:o.getOutboundVideoInfo()}),subscribeList:e.filter((e=>{const t=e.track.getTrackId(),{userId:r}=rt(t),o=i.getResourcesByUserId(r);if(!o)return!1;const s=o.filter((e=>t===`${e.msid}_${e.mediaType}`)).length;return s})).map((e=>({simulcast:e.subTiny?yt.TINY:yt.NORMAL,resolution:"",uri:i.getPublishedResourceByTrackId(e.track.getTrackId()).uri}))),switchstream:!1}}))}function Ir(i,s,n){return r(this,void 0,void 0,(function*(){const r=yield i.setRTCCDNUris(s,Tt.TOTAL_CONTENT_RESOURCE,JSON.stringify([n]));return r!==t.ErrorCode.SUCCESS?(o.error(`spreadCDNInfo failed -> code: ${r}`),{code:e.RCRTCCode.SIGNAL_ERROR}):(o.info("spreadCDNInfo succeed"),{code:e.RCRTCCode.SUCCESS})}))}function Er(i,s,n){return r(this,void 0,void 0,(function*(){const r=yield i.setRTCData(s,"cdn_uris",JSON.stringify([n]),!0,rr.ROOM);return r!==t.ErrorCode.SUCCESS?(o.error(`setRoomCDNInfo failed -> code: ${r}`),{code:e.RCRTCCode.SIGNAL_ERROR}):(o.info("setRoomCDNInfo succeed"),{code:e.RCRTCCode.SUCCESS})}))}function fr(o){return r(this,void 0,void 0,(function*(){const{context:r}=o,{roomId:i}=o,a=Object.assign({},o.getCDNUris(),{enableInnerCDN:o.getCDNEnable()});t.logger.info(s.L_LIVING_ROOM_SPREAD_CDN_INFO_T,{roomId:i,CDNUris:a},{logSource:t.LogSource.RTC});const c=(yield Promise.all([Ir(r,i,a),Er(r,i,a)])).every((t=>t.code===e.RCRTCCode.SUCCESS));return c?t.logger.info(s.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:n.SUCCESSED,CDNUris:a},{logSource:t.LogSource.RTC}):t.logger.error(s.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:n.FAILED,code:e.RCRTCCode.SIGNAL_ERROR,msg:"signal error"},{logSource:t.LogSource.RTC}),c?{code:e.RCRTCCode.SUCCESS}:{code:e.RCRTCCode.SIGNAL_ERROR}}))}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(Xt||(Xt={})),function(e){e.BEGIN="begin",e.END="end"}(er||(er={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(tr||(tr={})),function(e){e[e.ROOM=1]="ROOM",e[e.PERSON=2]="PERSON"}(rr||(rr={}));class Lr extends Cr{constructor(e,t){super(),this.headers=e,this.reqBody=t}execute(t,o){var i,s;return r(this,void 0,void 0,(function*(){const r=yield t.service.exchange(this.headers,this.reqBody);if(t.roomMode!==zt.LIVE)return r;const o=null===(s=null===(i=r.data)||void 0===i?void 0:i.urls)||void 0===s?void 0:s.pull_url;if(r.code!==e.RCRTCCode.SUCCESS||!o)return r;const n=JSON.parse(o);return t.setCDNUris(n),(null==n?void 0:n.broadcast)===tr.SPREAD&&(t.setCDNEnabel(!0),fr(t)),r}))}}class vr extends Cr{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(i,n){var a,c;return r(this,void 0,void 0,(function*(){const{tracks:r,forceReq:d}=this,{roomId:u}=i;if(!t.validate("tracks",r,(()=>t.isArray(r)&&r.every((e=>e instanceof je||e.track instanceof je))),!0))return o.warn(`update sublist failed, tracks is invalid -> roomId: ${u}`),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`update subscribe list -> roomId: ${u}, forceReq: ${d}, tracks: ${r.map(St)}`);let _=r.map((e=>e instanceof je?{track:e}:Object.assign({},e)));const l={};_=_.filter((e=>{const t=e.track.getTrackId();return i.getRemoteTrack(t)?!l[t]&&(l[t]=!0,!0):(o.warn(`track cannot found in room -> trackId: ${t}`),!1)})).map((e=>Object.assign({},e)));const R=i.getSubscribedList().map((e=>Object.assign({},e)));if(!d){let t=!1;if(_.forEach((e=>{const r=R.findIndex((t=>t.track===e.track));if(-1===r)return void(t=!0);R.splice(r,1)[0].subTiny!==e.subTiny&&(t=!0)})),R.length&&(t=!0),!t)return{code:e.RCRTCCode.SUCCESS}}const{pc:C,pushOtherRooms:h,headers:g}=this.subhook(r);C.updateSubRemoteTracks(_.map((e=>e.track)));const p=At.getMemo();t.logger.info(s.L_QS_CREATE_OFFER_O,{identify:p.qualityStatusId},{logSource:t.LogSource.RTC});const S={dur:0,cod:0,rid:i.roomId,csnid:null===(a=p.clientData)||void 0===a?void 0:a.clientSessionId,snid:i.getSessionId(),rsid:"",msa:"",msas:[],time:0,resid:"",mtp:0,smct:1,cr:"unknown",net:"unknown",uid:"",stp:0};p.qualitySubscribeReportData=S,p.subscribeData={start:Date.now()};const m={dur:0,cod:0,rid:i.roomId,csnid:null===(c=p.clientData)||void 0===c?void 0:c.clientSessionId,snid:i.getSessionId(),rsid:"",msa:"",msas:[],time:0,resid:"",mtp:0,smct:1,uid:"",stp:0};p.qualityUnsubscribeReportData=m,p.unsubscribeData={start:Date.now()};const T=yield Tr(_,!1,C,i);h&&(T.pushOtherRooms=h),t.logger.info(s.L_QS_SUBSCRIBE_EXCHANGE_O,{identify:p.qualityStatusId},{logSource:t.LogSource.RTC});const I=yield new Lr(g,T).execute(i,n),E=_.map((e=>e.track.getTrackId()));if(I.code!==e.RCRTCCode.SUCCESS){let e=[],r=Date.now();return p.mediaService.forEach((t=>{e.push({rsid:t.reqId,rsdur:t.end-t.start,msa:t.url,rscod:t.rscod})})),p.subscribeCommand&&(p.subscribeCommand=!1,_.forEach((o=>{var i,n;const a=JSON.stringify(Object.assign(p.qualitySubscribeReportData,{dur:r-((null===(i=p.subscribeData)||void 0===i?void 0:i.start)||0),cod:I.code,msas:e,time:r,resid:o.track.getTrackId(),mtp:rt(o.track.getTrackId()).mediaType,smct:o.track instanceof we&&(null===(n=o.track)||void 0===n?void 0:n.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,a,t.LogSource.RTC)}))),p.unsubscribeCommand&&(p.unsubscribeCommand=!1,_.forEach((o=>{var i,n;const a=JSON.stringify(Object.assign(p.qualityUnsubscribeReportData,{dur:r-((null===(i=p.unsubscribeData)||void 0===i?void 0:i.start)||0),cod:I.code,time:r,msas:e,resid:o.track.getTrackId(),mtp:rt(o.track.getTrackId()).mediaType,smct:o.track instanceof we&&(null===(n=o.track)||void 0===n?void 0:n.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,a,t.LogSource.RTC)}))),{code:I.code}}const{sdp:f,resultCode:L,message:v,subscribedList:O}=I.data;if(L!==e.RCRTCCode.SUCCESS){let e=[],r=Date.now();return p.mediaService.forEach((t=>{e.push({rsid:t.reqId,rsdur:t.end-t.start,msa:t.url,rscod:t.rscod})})),p.subscribeCommand&&(p.subscribeCommand=!1,_.forEach((o=>{var i,n;const a=JSON.stringify(Object.assign(p.qualitySubscribeReportData,{dur:r-((null===(i=p.subscribeData)||void 0===i?void 0:i.start)||0),cod:L,msas:e,time:r,resid:o.track.getTrackId(),mtp:rt(o.track.getTrackId()).mediaType,smct:o.track instanceof we&&(null===(n=o.track)||void 0===n?void 0:n.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,a,t.LogSource.RTC)}))),p.unsubscribeCommand&&(p.unsubscribeCommand=!1,_.forEach((o=>{var i,n;const a=JSON.stringify(Object.assign(p.qualityUnsubscribeReportData,{dur:r-((null===(i=p.unsubscribeData)||void 0===i?void 0:i.start)||0),cod:L,msas:e,time:r,resid:o.track.getTrackId(),mtp:rt(o.track.getTrackId()).mediaType,smct:o.track instanceof we&&(null===(n=o.track)||void 0===n?void 0:n.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,a,t.LogSource.RTC)}))),o.error(`change subscribe list failed: ${L}`),{code:L}}t.logger.info(s.L_QS_GET_ANSWER_O,{identify:p.qualityStatusId},{logSource:t.LogSource.RTC}),o.debug(`subscribe success: ${E.join(",")}`);const A=yield C.setRemoteAnswer(f.sdp);if(A!==e.RCRTCCode.SUCCESS){let e=[],r=Date.now();return p.mediaService.forEach((t=>{e.push({rsid:t.reqId,rsdur:t.end-t.start,msa:t.url,rscod:t.rscod})})),p.subscribeCommand&&(p.subscribeCommand=!1,_.forEach((o=>{var i,n;const a=JSON.stringify(Object.assign(p.qualitySubscribeReportData,{dur:r-((null===(i=p.subscribeData)||void 0===i?void 0:i.start)||0),cod:A,msas:e,time:r,resid:o.track.getTrackId(),mtp:rt(o.track.getTrackId()).mediaType,smct:o.track instanceof we&&(null===(n=o.track)||void 0===n?void 0:n.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,a,t.LogSource.RTC)}))),p.unsubscribeCommand&&(p.unsubscribeCommand=!1,_.forEach((o=>{var i,n;const a=JSON.stringify(Object.assign(p.qualityUnsubscribeReportData,{dur:r-((null===(i=p.unsubscribeData)||void 0===i?void 0:i.start)||0),cod:A,msas:e,time:r,resid:o.track.getTrackId(),mtp:rt(o.track.getTrackId()).mediaType,smct:o.track instanceof we&&(null===(n=o.track)||void 0===n?void 0:n.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,a,t.LogSource.RTC)}))),{code:A}}let D=[],N=Date.now();p.mediaService.forEach((e=>{D.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),p.subscribeCommand&&(p.subscribeCommand=!1,_.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(p.qualitySubscribeReportData,{dur:N-((null===(r=p.subscribeData)||void 0===r?void 0:r.start)||0),cod:A,msas:D,time:N,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,i,t.LogSource.RTC)}))),p.unsubscribeCommand&&(p.unsubscribeCommand=!1,_.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(p.qualityUnsubscribeReportData,{dur:N-((null===(r=p.unsubscribeData)||void 0===r?void 0:r.start)||0),cod:A,msas:D,time:N,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,i,t.LogSource.RTC)}))),p.iceStatusData?p.iceStatusData.subscribe={time:Date.now()}:p.iceStatusData={};const y=null==O?void 0:O.map((e=>`${e.msid}_${e.mediaType}`)),b=_.filter((e=>null==y?void 0:y.includes(e.track.getTrackId()))),k=_.filter((e=>!(null==y?void 0:y.includes(e.track.getTrackId())))),U=i.getRemoteTracks();for(const e in U){const t=b.some((t=>t.track.getTrackId()===e));U[e].__innerSetSubscribed(t);const r=b.some((t=>t.track.getTrackId()===e&&t.subTiny));U[e].isVideoTrack()&&U[e].__innerSetIsTinyTrack(r)}return i.resetSubscribedList(b),t.logger.info(s.L_QS_GET_RESOURCES_O,{identify:p.qualityStatusId},{logSource:t.LogSource.RTC}),k.length?{code:e.RCRTCCode.SUCCESS,failedList:k}:{code:e.RCRTCCode.SUCCESS}}))}}class Or extends Cr{constructor(e,t){super(),this.tracks=e,this.subhook=t}execute(i,a){return r(this,void 0,void 0,(function*(){const{tracks:r}=this,{roomId:c}=i;if(t.logger.info(s.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:r.map(St)},{logSource:t.LogSource.RTC}),!t.validate("tracks",r,(()=>t.isArray(r)&&r.length>0&&r.every((e=>e instanceof je))),!0))return o.warn(`unsubscribe failed, tracks is invalid -> roomId: ${c}`),t.logger.warn(s.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`unsubscribe -> roomId: ${c}, tracks: ${r.map(St)}`);const d=i.getSubscribedList().map((e=>Object.assign({},e))).filter((e=>!r.includes(e.track)));i.polarisReport.sendR2(Xt.SUBSCRIBE,er.END,r.map((e=>e.getTrackId()))),t.logger.info(s.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:r.map(St),roomId:c},{logSource:t.LogSource.RTC});return At.getMemo().unsubscribeCommand=!0,new vr(d,this.subhook,!1).execute(i,a)}))}}class Ar extends Cr{constructor(e,t){super(),this.msgContent=e,this.subhook=t}get priority(){return Yt.NORMAL}execute(e,t){return r(this,void 0,void 0,(function*(){const r=[],i=[],s=[],n=[],a={joined:r,left:i,upgrade:s,downgrade:n},{users:c}=this.msgContent;if(0===c.length)return a;for(let t=0;t<c.length;t++){const r=c[t];if(r.extra&&r.extra.roomId!==e.roomId)return a;if(1==+r.state&&!e.getRemoteUserIds().includes(r.userId))return a}c.forEach((t=>{const{userId:a}=t;if(0==+t.state){o.info(`user joined -> ${a}`);const i=e.getResourcesByUserId(a);i||(t.switchRoleType?s.push(a):r.push(a)),e.setResourcesByUserId(a,i||[])}else o.info(`user left -> ${a}`),t.switchRoleType?n.push(a):i.push(a)}));const d=[...i,...n];if(d.length){const r=[],o=[];d.forEach((t=>{r.push(...e.getRemoteTracksByUserId(t)),o.push(t)})),r.length&&(yield new Or(r,this.subhook).execute(e,t),r.forEach((t=>e.removeRemoteTrack(t.getTrackId())))),o.length&&o.forEach((t=>e.removeResourcesByUserId(t)))}return a}))}}class Dr extends Cr{constructor(e,t,r){super(),this.subhook=e,this.tracks=t,this.onTrackUnpublish=r}execute(e,t){return r(this,void 0,void 0,(function*(){const{tracks:r}=this;yield new Or(r,this.subhook).execute(e,t),r.forEach((t=>{t.__innerDestroy(),e.removeRemoteTrack(t.getTrackId())})),this.onTrackUnpublish(r)}))}}class Nr extends Cr{constructor(e,t,r,o,i){super(),this.msgContent=e,this.messageType=t,this.senderId=r,this.subhook=o,this.callback=i}get priority(){return Yt.NORMAL}execute(t,i){var s,n;return r(this,void 0,void 0,(function*(){const{uris:r}=this.msgContent,a=[],c=[],d=[];let u;const _=this.senderId,{messageType:l}=this,R=t.getResourcesByUserId(_)||[];switch(t.setResourcesByUserId(_,R),l){case Tt.MODIFY:d.push(...r);break;case Tt.PUBLISH:a.push(...r);break;case Tt.UNPUBLISH:c.push(...r);break;case Tt.TOTAL_CONTENT_RESOURCE:u=st(R,r),a.push(...u.publishedList),c.push(...u.unpublishedList),d.push(...u.modifiedList)}if(a.length>0){const r=R.map(tt),s=[],n=[];if(a.forEach((o=>{const i=tt(o),a=r.indexOf(i),{userId:c,tag:d,mediaType:u}=rt(i);a>-1?R[a]=o:R.push(o);let _=t.getRemoteTrack(i);_?_.isSubscribed()&&s.push(_):(_=u===e.RCMediaType.AUDIO_ONLY?new Je(d,c):new qe(d,c),t.addRemoteTrack(_),n.push(_)),_.__innerSetRemoteMuted(0===o.state)})),s.length){const r=s.map((e=>e.getTrackId()));o.debug(`resub tracks -> ${JSON.stringify(r)}`);const{code:n}=yield new vr(s,this.subhook).execute(t,i);n!==e.RCRTCCode.SUCCESS&&o.error(`resub tracks failed -> code: ${n}, ids: ${JSON.stringify(r)}`)}this.callback.onTrackPublish(n)}if(c.length>0){const e=c.map(tt);for(let t=R.length-1;t>=0;t-=1){const r=R[t];e.includes(tt(r))&&R.splice(t,1)}const r=c.map((e=>{const r=tt(e);return t.getRemoteTrack(r)}));yield new Dr(this.subhook,r,this.callback.onTrackUnublish).execute(t,i)}if(d.length>0){const e=R.map(tt);for(let r=0;r<d.length;r+=1){const o=d[r],i=tt(o),s=e.indexOf(i);R[s].state=o.state;const n=t.getRemoteTrack(i);n.__innerSetRemoteMuted(0===o.state),n.isAudioTrack()?this.callback.onAudioMute(n):this.callback.onVideoMute(n)}}if(t.roomMode!==zt.LIVE)return;const C=this.msgContent;if(!C.cdn_uris)return;const h=(null===(s=t.getCDNUris())||void 0===s?void 0:s.enableInnerCDN)!==C.cdn_uris[0].enableInnerCDN;t.setCDNUris(C.cdn_uris[0]),h&&this.callback.onCDNEnableChange(!!(null===(n=t.getCDNUris())||void 0===n?void 0:n.enableInnerCDN))}))}}class yr extends Cr{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(i,a){return r(this,void 0,void 0,(function*(){const{tracks:r,forceReq:c}=this,{roomId:d}=i;if(t.logger.info(s.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:r.map(St),forceReq:c},{logSource:t.LogSource.RTC}),!t.validate("tracks",r,(()=>t.isArray(r)&&r.length>0&&r.every((e=>e instanceof je||e.track instanceof je))),!0))return o.warn(`subscribe failed, tracks is invalid -> roomId: ${d}`),t.logger.error(s.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`subscribe -> roomId: ${d}, tracks: ${r.map(St)}`);const u=i.getSubscribedList().map((e=>Object.assign({},e))),_=r.map((e=>e instanceof je?{track:e}:e));let l=!1;const R=[];if(_.forEach((e=>{const t=e.track.getTrackId();R.push(t);const r=u.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:u.push(e),l=!0)})),!l&&!c)return t.logger.warn(s.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:n.FAILED,code:"",msg:"repeat subscribe"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS};i.polarisReport.sendR2(Xt.SUBSCRIBE,er.BEGIN,R),t.logger.info(s.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:r.map(St),roomId:d},{logSource:t.LogSource.RTC});return At.getMemo().subscribeCommand=!0,new vr(u,this.subhook,!0).execute(i,a)}))}}class br extends Cr{constructor(e,t){super(),this.tracks=e,this.pubhook=t}get kind(){return qt.Publish}_removePubFailedTracks(e,t){e.forEach((e=>{const r=e instanceof Me?e:e.track;o.debug(`remove pub failed track from peerconnection -> trackId: ${r.getTrackId()}`),t.removeLocalTrackById(r.getTrackId())}))}__publish(i,a,c,d,u){var _;return r(this,void 0,void 0,(function*(){const{pcName:r,pc:l,headers:R}=a,{roomId:C}=i,h=[];c.forEach((e=>{const{track:t}=e instanceof Me?{track:e}:e;h.push(t)})),c.sort(((e,t)=>{const{track:r}=e instanceof Me?{track:e}:e,{max:o}=r.getBitrate(),{track:i}=t instanceof Me?{track:t}:t,{max:s}=i.getBitrate();return o-s}));if(l.getLocalTracks().length+((e,t)=>{let r=0;return e.forEach((e=>{const o=e instanceof Me?e.getTrackId():e.track.getTrackId();t.getLocalTrack(o)||(e instanceof Me?r++:e.pubTiny&&e.track.isVideoTrack()&&(r+=2))})),r})(c,l)>10)return o.error(`publish failed, tracks limit exceeded -> roomId: ${C}`),{code:e.RCRTCCode.PUBLISH_TRACK_LIMIT_EXCEEDED,tracks:h};o.debug(`publish tracks -> roomId: ${C}, tracks: ${c.map(St)}`);for(let t=0;t<c.length;t++){const r=c[t],{track:i,pubTiny:s}=r instanceof Me?{pubTiny:!1,track:r}:r;if(i.isVideoTrack()&&s){let t;try{t=i.__innerGetMediaStreamTrack().clone();const r=s.frameRate||e.RCFrameRate.FPS_15,o=s.resolution||e.RCResolution.W176_H144,{width:n,height:a}=at(o),c=ut(r);yield t.applyConstraints({width:n,height:a,frameRate:c})}catch(e){null==t||t.stop(),o.warn(`pubTiny failed -> id: ${i.getTrackId()}, msg: ${e.message}`);break}l.addLocalTrack(new we(i.getTag(),i.getUserId(),t,!0))}l.addLocalTrack(i)}l.clearReTryExchangeTimer();const g=i.useMutilPeerC?[]:i.getSubscribedList(),p=`${Date.now()}`,S=At.getMemo();S.qualityStatus=p,t.logger.info(s.L_QS_CREATE_OFFER_O,{identify:p},{logSource:t.LogSource.RTC});const m={dur:0,cod:0,rid:i.roomId,csnid:null===(_=S.clientData)||void 0===_?void 0:_.clientSessionId,snid:i.getSessionId(),rsid:"",msa:"",msas:[],sigs:[],time:0,resid:"",mtp:0,smct:1,cr:"unknown",net:"unknown",uid:i.crtUserId,stp:0};S.qualityPublishReportData=m,S.publish={start:Date.now()};const T=yield Tr(g,!1,l,i);d&&(T.pushOtherRooms=d),t.logger.info(s.L_QS_PUBLISH_EXCHANGE_O,{identify:p},{logSource:t.LogSource.RTC});const I=yield new Lr(R,T).execute(i,u);if(I.code!==e.RCRTCCode.SUCCESS){const e=Date.now();let r=[];return S.mediaService.forEach((e=>{r.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),h.forEach((o=>{var i;const n=JSON.stringify(Object.assign(S.qualityPublishReportData,{dur:e-((null===(i=S.publish)||void 0===i?void 0:i.start)||0),cod:I.code,msas:r,time:e,resid:o.getTrackId(),mtp:rt(o.getTrackId()).mediaType,smct:o instanceof we&&o.__isTiny()?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_PUBLISH_S,n,t.LogSource.RTC)})),o.error(`publish failed -> roomId: ${C}, code: ${I.code}`),this._removePubFailedTracks(c,l),{code:I.code,tracks:h}}t.logger.info(s.L_QS_GET_ANSWER_O,{status:n.SUCCESSED,identify:p},{logSource:t.LogSource.RTC});const{sdp:E,resultCode:f,message:L}=I.data;if(f!==e.RCRTCCode.SUCCESS){const e=Date.now();let r=[];return S.mediaService.forEach((e=>{r.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),h.forEach((o=>{var i;const n=JSON.stringify(Object.assign(S.qualityPublishReportData,{dur:e-((null===(i=S.publish)||void 0===i?void 0:i.start)||0),cod:f,msas:r,time:e,resid:o.getTrackId(),mtp:rt(o.getTrackId()).mediaType,smct:o instanceof we&&o.__isTiny()?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_PUBLISH_S,n,t.LogSource.RTC)})),o.error(`publish failed -> roomId: ${C}, code: ${f}, msg: ${L}`),this._removePubFailedTracks(c,l),{code:f,tracks:h}}const v=yield l.setRemoteAnswer(E.sdp);if(v!==e.RCRTCCode.SUCCESS){const e=Date.now();let r=[];return S.mediaService.forEach((e=>{r.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),h.forEach((o=>{var i;const n=JSON.stringify(Object.assign(S.qualityPublishReportData,{dur:e-((null===(i=S.publish)||void 0===i?void 0:i.start)||0),cod:v,msas:r,time:e,resid:o.getTrackId(),mtp:rt(o.getTrackId()).mediaType,smct:o instanceof we&&o.__isTiny()?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_PUBLISH_S,n,t.LogSource.RTC)})),{code:v,tracks:h}}return Object.assign(Object.assign({},I),{tracks:h})}))}_mergePublishRes(i,n){return r(this,void 0,void 0,(function*(){const r=n.crtUserId,{roomId:a}=n;let c="";const d=[],u=n.getResourcesByUserId(r),_=[...u];let l=[];i.forEach((t=>{if(t.code!==e.RCRTCCode.SUCCESS){const{tracks:e}=t;return void d.push({code:t.code,tracks:e})}const{publishList:r,urls:o,mcuPublishList:i}=t.data;c=null==o?void 0:o.liveUrl;r.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:n.getTrackState(tt(e))},e))).forEach((e=>{const{isInclude:t,index:r}=((e,t)=>{let r=!1,o=0;for(let i=0;i<t.length;i++){const s=t[i];if(`${e.msid}_${e.mediaType}`==`${s.msid}_${s.mediaType}`){r=!0,o=i;break}}return{isInclude:r,index:o}})(e,_);t?_.splice(r,1,e):_.push(e)}));const s=(null==i?void 0:i.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))))||[];l=s}));const{publishedList:R}=st(u,_),C=At.getMemo();C.publishSignalTotal={start:Date.now()};const h=yield n.context.setRTCTotalRes(a,We(Tt.PUBLISH,R),Ye(_),Tt.TOTAL_CONTENT_RESOURCE,Ye(l));if(h!==t.ErrorCode.SUCCESS){const r=Date.now();let i=[];C.mediaService.forEach((e=>{i.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const n=[];return n.push({dur:Date.now()-(C.publishSignalTotal.start||0),cod:h}),_.forEach((e=>{var o;const a=JSON.stringify(Object.assign(C.qualityPublishReportData,{dur:r-((null===(o=C.publish)||void 0===o?void 0:o.start)||0),cod:h,msas:i,sigs:n,time:r,resid:tt(e),mtp:e.mediaType,smct:e.simulcast}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_PUBLISH_S,a,t.LogSource.RTC)})),o.error(`send publish streams notification failed: ${h}`),{code:e.RCRTCCode.SIGNAL_ERROR}}const g=Date.now();let p=[];C.mediaService.forEach((e=>{p.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const S=[];S.push({dur:Date.now()-(C.publishSignalTotal.start||0),cod:h}),_.forEach((e=>{var r;const o=JSON.stringify(Object.assign(C.qualityPublishReportData,{dur:g-((null===(r=C.publish)||void 0===r?void 0:r.start)||0),cod:h,msas:p,sigs:S,time:g,resid:tt(e),mtp:e.mediaType,smct:e.simulcast}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_PUBLISH_S,o,t.LogSource.RTC)})),C.iceStatusData?C.iceStatusData.publish={time:Date.now()}:C.iceStatusData={},n.setResourcesByUserId(r,_);const m=R.map((e=>tt(e)));n.polarisReport&&n.polarisReport.sendR2(Xt.PUBLISH,er.BEGIN,m),R.forEach((e=>{const t=n.useMutilPeerC?`${a}_${(e=>{const t=e.split("_");return{tag:t.pop(),userId:t.join("_")}})(e.msid).tag}`:`${a}_pub`,{pc:r}=n.peerMgr.getPCItemByPCName(t);r.getLocalTrack(`${e.msid}_${e.mediaType}`).__innerSetPublished(!0)})),o.debug(`publish success: ${m.join(",")}`);const T={code:e.RCRTCCode.SUCCESS};return c&&(T.liveUrl=c),d.length&&(T.failedTracks=d,T.code=e.RCRTCCode.SOME_TRACKS_PUBLISH_FAILED),T}))}execute(i,a){return r(this,void 0,void 0,(function*(){let{tracks:r}=this;const{roomId:c}=i;if(t.logger.info(s.L_ABSTRACT_ROOM_PUBLISH_T,{trackIds:r.map(St)},{logSource:t.LogSource.RTC}),!t.validate("tracks",r,(()=>t.isArray(r)&&r.length>0&&r.every((e=>e instanceof Me||e.track instanceof Me))),!0))return o.warn(`publish failed, tracks is invalid -> roomId: ${c}`),t.logger.error(s.L_ABSTRACT_ROOM_PUBLISH_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(r=r.filter((e=>{const{track:r}=e instanceof Me?{track:e}:e,o=r.isDestroyed();return o&&t.logger.warn(s.L_ABSTRACT_ROOM_PUBLISH_R,{status:n.FAILED,msg:`track -> ${r.getTrackId()} has beem destroyed`}),!o})),!r.length)return{code:e.RCRTCCode.PUBLISH_TRACKS_IS_INVALID};const d=[],{plist:u,pushOtherRooms:_}=this.pubhook(r);for(let e=0;e<u.length;e++){const t=u[e];d.push(this.__publish(i,t,t.tracks,_,a))}const l=yield Promise.all(d),R=yield this._mergePublishRes(l,i);return t.logger.info(s.L_ABSTRACT_ROOM_PUBLISH_R,{status:n.SUCCESSED,roomId:c,trackIds:r.map(St)},{logSource:t.LogSource.RTC}),R}))}}class kr extends Cr{constructor(e,t){super(),this.tracks=e,this.unpubhook=t}get kind(){return qt.UnPublish}__unpublish(i,n,a,c){var d;return r(this,void 0,void 0,(function*(){const{pcName:r,pc:u}=a,_=c.map((e=>e.getTrackId()));if(0===_.map(i.getPublishedResourceByTrackId.bind(i)).filter((e=>!!e)).length)return{code:e.RCRTCCode.SUCCESS,tracks:c};_.forEach((e=>u.removeLocalTrackById(e))),i.polarisReport.sendR2(Xt.PUBLISH,er.END,_),u.clearReTryExchangeTimer();const l=i.useMutilPeerC?[]:i.getSubscribedList(),R=At.getMemo(),C={dur:0,cod:0,rid:i.roomId,csnid:null===(d=R.clientData)||void 0===d?void 0:d.clientSessionId,snid:i.getSessionId(),rsid:"",msa:"",msas:[],sigs:[],time:0,resid:"",mtp:0,smct:1,uid:i.crtUserId,stp:0};R.qualityUnpublishReportData=C,R.unpublish={start:Date.now()};const h=yield Tr(l,!1,u,i),{pushOtherRooms:g,headers:p}=this.unpubhook(c,r);g&&(h.pushOtherRooms=g);const S=yield new Lr(p,h).execute(i,n);if(S.code!==e.RCRTCCode.SUCCESS){const e=Date.now();return c.forEach((r=>{var o;const i=r.getTrackId(),n=JSON.stringify(Object.assign(R.qualityUnpublishReportData,{dur:e-((null===(o=R.unpublish)||void 0===o?void 0:o.start)||0),cod:S.code,time:e,resid:i,mtp:rt(i).mediaType,smct:r instanceof we&&r.__isTiny()?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNPUBLISH_S,n,t.LogSource.RTC)})),o.error(`exchange failed -> code: ${S.code}`),{code:S.code,tracks:c}}return Object.assign(Object.assign({},S),{tracks:c})}))}_mergeUnpublishRes(i,n){return r(this,void 0,void 0,(function*(){const a=i.context.getCurrentId(),{roomId:c}=i,d=At.getMemo(),u=[],_=[],l=[],R=[];let C=[];for(let r=0;r<n.length;r++){const a=n[r];if(a.code!==e.RCRTCCode.SUCCESS){const{tracks:e}=a;_.push({code:a.code,tracks:e});continue}const{resultCode:c,message:h,mcuPublishList:g}=a.data;if(c!==e.RCRTCCode.SUCCESS){const e=Date.now();let r=[];d.mediaService.forEach((e=>{r.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),l.forEach((o=>{var i;if(o){const n=JSON.stringify(Object.assign(d.qualityUnpublishReportData,{dur:e-((null===(i=d.publish)||void 0===i?void 0:i.start)||0),cod:c,msas:r,time:e,resid:tt(o),mtp:o.mediaType,smct:o.simulcast}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNPUBLISH_S,n,t.LogSource.RTC)}})),o.error(`unpublish streams failed -> code: ${c}, msg: ${h}`)}const p=a.tracks.map((e=>e.getTrackId()));R.push(...p);const S=p.map(i.getPublishedResourceByTrackId.bind(i)).filter((e=>!!e));l.push(...S),u.push(a);const m=g?g.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[];C=m}const h=i.getResourcesByUserId(a),g=h.filter((e=>!l.includes(e)));d.unPublishSignalTotal={start:Date.now()};const p=yield i.context.setRTCTotalRes(c,We(Tt.UNPUBLISH,l),Ye(g),Tt.TOTAL_CONTENT_RESOURCE,Ye(C));if(p!==t.ErrorCode.SUCCESS){const r=Date.now();let i=[];d.mediaService.forEach((e=>{i.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const n=[];return n.push({dur:Date.now()-(d.unPublishSignalTotal.start||0),cod:p}),h.forEach((e=>{var o;const a=JSON.stringify(Object.assign(d.qualityUnpublishReportData,{dur:r-((null===(o=d.publish)||void 0===o?void 0:o.start)||0),cod:p,msas:i,sigs:n,time:r,resid:tt(e),mtp:e.mediaType,smct:e.simulcast}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNPUBLISH_S,a,t.LogSource.RTC)})),o.error("send unpublish notification failed:",p),{code:e.RCRTCCode.SIGNAL_ERROR}}o.debug(`unpublish success -> tracks: ${R.join(",")}`);const S=Date.now();let m=[];d.mediaService.forEach((e=>{m.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})}));const T=[];T.push({dur:Date.now()-(d.unPublishSignalTotal.start||0),cod:p}),h.forEach((r=>{var o;const i=JSON.stringify(Object.assign(d.qualityUnpublishReportData,{dur:S-((null===(o=d.publish)||void 0===o?void 0:o.start)||0),cod:e.RCRTCCode.SUCCESS,msas:m,sigs:T,time:S,resid:tt(r),mtp:r.mediaType,smct:r.simulcast}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNPUBLISH_S,i,t.LogSource.RTC)})),u.forEach((e=>r(this,void 0,void 0,(function*(){const{sdp:t}=e.data,{tracks:r}=e,o=i.peerMgr.getPCByTrackId(r[0].getTrackId());yield o.setRemoteAnswer(t.sdp)})))),i.setResourcesByUserId(a,g);const I={code:e.RCRTCCode.SUCCESS};return _.length&&(I.failedTracks=_,I.code=e.RCRTCCode.SOME_TRACKS_PUBLISH_FAILED),I}))}execute(i,a){return r(this,void 0,void 0,(function*(){const{crtUserId:r,roomId:c}=i,{tracks:d}=this;t.logger.info(s.L_ABSTRACT_ROOM_UNPUBLISH_T,{trackIds:d.map(St)},{logSource:t.LogSource.RTC});if(!t.validate("tracks",d,(()=>d.every((e=>e.getUserId()===r&&e instanceof Me))),!0))return o.warn(`unpublish failed, tracks is invalid -> roomId: ${c}, tracks: ${d.map(St)}`),t.logger.error(s.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};const u=i.peerMgr.createPeerCList(d),_=[];for(let e=0;e<u.length;e++){const{tracks:t}=u[e];_.push(this.__unpublish(i,a,u[e],t))}const l=yield Promise.all(_);let R=l.length;if(l.forEach((t=>{t.code!==e.RCRTCCode.SUCCESS||t.data||(R-=1)})),0===R)return{code:e.RCRTCCode.SUCCESS};const C=yield this._mergeUnpublishRes(i,l);return t.logger.info(s.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:n.SUCCESSED,roomId:c,trackIds:d.map(St)},{logSource:t.LogSource.RTC}),C}))}}class Ur extends Cr{constructor(e,t){super(),this.localTrack=e,this._recvSignalResultFn=t}execute(e,i){return r(this,void 0,void 0,(function*(){const{localTrack:r}=this,i=r.getTrackId(),{crtUserId:s,roomId:n}=e,a=[{resourceId:i,enabled:!r.isLocalMuted()}],c=e.getResourcesByUserId(s),d=[];for(let e=0;e<c.length;e+=1){const t=c[e],r=tt(t),o=a.findIndex((e=>e.resourceId===r));if(o>=0){const{enabled:e}=a[o];t.state=e?1:0,d.push(t);break}}const u=yield e.context.setRTCTotalRes(n,We(Tt.MODIFY,d),Ye(c),Tt.TOTAL_CONTENT_RESOURCE);this._recvSignalResultFn(u),u!==t.ErrorCode.SUCCESS&&o.error(`notice \`track.enabled\` change failed -> code: ${u}`)}))}}class Pr extends Cr{constructor(e,t,r){super(),this.pcName=e,this.isPub=t,this.retryHook=r}get priority(){return Yt.HIGH}execute(t,i){return r(this,void 0,void 0,(function*(){const{pcName:r,isPub:s}=this,{useMutilPeerC:n}=t,{pc:a}=t.peerMgr.getPCItemByPCName(r),c=s&&n?[]:t.getSubscribedList(),d=yield Tr(c,!0,a,t),{pushOtherRooms:u,headers:_}=this.retryHook(r);u&&(d.pushOtherRooms=u);const l=yield new Lr(_,d).execute(t,i);if(l.code!==e.RCRTCCode.SUCCESS)return void o.error(`reTryExchange failed: ${l.code}, pcName: ${r}`);const{sdp:R,resultCode:C}=l.data;C===e.RCRTCCode.SUCCESS?(a.clearReTryExchangeTimer(),yield a.setRemoteAnswer(R.sdp)):o.error(`reTryExchange failed: ${C}, pcName: ${r}`)}))}}class Mr extends Cr{constructor(e,t,r){super(),this.subhook=e,this.callbacks=t,this.livingType=r}get priority(){return Yt.HIGH}execute(i,a){return r(this,void 0,void 0,(function*(){const{livingType:r}=this,{roomId:c,crtUserId:d,roomMode:u}=i;t.logger.info(s.L_ABSTRACT_ROOM_RECONNECTED_T,{livingType:r},{logSource:t.LogSource.RTC});if(i.peerMgr.getPCList().some((e=>"closed"===e.getRTCPeerConn().connectionState)))return o.warn("RTCPeerConnection closed. Please rejoin room to restore services."),t.logger.error(s.L_ABSTRACT_ROOM_RECONNECTED_R,{status:n.FAILED,code:"",msg:"RTCPeerConnection closed"},{logSource:t.LogSource.RTC}),void this.callbacks.onPeerClosed();const{code:_,data:l}=yield i.context.joinRTCRoom(c,u,r);if(_!==t.ErrorCode.SUCCESS)return o.error(`RTC __onReconnected getRTCRoomInfo failed: ${_}`),void t.logger.error(s.L_ABSTRACT_ROOM_RECONNECTED_R,{status:n.FAILED,code:_,msg:""},{logSource:t.LogSource.RTC});o.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(l)}`);const R=[],C={},h={},g={},p=gt(l,c),S=Object.keys(p),m=i.getAllUserIds();for(let e=S.length-1;e>=0;e-=1){const t=S[e],r=m.indexOf(t);if(-1===r){R.push(t),C[t]=it(p[t]);continue}const o=i.getResourcesByUserId(t),s=p[t],{publishedList:n,modifiedList:a,unpublishedList:c}=st(o,s,!0);C[t]=it(n),h[t]=it(c),g[t]=it(a),m.splice(r,1)}m.length&&m.forEach((e=>{i.removeResourcesByUserId(e)})),i.assignRoomData(p),m.length&&this.callbacks.onUserLeave(m),R.length&&this.callbacks.onUserJoin(R);for(const e in h){if(e===d)continue;const t=h[e];if(t.length){const e=t.map((e=>i.getRemoteTrack(tt(e))));yield new Dr(this.subhook,e,this.callbacks.onTrackUnpublish).execute(i,a)}}return Object.keys(C).forEach((t=>{const r=C[t];if(0===r.length)return;const o=r.map((t=>{const r=tt(t),{userId:o,tag:s,mediaType:n}=rt(r),a=n===e.RCMediaType.AUDIO_ONLY?new Je(s,o):new qe(s,o);return i.addRemoteTrack(a),a.__innerSetRemoteMuted(0===t.state),a}));this.callbacks.onTrackPublish(o)})),Object.keys(g).forEach((e=>{g[e].forEach((e=>{const t=tt(e),r=i.getRemoteTrack(t);r.__innerSetRemoteMuted(0===e.state),r.isAudioTrack()?this.callbacks.onAudioMuteChange(r):this.callbacks.onVideoMuteChange(r)}))})),i.roomMode===zt.LIVE&&this.executeInLivingRoom(i,l),t.logger.info(s.L_ABSTRACT_ROOM_RECONNECTED_R,{status:n.SUCCESSED,roomData:l},{logSource:t.LogSource.RTC}),{data:l}}))}executeInLivingRoom(e,r){var o,i;if(t.logger.error(s.L_LIVING_ROOM_RECONNECTED_T,{roomData:r},{logSource:t.LogSource.RTC}),!r)return void t.logger.info(s.L_LIVING_ROOM_RECONNECTED_R,{status:n.FAILED,code:"",msg:"room not fond"},{logSource:t.LogSource.RTC});const{roomInfo:a}=r,c=null===(o=a.filter((e=>"cdn_uris"===e.key))[0])||void 0===o?void 0:o.value;if(!c)return void t.logger.error(s.L_LIVING_ROOM_RECONNECTED_R,{status:n.FAILED,code:"",msg:"cdn_uris not found"},{logSource:t.LogSource.RTC});const d=JSON.parse(c),u=(null===(i=e.getCDNUris())||void 0===i?void 0:i.enableInnerCDN)!==d.enableInnerCDN;e.setCDNUris(d),t.logger.info(s.L_LIVING_ROOM_RECONNECTED_R,{status:n.SUCCESSED,roomData:r},{logSource:t.LogSource.RTC}),u&&this.callbacks.onCDNEnableChange(d.enableInnerCDN)}}class xr extends hr{constructor(e,t,r,o=Wt.NORMAL){super(o),this.tracks=e,this.subhook=t,this.callbacks=r}execute(t,i){var s,n,a;return r(this,void 0,void 0,(function*(){const{tracks:r}=this,{roomId:c}=t;if(o.info(`unsubscribe -> roomId: ${c}, tracks: ${r.map(St)}`),this.state===Wt.NORMAL){const e=t.getSubscribedList().slice(),{code:o,failedList:n}=yield new vr(r,this.subhook).execute(t,i),a=t.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,e);return null===(s=this.callbacks)||void 0===s||s.onTaskCompleted({code:o,subscribe:c,unsubscribe:d,failedList:n}),{code:o,failedList:n}}if(this.state===Wt.TAIL){const{code:r}=yield new xr(this.tracks,this.subhook,this.callbacks,Wt.MIDDLE).execute(t,i);if(r===e.RCRTCCode.SUCCESS){const r=t.getCollectSubscribeList().slice(0),o=t.getSubscribedList().slice(),{code:s,failedList:c}=yield new vr(r,this.subhook).execute(t,i);if(s!==e.RCRTCCode.SUCCESS)return null===(n=this.callbacks)||void 0===n||n.onTaskCompleted({code:s,subscribe:[],unsubscribe:[],failedList:c}),{code:s,failedList:c};const d=t.getSubscribedList().slice(0),{subscribe:u,unsubscribe:_}=this.pickoutSubscribed(d,o);return null===(a=this.callbacks)||void 0===a||a.onTaskCompleted({code:s,subscribe:u,unsubscribe:_,failedList:c}),{code:s,failedList:c}}return{code:r}}return hr.AsyncUpdateSubscribeTasks.splice(hr.AsyncUpdateSubscribeTasks.length,0,...this.tracks),new Promise((o=>{const i=this.formateTrack(r);t.resetCollectSubscribeList(i),o({code:e.RCRTCCode.SUCCESS})}))}))}}class wr extends hr{constructor(e,t,r,o=Wt.NORMAL){super(o),this.tracks=e,this.subhook=t,this.callbacks=r}execute(i,a){var c;return r(this,void 0,void 0,(function*(){const{tracks:r}=this,{roomId:d}=i;if(this.state===Wt.NORMAL){const e=i.getSubscribedList().slice(),{code:t,failedList:o}=yield new yr(r,this.subhook).execute(i,a),s=i.getSubscribedList().slice(),{subscribe:n,unsubscribe:d}=this.pickoutSubscribed(s,e);return null===(c=this.callbacks)||void 0===c||c.onTaskCompleted({code:t,subscribe:n,unsubscribe:d,failedList:o}),{code:t,failedList:o}}if(t.logger.info(s.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:r.map(St)},{logSource:t.LogSource.RTC}),!t.validate("tracks",r,(()=>t.isArray(r)&&r.length>0&&r.every((e=>e instanceof je||e.track instanceof je))),!0))return o.warn(`subscribe failed, tracks is invalid -> roomId: ${d}`),t.logger.error(s.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`subscribe -> roomId: ${d}, tracks: ${r.map(St)}`);const u=this.getSubscribedList(i).map((e=>Object.assign({},e))),_=r.map((e=>e instanceof je?{track:e}:e)),l=[];if(_.forEach((e=>{const t=e.track.getTrackId();l.push(t);const r=u.find((e=>e.track.getTrackId()===t));if(r){if(r.subTiny===e.subTiny)return;r.subTiny=e.subTiny}else u.push(e)})),i.polarisReport.sendR2(Xt.SUBSCRIBE,er.BEGIN,l),t.logger.info(s.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:r.map(St),roomId:d},{logSource:t.LogSource.RTC}),this.state===Wt.TAIL){const{code:t}=yield new wr(this.tracks,this.subhook,this.callbacks,Wt.MIDDLE).execute(i,a);if(t===e.RCRTCCode.SUCCESS){const e=i.getCollectSubscribeList().slice(0);return new xr(e,this.subhook,this.callbacks).execute(i,a)}return{code:t}}return hr.AsyncSubscribeTasks.splice(hr.AsyncSubscribeTasks.length,0,...this.tracks),new Promise((t=>{i.resetCollectSubscribeList(u),t({code:e.RCRTCCode.SUCCESS})}))}))}getSubscribedList(e){return this.state===Wt.MIDDLE?e.getCollectSubscribeList():e.getSubscribedList()}}class Br extends hr{constructor(e,t,r,o=Wt.NORMAL){super(o),this.tracks=e,this.subhook=t,this.callbacks=r}execute(i,a){var c;return r(this,void 0,void 0,(function*(){const{tracks:r}=this,{roomId:d}=i;if(this.state===Wt.NORMAL){const e=i.getSubscribedList().slice(),{code:t,failedList:o}=yield new Or(r,this.subhook).execute(i,a),s=i.getSubscribedList().slice(),{subscribe:n,unsubscribe:d}=this.pickoutSubscribed(s,e);return null===(c=this.callbacks)||void 0===c||c.onTaskCompleted({code:t,subscribe:n,unsubscribe:d,failedList:o}),{code:t,failedList:o}}if(t.logger.info(s.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:r.map(St)},{logSource:t.LogSource.RTC}),!t.validate("tracks",r,(()=>t.isArray(r)&&r.length>0&&r.every((e=>e instanceof je))),!0))return o.warn(`unsubscribe failed, tracks is invalid -> roomId: ${d}`),t.logger.warn(s.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`unsubscribe -> roomId: ${d}, tracks: ${r.map(St)}`);const u=this.getSubscribedList(i).map((e=>Object.assign({},e))).filter((e=>!r.includes(e.track)));if(i.polarisReport.sendR2(Xt.SUBSCRIBE,er.END,r.map((e=>e.getTrackId()))),t.logger.info(s.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:r.map(St),roomId:d},{logSource:t.LogSource.RTC}),this.state===Wt.TAIL){const{code:t}=yield new Br(this.tracks,this.subhook,this.callbacks,Wt.MIDDLE).execute(i,a);if(t===e.RCRTCCode.SUCCESS){const e=i.getCollectSubscribeList().slice(0).map((e=>e.track));return new xr(e,this.subhook,this.callbacks).execute(i,a)}return{code:t}}return hr.AsyncUnsubscribeTasks.splice(hr.AsyncUnsubscribeTasks.length,0,...this.tracks),new Promise((t=>{i.resetCollectSubscribeList(u),t({code:e.RCRTCCode.SUCCESS})}))}))}getSubscribedList(e){return this.state===Wt.MIDDLE?e.getCollectSubscribeList():e.getSubscribedList()}}e.RCKickReason=void 0,(or=e.RCKickReason||(e.RCKickReason={}))[or.SERVER_KICK=1]="SERVER_KICK",or[or.OTHER_KICK=2]="OTHER_KICK";const Vr={[e.RCKickReason.SERVER_KICK]:1,[e.RCKickReason.OTHER_KICK]:5},$r="evt-leave";class Fr extends t.EventEmitter{constructor(e,t,r,o,i,s,n,a,c,d=Lt()){super(),this._context=e,this._runtime=t,this._roomId=r,this._service=i,this._initOptions=s,this._useMutilPeerC=c,this._clientSessionId=d,this._appListener=null,this._reportListener=null,this._onRecvPKMsg=null,this._polarisReport=new _r(this._context,this._runtime,this._roomId,this),this._peerCManager=new Rr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._invoker=new pr(this._context,this._service,this._peerCManager,r,this._context.getCurrentId(),o,this._polarisReport,n,a),this._store=this._invoker.store}__innerInit(t,o,i,s,n){return r(this,void 0,void 0,(function*(){const{code:r,data:a}=yield this._invoker.push(new mr(this._roomId,t,o,i,s,n));return r!==e.RCRTCCode.SUCCESS?{code:r}:(this._initWithRoomData(a.offlineKickTime),{code:r,data:a})}))}_initWithRoomData(e){var t;this._pinger=new Et(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,r,i){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."),t.assert("max",e,(e=>t.isNumber(e)&&e>Math.max(r||1,200)),!0),t.assert("min",r,(r=>t.isNumber(r)&&r>=1&&(!t.isNumber(e)||r<e)),!0),t.assert("start",i,(o=>t.isNumber(o)&&o>r&&o<=e));this._peerCManager.getPCList().forEach((t=>{t.setBitrate(e,r,i)}))}_onTrackReady(r){const i=r.streams[0].id,{track:n}=r.receiver,a=[i,"audio"===n.kind?e.RCMediaType.AUDIO_ONLY:e.RCMediaType.VIDEO_ONLY].join("_"),c=this._store.getRemoteTrack(a);if(!c)return void o.warn(`cannot found remote track ${n.id}`);c.__innerSetMediaStreamTrack(n);const d=At.getMemo();t.logger.info(s.L_QS_TRACK_READY_O,{identify:d.qualityStatusId},{logSource:t.LogSource.RTC}),this._callAppListener("onTrackReady",c)}_callAppListener(e,...r){var i;"onPing"!==e&&t.logger.info(s.L_ABSTRACT_ROOM_CALL_APP_LISTENER_O,{status:n.SUCCESSED,eventType:e,attrs:r},{logSource:t.LogSource.RTC}),"onPing"!==e&&o.info(`${e} callback ->`,...r);const a=null===(i=this._appListener)||void 0===i?void 0:i[e];if(a)try{a(...r)}catch(e){o.error(e)}}_onTrackUnpublish(e){this._callAppListener("onTrackUnpublish",e)}__parseInnerMessage(e){var r;const{targetId:i,conversationType:a}=e;if(i!==this._roomId)return t.logger.warn(s.L_RTC_CLIENT_MESSAGE_O,{status:n.FAILED,message:`roomId is different, msg roomId-> ${i}, this._roomId-> ${this._roomId} `},{logSource:t.LogSource.RTC}),!0;o.info(`recv inner msg -> message: ${JSON.stringify(e)} | roomid: ${this._roomId}`);const{content:c}=e,d=At.getMemo();switch(e.messageType){case Tt.KICK:this._kickoff(!0,c);break;case Tt.STATE:this._stateHandle(c);break;case Tt.MODIFY:case Tt.PUBLISH:case Tt.UNPUBLISH:case Tt.TOTAL_CONTENT_RESOURCE:if(!d.messageData){d.messageData={sentTime:e.sentTime,senderUserId:e.senderUserId};const o=Date.now(),n={dur:o-e.sentTime,puid:e.senderUserId,rid:i,csnid:null===(r=d.clientData)||void 0===r?void 0:r.clientSessionId,snid:this.getSessionId(),time:o,cr:"unknown",net:"unknown",uid:this.getCrtUserId()},a=JSON.stringify(n);t.reportLog(t.LogLevel.STATISTICS,s.L_QS_RECV_PUB_MSG_S,a,t.LogSource.RTC)}this._resourceHandle(c,e.messageType,e.senderUserId);break;case Tt.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",e.messageType,e.content);break;case Tt.USER_NOTIFY:o.warn(`TODO: ${Tt.USER_NOTIFY}`);break;case Tt.PK_INVITE:case Tt.PK_CANCEL_INVITE:case Tt.PK_INVITE_TIMEOUT:case Tt.PK_INVITE_ANSWER:case Tt.PK_END:this._onRecvPKMsg&&this._onRecvPKMsg(e);break;case Tt.OTHER_ROOM_OFFLINE:break;default:this._callAppListener("onMessageReceive",e.messageType,c,e.senderUserId,e.messageUId)}return!0}_kickoff(e,i){return r(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;let r,n;if(o.warn(`onKickOff -> byServer: ${e}`),this.emit($r),this._leaveHandle(!e),e){((null==i?void 0:i.users)||[]).forEach((e=>{e.userId===this._context.getCurrentId()&&(n=e.type,r=e.kickExtra)}));const e=Date.now(),o=JSON.stringify({cod:Vr[n||1],rid:this._roomId,csnid:this.getClientSessionId(),snid:this.getSessionId(),time:e,cr:"unknown",net:"unknown",uid:this.getCrtUserId()});t.reportLog(t.LogLevel.STATISTICS,s.L_QS_KICKED_S,o,t.LogSource.RTC)}this._callAppListener("onKickOff",e,n,r)}))}_rtcpeerClosed(){this.emit($r),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,t,o){return r(this,void 0,void 0,(function*(){const{uris:r,ignore:i}=e;!i&&r&&this._invoker.push(new Nr(e,t,o,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(t){var o;return r(this,void 0,void 0,(function*(){const{left:r,joined:i,upgrade:s,downgrade:n}=yield this._invoker.push(new Ar(t,this._subhook.bind(this)));if(null===(o=this._appListener)||void 0===o?void 0:o.onSwitchRole)return s.length&&s.forEach((t=>this._callAppListener("onSwitchRole",t,e.RCRTCLiveRole.ANCHOR))),n.length&&n.forEach((t=>this._callAppListener("onSwitchRole",t,e.RCRTCLiveRole.AUDIENCE))),i.length&&this._callAppListener("onUserJoin",i),void(r.length&&this._callAppListener("onUserLeave",r));const a=[...i,...s],c=[...r,...n];a.length&&this._callAppListener("onUserJoin",a),c.length&&this._callAppListener("onUserLeave",c)}))}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(i,a){return r(this,void 0,void 0,(function*(){t.logger.info(s.L_ABSTRACT_ROOM_SEND_MESSAGE_T,{name:i,content:a},{logSource:t.LogSource.RTC});const{code:r}=yield this._context.sendMessage(t.ConversationType.RTC_ROOM,this._roomId,{messageType:i,content:a,isStatusMessage:!0});return r!==t.ErrorCode.SUCCESS?(o.error(`send message failed -> code: ${r}`),t.logger.error(s.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:n.FAILED,code:r,msg:""},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_ERROR}):(t.logger.info(s.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:n.SUCCESSED,name:i,content:a},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS})}))}setRoomAttribute(i,a,c,d=!1){return r(this,void 0,void 0,(function*(){t.logger.info(s.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_T,{roomId:this._roomId,key:i,value:a,message:c,isInner:d},{logSource:t.LogSource.RTC});const r=yield this._context.setRTCData(this._roomId,i,a,d,rr.ROOM,c);return r!==t.ErrorCode.SUCCESS?(o.error(`SetRoomAttributeValue Failed: ${r}`),t.logger.error(s.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:n.FAILED,code:r,msg:""},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_ERROR}):(t.logger.info(s.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:n.SUCCESSED,roomId:this._roomId,key:i,value:a,message:c,isInner:d},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS})}))}deleteRoomAttributes(i,a,c=!1){return r(this,void 0,void 0,(function*(){t.logger.info(s.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_T,{roomId:this._roomId,keys:i,message:a,isInner:c},{logSource:t.LogSource.RTC});const r=yield this._context.removeRTCData(this._roomId,i,c,rr.ROOM,a);return r!==t.ErrorCode.SUCCESS?(o.error(`DeleteRoomAttribute Failed: ${r}`),t.logger.error(s.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:n.FAILED,code:r,msg:""},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_ERROR}):(t.logger.info(s.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:n.SUCCESSED,roomId:this._roomId,keys:i,message:a,isInner:c},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS})}))}getRoomAttributes(i=[],s=!1){return r(this,void 0,void 0,(function*(){const{code:r,data:n}=yield this._context.getRTCData(this._roomId,i,s,rr.ROOM);return r!==t.ErrorCode.SUCCESS?(o.error(`GetRoomAttributes Failed: ${r}`),{code:e.RCRTCCode.SIGNAL_ERROR}):{code:e.RCRTCCode.SUCCESS,data:n}}))}_setUserAttributeValue(e,t,r){return this._context.setRTCData(this._roomId,e,t,!1,rr.PERSON,r)}_deleteUserAttributes(e,t){return this._context.removeRTCData(this._roomId,e,!1,rr.PERSON,t)}_getUserAttributes(e){return this._context.getRTCData(this._roomId,e,!1,rr.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 r(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;At.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(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Me.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)})),this._peerCManager.clear(),this._peerCManager=null}_onLocalTrackDestroied(e){e instanceof we&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(e,t){return r(this,void 0,void 0,(function*(){this._invoker.push(new Ur(e,t))}))}publish(e){return r(this,void 0,void 0,(function*(){return this._invoker.push(new br(e,this._pubhook.bind(this)))}))}_getPushOtherRoomsParams(){return[]}_reTryExchange(e,t){return r(this,void 0,void 0,(function*(){this._invoker.push(new Pr(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 r(this,void 0,void 0,(function*(){return this._invoker.push(new kr(e,((e,t)=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(t)}))))}))}_getResourceById(e){return this._store.getPublishedResourceByTrackId(e)}_isValidResourceId(e){var t;const{userId:r}=rt(e);return!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>tt(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(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.on(Me.__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 r(this,void 0,void 0,(function*(){return this._invoker.push(new yr(e,this._subhook.bind(this)))}))}addSubscribeTask(e){this._invoker.push(new wr(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}unsubscribe(e){return r(this,void 0,void 0,(function*(){return this._invoker.push(new Or(e,this._subhook.bind(this)))}))}addUnsubscribeTask(e){this._invoker.push(new Br(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}updateSubList(e){return r(this,void 0,void 0,(function*(){return this._invoker.push(new vr(e,this._subhook.bind(this)))}))}addUpdateSubscribeListTask(e){this._invoker.push(new xr(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){t.logger.info(s.L_ABSTRACT_ROOM_REGISTER_ROOM_EVENT_LISTENER_O,{status:n.SUCCESSED,listener:e&&Object.keys(e)},{logSource:t.LogSource.RTC}),this._appListener=e}registerReportListener(e){t.logger.info(s.L_ABSTRACT_ROOM_REGISTER_REPORT_LISTENER_O,{status:n.SUCCESSED,listener:e&&Object.keys(e)},{logSource:t.LogSource.RTC}),this._reportListener=e}onAudioLevelChange(e,r){var o;t.logger.info(s.L_ABSTRACT_ROOM_AUDIO_LEVEL_O,{status:n.SUCCESSED,handler:null==e?void 0:e.name,gap:r},{logSource:t.LogSource.RTC}),null===(o=this._audioLevelReport)||void 0===o||o.clearAudioLevelReportTimer(),this._audioLevelReport=new lr(this),this._audioLevelReport.onAudioLevelChange(e,r||1e3)}__onReconnected(e){return r(this,void 0,void 0,(function*(){return this._invoker.push(new Mr(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 Gr extends Cr{constructor(e,t){super(),this.data=e,this.cdnValues=t}execute(t,i){var s,n,a,c;return r(this,void 0,void 0,(function*(){const r={"App-Key":t.context.getAppkey(),Token:t.getToken(),RoomId:t.roomId,UserId:t.context.getCurrentId(),SessionId:t.getSessionId()},{code:i,res:d}=yield t.service.setMcuConfig(r,this.data);if(i!==e.RCRTCCode.SUCCESS)return o.error(`set MCU config failed: ${i}`),{code:i};o.info("set MCU config success"),d.pull_url&&t.setCDNUris(JSON.parse(d.pull_url));const u=this.cdnValues;return i===e.RCRTCCode.SUCCESS&&((null===(n=null===(s=u.output)||void 0===s?void 0:s.video.normal)||void 0===n?void 0:n.width)||(null===(c=null===(a=u.output)||void 0===a?void 0:a.video.normal)||void 0===c?void 0:c.fps))&&fr(t),{code:i,res:d}}))}}var Kr,Hr,jr,Jr;e.BackgroundPictureFillMode=void 0,(Kr=e.BackgroundPictureFillMode||(e.BackgroundPictureFillMode={}))[Kr.CROP=1]="CROP",Kr[Kr.WHOLE=2]="WHOLE",e.MixLayoutMode=void 0,(Hr=e.MixLayoutMode||(e.MixLayoutMode={}))[Hr.CUSTOMIZE=1]="CUSTOMIZE",Hr[Hr.SUSPENSION=2]="SUSPENSION",Hr[Hr.ADAPTATION=3]="ADAPTATION",e.MixVideoRenderMode=void 0,(jr=e.MixVideoRenderMode||(e.MixVideoRenderMode={}))[jr.CROP=1]="CROP",jr[jr.WHOLE=2]="WHOLE",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"}(Jr||(Jr={}));const qr=()=>({version:2,mode:e.MixLayoutMode.SUSPENSION});class Wr{constructor(e,t){this._invoker=e,this._isValidTrackId=t,this._values=qr()}setHostVideoTrack(r){if(o.info(`setHostVideoTrack -> videoTrackId: ${r}`),!this._isValidTrackId(r))return o.error(`setHostVideoTrack failed -> videoTrackId is invalid: ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:n.FAILED,code:"",msg:"params error -> videoTrackId"},{logSource:t.LogSource.RTC}),this;const{mediaType:i,tag:a,userId:c}=rt(r);return i!==e.RCMediaType.VIDEO_ONLY?(o.error(`setHostVideoTrack failed -> kind of resource is not 'video' -> ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:n.FAILED,code:"",msg:"not video"},{logSource:t.LogSource.RTC}),this):(this._values.host_stream_id=ot(c,a),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:n.SUCCESSED,videoTrackId:r},{logSource:t.LogSource.RTC}),this)}setMixLayoutMode(r){o.info(`setMixLayoutMode -> mode: ${r}`);return[e.MixLayoutMode.CUSTOMIZE,e.MixLayoutMode.SUSPENSION,e.MixLayoutMode.ADAPTATION].includes(r)?(this._values.mode=r,t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:n.SUCCESSED,mode:r},{logSource:t.LogSource.RTC}),this):(o.error(`setMixLayoutMode failed -> mode is invalid: ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:n.SUCCESSED,code:"",msg:`params error -> mode: ${r}`},{logSource:t.LogSource.RTC}),this)}_addOutputValue(t,r,o="normal"){const i=this._values.output||(this._values.output={video:{normal:{width:640,height:480}}});if("cdn"===t)return void(i.cdn=r);if("audio"===t)return void(i.audio={bitrate:r});const{video:s}=i;if("normal"!==o&&"tiny"!==o)if("backgroundColor"!==o)if("exparams"!==o){if("backgroundPicture"===o){const t=s.backgroundPicture||(s.backgroundPicture={fillMode:e.BackgroundPictureFillMode.CROP,picture:[]});Object.assign(t,r)}}else s.exparams={renderMode:r};else s.backgroundColor=r;else{const e=s[o]||(s[o]={});Object.assign(e,r)}}setOutputVideoResolution(e){if(o.info(`setOutputVideoResolution -> resolution: ${e}`),!ct(e))return o.error(`setOutputVideoResolution failed -> resolution is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:n.FAILED,code:"",msg:`params error -> resolution: ${e}`},{logSource:t.LogSource.RTC}),this;const{width:r,height:i}=at(e);return this._addOutputValue("video",{width:r,height:i},"normal"),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:n.SUCCESSED,resolution:e},{logSource:t.LogSource.RTC}),this}setOutputVideoFPS(e){if(o.info(`setOutputVideoFPS -> fps: ${e}`),!dt(e))return o.error(`setOutputVideoFPS failed -> fps is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:n.FAILED,code:"",msg:`params error -> fps: ${e}`},{logSource:t.LogSource.RTC}),this;const r=ut(e);return this._addOutputValue("video",{fps:r},"normal"),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:n.SUCCESSED,fps:e},{logSource:t.LogSource.RTC}),this}setOutputVideoBitrate(e){return o.info(`setOutputVideoBitrate -> bitrate: ${e}`),!t.isNumber(e)||e<=0?(o.error(`setOutputVideoBitrate failed -> bitrate is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:n.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:t.LogSource.RTC})):this._addOutputValue("video",{bitrate:e},"normal"),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:n.SUCCESSED,bitrate:e},{logSource:t.LogSource.RTC}),this}setOutputTinyVideoResolution(e){if(o.info(`setOutputTinyVideoResolution -> resolution: ${e}`),!ct(e))return o.error(`setOutputTinyVideoResolution failed -> resolution is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:n.FAILED,code:"",msg:`params error -> resolution: ${e}`},{logSource:t.LogSource.RTC}),this;const{width:r,height:i}=at(e);return this._addOutputValue("video",{width:r,height:i},"tiny"),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:n.SUCCESSED,resolution:e},{logSource:t.LogSource.RTC}),this}setOutputTinyVideoFPS(e){if(o.info(`setOutputTinyVideoFPS -> fps: ${e}`),!dt(e))return o.error(`setOutputTinyVideoFPS failed -> fps is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:n.FAILED,code:"",msg:`params error -> fps: ${e}`},{logSource:t.LogSource.RTC}),this;const r=ut(e);return this._addOutputValue("video",{fps:r},"tiny"),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:n.SUCCESSED,fps:e},{logSource:t.LogSource.RTC}),this}setOutputTinyVideoBitrate(e){return o.info(`setOutputTinyVideoBitrate -> bitrate: ${e}`),!t.isNumber(e)||e<=0?(o.error(`setOutputTinyVideoBitrate failed -> bitrate is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:n.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:t.LogSource.RTC})):this._addOutputValue("video",{bitrate:e},"tiny"),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:n.SUCCESSED,bitrate:e},{logSource:t.LogSource.RTC}),this}setOutputVideoRenderMode(r){return o.info(`setOutputVideoRenderMode -> renderMode: ${r}`),[e.MixVideoRenderMode.CROP,e.MixVideoRenderMode.WHOLE].includes(r)?this._addOutputValue("video",r,"exparams"):(o.error(`setOutputVideoRenderMode failed -> renderMode is invalid: ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:n.FAILED,code:"",msg:`params error -> renderMode: ${r}`},{logSource:t.LogSource.RTC})),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:n.SUCCESSED,renderMode:r},{logSource:t.LogSource.RTC}),this}setOutputAudioBitrate(e){return o.info(`setOutputAudioBitrate -> bitrate: ${e}`),t.isNumber(e)&&e>0?this._addOutputValue("audio",e):(o.error(`setOutputAudioBitrate failed -> bitrate is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:n.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:t.LogSource.RTC})),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:n.SUCCESSED,bitrate:e},{logSource:t.LogSource.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}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:n.FAILED,code:"",msg:`params error -> color: ${e}`},{logSource:t.LogSource.RTC})),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:n.SUCCESSED,color:e},{logSource:t.LogSource.RTC}),this}addOutputBackgroundPicture(e,r,i,a,c){var d,u,_;if(o.info(`addOutputBackgroundPicture -> uri: ${e}, x: ${r}, y: ${i}, w: ${a}, h: ${c}`),!t.isHttpUrl(e))return o.error(`addOutputBackgroundPicture failed -> uri is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:n.FAILED,code:"",msg:`params error -> uri: ${e}`},{logSource:t.LogSource.RTC}),this;if([r,i,a,c].some((e=>!t.isNumber(e)||e<0||e>1)))return o.error(`addOutputBackgroundPicture failed -> some attrs of (x, y, w, h) is invalid: ${r}, ${i}, ${a}, ${c}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:n.FAILED,code:"",msg:`params error -> x: ${r}, y: ${i}, w: ${a}, h: ${c}`},{logSource:t.LogSource.RTC}),this;const l=(null===(_=null===(u=null===(d=this._values.output)||void 0===d?void 0:d.video)||void 0===u?void 0:u.backgroundPicture)||void 0===_?void 0:_.picture)||[];return l.push({uri:e,w:a,h:c,x:r,y:i}),this._addOutputValue("video",{picture:l},"backgroundPicture"),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:n.SUCCESSED,uri:e,x:r,y:i,w:a,h:c},{logSource:t.LogSource.RTC}),this}removeOutputBackgroundPicture(e){var r,i,a;if(o.info(`removeOutputBackgroundPicture -> uri: ${e}`),!t.isHttpUrl(e))return o.error(`removeOutputBackgroundPicture failed -> uri is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:n.FAILED,code:"",msg:`params error -> uri: ${e}`},{logSource:t.LogSource.RTC}),this;let c=null===(a=null===(i=null===(r=this._values.output)||void 0===r?void 0:r.video)||void 0===i?void 0:i.backgroundPicture)||void 0===a?void 0:a.picture;return c&&(c=c.filter((t=>t.uri!==e)),this._addOutputValue("video",{pictures:c},"backgroundPicture")),t.logger.info(s.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:n.SUCCESSED,uri:e},{logSource:t.LogSource.RTC}),this}clearOutputBackgroundPicture(){return o.info("clearOutputBackgroundPicture ->"),this._addOutputValue("video",{pictures:[]},"backgroundPicture"),t.logger.info(s.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),this}setOutputBackgroundPictureFillMode(r){return o.info(`setOutputBackgroundPictureFillMode -> fillMode: ${r}`),[e.BackgroundPictureFillMode.CROP,e.BackgroundPictureFillMode.WHOLE].includes(r)?this._addOutputValue("video",{fillMode:r},"backgroundPicture"):(o.error(`setOutputBackgroundPictureFillMode failed -> fillMode is invalid: ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:n.FAILED,code:"",msg:`params error -> fillMode: ${r}`},{logSource:t.LogSource.RTC})),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:n.SUCCESSED,fillMode:r},{logSource:t.LogSource.RTC}),this}addPublishStreamUrls(e){var r,i;o.info(`addPublishStreamUrls -> urls: ${e.join(",")}`);const a=/^rtmp:\/\/.+/;if(!t.isArray(e)||0===e.length||e.some((e=>!a.test(e))))return o.error(`addPublishStreamUrls failed -> urls is invalid: ${e.join(",")}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:n.FAILED,code:"",msg:`params error -> urls: ${e.join(",")}`},{logSource:t.LogSource.RTC}),this;const c=(null===(i=null===(r=this._values.output)||void 0===r?void 0:r.cdn)||void 0===i?void 0:i.concat())||[];let d=!1;return e.forEach((e=>{c.some((t=>t.pushurl===e))||(d=!0,c.push({pushurl:e}))})),c.length>5?(o.error("addPublishStreamUrls failed -> publish stream urls no more than 5!"),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:n.FAILED,code:"",msg:`params error -> publish stream urls no more than 5, length: ${e.length}`},{logSource:t.LogSource.RTC}),this):(d&&this._addOutputValue("cdn",c),t.logger.info(s.L_MCU_CONFIG_BUILDER_ADD_PUBLISH_STREAM_URLS_O,{status:n.SUCCESSED,urls:e},{logSource:t.LogSource.RTC}),this)}removePublishStreamUrls(e){var r,i;o.info(`removePublishStreamUrls -> urls: ${e.join(",")}`);const a=/^rtmp:\/\/.+/;if(!t.isArray(e)||0===e.length||e.some((e=>!a.test(e))))return o.error(`removePublishStreamUrls failed -> urls contain invalid items: ${e.join(",")}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:n.FAILED,code:"",msg:`params error -> urls: ${e.join(",")}`},{logSource:t.LogSource.RTC}),this;const c=(null===(i=null===(r=this._values.output)||void 0===r?void 0:r.cdn)||void 0===i?void 0:i.concat())||[];for(let t=c.length-1;t>=0;t-=1){const{pushurl:r}=c[t],o=e.indexOf(r);o>=0&&(e.splice(o,1),c.splice(t,1))}return this._addOutputValue("cdn",c),t.logger.info(s.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:n.SUCCESSED,urls:e},{logSource:t.LogSource.RTC}),this}clearPublishStreamUrls(){return o.info("clearPublishStreamUrls ->"),this._addOutputValue("cdn",[]),t.logger.info(s.L_MCU_CONFIG_BUILDER_CLEAR_PUBLISH_STREAM_URLS_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),this}addCustomizeLayoutVideo(r,i,a,c,d){if(o.info(`addCustomizeLayoutVideo -> trackId: ${r}, x: ${i}, y: ${a}, width: ${c}, height: ${d}`),!t.notEmptyString(r)||!this._isValidTrackId(r))return o.error(`addCustomizeLayoutVideo failed -> trackId is invalid: ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${r}`},{logSource:t.LogSource.RTC}),this;if(!t.isNumber(i)||!t.isNumber(a))return o.error(`addCustomizeLayoutVideo failed -> some attrs of (x, y) is invalid: ${i}, ${a}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.FAILED,code:"",msg:`params error -> x: ${i}, y: ${a}`},{logSource:t.LogSource.RTC}),this;if([c,d].some((e=>!t.isNumber(e)||e<0)))return o.error(`addCustomizeLayoutVideo failed -> some attrs of (width, height) is invalid: ${c}, ${d}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.FAILED,code:"",msg:`params error -> width: ${c}, height: ${d}`},{logSource:t.LogSource.RTC}),this;const{userId:u,tag:_,mediaType:l}=rt(r);if(l!==e.RCMediaType.VIDEO_ONLY)return o.error(`addCustomizeLayoutVideo failed -> kind of trackId is not 'video': ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${r}的资源不是视频`},{logSource:t.LogSource.RTC}),this;const R=ot(u,_),C=this._values.input||(this._values.input={}),h=C.video||(C.video=[]);return h.some((e=>e.height===d&&e.width===c&&e.stream_id===R&&e.user_id===u&&e.x===i&&e.y===a))?(t.logger.warn(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.FAILED,code:"",msg:"Duplicate configuration item ignored"},{logSource:t.LogSource.RTC}),this):(h.push({user_id:u,stream_id:R,x:i,y:a,width:c,height:d}),t.logger.info(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.SUCCESSED,trackId:r,x:i,y:a,width:c,height:d},{logSource:t.LogSource.RTC}),this)}removeCustomizeLayoutVideo(r){if(o.info(`clearCustomizeInputAudio -> trackId: ${r}`),!this._isValidTrackId(r))return o.error(`clearCustomizeInputAudio failed -> trackId is invalid: ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${r}`},{logSource:t.LogSource.RTC}),this;const{userId:i,tag:a,mediaType:c}=rt(r);if(c!==e.RCMediaType.VIDEO_ONLY)return o.error(`clearCustomizeInputAudio failed -> kind of trackId is not 'video': ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${r}的资源不是视频`},{logSource:t.LogSource.RTC}),this;const d=ot(i,a),{input:u}=this._values;return(null==u?void 0:u.video)&&u.video.length>0&&(u.video=u.video.filter((e=>e.stream_id===d))),t.logger.info(s.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.SUCCESSED,trackId:r},{logSource:t.LogSource.RTC}),this}clearCustomizeLayoutVideo(){o.info("clearCustomizeLayoutVideo ->");const{input:e}=this._values;return null==e||delete e.video,t.logger.info(s.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_LAYOUT_VIDEO_O,{status:n.SUCCESSED},{logSource:t.LogSource.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(",")}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:n.FAILED,code:"",msg:`params error -> trackIds: ${e.join(",")}`},{logSource:t.LogSource.RTC}),this;return(this._values.input||(this._values.input={})).audio=e.map((e=>{const{userId:t,tag:r}=rt(e);return{stream_id:ot(t,r),user_id:t}})),this._values.inputFilterMode=Jr.AUDIO_INPUT_VIDEO_ALL,t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:n.SUCCESSED,trackIds:e},{logSource:t.LogSource.RTC}),this}addCustomizeInputAudio(e){if(o.info(`addCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return o.warn(`addCustomizeInputAudio failed -> trackId is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:t.LogSource.RTC}),this;const r=this._values.input||(this._values.input={}),i=r.audio||(r.audio=[]),{userId:a,tag:c}=rt(e),d=ot(a,c);return i.some((e=>e.stream_id===d&&e.user_id===a))?(t.logger.warn(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:n.FAILED,code:"",msg:`trackId:${e} is exist`},{logSource:t.LogSource.RTC}),this):(i.push({user_id:a,stream_id:d}),this._values.inputFilterMode=Jr.AUDIO_INPUT_VIDEO_ALL,t.logger.info(s.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:n.SUCCESSED,trackId:e},{logSource:t.LogSource.RTC}),this)}removeCustomizeInputAudio(e){if(o.info(`removeCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return o.error(`removeCustomizeInputAudio failed -> trackId is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:t.LogSource.RTC}),this;const{input:r}=this._values;if(!(null==r?void 0:r.audio)||0===r.audio.length)return t.logger.error(s.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:n.FAILED,code:"",msg:"not audio"},{logSource:t.LogSource.RTC}),this;const{userId:i,tag:a}=rt(e),c=ot(i,a);return r.audio=r.audio.filter((e=>i!==e.user_id||c!==e.stream_id)),t.logger.info(s.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:n.SUCCESSED,trackId:e},{logSource:t.LogSource.RTC}),this}clearCustomizeInputAudio(){o.info("clearCustomizeInputAudio ->");const{input:e}=this._values;return(null==e?void 0:e.audio)&&delete e.audio,this._values.inputFilterMode=Jr.AUDIO_VIDEO_ALL,t.logger.info(s.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_INPUT_AUDIO_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),this}addPictureWaterMark(e,r,i,a,c,d){if(o.info(`addPictureWaterMark -> trackId: ${e} uri: ${r}, x: ${i}, y: ${a}, w: ${c}, h: ${d}`),!this._isValidTrackId(e))return o.warn(`addPictureWaterMark failed -> trackId is invalid: ${e}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:t.LogSource.RTC}),this;if(!t.isHttpUrl(r))return o.error(`addPictureWaterMark failed -> uri is invalid: ${r}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:n.FAILED,code:"",msg:`params error -> uri: ${r}`},{logSource:t.LogSource.RTC}),this;if([i,a,c,d].some((e=>!t.isNumber(e)||e<0||e>1)))return o.error(`addPictureWaterMark failed -> some attrs of (x, y, w, h) is invalid: ${i}, ${a}, ${c}, ${d}`),t.logger.error(s.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:n.FAILED,code:"",msg:`params error -> x: ${i}, y: ${a}, w: ${c}, h: ${d}`},{logSource:t.LogSource.RTC}),this;const{userId:u,tag:_}=rt(e),l=ot(u,_),R=this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]}),{singleScreen:C}=R;o.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(C)}`);const h=C.filter((e=>e.streamId===l))[0];return o.info(`addPictureWaterMark target-> : ${h}`),h?h.picture.push({uri:r,w:c,h:d,x:i,y:a}):C.push({streamId:l,picture:[{uri:r,w:c,h:d,x:i,y:a}]}),o.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(C)}`),this._values.waterMark.singleScreen=C,o.info(`addPictureWaterMark this._values.waterMark.singleScreen-> : ${JSON.stringify(this._values.waterMark.singleScreen)}`),t.logger.info(s.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:n.SUCCESSED,trackId:e,uri:r,x:i,y:a,w:c,h:d},{logSource:t.LogSource.RTC}),this}clearPictureWaterMark(){o.info("clearOutputBackgroundPicture ->");return(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen=[],t.logger.info(s.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),this}removePictureWaterMark(e,r){if(!t.notEmptyString(e)||!this._isValidTrackId(e))return t.logger.error(s.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O,{status:n.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:t.LogSource.RTC}),this;const{userId:o,tag:i}=rt(e),a=ot(o,i),c=this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]}),{singleScreen:d}=c;return d.forEach((e=>{e.streamId===a&&(e.picture=e.picture.filter((e=>e.uri!==r)))})),t.logger.info(s.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O,{status:n.SUCCESSED,trackId:e,uri:r},{logSource:t.LogSource.RTC}),this}reset(){return o.info("MCUConfigBuilder.reset ->"),this._values=qr(),t.logger.info(s.L_MCU_CONFIG_BUILDER_RESET_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),this}flush(e=!0){return r(this,void 0,void 0,(function*(){const r=JSON.parse(JSON.stringify(this._values)),{code:o}=yield this._invoker.push(new Gr(r,this._values));return e&&(this._values=qr()),t.logger.info(s.L_MCU_CONFIG_BUILDER_FLUSH_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),{code:o}}))}__innerGetValues(){return JSON.parse(JSON.stringify(this._values))}}var Yr,Qr,zr,Zr;e.RCLivingType=void 0,(Yr=e.RCLivingType||(e.RCLivingType={}))[Yr.VIDEO=0]="VIDEO",Yr[Yr.AUDIO=1]="AUDIO",function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(Qr||(Qr={}));class Xr extends Cr{constructor(e,t,r){super(),this.roomId=e,this.hooks=t,this.roomPKHandler=r}_exchangeWithPushOtherRoom(t,i){return r(this,void 0,void 0,(function*(){if(!t.getLocalTracks().length)return;const r=Object.values(t.peerMgr.getMutilPeerCData()),s=Object.keys(t.peerMgr.getMutilPeerCData());for(let n=0;n<r.length;n++){const{pc:a,isPub:c}=r[n],d=c&&t.useMutilPeerC?[]:t.getSubscribedList(),u=yield Tr(d,!1,a,t),{pushOtherRooms:_,headers:l}=this.hooks(s[n]);u.pushOtherRooms=_;const R=yield new Lr(l,u).execute(t,i);if(R.code!==e.RCRTCCode.SUCCESS)return void o.error(`exchange with pushOtherRoom failed: ${R.code}`);const{sdp:C,resultCode:h}=R.data;if(h!==e.RCRTCCode.SUCCESS)return void o.error(`exchange with pushOtherRoom failed: ${h}`);a.setRemoteAnswer(C.sdp)}}))}execute(e,i){return r(this,void 0,void 0,(function*(){const{roomId:r}=this;if(t.logger.info(s.L_LIVING_ROOM_JOINED_PK_ROOM_T,{roomId:r,userId:e.crtUserId},{logSource:t.LogSource.RTC}),!this.roomPKHandler)return void t.logger.error(s.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:n.FAILED,code:"",msg:"_roomPKHandler not exist"},{logSource:t.LogSource.RTC});const a=this.roomPKHandler.getPKInfo(r);if(!a)return o.warn(`exchange to update pushOtherRoom cancel, pkInfo lost -> roomId: ${r}`),void t.logger.error(s.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:n.FAILED,code:"",msg:"PKInfo not exist"},{logSource:t.LogSource.RTC});yield this._exchangeWithPushOtherRoom(e,i),t.logger.info(s.L_LIVING_ROOM_JOINED_PK_ROOM_T,{status:n.SUCCESSED,roomId:r,userId:e.crtUserId,PKInfo:a},{logSource:t.LogSource.RTC})}))}}class eo extends Cr{constructor(e,t,r,o,i,s){super(),this.pkHandler=e,this.room=t,this._PKInfo=r,this.hooks=o,this._joinedPKRooms=i,this.isQuitPK=s}get kind(){return qt.LeaveRoom}quitRoomPK(i,s){return r(this,void 0,void 0,(function*(){if(!this._PKInfo[i])return;const{inviterRoomId:r,inviteeRoomId:n,inviterUserId:a,inviteSessionId:c}=this._PKInfo[i],d={inviteeRoomId:n,inviterRoomId:r,userId:s.crtUserId},u={roomId:s.roomId,endRoomId:i,sessionId:c,content:JSON.stringify(d),keys:[`${r}|${a}`]};o.info(`quitRoomPK -> params: ${JSON.stringify(u)}`);const _=yield s.context.endRoomPK(u);return _!==t.ErrorCode.SUCCESS?(o.error(`quitRoomPK failed: ${_}`),{code:e.RCRTCCode.SIGNAL_ERROR}):(o.info("quitRoomPK success"),delete this._PKInfo[i],{code:e.RCRTCCode.SUCCESS})}))}execute(i,a){return r(this,void 0,void 0,(function*(){const{room:r,isQuitPK:c}=this,d=r.getRoomId();return o.info(`leavePKRoom -> userId: ${i.crtUserId} , roomId: ${d}`),t.logger.info(s.L_LIVING_ROOM_LEAVE_PK_ROOM_T,{roomId:d,userId:i.crtUserId,isQuitPK:c},{logSource:t.LogSource.RTC}),yield r.__destroy(!0),delete this._joinedPKRooms[d],yield new Xr(d,this.hooks,this.pkHandler).execute(i,a),c&&this.quitRoomPK(d,i),t.logger.info(s.L_LIVING_ROOM_LEAVE_PK_ROOM_R,{status:n.SUCCESSED,roomId:d,userId:i.crtUserId,isQuitPK:c},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS}}))}}class to{constructor(e,t,r,o,i,s,n,a,c,d,u){this._invoker=e,this._PKInfo=t,this._hooks=r,this._context=o,this._runtime=i,this._service=s,this._initOptions=n,this._mainLivingRoom=a,this._registerPKMsgListener=c,this._onJoinedPKRoom=d,this._clientSessionId=u,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:o,extra:i}=t,s={inviterRoomId:r,inviterUserId:o,extra:i};this._PKInfo[r]=t,this._callAppListener("onRequestJoinOtherRoom",s)}_onCancelInvite(e){const{inviterRoomId:t,inviterUserId:r,extra:o}=e.inviteInfo||{},i={inviterRoomId:t,inviterUserId:r,extra:o};delete this._PKInfo[t],this._callAppListener("onCancelRequestOtherRoom",i)}_onInviteTimeout(e){}_onInviteAnswer(e){const{answerCode:t,inviteContent:r}=e,{inviteSessionId:o,inviterUserId:i,inviterRoomId:s,inviteeUserId:n,inviterUserAutoMix:a,inviteeUserAutoMix:c,inviteeRoomId:d,extra:u}=r,_={agree:1===t,inviterRoomId:s,inviterUserId:i,inviteeRoomId:d,inviteeUserId:n,extra:u};this._PKInfo[d]=this._PKInfo[d]||{inviteSessionId:o,inviterRoomId:s,inviterUserId:i,inviterUserAutoMix:a,inviteeRoomId:d},this._PKInfo[d].inviteeUserAutoMix=c,this._callAppListener("onResponseJoinOtherRoom",_)}createLeaveOtherRoomCommand(e,t){return new eo(this,e,this._PKInfo,this._hooks,this._joinedPKRooms,t)}_onPKEnd(e){return r(this,void 0,void 0,(function*(){const{inviteeRoomId:t,inviterRoomId:r,userId:o}=e.inviteInfo,i=r===this._mainRoomId?t:r,s={endRoomId:i,endUserId:o},n=this._joinedPKRooms[i];n&&(yield this._invoker.push(this.createLeaveOtherRoomCommand(n))),delete this._PKInfo[i],this._callAppListener("onFinishOtherRoom",s)}))}_onRecvPKMsg(e){const{targetId:t,content:r,messageType:o}=e;switch(o){case Tt.PK_INVITE:this._onInvite(r);break;case Tt.PK_CANCEL_INVITE:this._onCancelInvite(r);break;case Tt.PK_INVITE_TIMEOUT:this._onInviteTimeout(r);break;case Tt.PK_INVITE_ANSWER:this._onInviteAnswer(r);break;case Tt.PK_END:this._onPKEnd(r)}}registerRoomPKEventListener(e){t.logger.info(s.L_LIVING_PK_HANDLER_REGISTER_ROOM_PK_EVENT_LISTENER_O,{status:n.SUCCESSED,listener:e&&Object.keys(e)},{logSource:t.LogSource.RTC}),this._appListener=e}requestJoinOtherRoom(i,a,c){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:i,inviteeUserId:a,options:c},{logSource:t.LogSource.RTC}),!t.validate("inviteeRoomId",i,t.notEmptyString,!0)||!t.validate("inviteeUserId",a,t.notEmptyString,!0))return t.logger.error(s.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> inviteeRoomId 或 inviteeUserId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`requestRoomPK -> inviteeRoomId: ${i}; inviteeUserId: ${a}; options: ${JSON.stringify(c||{})}`);const r=Lt(),d=!t.isBoolean(null==c?void 0:c.autoMix)||(null==c?void 0:c.autoMix),u={inviteSessionId:r,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:d,inviteeRoomId:i,inviteeUserId:a,inviteeTimeoutTime:this._inviteTimeout,extra:(null==c?void 0:c.extra)||""},_={roomId:this._mainRoomId,invitedRoomId:i,invitedUserId:a,inviteTimeout:this._inviteTimeout,inviteInfo:JSON.stringify(u),inviteSessionId:r};o.info(`requestRoomPK -> params: ${JSON.stringify(_)}`);const l=yield this._context.requestRoomPK(_);return l!==t.ErrorCode.SUCCESS?(o.error(`requestRoomPK failed: ${l}`),t.logger.error(s.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:l,msg:""},{logSource:t.LogSource.RTC}),{code:l}):(o.info("requestRoomPK success"),this._PKInfo[i]={inviteSessionId:r,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:d,inviteeRoomId:i},t.logger.info(s.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{inviteeRoomId:i,inviteeUserId:a,options:c},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS})}))}cancelRequestJoinOtherRoom(i,a,c){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:i,inviteeUserId:a,extra:c,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:t.LogSource.RTC}),!t.validate("inviteeRoomId",i,t.notEmptyString,!0)||!t.validate("inviteeUserId",a,t.notEmptyString,!0))return t.logger.error(s.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> inviteeRoomId or inviteeUserId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(!this._PKInfo[i])return o.error(`The request to connect with ${a} user in room ${i} is not initiated`),t.logger.error(s.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:`The request to connect with ${a} user in room ${i} is not initiated`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`canceRequestJoinPK -> inviteeRoomId: ${i}; inviteeUserId: ${a}; extra: ${c}`);const r={inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviteeRoomId:i,inviteeUserId:a,extra:c||""},d={roomId:this._mainRoomId,invitedRoomId:i,invitedUserId:a,inviteSessionId:this._PKInfo[i].inviteSessionId,inviteInfo:JSON.stringify(r)};o.info(`canceRequestJoinPK -> params: ${JSON.stringify(d)}`);const u=yield this._context.cancelRoomPK(d);return u!==t.ErrorCode.SUCCESS?(o.error(`canceRequestJoinPK failed: ${u}`),t.logger.error(s.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:u,msg:`The request to connect with ${a} user in room ${i} is not initiated`},{logSource:t.LogSource.RTC}),{code:u}):(o.info("canceRequestJoinPK success"),t.logger.info(s.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:n.SUCCESSED,inviteeRoomId:i,inviteeUserId:a,extra:c},{logSource:t.LogSource.RTC}),delete this._PKInfo[i],{code:e.RCRTCCode.SUCCESS})}))}responseJoinOtherRoom(i,a,c,d){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_T,{inviterRoomId:i,inviterUserId:a,agree:c,options:d,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:t.LogSource.RTC}),!t.validate("inviterRoomId",i,t.notEmptyString,!0)||!t.validate("inviterUserId",a,t.notEmptyString,!0))return t.logger.error(s.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> inviterRoomId or inviterUserId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(!this._PKInfo[i])return o.error(`User ${a} in room ${i} did not send a request for connection`),t.logger.error(s.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:`User ${a} in room ${i} did not send a request for connection`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};o.info(`responseRoomPK -> inviterRoomId: ${i}; inviterUserId: ${a}; agree: ${c}; options: ${JSON.stringify(d||{})}`);const{inviteSessionId:r,inviterUserAutoMix:u}=this._PKInfo[i],_=!t.isBoolean(null==d?void 0:d.autoMix)||(null==d?void 0:d.autoMix),l={inviteSessionId:r,inviterRoomId:i,inviterUserId:a,inviterUserAutoMix:u,inviteeRoomId:this._mainRoomId,inviteeUserId:this._context.getCurrentId(),inviteeUserAutoMix:_},R=Object.assign(l,{inviterUserAutoMix:u}),C=c?Object.assign(l,{MultiRoomKey:`${i}|${this._mainRoomId}`,MultiRoomValue:JSON.stringify(R)}):l;!t.isUndefined(null==d?void 0:d.extra)&&Object.assign(C,{extra:d.extra});const h={agree:c,roomId:this._mainRoomId,inviteSessionId:r,inviteRoomId:i,inviteUserId:a,content:JSON.stringify(C),key:`${i}|${this._mainRoomId}`,value:JSON.stringify(l)};o.info(`responseRoomPK -> params: ${JSON.stringify(h)}`);const g=yield this._context.responseRoomPK(h);return g!==t.ErrorCode.SUCCESS?(o.error(`responseRoomPK failed: ${g}`),t.logger.error(s.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:g,msg:""},{logSource:t.LogSource.RTC}),{code:g}):(o.info("responseRoomPK success"),t.logger.info(s.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:n.SUCCESSED,inviterRoomId:i,inviterUserId:a,agree:c,options:d,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:t.LogSource.RTC}),this._PKInfo[i].inviteeUserAutoMix=_,{code:e.RCRTCCode.SUCCESS})}))}joinOtherRoom(i){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_T,{roomId:i,userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),!t.validate("roomId",i,t.notEmptyString,!0))return t.logger.error(s.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(this._context.getConnectionStatus()!==t.ConnectionStatus.CONNECTED)return t.logger.error(s.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.SIGNAL_DISCONNECTED,msg:"IM disconnected"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_DISCONNECTED};if(o.info(`JoinPKRoom, roomId: ${i}`),this._joinedPKRooms[i])return t.logger.warn(s.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REPERT_JOIN_ROOM};const r=e.RCLivingType.VIDEO,a={extra:`{"roomId": "${this._mainRoomId}"}`},c=new io(this._context,this._runtime,i,this._service,this._initOptions,r,!1,!1,!1,this._clientSessionId),{code:d,data:u}=yield c.__innerInit(zt.LIVE,void 0,r,a);return d!==e.RCRTCCode.SUCCESS?(o.error(`JoinPKRoom failed -> code: ${d}`),t.logger.error(s.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:n.FAILED,code:d,msg:""},{logSource:t.LogSource.RTC}),{code:d}):(o.info(`JoinPKRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${i}, data: ${JSON.stringify(u)}`),this._joinedPKRooms[i]=c,yield this._onJoinedPKRoom(i,c),t.logger.info(s.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:n.SUCCESSED,roomId:i,userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),{room:c,code:e.RCRTCCode.SUCCESS,userIds:c.getRemoteUserIds(),tracks:c.getRemoteTracks()})}))}leaveOtherRoom(e,t){return r(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"}(zr||(zr={}));class ro extends Cr{constructor(e,t){super(),this.cdnValues=e,this.enable=t}execute(i,a){return r(this,void 0,void 0,(function*(){const{enable:r}=this;if(t.logger.info(s.L_LIVING_ROOM_ENABLE_INNER_CDN_T,{roomId:i.roomId,enable:r},{logSource:t.LogSource.RTC}),!i.isMainRoom)return o.error("the `enableInnerCDN` is disabled in PK room"),t.logger.error(s.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:n.FAILED,code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!t.isBoolean(r))return o.error("`enable` is invalid"),t.logger.error(s.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> enable"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};i.setCDNEnabel(r);const c={version:2,output:{inCDNModel:r?zr.OPEN:zr.STOP}},{code:d}=yield new Gr(c,this.cdnValues).execute(i,a);if(d!==e.RCRTCCode.SUCCESS)return o.error(`enableInnerCDN failed -> code: ${d}`),t.logger.error(s.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:n.FAILED,code:d,msg:"signal error"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_ERROR};const u=i.getCDNUris();if(u&&u.broadcast!==tr.SPREAD)return o.info("enableInnerCDN succeed"),t.logger.info(s.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:n.SUCCESSED,enable:r},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS};const{code:_}=yield fr(i);return _===e.RCRTCCode.SUCCESS?(o.info("enableInnerCDN succeed"),t.logger.info(s.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:n.SUCCESSED,enable:r},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS}):(o.error(`enableInnerCDN failed -> code: ${_}`),t.logger.error(s.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:n.FAILED,code:_,msg:""},{logSource:t.LogSource.RTC}),{code:_})}))}}!function(e){e[e.AnchorToViewer=1]="AnchorToViewer",e[e.ViewerToAnchor=2]="ViewerToAnchor"}(Zr||(Zr={}));class oo extends Cr{constructor(e){super(),this.livingType=e}execute(e,o){var i;return r(this,void 0,void 0,(function*(){const{code:r,data:s}=yield e.context.rtcIdentityChange(e.roomId,Zr.ViewerToAnchor,this.livingType);if(r!==t.ErrorCode.SUCCESS||!s)return{code:r};e.initWithRoomData(s);e.getResourcesByUserId(e.crtUserId).length>0&&o.push(new Sr);const n=null===(i=s.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===i?void 0:i.value;return n&&e.setCDNUris(JSON.parse(n)[0]),{code:r,data:s}}))}}class io extends Fr{constructor(e,t,r,o,i,s,n,a,c,d){super(e,t,r,zt.LIVE,o,i,n,a,c,d),this._livingType=s,this._mcuConfigBuilder=new Wr(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 o=JSON.parse(t.value),{inviterRoomId:i,inviteeRoomId:s}=o;r[e===i?s:i]=JSON.parse(t.value)})),r})(this._roomId,e.roomInfo);this._roomPKHandler=new to(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(o,i,a,c,d){const u=Object.create(null,{__innerInit:{get:()=>super.__innerInit}});return r(this,void 0,void 0,(function*(){if(!t.validate("livingType",a,(t=>t===e.RCLivingType.AUDIO||t===e.RCLivingType.VIDEO)))return t.logger.error(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> livingType"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};const{code:r,data:_}=yield u.__innerInit.call(this,o,i,a,c,d);return r===e.RCRTCCode.SUCCESS&&_&&this._initAfterCatchRoomData(_),{code:r,data:_}}))}__innerInitByIdentityChange(){return r(this,void 0,void 0,(function*(){const{code:e,data:r}=yield this._invoker.push(new oo(this._livingType));return e===t.ErrorCode.SUCCESS&&r&&(this._initAfterCatchRoomData(r),this._initWithRoomData(r.offlineKickTime),t.logger.info(s.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:n.SUCCESSED,roomData:r},{logSource:t.LogSource.RTC})),e}))}publish(i){const a=Object.create(null,{publish:{get:()=>super.publish}});return r(this,void 0,void 0,(function*(){return this._store.isMainRoom?a.publish.call(this,i):(o.warn("the `publish` is disabled in PK room "),t.logger.error(s.L_ABSTRACT_ROOM_PUBLISH_R,{status:n.FAILED,code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}unpublish(i){const a=Object.create(null,{unpublish:{get:()=>super.unpublish}});return r(this,void 0,void 0,(function*(){return this._store.isMainRoom?a.unpublish.call(this,i):(o.warn("the `unpublish` is disabled in PK room "),t.logger.error(s.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:n.FAILED,code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}_isValidResourceId(t){var r;const{userId:o}=rt(t),i=!!(null===(r=this._store.getResourcesByUserId(o))||void 0===r?void 0:r.find((e=>tt(e)===t)));let s=!1;const{code:n,roomPKHandler:a}=this.getRoomPKHandler();if(n!==e.RCRTCCode.SUCCESS||!a)return i;const c=a.getJoinedPKRooms(),d=[];return Object.values(c).forEach((e=>{d.push(...e.getRemoteTracks())})),s=d.some((e=>t===e.getTrackId())),i||s}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._store.isMainRoom?this._mcuConfigBuilder:(o.error("the `getMCUConfigBuilder` is disabled in PK room"),{code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}enableInnerCDN(e){return r(this,void 0,void 0,(function*(){return this._invoker.push(new ro(this._mcuConfigBuilder.__innerGetValues(),e))}))}_resourceHandle(e,t,o){const i=Object.create(null,{_resourceHandle:{get:()=>super._resourceHandle}});return r(this,void 0,void 0,(function*(){i._resourceHandle.call(this,e,t,o)}))}_afterChangedRole(e){const t=gt(e,this._roomId),r=this._context.getCurrentId(),o=Object.keys(t);setTimeout((()=>{var i;const s=o.filter((e=>e!==r));s.length>0&&this._callAppListener("onUserJoin",s);for(const e in t)e!==r&&this._resourceHandle({uris:t[e]},Tt.TOTAL_CONTENT_RESOURCE,e);if(!(null===(i=e.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===i?void 0:i.value))return;const n=this._store.getCDNUris();(null==n?void 0:n.push_mode)===Qr.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 r(this,void 0,void 0,(function*(){this._invoker.push(new Xr(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 o=t[r].getSessionId(),i=this._roomPKHandler.getPKInfo(r);if(!i)continue;const{inviterUserAutoMix:s,inviteeUserAutoMix:n,inviterUserId:a}=i,c=this._context.getCurrentId()===a;e.push({roomId:r,sessionId:o,autoMix:c?!!s:!!n})}return e}getRoomPKHandler(){return this._store.isMainRoom?(t.logger.info(s.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,roomPKHandler:this._roomPKHandler}):(o.error("the `getRoomPKHandler` is disabled in PK room"),t.logger.error(s.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:n.SUCCESSED,code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}_quitAllPKRoom(){return r(this,void 0,void 0,(function*(){const e=this._roomPKHandler.getJoinedPKRooms();for(const t in e)this._roomPKHandler.leaveOtherRoom(e[t]);t.logger.info(s.L_LIVING_ROOM_QUIT_ALL_PK_ROOM_O,{status:n.SUCCESSED,roomIds:Object.keys(e)},{logSource:t.LogSource.RTC})}))}isMainRoom(){return this._store.isMainRoom}}class so extends Fr{constructor(e,t,r,o,i,s,n,a,c,d=zt.RTC){super(e,t,r,d,o,i,s,n,a,c)}}const no=new class{constructor(){this.queue=[],this.locked=!1,this.taskCount=0}checkToStart(){return r(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 o;try{o=yield t(),e(o)}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}},ao=(e,t="")=>no.push(e,t);class co{constructor(e,t,r,o){this._context=e,this._useMutilPeerC=o,this._rtcToken="",this._liveUrl="",this._subTracks=[],this._clientSessionId=Lt(),this._livingType=null,this._mediaType=null,this._subTiny=!1,this._fromRetry=!1,this._appListener=null,this._service=new Nt(t,e,r.mediaServer),this._peerCManager=new Rr(this._useMutilPeerC,this._context.getCurrentId(),this._reTryExchange.bind(this),this._context.getCurrentId())}_getReqHeaders(i){return r(this,void 0,void 0,(function*(){const r=this._context.getCurrentId(),s=r;if(!this._rtcToken){const{code:r,data:n}=yield this._context.getRTCToken(s,zt.LIVE,i);if(r!==t.ErrorCode.SUCCESS)return o.error(`getRTCToken failed: ${r}`),{code:e.RCRTCCode.SIGNAL_ERROR};this._rtcToken=n.rtcToken}return{code:e.RCRTCCode.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:r,RoomId:s,RoomType:zt.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 t;return r(this,void 0,void 0,(function*(){this._fromRetry=!0;const{code:r}=yield this.subscribe(this._liveUrl,this._livingType,this._mediaType,this._subTiny);r===e.RCRTCCode.SUCCESS&&(null===(t=this._pc)||void 0===t||t.clearReTryExchangeTimer())}))}subscribe(e,t,o,i=!1){return r(this,void 0,void 0,(function*(){return ao((()=>this.__subscribe(e,t,o,i)),"audience-client-sub")}))}__subscribe(i,a,c,d=!1){var u;return r(this,void 0,void 0,(function*(){t.logger.info(s.L_AUDIENCE_CLIENT_SUBSCRIBE_T,{liveUrl:i,livingType:a,mediaType:c,subTiny:d},{logSource:t.LogSource.RTC});const r=[];if(ht(this._context.getNaviInfo()))return t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,tracks:r};if(!this._fromRetry&&(null===(u=this._pc)||void 0===u||u.clearReTryExchangeTimer()),this._fromRetry=!1,!t.isString(i))return o.error(`liveUrl is invalid: ${i}`),t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:`params error -> liveUrl: ${i}`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR,tracks:r};if(![e.RCLivingType.AUDIO,e.RCLivingType.VIDEO].includes(a))return o.error(`livingType is invalid: ${a}`),t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:`params error -> livingType: ${a}`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR,tracks:r};if(![e.RCMediaType.AUDIO_ONLY,e.RCMediaType.VIDEO_ONLY,e.RCMediaType.AUDIO_VIDEO].includes(c))return o.error(`mediaType is invalid: ${c}`),t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:`params error -> -> mediaType: ${c}`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR,tracks:r};if(this._liveUrl&&this._liveUrl!==i)return t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.BROADCAST_SUB_LIST_NOT_EMPTY,msg:"repeat subscribe"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.BROADCAST_SUB_LIST_NOT_EMPTY,tracks:r};if(!this._pc){const{pcName:e,pc:t}=this._peerCManager.createPeerCList(r)[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=i;const{code:_,headers:l}=yield this._getReqHeaders(a);if(_!==e.RCRTCCode.SUCCESS)return t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:_,msg:""},{logSource:t.LogSource.RTC}),{code:_,tracks:r};const R=`rc_mcu_${Date.now()}`,C="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new Je(C,R),new qe(C,R)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const h=`${Date.now()}`;At.getMemo().qualityStatus=h,t.logger.info(s.L_QS_CREATE_OFFER_O,{identify:h},{logSource:t.LogSource.RTC});const g={sdp:yield this._pc.createOffer(!0),liveUrl:i,mediaType:c,simulcast:d?yt.TINY:yt.NORMAL,switchstream:!1};t.logger.info(s.L_QS_SUBSCRIBE_EXCHANGE_O,{identify:h},{logSource:t.LogSource.RTC});const p=yield this._service.broadcastSubscribe(l,g);if(p.code!==e.RCRTCCode.SUCCESS)return o.error(`andience subscribe failed: ${p.code}`),t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:p.code,msg:""},{logSource:t.LogSource.RTC}),{code:p.code,tracks:r};const S=p.data;if(S.resultCode!==e.RCRTCCode.SUCCESS)return o.error(`andience subscribe failed! code: ${S.resultCode}; message: ${S.message}`),t.logger.error(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.FAILED,code:S.resultCode,msg:""},{logSource:t.LogSource.RTC}),{code:S.resultCode,tracks:r};o.debug(`andience subscribe success: ${i}`),this._livingType=a,this._mediaType=c,this._subTiny=d;const{sdp:m,subscribedList:T}=S;t.logger.info(s.L_QS_GET_ANSWER_O,{identify:h},{logSource:t.LogSource.RTC});const I=[];return T.forEach((e=>{const{mediaType:t}=e,r=this._subTracks[t];I.push(r),r.__innerSetRemoteMuted(!0)})),t.logger.info(s.L_QS_GET_RESOURCES_O,{identify:h},{logSource:t.LogSource.RTC}),this._pc.setRemoteAnswer(m.sdp),t.logger.info(s.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:n.SUCCESSED,liveUrl:i},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,tracks:I}}))}unsubscribe(){return r(this,void 0,void 0,(function*(){return ao((()=>this.__unsubscribe()),"audience-client-unsub")}))}__unsubscribe(){var i;return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_AUDIENCE_CLIENT_UNSUBSCRIBE_T,{liveUrl:this._liveUrl},{logSource:t.LogSource.RTC}),null===(i=this._pc)||void 0===i||i.clearReTryExchangeTimer(),!this._rtcToken||!this._liveUrl)return t.logger.warn(s.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:n.FAILED,code:"",msg:"Address does not exist, without unsubscribe"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS};const{headers:r}=yield this._getReqHeaders(),{code:a}=yield this._service.broadcastExit(r);return a!==e.RCRTCCode.SUCCESS?(o.error(`broadcast unsubscribe failed: ${a}`),t.logger.error(s.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:n.FAILED,code:a,msg:""},{logSource:t.LogSource.RTC})):(o.debug("broadcast unsubscribe success"),t.logger.info(s.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:n.SUCCESSED,liveUrl:this._liveUrl},{logSource:t.LogSource.RTC})),this._clearSubscribeInfo(),{code:a}}))}registerReportListener(e){this._reportListener=e}registerTrackEventListener(e){this._appListener=e}_onTrackReady(r){var i,n;const{track:a}=r.receiver,c="audio"===a.kind?e.RCMediaType.AUDIO_ONLY:e.RCMediaType.VIDEO_ONLY,d=this._subTracks[c];d.__innerSetMediaStreamTrack(a);const u=At.getMemo();t.logger.info(s.L_QS_CREATE_OFFER_O,{identify:u.qualityStatusId},{logSource:t.LogSource.RTC});try{null===(n=null===(i=this._appListener)||void 0===i?void 0:i.onTrackReady)||void 0===n||n.call(i,d)}catch(e){o.error(e)}}}var uo,_o;e.RCInnerCDNPullKind=void 0,(uo=e.RCInnerCDNPullKind||(e.RCInnerCDNPullKind={})).RTMP="rtmp",uo.FLV="flv",uo.HLS="hls",e.RCInnerCDNPullIsHttps=void 0,(_o=e.RCInnerCDNPullIsHttps||(e.RCInnerCDNPullIsHttps={}))[_o.NOT_HTTPS=0]="NOT_HTTPS",_o[_o.HTTPS=1]="HTTPS";const lo=Object.assign(Object.assign({},at(e.RCResolution.W176_H144)),{frameRate:ut(e.RCFrameRate.FPS_15)});class Ro{constructor(e,t,i,s,n,a,c,d=Lt()){this._context=e,this._runtime=t,this._initOptions=i,this._roomId=s,this._joinResData=n,this.livingType=a,this._useMutilPeerC=c,this._clientSessionId=d,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 Nt(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new _r(this._context,this._runtime,this._roomId,this,jt.Audience),this._polarisReport.sendR1(),this._peerCManager=new Rr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._context.registerRTCSignalListener((e=>r(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,i){return r(this,void 0,void 0,(function*(){if(this._isPulling)return;this._isPulling=!0;if(this._pullTime>i)return void(this._isPulling=!1);const{code:r,data:s}=yield this._context.pullRTCRoomEntry(e);if(r===t.ErrorCode.SUCCESS){this._isPulling=!1,this._pullTime=s.syncTime||0;const t=(null==s?void 0:s.kvEntries)||[];o.info(`_startPull -> ${JSON.stringify(t)}`),this.singalDataChange(t,e)}}))}_setInitData(){const{sessionId:e,remoteUserIds:t,remoteRTCUris:r,remoteMUCUris:o,remoteTracks:i,CDNUris:s}=pt(this._roomId,this._joinResData.kvEntries);this._sessionId=e,this._roomAnchorList=t,i.forEach((e=>{this._remoteTracks[e.getTrackId()]=e})),this._CDNUris=s,r.forEach((e=>{const t=e.msid.split("_")[0];this._roomAnchorRes[t]?this._roomAnchorRes[t].push(e):this._roomAnchorRes[t]=[e]})),o.forEach((e=>{const{mediaType:t,tag:r}=e,o=[this._roomId,r,t].join("_");this._roomRes[o]=e})),r.forEach((e=>{const t=tt(e);this._roomRes[t]=e}))}_assertRoomDestroyed(){if(this._destroyed){const t="This room has been destroyed. Please use `RCRTCClient.joinLivingRoomAsAudience` to catch another instance.";return o.warn(t),e.RCRTCCode.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(e,r){var i;if(t.logger.info(s.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_T,{singalData:e,roomId:r,userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),r!==this._roomId)return o.warn(`singalDataChange -> not the current room data: data roomId: ${r}, current roomId: ${this._roomId}`),void t.logger.error(s.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:n.FAILED,code:"",msg:`id inconsistency -> params id:${r},current id:${this._roomId}`},{logSource:t.LogSource.RTC});o.debug("singalDataChange -> singalData:",JSON.stringify(e||{}));const a=[],c=null===(i=e.filter((e=>"RC_CDN"===e.key))[0])||void 0===i?void 0:i.value;c&&this._diffCDNUris(JSON.parse(JSON.parse(c).cdn_uris)[0]),e.forEach((e=>{const{key:t,value:r,timestamp:o,uid:i}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),o=JSON.parse(e.uris||"[]");return a.push(...t),void this._diffAnchorResource(o,i)}if("RC_ANCHOR_LIST"===t){const e=JSON.parse(r||"[]"),{joinUserIds:t,leftUserIds:o}=this._diffAnchorList(e);t.length>0&&this._handleNewJoinedAnchor(t),o.length>0&&this._handleLeftedAnchor(o)}})),this._diffRoomResource(a),t.logger.info(s.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:n.SUCCESSED,singalData:e,roomId:r,userId:this._context.getCurrentId()},{logSource:t.LogSource.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 r(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(t){return r(this,void 0,void 0,(function*(){const r=[],o=[],i=[];t.forEach((t=>{const o=tt(t),{userId:s,tag:n,mediaType:a}=rt(o),c=[this._roomId,n,a].join("_");if(!this._remoteTracks[c]){const o=a===e.RCMediaType.AUDIO_ONLY?new Je(n,"",this._roomId):new qe(n,"",this._roomId);r.push(o),this._remoteTracks[c]=o,this._roomRes[o.getTrackId()]=t}i.push(c)})),Object.keys(this._remoteTracks).forEach((e=>{i.indexOf(e)<0&&this._remoteTracks[e].isMCUTrack()&&o.push(this._remoteTracks[e])})),r.length>0&&this._callAppListener("onTrackPublish",r),o.length>0&&this._onUserUnpublish(o,"onTrackUnpublish")}))}_diffAnchorResource(t,i){return r(this,void 0,void 0,(function*(){const r=this._roomAnchorRes[i]||(this._roomAnchorRes[i]=[]),{publishedList:s,unpublishedList:n,modifiedList:a}=st(r,t);if(s.length){const t=r.map(tt),i=[],n=[];if(s.forEach((o=>{const s=tt(o),a=t.indexOf(s),{userId:c,tag:d,mediaType:u}=rt(s);a>-1?r[a]=o:r.push(o);let _=this._remoteTracks[s];this._roomRes[s]=o,_?_.isSubscribed()&&i.push(_):(_=u===e.RCMediaType.AUDIO_ONLY?new Je(d,c):new qe(d,c),this._remoteTracks[s]=_,n.push(_)),_.__innerSetRemoteMuted(0===o.state)})),i.length){const t=i.map((e=>e.getTrackId()));o.debug(`resub tracks -> ${JSON.stringify(t)}`);const{code:r}=yield ao((()=>this._subscribeHandle(i,!0)));r!==e.RCRTCCode.SUCCESS&&o.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(t)}`)}this._callAppListener("onAnchorTrackPublish",n)}if(n.length){const e=n.map(tt);for(let t=r.length-1;t>=0;t-=1){const o=r[t];e.includes(tt(o))&&r.splice(t,1)}const t=n.map((e=>{const t=tt(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t,"onAnchorTrackUnpublish")}if(a.length){const e=r.map(tt);for(let t=0;t<a.length;t++){const o=a[t],i=tt(o),s=e.indexOf(i);r[s].state=o.state;const n=this._remoteTracks[i];n.__innerSetRemoteMuted(0===o.state),n.isAudioTrack()?this._callAppListener("onAudioMuteChange",n):this._callAppListener("onVideoMuteChange",n)}}}))}_onUserUnpublish(e,t){return r(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 r(this,void 0,void 0,(function*(){ao((()=>r(this,void 0,void 0,(function*(){var t;const{reqBody:r}=yield this._createSubscribeParams(this._subscribedList,{},!0),i=yield this._exchangeHandle(r);if(i.code!==e.RCRTCCode.SUCCESS)return o.error(`reTryExchange failed: ${i.code}`),{code:i.code};const{sdp:s,resultCode:n}=i.data;if(n!==e.RCRTCCode.SUCCESS)return o.error(`reTryExchange failed: ${n}`),{code:n};this._pc.clearReTryExchangeTimer();const a=this._subscribedList.filter((e=>e.track.isMCUTrack()));if(a.length>0){const e=a[0].track.getTrackId(),r=null===(t=this._roomRes[e])||void 0===t?void 0:t.msid,o=[this._roomId,"RongCloudRTC"].join("_");s.sdp=s.sdp.replace(new RegExp(r,"g"),o)}const c=yield this._pc.setRemoteAnswer(s.sdp);return c!==e.RCRTCCode.SUCCESS?{code:c}:void 0}))),"audience-retry-exchange")}))}_createSubscribeParams(e,t,o){return r(this,void 0,void 0,(function*(){const r=yield this._pc.createOffer(o),i={resolutionInfo:[]},s={min:0,max:0};Object.keys(t).forEach((e=>{const{mediaStream:o,tinyStream:n}=t[e];[o,n].forEach(((t,o)=>{var n;const a=1===o?[e,"tiny"].join("_"):e;r.sdp=null===(n=r.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===o,{width:u,height:_,frameRate:l}=d?Xe(c):lo;i.resolutionInfo.push({trackId:c.id,simulcast:d?yt.NORMAL:yt.TINY,resolution:`${u}x${_}`});const R=Le(u,_),C=Oe(l);s.min+=R.minBitrate*C,s.max+=R.maxBitrate*C}))}));return{reqBody:{sdp:r,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?yt.TINY:yt.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:s,offer:r}}))}_subscribeHandle(o,i=!1){var a;return r(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return t.logger.error(s.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.ROOM_HAS_BEEN_DESTROYED,msg:"room destroyed"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!t.validate("tracks",o,(()=>t.isArray(o)&&o.length>0&&o.every((e=>e instanceof je||e.track instanceof je))),!0))return t.logger.error(s.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};const{pc:r,pcName:c}=this._peerCManager.createPeerCList(o)[0];this._pc=r,this._pc.__reportR3R4ToPolaris(),this._pcName=c,this._pc.registerReportListener(this._reportListener),this._addPeerCEvent();const d=this._subscribedList.map((e=>Object.assign({},e))),u=o.map((e=>e instanceof je?{track:e}:e));let _=!1;const l=[];return u.forEach((e=>{const t=e.track.getTrackId();l.push(t);const r=d.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:d.push(e),_=!0)})),_||i?(null===(a=this._polarisReport)||void 0===a||a.sendR2(Xt.SUBSCRIBE,er.BEGIN,l),t.logger.info(s.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:n.SUCCESSED,trackIds:o.map(St),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:i},{logSource:t.LogSource.RTC}),this._updateSubListHandle(d,!0)):(t.logger.warn(s.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:n.FAILED,code:"",msg:"repeat subscribe"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS})}))}_addPeerCEvent(){this._pc.on(ur.__INNER_EVENT_TRACK_READY__,(r=>{const i=r.streams[0].id,{track:n}=r.receiver,a=[i,"audio"===n.kind?e.RCMediaType.AUDIO_ONLY:e.RCMediaType.VIDEO_ONLY].join("_"),c=this._remoteTracks[a];if(!c)return void o.warn("cannot found RCRemoteTrack:",n.id);c.__innerSetMediaStreamTrack(n);const d=At.getMemo();t.logger.info(s.L_QS_TRACK_READY_O,{identify:d.qualityStatusId},{logSource:t.LogSource.RTC}),this._callAppListener("onTrackReady",c)}))}_getReqHeaders(){const e=this._context.getCurrentId();return{"App-Key":this._context.getAppkey(),RoomId:e,Token:this._joinResData.token,RoomType:zt.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(i,n=!1){var a;return r(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:e.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!t.validate("resources",i,(()=>t.isArray(i)&&i.every((e=>e instanceof je||e.track instanceof je))),!0))return{code:e.RCRTCCode.PARAMS_ERROR};let r=i.map((e=>e instanceof je?{track:e}:Object.assign({},e)));const c={};r=r.filter((e=>{const t=e.track.getTrackId();return!c[t]&&(c[t]=!0,!0)})).map((e=>Object.assign({},e)));const d=this._subscribedList.map((e=>Object.assign({},e)));if(!n){let t=!1;if(r.forEach((e=>{const r=d.findIndex((t=>t.track===e.track));if(-1===r)return void(t=!0);d.splice(r,1)[0].subTiny!==e.subTiny&&(t=!0)})),d.length&&(t=!0),!t)return{code:e.RCRTCCode.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(r.map((e=>e.track)));const u=At.getMemo(),_={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};u.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};u.qualityUnsubscribeReportData=l,u.unsubscribeData={start:Date.now()},t.logger.info(s.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_T,{trackIds:i.map(St),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:n},{logSource:t.LogSource.RTC});const{reqBody:R}=yield this._createSubscribeParams(r,{},!1),C=yield this._exchangeHandle(R);let h=[],g=Date.now();if(u.mediaService.forEach((e=>{h.push({rsid:e.reqId,rsdur:e.end-e.start,msa:e.url,rscod:e.rscod})})),d.length){const e=[];d.forEach((t=>{e.push(t.track.getTrackId())})),null===(a=this._pc.reportParser)||void 0===a||a.clearLatestPacketsRecv(e)}if(C.code!==e.RCRTCCode.SUCCESS)return u.subscribeCommand&&(u.subscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualitySubscribeReportData,{dur:g-((null===(r=u.subscribeData)||void 0===r?void 0:r.start)||0),cod:C.code,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,i,t.LogSource.RTC)}))),u.unsubscribeCommand&&(u.unsubscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualityUnsubscribeReportData,{dur:g-((null===(r=u.unsubscribeData)||void 0===r?void 0:r.start)||0),cod:C.code,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,i,t.LogSource.RTC)}))),{code:C.code};const{sdp:p,resultCode:S,message:m,subscribedList:T}=C.data;if(S!==e.RCRTCCode.SUCCESS)return u.subscribeCommand&&(u.subscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualitySubscribeReportData,{dur:g-((null===(r=u.subscribeData)||void 0===r?void 0:r.start)||0),cod:S,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,i,t.LogSource.RTC)}))),u.unsubscribeCommand&&(u.unsubscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualityUnsubscribeReportData,{dur:g-((null===(r=u.unsubscribeData)||void 0===r?void 0:r.start)||0),cod:S,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,i,t.LogSource.RTC)}))),o.error("change subscribe list failed:",m,S),{code:S};r.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:o}=rt(t.getTrackId()),i=[o,r].join("_");p.sdp=p.sdp.replace(new RegExp(e,"g"),i)}}));const I=yield this._pc.setRemoteAnswer(p.sdp);if(I!==e.RCRTCCode.SUCCESS)return u.subscribeCommand&&(u.subscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualitySubscribeReportData,{dur:g-((null===(r=u.subscribeData)||void 0===r?void 0:r.start)||0),cod:I,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,i,t.LogSource.RTC)}))),u.unsubscribeCommand&&(u.unsubscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualityUnsubscribeReportData,{dur:g-((null===(r=u.unsubscribeData)||void 0===r?void 0:r.start)||0),cod:I,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,i,t.LogSource.RTC)}))),{code:I};u.subscribeCommand&&(u.subscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualitySubscribeReportData,{dur:g-((null===(r=u.subscribeData)||void 0===r?void 0:r.start)||0),cod:I,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_SUBSCRIBE_S,i,t.LogSource.RTC)}))),u.unsubscribeCommand&&(u.unsubscribeCommand=!1,r.forEach((e=>{var r,o;const i=JSON.stringify(Object.assign(u.qualityUnsubscribeReportData,{dur:g-((null===(r=u.unsubscribeData)||void 0===r?void 0:r.start)||0),cod:I,msas:h,time:g,resid:e.track.getTrackId(),mtp:rt(e.track.getTrackId()).mediaType,smct:e.track instanceof we&&(null===(o=e.track)||void 0===o?void 0:o.__isTiny())?2:1}));t.reportLog(t.LogLevel.STATISTICS,s.L_QS_UNSUBSCRIBE_S,i,t.LogSource.RTC)})));const E=null==T?void 0:T.map((e=>`${e.msid}_${e.mediaType}`)),f=r.filter((e=>{if(e.track.isMCUTrack()){const t=this._roomRes[e.track.getTrackId()],r=`${t.msid}_${t.mediaType}`;return E.includes(r)}return null==E?void 0:E.includes(e.track.getTrackId())})),L=null==f?void 0:f.map((e=>`${e.track.getTrackId()}`)),v=r.filter((e=>!(null==L?void 0:L.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=f.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...f),v.length?{code:e.RCRTCCode.SUCCESS,failedList:v}:{code:e.RCRTCCode.SUCCESS}}))}_diffCDNUris(e){return r(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,o=this._CDNUris.fps&&e.fps&&this._CDNUris.fps!==e.fps;(t||r||o)&&this._callAppListener("onCDNInfoChange",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`}),this._CDNUris=e}))}_getCDNPlayUrl(t){return r(this,void 0,void 0,(function*(){const{w:r,h:i,fps:s}=t,n=this._initOptions.pullInnerCDNProtocol||e.RCInnerCDNPullKind.FLV,a=this._initOptions.pullInnerCDNUseHttps===e.RCInnerCDNPullIsHttps.NOT_HTTPS?e.RCInnerCDNPullIsHttps.NOT_HTTPS:e.RCInnerCDNPullIsHttps.HTTPS;if(!this._CDNUris.url)return o.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${e.RCRTCCode.CDN_RESOURCE_IS_EMPTY}`),{code:e.RCRTCCode.CDN_RESOURCE_IS_EMPTY};const c={"App-Key":this._context.getAppkey(),Token:this._joinResData.token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},d=[],{w:u=0,h:_=1}=this._CDNUris;u/_>1?(r&&d.push(`w=${r}`),i&&d.push(`h=${i}`)):(r&&d.push(`h=${r}`),i&&d.push(`w=${i}`)),s&&d.push(`fps=${s}`),d.push(`kind=${n}`),d.push(`is_https=${a}`);const l=d.join("&");let R=`${this._CDNUris.url}?`;l&&(R+=l);const{code:C,res:h}=yield this._service.getCDNResourceInfo(c,R);return C!==e.RCRTCCode.SUCCESS?(o.error(`getCDNPlayUrl failed: ${C}`),{code:C}):(o.info(`getCDNPlayUrl success: ${null==h?void 0:h.data.pull_url}`),{code:C,CDNPlayUrl:null==h?void 0:h.data.pull_url})}))}getCDNPlayUrl(i,a){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_T,{resolution:i,fps:a},{logSource:t.LogSource.RTC}),i&&!ct(i))return o.error("`resolution` is invalid"),t.logger.error(s.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> resolution"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(a&&!dt(a))return o.error("`fps` is invalid"),t.logger.error(s.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> fps"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};const{width:r,height:c}=i?at(i):{width:null,height:null},d=a?ut(a):null,u={};return r&&(u.w=r),c&&(u.h=c),d&&(u.fps=d),t.logger.info(s.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:n.SUCCESSED,resolution:i,fps:a},{logSource:t.LogSource.RTC}),this._getCDNPlayUrl(u)}))}subscribe(e){return r(this,void 0,void 0,(function*(){return At.getMemo().subscribeCommand=!0,ao((()=>this._subscribeHandle(e,!1)),"audience-sub")}))}addSubscribeTask(e){return r(this,void 0,void 0,(function*(){return At.getMemo().subscribeCommand=!0,ao((()=>this._subscribeHandle(e,!1)),"audience-sub")}))}__unsubscribe(i){var a;return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_T,{trackIds:i.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),!t.validate("tracks",i,(()=>t.isArray(i)&&i.length>0&&i.every((e=>e instanceof je))),!0))return o.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),t.logger.error(s.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};const r=this._subscribedList.map((e=>Object.assign({},e))).filter((e=>!i.includes(e.track)));null===(a=this._polarisReport)||void 0===a||a.sendR2(Xt.SUBSCRIBE,er.END,i.map((e=>e.getTrackId()))),t.logger.info(s.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:n.SUCCESSED,trackIds:i.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC});return At.getMemo().unsubscribeCommand=!0,this._updateSubListHandle(r,!1)}))}unsubscribe(e){return r(this,void 0,void 0,(function*(){return ao((()=>this.__unsubscribe(e)),"audience-unsub")}))}addUnsubscribeTask(e){return r(this,void 0,void 0,(function*(){return ao((()=>this.__unsubscribe(e)),"audience-unsub")}))}__destroy(e){var t,o;return r(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===(o=this._pc)||void 0===o||o.destroy(),At.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 r(this,void 0,void 0,(function*(){const{code:e}=yield this._context.joinLivingRoomAsAudience(this._roomId,zt.LIVE);e!==t.ErrorCode.SUCCESS&&o.error("join living room error when on reconnected")}))}registerRoomEventListener(e){this._appListener=e}onAudioLevelChange(e,r){var o;null===(o=this._audioLevelReport)||void 0===o||o.clearAudioLevelReportTimer(),this._audioLevelReport=new lr(this),this._audioLevelReport.onAudioLevelChange(e,r||1e3),t.logger.info(s.L_AUDIENCE_LIVING_ROOM_AUDIO_LEVEL_CHANGE_O,{status:n.SUCCESSED,handler:null==e?void 0:e.name,gap:r},{logSource:t.LogSource.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 o=this._remoteTracks[r];o.getUserId()===e&&t.push(o)}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 Co{constructor(e){this._context=e,this._isElectron=/Electron/.test(navigator.userAgent)}_getMediaStream(t,i="getUserMedia"){return r(this,void 0,void 0,(function*(){try{const r=this.setConstraintsConfig(t),o=yield navigator.mediaDevices[i](r);return{code:e.RCRTCCode.SUCCESS,stream:o}}catch(t){if("Permission denied"===t.message)return{code:e.RCRTCCode.BROWSER_PERMISSION_DENIED};if("Permission denied by system"===t.message)return{code:e.RCRTCCode.SYSTEM_PERMISSION_DENIED};o.error(`get user media failed -> ${t.message}`)}return{code:"getUserMedia"===i?e.RCRTCCode.GET_USER_MEDIA_FAILED:e.RCRTCCode.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(o="RongCloudRTC",i){return r(this,void 0,void 0,(function*(){if(!Qe(o))return t.logger.error(s.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return t.logger.error(s.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID};const{stream:a,code:c}=yield this._getMediaStream({audio:{deviceId:null==i?void 0:i.micphoneId,sampleRate:null==i?void 0:i.sampleRate}});if(c!==e.RCRTCCode.SUCCESS)return t.logger.error(s.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:n.FAILED,code:c,msg:"Failed to get microphone audio stream"},{logSource:t.LogSource.RTC}),{code:c};const d=a.getAudioTracks()[0],u=new Fe(o,r,d);return t.logger.info(s.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:n.SUCCESSED,trackId:u.getTrackId()},{logSource:t.LogSource.RTC}),{code:c,track:u}}))}createCameraVideoTrack(o="RongCloudRTC",i){return r(this,void 0,void 0,(function*(){if(!Qe(o))return t.logger.error(s.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return t.logger.error(s.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID};const a=ct(null==i?void 0:i.resolution)?i.resolution:e.RCResolution.W640_H480,{width:c,height:d}=at(a),{stream:u,code:_}=yield this._getMediaStream({video:{deviceId:null==i?void 0:i.cameraId,frameRate:ut((null==i?void 0:i.frameRate)||e.RCFrameRate.FPS_15),width:c,height:d,facingMode:null==i?void 0:i.faceMode}});if(_!==e.RCRTCCode.SUCCESS)return t.logger.error(s.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"Failed to get camera video stream"},{logSource:t.LogSource.RTC}),{code:_};const l=u.getVideoTracks()[0],R=new Ge(o,r,l);return t.logger.info(s.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:n.SUCCESSED,trackId:R.getTrackId()},{logSource:t.LogSource.RTC}),{code:_,track:R}}))}createMicrophoneAndCameraTracks(o="RongCloudRTC",i){var a,c,d,u,_,l;return r(this,void 0,void 0,(function*(){const r=[];if(!Qe(o))return t.logger.error(s.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS,tracks:r};const R=this._context.getCurrentId();if(!R)return t.logger.error(s.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID,tracks:r};const C=ct(null===(a=null==i?void 0:i.video)||void 0===a?void 0:a.resolution)?i.video.resolution:e.RCResolution.W640_H480,{width:h,height:g}=at(C),{stream:p,code:S}=yield this._getMediaStream({video:{deviceId:null===(c=null==i?void 0:i.video)||void 0===c?void 0:c.cameraId,frameRate:ut((null===(d=null==i?void 0:i.video)||void 0===d?void 0:d.frameRate)||e.RCFrameRate.FPS_15),width:h,height:g,facingMode:null===(u=null==i?void 0:i.video)||void 0===u?void 0:u.faceMode},audio:{deviceId:null===(_=null==i?void 0:i.audio)||void 0===_?void 0:_.micphoneId,sampleRate:null===(l=null==i?void 0:i.audio)||void 0===l?void 0:l.sampleRate}});return S!==e.RCRTCCode.SUCCESS?(t.logger.error(s.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:n.FAILED,code:S,msg:"Failed to get audio and video stream of camera and microphone"},{logSource:t.LogSource.RTC}),{code:S,tracks:r}):(p.getTracks().forEach((e=>{"video"===e.kind?r.push(new Ge(o,R,e)):r.unshift(new Fe(o,R,e))})),t.logger.info(s.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:n.SUCCESSED,trackIds:r.map((e=>e.getTrackId()))},{logSource:t.LogSource.RTC}),{code:S,tracks:r})}))}createScreenVideoTrack(t="screenshare",o){return r(this,void 0,void 0,(function*(){const r=yield this._createScreenTracks(t,!1,s.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,o);return r.code===e.RCRTCCode.SUCCESS?{code:r.code,track:r.tracks[0]}:r}))}createScreenWithAudioTracks(e="screenshare",t){return r(this,void 0,void 0,(function*(){return this._createScreenTracks(e,!0,s.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_AND_AUDIO_TRACKS_O,t)}))}_createScreenTracks(o,i,a,c){var d,u;return r(this,void 0,void 0,(function*(){if(!Qe(o))return t.logger.error(a,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return t.logger.error(a,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID};if(!Rt())return t.logger.error(s.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.BROWSER_NOT_SUPPORT};const _=/macintosh|mac os x/i.test(navigator.userAgent);this._isElectron&&_&&i&&t.logger.warn(a,{status:n.INFO,code:e.RCRTCCode.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO,msg:"mac in electron not support screen share with audio"});const l=(!this._isElectron||!_)&&i;if(this._isElectron&&!t.isUndefined(null==c?void 0:c.chromeMediaSourceId)&&!t.isString(null==c?void 0:c.chromeMediaSourceId))return t.logger.error(a,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> options.chromeMediaSourceId type is string"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};const R=ct(null==c?void 0:c.resolution)?c.resolution:e.RCResolution.W1280_H720,{width:C,height:h}=at(R),g=this._isElectron?{mandatory:{chromeMediaSourceId:null==c?void 0:c.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:C,maxWidth:C,minHeight:h,maxHeight:h}}:{frameRate:ut((null==c?void 0:c.frameRate)||e.RCFrameRate.FPS_15),width:C,height:h};!(null==c?void 0:c.chromeMediaSourceId)&&this._isElectron&&(null===(d=g.mandatory)||void 0===d||delete d.chromeMediaSourceId);let p=null;l&&this._isElectron&&(null===(u=g.mandatory)||void 0===u||delete u.chromeMediaSourceId,p={mandatory:{chromeMediaSource:"desktop"}});const{stream:S,code:m}=yield this._getMediaStream({video:g,audio:p||l},this._isElectron?"getUserMedia":"getDisplayMedia");if(m!==e.RCRTCCode.SUCCESS)return t.logger.error(a,{status:n.FAILED,code:m,msg:"Failed to get shared screen video stream"},{logSource:t.LogSource.RTC}),{code:m};const T=S.getVideoTracks()[0],I=[new Ke(o,r,T)];if(l){const e=S.getAudioTracks()[0];e&&I.push(new He(o,r,e))}return t.logger.info(a,{status:n.SUCCESSED,trackIds:I.map((e=>e.getTrackId()))},{logSource:t.LogSource.RTC}),{code:m,tracks:I}}))}createLocalAudioTrack(o,i){return r(this,void 0,void 0,(function*(){if(!Qe(o))return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS};if(!i||"[object MediaStreamTrack]"!==i.toString()||"audio"!==i.kind)return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"Failed to create custom stream"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED};const r=this._context.getCurrentId();if(!r)return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID};const a=new xe(o,r,i);return t.logger.info(s.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:n.SUCCESSED,trackId:a.getTrackId()},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,track:a}}))}createLocalVideoTrack(o,i){return r(this,void 0,void 0,(function*(){if(!Qe(o))return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS};if(!i||"[object MediaStreamTrack]"!==i.toString()||"video"!==i.kind)return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED,msg:"Failed to create custom stream"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED};const r=this._context.getCurrentId();if(!r)return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID};const a=new we(o,r,i);return t.logger.info(s.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:n.SUCCESSED,trackId:a.getTrackId()},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,track:a}}))}createLocalFileTracks(i,a,c){return r(this,void 0,void 0,(function*(){if(!Qe(i))return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS,tracks:[]};if(!lt())return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.BROWSER_NOT_SUPPORT,tracks:[]};const r=a instanceof File?URL.createObjectURL(a):a;if(!t.isHttpUrl(r)&&!/^blob:/.test(r))return o.warn(`createLocalFileTracks failed: params error -> url: ${r}`),t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> file"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR,tracks:[]};const d=this._context.getCurrentId();return d?new Promise((a=>{const u=document.createElement("video");(null==c?void 0:c.withoutAudio)&&(u.muted=!0),u.onloadedmetadata=()=>{const _=[];let l;try{const e=u.mozCaptureStream?"mozCaptureStream":"captureStream";l=u[e]()}catch(i){o.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${r}`),o.error(i),t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:t.LogSource.RTC}),a({code:e.RCRTCCode.CREATE_FILE_TRACK_FAILED,tracks:_})}const[R,C]=Co.getTracksWithOptions(l,c);R&&_.push(new $e(i,d,R,u)),C&&_.push(new Ve(i,d,C,u)),0===_.length&&(u.pause(),u.src=""),u.onerror=null,t.logger.info(s.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:n.SUCCESSED,trackIds:_.map((e=>e.getTrackId()))},{logSource:t.LogSource.RTC}),a({code:e.RCRTCCode.SUCCESS,tracks:_})},u.onerror=()=>{o.error(`create RCLocalFileTrack failed -> url: ${r}`),t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:t.LogSource.RTC}),a({code:e.RCRTCCode.CREATE_FILE_TRACK_FAILED,tracks:[]})},u.src=r,u.loop=!0,u.play()})):(t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID,tracks:[]})}))}createLocalTracks(o,i,a){return r(this,void 0,void 0,(function*(){const r=[];if(!Qe(o))return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_TAGS,tracks:r};if(!(i instanceof MediaStream))return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> stream"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR,tracks:r};const c=this._context.getCurrentId();if(!c)return t.logger.error(s.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:n.FAILED,code:e.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.INVALID_USER_ID,tracks:r};const[d,u]=Co.getTracksWithOptions(i,a);return d&&r.push(new xe(o,c,d)),u&&r.push(new we(o,c,u)),t.logger.info(s.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:n.SUCCESSED,trackIds:r.map((e=>e.getTrackId()))},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,tracks:r}}))}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 ho extends Co{constructor(e,t,r){super(e),this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,ir.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new Nt(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.ConversationType.RTC_ROOM)return!1;if(this._crtRoom instanceof io){this._getJoinedPKRoomList().forEach((t=>{t.__parseInnerMessage(e)}))}return t.logger.info(s.L_RTC_CLIENT_MESSAGE_O,{status:n.SUCCESSED,message:e},{logSource:t.LogSource.RTC}),this._crtRoom?(this._crtRoom.__parseInnerMessage(e),!0):(t.logger.warn(s.L_RTC_CLIENT_MESSAGE_O,{status:n.FAILED,message:"the crtRoom is empty"},{logSource:t.LogSource.RTC}),!0)}naviDataChange(e){t.logger.info(`on navi change data => ${JSON.stringify(e)}`),this._service.detectorMediaSever()}_getJoinedPKRoomList(){const{code:t,roomPKHandler:r}=this._crtRoom.getRoomPKHandler();if(t===e.RCRTCCode.SUCCESS&&r){const e=r.getJoinedPKRooms()||{};return Object.values(e)}return[]}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(o,i,a,c,d=zt.RTC){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_RTC_CLIENT_JOIN_RTC_ROOM_T,{roomId:o,joinType:i,outerUserDatas:a,useMutilPeerC:c,roomType:d},{logSource:t.LogSource.RTC}),this._crtRoom)return t.logger.error(s.L_RTC_CLIENT_JOIN_RTC_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REPERT_JOIN_ROOM};const r=this._crtRoom=new so(this._context,this._runtime,o,this._service,this._options,!1,!1,c,Lt()),{code:u}=yield r.__innerInit(d,i,void 0,void 0,a);return u!==e.RCRTCCode.SUCCESS?(this._crtRoom=null,{code:u}):(r.once($r,(()=>{this._crtRoom=null})),{code:u,room:r,userIds:r.getRemoteUserIds(),tracks:r.getRemoteTracks()})}))}joinCrossRTCRoom(o,i,a,c,d=zt.CROSS_MUTI){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_T,{roomId:o,joinType:i,outerUserDatas:a,useMutilPeerC:c,roomType:d},{logSource:t.LogSource.RTC}),this._crtRoom)return t.logger.error(s.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REPERT_JOIN_ROOM};const r=this._crtRoom=new so(this._context,this._runtime,o,this._service,this._options,!1,!1,c,Lt(),d),{code:u}=yield r.__innerInit(d,i,void 0,void 0,a);return u!==e.RCRTCCode.SUCCESS?(this._crtRoom=null,{code:u}):(r.once($r,(()=>{this._crtRoom=null})),{code:u,room:r,userIds:r.getRemoteUserIds(),tracks:r.getRemoteTracks()})}))}joinLivingRoom(o,i,a,c,d){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_T,{roomId:o,livingType:i,joinType:a,outerUserDatas:c,useMutilPeerC:d},{logSource:t.LogSource.RTC}),this._crtRoom)return t.logger.error(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.REPERT_JOIN_ROOM,msg:`Join the room repeatedly -> roomId: ${o}`},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REPERT_JOIN_ROOM};const r=this._crtRoom=new io(this._context,this._runtime,o,this._service,this._options,i,!1,!0,d),{code:u}=yield r.__innerInit(zt.LIVE,a,i,void 0,c);if(u!==e.RCRTCCode.SUCCESS)return this._crtRoom=null,{code:u};r.once($r,(()=>{this._crtRoom=null}));const _={code:u,room:r,userIds:r.getRemoteUserIds(),tracks:r.getRemoteTracks()};return r.__getCDNPushMode()===Qr.MANUAL&&Object.assign(_,{CDNEnable:r.__getCDNEnable()}),_}))}getAudienceClient(e){return this._audience||(this._audience=new co(this._context,this._runtime,this._options,e)),t.logger.info(s.L_RTC_CLIENT_GET_AUDIENCE_CLIENT_O,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),this._audience}_onIMStatusChange(e){if(o.debug(`signal server connection state change: ${e}`),t.logger.info(s.L_RTC_CLIENT_CONNECTION_STATE_S,{status:n.SUCCESSED,data:e},{logSource:t.LogSource.RTC}),e===t.ConnectionStatus.CONNECTED){if(this._service.detectorMediaSever(),this._crtRoom instanceof io){this._getJoinedPKRoomList().forEach((e=>{e.__onReconnected()}))}this._crtRoom&&this._crtRoom.__onReconnected()}}_onIMDisconnect(){t.logger.info(s.L_RTC_CLIENT_DISCONNECT_S,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),o.debug("TODO -> on IM disconnect")}_onIMUninit(){t.logger.info(s.L_RTC_CLIENT_DESTROY_S,{status:n.SUCCESSED},{logSource:t.LogSource.RTC}),o.debug("TODO -> on IM client ondestroy")}leaveRoom(i){var a,c;return r(this,void 0,void 0,(function*(){return t.logger.info(s.L_RTC_CLIENT_LEAVE_ROOM_T,{userId:this._context.getCurrentId(),roomId:null===(a=this._crtRoom)||void 0===a?void 0:a.getRoomId()},{logSource:t.LogSource.RTC}),this._crtRoom?(yield this._crtRoom.__destroy(!0),o.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),this._service.detectorMediaSever(),t.logger.info(s.L_RTC_CLIENT_LEAVE_ROOM_R,{status:n.SUCCESSED,userId:this._context.getCurrentId(),roomId:null===(c=this._crtRoom)||void 0===c?void 0:c.getRoomId()},{logSource:t.LogSource.RTC}),this._crtRoom=null,{code:e.RCRTCCode.SUCCESS}):(t.logger.warn(s.L_RTC_CLIENT_LEAVE_ROOM_R,{status:n.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS})}))}joinLivingRoomAsAudience(i,a,c){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_T,{roomId:i,livingType:a,useMutilPeerC:c},{logSource:t.LogSource.RTC}),this._service.detectorMediaSever(),ht(this._context.getNaviInfo()))return t.logger.error(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:n.FAILED,code:e.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR};if(!t.validate("roomId",i,t.notEmptyString,!0)||!t.validate("livingType",a,(t=>t===e.RCLivingType.AUDIO||t===e.RCLivingType.VIDEO)))return t.logger.error(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:n.FAILED,code:e.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"params error -> roomId or livingType"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return t.logger.error(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:n.FAILED,code:e.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REPERT_JOIN_ROOM};if(!this._service.getNaviMS().length)return t.logger.error(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:n.FAILED,code:e.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:r,data:d}=yield this._context.joinLivingRoomAsAudience(i,zt.LIVE,a);if(r!==t.ErrorCode.SUCCESS)return o.error("audienceJoinLivingRoomError:",r),t.logger.error(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:n.FAILED,code:e.RCRTCCode.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED,msg:"signal error -> audience join room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};o.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(d)}`);const u=Lt();At.getMemo().clientData={clientSessionId:u};const _=new Ro(this._context,this._runtime,this._options,i,d,a,c,u);return this._crtAudienceLivingRoom=_,t.logger.info(s.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:n.SUCCESSED,roomData:d},{logSource:t.LogSource.RTC}),{room:_,code:e.RCRTCCode.SUCCESS,userIds:_.getRemoteUserIds(),RTCTracks:_.getRemoteRTCTracks(),MCUTracks:_.getRemoteMCUTracks(),CDNUris:_.getCDNInfo()}}))}leaveLivingRoomAsAudience(o){return r(this,void 0,void 0,(function*(){return t.logger.info(s.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_T,{roomId:o.getRoomId(),userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),this._crtAudienceLivingRoom?this._crtAudienceLivingRoom!==o?(t.logger.error(s.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR}):(yield this._crtAudienceLivingRoom.__destroy(!0),this._crtAudienceLivingRoom=null,t.logger.info(s.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:n.SUCCESSED,roomId:o.getRoomId(),userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS}):(t.logger.warn(s.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:n.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS})}))}upgradeToAnchorRoom(i){return r(this,void 0,void 0,(function*(){if(!t.validate("room",i,(()=>i instanceof Ro),!0))return t.logger.error(s.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(t.logger.info(s.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_T,{roomId:i.getRoomId(),userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),this._crtRoom)return t.logger.error(s.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REPERT_JOIN_ROOM};const r=i.getRoomId(),a=this._crtRoom=new io(this._context,this._runtime,r,this._service,this._options,i.livingType,!0,!0,!1,i.getClientSessionId()),c=yield a.__innerInitByIdentityChange();return c!==t.ErrorCode.SUCCESS?(o.warn(`change room identity failed -> code: ${c}`),this._crtRoom=null,t.logger.error(s.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):(a.once($r,(()=>{this._crtRoom=null})),yield this._crtAudienceLivingRoom.__destroy(!1),this._crtAudienceLivingRoom=null,{room:a,code:e.RCRTCCode.SUCCESS,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()})}))}downgradeToAudienceRoom(i){return r(this,void 0,void 0,(function*(){if(t.logger.info(s.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_T,{roomId:i._roomId,userId:this._context.getCurrentId()},{logSource:t.LogSource.RTC}),!i.isMainRoom())return o.error("the `downgradeToAudienceRoom` is disabled in PK room"),t.logger.error(s.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!t.validate("room._roomId",i._roomId,t.notEmptyString,!0))return t.logger.error(s.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.PARAMS_ERROR,msg:"params error -> room._roomId"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return t.logger.error(s.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.REPERT_JOIN_ROOM};const{code:r,data:a}=yield this._context.rtcIdentityChange(i._roomId,Zr.AnchorToViewer,i.getLivingType());if(r!==t.ErrorCode.SUCCESS)return o.error("change room identity error",r),t.logger.error(s.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:n.FAILED,code:e.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};o.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(a)}`),t.logger.info(s.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:n.SUCCESSED,roomData:a},{logSource:t.LogSource.RTC});const c=i.getClientSessionId(),d=new Ro(this._context,this._runtime,this._options,i._roomId,a,i.getLivingType(),!1,c);return this._crtAudienceLivingRoom=d,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:d,code:e.RCRTCCode.SUCCESS,userIds:d.getRemoteUserIds(),RTCTracks:d.getRemoteRTCTracks(),MCUTracks:d.getRemoteMCUTracks(),CDNUris:d.getCDNInfo()}}))}getJoinedRoomInfo(){return r(this,void 0,void 0,(function*(){const{code:r,data:i}=yield this._context.getRTCJoinedUserInfo(this._context.getCurrentId());return r!==t.ErrorCode.SUCCESS?(o.error("getJoinedUserInfo error",r),t.logger.error(s.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:n.FAILED,code:r,msg:"Switch identity error"},{logSource:t.LogSource.RTC}),{code:r}):(t.logger.info(s.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:n.SUCCESSED,roomInfo:i},{logSource:t.LogSource.RTC}),{code:e.RCRTCCode.SUCCESS,data:i})}))}reportSDKInfo(){this._context.reportSDKInfo({"plugin-rtc":"5.5.3"})}}const go="rtcRJoin_data",po="rtcRExit",So="rtcRInfo",mo="rtcUData",To="rtcUDel",Io="rtcSetData",Eo="userSetData",fo="rtcQryData",Lo="rtcDelData",vo="rtcToken",Oo="rtcUserState",Ao="rtcUList",Do="viewerJoinR",No="viewerExitR",yo="rtcPullKv",bo="rtcIdentityChange",ko="rtcInvite",Uo="rtcCancelInvite",Po="rtcInviteAnswer",Mo="rtcEndInvite",xo="rtcQueryJoined",wo="reportsdk";var Bo;!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"}(Bo||(Bo={}));const Vo={[Bo.RtcInput]:["roomType","broadcastType","extraInnerData","needSysChatroom","identityChangeType","joinType","innerDatas","outerDatas"],[Bo.RtcUserListOutput]:["users","token","sessionId","roomInfo"],[Bo.SetUserStatusInput]:["status"],[Bo.RtcSetDataInput]:["interior","target","key","value","objectName","content"],[Bo.RtcUserSetDataInput]:["valueInfo","objectName","content"],[Bo.RtcDataInput]:["interior","target","key","objectName","content"],[Bo.RtcSetOutDataInput]:["target","valueInfo","objectName","content"],[Bo.MCFollowInput]:["state"],[Bo.RtcTokenOutput]:["rtcToken"],[Bo.RtcQryOutput]:["outInfo"],[Bo.RtcQryUserOutDataInput]:["userId"],[Bo.RtcUserOutDataOutput]:["user"],[Bo.RtcQueryListInput]:["order"],[Bo.RtcRoomInfoOutput]:["roomId","roomData","userCount","list"],[Bo.RtcValueInfo]:["key","value"],[Bo.RtcKeyDeleteInput]:["key"],[Bo.RtcNotifyMsg]:["type","time","roomId"],[Bo.RtcPullKV]:["timestamp","roomId"],[Bo.RtcKVOutput]:["entries","bFullUpdate","syncTime"],[Bo.RtcQueryUserJoinedInput]:["userId"],[Bo.RtcQueryUserJoinedOutput]:["info"],[Bo.RtcInviteInput]:["invitedUserId","timeoutTime","invitedRoomId","inviteInfo","inviteSessionId"],[Bo.RtcCancelInviteInput]:["invitedUserId","invitedRoomId","inviteInfo","inviteSessionId"],[Bo.RtcInviteAnswerInput]:["inviteUserId","answerCode","inviteRoomId","inviteSessionId","content","key","value"],[Bo.RtcEndInviteInput]:["inviteRoomId","inviteSessionId","inviteContent","inviteRoomKeys"],[Bo.RtcReportSDKInput]:["sdkInfo"]},$o=`\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 ${Bo.SetUserStatusInput}\n {\n optional int32 status=1;\n }\n message ${Bo.MCFollowInput}\n {\n required string state = 1;\n }\n message ${Bo.RtcQueryListInput}{\n optional int32 order=1;\n }\n message ${Bo.RtcKeyDeleteInput}{\n repeated string key=1;\n }\n message ${Bo.RtcValueInfo}{\n required string key=1;\n required string value=2;\n }\n message RtcUserInfo{\n required string userId=1;\n repeated ${Bo.RtcValueInfo} userData=2; //用户资源信息\n }\n message ${Bo.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 ${Bo.RtcValueInfo} roomData = 2;\n optional int32 userCount = 3;\n repeated RtcUserInfo list=4;\n }\n message ${Bo.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 ${Bo.RtcValueInfo} innerDatas = 7; //用户内部inner数据,角色或者连麦信息等\n repeated ${Bo.RtcValueInfo} outerDatas = 8; //用户内部outer数据,自定义数据结构RtcInput。\n }\n message ${Bo.RtcQryOutput}{\n repeated ${Bo.RtcValueInfo} outInfo=1;\n }\n message ${Bo.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 ${Bo.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 ${Bo.RtcUserSetDataInput} {\n repeated ${Bo.RtcValueInfo} valueInfo = 1;\n required string objectName = 2;\n repeated ${Bo.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 ${Bo.RtcTokenOutput}{\n required string rtcToken=1;\n }\n message ${Bo.RtcSetOutDataInput}{\n required targetType target=1;\n repeated ${Bo.RtcValueInfo} valueInfo=2;\n optional string objectName=3;\n optional string content=4;\n }\n message ${Bo.RtcQryUserOutDataInput}{\n repeated string userId = 1;\n }\n message ${Bo.RtcUserOutDataOutput}{\n repeated RtcUserInfo user = 1;\n }\n message ${Bo.RtcNotifyMsg} \n {\n required int32 type= 1; //(通知类型 1:rtc房间状态KV变更通知)\n optional int64 time= 2; //消息产生时间\n optional string roomId=3; //主播房间id\n }\n message ${Bo.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 ${Bo.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 ${Bo.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 ${Bo.RtcQueryUserJoinedOutput}\n {\n repeated RtcJoinedInfo info = 1;\n }\n message ${Bo.RtcViewerJoinedOutput}\n {\n required string rtcToken=1;\n repeated RtcKVEntity entries = 2;//KV属性对象集合\n optional int64 syncTime = 3;//所有属性的最大时间戳(下次拉取KV时用)。\n }\n message ${Bo.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 ${Bo.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 ${Bo.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 ${Bo.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 ${Bo.RtcReportSDKInput} {\n required string sdkInfo=1; // 用户集成的 sdk 信息,json 格式 {"web-rtc": "4.0.3.7"}\n }\n}\n`,Fo=(e,t,r,o,i,s)=>{const n=i?Object.keys(i).map((t=>e.encode(Bo.RtcValueInfo,{key:t,value:i[t]},!0))):void 0,a=s?Object.keys(s).map((t=>e.encode(Bo.RtcValueInfo,{key:t,value:s[t]},!0))):void 0;return e.encode(Bo.RtcInput,{roomType:t,broadcastType:r,joinType:o,innerDatas:n,outerDatas:a})},Go=(e,r)=>{const o=e.decode(Bo.RtcUserListOutput,r),{users:i,token:s,sessionId:n,roomInfo:a,entries:c,offlineKickTime:d}=o,u={};return t.forEach(i,(e=>{const{userId:r,userData:o}=e,i={};t.forEach(o,(e=>{const{key:t,value:r}=e;i[t]=r})),u[r]=i})),{users:u,token:s,sessionId:n,roomInfo:a,kvEntries:c,offlineKickTime:d}};class Ko{constructor(e,t){this.context=e,this.codec=t}joinRTCRoom(e,o,i,s,n,a){return r(this,void 0,void 0,(function*(){const r=Fo(this.codec,o,i,s,n,a),{code:c,buffer:d}=yield this.context.rtcSignaling(e,go,!0,r);let u;return c===t.ErrorCode.SUCCESS&&d&&(u=Go(this.codec,d)),{code:c,data:u}}))}quitRTCRoom(e){return r(this,void 0,void 0,(function*(){const t=this.codec.encode(Bo.SetUserStatusInput,{status:0}),{code:r}=yield this.context.rtcSignaling(e,po,!0,t);return r}))}getRTCRoomInfo(e){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcQueryListInput,{order:2}),{code:o,buffer:i}=yield this.context.rtcSignaling(e,So,!0,r);let s;return o===t.ErrorCode.SUCCESS&&i&&(s=this.codec.decode(Bo.RtcRoomInfoOutput,i)),{code:o,data:s}}))}getRTCUserInfoList(e){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcQueryListInput,{order:2}),{code:o,buffer:i}=yield this.context.rtcSignaling(e,mo,!0,r);let s;if(o===t.ErrorCode.SUCCESS&&i){s={users:Go(this.codec,i).users}}return{code:o,data:s}}))}getRTCUserInfo(e){throw new Error("Method not implemented.")}removeRTCUserInfo(e,t){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcKeyDeleteInput,{key:t}),{code:o}=yield this.context.rtcSignaling(e,To,!1,r);return o}))}setRTCData(e,t,o,i,s,n){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcSetDataInput,{interior:i,target:s,key:t,value:o,objectName:null==n?void 0:n.name,content:null==n?void 0:n.content}),{code:a}=yield this.context.rtcSignaling(e,Io,!1,r);return a}))}setRTCTotalRes(e,t,o,i,s=""){return r(this,void 0,void 0,(function*(){const r={objectName:i,content:this.codec.encode(Bo.RtcValueInfo,{key:t.name,value:t.content},!0),valueInfo:[this.codec.encode(Bo.RtcValueInfo,{key:"uris",value:o},!0),this.codec.encode(Bo.RtcValueInfo,{key:"mcu_uris",value:s},!0)]},n=this.codec.encode(Bo.RtcUserSetDataInput,r),{code:a}=yield this.context.rtcSignaling(e,Eo,!0,n);return a}))}setRTCCDNUris(e,t,o){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcUserSetDataInput,{objectName:t,valueInfo:this.codec.encode(Bo.RtcValueInfo,{key:"cdn_uris",value:o},!0)}),{code:i}=yield this.context.rtcSignaling(e,Eo,!0,r);return i}))}getRTCData(e,o,i,s){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcDataInput,{interior:i,target:s,key:o}),{code:n,buffer:a}=yield this.context.rtcSignaling(e,fo,!0,r);if(n!==t.ErrorCode.SUCCESS||!a)return{code:n};const{outInfo:c}=this.codec.decode(Bo.RtcQryOutput,a),d={};return c.forEach((e=>{d[e.key]=e.value})),{code:n,data:d}}))}removeRTCData(e,t,o,i,s){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcDataInput,{interior:o,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,Lo,!1,r);return n}))}setRTCOutData(e,t,o,i){return r(this,void 0,void 0,(function*(){throw new Error("JSEngine's method not implemented.")}))}getRTCOutData(e,t){return r(this,void 0,void 0,(function*(){throw new Error("JSEngine's method not implemented.")}))}getRTCToken(e,o,i){return r(this,void 0,void 0,(function*(){const r=Fo(this.codec,o,i),{code:s,buffer:n}=yield this.context.rtcSignaling(e,vo,!0,r);if(s!==t.ErrorCode.SUCCESS||!n)return{code:s};const{rtcToken:a}=this.codec.decode(Bo.RtcTokenOutput,n);return{code:s,data:{rtcToken:a}}}))}setRTCState(e,t){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.MCFollowInput,{state:t}),{code:o}=yield this.context.rtcSignaling(e,Oo,!0,r);return o}))}getRTCUserList(e){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcQueryListInput,{order:2}),{code:o,buffer:i}=yield this.context.rtcSignaling(e,Ao,!0,r);if(o!==t.ErrorCode.SUCCESS||!i)return{code:o};return{code:o,data:Go(this.codec,i)}}))}joinLivingRoomAsAudience(e,o,i){var n,a;return r(this,void 0,void 0,(function*(){const r=Fo(this.codec,o,i),c=At.getMemo(),d={dur:0,cod:0,rid:"",rtp:o,csnid:"",snid:"",time:0,cr:"unknown",net:"unknown",uid:""};c.qualityJoinRoomReportData=d,c.joinRoomData={start:Date.now()};const{code:u,buffer:_}=yield this.context.rtcSignaling(e,Do,!0,r);if(u!==t.ErrorCode.SUCCESS||!_)return{code:u};const{rtcToken:l,entries:R}=this.codec.decode(Bo.RtcViewerJoinedOutput,_),C=Date.now(),h=JSON.stringify(Object.assign(c.qualityJoinRoomReportData,{dur:C-((null===(n=c.joinRoomData)||void 0===n?void 0:n.start)||0),cod:u,rid:e,csnid:null===(a=c.clientData)||void 0===a?void 0:a.clientSessionId,snid:pt(e,R).sessionId,time:C,uid:this.context.getCurrentId()}));return t.reportLog(t.LogLevel.STATISTICS,s.L_QS_JOIN_ROOM_S,h,t.LogSource.RTC),{code:u,data:{token:l,kvEntries:R}}}))}quitLivingRoomAsAudience(e){return r(this,void 0,void 0,(function*(){const t=this.codec.encode(Bo.SetUserStatusInput,{status:0}),{code:r}=yield this.context.rtcSignaling(e,No,!0,t);return r}))}rtcIdentityChange(e,o,i){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcInput,{roomType:zt.LIVE,broadcastType:i,identityChangeType:o,needSysChatroom:!1}),{code:s,buffer:n}=yield this.context.rtcSignaling(e,bo,!0,r);if(s!==t.ErrorCode.SUCCESS||!n)return{code:s};return{code:s,data:Go(this.codec,n)}}))}requestRoomPK(e){return r(this,void 0,void 0,(function*(){const{invitedRoomId:t,invitedUserId:r,inviteSessionId:o,inviteTimeout:i,inviteInfo:s,roomId:n}=e,a=this.codec.encode(Bo.RtcInviteInput,{invitedRoomId:t,invitedUserId:r,inviteSessionId:o,timeoutTime:i,inviteInfo:s}),{code:c}=yield this.context.rtcSignaling(n,ko,!0,a);return c}))}cancelRoomPK(e){return r(this,void 0,void 0,(function*(){const{invitedRoomId:t,invitedUserId:r,inviteSessionId:o,inviteInfo:i,roomId:s}=e,n=this.codec.encode(Bo.RtcCancelInviteInput,{invitedRoomId:t,invitedUserId:r,inviteSessionId:o,inviteInfo:i}),{code:a}=yield this.context.rtcSignaling(s,Uo,!0,n);return a}))}responseRoomPK(e){return r(this,void 0,void 0,(function*(){const{inviteUserId:t,inviteRoomId:r,inviteSessionId:o,content:i,key:s,value:n,agree:a,roomId:c}=e,d=this.codec.encode(Bo.RtcInviteAnswerInput,{inviteUserId:t,inviteRoomId:r,inviteSessionId:o,content:i,key:s,value:n,answerCode:a?1:0}),{code:u}=yield this.context.rtcSignaling(c,Po,!0,d);return u}))}endRoomPK(e){return r(this,void 0,void 0,(function*(){const{endRoomId:t,sessionId:r,content:o,keys:i,roomId:s}=e,n=this.codec.encode(Bo.RtcEndInviteInput,{inviteRoomId:t,inviteSessionId:r,inviteContent:o,inviteRoomKeys:i}),{code:a}=yield this.context.rtcSignaling(s,Mo,!0,n);return a}))}getRTCJoinedUserInfo(e){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcQueryUserJoinedInput,{userId:e}),{code:o,buffer:i}=yield this.context.rtcSignaling("",xo,!0,r);if(o!==t.ErrorCode.SUCCESS||!i)return{code:o};return{code:o,data:(this.codec.decode(Bo.RtcQueryUserJoinedOutput,i).info||[]).map((e=>({deviceId:e.deviceId,roomId:e.roomId,joinTime:mt(e.joinTime)})))}}))}pullRTCRoomEntry(e){return r(this,void 0,void 0,(function*(){const r=this.codec.encode(Bo.RtcPullKV,{timestamp:0,roomId:e}),{code:o,buffer:i}=yield this.context.rtcSignaling(e,yo,!0,r);if(o!==t.ErrorCode.SUCCESS)return{code:o};const s=this.codec.decode(Bo.RtcKVOutput,i);let{entries:n,syncTime:a}=s;return n=(n||[]).map((e=>Object.assign(Object.assign({},e),{timestamp:mt(e.timestamp)}))),{code:o,data:{kvEntries:n,syncTime:mt(a)}}}))}decodeRtcNotify(e){const{time:t,type:r,roomId:o}=this.codec.decode(Bo.RtcNotifyMsg,e);return{time:mt(t),type:r,roomId:o}}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(Bo.RtcReportSDKInput,{sdkInfo:JSON.stringify(e)});this.context.rtcSignaling("",wo,!0,t)}}const Ho={tag:"RCRTC",verify:e=>"browser"!==e.tag?(o.error(`RCRTC Plugin is not support the runtime '${e.tag}'`),!1):ze?(t.VersionManage.add("plugin-rtc","5.5.3"),!!t.VersionManage.validEngine("^5.5.5-beem")||(o.error(`The current engine version '${t.VersionManage.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,r,i={}){var n,a,c,d,u,_,l,R;return t.logger.init({localLogLevel:i.logLevel,customLogPrint:i.logStdout}),t.logger.warn(s.L_INDEX_INSTALL_RTC_PLUGIN_O,{"RCRTC Version":"5.5.3",Commit:"07c9cc6a285a9f5cd59a94126514dc54495a17c2","browserInfo.browser":_t.browser,"browserInfo.supportsUnifiedPlan":_t.supportsUnifiedPlan,"browserInfo.version":_t.version}),o.setLogLevel(i.logLevel),o.setLogStdout(i.logStdout),o.warn("RCRTC Version: 5.5.3, Commit: 07c9cc6a285a9f5cd59a94126514dc54495a17c2"),o.warn(`browserInfo.browser -> ${_t.browser}`),o.warn(`browserInfo.supportsUnifiedPlan -> ${_t.supportsUnifiedPlan}`),o.warn(`browserInfo.version -> ${_t.version}`),t.assert("options.mediaServer",i.mediaServer,(e=>!(!t.isHttpUrl(e)||"https:"===location.protocol&&!/^https/.test(e)))),t.assert("options.timeout",i.timeout,(e=>t.isNumber(e)&&e>=5e3&&e<=3e4)),t.assert("options.pingGap",i.pingGap,(e=>t.isNumber(e)&&e>=3e3&&e<=1e4)),(null==i?void 0:i.audio)&&((null===(n=i.audio)||void 0===n?void 0:n.workletModule)&&(Pe.workletModule=null===(a=i.audio)||void 0===a?void 0:a.workletModule),(null===(c=i.audio)||void 0===c?void 0:c.workletWasm)&&(Pe.workletWasm=null===(d=i.audio)||void 0===d?void 0:d.workletWasm),(null===(u=i.audio)||void 0===u?void 0:u.workletModule)&&(null===(_=i.audio)||void 0===_?void 0:_.workletWasm)&&(Pe.isOpen=!0),void 0!==(null===(l=i.audio)||void 0===l?void 0:l.isOpen)&&(Pe.isOpen=null===(R=i.audio)||void 0===R?void 0:R.isOpen)),new ho(new Ko(e,e.createCodec(Vo,$o)),r,i)}},jo={transResolution:at,transFrameRate:ut,parseTrackId:rt,ifSupportLocalFileTrack:lt,ifSupportScreenShare:Rt};e.RCAbstractRoom=Fr,e.RCAudienceClient=co,e.RCAudienceLivingRoom=Ro,e.RCCameraVideoTrack=Ge,e.RCLivingRoom=io,e.RCLocalAudioTrack=xe,e.RCLocalFileAudioTrack=$e,e.RCLocalFileTrack=Be,e.RCLocalFileVideoTrack=Ve,e.RCLocalTrack=Me,e.RCLocalVideoTrack=we,e.RCMCUConfigBuilder=Wr,e.RCMediaStreamCapture=Co,e.RCMicphoneAudioTrack=Fe,e.RCRTCClient=ho,e.RCRTCRoom=so,e.RCRemoteAudioTrack=Je,e.RCRemoteTrack=je,e.RCRemoteVideoTrack=qe,e.RCScreenAudioTrack=He,e.RCScreenVideoTrack=Ke,e.RCTag={DEFAULT:"RongCloudRTC"},e.RCTrack=ye,e.device=Ae,e.helper=jo,e.installer=Ho,Object.defineProperty(e,"__esModule",{value:!0})}));
|