@rongcloud/plugin-rtc 5.5.5 → 5.5.6
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/core/codec/RTCContext.d.ts +2 -2
- package/dist/core/command/helper.d.ts +8 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/index.umd.js +1 -1
- package/package.json +2 -2
package/dist/index.esm.js
CHANGED
|
@@ -12,4 +12,4 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
|
12
12
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
13
13
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
14
14
|
PERFORMANCE OF THIS SOFTWARE.
|
|
15
|
-
***************************************************************************** */function f(e,t,r,i){return new(r||(r=Promise))((function(o,s){function n(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,a)}c((i=i.apply(e,t||[])).next())}))}const v=new e("RCRTC");var O,L,A;!function(e){e[e.SUCCESS=1e4]="SUCCESS",e[e.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",e[e.PARAMS_ERROR=50001]="PARAMS_ERROR",e[e.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",e[e.NOT_IN_ROOM=50003]="NOT_IN_ROOM",e[e.SERVICE_INVALID=50004]="SERVICE_INVALID",e[e.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",e[e.SIGNAL_ERROR=53001]="SIGNAL_ERROR",e[e.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",e[e.REQUEST_FAILED=53004]="REQUEST_FAILED",e[e.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",e[e.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",e[e.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",e[e.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",e[e.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",e[e.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",e[e.BROWSER_PERMISSION_DENIED=53012]="BROWSER_PERMISSION_DENIED",e[e.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",e[e.INVALID_TAGS=53014]="INVALID_TAGS",e[e.INVALID_USER_ID=53015]="INVALID_USER_ID",e[e.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",e[e.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",e[e.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",e[e.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",e[e.TRACK_NOT_READY=53020]="TRACK_NOT_READY",e[e.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",e[e.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",e[e.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",e[e.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",e[e.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",e[e.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",e[e.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",e[e.SIGNAL_JOIN_RTC_ROOM_REFUSED=53028]="SIGNAL_JOIN_RTC_ROOM_REFUSED",e[e.NO_PERMISSION_TO_USE_REQUESTED_DEVICE=53029]="NO_PERMISSION_TO_USE_REQUESTED_DEVICE",e[e.THE_FUNCTION_IS_DISABLED_IN_PKROOM=53030]="THE_FUNCTION_IS_DISABLED_IN_PKROOM",e[e.SOME_TRACKS_PUBLISH_FAILED=53031]="SOME_TRACKS_PUBLISH_FAILED",e[e.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO=53032]="MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO",e[e.JWT_TIME_OUT=1004]="JWT_TIME_OUT",e[e.SYSTEM_PERMISSION_DENIED=53033]="SYSTEM_PERMISSION_DENIED",e[e.PUBLISH_TRACKS_IS_INVALID=53034]="PUBLISH_TRACKS_IS_INVALID"}(O||(O={})),function(e){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_TIMEOUT_O="L-pinger_timeout-O",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"}(L||(L={})),function(e){e.FAILED="fail",e.SUCCESSED="success",e.TIMEOUT="timeout",e.INFO="info"}(A||(A={}));let N=!0,D=!0;function k(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function y(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,o=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return o.apply(this,arguments);const s=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,s),o.apply(this,[e,s])};const s=i.removeEventListener;i.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 i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function U(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(N=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function b(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(D=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function P(){if("object"==typeof window){if(N)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function M(e,t){D&&console.warn(e+" is deprecated, please use "+t+" instead.")}function x(e){return"[object Object]"===Object.prototype.toString.call(e)}function w(e){return x(e)?Object.keys(e).reduce((function(t,r){const i=x(e[r]),o=i?w(e[r]):e[r],s=i&&!Object.keys(o).length;return void 0===o||s?t:Object.assign(t,{[r]:o})}),{}):e}function B(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?B(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{B(e,e.get(t),r)}))})))}function V(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",o=new Map;if(null===t)return o;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&B(e,r,o)}))})),o}const $=P;function F(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const o=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[o("min",r)]=i.ideal,t.optional.push(e),e={},e[o("max",r)]=i.ideal,t.optional.push(e)):(e[o("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[o("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[o(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},o=function(e,o){if(t.version>=61)return o(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let 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=i(e.video),$("chrome: "+JSON.stringify(e)),o(e)}))}e.video=i(e.video)}return $("chrome: "+JSON.stringify(e)),o(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,i){o(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return o(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 G(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function K(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const o=new Event("track");o.track=r.track,o.receiver=i,o.transceiver={receiver:i},o.streams=[t.stream],this.dispatchEvent(o)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const o=new Event("track");o.track=r,o.receiver=i,o.transceiver={receiver:i},o.streams=[t.stream],this.dispatchEvent(o)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else y(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function H(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let o=r.apply(this,arguments);return o||(o=t(this,e),this._senders.push(o)),o};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function j(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,i]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const o=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 i=function(e){r(s(o(e)))};return t.apply(this,[i,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(s(o(t)))},r])})).then(r,i)}}function J(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=>V(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),y(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>V(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,i;return this.getSenders().forEach((r=>{r.track===e&&(t?i=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?i=!0:r=t),t.track===e))),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function W(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();r.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const o=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]})),o.apply(this,arguments)}}function q(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return W(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const o=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],o=e._streams[i.id];r=r.replace(new RegExp(o.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function n(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],o=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),o.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},o.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const o=this.getSenders().find((e=>e.track===t));if(o)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 i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=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]=i[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=n(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=c.get.apply(this);return""===e.type?e: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 Y(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function z(e,t){y(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var Q=Object.freeze({__proto__:null,shimMediaStream:G,shimOnTrack:K,shimGetSendersWithDtmf:H,shimGetStats:j,shimSenderReceiverGetStats:J,shimAddTrackRemoveTrackWithNative:W,shimAddTrackRemoveTrack:q,shimPeerConnection:Y,fixNegotiationNeeded:z,shimGetUserMedia:F,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const i=r.video&&r.video.width,o=r.video&&r.video.height,s=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},i&&(r.video.mandatory.maxWidth=i),o&&(r.video.mandatory.maxHeight=o),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});var Z,X,ee=(Z=function(e){var t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},t.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},t.getDescription=function(e){var r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){var r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((function(e){return 0===e.indexOf(r)}))},t.parseCandidate=function(e){for(var t,r={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},i=8;i<t.length;i+=2)switch(t[i]){case"raddr":r.relatedAddress=t[i+1];break;case"rport":r.relatedPort=parseInt(t[i+1],10);break;case"tcptype":r.tcpType=t[i+1];break;case"ufrag":r.ufrag=t[i+1],r.usernameFragment=t[i+1];break;default:r[t[i]]=t[i+1]}return r},t.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substr(14).split(" ")},t.parseRtpMap=function(e){var t=e.substr(9).split(" "),r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){for(var t,r={},i=e.substr(e.indexOf(" ")+1).split(";"),o=0;o<i.length;o++)r[(t=i[o].trim().split("="))[0].trim()]=t[1];return r},t.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var i=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){var t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r},t.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},t.getMid=function(e){var r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substr(6)},t.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){var r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){var t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;var t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){var i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],o=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&o?{usernameFragment:i.substr(12),password:o.substr(10)}:null},t.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},t.parseRtpParameters=function(e){for(var r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" "),o=3;o<i.length;o++){var s=i[o],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 i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" UDP/TLS/RTP/SAVPF ",i+=r.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((function(e){i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));var o=0;return r.codecs.forEach((function(e){e.maxptime>o&&(o=e.maxptime)})),o>0&&(i+="a=maxptime:"+o+"\r\n"),i+="a=rtcp-mux\r\n",r.headerExtensions&&r.headerExtensions.forEach((function(e){i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){var r,i=[],o=t.parseRtpParameters(e),s=-1!==o.fecMechanisms.indexOf("RED"),n=-1!==o.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]),o.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&r&&(t.rtx={ssrc:r}),i.push(t),s&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:n?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&c&&i.push({ssrc:c});var _=t.matchPrefix(e,"b=");return _.length&&(_=0===_[0].indexOf("b=TIAS:")?parseInt(_[0].substr(7),10):0===_[0].indexOf("b=AS:")?1e3*parseInt(_[0].substr(5),10)*.95-16e3:void 0,i.forEach((function(e){e.maxBitrate=_}))),i},t.parseRtcpParameters=function(e){var r={},i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);var o=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=o.length>0,r.compound=0===o.length;var s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.parseMsid=function(e){var r,i=t.matchPrefix(e,"a=msid:");if(1===i.length)return{stream:(r=i[0].substr(7).split(" "))[0],track:r[1]};var o=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return o.length>0?{stream:(r=o[0].value.split(" "))[0],track:r[1]}:void 0},t.parseSctpDescription=function(e){var r,i=t.parseMLine(e),o=t.matchPrefix(e,"a=max-message-size:");o.length>0&&(r=parseInt(o[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:i.fmt,maxMessageSize:r};if(t.matchPrefix(e,"a=sctpmap:").length>0){var n=t.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(n[0],10),protocol:n[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){var r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,r,i){var o=void 0!==r?r:2;return"v=0\r\no="+(i||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,r,i,o){var s=t.writeRtpDescription(e.kind,r);if(s+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===i?"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:"+o.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 i=t.splitLines(e),o=0;o<i.length;o++)switch(i[o]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[o].substr(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substr(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){var r=t.splitLines(e)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){var r=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var r=t.splitLines(e),i=0;i<r.length;i++)if(r[i].length<2||"="!==r[i].charAt(1))return!1;return!0},e.exports=t},Z(X={exports:{}},X.exports),X.exports);function te(e,t,r,i,o){var s=ee.writeRtpDescription(e.kind,t);if(s+=ee.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=ee.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":o||"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:"+(i?i.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:"+ee.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+ee.localCName+"\r\n"),s}function re(e,t){var r={codecs:[],headerExtensions:[],fecMechanisms:[]},i=function(e,t){e=parseInt(e,10);for(var r=0;r<t.length;r++)if(t[r].payloadType===e||t[r].preferredPayloadType===e)return t[r]},o=function(e,t,r,o){var s=i(e.parameters.apt,r),n=i(t.parameters.apt,o);return s&&n&&s.name.toLowerCase()===n.name.toLowerCase()};return e.codecs.forEach((function(i){for(var s=0;s<t.codecs.length;s++){var n=t.codecs[s];if(i.name.toLowerCase()===n.name.toLowerCase()&&i.clockRate===n.clockRate){if("rtx"===i.name.toLowerCase()&&i.parameters&&n.parameters.apt&&!o(i,n,e.codecs,t.codecs))continue;(n=JSON.parse(JSON.stringify(n))).numChannels=Math.min(i.numChannels,n.numChannels),r.codecs.push(n),n.rtcpFeedback=n.rtcpFeedback.filter((function(e){for(var t=0;t<i.rtcpFeedback.length;t++)if(i.rtcpFeedback[t].type===e.type&&i.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var i=0;i<t.headerExtensions.length;i++){var o=t.headerExtensions[i];if(e.uri===o.uri){r.headerExtensions.push(o);break}}})),r}function ie(e,t,r){return-1!=={offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[t][e].indexOf(r)}function oe(e,t){var r=e.getRemoteCandidates().find((function(e){return t.foundation===e.foundation&&t.ip===e.ip&&t.port===e.port&&t.priority===e.priority&&t.protocol===e.protocol&&t.type===e.type}));return r||e.addRemoteCandidate(t),!r}function se(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 ne=function(e,t){function r(t,r){r.addTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function i(t,r,i,o){var s=new Event("track");s.track=r,s.receiver=i,s.transceiver={receiver:i},s.streams=o,e.setTimeout((function(){t._dispatchEvent("track",s)}))}var o=function(r){var i=this,o=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){i[e]=o[e].bind(o)})),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 se("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var i=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var o="string"==typeof i;return o&&(i=[i]),i=i.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||r?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(r=!0,!0)})),delete e.url,e.urls=o?i[0]:i,!!i.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=ee.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(o.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(o.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),o.prototype.onicecandidate=null,o.prototype.onaddstream=null,o.prototype.ontrack=null,o.prototype.onremovestream=null,o.prototype.onsignalingstatechange=null,o.prototype.oniceconnectionstatechange=null,o.prototype.onconnectionstatechange=null,o.prototype.onicegatheringstatechange=null,o.prototype.onnegotiationneeded=null,o.prototype.ondatachannel=null,o.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},o.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},o.prototype.getConfiguration=function(){return this._config},o.prototype.getLocalStreams=function(){return this.localStreams},o.prototype.getRemoteStreams=function(){return this.remoteStreams},o.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,i={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&r)i.iceTransport=this.transceivers[0].iceTransport,i.dtlsTransport=this.transceivers[0].dtlsTransport;else{var o=this._createIceAndDtlsTransports();i.iceTransport=o.iceTransport,i.dtlsTransport=o.dtlsTransport}return t||this.transceivers.push(i),i},o.prototype.addTrack=function(t,r){if(this._isClosed)throw se("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var i;if(this.transceivers.find((function(e){return e.track===t})))throw se("InvalidAccessError","Track already exists.");for(var o=0;o<this.transceivers.length;o++)this.transceivers[o].track||this.transceivers[o].kind!==t.kind||(i=this.transceivers[o]);return i||(i=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),i.track=t,i.stream=r,i.rtpSender=new e.RTCRtpSender(t,i.dtlsTransport),i.rtpSender},o.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var i=e.clone();e.getTracks().forEach((function(e,t){var r=i.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),i.getTracks().forEach((function(e){r.addTrack(e,i)}))}},o.prototype.removeTrack=function(t){if(this._isClosed)throw se("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 se("InvalidAccessError","Sender was not created by this connection.");var i=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(i)&&this.localStreams.indexOf(i)>-1&&this.localStreams.splice(this.localStreams.indexOf(i),1),this._maybeFireNegotiationNeeded()},o.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)}))},o.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},o.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},o.prototype._createIceGatherer=function(t,r){var i=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var o=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(o,"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;o.state=r?"completed":"gathering",null!==i.transceivers[t].bufferedCandidateEvents&&i.transceivers[t].bufferedCandidateEvents.push(e)},o.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),o},o.prototype._gather=function(t,r){var i=this,o=this.transceivers[r].iceGatherer;if(!o.onlocalcandidate){var s=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,o.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),o.onlocalcandidate=function(e){if(!(i.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"!==o.state&&"gathering"!==o.state||(o.state="completed");else{"new"===o.state&&(o.state="gathering"),n.component=1,n.ufrag=o.getLocalParameters().usernameFragment;var c=ee.writeCandidate(n);s.candidate=Object.assign(s.candidate,ee.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=ee.getMediaSections(i._localDescription.sdp);d[s.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",i._localDescription.sdp=ee.getDescription(i._localDescription.sdp)+d.join("");var _=i.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==i.iceGatheringState&&(i.iceGatheringState="gathering",i._emitGatheringStateChange()),a||i._dispatchEvent("icecandidate",s),_&&(i._dispatchEvent("icecandidate",new Event("icecandidate")),i.iceGatheringState="complete",i._emitGatheringStateChange())}},e.setTimeout((function(){s.forEach((function(e){o.onlocalcandidate(e)}))}),0)}},o.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var i=new e.RTCDtlsTransport(r);return i.ondtlsstatechange=function(){t._updateConnectionState()},i.onerror=function(){Object.defineProperty(i,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:i}},o.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var r=this.transceivers[e].iceTransport;r&&(delete r.onicestatechange,delete this.transceivers[e].iceTransport);var i=this.transceivers[e].dtlsTransport;i&&(delete i.ondtlsstatechange,delete i.onerror,delete this.transceivers[e].dtlsTransport)},o.prototype._transceive=function(e,r,i){var o=re(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(o.encodings=e.sendEncodingParameters,o.rtcp={cname:ee.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(o.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(o)),i&&e.rtpReceiver&&o.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?o.encodings=e.recvEncodingParameters:o.encodings=[{}],o.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(o.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(o.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(o))},o.prototype.setLocalDescription=function(e){var t,r,i=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(se("TypeError",'Unsupported type "'+e.type+'"'));if(!ie("setLocalDescription",e.type,i.signalingState)||i._isClosed)return Promise.reject(se("InvalidStateError","Can not set local "+e.type+" in state "+i.signalingState));if("offer"===e.type)t=ee.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=ee.parseRtpParameters(e);i.transceivers[t].localCapabilities=r})),i.transceivers.forEach((function(e,t){i._gather(e.mid,t)}));else if("answer"===e.type){t=ee.splitSections(i._remoteDescription.sdp),r=t.shift();var o=ee.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var s=i.transceivers[t],n=s.iceGatherer,a=s.iceTransport,c=s.dtlsTransport,d=s.localCapabilities,_=s.remoteCapabilities;if(!(ee.isRejected(e)&&0===ee.matchPrefix(e,"a=bundle-only").length)&&!s.rejected){var u=ee.getIceParameters(e,r),l=ee.getDtlsParameters(e,r);o&&(l.role="server"),i.usingBundle&&0!==t||(i._gather(s.mid,t),"new"===a.state&&a.start(n,u,o?"controlling":"controlled"),"new"===c.state&&c.start(l));var h=re(d,_);i._transceive(s,h.codecs.length>0,!1)}}))}return i._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?i._updateSignalingState("have-local-offer"):i._updateSignalingState("stable"),Promise.resolve()},o.prototype.setRemoteDescription=function(o){var s=this;if(-1===["offer","answer"].indexOf(o.type))return Promise.reject(se("TypeError",'Unsupported type "'+o.type+'"'));if(!ie("setRemoteDescription",o.type,s.signalingState)||s._isClosed)return Promise.reject(se("InvalidStateError","Can not set remote "+o.type+" in state "+s.signalingState));var n={};s.remoteStreams.forEach((function(e){n[e.id]=e}));var a=[],c=ee.splitSections(o.sdp),d=c.shift(),_=ee.matchPrefix(d,"a=ice-lite").length>0,u=ee.matchPrefix(d,"a=group:BUNDLE ").length>0;s.usingBundle=u;var l=ee.matchPrefix(d,"a=ice-options:")[0];return s.canTrickleIceCandidates=!!l&&l.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(i,c){var l=ee.splitLines(i),h=ee.getKind(i),R=ee.isRejected(i)&&0===ee.matchPrefix(i,"a=bundle-only").length,p=l[0].substr(2).split(" ")[2],m=ee.getDirection(i,d),C=ee.parseMsid(i),T=ee.getMid(i)||ee.generateIdentifier();if(R||"application"===h&&("DTLS/SCTP"===p||"UDP/DTLS/SCTP"===p))s.transceivers[c]={mid:T,kind:h,protocol:p,rejected:!0};else{var I,E,S,g,f,v,O,L,A;!R&&s.transceivers[c]&&s.transceivers[c].rejected&&(s.transceivers[c]=s._createTransceiver(h,!0));var N,D,k=ee.parseRtpParameters(i);R||(N=ee.getIceParameters(i,d),(D=ee.getDtlsParameters(i,d)).role="client"),O=ee.parseRtpEncodingParameters(i);var y=ee.parseRtcpParameters(i),U=ee.matchPrefix(i,"a=end-of-candidates",d).length>0,b=ee.matchPrefix(i,"a=candidate:").map((function(e){return ee.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===o.type||"answer"===o.type)&&!R&&u&&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"!==o.type||R){if("answer"===o.type&&!R){E=(I=s.transceivers[c]).iceGatherer,S=I.iceTransport,g=I.dtlsTransport,f=I.rtpReceiver,v=I.sendEncodingParameters,L=I.localCapabilities,s.transceivers[c].recvEncodingParameters=O,s.transceivers[c].remoteCapabilities=k,s.transceivers[c].rtcpParameters=y,b.length&&"new"===S.state&&(!_&&!U||u&&0!==c?b.forEach((function(e){oe(I.iceTransport,e)})):S.setRemoteCandidates(b)),u&&0!==c||("new"===S.state&&S.start(E,N,"controlling"),"new"===g.state&&g.start(D)),!re(I.localCapabilities,I.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&I.sendEncodingParameters[0].rtx&&delete I.sendEncodingParameters[0].rtx,s._transceive(I,"sendrecv"===m||"recvonly"===m,"sendrecv"===m||"sendonly"===m),!f||"sendrecv"!==m&&"sendonly"!==m?delete I.rtpReceiver:(A=f.track,C?(n[C.stream]||(n[C.stream]=new e.MediaStream),r(A,n[C.stream]),a.push([A,f,n[C.stream]])):(n.default||(n.default=new e.MediaStream),r(A,n.default),a.push([A,f,n.default])))}}else{(I=s.transceivers[c]||s._createTransceiver(h)).mid=T,I.iceGatherer||(I.iceGatherer=s._createIceGatherer(c,u)),b.length&&"new"===I.iceTransport.state&&(!U||u&&0!==c?b.forEach((function(e){oe(I.iceTransport,e)})):I.iceTransport.setRemoteCandidates(b)),L=e.RTCRtpReceiver.getCapabilities(h),t<15019&&(L.codecs=L.codecs.filter((function(e){return"rtx"!==e.name}))),v=I.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var P,M=!1;if("sendrecv"===m||"sendonly"===m){if(M=!I.rtpReceiver,f=I.rtpReceiver||new e.RTCRtpReceiver(I.dtlsTransport,h),M)A=f.track,C&&"-"===C.stream||(C?(n[C.stream]||(n[C.stream]=new e.MediaStream,Object.defineProperty(n[C.stream],"id",{get:function(){return C.stream}})),Object.defineProperty(A,"id",{get:function(){return C.track}}),P=n[C.stream]):(n.default||(n.default=new e.MediaStream),P=n.default)),P&&(r(A,P),I.associatedRemoteMediaStreams.push(P)),a.push([A,f,P])}else I.rtpReceiver&&I.rtpReceiver.track&&(I.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===I.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),I.associatedRemoteMediaStreams=[]);I.localCapabilities=L,I.remoteCapabilities=k,I.rtpReceiver=f,I.rtcpParameters=y,I.sendEncodingParameters=v,I.recvEncodingParameters=O,s._transceive(s.transceivers[c],!1,M)}}})),void 0===s._dtlsRole&&(s._dtlsRole="offer"===o.type?"active":"passive"),s._remoteDescription={type:o.type,sdp:o.sdp},"offer"===o.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 o=new Event("addstream");o.stream=r,e.setTimeout((function(){s._dispatchEvent("addstream",o)}))}a.forEach((function(e){var t=e[0],o=e[1];r.id===e[2].id&&i(s,t,o,[r])}))}})),a.forEach((function(e){e[2]||i(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()},o.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")},o.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},o.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))},o.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)}},o.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)}},o.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(se("InvalidStateError","Can not call createOffer after close"));var i=r.transceivers.filter((function(e){return"audio"===e.kind})).length,o=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&&(i=!0===s.offerToReceiveAudio?1:!1===s.offerToReceiveAudio?0:s.offerToReceiveAudio),void 0!==s.offerToReceiveVideo&&(o=!0===s.offerToReceiveVideo?1:!1===s.offerToReceiveVideo?0:s.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--i<0&&(e.wantReceive=!1):"video"===e.kind&&--o<0&&(e.wantReceive=!1)}));i>0||o>0;)i>0&&(r._createTransceiver("audio"),i--),o>0&&(r._createTransceiver("video"),o--);var n=ee.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(i,o){var s=i.track,n=i.kind,a=i.mid||ee.generateIdentifier();i.mid=a,i.iceGatherer||(i.iceGatherer=r._createIceGatherer(o,r.usingBundle));var c=e.RTCRtpSender.getCapabilities(n);t<15019&&(c.codecs=c.codecs.filter((function(e){return"rtx"!==e.name}))),c.codecs.forEach((function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1"),i.remoteCapabilities&&i.remoteCapabilities.codecs&&i.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(i.remoteCapabilities&&i.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=i.sendEncodingParameters||[{ssrc:1001*(2*o+1)}];s&&t>=15019&&"video"===n&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),i.wantReceive&&(i.rtpReceiver=new e.RTCRtpReceiver(i.dtlsTransport,n)),i.localCapabilities=c,i.sendEncodingParameters=d})),"max-compat"!==r._config.bundlePolicy&&(n+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),n+="a=ice-options:trickle\r\n",r.transceivers.forEach((function(e,t){n+=te(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="+ee.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)},o.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(se("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(se("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var i=ee.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.usingBundle&&(i+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),i+="a=ice-options:trickle\r\n";var o=ee.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,s){if(!(s+1>o)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?i+="m=application 0 DTLS/SCTP 5000\r\n":i+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?i+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(i+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(i+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var n;if(e.stream)"audio"===e.kind?n=e.stream.getAudioTracks()[0]:"video"===e.kind&&(n=e.stream.getVideoTracks()[0]),n&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1});var a=re(e.localCapabilities,e.remoteCapabilities);!a.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,i+=te(e,a,"answer",e.stream,r._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(i+="a=rtcp-rsize\r\n")}}));var s=new e.RTCSessionDescription({type:"answer",sdp:i});return Promise.resolve(s)},o.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(i,o){if(!r._remoteDescription)return o(se("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 o(se("OperationError","Can not add ICE candidate"));if(a.rejected)return i();var c=Object.keys(e.candidate).length>0?ee.parseCandidate(e.candidate):{};if("tcp"===c.protocol&&(0===c.port||9===c.port))return i();if(c.component&&1!==c.component)return i();if((0===s||s>0&&a.iceTransport!==r.transceivers[0].iceTransport)&&!oe(a.iceTransport,c))return o(se("OperationError","Can not add ICE candidate"));var d=e.candidate.trim();0===d.indexOf("a=")&&(d=d.substr(2)),(t=ee.getMediaSections(r._remoteDescription.sdp))[s]+="a="+(c.type?d:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=ee.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var _=0;_<r.transceivers.length&&(r.transceivers[_].rejected||(r.transceivers[_].iceTransport.addRemoteCandidate({}),(t=ee.getMediaSections(r._remoteDescription.sdp))[_]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=ee.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));_++);i()}))},o.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 se("InvalidAccessError","Invalid selector.");return r.getStats()}var i=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&i.push(e[t].getStats())}))})),Promise.all(i).then((function(e){var t=new Map;return e.forEach((function(e){e.forEach((function(e){t.set(e.id,e)}))})),t}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(t){var r=e[t];if(r&&r.prototype&&r.prototype.getStats){var i=r.prototype.getStats;r.prototype.getStats=function(){return i.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var i;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(i=e[r]).type]||i.type,t.set(r,e[r])})),t}))}}}));var s=["createOffer","createAnswer"];return s.forEach((function(e){var t=o.prototype[e];o.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=o.prototype[e];o.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=o.prototype[e];o.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)}})),o};function ae(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 ce(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 de(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=ne(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&&M("RTCIceServer.url","RTCIceServer.urls");const i="string"==typeof t;return i&&(t=[t]),t=t.filter((e=>{if(0===e.indexOf("stun:"))return!1;const t=e.startsWith("turn")&&!e.startsWith("turn:[")&&e.includes("transport=udp");return t&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=i?t[0]:t,!!t.length}}))}(e.iceServers,t.version),P("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype}function _e(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var ue=Object.freeze({__proto__:null,shimPeerConnection:de,shimReplaceTrack:_e,shimGetUserMedia:ae,shimGetDisplayMedia:ce});function le(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){M("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function he(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 Re(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,o,s]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!o)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(o,s)}}function pe(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function me(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),y(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ce(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){M("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Te(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ie(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],r=e&&"sendEncodings"in e;r&&e.sendEncodings.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function Ee(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Se(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 ge(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 fe=Object.freeze({__proto__:null,shimOnTrack:he,shimPeerConnection:Re,shimSenderGetStats:pe,shimReceiverGetStats:me,shimRemoveStream:Ce,shimRTCDataChannel:Te,shimAddTransceiver:Ie,shimGetParameters:Ee,shimCreateOffer:Se,shimCreateAnswer:ge,shimGetUserMedia:le,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 ve(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 Oe(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 Le(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,o=t.setLocalDescription,s=t.setRemoteDescription,n=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],o=r.apply(this,[i]);return t?(o.then(e,t),Promise.resolve()):o},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],o=i.apply(this,[r]);return t?(o.then(e,t),Promise.resolve()):o};let a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function Ae(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(Ne(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function Ne(e){return e&&void 0!==e.video?Object.assign({},e,{video:w(e.video)}):e}function De(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];!i.hasOwnProperty("urls")&&i.hasOwnProperty("url")?(M("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function ke(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ye(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio"),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video")}return t.apply(this,arguments)}}function Ue(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var be=Object.freeze({__proto__:null,shimLocalStreamsAPI:ve,shimRemoteStreamsAPI:Oe,shimCallbacksAPI:Le,shimGetUserMedia:Ae,shimConstraints:Ne,shimRTCIceServerUrls:De,shimTrackEventTransceiver:ke,shimCreateOfferLegacy:ye,shimAudioContext:Ue});function Pe(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const r=new t(e),i=ee.parseCandidate(e.candidate),o=Object.assign(r,i);return o.toJSON=function(){return{candidate:o.candidate,sdpMid:o.sdpMid,sdpMLineIndex:o.sdpMLineIndex,usernameFragment:o.usernameFragment}},o}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,y(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Me(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=ee.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=ee.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},i=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r},o=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 i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const o=ee.matchPrefix(e.sdp,"a=max-message-size:");return o.length>0?i=parseInt(o[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i},n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){const e=i(arguments[0]),t=o(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 xe(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],o=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&o>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},y(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function we(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 Be(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 Ve(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 $e=Object.freeze({__proto__:null,shimRTCIceCandidate:Pe,shimMaxMessageSize:Me,shimSendThrowTypeError:xe,shimConnectionState:we,removeExtmapAllowMixed:Be,shimAddIceCandidateNullOrEmpty:Ve});const Fe=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=P,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=k(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=k(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=k(r.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=k(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),o={browserDetails:i,commonShim:$e,extractVersion:k,disableLog:U,disableWarnings:b};switch(i.browser){case"chrome":if(!Q||!Y||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),o;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),o;r("adapter.js shimming chrome."),o.browserShim=Q,Ve(e,i),F(e,i),G(e),Y(e,i),K(e),q(e,i),H(e),j(e),J(e),z(e,i),Pe(e),we(e),Me(e,i),xe(e),Be(e,i);break;case"firefox":if(!fe||!Re||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),o;r("adapter.js shimming firefox."),o.browserShim=fe,Ve(e,i),le(e,i),Re(e,i),he(e),Ce(e),pe(e),me(e),Te(e),Ie(e),Ee(e),Se(e),ge(e),Pe(e),we(e),Me(e,i),xe(e);break;case"edge":if(!ue||!de||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),o;r("adapter.js shimming edge."),o.browserShim=ue,ae(e),ce(e),de(e,i),_e(e),Me(e,i),xe(e);break;case"safari":if(!be||!t.shimSafari)return r("Safari shim is not included in this adapter release."),o;r("adapter.js shimming safari."),o.browserShim=be,Ve(e,i),De(e),ye(e),Le(e),ve(e),Oe(e),ke(e),Ae(e),Ue(e),Pe(e),Me(e,i),xe(e),Be(e,i);break;default:r("Unsupported browser!")}return o}({window:"undefined"==typeof window?void 0:window});var Ge,Ke,He;!function(e){e.FPS_10="FPS_10",e.FPS_15="FPS_15",e.FPS_24="FPS_24",e.FPS_30="FPS_30"}(Ge||(Ge={})),function(e){e.W176_H132="W176_H132",e.W176_H144="W176_H144",e.W180_H180="W180_H180",e.W240_H180="W240_H180",e.W240_H240="W240_H240",e.W256_H144="W256_H144",e.W320_H180="W320_H180",e.W320_H240="W320_H240",e.W360_H360="W360_H360",e.W480_H360="W480_H360",e.W480_H480="W480_H480",e.W640_H360="W640_H360",e.W640_H480="W640_H480",e.W720_H480="W720_H480",e.W848_H480="W848_H480",e.W960_H720="W960_H720",e.W1280_H720="W1280_H720",e.W1920_H1080="W1920_H1080"}(Ke||(Ke={})),function(e){e[e.AUDIO_ONLY=0]="AUDIO_ONLY",e[e.VIDEO_ONLY=1]="VIDEO_ONLY",e[e.AUDIO_VIDEO=2]="AUDIO_VIDEO"}(He||(He={}));const je={[Ke.W176_H132]:{width:176,height:132,maxBitrate:150,minBitrate:80},[Ke.W176_H144]:{width:176,height:144,maxBitrate:150,minBitrate:80},[Ke.W180_H180]:{width:180,height:180,maxBitrate:200,minBitrate:100},[Ke.W240_H180]:{width:240,height:180,maxBitrate:240,minBitrate:120},[Ke.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[Ke.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[Ke.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[Ke.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[Ke.W360_H360]:{width:360,height:360,maxBitrate:520,minBitrate:140},[Ke.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[Ke.W480_H480]:{width:480,height:480,maxBitrate:800,minBitrate:180},[Ke.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[Ke.W640_H480]:{width:640,height:480,maxBitrate:900,minBitrate:200},[Ke.W720_H480]:{width:720,height:480,maxBitrate:1e3,minBitrate:200},[Ke.W848_H480]:{width:848,height:480,maxBitrate:1860,minBitrate:200},[Ke.W960_H720]:{width:960,height:720,maxBitrate:2e3,minBitrate:250},[Ke.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[Ke.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},Je=e=>{const t={192:180,368:360,1088:1080};return t[e]?t[e]:e},We=(e,t)=>{e=Je(e),t=Je(t);const r=je[`W${e}_H${t}`];if(r)return r;const i=e*t;return Object.keys(je).map((e=>je[e])).sort(((e,t)=>e.height*e.width-t.width*t.height)).filter((e=>e.height*e.width>=i))[0]||je.W1920_H1080},qe={10:1,15:1,24:1.5,30:1.5},Ye=e=>{let t=Number.MAX_VALUE,r=1;for(const i in qe){const o=Math.abs(e-parseInt(i));o<t&&(t=o,r=qe[i])}return r},ze={getCameras:()=>f(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))})),getMicrophones:()=>f(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))})),getSpeakers:()=>f(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audiooutput"===e.kind))}))};var Qe,Ze;!function(e){e.AUDIO="audio",e.VIDEO="video"}(Qe||(Qe={}));class Xe extends t{constructor(e,t,r,i,o){super(),this._tag=e,this._userId=t,this._kind=r,this._isLocalTrack=i,this._roomId=o,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 v.info(`set ${this._id} enabled: false`),r.info(L.L_TRACK_MUTE_O,{status:A.SUCCESSED,id:this._id},{logSource:i.RTC}),this._setLocalMuted(!0)}unmute(){return v.info(`set ${this._id} enabled: true`),r.info(L.L_TRACK_UNMUTE_O,{status:A.SUCCESSED,id:this._id},{logSource:i.RTC}),this._setLocalMuted(!1)}isLocalMuted(){return this._localMuted}isMCUTrack(){return Boolean(this._roomId)}isOwnerMuted(){return this._remoteMuted}play(e,t){return f(this,void 0,void 0,(function*(){if(r.info(L.L_TRACK_PLAY_T,{element:e,options:t},{logSource:i.RTC}),!this._msTrack)return v.warn(`the track is not ready to play -> id: ${this._id}`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:O.TRACK_NOT_READY,msg:`play error -> id: ${this._id}`},{logSource:i.RTC}),{code:O.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&(v.warn(`the track's readyState is 'ended' -> id: ${this._id}`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:"",msg:`the track's readyState is ended -> id: ${this._id}`},{logSource:i.RTC})),null==t?void 0:t.volume){if(!o(null==t?void 0:t.volume))return v.error(`${null==t?void 0:t.volume} is not a number, the valid range of options.volume is 0-100`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> options.volume不是数字"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};(null==t?void 0:t.volume)<0&&(t.volume=0,v.warn("the valid range of options.volume is 0-100, the value of volume has been set 0"),r.warn(L.L_TRACK_PLAY_R,{status:A.FAILED,code:"",msg:"params error -> options.volume < 0"},{logSource:i.RTC})),(null==t?void 0:t.volume)>100&&(t.volume=100,v.warn("the valid range of options.volume is 0-100, the value of volume has been set 100"),r.warn(L.L_TRACK_PLAY_R,{status:A.FAILED,code:"",msg:"params error -> options.volume > 100"},{logSource:i.RTC}))}if(null==t?void 0:t.audioDeviceId){if(!(yield ze.getSpeakers()).map((e=>e.deviceId)).includes(t.audioDeviceId))return v.error(`the options.audioDeviceId is invalid --\x3e ${t.audioDeviceId}`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> options.audioDeviceId"},{logSource:i.RTC}),{code:O.PARAMS_ERROR}}const s=this.isVideoTrack();return!s||e&&(e instanceof HTMLVideoElement||this.__validateVideoNodeName(e))?(this._element=s?e:this._element||new Audio,this._localMuted&&this._setLocalMuted(!1),this._element.srcObject&&this._element.srcObject===this._msStream||this._element.pause(),this._element.onloadstart=e=>{var t,o;v.debug(`HTMLMediaElement onloadstart -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onloadstart -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.ondurationchange=e=>{var t,o;v.debug(`HTMLMediaElement ondurationchange -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement ondurationchange -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onloadedmetadata=e=>{var t,o;v.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onloadedmetadata -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onloadeddata=e=>{var t,o;v.debug(`HTMLMediaElement onloadeddata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onloadeddata -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onabort=e=>{var t,o;v.info(`HTMLMediaElement onabort -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onabort -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.oncanplay=e=>f(this,void 0,void 0,(function*(){var o,n,a;v.info(`HTMLMediaElement oncanplay -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement oncanplay -> id: ${null===(n=e.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:i.RTC});try{yield null===(a=this._element)||void 0===a?void 0:a.play(),(null==t?void 0:t.audioDeviceId)&&!s&&(yield this._element.setSinkId(t.audioDeviceId))}catch(e){if("No permission to use requested device"===e.message)return v.error(`setSinkId failed -> ${e.message}`),void r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:O.NO_PERMISSION_TO_USE_REQUESTED_DEVICE,msg:"No permission"},{logSource:i.RTC});v.error(e),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:O.TRACK_PLAY_ERROR,msg:"play error"},{logSource:i.RTC})}})),this._element.onvolumechange=e=>{var t,o;const s=Math.floor(100*(null===(t=e.target)||void 0===t?void 0:t.volume));v.info(`HTMLMediaElement onvolumechange -> volume: ${s}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onvolumechange -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.srcObject=this._msStream,this._element.autoplay=!0,s&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),s||!(null==t?void 0:t.volume)&&0!==(null==t?void 0:t.volume)||(this._element.volume=(null==t?void 0:t.volume)/100),r.info(L.L_TRACK_PLAY_R,{status:A.SUCCESSED,element:e,options:t},{logSource:i.RTC}),{code:O.SUCCESS}):(v.error(`the video track need an <video> to play -> id: ${this._id}`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> element不是一个video标签"},{logSource:i.RTC}),{code:O.VIDEO_TRACK_MISS_MEDIA_ELEMENT})}))}__innerDestroy(){this.__innerSetMediaStreamTrack(void 0)}__releaseMediaElement(){this._element&&(this._element.remove(),this._element.srcObject=null)}__validateVideoNodeName(e){return e&&e.nodeName&&"VIDEO"===e.nodeName.toUpperCase()}}!function(e){e.Speech="Speech",e.Music="Music",e.MusicHigh="MusicHigh"}(Ze||(Ze={}));const et={[Ze.Music]:{max:64,min:64},[Ze.MusicHigh]:{max:128,min:128},[Ze.Speech]:{max:32,min:32}};var tt;!function(e){e.LEVEL0="LEVEL0",e.LEVEL1="LEVEL1",e.LEVEL2="LEVEL2",e.LEVEL3="LEVEL3",e.LEVEL4="LEVEL4",e.LEVEL5="LEVEL5"}(tt||(tt={}));const rt={[tt.LEVEL0]:{max:150,min:80},[tt.LEVEL1]:{max:280,min:120},[tt.LEVEL2]:{max:650,min:150},[tt.LEVEL3]:{max:1e3,min:200},[tt.LEVEL4]:{max:2200,min:250},[tt.LEVEL5]:{max:4e3,min:400}};class it{static setStatus(e=!0){it.isOpen=e}static setWroklet(e,t){it.workletModule=e,it.workletModule=t}static transformStreamTrack(e){var t;return f(this,void 0,void 0,(function*(){if(!it.isOpen)return new Promise((t=>{t({track:null==e?void 0:e.getAudioTracks()[0],stop:()=>{}})}));let r=new AudioContext({sampleRate:44100}),o=r.createMediaStreamSource(e),s=r.createMediaStreamDestination(),n=null,a=null;if(n=yield r.audioWorklet.addModule(it.workletModule).then((()=>(v.info(L.L_RTC_3ANOISE_NODE_O,{status:A.SUCCESSED,message:{msg:"addModule RC3AnoiseTrack.workletModule success"}},{logSource:i.RTC}),fetch(it.workletWasm,{cache:"force-cache",credentials:"same-origin"}).then((function(e){return e.arrayBuffer()})).catch((e=>{throw new Error(e.message)}))))).then((e=>(a=new AudioWorkletNode(r,"process-worklet",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{binary:e}}),a))).catch((e=>{v.info(L.L_RTC_3ANOISE_NODE_E,{status:A.FAILED,message:{msg:e.message}},{logSource:i.RTC})})),!n)return new Promise((t=>{t({track:null==e?void 0:e.getAudioTracks()[0],stop:()=>{}})}));o.connect(n).connect(s);let c=null===(t=null==s?void 0:s.stream)||void 0===t?void 0:t.getAudioTracks()[0],d=()=>{v.info(L.L_RTC_3ANOISE_NODE_STOP_O,{status:A.SUCCESSED,message:{msg:"call stop RC3AnoiseTrack.workletModule"}},{logSource:i.RTC}),null==n||n.port.postMessage({type:"stop",msg:""}),setTimeout((()=>{const t=null==e?void 0:e.getAudioTracks()[0];null==t||t.stop(),r.suspend(),r.close(),s.disconnect(),n.disconnect(),o.disconnect(),r=null,n=null,s=null,o=null,a=null,e=null,null==c||c.stop(),c=null,d=null}),200)};return{track:c,stop:d}}))}}it.workletModule="https://cdn.ronghub.com/plugin-rtc/wasm/5.0.0-alpha.2/process-worklet.js",it.workletWasm="https://cdn.ronghub.com/plugin-rtc/wasm/5.0.0-alpha.2/AudioProcessing.wasm",it.isOpen=!1;class ot extends Xe{constructor(e,t,r,i){super(e,t,r,!0),this._isDestroyed=!1,this._isPublished=!1,this.__innerSetMediaStreamTrack(i),i.onended=()=>{i.onended=null,this.emit(ot.EVENT_LOCAL_TRACK_END,this),this.removeAll(ot.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(e){return new Promise(((t,o)=>{const s=this._localMuted!==e;super._setLocalMuted(e),this._remoteMuted=this._localMuted,s&&this.emit(ot.__INNER_EVENT_MUTED_CHANGE__,this,t),r.info(L.L_LOCAL_TRACK_SET_LOCAL_MUTED_O,{status:A.SUCCESSED,bool:e},{logSource:i.RTC})}))}__innerSetPublished(e){r.info(L.L_LOCAL_TRACK_INNER_SET_PUBLISHED_O,{status:A.SUCCESSED,bool:e},{logSource:i.RTC}),this._isPublished=e}isPublished(){return this._isPublished}destroy(){var e;v.info(`track is destroyed -> trackId: ${this.getTrackId()}`),this._isDestroyed=!0,null===(e=this._msTrack)||void 0===e||e.stop(),super.__innerDestroy(),this.isAudioTrack()&&super.__releaseMediaElement(),this.emit(ot.__INNER_EVENT_DESTROY__,this),r.info(L.L_LOCAL_TRACK_DESTROY_O,{status:A.SUCCESSED},{logSource:i.RTC})}isDestroyed(){return this._isDestroyed}setBitrate(e=0,t=0,s=0){if(!o(e)||!o(t)||!o(s)||e<=0||t<=0||e<t)return v.error("setBitrate params error ->"),void r.error(L.L_LOCAL_TRACK_SET_BITRATE_O,{status:A.FAILED,code:"",msg:`params error -> max: ${e},min: ${t}, start: ${s}`},{logSource:i.RTC});r.info(L.L_LOCAL_TRACK_SET_BITRATE_O,{status:A.SUCCESSED,max:e,min:t,start:s},{logSource:i.RTC}),this._bitrateInfo={max:e,min:t,start:s}}getBitrate(){var e,t,r,i,o,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)===Qe.VIDEO?({min:a,max:c}=ft(this._msTrack)):(null===(t=this._msTrack)||void 0===t?void 0:t.kind)===Qe.AUDIO&&({min:a,max:c}={min:32,max:32}),(null===(r=this._bitrateInfo)||void 0===r?void 0:r.max)&&(d=.7*(null===(i=this._bitrateInfo)||void 0===i?void 0:i.max)),{min:(null===(o=this._bitrateInfo)||void 0===o?void 0:o.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}}}ot.EVENT_LOCAL_TRACK_END="local-track-end",ot.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",ot.__INNER_EVENT_DESTROY__="inner-destroy";class st extends ot{constructor(e,t,r){super(e,t,"audio",r),this._stopProcess=()=>{}}setRecommendBitrate(e){if(!s("livingType",e,(e=>e in Ze)))return void r.warn(L.L_RTC_SET_RECOMMEND_BITRATE_O,{status:A.FAILED,msg:"params error -> setRecommendBitrate Audio"},{logSource:i.RTC});const t=et[e];this.setBitrate(t.max,t.min,t.start||.7*t.max)}setBitrate(e,...t){const[r=1,i=.7*e||1]=t;super.setBitrate(e,r,i)}__innerSetMediaStreamTrack(e){if(e)if(it.isOpen){const t=new MediaStream([e]);it.transformStreamTrack(t).then((({track:e,stop:t})=>{super.__innerSetMediaStreamTrack(e),this._stopProcess=t}))}else super.__innerSetMediaStreamTrack(e);else super.__innerSetMediaStreamTrack(e),this._stopProcess()}}class nt extends ot{constructor(e,t,r,i=!1){super(e,t,"video",r),this._isTiny=i}__isTiny(){return this._isTiny}getStreamId(){const e=super.getStreamId();return this._isTiny?`${e}_tiny`:e}getTrackId(){const e=super.getTrackId();return this._isTiny?`${e}_tiny`:e}setRecommendBitrate(e){if(!s("livingType",e,(e=>e in tt)))return void r.warn(L.L_RTC_SET_RECOMMEND_BITRATE_O,{status:A.FAILED,msg:"params error -> setRecommendBitrate Video"},{logSource:i.RTC});const t=rt[e];this.setBitrate(t.max,t.min,t.start||.7*t.max)}setBitrate(e,...t){const[r=1,i=.7*e||1]=t;super.setBitrate(e,r,i)}}class at extends ot{constructor(e,t,r,i,o){super(e,t,r,i),this._resource=o,at.__innerSetMapping(this.getTrackId(),o)}static __innerSetMapping(e,t){const r=this._mapping.get(t)||[];r.push(e),this._mapping.set(t,r)}static __innerRemoveMapping(e,t){var r,i;const o=null===(r=this._mapping.get(t))||void 0===r?void 0:r.filter((t=>t!==e));o&&o.length>0?this._mapping.set(t,o):(this._mapping.delete(t),t.pause(),t.src="",null===(i=t.parentNode)||void 0===i||i.removeChild(t))}destroy(){this.isAudioTrack()&&this.mute(),at.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}at._mapping=new Map;class ct extends at{constructor(e,t,r,i){super(e,t,"video",r,i)}}class dt extends at{constructor(e,t,r,i){super(e,t,"audio",r,i),this._stopProcess=()=>{}}_setLocalMuted(e){const t=Object.create(null,{_setLocalMuted:{get:()=>super._setLocalMuted}});return f(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:O.SUCCESS})}__innerSetMediaStreamTrack(e){if(e)if(it.isOpen){const t=new MediaStream([e]);it.transformStreamTrack(t).then((({track:e,stop:t})=>{super.__innerSetMediaStreamTrack(e),this._stopProcess=t}))}else super.__innerSetMediaStreamTrack(e);else super.__innerSetMediaStreamTrack(e),this._stopProcess()}}class _t extends st{}class ut extends nt{}class lt extends nt{}class ht extends st{}class Rt extends Xe{constructor(e,t,r,i){super(e,t,r,!1,i),this._isSubscribed=!1}__innerSetRemoteMuted(e){this._remoteMuted=e}__innerSetSubscribed(e){this._isSubscribed=e,r.info(L.L_REMOTE_TRACK_INNER_SET_SUBSCRIBED_O,{status:A.SUCCESSED,bool:e},{logSource:i.RTC})}isSubscribed(){return this._isSubscribed}}class pt extends Rt{constructor(e,t,r){super(e,t,"audio",r)}}class mt extends Rt{constructor(e,t,r){super(e,t,"video",r),this._isSubTiny=!1}__innerSetIsTinyTrack(e){this._isSubTiny=e}isSubTiny(){return this._isSubTiny}}const Ct=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),Tt=e=>JSON.stringify(e),It=e=>/^[a-zA-Z\d-=]+$/g.test(e),Et="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),St=e=>{if(void 0===e)return 0;if(o(e))return e;const t=e;return t.exact||t.ideal||t.max||0},gt=e=>{const t=e.getSettings(),r=e.getConstraints();return{width:St(r.width)||t.width||0,height:St(r.height)||t.height||0,frameRate:t.frameRate||St(r.frameRate)}},ft=e=>{const{width:t,height:r,frameRate:i}=gt(e),o=We(t||1920,r||1080),s=Ye(i);return{min:o.minBitrate*s,max:o.maxBitrate*s}},vt=e=>[e.msid,e.mediaType].join("_"),Ot=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},Lt=(e,t)=>[e,t].join("_"),At=e=>e.map((e=>Object.assign({},e))),Nt=(e,t,r=!1)=>{e=e.slice();const i=[],o=[],s=[];return t.forEach((t=>{const o=vt(t);let n=e.findIndex((e=>vt(e)===o));if(r&&(n=e.findIndex((e=>e.uri===t.uri))),-1===n)return void i.push(t);const a=e[n];a.uri!==t.uri?i.push(t):a.state!==t.state&&s.push(t),e.splice(n,1)})),o.push(...e),{publishedList:i,unpublishedList:o,modifiedList:s}},Dt=()=>{let e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return e=e.replace(/-/g,"")+"0",e=parseInt(e,16),e=(e=>{const t="0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ+/".split(""),r=t.length+1;let i=+e;const o=[];do{const e=i%r;i=(i-e)/r,o.unshift(t[e])}while(i);return o.join("")})(e),e.length>22&&(e=e.slice(0,22)),e},kt=e=>{if(je[e]){const{width:t,height:r}=je[e];return{width:t,height:r}}const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},yt=e=>!!Ke[e],Ut=e=>!!Ge[e],bt=e=>parseInt(e.replace("FPS_","")),Pt=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=Fe.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function Mt(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function xt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const wt=e=>"[object Null]"===Object.prototype.toString.call(e),Bt=e=>1===e.type,Vt=(e,t)=>{const r={},i=Object.keys(e.users);return i.length&&i.forEach((i=>{const o=[],s=e.users[i];if(s.extra){const e=JSON.parse(s.extra).roomId;if(t!==e)return}if(s.uris)try{o.push(...JSON.parse(s.uris))}catch(e){v.warn(`invalid user data -> userId: ${i}, userData: ${s}`)}r[i]=o})),r},$t=e=>e instanceof Xe?e.getTrackId():e.track.getTrackId(),Ft=e=>{if(!n(e)||void 0===e.low||void 0===e.high)return e;let t=e.low;t<0&&(t+=4294967296),t=t.toString(16);return parseInt(e.high.toString(16)+"00000000".replace(new RegExp("0{"+t.length+"}$"),t),16)};var Gt,Kt;!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"}(Gt||(Gt={})),function(e){e.SUCCESS="Success",e.FAIL="Fail"}(Kt||(Kt={}));class Ht{constructor(e,t,r,i=5e3,o=6e4){this._roomId=e,this._roomMode=t,this._context=r,this._gap=i,this._offlineKickTime=o,this._latestTimestamp=Date.now(),this._started=!1,this._timer=null}start(){this._started||(v.info("rtcping start ->"),r.info(L.L_PINGER_START_O,{status:A.SUCCESSED,interval:this._gap},{logSource:i.RTC}),this._started=!0,this._checkAlive())}_sendPing(){return new Promise((e=>{this._context.rtcPing(this._roomId,this._roomMode).then(e).catch((t=>{v.error(`rtcping receive unknown error -> ${t}`),e(a.UNKNOWN)})),setTimeout(e,5e3,a.TIMEOUT)}))}_checkAlive(){var e,t,o;return f(this,void 0,void 0,(function*(){v.info("rtcping ->");const s=yield this._sendPing(),n=Date.now();return s===a.SUCCESS?(v.info("rtcping success ->"),this._latestTimestamp=n,null===(e=this.onPingResult)||void 0===e||e.call(this,Kt.SUCCESS),void(this._timer=setTimeout((()=>this._checkAlive()),this._gap))):(s===a.TIMEOUT&&r.error(L.L_PINGER_TIMEOUT_O,{status:A.TIMEOUT},{logSource:i.RTC}),v.warn(`rtcping failed -> code: ${s}`),null===(t=this.onPingResult)||void 0===t||t.call(this,Kt.FAIL),40003===s||n-this._latestTimestamp>this._offlineKickTime?(this.stop(),void(null===(o=this.onFailed)||void 0===o||o.call(this,40003===s))):void(this._timer=setTimeout((()=>this._checkAlive()),500)))}))}stop(){this._started&&(v.info("rtcping stop ->"),r.info(L.L_PINGER_STOP_O,{status:A.SUCCESSED},{logSource:i.RTC}),this._started=!1,this._timer&&(clearTimeout(this._timer),this._timer=null))}}const jt=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),Jt=(e,t,r)=>f(void 0,void 0,void 0,(function*(){const i=[];return yield Promise.any(e.map((e=>f(void 0,void 0,void 0,(function*(){const o=`${e.detectorAddr.replace(/^(https?:\/\/)?/,"https://")}/rtc/detector/ping?t=${s=1e3,n=9999,s+Math.floor(Math.random()*(n-s))}`;var s,n;const a={jwt:r},d=yield t.httpReq({url:o,body:JSON.stringify(a),timeout:_,method:c.POST});if(v.info(`ping res => ${JSON.stringify({status:d.status,host:e})}`),200!==d.status)return Promise.reject();i.push(e.clusterId)}))))),i})),Wt=(e,t)=>f(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 v.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 o=i[0];return o.detectorManager?o.detectorManager:""})(t),i=(o=t)&&o.jwt||"";var o;let s=null,n=120,a=0;const _={jwt:i};if(r&&i){const t=yield e.httpReq({url:`${r}/rtc/detector/servers`,body:JSON.stringify(_),headers:{"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${Pt.browser}|${Pt.version}`,ClientVersion:"5.5.5","Client-Session-Id":jt(),"Request-Id":Date.now().toString()},method:c.POST}),o=t.data&&JSON.parse(t.data).detectorAddrs;n=t.data&&JSON.parse(t.data).clientDetectMinute,a=t.data&&JSON.parse(t.data).resultCode,o&&d(o)&&(s=yield Jt(o,e,i))}return{fastMediaUrl:s,clientDetectMinute:n,status:a}})),qt=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${Pt.browser}|${Pt.version}`,ClientVersion:"5.5.5","Client-Session-Id":jt(),"Request-Id":Date.now().toString()});class Yt{constructor(e,t,r,i=5e3){this._runtime=e,this._context=t,this._msUrl=r,this._timeout=i,this._msInNavi=[],this._failedMs=[],this._rtcFinger=void 0,this._clusterId="",this._configUrl="",this._msList=[],Yt.isDetector||t.getConnectionStatus()!==u.CONNECTED||this.detectorMediaSever()}detectorMediaSever(){if(this._msUrl)return;const e=Date.now(),t=Yt.detectValidMinute+Yt.detectorTime>e;Yt.isDetector=t,r.info(`set msInDetector => ${JSON.stringify(Yt.msInDetector)}`);const i=this._context.getNaviInfo();!t&&i&&l(i)&&(this._msList=[],this._getDetectorUrls(i))}_getDetectorUrls(e){return f(this,void 0,void 0,(function*(){if(Yt.isDetector)return;Yt.isDetector=!0;const{fastMediaUrl:t,clientDetectMinute:r,status:i}=yield Wt(this._runtime,e);if(i===O.JWT_TIME_OUT&&Yt.naviRefetchCount<5){this._context.getPluginContext().refetchNaviInfo().then((()=>{this.detectorMediaSever()})),++Yt.naviRefetchCount,v.info(`RCMediaService refetch navi count => ${Yt.naviRefetchCount}`)}Yt.msInDetector=t||[],Yt.detectorTime=Date.now(),Yt.detectValidMinute=60*r*1e3,v.info(`RCMediaService detectorTime => ${Yt.detectorTime}`),v.info(`RCMediaService detectValidMinute => ${Yt.detectValidMinute}`)}))}getNaviMS(){return this._msUrl?[this._msUrl]:(h(this._msList)&&!this._clusterId||(this._msList=this.setMediaServiceList()),this._msList)}setMediaServiceList(){let e=[],t=[];return this._clusterId&&(this._clusterId=this._clusterId.replace(/^(https?:\/\/)?/,"https://"),this._msList.push(this._clusterId)),v.info(`MediaServiceList _clusterId -> ${this._clusterId}`),h(Yt.msInDetector)&&(Yt.msInDetector=Yt.msInDetector.map((e=>e.replace(/^(https?:\/\/)?/,"https://"))),this._msList.push(Yt.msInDetector[0]),e=Yt.msInDetector.concat().splice(1,Yt.msInDetector.length-1)),v.info(`MediaServiceList msInDetector ->${JSON.stringify(Yt.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 v.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 o=i[0],s=[];return o.mediaServer&&s.push(o.mediaServer.replace(/^(https?:\/\/)?/,"https://")),o.backupMediaServer&&o.backupMediaServer.forEach((e=>{s.push(e.replace(/^(https?:\/\/)?/,"https://"))})),s})(this._context.getNaviInfo())):(this._msInNavi.push(...this._failedMs),this._failedMs.length=0)),v.info(`MediaServiceList _msInNavi-> ${JSON.stringify(this._msInNavi)}`),t=this._msInNavi.concat().splice(1,this._msInNavi.length-1),this._msList.push(this._msInNavi[0]),this._msList=[...this._msList,...e,...t],this._msList=[...new Set(this._msList)],v.info(`MediaServiceList msList -> ${JSON.stringify(this._msList)}`),this._msList}_request(e,t,o){return f(this,void 0,void 0,(function*(){const s=this.getNaviMS();if(0===s.length)return v.warn(`request '${e}' failed -> have no valid service address.`),r.error(L.L_MEDIA_SERVICE_REQUEST_R,{status:A.FAILED,code:O.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"invalid navi_url"},{logSource:i.RTC}),{code:O.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(o.rtcFinger=this._rtcFinger);for(let n=0;n<s.length;n+=1){const a=`${s[n]}${e}`,d=qt(),_=Object.assign(Object.assign({},d),t),u=JSON.stringify(o),l=d["Request-Id"];r.info(L.L_MEDIA_SERVICE_REQUEST_T,{path:e,headers:t,body:o,reqId:l},{logSource:i.RTC}),v.info(`request -> Request-Id: ${l}, url: ${a}, headers: ${JSON.stringify(_)}, body: ${u}, timeout: ${this._timeout}`);const{status:h,data:R}=yield this._runtime.httpReq({url:a,body:u,headers:_,method:c.POST,timeout:this._timeout});if(200===h){const e=JSON.parse(R);return e.rtcFinger&&(this._rtcFinger=e.rtcFinger),e.clusterId&&(this._clusterId=e.clusterId),v.info(`request success -> Request-Id: ${l}`),r.info(L.L_MEDIA_SERVICE_REQUEST_R,{status:A.SUCCESSED,url:a,reqId:l},{logSource:i.RTC}),{code:O.SUCCESS,data:e}}v.warn(`request failed -> Request-Id: ${l}, status: ${h}, url: ${a}`),this._failedMs.push(...this._msInNavi.splice(n,1)),r.error(L.L_MEDIA_SERVICE_REQUEST_R,{status:A.FAILED,code:"",reqId:l,url:a,msg:`request error -> Request-Id: ${l}, status: ${h}, url: ${a}`},{logSource:i.RTC})}return{code:O.REQUEST_FAILED}}))}exchange(e,t){var r;return f(this,void 0,void 0,(function*(){const i=yield this._request("/exchange",e,t);if(i.code===O.SUCCESS&&(null===(r=i.data)||void 0===r?void 0:r.resultCode)===O.SUCCESS){const e=i.data.urls;e&&(this._configUrl=e.configUrl)}return i}))}exit(e){return f(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 f(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/broadcast/exit",e,{});return{code:t}}))}setMcuConfig(e,t){return f(this,void 0,void 0,(function*(){if(r.info(L.L_MEDIA_SERVICE_SET_MCU_CONFIG_T,{headers:e,body:t},{logSource:i.RTC}),!this._configUrl)return v.warn("RCMediaService.setMcuConfig failed -> RCRTCCode.MCU_SERVER_NOT_FOUND"),r.error(L.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:A.FAILED,code:O.MCU_SERVER_NOT_FOUND,msg:"MCU not found"},{logSource:i.RTC}),{code:O.MCU_SERVER_NOT_FOUND};const o=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,s=qt(),n=Object.assign(Object.assign({},s),e),a=JSON.stringify(t),d=s["Request-Id"];v.info(`request -> Request-Id: ${d}, url: ${o}, headers: ${JSON.stringify(n)}, body: ${a}`);const{status:_,data:u}=yield this._runtime.httpReq({url:o,headers:n,body:a,method:c.POST});if(200===_){v.info(`request success -> Request-Id: ${d}`);const e=JSON.parse(u);return r.info(L.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:A.SUCCESSED,reqId:d},{logSource:i.RTC}),{code:e.resultCode,res:e}}return v.warn(`request failed -> Request-Id: ${d}, status: ${_}, url: ${o}`),r.error(L.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:A.FAILED,code:O.REQUEST_FAILED,msg:`request error -> Request-Id: ${d}, status: ${_}, url: ${o}`},{logSource:i.RTC}),{code:O.REQUEST_FAILED}}))}getCDNResourceInfo(e,t){return f(this,void 0,void 0,(function*(){r.info(L.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_T,{headers:e,url:t},{logSource:i.RTC});const o=qt(),s=Object.assign(Object.assign({},o),e),n=o["Request-Id"];v.info(`request -> Request-Id: ${n}, url: ${t}, headers: ${JSON.stringify(s)}`);const{status:a,data:d}=yield this._runtime.httpReq({url:t,headers:s,method:c.GET});if(200===a){v.info(`request success -> Request-Id: ${o["Request-Id"]}`);const e=JSON.parse(d);return r.info(L.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:A.SUCCESSED,reqId:o["Request-Id"]},{logSource:i.RTC}),{code:e.resultCode,res:e}}return v.warn(`request failed -> Request-Id: ${o["Request-Id"]}, status: ${a}, url: ${t}`),r.info(L.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:A.FAILED,code:O.REQUEST_FAILED,msg:`request error -> Request-Id: ${o["Request-Id"]}, status: ${a}, url: ${t}`},{logSource:i.RTC}),{code:O.REQUEST_FAILED}}))}}var zt;Yt.isDetector=!1,Yt.msInDetector=[],Yt.detectorTime=0,Yt.detectValidMinute=72e5,Yt.naviRefetchCount=0,function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(zt||(zt={}));const Qt=(e,t)=>Math.round(8*t/e),Zt=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},Xt=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.round(e*r)},er=(e,t,r,i)=>{if(0===t)return 0;if(!r||!i)return Zt(e/t,3);const o=t-i;if(0===o)return 0;const s=e-r;return s<0||o<0?0:Zt(s/o,3)},tr=e=>{const{jitter:t,rtt:r,packetsLostRate:i}=e;return!wt(t)||!wt(r)||0!==i};class rr{constructor(e,t,r){this._rtcPeerConn=e,this._sdpSemantics=t,this._currentUserId=r,this._latestPacketsSent={},this._latestBytesSent={},this._latestBytesRecv={},this._latestPacketsRecv={}}updateBytesSent(e,t,r){let i,o;if(this._latestBytesSent[e]&&t<this._latestBytesSent[e].bytesSent&&this.clearLatestpacketsSent([e]),this._latestBytesSent[e]){const{bytesSent:s,timestamp:n}=this._latestBytesSent[e];i=t-s,o=r-n,this._latestBytesSent[e]={bytesSent:t,timestamp:r}}else i=t,o=1e3,this._latestBytesSent[e]={bytesSent:t,timestamp:r};return Qt(o,i)}updateBytesRecv(e,t,r){let i,o;if(this._latestBytesRecv[e]&&t<this._latestBytesRecv[e].bytesRecv&&this.clearLatestPacketsRecv([e]),this._latestBytesRecv[e]){const{bytesRecv:s,timestamp:n}=this._latestBytesRecv[e];i=t-s,o=r-n,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r}}else i=t,o=1e3,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r};return Qt(o,i)}updateSenderPacketsLost(e,t,r){let i;if(Object.prototype.hasOwnProperty.call(this._latestPacketsSent[e],"packetsSent")){const{packetsLost:o,packetsSent:s}=this._latestPacketsSent[e];i=er(t,r,o,s),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=o===t?s:r}else i=er(t,r),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=r;return i}updateReceiverPacketsLost(e,t,r){let i;if(this._latestPacketsRecv[e]){const{packetsLost:o,packetsRecv:s}=this._latestPacketsRecv[e];i=er(t,r+t,o,s+o)}else i=er(t,r);return this._latestPacketsRecv[e]={packetsLost:t,packetsRecv:r},i}clearLatestpacketsSent(e){e.forEach((e=>{if(parseInt(e.split("_").pop())===He.VIDEO_ONLY){const t=`${e}_tiny`;delete this._latestPacketsSent[t],delete this._latestBytesSent[t]}delete this._latestPacketsSent[e],delete this._latestBytesSent[e]}))}clearLatestPacketsRecv(e){e.forEach((e=>{delete this._latestPacketsRecv[e],delete this._latestBytesRecv[e]}))}parseRTCStatsReport(e){const t=e.keys(),r={};let i=t.next();for(;!i.done;){const o=i.value,s=e.get(o);/^RTCCodec_/.test(o)||(r[o]=s),i=t.next()}return r}formatRCRTCStateReport(e){const t={senders:[],receivers:[]};return r.info(L.L_ABSTRACT_STAT_PARSER_FORMAT_RTC_STATE_REPORT_O,{status:A.SUCCESSED,stats:e,reports:t},{logSource:i.RTC}),t}getAudioLevelList(e){return[]}getResourceIdByParseSdp(e){var t,r;const i=e.ssrc,o=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:${i} msid:(.*?) `);const c=null==s?void 0:s.split("\r\nm="),d=null==c?void 0:c.filter((e=>e.includes(`a=ssrc:${i}`)))[0],_=null==d?void 0:d.match(a);let u=_?_[1]:"";if(u){if("audio"===o)return`${u}_0`;const e=u.replace(`${this._currentUserId}_`,"").split("_");return e.length>1&&"tiny"===e[1]?`${this._currentUserId}_${e[0]}_1_tiny`:`${u}_1`}const l=null==n?void 0:n.split("\r\nm="),h=null==l?void 0:l.filter((e=>e.includes(`a=ssrc:${i}`)))[0],R=null==h?void 0:h.match(a);return u=R?R[1]:"",u?`${u}_${"video"===o?1:0}`:""}isValidSender(e){var t;const r=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}isValidReceiver(e){var t;const r=null===(t=this._rtcPeerConn.currentRemoteDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}}class ir extends rr{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let o=0,s=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const n=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const{id:a,kind:c,transportId:d,mediaSourceId:_,remoteId:u,packetsSent:l,bytesSent:h,trackId:R,encoderImplementation:p,pliCount:m,nackCount:C,firCount:T}=n;if(!R)return;let{framesPerSecond:I,frameWidth:E,frameHeight:S}=n;"video"!==c||E||S||I||(E=e[R].frameWidth,S=e[R].frameHeight,I=_?e[_].framesPerSecond:null);const g=e[u];let f=null,v=null,O=0;g&&(f=g.jitter,v=g.roundTripTime,O=g.packetsLost),o+=O;const L=this.getResourceIdByParseSdp(n);if(!L)return;const A=_?e[_].audioLevel:e[R].audioLevel;let N=null;!this._latestPacketsSent[L]&&(this._latestPacketsSent[L]={}),g?N=this.updateSenderPacketsLost(L,O,l):this._latestPacketsSent[L].crtPacketsSent=l;let D=this.updateBytesSent(L,h,r);D<0&&(D=0),s+=D,t.senders.push({id:a,trackId:L,kind:c,packetsLostRate:N,remoteResource:!1,audioLevel:A||0===A?Xt(A):null,frameWidth:E,frameHeight:S,frameRate:I,bitrate:D,jitter:f?Math.round(1e3*f):f,rtt:v,encoderImplementation:p,pliCount:m,nackCount:C,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));i.filter((e=>/RTCRemoteInboundRtp(Video|Audio)Stream_/.test(e))).forEach((r=>{const{localId:i,jitter:o,roundTripTime:s,packetsLost:n}=e[r],a=t.senders.filter((e=>e.id===i))[0];if(a&&!tr(a)){const t=this.getResourceIdByParseSdp(e[a.id]);a.jitter=Math.round(1e3*o),a.rtt=s;const r=this._latestPacketsSent[t].crtPacketsSent;a.packetsLostRate=this.updateSenderPacketsLost(t,n,r)}}));let n=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const s=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:_,bytesReceived:u,framesPerSecond:l,kind:h,codecImplementationName:R,nackCount:p,pliCount:m}=s;if(!a)return;let{frameWidth:C,frameHeight:T,audioLevel:I}=s;"video"===h?C||T||(C=e[a].frameWidth,T=e[a].frameHeight):I||(I=e[a].audioLevel),o+=c;const E=this.getResourceIdByParseSdp(s),S=this.updateReceiverPacketsLost(E,c,d);let g=this.updateBytesRecv(E,u,r);g<0&&(g=0),n+=g,t.receivers.push({trackId:E,kind:h,packetsLostRate:S,remoteResource:!0,audioLevel:I||0===I?Xt(I):null,frameWidth:C,frameHeight:T,frameRate:l,bitrate:g,jitter:_?Math.round(1e3*_):0,codecImplementationName:R,nackCount:p,pliCount:m,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:_,remoteCandidateId:u}=r,l=e[_],{ip:h,port:R,networkType:p}=l,m=e[u],{ip:C,port:T,protocol:I}=m;t.iceCandidatePair={IP:h,port:R,networkType:p,remoteIP:C,remotePort:T,protocol:I,bitrateRecv:n,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:o},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTPAudioStream_/.test(e))).forEach((r=>{var i;const o=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))return;const{mediaSourceId:s,trackId:n}=o,a=this.getResourceIdByParseSdp(o),c=s&&e[s]?e[s].audioLevel:(null===(i=e[n])||void 0===i?void 0:i.audioLevel)||null;t.push({trackId:a,audioLevel:c||0===c?Xt(c):null})}));return r.filter((e=>/^RTCInboundRTPAudioStream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:o}=i,s=i.audioLevel||e[o].audioLevel,n=this.getResourceIdByParseSdp(i);t.push({trackId:n,audioLevel:s||0===s?Xt(s):null})})),t}}class or extends rr{formatRCRTCStateReport(e){const t=+new Date,r={senders:[],receivers:[],timestamp:t};let i=0,o=0,s=0;for(const n in e){const a=e[n],c=a.type;if("outbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(a))continue;const{id:s,kind:n,bytesSent:c,packetsSent:d,bitrateMean:_,framerateMean:u,nackCount:l,pliCount:h,remoteId:R}=a,{jitter:p,roundTripTime:m,packetsLost:C}=R?e[R]:{jitter:null,roundTripTime:null,packetsLost:0},T=this.getResourceIdByParseSdp(a);i+=C;let I=null;!this._latestPacketsSent[T]&&(this._latestPacketsSent[T]={}),R?I=this.updateSenderPacketsLost(T,C,d):this._latestPacketsSent[T].crtPacketsSent=d;let E=0;"video"===n?_&&(E=Math.floor(_/1e3)):E=this.updateBytesSent(T,c,t),E<0&&(E=0),o+=E,r.senders.push({trackId:T,kind:n,packetsLostRate:I,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:E,jitter:p?Math.round(1e3*p):null,rtt:m,encoderImplementation:null,pliCount:h,nackCount:l,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}if("remote-inbound-rtp"===c){const{localId:t}=a,i=this.getResourceIdByParseSdp(e[t]),o=r.senders.filter((e=>e.trackId===i))[0];o&&tr(o)&&(o.jitter=Math.round(1e3*a.jitter),o.rtt=a.rtt,o.packetsLostRate=this.updateSenderPacketsLost(i,a.packetsLost,this._latestPacketsSent[i].crtPacketsSent))}if("inbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(a))continue;const{id:e,packetsLost:o,bytesReceived:n,packetsReceived:c,jitter:d,framerateMean:_,kind:u,bitrateMean:l,nackCount:h,pliCount:R}=a,p=this.getResourceIdByParseSdp(a);i+=o;const m=this.updateReceiverPacketsLost(p,o,c);let C=0;"video"===u?l&&(C=Math.floor(l/1e3)):C=this.updateBytesRecv(p,n,t),C<0&&(C=0),s+=C,r.receivers.push({trackId:p,kind:u,packetsLostRate:m,remoteResource:!0,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(_),bitrate:C,jitter:d?Math.round(1e3*d):null,codecImplementationName:null,nackCount:h,pliCount:R,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}if("candidate-pair"===c&&"succeeded"===a.state){const t=e[a.localCandidateId],{address:n,port:c}=t,d=e[a.remoteCandidateId],{address:_,port:u,protocol:l}=d;r.iceCandidatePair={IP:n,port:c,networkType:null,remoteIP:_,remotePort:u,protocol:l,bitrateRecv:s,bitrateSend:o,rtt:null,availableOutgoingBitrate:null,availableIncomingBitrate:null,totalPacketsLost:i}}}return r.iceCandidatePair&&(r.iceCandidatePair.bitrateSend=o),r.iceCandidatePair&&(r.iceCandidatePair.bitrateRecv=s),r}getAudioLevelList(e){const t=[];for(const r in e){const i=e[r],o=i.type;if("outbound-rtp"===o){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}if("inbound-rtp"===o){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}}return t}}class sr extends rr{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let o=0,s=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const o=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))return;const n=this.getResourceIdByParseSdp(o),{mediaType:a,transportId:c,remoteId:d,packetsSent:_,bytesSent:u,trackId:l,encoderImplementation:h,pliCount:R,nackCount:p,firCount:m}=o;if(!l)return;const{audioLevel:C,frameHeight:T,frameWidth:I}=e[l];let E=this.updateBytesSent(n,u,r);E<0&&(E=0),s+=E,t.senders.push({trackId:n,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:C||0===C?Xt(C):null,frameWidth:I,frameHeight:T,frameRate:null,bitrate:E,jitter:null,rtt:null,encoderImplementation:h,pliCount:R,nackCount:p,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));let n=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const s=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:_,bytesReceived:u,mediaType:l,nackCount:h,pliCount:R}=s,p=this.getResourceIdByParseSdp(s);if(!a)return;const{frameHeight:m,frameWidth:C,audioLevel:T}=e[a];o+=c;const I=this.updateReceiverPacketsLost(p,c,d);let E=this.updateBytesRecv(p,u,r);E<0&&(E=0),n+=E,t.receivers.push({trackId:p,kind:l,packetsLostRate:I,remoteResource:!0,audioLevel:T||0===T?Xt(T):null,frameWidth:C,frameHeight:m,frameRate:null,bitrate:E,jitter:_,codecImplementationName:null,nackCount:h,pliCount:R,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:_,remoteCandidateId:u}=r,l=e[_],{address:h,port:R}=l,p=e[u],{address:m,port:C,protocol:T}=p;t.iceCandidatePair={IP:h||null,port:R,networkType:null,remoteIP:m,remotePort:C,protocol:T,bitrateRecv:n,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:o},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const{trackId:o,mediaType:s}=i;if("video"===s)return;const n=this.getResourceIdByParseSdp(i),a=e[o];t.push({trackId:n,audioLevel:a||0===a?Xt(a):null})}));return r.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:o,mediaType:s}=i;if(!o||"video"===s)return;const{audioLevel:n}=e[o],a=this.getResourceIdByParseSdp(i);t.push({trackId:a,audioLevel:n||0===n?Xt(n):null})})),t}}class nr{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=RegExp("m=(?:video|audio)","img"),t=new Set([0]);let r;for(;null!==(r=e.exec(this.SDP));)t.add(r.index);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*nr.KBitrate}\r\nb=TIAS:${e*nr.KBitrate*850}`)}setAudiosBitrate(e){return v.info(L.L_RTC_SDP_BITRATE_O,{bitrate:e,msg:"SDP setAudiosBitrate"},{logSource:i.RTC}),this.audioStreams=this.audioStreams.map((t=>this.setAudioItemBitrate(t,e))),this}setAudioBitrateWithStreamId(e,t){return v.info(L.L_RTC_SDP_BITRATE_O,{bitrate:e,streamId:t,msg:"SDP setAudioBitrateWithStreamId"},{logSource:i.RTC}),this.audioStreams=this.audioStreams.map((r=>new RegExp(`\\bmsid:${t}\\b`,"ig").test(r)?this.setAudioItemBitrate(r,e):r)),this}setAudioBitrateWithMid(e,t){return v.info(L.L_RTC_SDP_BITRATE_O,{bitrate:e,mid:t,msg:"SDP setAudioBitrateWithMid"},{logSource:i.RTC}),this.audioStreams=this.audioStreams.map((r=>new RegExp(`\\bmid:${t}\\b`,"ig").test(r)?this.setAudioItemBitrate(r,e):r)),this}setAudioItemBitrate(e,t){if(0===t.max&&/\ba=inactive\b/gi.test(e))return e;if(!/\bmaxaveragebitrate\b/gi.test(e)){const r=["$1","maxaveragebitrate="+t.max*nr.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*nr.KBitrate}\r\nb=TIAS:${t.max*nr.KBitrate*850}`)}setVideosBitrate(e){return v.info(L.L_RTC_SDP_BITRATE_O,{bitrate:e,msg:"SDP setVideosBitrate"},{logSource:i.RTC}),this.videoStreams=this.videoStreams.map((t=>this.setVideoItemBitrate(t,e))),this}setVideoBitrateWithStreamId(e,t){return v.info(L.L_RTC_SDP_BITRATE_O,{bitrate:e,streamId:t,msg:"SDP setVideoBitrateWithStreamId"},{logSource:i.RTC}),this.videoStreams=this.videoStreams.map((r=>new RegExp(`\\bmsid:${t}\\b`,"ig").test(r)?this.setVideoItemBitrate(r,e):r)),this}setVideoBitrateWithMid(e,t){return v.info(L.L_RTC_SDP_BITRATE_O,{bitrate:e,mid:t,msg:"SDP setVideoBitrateWithMid"},{logSource:i.RTC}),this.videoStreams=this.videoStreams.map((r=>new RegExp(`\\bmid:${t}\\b`,"ig").test(r)?this.setVideoItemBitrate(r,e):r)),this}setVideoItemBitrate(e,t){if(0===t.max&&/\ba=inactive\b/gi.test(e))return e;if(!/\bx-google-max-bitrate\b/.test(e)){console.log("old:",e);const r=["$1","x-google-max-bitrate="+t.max*nr.KBitrate,"x-google-min-bitrate="+t.min*nr.KBitrate,`x-google-start-bitrate=${t.start||t.max*nr.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*nr.KBitrate}\r\nb=TIAS:${t.max*nr.KBitrate*850}`)}clearnSsrcWithMid(e,t){return v.info(L.L_RTC_SDP_BITRATE_O,{mid:e,msg:"SDP clearnSsrcWithMid"},{logSource:i.RTC}),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===cr.SENDONLY){if(/\ba=sendonly\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}if(t===cr.RECVONLY){if(/\ba=recvonly\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}if(t===cr.INACTIVE){if(/\ba=inactive\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}return e}}var ar,cr,dr,_r,ur,lr,hr,Rr,pr,mr,Cr,Tr,Ir,Er,Sr;nr.KBitrate=1,function(e){e.PLANB="plan-b",e.UNIFIEDPLAN="unified-plan"}(ar||(ar={})),function(e){e.SENDONLY="sendonly",e.RECVONLY="recvonly",e.INACTIVE="inactive"}(cr||(cr={}));class gr{constructor(e){this._peer=e,this._outboundStreams={}}static setSdpSemantics(e){r.info(L.L_A_SDP_STRATEGY_SET_SDP_SEMANTICS_O,{status:A.SUCCESSED,sdpSemantics:e},{logSource:i.RTC});const{browser:t,version:o,supportsUnifiedPlan:s}=Pt;r.debug(`sdpSemantics, browser: ${t}, version: ${o}, supportsUnifiedPlan: ${s}`),s?/chrome/i.test(t)?this._sdpSemantics=o>92?"unified-plan":o<72?"plan-b":e:/firefox/i.test(t)?this._sdpSemantics="unified-plan":/safari/i.test(t)?this._sdpSemantics=o<12?"plan-b":"unified-plan":this._sdpSemantics="unified-plan":this._sdpSemantics="plan-b"}static getSdpSemantics(){return gr._sdpSemantics}getOutboundVideoInfo(){const e=[];for(const t in this._outboundStreams){const r=this._outboundStreams[t].getVideoTracks()[0];if(!r)continue;const i=/_tiny$/.test(t),{width:o,height:s}=gt(r);e.push({trackId:r.id,simulcast:i?zt.TINY:zt.NORMAL,resolution:`${o}x${s}`})}return e}setRemoteAnswer(e){return f(this,void 0,void 0,(function*(){e=nr.trimBlankLine(e),r.info(`set remote answer -> ${e}`);try{yield this._peer.setRemoteDescription({type:"answer",sdp:e})}catch(e){return v.error(e),r.info(L.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:A.FAILED,code:"",msg:e},{logSource:i.RTC}),O.SET_REMOTE_DESCRIPTION_FAILED}return r.info(L.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:A.SUCCESSED,sdp:e},{logSource:i.RTC}),O.SUCCESS}))}getStatParsr(e,t,r){return/chrome/i.test(Pt.browser)?new ir(e,t,r):/Firefox/i.test(Pt.browser)?new or(e,t,r):/Safari/i.test(Pt.browser)?new sr(e,t,r):null}resetSdp(e){return nr.trimBlankLine(e)}}class fr extends nr{constructor(e){super(e,ar.PLANB),this.SDP=e}stringify(){const e=[this.SDPHeader];[...this.audioStreams,...this.videoStreams].forEach((t=>{const r=t.match(/\ba=mid:(video|audio)\b/),i=nr.clearInactiveOrRecvonly(t);r&&r[1]===Qe.AUDIO&&(e[1]=i),r&&r[1]===Qe.VIDEO&&(e[2]=i)}));const t=e.join("");return nr.trimBlankLine(t)}setAudioBitrateWithStreamId(e,t){return v.warn("plan-b not support set Audio Bitrate With Stream Id"),this}setVideoBitrateWithStreamId(e,t){return v.warn("plan-b not support set Video Bitrate With Stream Id"),this}}class vr extends gr{constructor(){super(...arguments),this.senders={},this._localTracks=[]}addLocalTrack(e){this._localTracks.includes(e)||this._localTracks.push(e);const t=e.getStreamId(),r=e.__innerGetMediaStreamTrack(),i=this._outboundStreams[t]||(this._outboundStreams[t]=new MediaStream);i.getTracks().forEach((e=>{e.kind===r.kind&&i.removeTrack(e)})),i.addTrack(r);const o=e.getTrackId(),s=this.senders[o];s?s.replaceTrack(r):this.senders[o]=this._peer.addTrack(r,i)}removeLocalTrack(e){const t=this._localTracks.findIndex((t=>t===e));t>=0&&this._localTracks.splice(t,1);const r=e.getTrackId(),i=this.senders[r];i&&(i.replaceTrack(null),this._peer.removeTrack(i),delete this.senders[r])}updateSubRemoteTracks(e){}updateRecvTransceiverMap(e,t){}setBitrate(e,t,r){this._maxBitrate=e,this._minBitrate=t,this._startBitrate=r||.7*e}createOffer(e){return f(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0});for(const e in this._outboundStreams){const r=this._outboundStreams[e].id;t.sdp=t.sdp.replace(new RegExp(r,"g"),e)}return t.sdp&&(t.sdp=nr.clearInactiveOrRecvonly(t.sdp)),yield this._peer.setLocalDescription(t),{type:"offer",semantics:"plan-b",sdp:t.sdp}}))}setRemoteAnswer(e){return e=this.resetSdp(e),super.setRemoteAnswer(e)}resetSdp(e){const t=new fr(e),r={max:0,min:0},i={max:0,min:0};return this._localTracks.forEach((e=>{const{min:t,max:o,start:s}=e.getBitrate();e.isAudioTrack()&&(i.max=i.max<o?o:i.max,i.min=i.min>t?t:i.min,i.max===o?i.start=s:i.start=.7*i.max),e.isVideoTrack()&&(r.max=r.max<o?o:r.max,r.min=r.min>t?t:r.min,r.max===o?r.start=s:r.start=.7*r.max)})),t.setAudiosBitrate(i),t.setVideosBitrate(r),t.stringify()}}class Or extends nr{constructor(e){super(e,ar.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 nr.trimBlankLine(t)}}class Lr{static splitSections(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))}static getMediaSections(e){const t=Lr.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=Lr.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 Lr.splitLines(e).filter((e=>0===e.indexOf(t)))}static parseMsid(e){let t;const r=Lr.matchPrefix(e,"a=msid:");if(1===r.length)return t=r[0].substr(7).split(" "),{stream:t[0],track:t[1]};const i=Lr.matchPrefix(e,"a=ssrc:").map((e=>Lr.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return i.length>0&&i[0].value?(t=i[0].value.split(" "),{stream:t[0],track:t[1]}):{stream:"",track:""}}static parseSsrcMedia(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r}static getMid(e){const t=Lr.matchPrefix(e,"a=mid:")[0];if(t)return t.substr(6)}}class Ar extends gr{constructor(){super(...arguments),this._sendTransceiver={},this._localTracks={},this._recvAudio=[],this._recvVideo=[],this._recvTransceiver={},this._subedTracks=[],this.midMsid={}}setBitrate(e,t,r){v.warn("the interface named `setBitrate` is invalid while sdpSemantics value is `unified-plan`")}addLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId(),i=e.__innerGetMediaStreamTrack();this._localTracks[t]=e;const o=this._outboundStreams[r]||(this._outboundStreams[r]=new MediaStream);o.getTracks().forEach((e=>{e.kind===i.kind&&o.removeTrack(e)})),o.addTrack(i);const s=this._sendTransceiver[t];s?(s.sender.replaceTrack(i),s.direction="sendonly"):this._sendTransceiver[t]=this._peer.addTransceiver(i,{direction:"sendonly",streams:[o]})}removeLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId();e.__innerGetMediaStreamTrack(),delete this._localTracks[t];const i=this._sendTransceiver[t];if(!i)return;i.direction="inactive",this._peer.removeTrack(i.sender),i.sender.replaceTrack(null);const o=this._outboundStreams[r];(e.isAudioTrack()?o.getAudioTracks():o.getVideoTracks()).forEach((e=>o.removeTrack(e)));const s=this._sendTransceiver[`${t}_tiny`];if(!s||"inactive"===s.direction)return;s.direction="inactive";const n=s.sender,a=n.track;this._peer.removeTrack(n),n.replaceTrack(null);this._outboundStreams[`${r}_tiny`].removeTrack(a),a.stop()}updateRecvTransceiverMap(e,t){const{mediaType:r}=Ot(e);this._recvTransceiver[e]=t;const i=r===He.AUDIO_ONLY?this._recvAudio:this._recvVideo,o=i.findIndex((e=>e===t));o>=0&&i.splice(o,1)}updateSubRemoteTracks(e){const t=e.slice(),r=this._subedTracks.slice();this._subedTracks=e.slice();for(let e=t.length-1;e>=0;e-=1){const i=t[e],o=r.findIndex((e=>e===i));o>=0&&(t.splice(e,1),r.splice(o,1))}r.length&&r.forEach((e=>{const t=e.getTrackId();e.__innerSetMediaStreamTrack(void 0);const r=this._recvTransceiver[t];r&&(r.direction="inactive")}));const i={audio:0,video:0};t.length&&t.forEach((e=>{const t=e.isAudioTrack()?"audio":"video",r=this._recvTransceiver[e.getTrackId()];r?r.direction="recvonly":i[t]+=1}));for(let e=this._recvAudio.length;e<i.audio;e+=1)this._recvAudio.push(this._peer.addTransceiver("audio",{direction:"recvonly"}));for(let e=this._recvVideo.length;e<i.video;e+=1)this._recvVideo.push(this._peer.addTransceiver("video",{direction:"recvonly"}))}createOffer(e){return f(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e});let r=t.sdp;for(const e in this._outboundStreams){const t=this._outboundStreams[e].id;r=r.replace(new RegExp(t,"g"),e)}return r=this.resetOfferSdp(r),r=r.replace(/(a=ice-options:trickle)/g,"$1\r\na=ice-options:renomination"),t.sdp=r,yield this._peer.setLocalDescription(t),{type:"offer",semantics:"unified-plan",sdp:r}}))}setRemoteAnswer(e){e=this.resetAnswerSdp(e);const t=/[\r\n]+\r\n[\r\n]+/g;return t.test(e)&&(v.warn(`answer sdp invalid -> ${JSON.stringify(e)}`),e=e.replace(t,"\r\n")),super.setRemoteAnswer(e)}resetOfferSdp(e){var t;const r=new Or(e);for(const i in this._sendTransceiver){const o=this._sendTransceiver[i],s=null===(t=o.sender.track)||void 0===t?void 0:t.kind;let{direction:n,mid:a}=o;if(!a){Lr.getMediaSections(e).forEach((e=>{Lr.parseExtmap(e);const{kind:t}=Lr.parseMLine(e);let{stream:r}=Lr.parseMsid(e);const o=Lr.getMid(e);"video"===s?/tiny$/.test(r)?r=r.replace(/tiny$/gi,"1_tiny"):r+="_1":r+="_0",r===i&&s===t&&o&&(a=o)}))}if(a){if(n===cr.SENDONLY){const e=this._localTracks[i],t=null==e?void 0:e.getBitrate();s===Qe.AUDIO&&t&&r.setAudioBitrateWithMid(t,a),s===Qe.VIDEO&&t&&r.setVideoBitrateWithMid(t,a)}n===cr.INACTIVE&&r.clearnSsrcWithMid(a,cr.INACTIVE)}}for(const e in this._recvTransceiver){const t=this._recvTransceiver[e],{direction:i,mid:o}=t;o&&(cr.RECVONLY,i===cr.INACTIVE&&r.clearnSsrcWithMid(o,cr.RECVONLY))}return r.stringify()}resetAnswerSdp(e){var t;const r=new Or(e);for(const e in this._sendTransceiver){const i=this._sendTransceiver[e],{mid:o}=i;if(o){const s=this._localTracks[e],n=null==s?void 0:s.getBitrate(),a=null===(t=i.sender.track)||void 0===t?void 0:t.kind;a===Qe.AUDIO&&n&&r.setAudioBitrateWithMid(n,o),a===Qe.VIDEO&&n&&r.setVideoBitrateWithMid(n,o)}}return r.stringify()}}class Nr extends t{constructor(e,t,r,i){super(),this._pcName=e,this._reTryExchange=t,this._currentUserId=r,this._polarisReport=i,this.pubLocalTracks={},this._reTryExchangeTimer=null,this._reportStatsTimer=null,this._reportR3R4ToPolarisTimer=null,this._isDestroyed=!1,this._reportListener=null;const o=gr.getSdpSemantics(),s=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:o});this._sdpStrategy="plan-b"===o?new vr(s):new Ar(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,o,this._currentUserId)}getName(){return this._pcName}getLocalTracks(){return r.info(L.L_RTC_PEER_CONNECTION_GET_LOCAL_TRACKS_O,{status:A.SUCCESSED,trackIds:Object.keys(this.pubLocalTracks)},{logSource:i.RTC}),Object.values(this.pubLocalTracks)}_onConnectionStateChange(){v.info(`onconnectionstatechange -> ${this._rtcPeerConn.connectionState}, ${this._pcName}`),r.info(L.L_RTC_PEER_CONNECTION_CONNECTION_STATE_S,{status:A.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:i.RTC})}_onICEConnectionStateChange(){var e,t;v.info(`oniceconnectionstatechange -> ${this._rtcPeerConn.iceConnectionState}, ${this._pcName}`),"connected"===this._rtcPeerConn.iceConnectionState&&(this._reportStatsTimer&&clearInterval(this._reportStatsTimer),this._reportStatsTimer=setInterval(this._reportHandle.bind(this),1e3)),"failed"!==this._rtcPeerConn.iceConnectionState&&"disconnected"!==this._rtcPeerConn.iceConnectionState||(v.warn(`${this._pcName} iceconenction state is failed, exchange SDP to try again.`),r.error(L.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:A.FAILED,code:"",msg:`${this._pcName} iceconenction state is failed, exchange SDP to try again.`},{logSource:i.RTC}),this._reTryExchange(),this._reTryExchangeTimer=setInterval(this._reTryExchange,15e3));try{null===(t=null===(e=this._reportListener)||void 0===e?void 0:e.onICEConnectionStateChange)||void 0===t||t.call(e,this._rtcPeerConn.iceConnectionState,this._pcName)}catch(e){v.error("onICEConnectionStateChange error",e,this._pcName),r.error(L.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:A.FAILED,code:"",msg:`${this._pcName}, ${e}`},{logSource:i.RTC})}r.info(L.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:A.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:i.RTC})}_onTrackReady(e){if(!e.streams.length)return;const t=[e.streams[0].id,"audio"===e.receiver.track.kind?He.AUDIO_ONLY:He.VIDEO_ONLY].join("_");this._updateRecvTransceiverMap(t,e.transceiver),this.emit(Nr.__INNER_EVENT_TRACK_READY__,e)}setBitrate(e,t,o){return f(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(e,t,o),r.info(L.L_RTC_PEER_CONNECTION_SET_BITRATE_O,{status:A.SUCCESSED,max:e,min:t,start:o},{logSource:i.RTC})}))}createOffer(e){return f(this,void 0,void 0,(function*(){const t=yield this._sdpStrategy.createOffer(e);return v.debug(`offer -> ${JSON.stringify(t.sdp)}`),r.info(L.L_RTC_PEER_CONNECTION_CREATE_OFFER_O,{status:A.SUCCESSED,offerSDP:t.sdp},{logSource:i.RTC}),t}))}setRemoteAnswer(e){return f(this,void 0,void 0,(function*(){return v.debug(`answer -> ${JSON.stringify(e)}`),r.info(L.L_RTC_PEER_CONNECTION_SET_REMOTE_ANSWER_O,{status:A.SUCCESSED,answer:e},{logSource:i.RTC}),this._sdpStrategy.setRemoteAnswer(e)}))}getLocalTrack(e){return this.pubLocalTracks[e]||null}addLocalTrack(e){this.pubLocalTracks[e.getTrackId()]=e,this._sdpStrategy.addLocalTrack(e),e.off(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.on(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.on(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),r.info(L.L_RTC_PEER_CONNECTION_ADD_LOCAL_TRACK_O,{status:A.SUCCESSED,trackId:e.getTrackId()},{logSource:i.RTC})}removeLocalTrackById(e){const t=this.getLocalTrack(e);t?(r.info(L.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:A.SUCCESSED,trackId:e},{logSource:i.RTC}),this.removeLocalTrack(t)):r.warn(L.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:A.FAILED,code:"",msg:"track not found"},{logSource:i.RTC})}removeAllLocalTrack(){Object.keys(this.pubLocalTracks).forEach((e=>{/_tiny$/.test(e)||this.removeLocalTrackById(e)})),r.info(L.L_RTC_PEER_CONNECTION_REMOVE_ALL_LOCAL_TRACK_O,{status:A.SUCCESSED},{logSource:i.RTC})}removeLocalTrack(e){const t=e.getTrackId();delete this.pubLocalTracks[t],this._sdpStrategy.removeLocalTrack(e),e.__innerSetPublished(!1),e.off(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this);const o=`${t}_tiny`,s=this.getLocalTrack(o);s&&(this._sdpStrategy.removeLocalTrack(s),delete this.pubLocalTracks[o],s.destroy()),r.info(L.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_O,{status:A.SUCCESSED,trackId:t},{logSource:i.RTC})}_updateRecvTransceiverMap(e,t){this._sdpStrategy.updateRecvTransceiverMap(e,t)}updateSubRemoteTracks(e){this._sdpStrategy.updateSubRemoteTracks(e),r.info(L.L_RTC_PEER_CONNECTION_UPDATE_SUB_REMOTE_TRACKS_O,{status:A.SUCCESSED,trackIds:e.map((e=>e.getTrackId()))},{logSource:i.RTC})}getOutboundVideoInfo(){return this._sdpStrategy.getOutboundVideoInfo()}_onLocalTrackMuted(e,t){const o=this.getLocalTrack(`${e.getTrackId()}_tiny`);o&&(o.__innerGetMediaStreamTrack().enabled=!e.isLocalMuted()),this.emit(ot.__INNER_EVENT_MUTED_CHANGE__,e,t),r.info(L.L_RTC_PEER_CONNECTION_LOCAL_TRACK_MUTED_O,{status:A.SUCCESSED,trackId:e.getTrackId()},{logSource:i.RTC})}_onLocalTrackDestroied(e){this.emit(ot.__INNER_EVENT_DESTROY__,e)}registerReportListener(e){this._reportListener=e}_createRCRTCStateReport(e){const{timestamp:t,iceCandidatePair:r,senders:i,receivers:o}=JSON.parse(JSON.stringify(e));null==r||delete r.totalPacketsLost;for(const e in r)wt(r[e])&&delete r[e];return{timestamp:t,iceCandidatePair:r,senders:i.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),receivers: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})),pcName:this._pcName}}_getStatsData(){var e,t;return f(this,void 0,void 0,(function*(){const r=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(r);return null===(t=this.reportParser)||void 0===t?void 0:t.formatRCRTCStateReport(i)}))}getAudioLevelReportData(){var e,t;return f(this,void 0,void 0,(function*(){const r=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(r);if(!i)return[];return null===(t=this.reportParser)||void 0===t?void 0:t.getAudioLevelList(i)}))}_reportHandle(){var e,t;return f(this,void 0,void 0,(function*(){const r=yield this._getStatsData();if(!r)return;const i=this._createRCRTCStateReport(r);null===(t=null===(e=this._reportListener)||void 0===e?void 0:e.onStateReport)||void 0===t||t.call(e,i)}))}_sendR3R4Data(){var e;return f(this,void 0,void 0,(function*(){const t=yield this._getStatsData();return!t||(t.senders.length||t.receivers.length?yield null===(e=this._polarisReport)||void 0===e?void 0:e.sendR3R4Data(t):void 0)}))}__reportR3R4ToPolaris(){return f(this,void 0,void 0,(function*(){clearTimeout(this._reportR3R4ToPolarisTimer),yield this._sendR3R4Data(),this._reportR3R4ToPolarisTimer=setTimeout(this.__reportR3R4ToPolaris.bind(this),2e3)}))}getRTCPeerConn(){return this._rtcPeerConn}destroy(){this.clear(),this.clearReTryExchangeTimer(),clearTimeout(this._reportR3R4ToPolarisTimer),this._reportStatsTimer&&(clearInterval(this._reportStatsTimer),this._reportStatsTimer=null),this.registerReportListener(null),this._rtcPeerConn.close(),this._isDestroyed=!0,this.reportParser=null,r.info(L.L_RTC_PEER_CONNECTION_DESTROY_O,{status:A.SUCCESSED},{logSource:i.RTC})}clearReTryExchangeTimer(){clearInterval(this._reTryExchangeTimer),this._reTryExchangeTimer=null}isDestroyed(){return this._isDestroyed}}Nr.__INNER_EVENT_TRACK_READY__="inner-track-ready",function(e){e[e.DISABLE=0]="DISABLE",e[e.ENABLE=1]="ENABLE"}(dr||(dr={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(_r||(_r={}));class Dr{constructor(e,t,r,i,o=_r.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=i,this._userRole=o}_send(e){return f(this,void 0,void 0,(function*(){let t=!1;if(this._context.getConnectionStatus()!==u.CONNECTED)return t;return t=(yield this._context.setRTCState(this._roomId,e))===a.SUCCESS,t}))}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=Dt(),this._runtime.localStorage.setItem(e,t)),t}_getRealResourceId(e){let t=e;const r=e.indexOf("_tiny");return r>-1&&(t=e.slice(0,r)),t}_getPolarisTrackId(e){let t="";const r=e.split("_");if(e.includes("_tiny")){const e=r.pop(),i=parseInt(r.pop())===He.AUDIO_ONLY?"audio":"video",o=r.pop();t=[r.join("_"),o,e,i].join("_")}else{const e=parseInt(r.pop())===He.AUDIO_ONLY?"audio":"video",i=r.pop();t=[r.join("_"),i,e].join("_")}return t}sendR3R4Data(e){return f(this,void 0,void 0,(function*(){const{iceCandidatePair:t,senders:r,receivers:i}=e,o=(null==t?void 0:t.bitrateSend)||-1,s=(null==t?void 0:t.bitrateRecv)||-1,n=(null==t?void 0:t.networkType)||"unknown",a=(null==t?void 0:t.rtt)||-1,c=`${(null==t?void 0:t.IP)||-1}:${null==t?void 0:t.port}`,d=(null==t||t.remoteIP,null==t||t.remotePort,(null==t?void 0:t.availableIncomingBitrate)||-1),_=(null==t?void 0:t.availableOutgoingBitrate)||-1,u=(null==t?void 0:t.totalPacketsLost)||-1,l=this._context.getCurrentId();let h=`R3\t${o}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${_}\t${u}\t${l}\r`,R=`R4\t${s}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${_}\t${u}\t${l}\r`;const p=r.map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:o,bitrate:s,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:_,jitter:u,nackCount:l,pliCount:h,rtt:R,googFirsSent:p,encoderImplementation:m}=e,C=this._getPolarisTrackId(r),T=this._getRealResourceId(r);return{trackId:C,googCodecName:m||String(-1),audioLevel:i||0===i?i:-1,bitrate:s||0===s?s:-1,packetsLostRate:n||0===n?n:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:h||0===h?h:-1,rtt:R||-1,googFirsSent:p,samplingRate:o,googRenderDelayMs:_,encoderImplementation:m||String(-1),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(T))||void 0===t?void 0:t.isLocalMuted())?dr.DISABLE:dr.ENABLE}})),m=i.filter((e=>!!e.trackId)).map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:o,bitrate:s,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:_,jitter:u,nackCount:l,pliCount:h,rtt:R,googFirsReceived:p,codecImplementationName:m}=e,C=this._getPolarisTrackId(r),T=this._getRealResourceId(r);return{trackId:C,googCodecName:m||String(-1),audioLevel:i||0===i?i:-1,bitrate:s||0===s?s:-1,packetsLostRate:n||0===n?n:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:h||0===h?h:-1,rtt:R||-1,googFirsReceived:p,samplingRate:o,googRenderDelayMs:_,codecImplementationName:m||String(-1),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(T))||void 0===t?void 0:t.isLocalMuted())?dr.DISABLE:dr.ENABLE}}));let C=!1;h+=p.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsSent}\t${e.encoderImplementation}\t${e.trackState}`)).join("\n"),e.senders.length&&(C=yield this._send(h+`\r${this._userRole}`));let T=!1;return R+=m.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsReceived}\t${e.codecImplementationName}\t${e.trackState}`)).join("\n"),e.receivers.length&&(T=yield this._send(R+`\r${this._userRole}`)),!(!C&&!T)}))}sendR1(){const e=`R1\t5.5.5\t${this._context.getCoreVersion()}\tweb\t${navigator.platform}\t-1\t${Pt.browser}\t${Pt.version}\t${this._getClientID()}\t${this._userRole}`;this._send(e)}sendR2(e,t,r){const i=`R2\t${e}\t${t}\t${this._getClientID()}\r${r.join("\t")}\r${this._userRole}`;this._send(i)}}class kr{constructor(e){this._room=e,this._audioLevelChangeHandler=null,this._timer=null}_audioLevelReport(){return f(this,void 0,void 0,(function*(){if(!this._audioLevelChangeHandler)return;const e=[],t=this._room.__getPC();for(let r=0;r<t.length;r++){const i=t[r];if("new"===i.getRTCPeerConn().iceConnectionState)return;const o=(yield i.getAudioLevelReportData()).map((e=>{const{userId:t}=Ot(e.trackId);return{track:this._room.getCrtUserId()===t?this._room.getLocalTrack(e.trackId):this._room.getRemoteTrack(e.trackId),audioLevel:e.audioLevel||0}})).filter((e=>e.track));e.push(...o)}this._audioLevelChangeHandler(e)}))}onAudioLevelChange(e,t){t<300||t>1e3?v.error('the valid range of onAudioLevelChange params "gap" is: > 300 && < 1000'):e?(this._audioLevelChangeHandler=e,this._timer=setInterval(this._audioLevelReport.bind(this),t)):this._audioLevelChangeHandler=null}clearAudioLevelReportTimer(){this._timer&&(clearInterval(this._timer),this._timer=null)}}!function(e){e[e.ANCHOR=1]="ANCHOR",e[e.AUDIENCE=2]="AUDIENCE"}(ur||(ur={}));class yr{constructor(e=!1,t,r,i,o){this._useMutilPeerC=e,this._roomId=t,this._reTryExchange=r,this._currentUserId=i,this._polarisReport=o,this._mutilPeerC={}}get useMutilPeerC(){return this._useMutilPeerC}_isPub(e){if(!e.length)return!1;const{track:t}=e[0]instanceof ot||e[0]instanceof Rt?{track:e[0]}:e[0];return t.isLocalTrack()}_groupTracksByTag(e){const t={};return e.map((e=>{const{track:r}=e instanceof ot?{track:e}:e,i=r.getTag();t[i]?t[i].push(e):t[i]=[e]})),t}_genPCName(e,t){let r=null;return r=e?this._useMutilPeerC?`${this._roomId}_${t}`:`${this._roomId}_pub`:`${this._roomId}_sub`,r}_createOnePeerCItem(e,t){if(this._mutilPeerC[e]&&!this._mutilPeerC[e].pc.isDestroyed())this._mutilPeerC[e].tracks=t;else{const r=this._isPub(t),i=new Nr(e,(()=>this._reTryExchange(e,r)),this._currentUserId,this._polarisReport);this._mutilPeerC[e]={pc:i,tracks:t,isPub:r}}return Object.assign({},this._mutilPeerC[e],{pcName:e})}createPeerCList(e){const t=[],r=this._isPub(e);if(!this._useMutilPeerC){const r=this._genPCName(!0);return t.push(this._createOnePeerCItem(r,e)),t}if(this._useMutilPeerC&&!r){const r=this._genPCName(!1);return t.push(this._createOnePeerCItem(r,e)),t}const i=this._groupTracksByTag(e);for(const e in i){const o=this._genPCName(r,e),s=i[e];t.push(this._createOnePeerCItem(o,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}=Ot(e),i=this._genPCName(t,r);return this._mutilPeerC[i].pc}getPCList(){const e=[];for(const t in this._mutilPeerC)e.push(this._mutilPeerC[t].pc);return e}getMutilPeerCData(){return this._mutilPeerC}setPeerCData(e,t,r){}clear(){this._removeAllLocalTrack(),this._destroyAllPeerC()}}!function(e){e[e.Unknow=0]="Unknow",e[e.Publish=1]="Publish",e[e.UnPublish=2]="UnPublish",e[e.JoinRoom=3]="JoinRoom",e[e.LeaveRoom=4]="LeaveRoom",e[e.UpdateSubscribeTask=5]="UpdateSubscribeTask",e[e.SubscribedTask=6]="SubscribedTask",e[e.UnSubscribedTask=7]="UnSubscribedTask",e.AsyncCommand="AsyncCommand"}(lr||(lr={})),function(e){e.NORMAL="normal",e.MIDDLE="middle",e.TAIL="tail"}(hr||(hr={})),function(e){e[e.LOW=0]="LOW",e[e.NORMAL=1]="NORMAL",e[e.HIGH=2]="HIGH"}(Rr||(Rr={})),function(e){e[e.Destroy=40400]="Destroy"}(pr||(pr={}));class Ur{get priority(){return Rr.LOW}get kind(){return lr.Unknow}}class br extends Ur{constructor(e=hr.NORMAL){super(),this.state=e}get kind(){return lr.AsyncCommand}setState(e){this.state=e}pickoutSubscribed(e,t){const{unsubscribe:r,subscribe:i}=this.calcSubscribeList(e,t);return br.AsyncSubscribeTasks=[],br.AsyncUnsubscribeTasks=[],br.AsyncUpdateSubscribeTasks=[],{subscribe:i,unsubscribe:r}}calcSubscribeList(e,t){const r=[],i=new Set,o=[],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)||i.has(t)||(r.push(e),i.add(t))})),n.forEach((e=>{const t=`${e.track.getTrackId()}_SUB_${e.subTiny?"0":"1"}`;this.trackInSubscribeList(e,a)||s.has(t)||(o.push(e),s.add(t))})),{unsubscribe:r,subscribe:o}}formateTrack(e){return e.map((e=>e instanceof Rt?{track:e,subTiny:!1}:Object.assign({subTiny:!1},e)))}trackInSubscribeList(e,t){if(0===t.length)return!1;return t.findIndex((t=>t.track.getTrackId()===e.track.getTrackId()&&t.subTiny===e.subTiny))>-1}}br.AsyncSubscribeTasks=[],br.AsyncUnsubscribeTasks=[],br.AsyncUpdateSubscribeTasks=[];class Pr{constructor(e,t,r,i,o,s,n,a,c){this.context=e,this.service=t,this.peerMgr=r,this.roomId=i,this.crtUserId=o,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 i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getRemoteTracks(){return this._remoteTracks}getSessionId(){return this._sessionId}getAllUserIds(){return Object.keys(this._roomResources)}getRemoteUserIds(){return this.getAllUserIds().filter((e=>e!==this.crtUserId))}getSubscribedList(){return this._subscribedList}getCollectSubscribeList(){return this._collectSubscribeList}getPublishedResourceByTrackId(e){const{userId:t}=Ot(e);return this._roomResources[t].find((t=>vt(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}}class Mr extends Pr{_initRemoteTracks(){for(const e in this._roomResources){const t=this._roomResources[e];e!==this.crtUserId&&0!==t.length&&t.forEach((e=>{const t=vt(e),{tag:r,userId:i,mediaType:o}=Ot(t),s=o===He.AUDIO_ONLY?new pt(r,i):new mt(r,i);s.__innerSetRemoteMuted(0===e.state),this._remoteTracks[t]=s}))}}initWithRoomData(e){this._sessionId=e.sessionId,this._token=e.token,this.isUpgrade?this._roomResources={}:this._roomResources=Vt(e,this.roomId),this._initRemoteTracks(),this.setResourcesByUserId(this.crtUserId,this.getResourcesByUserId(this.crtUserId)||[]),v.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 xr{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 f(this,void 0,void 0,(function*(){if(this._isDestroyed||this._busy||0===this._queue.length)return;this._busy=!0;const{command:e,resolve:t,reject:r}=this._queue.shift();let i;try{i=yield e.execute(this._store,this)}catch(e){return r(e),void this._next()}t(i),this._next()}))}push(e){return new Promise(((t,r)=>{if(this._isDestroyed)return;const i=e.kind;this._queue.length>0&&i===lr.AsyncCommand&&({command:e,resolve:t,reject:r}=this.commandOffset(e,t,r));const o=e.priority;if(o===Rr.LOW)this._queue.push({command:e,resolve:t,reject:r});else{const i=this._queue.findIndex((e=>e.command.priority<o)),s=-1===i?this._queue.length-1:i;this._queue.splice(s,0,{command:e,resolve:t,reject:r})}Promise.resolve().then((()=>{this._execute()}))}))}commandOffset(e,t,r){const i=this._queue.length-1;if(!(this._queue[i].command.kind===lr.AsyncCommand))return{command:e,resolve:t,reject:r};const[o]=this._queue.splice(i,1);o.command instanceof br&&(o.command.setState(hr.MIDDLE),e instanceof br&&e.setState(hr.TAIL));const s=e.execute;return e.execute=function(t,r){return f(this,void 0,void 0,(function*(){return o.command.execute.call(o.command,t,r),s.call(e,t,r)}))},{command:e,resolve:e=>{o.resolve.call(o,e),t(e)},reject:e=>{o.reject.call(o,e),r(e)}}}isDestroyed(){return this._isDestroyed}destroy(){this._isDestroyed||(this._isDestroyed=!0,this._queue.forEach((e=>{e.resolve({code:this.abortCode})})),this._queue.length=0)}}class wr extends xr{constructor(e,t,r,i,o,s,n,a,c){super(new Mr(e,t,r,i,o,s,n,a,c),O.ROOM_HAS_BEEN_DESTROYED)}get store(){return this._store}destroy(){super.destroy(),this._store.removeRemoteTracks()}}class Br extends Ur{execute(e){return f(this,void 0,void 0,(function*(){const t=e.getResourcesByUserId(e.crtUserId),r=t.slice();t.length=0,v.info(`unpublish uris before rejoin -> ${JSON.stringify(r)}`);const i=yield e.context.setRTCTotalRes(e.roomId,Ct(Gt.UNPUBLISH,r),Tt([]),Gt.TOTAL_CONTENT_RESOURCE,Tt([]));i!==a.SUCCESS?v.error(`unpublish uris before rejoin failed -> code: ${i}`):v.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"}(mr||(mr={})),function(e){e[e.KICK=0]="KICK",e[e.REFUSE=1]="REFUSE",e[e.COEXIST=2]="COEXIST"}(Cr||(Cr={}));class Vr extends Ur{constructor(e,t,r,i,o,s){super(),this.roomId=e,this.roomType=t,this.joinType=r,this.livingType=i,this.innerUserDatas=o,this.outerUserDatas=s}get kind(){return lr.JoinRoom}execute(e,t){var o;return f(this,void 0,void 0,(function*(){const{context:c,service:d}=e;let _=L.L_RTC_CLIENT_JOIN_RTC_ROOM_R;if(this.roomType===mr.LIVE?_=L.L_RTC_CLIENT_JOIN_LIVING_ROOM_R:this.roomType===mr.CROSS_MUTI&&(_=L.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_R),c.getConnectionStatus()!==u.CONNECTED)return r.error(_,{status:A.FAILED,code:O.SIGNAL_DISCONNECTED,msg:"im not connected"},{logSource:i.RTC}),{code:O.SIGNAL_DISCONNECTED};if(d.detectorMediaSever(),Bt(c.getNaviInfo()))return r.error(_,{status:A.FAILED,code:O.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_usl error"},{logSource:i.RTC}),{code:O.PACKAGE_ENVIRONMENT_ERROR};if(!s("roomId",this.roomId,R,!0))return r.error(_,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(!s("roomType",this.roomType,(e=>void 0!==mr[e])))return r.error(_,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> roomType"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(!s("outerUserDatas",this.outerUserDatas,n,!1))return r.error(_,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(this.outerUserDatas){if(!Object.keys(this.outerUserDatas).every((e=>s(`outerUserDatas.${e}`,this.outerUserDatas[e],p,!0))))return r.error(_,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:i.RTC}),{code:O.PARAMS_ERROR}}if(!d.getNaviMS().length)return r.error(_,{status:A.FAILED,code:O.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:i.RTC}),{code:O.NOT_OPEN_VIDEO_AUDIO_SERVER};v.info(`joinRoom -> roomId: ${this.roomId}; joinType: ${this.joinType||Cr.KICK}`);const{code:l,data:h}=yield c.joinRTCRoom(this.roomId,this.roomType,this.livingType,this.joinType,this.innerUserDatas,this.outerUserDatas);if(l!==a.SUCCESS||!h){v.warn(`joinRoom failed -> code: ${l}`);const e=40032===l?O.SIGNAL_JOIN_RTC_ROOM_REFUSED:l;return r.error(_,{status:A.FAILED,code:e,msg:`joinRoom failed -> code: ${l}`},{logSource:i.RTC}),{code:e}}v.info(`joinRoom success -> userId: ${c.getCurrentId()}, roomId: ${this.roomId}, data: ${JSON.stringify(h)}`),e.initWithRoomData(h);e.getResourcesByUserId(e.crtUserId).length>0&&t.push(new Br);const m=null===(o=h.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===o?void 0:o.value;return m&&e.setCDNUris(JSON.parse(m)[0]),r.info(_,{status:A.SUCCESSED,userId:e.crtUserId,roomId:this.roomId,data:h},{logSource:i.RTC}),{code:O.SUCCESS,data:h}}))}}function $r(e,t,r,i){return f(this,void 0,void 0,(function*(){return{sdp:yield r.createOffer(t),extend:JSON.stringify({resolutionInfo:r.getOutboundVideoInfo()}),subscribeList:e.filter((e=>{const t=e.track.getTrackId(),{userId:r}=Ot(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?zt.TINY:zt.NORMAL,resolution:"",uri:i.getPublishedResourceByTrackId(e.track.getTrackId()).uri}))),switchstream:!1}}))}function Fr(e,t,r){return f(this,void 0,void 0,(function*(){const i=yield e.setRTCCDNUris(t,Gt.TOTAL_CONTENT_RESOURCE,JSON.stringify([r]));return i!==a.SUCCESS?(v.error(`spreadCDNInfo failed -> code: ${i}`),{code:O.SIGNAL_ERROR}):(v.info("spreadCDNInfo succeed"),{code:O.SUCCESS})}))}function Gr(e,t,r){return f(this,void 0,void 0,(function*(){const i=yield e.setRTCData(t,"cdn_uris",JSON.stringify([r]),!0,Sr.ROOM);return i!==a.SUCCESS?(v.error(`setRoomCDNInfo failed -> code: ${i}`),{code:O.SIGNAL_ERROR}):(v.info("setRoomCDNInfo succeed"),{code:O.SUCCESS})}))}function Kr(e){return f(this,void 0,void 0,(function*(){const t=e.context,o=e.roomId,s=Object.assign({},e.getCDNUris(),{enableInnerCDN:e.getCDNEnable()});r.info(L.L_LIVING_ROOM_SPREAD_CDN_INFO_T,{roomId:o,CDNUris:s},{logSource:i.RTC});const n=(yield Promise.all([Fr(t,o,s),Gr(t,o,s)])).every((e=>e.code===O.SUCCESS));return n?r.info(L.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:A.SUCCESSED,CDNUris:s},{logSource:i.RTC}):r.error(L.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:A.FAILED,code:O.SIGNAL_ERROR,msg:"signal error"},{logSource:i.RTC}),n?{code:O.SUCCESS}:{code:O.SIGNAL_ERROR}}))}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(Tr||(Tr={})),function(e){e.BEGIN="begin",e.END="end"}(Ir||(Ir={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(Er||(Er={})),function(e){e[e.ROOM=1]="ROOM",e[e.PERSON=2]="PERSON"}(Sr||(Sr={}));class Hr extends Ur{constructor(e,t){super(),this.headers=e,this.reqBody=t}execute(e,t){var r,i;return f(this,void 0,void 0,(function*(){const t=yield e.service.exchange(this.headers,this.reqBody);if(e.roomMode!==mr.LIVE)return t;const o=null===(i=null===(r=t.data)||void 0===r?void 0:r.urls)||void 0===i?void 0:i.pull_url;if(t.code!==O.SUCCESS||!o)return t;const s=JSON.parse(o);return e.setCDNUris(s),(null==s?void 0:s.broadcast)===Er.SPREAD&&(e.setCDNEnabel(!0),Kr(e)),t}))}}class jr extends Ur{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(e,t){return f(this,void 0,void 0,(function*(){const{tracks:r,forceReq:i}=this,o=e.roomId;if(!s("tracks",r,(()=>d(r)&&r.every((e=>e instanceof Rt||e.track instanceof Rt))),!0))return v.warn(`update sublist failed, tracks is invalid -> roomId: ${o}`),{code:O.PARAMS_ERROR};v.info(`update subscribe list -> roomId: ${o}, forceReq: ${i}, tracks: ${r.map($t)}`);let n=r.map((e=>e instanceof Rt?{track:e}:Object.assign({},e)));const a={};n=n.filter((t=>{const r=t.track.getTrackId();return e.getRemoteTrack(r)?!a[r]&&(a[r]=!0):(v.warn(`track cannot found in room -> trackId: ${r}`),!1)})).map((e=>Object.assign({},e)));const c=e.getSubscribedList().map((e=>Object.assign({},e)));if(!i){let e=!1;if(n.forEach((t=>{const r=c.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);c.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),c.length&&(e=!0),!e)return{code:O.SUCCESS}}const{pc:_,pushOtherRooms:u,headers:l}=this.subhook(r);_.updateSubRemoteTracks(n.map((e=>e.track)));const h=yield $r(n,!1,_,e);u&&(h.pushOtherRooms=u);const R=yield new Hr(l,h).execute(e,t),p=n.map((e=>e.track.getTrackId()));if(R.code!==O.SUCCESS)return{code:R.code};const{sdp:m,resultCode:C,message:T,subscribedList:I}=R.data;if(C!==O.SUCCESS)return v.error(`change subscribe list failed: ${C}`),{code:C};v.debug(`subscribe success: ${p.join(",")}`);const E=yield _.setRemoteAnswer(m.sdp);if(E!==O.SUCCESS)return{code:E};const S=null==I?void 0:I.map((e=>`${e.msid}_${e.mediaType}`)),g=n.filter((e=>null==S?void 0:S.includes(e.track.getTrackId()))),f=n.filter((e=>!(null==S?void 0:S.includes(e.track.getTrackId())))),L=e.getRemoteTracks();for(const e in L){const t=g.some((t=>t.track.getTrackId()===e));L[e].__innerSetSubscribed(t);const r=g.some((t=>t.track.getTrackId()===e&&t.subTiny));L[e].isVideoTrack()&&L[e].__innerSetIsTinyTrack(r)}return e.resetSubscribedList(g),f.length?{code:O.SUCCESS,failedList:f}:{code:O.SUCCESS}}))}}class Jr extends Ur{constructor(e,t){super(),this.tracks=e,this.subhook=t}execute(e,t){return f(this,void 0,void 0,(function*(){const o=this.tracks,n=e.roomId;if(r.info(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:o.map($t)},{logSource:i.RTC}),!s("tracks",o,(()=>d(o)&&o.length>0&&o.every((e=>e instanceof Rt))),!0))return v.warn(`unsubscribe failed, tracks is invalid -> roomId: ${n}`),r.warn(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};v.info(`unsubscribe -> roomId: ${n}, tracks: ${o.map($t)}`);const a=e.getSubscribedList().map((e=>Object.assign({},e))).filter((e=>!o.includes(e.track)));return e.polarisReport.sendR2(Tr.SUBSCRIBE,Ir.END,o.map((e=>e.getTrackId()))),r.info(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:o.map($t),roomId:n},{logSource:i.RTC}),new jr(a,this.subhook,!1).execute(e,t)}))}}class Wr extends Ur{constructor(e,t){super(),this.msgContent=e,this.subhook=t}get priority(){return Rr.NORMAL}execute(e,t){return f(this,void 0,void 0,(function*(){const r=[],i=[],o=[],s=[],n={joined:r,left:i,upgrade:o,downgrade:s},{users:a}=this.msgContent;if(0===a.length)return n;for(let t=0;t<a.length;t++){const r=a[t];if(r.extra&&r.extra.roomId!==e.roomId)return n;if(1==+r.state&&!e.getRemoteUserIds().includes(r.userId))return n}a.forEach((t=>{const n=t.userId;if(0==+t.state){v.debug(`user joined -> ${n}`);const i=e.getResourcesByUserId(n);i||(t.switchRoleType?o.push(n):r.push(n)),e.setResourcesByUserId(n,i||[])}else v.debug(`user left -> ${n}`),t.switchRoleType?s.push(n):i.push(n)}));const c=[...i,...s];if(c.length){const r=[],i=[];c.forEach((t=>{r.push(...e.getRemoteTracksByUserId(t)),i.push(t)})),r.length&&(yield new Jr(r,this.subhook).execute(e,t),r.forEach((t=>e.removeRemoteTrack(t.getTrackId())))),i.length&&i.forEach((t=>e.removeResourcesByUserId(t)))}return n}))}}class qr extends Ur{constructor(e,t,r){super(),this.subhook=e,this.tracks=t,this.onTrackUnpublish=r}execute(e,t){return f(this,void 0,void 0,(function*(){const r=this.tracks;yield new Jr(r,this.subhook).execute(e,t),r.forEach((t=>{t.__innerDestroy(),e.removeRemoteTrack(t.getTrackId())})),this.onTrackUnpublish(r)}))}}class Yr extends Ur{constructor(e,t,r,i,o){super(),this.msgContent=e,this.messageType=t,this.senderId=r,this.subhook=i,this.callback=o}get priority(){return Rr.NORMAL}execute(e,t){var r,i;return f(this,void 0,void 0,(function*(){const{uris:o}=this.msgContent,s=[],n=[],a=[];let c;const d=this.senderId,_=this.messageType,u=e.getResourcesByUserId(d)||[];switch(e.setResourcesByUserId(d,u),_){case Gt.MODIFY:a.push(...o);break;case Gt.PUBLISH:s.push(...o);break;case Gt.UNPUBLISH:n.push(...o);break;case Gt.TOTAL_CONTENT_RESOURCE:c=Nt(u,o),s.push(...c.publishedList),n.push(...c.unpublishedList),a.push(...c.modifiedList)}if(s.length>0){const r=u.map(vt),i=[],o=[];if(s.forEach((t=>{const s=vt(t),n=r.indexOf(s),{userId:a,tag:c,mediaType:d}=Ot(s);n>-1?u[n]=t:u.push(t);let _=e.getRemoteTrack(s);_?_.isSubscribed()&&i.push(_):(_=d===He.AUDIO_ONLY?new pt(c,a):new mt(c,a),e.addRemoteTrack(_),o.push(_)),_.__innerSetRemoteMuted(0===t.state)})),i.length){const r=i.map((e=>e.getTrackId()));v.debug(`resub tracks -> ${JSON.stringify(r)}`);const{code:o}=yield new jr(i,this.subhook).execute(e,t);o!==O.SUCCESS&&v.error(`resub tracks failed -> code: ${o}, ids: ${JSON.stringify(r)}`)}this.callback.onTrackPublish(o)}if(n.length>0){const r=n.map(vt);for(let e=u.length-1;e>=0;e-=1){const t=u[e];r.includes(vt(t))&&u.splice(e,1)}const i=n.map((t=>{const r=vt(t);return e.getRemoteTrack(r)}));yield new qr(this.subhook,i,this.callback.onTrackUnublish).execute(e,t)}if(a.length>0){const t=u.map(vt);for(let r=0;r<a.length;r+=1){const i=a[r],o=vt(i),s=t.indexOf(o);u[s].state=i.state;const n=e.getRemoteTrack(o);n.__innerSetRemoteMuted(0===i.state),n.isAudioTrack()?this.callback.onAudioMute(n):this.callback.onVideoMute(n)}}if(e.roomMode!==mr.LIVE)return;const l=this.msgContent;if(!l.cdn_uris)return;const h=(null===(r=e.getCDNUris())||void 0===r?void 0:r.enableInnerCDN)!==l.cdn_uris[0].enableInnerCDN;e.setCDNUris(l.cdn_uris[0]),h&&this.callback.onCDNEnableChange(!!(null===(i=e.getCDNUris())||void 0===i?void 0:i.enableInnerCDN))}))}}class zr extends Ur{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(e,t){return f(this,void 0,void 0,(function*(){const{tracks:o,forceReq:n}=this,a=e.roomId;if(r.info(L.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:o.map($t),forceReq:n},{logSource:i.RTC}),!s("tracks",o,(()=>d(o)&&o.length>0&&o.every((e=>e instanceof Rt||e.track instanceof Rt))),!0))return v.warn(`subscribe failed, tracks is invalid -> roomId: ${a}`),r.error(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};v.info(`subscribe -> roomId: ${a}, tracks: ${o.map($t)}`);const c=e.getSubscribedList().map((e=>Object.assign({},e))),_=o.map((e=>e instanceof Rt?{track:e}:e));let u=!1;const l=[];return _.forEach((e=>{const t=e.track.getTrackId();l.push(t);const r=c.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:c.push(e),u=!0)})),u||n?(e.polarisReport.sendR2(Tr.SUBSCRIBE,Ir.BEGIN,l),r.info(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:o.map($t),roomId:a},{logSource:i.RTC}),new jr(c,this.subhook,!0).execute(e,t)):(r.warn(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:"",msg:"repeat subscribe"},{logSource:i.RTC}),{code:O.SUCCESS})}))}}class Qr extends Ur{constructor(e,t){super(),this.tracks=e,this.pubhook=t}get kind(){return lr.Publish}_removePubFailedTracks(e,t){e.forEach((e=>{const r=e instanceof ot?e:e.track;v.debug(`remove pub failed track from peerconnection -> trackId: ${r.getTrackId()}`),t.removeLocalTrackById(r.getTrackId())}))}__publish(e,t,r,i,o){return f(this,void 0,void 0,(function*(){const{pcName:s,pc:n,headers:a}=t,c=e.roomId,d=[];r.forEach((e=>{const{track:t}=e instanceof ot?{track:e}:e;d.push(t)})),r.sort(((e,t)=>{const{track:r}=e instanceof ot?{track:e}:e,{max:i}=r.getBitrate(),{track:o}=t instanceof ot?{track:t}:t,{max:s}=o.getBitrate();return i-s}));if(n.getLocalTracks().length+((e,t)=>{let r=0;return e.forEach((e=>{const i=e instanceof ot?e.getTrackId():e.track.getTrackId();t.getLocalTrack(i)||(e instanceof ot?r++:e.pubTiny&&e.track.isVideoTrack()&&(r+=2))})),r})(r,n)>10)return v.error(`publish failed, tracks limit exceeded -> roomId: ${c}`),{code:O.PUBLISH_TRACK_LIMIT_EXCEEDED,tracks:d};v.debug(`publish tracks -> roomId: ${c}, tracks: ${r.map($t)}`);for(let e=0;e<r.length;e++){const t=r[e],{track:i,pubTiny:o}=t instanceof ot?{pubTiny:!1,track:t}:t;if(i.isVideoTrack()&&o){let e;try{e=i.__innerGetMediaStreamTrack().clone();const t=o.frameRate||Ge.FPS_15,r=o.resolution||Ke.W176_H144,{width:s,height:n}=kt(r),a=bt(t);yield e.applyConstraints({width:s,height:n,frameRate:a})}catch(t){null==e||e.stop(),v.warn(`pubTiny failed -> id: ${i.getTrackId()}, msg: ${t.message}`);break}n.addLocalTrack(new nt(i.getTag(),i.getUserId(),e,!0))}n.addLocalTrack(i)}n.clearReTryExchangeTimer();const _=e.useMutilPeerC?[]:e.getSubscribedList(),u=yield $r(_,!1,n,e);i&&(u.pushOtherRooms=i);const l=yield new Hr(a,u).execute(e,o);if(l.code!==O.SUCCESS)return v.error(`publish failed -> roomId: ${c}, code: ${l.code}`),this._removePubFailedTracks(r,n),{code:l.code,tracks:d};const{sdp:h,resultCode:R,message:p}=l.data;if(R!==O.SUCCESS)return v.error(`publish failed -> roomId: ${c}, code: ${R}, msg: ${p}`),this._removePubFailedTracks(r,n),{code:R,tracks:d};const m=yield n.setRemoteAnswer(h.sdp);return m!==O.SUCCESS?{code:m,tracks:d}:Object.assign({},l,{tracks:d})}))}_mergePublishRes(e,t){return f(this,void 0,void 0,(function*(){const r=t.crtUserId,i=t.roomId;let o="";const s=[],n=t.getResourcesByUserId(r),c=[...n];let d=[];e.forEach((e=>{if(e.code!==O.SUCCESS){const{tracks:t}=e;return void s.push({code:e.code,tracks:t})}const{publishList:r,urls:i,mcuPublishList:n}=e.data;o=null==i?void 0:i.liveUrl;r.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:t.getTrackState(vt(e))},e))).forEach((e=>{const{isInclude:t,index:r}=((e,t)=>{let r=!1,i=0;for(let o=0;o<t.length;o++){const s=t[o];if(`${e.msid}_${e.mediaType}`==`${s.msid}_${s.mediaType}`){r=!0,i=o;break}}return{isInclude:r,index:i}})(e,c);t?c.splice(r,1,e):c.push(e)}));const a=(null==n?void 0:n.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))))||[];d=a}));const{publishedList:_}=Nt(n,c),u=yield t.context.setRTCTotalRes(i,Ct(Gt.PUBLISH,_),Tt(c),Gt.TOTAL_CONTENT_RESOURCE,Tt(d));if(u!==a.SUCCESS)return v.error(`send publish streams notification failed: ${u}`),{code:O.SIGNAL_ERROR};t.setResourcesByUserId(r,c);const l=_.map((e=>vt(e)));t.polarisReport&&t.polarisReport.sendR2(Tr.PUBLISH,Ir.BEGIN,l),_.forEach((e=>{const r=t.useMutilPeerC?`${i}_${(e=>{const t=e.split("_");return{tag:t.pop(),userId:t.join("_")}})(e.msid).tag}`:`${i}_pub`,{pc:o}=t.peerMgr.getPCItemByPCName(r);o.getLocalTrack(`${e.msid}_${e.mediaType}`).__innerSetPublished(!0)})),v.debug(`publish success: ${l.join(",")}`);const h={code:O.SUCCESS};return o&&(h.liveUrl=o),s.length&&(h.failedTracks=s,h.code=O.SOME_TRACKS_PUBLISH_FAILED),h}))}execute(e,t){return f(this,void 0,void 0,(function*(){let o=this.tracks;const n=e.roomId;if(r.info(L.L_ABSTRACT_ROOM_PUBLISH_T,{trackIds:o.map($t)},{logSource:i.RTC}),!s("tracks",o,(()=>d(o)&&o.length>0&&o.every((e=>e instanceof ot||e.track instanceof ot))),!0))return v.warn(`publish failed, tracks is invalid -> roomId: ${n}`),r.error(L.L_ABSTRACT_ROOM_PUBLISH_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(o=o.filter((e=>{const{track:t}=e instanceof ot?{track:e}:e,i=t.isDestroyed();return i&&r.warn(L.L_ABSTRACT_ROOM_PUBLISH_R,{status:A.FAILED,msg:`track -> ${t.getTrackId()} has beem destroyed`}),!i})),!o.length)return{code:O.PUBLISH_TRACKS_IS_INVALID};const a=[],{plist:c,pushOtherRooms:_}=this.pubhook(o);for(let r=0;r<c.length;r++){const i=c[r];a.push(this.__publish(e,i,i.tracks,_,t))}const u=yield Promise.all(a),l=yield this._mergePublishRes(u,e);return r.info(L.L_ABSTRACT_ROOM_PUBLISH_R,{status:A.SUCCESSED,roomId:n,trackIds:o.map($t)},{logSource:i.RTC}),l}))}}class Zr extends Ur{constructor(e,t){super(),this.tracks=e,this.unpubhook=t}get kind(){return lr.UnPublish}__unpublish(e,t,r,i){return f(this,void 0,void 0,(function*(){const{pcName:o,pc:s}=r;e.roomId;const n=i.map((e=>e.getTrackId()));if(0===n.map(e.getPublishedResourceByTrackId.bind(e)).filter((e=>!!e)).length)return{code:O.SUCCESS,tracks:i};n.forEach((e=>s.removeLocalTrackById(e))),e.polarisReport.sendR2(Tr.PUBLISH,Ir.END,n),s.clearReTryExchangeTimer();const a=e.useMutilPeerC?[]:e.getSubscribedList(),c=yield $r(a,!1,s,e),{pushOtherRooms:d,headers:_}=this.unpubhook(i,o);d&&(c.pushOtherRooms=d);const u=yield new Hr(_,c).execute(e,t);return u.code!==O.SUCCESS?(v.error(`exchange failed -> code: ${u.code}`),{code:u.code,tracks:i}):Object.assign({},u,{tracks:i})}))}_mergeUnpublishRes(e,t){return f(this,void 0,void 0,(function*(){const r=e.context.getCurrentId(),i=e.roomId,o=[],s=[],n=[],c=[];let d=[];for(let r=0;r<t.length;r++){const i=t[r];if(i.code!==O.SUCCESS){const{tracks:e}=i;s.push({code:i.code,tracks:e});continue}const{resultCode:a,message:_,mcuPublishList:u}=i.data;a!==O.SUCCESS&&v.error(`unpublish streams failed -> code: ${a}, msg: ${_}`);const l=i.tracks.map((e=>e.getTrackId()));c.push(...l);const h=l.map(e.getPublishedResourceByTrackId.bind(e)).filter((e=>!!e));n.push(...h),o.push(i);const R=u?u.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[];d=R}const _=e.getResourcesByUserId(r).filter((e=>!n.includes(e))),u=yield e.context.setRTCTotalRes(i,Ct(Gt.UNPUBLISH,n),Tt(_),Gt.TOTAL_CONTENT_RESOURCE,Tt(d));if(u!==a.SUCCESS)return v.error("send unpublish notification failed:",u),{code:O.SIGNAL_ERROR};v.debug(`unpublish success -> tracks: ${c.join(",")}`),o.forEach((t=>f(this,void 0,void 0,(function*(){const{sdp:r}=t.data,{tracks:i}=t,o=e.peerMgr.getPCByTrackId(i[0].getTrackId());yield o.setRemoteAnswer(r.sdp)})))),e.setResourcesByUserId(r,_);const l={code:O.SUCCESS};return s.length&&(l.failedTracks=s,l.code=O.SOME_TRACKS_PUBLISH_FAILED),l}))}execute(e,t){return f(this,void 0,void 0,(function*(){const{crtUserId:o,roomId:n}=e,a=this.tracks;r.info(L.L_ABSTRACT_ROOM_UNPUBLISH_T,{trackIds:a.map($t)},{logSource:i.RTC});if(!s("tracks",a,(()=>a.every((e=>e.getUserId()===o&&e instanceof ot))),!0))return v.warn(`unpublish failed, tracks is invalid -> roomId: ${n}, tracks: ${a.map($t)}`),r.error(L.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};const c=e.peerMgr.createPeerCList(a),d=[];for(let r=0;r<c.length;r++){const{tracks:i}=c[r];d.push(this.__unpublish(e,t,c[r],i))}const _=yield Promise.all(d);let u=_.length;if(_.forEach((e=>{e.code!==O.SUCCESS||e.data||(u-=1)})),0===u)return{code:O.SUCCESS};const l=yield this._mergeUnpublishRes(e,_);return r.info(L.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:A.SUCCESSED,roomId:n,trackIds:a.map($t)},{logSource:i.RTC}),l}))}}class Xr extends Ur{constructor(e,t){super(),this.localTrack=e,this._recvSignalResultFn=t}execute(e,t){return f(this,void 0,void 0,(function*(){const{localTrack:t}=this,r=t.getTrackId(),{crtUserId:i,roomId:o}=e,s=[{resourceId:r,enabled:!t.isLocalMuted()}],n=e.getResourcesByUserId(i),c=[];for(let e=0;e<n.length;e+=1){const t=n[e],r=vt(t),i=s.findIndex((e=>e.resourceId===r));if(i>=0){const{enabled:e}=s[i];t.state=e?1:0,c.push(t);break}}const d=yield e.context.setRTCTotalRes(o,Ct(Gt.MODIFY,c),Tt(n),Gt.TOTAL_CONTENT_RESOURCE);this._recvSignalResultFn(d),d!==a.SUCCESS&&v.error("notice `track.enabled` change failed -> code: "+d)}))}}class ei extends Ur{constructor(e,t,r){super(),this.pcName=e,this.isPub=t,this.retryHook=r}get priority(){return Rr.HIGH}execute(e,t){return f(this,void 0,void 0,(function*(){const{pcName:r,isPub:i}=this,{useMutilPeerC:o}=e,{pc:s}=e.peerMgr.getPCItemByPCName(r),n=i&&o?[]:e.getSubscribedList(),a=yield $r(n,!0,s,e),{pushOtherRooms:c,headers:d}=this.retryHook(r);c&&(a.pushOtherRooms=c);const _=yield new Hr(d,a).execute(e,t);if(_.code!==O.SUCCESS)return void v.error(`reTryExchange failed: ${_.code}, pcName: ${r}`);const{sdp:u,resultCode:l}=_.data;l===O.SUCCESS?(s.clearReTryExchangeTimer(),yield s.setRemoteAnswer(u.sdp)):v.error(`reTryExchange failed: ${l}, pcName: ${r}`)}))}}class ti extends Ur{constructor(e,t,r){super(),this.subhook=e,this.callbacks=t,this.livingType=r}get priority(){return Rr.HIGH}execute(e,t){return f(this,void 0,void 0,(function*(){const{livingType:o}=this,{roomId:s,crtUserId:n,roomMode:c}=e;r.info(L.L_ABSTRACT_ROOM_RECONNECTED_T,{livingType:o},{logSource:i.RTC});if(e.peerMgr.getPCList().some((e=>"closed"===e.getRTCPeerConn().connectionState)))return v.warn("RTCPeerConnection closed. Please rejoin room to restore services."),r.error(L.L_ABSTRACT_ROOM_RECONNECTED_R,{status:A.FAILED,code:"",msg:"RTCPeerConnection disconnected"},{logSource:i.RTC}),void this.callbacks.onPeerClosed();const{code:d,data:_}=yield e.context.joinRTCRoom(s,c,o);if(d!==a.SUCCESS)return v.error(`RTC __onReconnected getRTCRoomInfo failed: ${d}`),void r.error(L.L_ABSTRACT_ROOM_RECONNECTED_R,{status:A.FAILED,code:d,msg:""},{logSource:i.RTC});v.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(_)}`);const u=[],l={},h={},R={},p=Vt(_,s),m=Object.keys(p),C=e.getAllUserIds();for(let t=m.length-1;t>=0;t-=1){const r=m[t],i=C.indexOf(r);if(-1===i){u.push(r),l[r]=At(p[r]);continue}const o=e.getResourcesByUserId(r),s=p[r],{publishedList:n,modifiedList:a,unpublishedList:c}=Nt(o,s,!0);l[r]=At(n),h[r]=At(c),R[r]=At(a),C.splice(i,1)}C.length&&C.forEach((t=>{e.removeResourcesByUserId(t)})),e.assignRoomData(p),C.length&&this.callbacks.onUserLeave(C),u.length&&this.callbacks.onUserJoin(u);for(const r in h){if(r===n)continue;const i=h[r];if(i.length){const r=i.map((t=>e.getRemoteTrack(vt(t))));yield new qr(this.subhook,r,this.callbacks.onTrackUnpublish).execute(e,t)}}return Object.keys(l).forEach((t=>{const r=l[t];if(0===r.length)return;const i=r.map((t=>{const r=vt(t),{userId:i,tag:o,mediaType:s}=Ot(r),n=s===He.AUDIO_ONLY?new pt(o,i):new mt(o,i);return e.addRemoteTrack(n),n.__innerSetRemoteMuted(0===t.state),n}));this.callbacks.onTrackPublish(i)})),Object.keys(R).forEach((t=>{R[t].forEach((t=>{const r=vt(t),i=e.getRemoteTrack(r);i.__innerSetRemoteMuted(0===t.state),i.isAudioTrack()?this.callbacks.onAudioMuteChange(i):this.callbacks.onVideoMuteChange(i)}))})),e.roomMode===mr.LIVE&&this.executeInLivingRoom(e,_),r.info(L.L_ABSTRACT_ROOM_RECONNECTED_R,{status:A.SUCCESSED,roomData:_},{logSource:i.RTC}),{data:_}}))}executeInLivingRoom(e,t){var o,s;if(r.error(L.L_LIVING_ROOM_RECONNECTED_T,{roomData:t},{logSource:i.RTC}),!t)return void r.info(L.L_LIVING_ROOM_RECONNECTED_R,{status:A.FAILED,code:"",msg:"room not fond"},{logSource:i.RTC});const n=null===(o=t.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===o?void 0:o.value;if(!n)return void r.error(L.L_LIVING_ROOM_RECONNECTED_R,{status:A.FAILED,code:"",msg:"cdn_uris not found"},{logSource:i.RTC});const a=JSON.parse(n),c=(null===(s=e.getCDNUris())||void 0===s?void 0:s.enableInnerCDN)!==a.enableInnerCDN;e.setCDNUris(a),r.info(L.L_LIVING_ROOM_RECONNECTED_R,{status:A.SUCCESSED,roomData:t},{logSource:i.RTC}),c&&this.callbacks.onCDNEnableChange(a.enableInnerCDN)}}class ri extends br{constructor(e,t,r,i=hr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var r,i,o;return f(this,void 0,void 0,(function*(){const{tracks:s}=this,n=e.roomId;if(v.info(`unsubscribe -> roomId: ${n}, tracks: ${s.map($t)}`),this.state===hr.NORMAL){const i=e.getSubscribedList().slice(),{code:o,failedList:n}=yield new jr(s,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,i);return null===(r=this.callbacks)||void 0===r||r.onTaskCompleted({code:o,subscribe:c,unsubscribe:d,failedList:n}),{code:o,failedList:n}}if(this.state===hr.TAIL){const{code:r}=yield new ri(this.tracks,this.subhook,this.callbacks,hr.MIDDLE).execute(e,t);if(r===O.SUCCESS){const r=e.getCollectSubscribeList().slice(0),s=e.getSubscribedList().slice(),{code:n,failedList:a}=yield new jr(r,this.subhook).execute(e,t);if(n!==O.SUCCESS)return null===(i=this.callbacks)||void 0===i||i.onTaskCompleted({code:n,subscribe:[],unsubscribe:[],failedList:a}),{code:n,failedList:a};const c=e.getSubscribedList().slice(0),{subscribe:d,unsubscribe:_}=this.pickoutSubscribed(c,s);return null===(o=this.callbacks)||void 0===o||o.onTaskCompleted({code:n,subscribe:d,unsubscribe:_,failedList:a}),{code:n,failedList:a}}return{code:r}}return br.AsyncUpdateSubscribeTasks.splice(br.AsyncUpdateSubscribeTasks.length,0,...this.tracks),new Promise((t=>{const r=this.formateTrack(s);e.resetCollectSubscribeList(r),t({code:O.SUCCESS})}))}))}}class ii extends br{constructor(e,t,r,i=hr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var o;return f(this,void 0,void 0,(function*(){const{tracks:n}=this,a=e.roomId;if(this.state===hr.NORMAL){const r=e.getSubscribedList().slice(),{code:i,failedList:s}=yield new zr(n,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,r);return null===(o=this.callbacks)||void 0===o||o.onTaskCompleted({code:i,subscribe:c,unsubscribe:d,failedList:s}),{code:i,failedList:s}}if(r.info(L.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:n.map($t)},{logSource:i.RTC}),!s("tracks",n,(()=>d(n)&&n.length>0&&n.every((e=>e instanceof Rt||e.track instanceof Rt))),!0))return v.warn(`subscribe failed, tracks is invalid -> roomId: ${a}`),r.error(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};v.info(`subscribe -> roomId: ${a}, tracks: ${n.map($t)}`);const c=this.getSubscribedList(e).map((e=>Object.assign({},e))),_=n.map((e=>e instanceof Rt?{track:e}:e)),u=[];if(_.forEach((e=>{const t=e.track.getTrackId();u.push(t);const r=c.find((e=>e.track.getTrackId()===t));if(r){if(r.subTiny===e.subTiny)return;r.subTiny=e.subTiny}else c.push(e)})),e.polarisReport.sendR2(Tr.SUBSCRIBE,Ir.BEGIN,u),r.info(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:n.map($t),roomId:a},{logSource:i.RTC}),this.state===hr.TAIL){const{code:r}=yield new ii(this.tracks,this.subhook,this.callbacks,hr.MIDDLE).execute(e,t);if(r===O.SUCCESS){const r=e.getCollectSubscribeList().slice(0);return new ri(r,this.subhook,this.callbacks).execute(e,t)}return{code:r}}return br.AsyncSubscribeTasks.splice(br.AsyncSubscribeTasks.length,0,...this.tracks),new Promise((t=>{e.resetCollectSubscribeList(c),t({code:O.SUCCESS})}))}))}getSubscribedList(e){return this.state===hr.MIDDLE?e.getCollectSubscribeList():e.getSubscribedList()}}class oi extends br{constructor(e,t,r,i=hr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var o;return f(this,void 0,void 0,(function*(){const n=this.tracks,a=e.roomId;if(this.state===hr.NORMAL){const r=e.getSubscribedList().slice(),{code:i,failedList:s}=yield new Jr(n,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,r);return null===(o=this.callbacks)||void 0===o||o.onTaskCompleted({code:i,subscribe:c,unsubscribe:d,failedList:s}),{code:i,failedList:s}}if(r.info(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:n.map($t)},{logSource:i.RTC}),!s("tracks",n,(()=>d(n)&&n.length>0&&n.every((e=>e instanceof Rt))),!0))return v.warn(`unsubscribe failed, tracks is invalid -> roomId: ${a}`),r.warn(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};v.info(`unsubscribe -> roomId: ${a}, tracks: ${n.map($t)}`);const c=this.getSubscribedList(e).map((e=>Object.assign({},e))).filter((e=>!n.includes(e.track)));if(e.polarisReport.sendR2(Tr.SUBSCRIBE,Ir.END,n.map((e=>e.getTrackId()))),r.info(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:n.map($t),roomId:a},{logSource:i.RTC}),this.state===hr.TAIL){const{code:r}=yield new oi(this.tracks,this.subhook,this.callbacks,hr.MIDDLE).execute(e,t);if(r===O.SUCCESS){const r=e.getCollectSubscribeList().slice(0).map((e=>e.track));return new ri(r,this.subhook,this.callbacks).execute(e,t)}return{code:r}}return br.AsyncUnsubscribeTasks.splice(br.AsyncUnsubscribeTasks.length,0,...this.tracks),new Promise((t=>{e.resetCollectSubscribeList(c),t({code:O.SUCCESS})}))}))}getSubscribedList(e){return this.state===hr.MIDDLE?e.getCollectSubscribeList():e.getSubscribedList()}}const si="evt-leave";class ni extends t{constructor(e,t,r,i,o,s,n,a,c,d=jt()){super(),this._context=e,this._runtime=t,this._roomId=r,this._service=o,this._initOptions=s,this._useMutilPeerC=c,this._clientSessionId=d,this._appListener=null,this._reportListener=null,this._onRecvPKMsg=null,this._polarisReport=new Dr(this._context,this._runtime,this._roomId,this),this._peerCManager=new yr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._invoker=new wr(this._context,this._service,this._peerCManager,r,this._context.getCurrentId(),i,this._polarisReport,n,a),this._store=this._invoker.store}__innerInit(e,t,r,i,o){return f(this,void 0,void 0,(function*(){const{code:s,data:n}=yield this._invoker.push(new Vr(this._roomId,e,t,r,i,o));return s!==O.SUCCESS?{code:s}:(this._initWithRoomData(n.offlineKickTime),{code:s,data:n})}))}_initWithRoomData(e){var t;this._pinger=new Ht(this._store.roomId,this._store.roomMode,this._context,this._initOptions.pingGap,1e3*e),this._pinger.onFailed=this._kickoff.bind(this),this._pinger.onPingResult=this._handlePingResult.bind(this),this._pinger.start(),null===(t=this._polarisReport)||void 0===t||t.sendR1()}_handlePingResult(e){this._callAppListener("onPing",e)}setBitrate(e,t,r){if(this._useMutilPeerC)return void v.error("`RCAbstractRoom.setBitrate` is disabled, use `RCLocalTrack.setBitrate` instead.");v.warn("`RCAbstractRoom.setBitrate` will be deprecated, use `RCLocalTrack.setBitrate` instead."),m("max",e,(e=>o(e)&&e>Math.max(t||1,200)),!0),m("min",t,(t=>o(t)&&t>=1&&(!o(e)||t<e)),!0),m("start",r,(r=>o(r)&&r>t&&r<=e));this._peerCManager.getPCList().forEach((i=>{i.setBitrate(e,t,r)}))}_onTrackReady(e){const t=e.streams[0].id,r=e.receiver.track,i=[t,"audio"===r.kind?He.AUDIO_ONLY:He.VIDEO_ONLY].join("_"),o=this._store.getRemoteTrack(i);o?(o.__innerSetMediaStreamTrack(r),this._callAppListener("onTrackReady",o)):v.warn(`cannot found remote track ${r.id}`)}_callAppListener(e,...t){var o;"onPing"!==e&&r.info(L.L_ABSTRACT_ROOM_CALL_APP_LISTENER_O,{status:A.SUCCESSED,eventType:e,attrs:t},{logSource:i.RTC}),"onPing"!==e&&v.info(`${e} callback ->`,...t);const s=null===(o=this._appListener)||void 0===o?void 0:o[e];if(s)try{s(...t)}catch(e){v.error(e)}}_onTrackUnpublish(e){this._callAppListener("onTrackUnpublish",e)}__parseInnerMessage(e){const{targetId:t,conversationType:r}=e;if(r!==C.RTC_ROOM)return!1;if(t!==this._roomId)return!0;v.info(`recv inner msg -> message: ${JSON.stringify(e)} | roomid: ${this._roomId}`);const i=e.content;switch(e.messageType){case Gt.KICK:this._kickoff(!0,i);break;case Gt.STATE:this._stateHandle(i);break;case Gt.MODIFY:case Gt.PUBLISH:case Gt.UNPUBLISH:case Gt.TOTAL_CONTENT_RESOURCE:this._resourceHandle(i,e.messageType,e.senderUserId);break;case Gt.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",e.messageType,e.content);break;case Gt.USER_NOTIFY:v.warn(`TODO: ${Gt.USER_NOTIFY}`);break;case Gt.PK_INVITE:case Gt.PK_CANCEL_INVITE:case Gt.PK_INVITE_TIMEOUT:case Gt.PK_INVITE_ANSWER:case Gt.PK_END:this._onRecvPKMsg&&this._onRecvPKMsg(e);break;case Gt.OTHER_ROOM_OFFLINE:break;default:this._callAppListener("onMessageReceive",e.messageType,i,e.senderUserId,e.messageUId)}return!0}_kickoff(e,t){return f(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;let r,i;v.warn(`onKickOff -> byServer: ${e}`),this.emit(si),this._leaveHandle(!e),e&&((null==t?void 0:t.users)||[]).forEach((e=>{e.userId===this._context.getCurrentId()&&(i=e.type,r=e.kickExtra)})),this._callAppListener("onKickOff",e,i,r)}))}_rtcpeerClosed(){this.emit(si),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,t,r){return f(this,void 0,void 0,(function*(){const{uris:i,ignore:o}=e;!o&&i&&this._invoker.push(new Yr(e,t,r,this._subhook.bind(this),{onAudioMute:this._onAudioMuteChange.bind(this),onVideoMute:this._onVideoMuteChange.bind(this),onTrackPublish:this._onTrackPublish.bind(this),onTrackUnublish:this._onTrackUnpublish.bind(this),onCDNEnableChange:this._callAppListener.bind(this,"onCDNEnableChange")}))}))}_onTrackPublish(e){this._callAppListener("onTrackPublish",e)}_stateHandle(e){var t;return f(this,void 0,void 0,(function*(){const{left:r,joined:i,upgrade:o,downgrade:s}=yield this._invoker.push(new Wr(e,this._subhook.bind(this)));if(null===(t=this._appListener)||void 0===t?void 0:t.onSwitchRole)return o.length&&o.forEach((e=>this._callAppListener("onSwitchRole",e,ur.ANCHOR))),s.length&&s.forEach((e=>this._callAppListener("onSwitchRole",e,ur.AUDIENCE))),i.length&&this._callAppListener("onUserJoin",i),void(r.length&&this._callAppListener("onUserLeave",r));const n=[...i,...o],a=[...r,...s];n.length&&this._callAppListener("onUserJoin",n),a.length&&this._callAppListener("onUserLeave",a)}))}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}__getPC(){return this._store.peerMgr.getPCList()}getRemoteUserIds(){return this._store.getRemoteUserIds()}getRemoteTracks(){const e=[];return this.getRemoteUserIds().forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),e}getRemoteTracksByUserId(e){return this._store.getRemoteTracksByUserId(e)}getSessionId(){return this._store.getSessionId()}sendMessage(e,t){return f(this,void 0,void 0,(function*(){r.info(L.L_ABSTRACT_ROOM_SEND_MESSAGE_T,{name:e,content:t},{logSource:i.RTC});const{code:o}=yield this._context.sendMessage(C.RTC_ROOM,this._roomId,{messageType:e,content:t,isStatusMessage:!0});return o!==a.SUCCESS?(v.error(`send message failed -> code: ${o}`),r.error(L.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:A.FAILED,code:o,msg:""},{logSource:i.RTC}),{code:O.SIGNAL_ERROR}):(r.info(L.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:A.SUCCESSED,name:e,content:t},{logSource:i.RTC}),{code:O.SUCCESS})}))}setRoomAttribute(e,t,o,s=!1){return f(this,void 0,void 0,(function*(){r.info(L.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_T,{roomId:this._roomId,key:e,value:t,message:o,isInner:s},{logSource:i.RTC});const n=yield this._context.setRTCData(this._roomId,e,t,s,Sr.ROOM,o);return n!==a.SUCCESS?(v.error(`SetRoomAttributeValue Failed: ${n}`),r.error(L.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:A.FAILED,code:n,msg:""},{logSource:i.RTC}),{code:O.SIGNAL_ERROR}):(r.info(L.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:A.SUCCESSED,roomId:this._roomId,key:e,value:t,message:o,isInner:s},{logSource:i.RTC}),{code:O.SUCCESS})}))}deleteRoomAttributes(e,t,o=!1){return f(this,void 0,void 0,(function*(){r.info(L.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_T,{roomId:this._roomId,keys:e,message:t,isInner:o},{logSource:i.RTC});const s=yield this._context.removeRTCData(this._roomId,e,o,Sr.ROOM,t);return s!==a.SUCCESS?(v.error(`DeleteRoomAttribute Failed: ${s}`),r.error(L.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:A.FAILED,code:s,msg:""},{logSource:i.RTC}),{code:O.SIGNAL_ERROR}):(r.info(L.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:A.SUCCESSED,roomId:this._roomId,keys:e,message:t,isInner:o},{logSource:i.RTC}),{code:O.SUCCESS})}))}getRoomAttributes(e=[],t=!1){return f(this,void 0,void 0,(function*(){const{code:r,data:i}=yield this._context.getRTCData(this._roomId,e,t,Sr.ROOM);return r!==a.SUCCESS?(v.error(`GetRoomAttributes Failed: ${r}`),{code:O.SIGNAL_ERROR}):{code:O.SUCCESS,data:i}}))}_setUserAttributeValue(e,t,r){return this._context.setRTCData(this._roomId,e,t,!1,Sr.PERSON,r)}_deleteUserAttributes(e,t){return this._context.removeRTCData(this._roomId,e,!1,Sr.PERSON,t)}_getUserAttributes(e){return this._context.getRTCData(this._roomId,e,!1,Sr.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 f(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;this._invoker.destroy(),this._muteRemoteTracksBeforeQuit(),this._muteRemoteTracksBeforeQuit(),null===(t=this._audioLevelReport)||void 0===t||t.clearAudioLevelReportTimer(),e&&(yield this._context.quitRTCRoom(this._roomId)),this._store.isMainRoom&&(yield this._quitAllPKRoom()),this._pinger.stop();const r=[];Object.keys(this._peerCManager.getMutilPeerCData()).forEach((e=>{r.push(this._service.exit(this._getRTCReqestHeaders(e)))})),yield Promise.all(r),this._releasePCManager(),this._polarisReport=null}))}_releasePCManager(){const e=this._peerCManager.getPCList();null==e||e.forEach((e=>{e.off(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)})),this._peerCManager.clear(),this._peerCManager=null}_onLocalTrackDestroied(e){e instanceof nt&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(e,t){return f(this,void 0,void 0,(function*(){this._invoker.push(new Xr(e,t))}))}publish(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new Qr(e,this._pubhook.bind(this)))}))}_getPushOtherRoomsParams(){return[]}_reTryExchange(e,t){return f(this,void 0,void 0,(function*(){this._invoker.push(new ei(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 f(this,void 0,void 0,(function*(){return this._invoker.push(new Zr(e,((e,t)=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(t)}))))}))}_getResourceById(e){return this._store.getPublishedResourceByTrackId(e)}_isValidResourceId(e){var t;const{userId:r}=Ot(e);return!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>vt(t)===e)))}_subhook(e){const{pc:t,pcName:r}=this._peerCManager.createPeerCList(e)[0];return t.on(Nr.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),t.__reportR3R4ToPolaris(),t.registerReportListener(this._reportListener),t.clearReTryExchangeTimer(),{pc:t,pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(r)}}_pubhook(e){return{plist:this._peerCManager.createPeerCList(e).map((e=>{const{pc:t,pcName:r}=e;return t.on(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.on(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),t.registerReportListener(this._reportListener),t.__reportR3R4ToPolaris(),Object.assign(Object.assign({},e),{headers:this._getRTCReqestHeaders(r)})})),pushOtherRooms:this._getPushOtherRoomsParams()}}subscribe(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new zr(e,this._subhook.bind(this)))}))}addSubscribeTask(e){this._invoker.push(new ii(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}unsubscribe(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new Jr(e,this._subhook.bind(this)))}))}addUnsubscribeTask(e){this._invoker.push(new oi(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}updateSubList(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new jr(e,this._subhook.bind(this)))}))}addUpdateSubscribeListTask(e){this._invoker.push(new ri(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}_onTaskCompleted(e){this._callAppListener("onTaskCompleted",e.code,e.subscribe,e.unsubscribe,e.failedList)}getLocalTrack(e){return this._store.getLocalTrack(e)}getLocalTracks(){return this._store.getLocalTracks()}getRemoteTrack(e){return this._store.getRemoteTrack(e)||null}get subscribedTracks(){return this._store.getSubscribedList().slice()}registerRoomEventListener(e){r.info(L.L_ABSTRACT_ROOM_REGISTER_ROOM_EVENT_LISTENER_O,{status:A.SUCCESSED,listener:e&&Object.keys(e)},{logSource:i.RTC}),this._appListener=e}registerReportListener(e){r.info(L.L_ABSTRACT_ROOM_REGISTER_REPORT_LISTENER_O,{status:A.SUCCESSED,listener:e&&Object.keys(e)},{logSource:i.RTC}),this._reportListener=e}onAudioLevelChange(e,t){var o;r.info(L.L_ABSTRACT_ROOM_AUDIO_LEVEL_O,{status:A.SUCCESSED,handler:null==e?void 0:e.name,gap:t},{logSource:i.RTC}),null===(o=this._audioLevelReport)||void 0===o||o.clearAudioLevelReportTimer(),this._audioLevelReport=new kr(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}__onReconnected(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new ti(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 ai extends Ur{constructor(e,t){super(),this.data=e,this.cdnValues=t}execute(e,t){var r,i,o,s;return f(this,void 0,void 0,(function*(){const t={"App-Key":e.context.getAppkey(),Token:e.getToken(),RoomId:e.roomId,UserId:e.context.getCurrentId(),SessionId:e.getSessionId()},{code:n,res:a}=yield e.service.setMcuConfig(t,this.data);if(n!==O.SUCCESS)return v.error(`set MCU config failed: ${n}`),{code:n};v.info("set MCU config success"),a.pull_url&&e.setCDNUris(JSON.parse(a.pull_url));const c=this.cdnValues;return n===O.SUCCESS&&((null===(i=null===(r=c.output)||void 0===r?void 0:r.video.normal)||void 0===i?void 0:i.width)||(null===(s=null===(o=c.output)||void 0===o?void 0:o.video.normal)||void 0===s?void 0:s.fps))&&Kr(e),{code:n,res:a}}))}}var ci,di,_i,ui;!function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(ci||(ci={})),function(e){e[e.CUSTOMIZE=1]="CUSTOMIZE",e[e.SUSPENSION=2]="SUSPENSION",e[e.ADAPTATION=3]="ADAPTATION"}(di||(di={})),function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(_i||(_i={})),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"}(ui||(ui={}));const li=()=>({version:2,mode:di.SUSPENSION});class hi{constructor(e,t){this._invoker=e,this._isValidTrackId=t,this._values=li()}setHostVideoTrack(e){if(v.info(`setHostVideoTrack -> videoTrackId: ${e}`),!this._isValidTrackId(e))return v.error(`setHostVideoTrack failed -> videoTrackId is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:A.FAILED,code:"",msg:"params error -> videoTrackId"},{logSource:i.RTC}),this;const{mediaType:t,tag:o,userId:s}=Ot(e);return t!==He.VIDEO_ONLY?(v.error(`setHostVideoTrack failed -> kind of resource is not 'video' -> ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:A.FAILED,code:"",msg:"not video"},{logSource:i.RTC}),this):(this._values.host_stream_id=Lt(s,o),r.info(L.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:A.SUCCESSED,videoTrackId:e},{logSource:i.RTC}),this)}setMixLayoutMode(e){v.info(`setMixLayoutMode -> mode: ${e}`);return[di.CUSTOMIZE,di.SUSPENSION,di.ADAPTATION].includes(e)?(this._values.mode=e,r.info(L.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:A.SUCCESSED,mode:e},{logSource:i.RTC}),this):(v.error(`setMixLayoutMode failed -> mode is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:A.SUCCESSED,code:"",msg:`params error -> mode: ${e}`},{logSource:i.RTC}),this)}_addOutputValue(e,t,r="normal"){const i=this._values.output||(this._values.output={video:{normal:{width:640,height:480}}});if("cdn"===e)return void(i.cdn=t);if("audio"===e)return void(i.audio={bitrate:t});const o=i.video;if("normal"!==r&&"tiny"!==r)if("backgroundColor"!==r)if("exparams"!==r){if("backgroundPicture"===r){const e=o.backgroundPicture||(o.backgroundPicture={fillMode:ci.CROP,picture:[]});Object.assign(e,t)}}else o.exparams={renderMode:t};else o.backgroundColor=t;else{const e=o[r]||(o[r]={});Object.assign(e,t)}}setOutputVideoResolution(e){if(v.info(`setOutputVideoResolution -> resolution: ${e}`),!yt(e))return v.error(`setOutputVideoResolution failed -> resolution is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:A.FAILED,code:"",msg:`params error -> resolution: ${e}`},{logSource:i.RTC}),this;const{width:t,height:o}=kt(e);return this._addOutputValue("video",{width:t,height:o},"normal"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:A.SUCCESSED,resolution:e},{logSource:i.RTC}),this}setOutputVideoFPS(e){if(v.info(`setOutputVideoFPS -> fps: ${e}`),!Ut(e))return v.error(`setOutputVideoFPS failed -> fps is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:A.FAILED,code:"",msg:`params error -> fps: ${e}`},{logSource:i.RTC}),this;const t=bt(e);return this._addOutputValue("video",{fps:t},"normal"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:A.SUCCESSED,fps:e},{logSource:i.RTC}),this}setOutputVideoBitrate(e){return v.info(`setOutputVideoBitrate -> bitrate: ${e}`),!o(e)||e<=0?(v.error(`setOutputVideoBitrate failed -> bitrate is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:A.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:i.RTC})):this._addOutputValue("video",{bitrate:e},"normal"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:A.SUCCESSED,bitrate:e},{logSource:i.RTC}),this}setOutputTinyVideoResolution(e){if(v.info(`setOutputTinyVideoResolution -> resolution: ${e}`),!yt(e))return v.error(`setOutputTinyVideoResolution failed -> resolution is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:A.FAILED,code:"",msg:`params error -> resolution: ${e}`},{logSource:i.RTC}),this;const{width:t,height:o}=kt(e);return this._addOutputValue("video",{width:t,height:o},"tiny"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:A.SUCCESSED,resolution:e},{logSource:i.RTC}),this}setOutputTinyVideoFPS(e){if(v.info(`setOutputTinyVideoFPS -> fps: ${e}`),!Ut(e))return v.error(`setOutputTinyVideoFPS failed -> fps is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:A.FAILED,code:"",msg:`params error -> fps: ${e}`},{logSource:i.RTC}),this;const t=bt(e);return this._addOutputValue("video",{fps:t},"tiny"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:A.SUCCESSED,fps:e},{logSource:i.RTC}),this}setOutputTinyVideoBitrate(e){return v.info(`setOutputTinyVideoBitrate -> bitrate: ${e}`),!o(e)||e<=0?(v.error(`setOutputTinyVideoBitrate failed -> bitrate is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:A.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:i.RTC})):this._addOutputValue("video",{bitrate:e},"tiny"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:A.SUCCESSED,bitrate:e},{logSource:i.RTC}),this}setOutputVideoRenderMode(e){return v.info(`setOutputVideoRenderMode -> renderMode: ${e}`),[_i.CROP,_i.WHOLE].includes(e)?this._addOutputValue("video",e,"exparams"):(v.error(`setOutputVideoRenderMode failed -> renderMode is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:A.FAILED,code:"",msg:`params error -> renderMode: ${e}`},{logSource:i.RTC})),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:A.SUCCESSED,renderMode:e},{logSource:i.RTC}),this}setOutputAudioBitrate(e){return v.info(`setOutputAudioBitrate -> bitrate: ${e}`),o(e)&&e>0?this._addOutputValue("audio",e):(v.error(`setOutputAudioBitrate failed -> bitrate is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:A.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:i.RTC})),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:A.SUCCESSED,bitrate:e},{logSource:i.RTC}),this}setOutputBackgroundColor(e){return v.info(`setOutputBackgroundColor -> color: ${e}`),/^0x[a-fA-F0-9]{6}$/.test(e)?this._addOutputValue("video",e,"backgroundColor"):(v.error(`setOutputBackgroundColor failed -> color is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:A.FAILED,code:"",msg:`params error -> color: ${e}`},{logSource:i.RTC})),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:A.SUCCESSED,color:e},{logSource:i.RTC}),this}addOutputBackgroundPicture(e,t,s,n,a){var c,d,_;if(v.info(`addOutputBackgroundPicture -> uri: ${e}, x: ${t}, y: ${s}, w: ${n}, h: ${a}`),!T(e))return v.error(`addOutputBackgroundPicture failed -> uri is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:A.FAILED,code:"",msg:`params error -> uri: ${e}`},{logSource:i.RTC}),this;if([t,s,n,a].some((e=>!o(e)||e<0||e>1)))return v.error(`addOutputBackgroundPicture failed -> some attrs of (x, y, w, h) is invalid: ${t}, ${s}, ${n}, ${a}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:A.FAILED,code:"",msg:`params error -> x: ${t}, y: ${s}, w: ${n}, h: ${a}`},{logSource:i.RTC}),this;const u=(null===(_=null===(d=null===(c=this._values.output)||void 0===c?void 0:c.video)||void 0===d?void 0:d.backgroundPicture)||void 0===_?void 0:_.picture)||[];return u.push({uri:e,w:n,h:a,x:t,y:s}),this._addOutputValue("video",{picture:u},"backgroundPicture"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:A.SUCCESSED,uri:e,x:t,y:s,w:n,h:a},{logSource:i.RTC}),this}removeOutputBackgroundPicture(e){var t,o,s;if(v.info(`removeOutputBackgroundPicture -> uri: ${e}`),!T(e))return v.error(`removeOutputBackgroundPicture failed -> uri is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:A.FAILED,code:"",msg:`params error -> uri: ${e}`},{logSource:i.RTC}),this;let n=null===(s=null===(o=null===(t=this._values.output)||void 0===t?void 0:t.video)||void 0===o?void 0:o.backgroundPicture)||void 0===s?void 0:s.picture;return n&&(n=n.filter((t=>t.uri!==e)),this._addOutputValue("video",{pictures:n},"backgroundPicture")),r.info(L.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:A.SUCCESSED,uri:e},{logSource:i.RTC}),this}clearOutputBackgroundPicture(){return v.info("clearOutputBackgroundPicture ->"),this._addOutputValue("video",{pictures:[]},"backgroundPicture"),r.info(L.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:A.SUCCESSED},{logSource:i.RTC}),this}setOutputBackgroundPictureFillMode(e){return v.info(`setOutputBackgroundPictureFillMode -> fillMode: ${e}`),[ci.CROP,ci.WHOLE].includes(e)?this._addOutputValue("video",{fillMode:e},"backgroundPicture"):(v.error(`setOutputBackgroundPictureFillMode failed -> fillMode is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:A.FAILED,code:"",msg:`params error -> fillMode: ${e}`},{logSource:i.RTC})),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:A.SUCCESSED,fillMode:e},{logSource:i.RTC}),this}addPublishStreamUrls(e){var t,o;v.info(`addPublishStreamUrls -> urls: ${e.join(",")}`);const s=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!s.test(e))))return v.error(`addPublishStreamUrls failed -> urls is invalid: ${e.join(",")}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:A.FAILED,code:"",msg:`params error -> urls: ${e.join(",")}`},{logSource:i.RTC}),this;const n=(null===(o=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===o?void 0:o.concat())||[];let a=!1;return e.forEach((e=>{n.some((t=>t.pushurl===e))||(a=!0,n.push({pushurl:e}))})),n.length>5?(v.error("addPublishStreamUrls failed -> publish stream urls no more than 5!"),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:A.FAILED,code:"",msg:`params error -> publish stream urls no more than 5, length: ${e.length}`},{logSource:i.RTC}),this):(a&&this._addOutputValue("cdn",n),r.info(L.L_MCU_CONFIG_BUILDER_ADD_PUBLISH_STREAM_URLS_O,{status:A.SUCCESSED,urls:e},{logSource:i.RTC}),this)}removePublishStreamUrls(e){var t,o;v.info(`removePublishStreamUrls -> urls: ${e.join(",")}`);const s=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!s.test(e))))return v.error(`removePublishStreamUrls failed -> urls contain invalid items: ${e.join(",")}`),r.error(L.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:A.FAILED,code:"",msg:`params error -> urls: ${e.join(",")}`},{logSource:i.RTC}),this;const n=(null===(o=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===o?void 0:o.concat())||[];for(let t=n.length-1;t>=0;t-=1){const{pushurl:r}=n[t],i=e.indexOf(r);i>=0&&(e.splice(i,1),n.splice(t,1))}return this._addOutputValue("cdn",n),r.info(L.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:A.SUCCESSED,urls:e},{logSource:i.RTC}),this}clearPublishStreamUrls(){return v.info("clearPublishStreamUrls ->"),this._addOutputValue("cdn",[]),r.info(L.L_MCU_CONFIG_BUILDER_CLEAR_PUBLISH_STREAM_URLS_O,{status:A.SUCCESSED},{logSource:i.RTC}),this}addCustomizeLayoutVideo(e,t,s,n,a){if(v.info(`addCustomizeLayoutVideo -> trackId: ${e}, x: ${t}, y: ${s}, width: ${n}, height: ${a}`),!R(e)||!this._isValidTrackId(e))return v.error(`addCustomizeLayoutVideo failed -> trackId is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;if(!o(t)||!o(s))return v.error(`addCustomizeLayoutVideo failed -> some attrs of (x, y) is invalid: ${t}, ${s}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:`params error -> x: ${t}, y: ${s}`},{logSource:i.RTC}),this;if([n,a].some((e=>!o(e)||e<0)))return v.error(`addCustomizeLayoutVideo failed -> some attrs of (width, height) is invalid: ${n}, ${a}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:`params error -> width: ${n}, height: ${a}`},{logSource:i.RTC}),this;const{userId:c,tag:d,mediaType:_}=Ot(e);if(_!==He.VIDEO_ONLY)return v.error(`addCustomizeLayoutVideo failed -> kind of trackId is not 'video': ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}的资源不是视频`},{logSource:i.RTC}),this;const u=Lt(c,d),l=this._values.input||(this._values.input={}),h=l.video||(l.video=[]);return h.some((e=>e.height===a&&e.width===n&&e.stream_id===u&&e.user_id===c&&e.x===t&&e.y===s))?(r.warn(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:"Duplicate configuration item ignored"},{logSource:i.RTC}),this):(h.push({user_id:c,stream_id:u,x:t,y:s,width:n,height:a}),r.info(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.SUCCESSED,trackId:e,x:t,y:s,width:n,height:a},{logSource:i.RTC}),this)}removeCustomizeLayoutVideo(e){if(v.info(`clearCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return v.error(`clearCustomizeInputAudio failed -> trackId is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const{userId:t,tag:o,mediaType:s}=Ot(e);if(s!==He.VIDEO_ONLY)return v.error(`clearCustomizeInputAudio failed -> kind of trackId is not 'video': ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}的资源不是视频`},{logSource:i.RTC}),this;const n=Lt(t,o),a=this._values.input;return(null==a?void 0:a.video)&&a.video.length>0&&(a.video=a.video.filter((e=>e.stream_id===n))),r.info(L.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.SUCCESSED,trackId:e},{logSource:i.RTC}),this}clearCustomizeLayoutVideo(){v.info("clearCustomizeLayoutVideo ->");const e=this._values.input;return null==e||delete e.video,r.info(L.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.SUCCESSED},{logSource:i.RTC}),this}setCustomizeInputAudio(e){if(v.info(`setCustomizeInputAudio -> trackIds: ${e.join(",")}`),e.some((e=>this._isValidTrackId(e))))return v.warn(`setCustomizeInputAudio failed -> trackIds contain invalid items: $${e.join(",")}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:A.FAILED,code:"",msg:`params error -> trackIds: ${e.join(",")}`},{logSource:i.RTC}),this;return(this._values.input||(this._values.input={})).audio=e.map((e=>{const{userId:t,tag:r}=Ot(e);return{stream_id:Lt(t,r),user_id:t}})),this._values.inputFilterMode=ui.AUDIO_INPUT_VIDEO_ALL,r.info(L.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:A.SUCCESSED,trackIds:e},{logSource:i.RTC}),this}addCustomizeInputAudio(e){if(v.info(`addCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return v.warn(`addCustomizeInputAudio failed -> trackId is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const t=this._values.input||(this._values.input={}),o=t.audio||(t.audio=[]),{userId:s,tag:n}=Ot(e),a=Lt(s,n);return o.some((e=>e.stream_id===a&&e.user_id===s))?(r.warn(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:A.FAILED,code:"",msg:`trackId:${e} is exist`},{logSource:i.RTC}),this):(o.push({user_id:s,stream_id:a}),this._values.inputFilterMode=ui.AUDIO_INPUT_VIDEO_ALL,r.info(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:A.SUCCESSED,trackId:e},{logSource:i.RTC}),this)}removeCustomizeInputAudio(e){if(v.info(`removeCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return v.error(`removeCustomizeInputAudio failed -> trackId is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const t=this._values.input;if(!(null==t?void 0:t.audio)||0===t.audio.length)return r.error(L.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:A.FAILED,code:"",msg:"not audio"},{logSource:i.RTC}),this;const{userId:o,tag:s}=Ot(e),n=Lt(o,s);return t.audio=t.audio.filter((e=>o!==e.user_id||n!==e.stream_id)),r.info(L.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:A.SUCCESSED,trackId:e},{logSource:i.RTC}),this}clearCustomizeInputAudio(){v.info("clearCustomizeInputAudio ->");const e=this._values.input;return(null==e?void 0:e.audio)&&delete e.audio,this._values.inputFilterMode=ui.AUDIO_VIDEO_ALL,r.info(L.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_INPUT_AUDIO_O,{status:A.SUCCESSED},{logSource:i.RTC}),this}addPictureWaterMark(e,t,s,n,a,c){if(v.info(`addPictureWaterMark -> trackId: ${e} uri: ${t}, x: ${s}, y: ${n}, w: ${a}, h: ${c}`),!this._isValidTrackId(e))return v.warn(`addPictureWaterMark failed -> trackId is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;if(!T(t))return v.error(`addPictureWaterMark failed -> uri is invalid: ${t}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:A.FAILED,code:"",msg:`params error -> uri: ${t}`},{logSource:i.RTC}),this;if([s,n,a,c].some((e=>!o(e)||e<0||e>1)))return v.error(`addPictureWaterMark failed -> some attrs of (x, y, w, h) is invalid: ${s}, ${n}, ${a}, ${c}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:A.FAILED,code:"",msg:`params error -> x: ${s}, y: ${n}, w: ${a}, h: ${c}`},{logSource:i.RTC}),this;const{userId:d,tag:_}=Ot(e),u=Lt(d,_),l=(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen;v.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(l)}`);const h=l.filter((e=>e.streamId===u))[0];return v.info(`addPictureWaterMark target-> : ${h}`),h?h.picture.push({uri:t,w:a,h:c,x:s,y:n}):l.push({streamId:u,picture:[{uri:t,w:a,h:c,x:s,y:n}]}),v.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(l)}`),this._values.waterMark.singleScreen=l,v.info(`addPictureWaterMark this._values.waterMark.singleScreen-> : ${JSON.stringify(this._values.waterMark.singleScreen)}`),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:A.SUCCESSED,trackId:e,uri:t,x:s,y:n,w:a,h:c},{logSource:i.RTC}),this}clearPictureWaterMark(){v.info("clearOutputBackgroundPicture ->");return(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen=[],r.info(L.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:A.SUCCESSED},{logSource:i.RTC}),this}removePictureWaterMark(e,t){if(!R(e)||!this._isValidTrackId(e))return r.error(L.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const{userId:o,tag:s}=Ot(e),n=Lt(o,s);return(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen.forEach((e=>{e.streamId===n&&(e.picture=e.picture.filter((e=>e.uri!==t)))})),r.info(L.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O,{status:A.SUCCESSED,trackId:e,uri:t},{logSource:i.RTC}),this}reset(){return v.info("MCUConfigBuilder.reset ->"),this._values=li(),r.info(L.L_MCU_CONFIG_BUILDER_RESET_O,{status:A.SUCCESSED},{logSource:i.RTC}),this}flush(e=!0){return f(this,void 0,void 0,(function*(){const t=JSON.parse(JSON.stringify(this._values)),{code:o}=yield this._invoker.push(new ai(t,this._values));return e&&(this._values=li()),r.info(L.L_MCU_CONFIG_BUILDER_FLUSH_O,{status:A.SUCCESSED},{logSource:i.RTC}),{code:o}}))}__innerGetValues(){return JSON.parse(JSON.stringify(this._values))}}var Ri,pi,mi,Ci;!function(e){e[e.VIDEO=0]="VIDEO",e[e.AUDIO=1]="AUDIO"}(Ri||(Ri={})),function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(pi||(pi={}));class Ti extends Ur{constructor(e,t,r){super(),this.roomId=e,this.hooks=t,this.roomPKHandler=r}_exchangeWithPushOtherRoom(e,t){return f(this,void 0,void 0,(function*(){if(!e.getLocalTracks().length)return;const r=Object.values(e.peerMgr.getMutilPeerCData()),i=Object.keys(e.peerMgr.getMutilPeerCData());for(let o=0;o<r.length;o++){const{pc:s,isPub:n}=r[o],a=n&&e.useMutilPeerC?[]:e.getSubscribedList(),c=yield $r(a,!1,s,e),{pushOtherRooms:d,headers:_}=this.hooks(i[o]);c.pushOtherRooms=d;const u=yield new Hr(_,c).execute(e,t);if(u.code!==O.SUCCESS)return void v.error(`exchange with pushOtherRoom failed: ${u.code}`);const{sdp:l,resultCode:h}=u.data;if(h!==O.SUCCESS)return void v.error(`exchange with pushOtherRoom failed: ${h}`);s.setRemoteAnswer(l.sdp)}}))}execute(e,t){return f(this,void 0,void 0,(function*(){const{roomId:o}=this;if(r.info(L.L_LIVING_ROOM_JOINED_PK_ROOM_T,{roomId:o,userId:e.crtUserId},{logSource:i.RTC}),!this.roomPKHandler)return void r.error(L.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:A.FAILED,code:"",msg:"_roomPKHandler not exist"},{logSource:i.RTC});const s=this.roomPKHandler.getPKInfo(o);if(!s)return v.warn(`exchange to update pushOtherRoom cancel, pkInfo lost -> roomId: ${o}`),void r.error(L.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:A.FAILED,code:"",msg:"PKInfo not exist"},{logSource:i.RTC});yield this._exchangeWithPushOtherRoom(e,t),r.info(L.L_LIVING_ROOM_JOINED_PK_ROOM_T,{status:A.SUCCESSED,roomId:o,userId:e.crtUserId,PKInfo:s},{logSource:i.RTC})}))}}class Ii extends Ur{constructor(e,t,r,i,o,s){super(),this.pkHandler=e,this.room=t,this._PKInfo=r,this.hooks=i,this._joinedPKRooms=o,this.isQuitPK=s}get kind(){return lr.LeaveRoom}quitRoomPK(e,t){return f(this,void 0,void 0,(function*(){if(!this._PKInfo[e])return;const{inviterRoomId:r,inviteeRoomId:i,inviterUserId:o,inviteSessionId:s}=this._PKInfo[e],n={inviteeRoomId:i,inviterRoomId:r,userId:t.crtUserId},c={roomId:t.roomId,endRoomId:e,sessionId:s,content:JSON.stringify(n),keys:[`${r}|${o}`]};v.info(`quitRoomPK -> params: ${JSON.stringify(c)}`);const d=yield t.context.endRoomPK(c);return d!==a.SUCCESS?(v.error(`quitRoomPK failed: ${d}`),{code:O.SIGNAL_ERROR}):(v.info("quitRoomPK success"),delete this._PKInfo[e],{code:O.SUCCESS})}))}execute(e,t){return f(this,void 0,void 0,(function*(){const{room:o,isQuitPK:s}=this,n=o.getRoomId();return v.info(`leavePKRoom -> userId: ${e.crtUserId} , roomId: ${n}`),r.info(L.L_LIVING_ROOM_LEAVE_PK_ROOM_T,{roomId:n,userId:e.crtUserId,isQuitPK:s},{logSource:i.RTC}),yield o.__destroy(!0),delete this._joinedPKRooms[n],yield new Ti(n,this.hooks,this.pkHandler).execute(e,t),s&&this.quitRoomPK(n,e),r.info(L.L_LIVING_ROOM_LEAVE_PK_ROOM_R,{status:A.SUCCESSED,roomId:n,userId:e.crtUserId,isQuitPK:s},{logSource:i.RTC}),{code:O.SUCCESS}}))}}class Ei{constructor(e,t,r,i,o,s,n,a,c,d,_){this._invoker=e,this._PKInfo=t,this._hooks=r,this._context=i,this._runtime=o,this._service=s,this._initOptions=n,this._mainLivingRoom=a,this._registerPKMsgListener=c,this._onJoinedPKRoom=d,this._clientSessionId=_,this._inviteTimeout=30,this._appListener=null,this._joinedPKRooms={},this._registerPKMsgListener(this._onRecvPKMsg.bind(this)),this._mainRoomId=this._mainLivingRoom.getRoomId()}_callAppListener(e,...t){var r;v.info(`${e} callback ->`,...t);const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){v.error(e)}}_onInvite(e){const t=e.inviteInfo||{},{inviterRoomId:r,inviterUserId:i,extra:o}=t,s={inviterRoomId:r,inviterUserId:i,extra:o};this._PKInfo[r]=t,this._callAppListener("onRequestJoinOtherRoom",s)}_onCancelInvite(e){const{inviterRoomId:t,inviterUserId:r,extra:i}=e.inviteInfo||{},o={inviterRoomId:t,inviterUserId:r,extra:i};delete this._PKInfo[t],this._callAppListener("onCancelRequestOtherRoom",o)}_onInviteTimeout(e){}_onInviteAnswer(e){const{answerCode:t,inviteContent:r}=e,{inviteSessionId:i,inviterUserId:o,inviterRoomId:s,inviteeUserId:n,inviterUserAutoMix:a,inviteeUserAutoMix:c,inviteeRoomId:d,extra:_}=r,u={agree:1===t,inviterRoomId:s,inviterUserId:o,inviteeRoomId:d,inviteeUserId:n,extra:_};this._PKInfo[d]=this._PKInfo[d]||{inviteSessionId:i,inviterRoomId:s,inviterUserId:o,inviterUserAutoMix:a,inviteeRoomId:d},this._PKInfo[d].inviteeUserAutoMix=c,this._callAppListener("onResponseJoinOtherRoom",u)}createLeaveOtherRoomCommand(e,t){return new Ii(this,e,this._PKInfo,this._hooks,this._joinedPKRooms,t)}_onPKEnd(e){return f(this,void 0,void 0,(function*(){const{inviteeRoomId:t,inviterRoomId:r,userId:i}=e.inviteInfo,o=r===this._mainRoomId?t:r,s={endRoomId:o,endUserId:i},n=this._joinedPKRooms[o];n&&(yield this._invoker.push(this.createLeaveOtherRoomCommand(n))),delete this._PKInfo[o],this._callAppListener("onFinishOtherRoom",s)}))}_onRecvPKMsg(e){const{targetId:t,content:r,messageType:i}=e;switch(i){case Gt.PK_INVITE:this._onInvite(r);break;case Gt.PK_CANCEL_INVITE:this._onCancelInvite(r);break;case Gt.PK_INVITE_TIMEOUT:this._onInviteTimeout(r);break;case Gt.PK_INVITE_ANSWER:this._onInviteAnswer(r);break;case Gt.PK_END:this._onPKEnd(r)}}registerRoomPKEventListener(e){r.info(L.L_LIVING_PK_HANDLER_REGISTER_ROOM_PK_EVENT_LISTENER_O,{status:A.SUCCESSED,listener:e&&Object.keys(e)},{logSource:i.RTC}),this._appListener=e}requestJoinOtherRoom(e,t,o){return f(this,void 0,void 0,(function*(){if(r.info(L.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:e,inviteeUserId:t,options:o},{logSource:i.RTC}),!s("inviteeRoomId",e,R,!0)||!s("inviteeUserId",t,R,!0))return r.error(L.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> inviteeRoomId 或 inviteeUserId"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};v.info(`requestRoomPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; options: ${JSON.stringify(o||{})}`);const n=jt(),c=!I(null==o?void 0:o.autoMix)||(null==o?void 0:o.autoMix),d={inviteSessionId:n,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:c,inviteeRoomId:e,inviteeUserId:t,inviteeTimeoutTime:this._inviteTimeout,extra:(null==o?void 0:o.extra)||""},_={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteTimeout:this._inviteTimeout,inviteInfo:JSON.stringify(d),inviteSessionId:n};v.info(`requestRoomPK -> params: ${JSON.stringify(_)}`);const u=yield this._context.requestRoomPK(_);return u!==a.SUCCESS?(v.error(`requestRoomPK failed: ${u}`),r.error(L.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:u,msg:""},{logSource:i.RTC}),{code:u}):(v.info("requestRoomPK success"),this._PKInfo[e]={inviteSessionId:n,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:c,inviteeRoomId:e},r.info(L.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{inviteeRoomId:e,inviteeUserId:t,options:o},{logSource:i.RTC}),{code:O.SUCCESS})}))}cancelRequestJoinOtherRoom(e,t,o){return f(this,void 0,void 0,(function*(){if(r.info(L.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:e,inviteeUserId:t,extra:o,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),!s("inviteeRoomId",e,R,!0)||!s("inviteeUserId",t,R,!0))return r.error(L.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> inviteeRoomId or inviteeUserId"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(!this._PKInfo[e])return v.error(`The request to connect with ${t} user in room ${e} is not initiated`),r.error(L.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:`The request to connect with ${t} user in room ${e} is not initiated`},{logSource:i.RTC}),{code:O.PARAMS_ERROR};v.info(`canceRequestJoinPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; extra: ${o}`);const n={inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviteeRoomId:e,inviteeUserId:t,extra:o||""},c={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteSessionId:this._PKInfo[e].inviteSessionId,inviteInfo:JSON.stringify(n)};v.info(`canceRequestJoinPK -> params: ${JSON.stringify(c)}`);const d=yield this._context.cancelRoomPK(c);return d!==a.SUCCESS?(v.error(`canceRequestJoinPK failed: ${d}`),r.error(L.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:d,msg:`The request to connect with ${t} user in room ${e} is not initiated`},{logSource:i.RTC}),{code:d}):(v.info("canceRequestJoinPK success"),r.info(L.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:A.SUCCESSED,inviteeRoomId:e,inviteeUserId:t,extra:o},{logSource:i.RTC}),delete this._PKInfo[e],{code:O.SUCCESS})}))}responseJoinOtherRoom(e,t,o,n){return f(this,void 0,void 0,(function*(){if(r.info(L.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_T,{inviterRoomId:e,inviterUserId:t,agree:o,options:n,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),!s("inviterRoomId",e,R,!0)||!s("inviterUserId",t,R,!0))return r.error(L.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> inviterRoomId or inviterUserId"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(!this._PKInfo[e])return v.error(`User ${t} in room ${e} did not send a request for connection`),r.error(L.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:`User ${t} in room ${e} did not send a request for connection`},{logSource:i.RTC}),{code:O.PARAMS_ERROR};v.info(`responseRoomPK -> inviterRoomId: ${e}; inviterUserId: ${t}; agree: ${o}; options: ${JSON.stringify(n||{})}`);const{inviteSessionId:c,inviterUserAutoMix:d}=this._PKInfo[e],_=!I(null==n?void 0:n.autoMix)||(null==n?void 0:n.autoMix),u={inviteSessionId:c,inviterRoomId:e,inviterUserId:t,inviterUserAutoMix:d,inviteeRoomId:this._mainRoomId,inviteeUserId:this._context.getCurrentId(),inviteeUserAutoMix:_},l=Object.assign(u,{inviterUserAutoMix:d}),h=o?Object.assign(u,{MultiRoomKey:`${e}|${this._mainRoomId}`,MultiRoomValue:JSON.stringify(l)}):u;!E(null==n?void 0:n.extra)&&Object.assign(h,{extra:n.extra});const p={agree:o,roomId:this._mainRoomId,inviteSessionId:c,inviteRoomId:e,inviteUserId:t,content:JSON.stringify(h),key:`${e}|${this._mainRoomId}`,value:JSON.stringify(u)};v.info(`responseRoomPK -> params: ${JSON.stringify(p)}`);const m=yield this._context.responseRoomPK(p);return m!==a.SUCCESS?(v.error(`responseRoomPK failed: ${m}`),r.error(L.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:m,msg:""},{logSource:i.RTC}),{code:m}):(v.info("responseRoomPK success"),r.info(L.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:A.SUCCESSED,inviterRoomId:e,inviterUserId:t,agree:o,options:n,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),this._PKInfo[e].inviteeUserAutoMix=_,{code:O.SUCCESS})}))}joinOtherRoom(e){return f(this,void 0,void 0,(function*(){if(r.info(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_T,{roomId:e,userId:this._context.getCurrentId()},{logSource:i.RTC}),!s("roomId",e,R,!0))return r.error(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(this._context.getConnectionStatus()!==u.CONNECTED)return r.error(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.SIGNAL_DISCONNECTED,msg:"IM disconnected"},{logSource:i.RTC}),{code:O.SIGNAL_DISCONNECTED};if(v.info(`JoinPKRoom, roomId: ${e}`),this._joinedPKRooms[e])return r.warn(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:O.REPERT_JOIN_ROOM};const t=Ri.VIDEO,o={extra:`{"roomId": "${this._mainRoomId}"}`},n=new fi(this._context,this._runtime,e,this._service,this._initOptions,t,!1,!1,!1,this._clientSessionId),{code:a,data:c}=yield n.__innerInit(mr.LIVE,void 0,t,o);return a!==O.SUCCESS?(v.error(`JoinPKRoom failed -> code: ${a}`),r.error(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:a,msg:""},{logSource:i.RTC}),{code:a}):(v.info(`JoinPKRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(c)}`),this._joinedPKRooms[e]=n,yield this._onJoinedPKRoom(e,n),r.info(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.SUCCESSED,roomId:e,userId:this._context.getCurrentId()},{logSource:i.RTC}),{room:n,code:O.SUCCESS,userIds:n.getRemoteUserIds(),tracks:n.getRemoteTracks()})}))}leaveOtherRoom(e,t){return f(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"}(mi||(mi={}));class Si extends Ur{constructor(e,t){super(),this.cdnValues=e,this.enable=t}execute(e,t){return f(this,void 0,void 0,(function*(){const{enable:o}=this;if(r.info(L.L_LIVING_ROOM_ENABLE_INNER_CDN_T,{roomId:e.roomId,enable:o},{logSource:i.RTC}),!e.isMainRoom)return v.error("the `enableInnerCDN` is disabled in PK room"),r.error(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.FAILED,code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!I(o))return v.error("`enable` is invalid"),r.error(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> enable"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};e.setCDNEnabel(o);const s={version:2,output:{inCDNModel:o?mi.OPEN:mi.STOP}},{code:n}=yield new ai(s,this.cdnValues).execute(e,t);if(n!==O.SUCCESS)return v.error(`enableInnerCDN failed -> code: ${n}`),r.error(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.FAILED,code:n,msg:"signal error"},{logSource:i.RTC}),{code:O.SIGNAL_ERROR};const a=e.getCDNUris();if(a&&a.broadcast!==Er.SPREAD)return v.info("enableInnerCDN succeed"),r.info(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.SUCCESSED,enable:o},{logSource:i.RTC}),{code:O.SUCCESS};const{code:c}=yield Kr(e);return c===O.SUCCESS?(v.info("enableInnerCDN succeed"),r.info(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.SUCCESSED,enable:o},{logSource:i.RTC}),{code:O.SUCCESS}):(v.error(`enableInnerCDN failed -> code: ${c}`),r.error(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.FAILED,code:c,msg:""},{logSource:i.RTC}),{code:c})}))}}!function(e){e[e.AnchorToViewer=1]="AnchorToViewer",e[e.ViewerToAnchor=2]="ViewerToAnchor"}(Ci||(Ci={}));class gi extends Ur{constructor(e){super(),this.livingType=e}execute(e,t){var r;return f(this,void 0,void 0,(function*(){const{code:i,data:o}=yield e.context.rtcIdentityChange(e.roomId,Ci.ViewerToAnchor,this.livingType);if(i!==a.SUCCESS||!o)return{code:i};e.initWithRoomData(o);e.getResourcesByUserId(e.crtUserId).length>0&&t.push(new Br);const s=null===(r=o.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===r?void 0:r.value;return s&&e.setCDNUris(JSON.parse(s)[0]),{code:i,data:o}}))}}class fi extends ni{constructor(e,t,r,i,o,s,n,a,c,d){super(e,t,r,mr.LIVE,i,o,n,a,c,d),this._livingType=s,this._mcuConfigBuilder=new hi(this._invoker,this._isValidResourceId.bind(this))}_initAfterCatchRoomData(e){if(this._store.isUpgrade&&this._afterChangedRole(e),this._store.isMainRoom){const t=((e,t)=>{const r={};return t.forEach((t=>{const i=JSON.parse(t.value),{inviterRoomId:o,inviteeRoomId:s}=i;r[e===o?s:o]=JSON.parse(t.value)})),r})(this._roomId,e.roomInfo);this._roomPKHandler=new Ei(this._invoker,t,(e=>({headers:this._getRTCReqestHeaders(e),pushOtherRooms:this._getPushOtherRoomsParams()})),this._context,this._runtime,this._service,this._initOptions,this,super._registerPKMsgListener.bind(this),this._onJoinedPKRoom.bind(this),this._clientSessionId)}}__innerInit(e,t,o,n,a){const c=Object.create(null,{__innerInit:{get:()=>super.__innerInit}});return f(this,void 0,void 0,(function*(){if(!s("livingType",o,(e=>e===Ri.AUDIO||e===Ri.VIDEO)))return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> livingType"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};const{code:d,data:_}=yield c.__innerInit.call(this,e,t,o,n,a);return d===O.SUCCESS&&_&&this._initAfterCatchRoomData(_),{code:d,data:_}}))}__innerInitByIdentityChange(){return f(this,void 0,void 0,(function*(){const{code:e,data:t}=yield this._invoker.push(new gi(this._livingType));return e===a.SUCCESS&&t&&(this._initAfterCatchRoomData(t),this._initWithRoomData(t.offlineKickTime),r.info(L.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:A.SUCCESSED,roomData:t},{logSource:i.RTC})),e}))}publish(e){const t=Object.create(null,{publish:{get:()=>super.publish}});return f(this,void 0,void 0,(function*(){return this._store.isMainRoom?t.publish.call(this,e):(v.warn("the `publish` is disabled in PK room "),r.error(L.L_ABSTRACT_ROOM_PUBLISH_R,{status:A.FAILED,code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}unpublish(e){const t=Object.create(null,{unpublish:{get:()=>super.unpublish}});return f(this,void 0,void 0,(function*(){return this._store.isMainRoom?t.unpublish.call(this,e):(v.warn("the `unpublish` is disabled in PK room "),r.error(L.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:A.FAILED,code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}_isValidResourceId(e){var t;const{userId:r}=Ot(e),i=!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>vt(t)===e)));let o=!1;const{code:s,roomPKHandler:n}=this.getRoomPKHandler();if(s!==O.SUCCESS||!n)return i;const a=n.getJoinedPKRooms(),c=[];return Object.values(a).map((e=>{c.push(...e.getRemoteTracks())})),o=c.some((t=>e===t.getTrackId())),i||o}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._store.isMainRoom?this._mcuConfigBuilder:(v.error("the `getMCUConfigBuilder` is disabled in PK room"),{code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}enableInnerCDN(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new Si(this._mcuConfigBuilder.__innerGetValues(),e))}))}_resourceHandle(e,t,r){const i=Object.create(null,{_resourceHandle:{get:()=>super._resourceHandle}});return f(this,void 0,void 0,(function*(){i._resourceHandle.call(this,e,t,r)}))}_afterChangedRole(e){const t=Vt(e,this._roomId),r=this._context.getCurrentId(),i=Object.keys(t);setTimeout((()=>{var o;const s=i.filter((e=>e!==r));s.length>0&&this._callAppListener("onUserJoin",s);for(const e in t)e!==r&&this._resourceHandle({uris:t[e]},Gt.TOTAL_CONTENT_RESOURCE,e);if(!(null===(o=e.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===o?void 0:o.value))return;const n=this._store.getCDNUris();(null==n?void 0:n.push_mode)===pi.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 f(this,void 0,void 0,(function*(){this._invoker.push(new Ti(e,(e=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(e)})),this._roomPKHandler))}))}_getPushOtherRoomsParams(){const e=[];if(!this.isMainRoom()||!this._roomPKHandler)return e;const t=this._roomPKHandler.getJoinedPKRooms();for(const r in t){const i=t[r].getSessionId(),o=this._roomPKHandler.getPKInfo(r);if(!o)continue;const{inviterUserAutoMix:s,inviteeUserAutoMix:n,inviterUserId:a}=o,c=this._context.getCurrentId()===a;e.push({roomId:r,sessionId:i,autoMix:c?!!s:!!n})}return e}getRoomPKHandler(){return this._store.isMainRoom?(r.info(L.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:A.SUCCESSED},{logSource:i.RTC}),{code:O.SUCCESS,roomPKHandler:this._roomPKHandler}):(v.error("the `getRoomPKHandler` is disabled in PK room"),r.error(L.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:A.SUCCESSED,code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}_quitAllPKRoom(){return f(this,void 0,void 0,(function*(){const e=this._roomPKHandler.getJoinedPKRooms();for(const t in e)this._roomPKHandler.leaveOtherRoom(e[t]);r.info(L.L_LIVING_ROOM_QUIT_ALL_PK_ROOM_O,{status:A.SUCCESSED,roomIds:Object.keys(e)},{logSource:i.RTC})}))}isMainRoom(){return this._store.isMainRoom}}class vi extends ni{constructor(e,t,r,i,o,s,n,a,c,d=mr.RTC){super(e,t,r,d,i,o,s,n,a,c)}}const Oi=new class{constructor(){this.queue=[],this.locked=!1,this.taskCount=0}checkToStart(){return f(this,void 0,void 0,(function*(){if(0===this.queue.length||this.locked)return;this.locked=!0;const{resolve:e,task:t,reject:r}=this.queue.shift();let i;try{i=yield t(),e(i)}catch(e){r(e)}this.locked=!1,this.checkToStart()}))}push(e,t=""){const r=new Promise(((t,r)=>{this.queue.push({resolve:t,task:e,reject:r})}));return this.checkToStart(),r}},Li=(e,t="")=>Oi.push(e,t);class Ai{constructor(e,t,r,i){this._context=e,this._useMutilPeerC=i,this._rtcToken="",this._liveUrl="",this._subTracks=[],this._clientSessionId=jt(),this._livingType=null,this._mediaType=null,this._subTiny=!1,this._fromRetry=!1,this._appListener=null,this._service=new Yt(t,e,r.mediaServer),this._peerCManager=new yr(this._useMutilPeerC,this._context.getCurrentId(),this._reTryExchange.bind(this),this._context.getCurrentId())}_getReqHeaders(e){return f(this,void 0,void 0,(function*(){const t=this._context.getCurrentId(),r=t;if(!this._rtcToken){const{code:t,data:i}=yield this._context.getRTCToken(r,mr.LIVE,e);if(t!==a.SUCCESS)return v.error(`getRTCToken failed: ${t}`),{code:O.SIGNAL_ERROR};this._rtcToken=i.rtcToken}return{code:O.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:t,RoomId:r,RoomType:mr.LIVE,Token:this._rtcToken,"Peer-Connection-Id":this._pcName,"Client-Session-Id":this._clientSessionId}}}))}_clearSubscribeInfo(){var e;this._liveUrl="",this._livingType=null,this._mediaType=null,this._subTiny=!1,this._subTracks.length=0,null===(e=this._pc)||void 0===e||e.destroy(),this._pc=null}_reTryExchange(){var e;return f(this,void 0,void 0,(function*(){this._fromRetry=!0;const{code:t}=yield this.subscribe(this._liveUrl,this._livingType,this._mediaType,this._subTiny);t===O.SUCCESS&&(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer())}))}subscribe(e,t,r,i=!1){return f(this,void 0,void 0,(function*(){return Li((()=>this.__subscribe(e,t,r,i)),"audience-client-sub")}))}__subscribe(e,t,o,s=!1){var n;return f(this,void 0,void 0,(function*(){r.info(L.L_AUDIENCE_CLIENT_SUBSCRIBE_T,{liveUrl:e,livingType:t,mediaType:o,subTiny:s},{logSource:i.RTC});const a=[];if(Bt(this._context.getNaviInfo()))return r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:O.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:i.RTC}),{code:O.PACKAGE_ENVIRONMENT_ERROR,tracks:a};if(!this._fromRetry&&(null===(n=this._pc)||void 0===n||n.clearReTryExchangeTimer()),this._fromRetry=!1,!p(e))return v.error(`liveUrl is invalid: ${e}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:`params error -> liveUrl: ${e}`},{logSource:i.RTC}),{code:O.PARAMS_ERROR,tracks:a};if(![Ri.AUDIO,Ri.VIDEO].includes(t))return v.error(`livingType is invalid: ${t}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:`params error -> livingType: ${t}`},{logSource:i.RTC}),{code:O.PARAMS_ERROR,tracks:a};if(![He.AUDIO_ONLY,He.VIDEO_ONLY,He.AUDIO_VIDEO].includes(o))return v.error(`mediaType is invalid: ${o}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:`params error -> -> mediaType: ${o}`},{logSource:i.RTC}),{code:O.PARAMS_ERROR,tracks:a};if(this._liveUrl&&this._liveUrl!==e)return r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:O.BROADCAST_SUB_LIST_NOT_EMPTY,msg:"repeat subscribe"},{logSource:i.RTC}),{code:O.BROADCAST_SUB_LIST_NOT_EMPTY,tracks:a};if(!this._pc){const{pcName:e,pc:t}=this._peerCManager.createPeerCList(a)[0];this._pc=t,this._pcName=e,this._pc.on(Nr.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this._pc.registerReportListener(this._reportListener),this._pc.__reportR3R4ToPolaris()}this._liveUrl=e;const{code:c,headers:d}=yield this._getReqHeaders(t);if(c!==O.SUCCESS)return r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:c,msg:""},{logSource:i.RTC}),{code:c,tracks:a};const _=`rc_mcu_${Date.now()}`,u="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new pt(u,_),new mt(u,_)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const l={sdp:yield this._pc.createOffer(!0),liveUrl:e,mediaType:o,simulcast:s?zt.TINY:zt.NORMAL,switchstream:!1},h=yield this._service.broadcastSubscribe(d,l);if(h.code!==O.SUCCESS)return v.error(`andience subscribe failed: ${h.code}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:h.code,msg:""},{logSource:i.RTC}),{code:h.code,tracks:a};const R=h.data;if(R.resultCode!==O.SUCCESS)return v.error(`andience subscribe failed! code: ${R.resultCode}; message: ${R.message}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:R.resultCode,msg:""},{logSource:i.RTC}),{code:R.resultCode,tracks:a};v.debug(`andience subscribe success: ${e}`),this._livingType=t,this._mediaType=o,this._subTiny=s;const{sdp:m,subscribedList:C}=R,T=[];return C.forEach((e=>{const{mediaType:t}=e,r=this._subTracks[t];T.push(r),r.__innerSetRemoteMuted(!0)})),this._pc.setRemoteAnswer(m.sdp),r.info(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.SUCCESSED,liveUrl:e},{logSource:i.RTC}),{code:O.SUCCESS,tracks:T}}))}unsubscribe(){return f(this,void 0,void 0,(function*(){return Li((()=>this.__unsubscribe()),"audience-client-unsub")}))}__unsubscribe(){var e;return f(this,void 0,void 0,(function*(){if(r.info(L.L_AUDIENCE_CLIENT_UNSUBSCRIBE_T,{liveUrl:this._liveUrl},{logSource:i.RTC}),null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer(),!this._rtcToken||!this._liveUrl)return r.warn(L.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:A.FAILED,code:"",msg:"Address does not exist, without unsubscribe"},{logSource:i.RTC}),{code:O.SUCCESS};const{headers:t}=yield this._getReqHeaders(),{code:o}=yield this._service.broadcastExit(t);return o!==O.SUCCESS?(v.error(`broadcast unsubscribe failed: ${o}`),r.error(L.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:A.FAILED,code:o,msg:""},{logSource:i.RTC})):(v.debug("broadcast unsubscribe success"),r.info(L.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:A.SUCCESSED,liveUrl:this._liveUrl},{logSource:i.RTC})),this._clearSubscribeInfo(),{code:o}}))}registerReportListener(e){this._reportListener=e}registerTrackEventListener(e){this._appListener=e}_onTrackReady(e){var t,r;const i=e.receiver.track,o="audio"===i.kind?He.AUDIO_ONLY:He.VIDEO_ONLY,s=this._subTracks[o];s.__innerSetMediaStreamTrack(i);try{null===(r=null===(t=this._appListener)||void 0===t?void 0:t.onTrackReady)||void 0===r||r.call(t,s)}catch(e){v.error(e)}}}var Ni,Di;!function(e){e.RTMP="rtmp",e.FLV="flv",e.HLS="hls"}(Ni||(Ni={})),function(e){e[e.NOT_HTTPS=0]="NOT_HTTPS",e[e.HTTPS=1]="HTTPS"}(Di||(Di={}));const ki=Object.assign(Object.assign({},kt(Ke.W176_H144)),{frameRate:bt(Ge.FPS_15)});class yi{constructor(e,t,r,i,o,s,n,a=jt()){this._context=e,this._runtime=t,this._initOptions=r,this._roomId=i,this._joinResData=o,this.livingType=s,this._useMutilPeerC=n,this._clientSessionId=a,this._roomAnchorList=[],this._roomRes={},this._roomAnchorRes={},this._remoteTracks={},this._appListener=null,this._pc=null,this._subscribedList=[],this._sessionId="",this._destroyed=!1,this._isPulling=!1,this._pullTime=0,this._reportListener=null,this._setInitData(),this._service=new Yt(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new Dr(this._context,this._runtime,this._roomId,this,_r.Audience),this._polarisReport.sendR1(),this._peerCManager=new yr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._context.registerRTCSignalListener((e=>f(this,void 0,void 0,(function*(){const{time:t,type:r,roomId:i}=this._context.decodeRtcNotify(e);if(v.warn(`registerRTCSignalListener -> ${JSON.stringify({time:t,type:r,roomId:i})}`),1===r)this._startPull(i,t)}))))}_startPull(e,t){return f(this,void 0,void 0,(function*(){if(this._isPulling)return;this._isPulling=!0;if(this._pullTime>t)return void(this._isPulling=!1);const{code:r,data:i}=yield this._context.pullRTCRoomEntry(e);if(r===a.SUCCESS){this._isPulling=!1,this._pullTime=i.syncTime||0;const t=(null==i?void 0:i.kvEntries)||[];v.info(`_startPull -> ${JSON.stringify(t)}`),this.singalDataChange(t,e)}}))}_setInitData(){const{sessionId:e,remoteUserIds:t,remoteRTCUris:r,remoteMUCUris:i,remoteTracks:o,CDNUris:s}=((e,t)=>{const r=t.filter((e=>"RC_RTC_SESSIONID"===e.key))[0],i=r?r.value:"",o=t.filter((e=>"RC_ANCHOR_LIST"===e.key)).map((e=>JSON.parse(e.value||"[]")))[0],s=t.filter((e=>e.key.includes("RC_RES_"))).map((e=>JSON.parse(e.value||"{}"))),n=s.length?JSON.parse(s[0].mcu_uris||"[]"):[],a=[];n.forEach((t=>{const{mediaType:r,tag:i}=t,o=r===He.AUDIO_ONLY?new pt(i,"",e):new mt(i,"",e);a.push(o)}));const c=[],d=[];s.forEach((e=>{const t=JSON.parse(e.uris||"[]");c.push(...t),t.forEach((e=>{const{mediaType:t,tag:r,msid:i}=e,o=i.split("_")[0],s=t===He.AUDIO_ONLY?new pt(r,o):new mt(r,o);d.push(s)}))}));const _=t.filter((e=>"RC_CDN"===e.key)).map((e=>{const t=JSON.parse(e.value||"[]");return JSON.parse(t.cdn_uris)[0]}))[0];return{sessionId:i,remoteUserIds:o||[],remoteRTCUris:c,remoteMUCUris:n,remoteRTCTracks:d,remoteMCUTracks:a,remoteTracks:[...d,...a],CDNUris:_||{}}})(this._roomId,this._joinResData.kvEntries);this._sessionId=e,this._roomAnchorList=t,o.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]})),i.forEach((e=>{const{mediaType:t,tag:r}=e,i=[this._roomId,r,t].join("_");this._roomRes[i]=e})),r.forEach((e=>{const t=vt(e);this._roomRes[t]=e}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinLivingRoomAsAudience` to catch another instance.";return v.warn(e),O.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(e,t){var o;if(r.info(L.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_T,{singalData:e,roomId:t,userId:this._context.getCurrentId()},{logSource:i.RTC}),t!==this._roomId)return v.warn(`singalDataChange -> not the current room data: data roomId: ${t}, current roomId: ${this._roomId}`),void r.error(L.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:A.FAILED,code:"",msg:`id inconsistency -> params id:${t},current id:${this._roomId}`},{logSource:i.RTC});v.debug("singalDataChange -> singalData:",JSON.stringify(e||{}));const s=[],n=null===(o=e.filter((e=>"RC_CDN"===e.key))[0])||void 0===o?void 0:o.value;n&&this._diffCDNUris(JSON.parse(JSON.parse(n).cdn_uris)[0]),e.forEach((e=>{const{key:t,value:r,timestamp:i,uid:o}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),i=JSON.parse(e.uris||"[]");return s.push(...t),void this._diffAnchorResource(i,o)}if("RC_ANCHOR_LIST"===t){const e=JSON.parse(r||"[]"),{joinUserIds:t,leftUserIds:i}=this._diffAnchorList(e);t.length>0&&this._handleNewJoinedAnchor(t),i.length>0&&this._handleLeftedAnchor(i)}})),this._diffRoomResource(s),r.info(L.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:A.SUCCESSED,singalData:e,roomId:t,userId:this._context.getCurrentId()},{logSource:i.RTC})}_diffAnchorList(e){const t=e.filter((e=>this._roomAnchorList.indexOf(e)<0));return{leftUserIds:this._roomAnchorList.filter((t=>e.indexOf(t)<0)),joinUserIds:t}}_handleNewJoinedAnchor(e){this._roomAnchorList.push(...e),this._callAppListener("onAnchorJoin",e)}_handleLeftedAnchor(e){return f(this,void 0,void 0,(function*(){this._roomAnchorList=this._roomAnchorList.filter((t=>!(e.indexOf(t)>-1)));const t=[];e.forEach((e=>{t.push(...this.getRemoteTracksByUserId(e)),delete this._roomAnchorRes[e]})),t.length&&(yield this.unsubscribe(t),t.forEach((e=>delete this._remoteTracks[e.getTrackId()]))),this._callAppListener("onAnchorLeave",e)}))}_diffRoomResource(e){return f(this,void 0,void 0,(function*(){const t=[],r=[],i=[];e.forEach((e=>{const r=vt(e),{userId:o,tag:s,mediaType:n}=Ot(r),a=[this._roomId,s,n].join("_");if(!this._remoteTracks[a]){const r=n===He.AUDIO_ONLY?new pt(s,"",this._roomId):new mt(s,"",this._roomId);t.push(r),this._remoteTracks[a]=r,this._roomRes[r.getTrackId()]=e}i.push(a)})),Object.keys(this._remoteTracks).forEach((e=>{i.indexOf(e)<0&&this._remoteTracks[e].isMCUTrack()&&r.push(this._remoteTracks[e])})),t.length>0&&this._callAppListener("onTrackPublish",t),r.length>0&&this._onUserUnpublish(r,"onTrackUnpublish")}))}_diffAnchorResource(e,t){return f(this,void 0,void 0,(function*(){const r=this._roomAnchorRes[t]||(this._roomAnchorRes[t]=[]),{publishedList:i,unpublishedList:o,modifiedList:s}=Nt(r,e);if(i.length){const e=r.map(vt),t=[],o=[];if(i.forEach((i=>{const s=vt(i),n=e.indexOf(s),{userId:a,tag:c,mediaType:d}=Ot(s);n>-1?r[n]=i:r.push(i);let _=this._remoteTracks[s];this._roomRes[s]=i,_?_.isSubscribed()&&t.push(_):(_=d===He.AUDIO_ONLY?new pt(c,a):new mt(c,a),this._remoteTracks[s]=_,o.push(_)),_.__innerSetRemoteMuted(0===i.state)})),t.length){const e=t.map((e=>e.getTrackId()));v.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:r}=yield Li((()=>this._subscribeHandle(t,!0)));r!==O.SUCCESS&&v.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(e)}`)}this._callAppListener("onAnchorTrackPublish",o)}if(o.length){const e=o.map(vt);for(let t=r.length-1;t>=0;t-=1){const i=r[t];e.includes(vt(i))&&r.splice(t,1)}const t=o.map((e=>{const t=vt(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t,"onAnchorTrackUnpublish")}if(s.length){const e=r.map(vt);for(let t=0;t<s.length;t++){const i=s[t],o=vt(i),n=e.indexOf(o);r[n].state=i.state;const a=this._remoteTracks[o];a.__innerSetRemoteMuted(0===i.state),a.isAudioTrack()?this._callAppListener("onAudioMuteChange",a):this._callAppListener("onVideoMuteChange",a)}}}))}_onUserUnpublish(e,t){return f(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;v.info(`${e} callback ->`,...t);const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){v.error(e)}}_reTryExchange(){return f(this,void 0,void 0,(function*(){Li((()=>f(this,void 0,void 0,(function*(){var e;const{reqBody:t}=yield this._createSubscribeParams(this._subscribedList,{},!0),r=yield this._exchangeHandle(t);if(r.code!==O.SUCCESS)return v.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:o}=r.data;if(o!==O.SUCCESS)return v.error(`reTryExchange failed: ${o}`),{code:o};this._pc.clearReTryExchangeTimer();const s=this._subscribedList.filter((e=>e.track.isMCUTrack()));if(s.length>0){const t=s[0].track.getTrackId(),r=null===(e=this._roomRes[t])||void 0===e?void 0:e.msid,o=[this._roomId,"RongCloudRTC"].join("_");i.sdp=i.sdp.replace(new RegExp(r,"g"),o)}const n=yield this._pc.setRemoteAnswer(i.sdp);return n!==O.SUCCESS?{code:n}:void 0}))),"audience-retry-exchange")}))}_createSubscribeParams(e,t,r){return f(this,void 0,void 0,(function*(){const i=yield this._pc.createOffer(r),o={resolutionInfo:[]},s={min:0,max:0};Object.keys(t).forEach((e=>{const{mediaStream:r,tinyStream:n}=t[e];[r,n].forEach(((t,r)=>{var n;const a=1===r?[e,"tiny"].join("_"):e;i.sdp=null===(n=i.sdp)||void 0===n?void 0:n.replace(new RegExp(t.id,"g"),a);const c=t.getVideoTracks()[0];if(!c)return;const d=0===r,{width:_,height:u,frameRate:l}=d?gt(c):ki;o.resolutionInfo.push({trackId:c.id,simulcast:d?zt.NORMAL:zt.TINY,resolution:`${_}x${u}`});const h=We(_,u),R=Ye(l);s.min+=h.minBitrate*R,s.max+=h.maxBitrate*R}))}));return{reqBody:{sdp:i,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?zt.TINY:zt.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:s,offer:i}}))}_subscribeHandle(e,t=!1){var o;return f(this,void 0,void 0,(function*(){r.info(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_T,{trackIds:e.map($t),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:t},{logSource:i.RTC});if(this._assertRoomDestroyed())return r.error(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:O.ROOM_HAS_BEEN_DESTROYED,msg:"room destroyed"},{logSource:i.RTC}),{code:O.ROOM_HAS_BEEN_DESTROYED};if(!s("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof Rt||e.track instanceof Rt))),!0))return r.error(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};const{pc:n,pcName:a}=this._peerCManager.createPeerCList(e)[0];this._pc=n,this._pc.__reportR3R4ToPolaris(),this._pcName=a,this._pc.registerReportListener(this._reportListener),this._addPeerCEvent();const c=this._subscribedList.map((e=>Object.assign({},e))),_=e.map((e=>e instanceof Rt?{track:e}:e));let u=!1;const l=[];return _.forEach((e=>{const t=e.track.getTrackId();l.push(t);const r=c.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:c.push(e),u=!0)})),u||t?(null===(o=this._polarisReport)||void 0===o||o.sendR2(Tr.SUBSCRIBE,Ir.BEGIN,l),r.info(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:A.SUCCESSED,trackIds:e.map($t),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:t},{logSource:i.RTC}),this._updateSubListHandle(c,!0)):(r.warn(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:"",msg:"repeat subscribe"},{logSource:i.RTC}),{code:O.SUCCESS})}))}_addPeerCEvent(){this._pc.on(Nr.__INNER_EVENT_TRACK_READY__,(e=>{const t=e.streams[0].id,r=e.receiver.track,i=[t,"audio"===r.kind?He.AUDIO_ONLY:He.VIDEO_ONLY].join("_"),o=this._remoteTracks[i];o?(o.__innerSetMediaStreamTrack(r),this._callAppListener("onTrackReady",o)):v.warn("cannot found RCRemoteTrack:",r.id)}))}_getReqHeaders(){const e=this._context.getCurrentId();return{"App-Key":this._context.getAppkey(),RoomId:e,Token:this._joinResData.token,RoomType:mr.LIVE,UserId:e,"Session-Id":this._sessionId,"Peer-Connection-Id":this._pcName,"Client-Session-Id":this._clientSessionId}}_exchangeHandle(e){return this._service.broadcastSubscribe(this._getReqHeaders(),e)}_updateSubListHandle(e,t=!1){var r;return f(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:O.ROOM_HAS_BEEN_DESTROYED};if(!s("resources",e,(()=>d(e)&&e.every((e=>e instanceof Rt||e.track instanceof Rt))),!0))return{code:O.PARAMS_ERROR};let i=e.map((e=>e instanceof Rt?{track:e}:Object.assign({},e)));const o={};i=i.filter((e=>{const t=e.track.getTrackId();return!o[t]&&(o[t]=!0)})).map((e=>Object.assign({},e)));const n=this._subscribedList.map((e=>Object.assign({},e)));if(!t){let e=!1;if(i.forEach((t=>{const r=n.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);n.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),n.length&&(e=!0),!e)return{code:O.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(i.map((e=>e.track)));const{reqBody:a}=yield this._createSubscribeParams(i,{},!1),c=yield this._exchangeHandle(a);if(n.length){const e=[];n.forEach((t=>{e.push(t.track.getTrackId())})),null===(r=this._pc.reportParser)||void 0===r||r.clearLatestPacketsRecv(e)}if(c.code!==O.SUCCESS)return{code:c.code};const{sdp:_,resultCode:u,message:l,subscribedList:h}=c.data;if(u!==O.SUCCESS)return v.error("change subscribe list failed:",l,u),{code:u};i.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:i}=Ot(t.getTrackId()),o=[i,r].join("_");_.sdp=_.sdp.replace(new RegExp(e,"g"),o)}}));const R=yield this._pc.setRemoteAnswer(_.sdp);if(R!==O.SUCCESS)return{code:R};const p=null==h?void 0:h.map((e=>`${e.msid}_${e.mediaType}`)),m=i.filter((e=>{if(e.track.isMCUTrack()){const t=this._roomRes[e.track.getTrackId()],r=`${t.msid}_${t.mediaType}`;return p.includes(r)}return null==p?void 0:p.includes(e.track.getTrackId())})),C=null==m?void 0:m.map((e=>`${e.track.getTrackId()}`)),T=i.filter((e=>!(null==C?void 0:C.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=m.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...m),T.length?{code:O.SUCCESS,failedList:T}:{code:O.SUCCESS}}))}_diffCDNUris(e){return f(this,void 0,void 0,(function*(){if(this._CDNUris.url&&!e.url)return this._callAppListener("onCDNInfoDisable"),void(this._CDNUris=e);(!this._CDNUris||!this._CDNUris.url&&e.url)&&this._callAppListener("onCDNInfoEnable",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`});const t=this._CDNUris.w&&e.w&&this._CDNUris.w!==e.w,r=this._CDNUris.h&&e.h&&this._CDNUris.h!==e.h,i=this._CDNUris.fps&&e.fps&&this._CDNUris.fps!==e.fps;(t||r||i)&&this._callAppListener("onCDNInfoChange",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`}),this._CDNUris=e}))}_getCDNPlayUrl(e){return f(this,void 0,void 0,(function*(){const{w:t,h:r,fps:i}=e,o=this._initOptions.pullInnerCDNProtocol||Ni.FLV,s=this._initOptions.pullInnerCDNUseHttps===Di.NOT_HTTPS?Di.NOT_HTTPS:Di.HTTPS;if(!this._CDNUris.url)return v.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${O.CDN_RESOURCE_IS_EMPTY}`),{code:O.CDN_RESOURCE_IS_EMPTY};const n={"App-Key":this._context.getAppkey(),Token:this._joinResData.token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},a=[];t&&a.push(`w=${t}`),r&&a.push(`h=${r}`),i&&a.push(`fps=${i}`),a.push(`kind=${o}`),a.push(`is_https=${s}`);const c=a.join("&");let d=`${this._CDNUris.url}?`;c&&(d+=c);const{code:_,res:u}=yield this._service.getCDNResourceInfo(n,d);return _!==O.SUCCESS?(v.error(`getCDNPlayUrl failed: ${_}`),{code:_}):(v.info(`getCDNPlayUrl success: ${null==u?void 0:u.data.pull_url}`),{code:_,CDNPlayUrl:null==u?void 0:u.data.pull_url})}))}getCDNPlayUrl(e,t){return f(this,void 0,void 0,(function*(){if(r.info(L.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_T,{resolution:e,fps:t},{logSource:i.RTC}),e&&!yt(e))return v.error("`resolution` is invalid"),r.error(L.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> resolution"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(t&&!Ut(t))return v.error("`fps` is invalid"),r.error(L.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> fps"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};const{width:o,height:s}=e?kt(e):{width:null,height:null},n=t?bt(t):null,a={};return o&&(a.w=o),s&&(a.h=s),n&&(a.fps=n),r.info(L.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:A.SUCCESSED,resolution:e,fps:t},{logSource:i.RTC}),this._getCDNPlayUrl(a)}))}subscribe(e){return f(this,void 0,void 0,(function*(){return Li((()=>this._subscribeHandle(e,!1)),"audience-sub")}))}addSubscribeTask(e){return f(this,void 0,void 0,(function*(){return Li((()=>this._subscribeHandle(e,!1)),"audience-sub")}))}__unsubscribe(e){var t;return f(this,void 0,void 0,(function*(){if(r.info(L.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_T,{trackIds:e.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:i.RTC}),!s("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof Rt))),!0))return v.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),r.error(L.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};const o=this._subscribedList.map((e=>Object.assign({},e))).filter((t=>!e.includes(t.track)));return null===(t=this._polarisReport)||void 0===t||t.sendR2(Tr.SUBSCRIBE,Ir.END,e.map((e=>e.getTrackId()))),r.info(L.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:A.SUCCESSED,trackIds:e.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:i.RTC}),this._updateSubListHandle(o,!1)}))}unsubscribe(e){return f(this,void 0,void 0,(function*(){return Li((()=>this.__unsubscribe(e)),"audience-unsub")}))}addUnsubscribeTask(e){return f(this,void 0,void 0,(function*(){return Li((()=>this.__unsubscribe(e)),"audience-unsub")}))}__destroy(e){var t,r;return f(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(t=this._audioLevelReport)||void 0===t||t.clearAudioLevelReportTimer(),e&&(yield this._context.quitLivingRoomAsAudience(this._roomId)),yield this._service.broadcastExit(this._getReqHeaders()),null===(r=this._pc)||void 0===r||r.destroy(),this._polarisReport=null,this._context.registerRTCSignalListener(void 0))}))}getRemoteTrack(e){return this._remoteTracks[e]}__getPC(){return this._peerCManager.getPCList()}getLocalTrack(e){return{}}__onReconnected(){return f(this,void 0,void 0,(function*(){const{code:e}=yield this._context.joinLivingRoomAsAudience(this._roomId,mr.LIVE);e!==a.SUCCESS&&v.error("join living room error when on reconnected")}))}registerRoomEventListener(e){this._appListener=e}onAudioLevelChange(e,t){var o;null===(o=this._audioLevelReport)||void 0===o||o.clearAudioLevelReportTimer(),this._audioLevelReport=new kr(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3),r.info(L.L_AUDIENCE_LIVING_ROOM_AUDIO_LEVEL_CHANGE_O,{status:A.SUCCESSED,handler:null==e?void 0:e.name,gap:t},{logSource:i.RTC})}registerReportListener(e){this._reportListener=e}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}getSessionId(){return this._sessionId}getRemoteUserIds(){return this._roomAnchorList}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getRemoteTracks(){const e=[],t=[];for(const e in this._remoteTracks){if(2===t.length)break;const r=this._remoteTracks[e];r.isMCUTrack()&&t.push(r)}return this._roomAnchorList.forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),[...t,...e]}getRemoteRTCTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()||e.push(r)}return e}getRemoteMCUTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()&&e.push(r)}return e}getCDNInfo(){return this._CDNUris.w?{resolution:`W${this._CDNUris.w}_H${this._CDNUris.h}`,fps:`FPS_${this._CDNUris.fps}`,CDNEnable:this._CDNUris.enableInnerCDN}:{CDNEnable:!1}}getClientSessionId(){return this._clientSessionId}}class Ui{constructor(e){this._context=e,this._isElectron=/Electron/.test(navigator.userAgent)}_getMediaStream(e,t="getUserMedia"){return f(this,void 0,void 0,(function*(){try{const r=this.setConstraintsConfig(e),i=yield navigator.mediaDevices[t](r);return{code:O.SUCCESS,stream:i}}catch(e){if("Permission denied"===e.message)return{code:O.BROWSER_PERMISSION_DENIED};if("Permission denied by system"===e.message)return{code:O.SYSTEM_PERMISSION_DENIED};v.error(`get user media failed -> ${e.message}`)}return{code:"getUserMedia"===t?O.GET_USER_MEDIA_FAILED:O.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),v.info(`browser supported -> ${JSON.stringify(t)}`)}return e}createMicrophoneAudioTrack(e="RongCloudRTC",t){return f(this,void 0,void 0,(function*(){if(!It(e))return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS};const o=this._context.getCurrentId();if(!o)return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID};const{stream:s,code:n}=yield this._getMediaStream({audio:{deviceId:null==t?void 0:t.micphoneId,sampleRate:null==t?void 0:t.sampleRate}});if(n!==O.SUCCESS)return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:A.FAILED,code:n,msg:"Failed to get microphone audio stream"},{logSource:i.RTC}),{code:n};const a=s.getAudioTracks()[0],c=new _t(e,o,a);return r.info(L.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:A.SUCCESSED,trackId:c.getTrackId()},{logSource:i.RTC}),{code:n,track:c}}))}createCameraVideoTrack(e="RongCloudRTC",t){return f(this,void 0,void 0,(function*(){if(!It(e))return r.error(L.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS};const o=this._context.getCurrentId();if(!o)return r.error(L.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID};const s=yt(null==t?void 0:t.resolution)?t.resolution:Ke.W640_H480,{width:n,height:a}=kt(s),{stream:c,code:d}=yield this._getMediaStream({video:{deviceId:null==t?void 0:t.cameraId,frameRate:bt((null==t?void 0:t.frameRate)||Ge.FPS_15),width:n,height:a,facingMode:null==t?void 0:t.faceMode}});if(d!==O.SUCCESS)return r.error(L.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"Failed to get camera video stream"},{logSource:i.RTC}),{code:d};const _=c.getVideoTracks()[0],u=new ut(e,o,_);return r.info(L.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:A.SUCCESSED,trackId:u.getTrackId()},{logSource:i.RTC}),{code:d,track:u}}))}createMicrophoneAndCameraTracks(e="RongCloudRTC",t){var o,s,n,a,c,d;return f(this,void 0,void 0,(function*(){const _=[];if(!It(e))return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS,tracks:_};const u=this._context.getCurrentId();if(!u)return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID,tracks:_};const l=yt(null===(o=null==t?void 0:t.video)||void 0===o?void 0:o.resolution)?t.video.resolution:Ke.W640_H480,{width:h,height:R}=kt(l),{stream:p,code:m}=yield this._getMediaStream({video:{deviceId:null===(s=null==t?void 0:t.video)||void 0===s?void 0:s.cameraId,frameRate:bt((null===(n=null==t?void 0:t.video)||void 0===n?void 0:n.frameRate)||Ge.FPS_15),width:h,height:R,facingMode:null===(a=null==t?void 0:t.video)||void 0===a?void 0:a.faceMode},audio:{deviceId:null===(c=null==t?void 0:t.audio)||void 0===c?void 0:c.micphoneId,sampleRate:null===(d=null==t?void 0:t.audio)||void 0===d?void 0:d.sampleRate}});return m!==O.SUCCESS?(r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:A.FAILED,code:m,msg:"Failed to get audio and video stream of camera and microphone"},{logSource:i.RTC}),{code:m,tracks:_}):(p.getTracks().forEach((t=>{"video"===t.kind?_.push(new ut(e,u,t)):_.unshift(new _t(e,u,t))})),r.info(L.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:A.SUCCESSED,trackIds:_.map((e=>e.getTrackId()))},{logSource:i.RTC}),{code:m,tracks:_})}))}createScreenVideoTrack(e="screenshare",t){return f(this,void 0,void 0,(function*(){const r=yield this._createScreenTracks(e,!1,L.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,t);return r.code===O.SUCCESS?{code:r.code,track:r.tracks[0]}:r}))}createScreenWithAudioTracks(e="screenshare",t){return f(this,void 0,void 0,(function*(){return this._createScreenTracks(e,!0,L.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_AND_AUDIO_TRACKS_O,t)}))}_createScreenTracks(e,t,o,s){var n,a;return f(this,void 0,void 0,(function*(){if(!It(e))return r.error(o,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS};const c=this._context.getCurrentId();if(!c)return r.error(o,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID};if(!xt())return r.error(L.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:A.FAILED,code:O.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:i.RTC}),{code:O.BROWSER_NOT_SUPPORT};const d=/macintosh|mac os x/i.test(navigator.userAgent);this._isElectron&&d&&t&&r.warn(o,{status:A.INFO,code:O.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO,msg:"mac in electron not support screen share with audio"});const _=(!this._isElectron||!d)&&t;if(this._isElectron&&!E(null==s?void 0:s.chromeMediaSourceId)&&!p(null==s?void 0:s.chromeMediaSourceId))return r.error(o,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> options.chromeMediaSourceId type is string"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};const u=yt(null==s?void 0:s.resolution)?s.resolution:Ke.W1280_H720,{width:l,height:h}=kt(u),R=this._isElectron?{mandatory:{chromeMediaSourceId:null==s?void 0:s.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:l,maxWidth:l,minHeight:h,maxHeight:h}}:{frameRate:bt((null==s?void 0:s.frameRate)||Ge.FPS_15),width:l,height:h};!(null==s?void 0:s.chromeMediaSourceId)&&this._isElectron&&(null===(n=R.mandatory)||void 0===n||delete n.chromeMediaSourceId);let m=null;_&&this._isElectron&&(null===(a=R.mandatory)||void 0===a||delete a.chromeMediaSourceId,m={mandatory:{chromeMediaSource:"desktop"}});const{stream:C,code:T}=yield this._getMediaStream({video:R,audio:m||_},this._isElectron?"getUserMedia":"getDisplayMedia");if(T!==O.SUCCESS)return r.error(o,{status:A.FAILED,code:T,msg:"Failed to get shared screen video stream"},{logSource:i.RTC}),{code:T};const I=C.getVideoTracks()[0],S=[new lt(e,c,I)];if(_){const t=C.getAudioTracks()[0];t&&S.push(new ht(e,c,t))}return r.info(o,{status:A.SUCCESSED,trackIds:S.map((e=>e.getTrackId()))},{logSource:i.RTC}),{code:T,tracks:S}}))}createLocalAudioTrack(e,t){return f(this,void 0,void 0,(function*(){if(!It(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"audio"!==t.kind)return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"Failed to create custom stream"},{logSource:i.RTC}),{code:O.CREATE_CUSTOM_TRACK_FAILED};const o=this._context.getCurrentId();if(!o)return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID};const s=new st(e,o,t);return r.info(L.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:A.SUCCESSED,trackId:s.getTrackId()},{logSource:i.RTC}),{code:O.SUCCESS,track:s}}))}createLocalVideoTrack(e,t){return f(this,void 0,void 0,(function*(){if(!It(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"video"!==t.kind)return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:A.FAILED,code:O.CREATE_CUSTOM_TRACK_FAILED,msg:"Failed to create custom stream"},{logSource:i.RTC}),{code:O.CREATE_CUSTOM_TRACK_FAILED};const o=this._context.getCurrentId();if(!o)return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID};const s=new nt(e,o,t);return r.info(L.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:A.SUCCESSED,trackId:s.getTrackId()},{logSource:i.RTC}),{code:O.SUCCESS,track:s}}))}createLocalFileTracks(e,t,o){return f(this,void 0,void 0,(function*(){if(!It(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS,tracks:[]};if(!Mt())return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:O.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:i.RTC}),{code:O.BROWSER_NOT_SUPPORT,tracks:[]};const s=t instanceof File?URL.createObjectURL(t):t;if(!T(s)&&!/^blob:/.test(s))return v.warn(`createLocalFileTracks failed: params error -> url: ${s}`),r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> file"},{logSource:i.RTC}),{code:O.PARAMS_ERROR,tracks:[]};const n=this._context.getCurrentId();return n?new Promise((t=>{const a=document.createElement("video");(null==o?void 0:o.withoutAudio)&&(a.muted=!0),a.onloadedmetadata=()=>{const c=[];let d;try{const e=a.mozCaptureStream?"mozCaptureStream":"captureStream";d=a[e]()}catch(e){v.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${s}`),v.error(e),r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:O.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:i.RTC}),t({code:O.CREATE_FILE_TRACK_FAILED,tracks:c})}const[_,u]=Ui.getTracksWithOptions(d,o);_&&c.push(new dt(e,n,_,a)),u&&c.push(new ct(e,n,u,a)),0===c.length&&(a.pause(),a.src=""),a.onerror=null,r.info(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.SUCCESSED,trackIds:c.map((e=>e.getTrackId()))},{logSource:i.RTC}),t({code:O.SUCCESS,tracks:c})},a.onerror=()=>{v.error(`create RCLocalFileTrack failed -> url: ${s}`),r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:O.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:i.RTC}),t({code:O.CREATE_FILE_TRACK_FAILED,tracks:[]})},a.src=s,a.loop=!0,a.play()})):(r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID,tracks:[]})}))}createLocalTracks(e,t,o){return f(this,void 0,void 0,(function*(){const s=[];if(!It(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS,tracks:s};if(!(t instanceof MediaStream))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> stream"},{logSource:i.RTC}),{code:O.PARAMS_ERROR,tracks:s};const n=this._context.getCurrentId();if(!n)return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID,tracks:s};const[a,c]=Ui.getTracksWithOptions(t,o);return a&&s.push(new st(e,n,a)),c&&s.push(new nt(e,n,c)),r.info(L.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:A.SUCCESSED,trackIds:s.map((e=>e.getTrackId()))},{logSource:i.RTC}),{code:O.SUCCESS,tracks:s}}))}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 bi extends Ui{constructor(e,t,r){super(e),this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,gr.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new Yt(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){var t;if(e.conversationType!==C.RTC_ROOM)return!1;if(this._crtRoom instanceof fi){this._getJoinedPKRoomList().forEach((t=>{t.__parseInnerMessage(e)}))}return null===(t=this._crtRoom)||void 0===t||t.__parseInnerMessage(e),r.info(L.L_RTC_CLIENT_MESSAGE_O,{status:A.SUCCESSED,message:Object.assign(e,{content:"内容涉及隐私不予显示"})},{logSource:i.RTC}),!0}naviDataChange(e){r.info(`on navi change data => ${JSON.stringify(e)}`),this._service.detectorMediaSever()}_getJoinedPKRoomList(){const{code:e,roomPKHandler:t}=this._crtRoom.getRoomPKHandler();if(e===O.SUCCESS&&t){const e=t.getJoinedPKRooms()||{};return Object.values(e)}return[]}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(e,t,o,s,n=mr.RTC){return f(this,void 0,void 0,(function*(){if(r.info(L.L_RTC_CLIENT_JOIN_RTC_ROOM_T,{roomId:e,joinType:t,outerUserDatas:o,useMutilPeerC:s,roomType:n},{logSource:i.RTC}),this._crtRoom)return r.error(L.L_RTC_CLIENT_JOIN_RTC_ROOM_R,{status:A.FAILED,code:O.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:O.REPERT_JOIN_ROOM};const a=this._crtRoom=new vi(this._context,this._runtime,e,this._service,this._options,!1,!1,s,jt()),{code:c}=yield a.__innerInit(n,t,void 0,void 0,o);return c!==O.SUCCESS?(this._crtRoom=null,{code:c}):(a.once(si,(()=>{this._crtRoom=null})),{code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()})}))}joinCrossRTCRoom(e,t,o,s,n=mr.CROSS_MUTI){return f(this,void 0,void 0,(function*(){if(r.info(L.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_T,{roomId:e,joinType:t,outerUserDatas:o,useMutilPeerC:s,roomType:n},{logSource:i.RTC}),this._crtRoom)return r.error(L.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_R,{status:A.FAILED,code:O.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:O.REPERT_JOIN_ROOM};const a=this._crtRoom=new vi(this._context,this._runtime,e,this._service,this._options,!1,!1,s,jt(),n),{code:c}=yield a.__innerInit(n,t,void 0,void 0,o);return c!==O.SUCCESS?(this._crtRoom=null,{code:c}):(a.once(si,(()=>{this._crtRoom=null})),{code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()})}))}joinLivingRoom(e,t,o,s,n){return f(this,void 0,void 0,(function*(){if(r.info(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_T,{roomId:e,livingType:t,joinType:o,outerUserDatas:s,useMutilPeerC:n},{logSource:i.RTC}),this._crtRoom)return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:A.FAILED,code:O.REPERT_JOIN_ROOM,msg:`Join the room repeatedly -> roomId: ${e}`},{logSource:i.RTC}),{code:O.REPERT_JOIN_ROOM};const a=this._crtRoom=new fi(this._context,this._runtime,e,this._service,this._options,t,!1,!0,n),{code:c}=yield a.__innerInit(mr.LIVE,o,t,void 0,s);if(c!==O.SUCCESS)return this._crtRoom=null,{code:c};a.once(si,(()=>{this._crtRoom=null}));const d={code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()};return a.__getCDNPushMode()===pi.MANUAL&&Object.assign(d,{CDNEnable:a.__getCDNEnable()}),d}))}getAudienceClient(e){return this._audience||(this._audience=new Ai(this._context,this._runtime,this._options,e)),r.info(L.L_RTC_CLIENT_GET_AUDIENCE_CLIENT_O,{status:A.SUCCESSED},{logSource:i.RTC}),this._audience}_onIMStatusChange(e){if(v.debug(`signal server connection state change: ${e}`),r.info(L.L_RTC_CLIENT_CONNECTION_STATE_S,{status:A.SUCCESSED,data:e},{logSource:i.RTC}),e===u.CONNECTED){if(this._service.detectorMediaSever(),this._crtRoom instanceof fi){this._getJoinedPKRoomList().forEach((e=>{e.__onReconnected()}))}this._crtRoom&&this._crtRoom.__onReconnected()}}_onIMDisconnect(){r.info(L.L_RTC_CLIENT_DISCONNECT_S,{status:A.SUCCESSED},{logSource:i.RTC}),v.debug("TODO -> on IM disconnect")}_onIMUninit(){r.info(L.L_RTC_CLIENT_DESTROY_S,{status:A.SUCCESSED},{logSource:i.RTC}),v.debug("TODO -> on IM client ondestroy")}leaveRoom(e){var t,o;return f(this,void 0,void 0,(function*(){return r.info(L.L_RTC_CLIENT_LEAVE_ROOM_T,{userId:this._context.getCurrentId(),roomId:null===(t=this._crtRoom)||void 0===t?void 0:t.getRoomId()},{logSource:i.RTC}),this._crtRoom?(yield this._crtRoom.__destroy(!0),v.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),this._service.detectorMediaSever(),r.info(L.L_RTC_CLIENT_LEAVE_ROOM_R,{status:A.SUCCESSED,userId:this._context.getCurrentId(),roomId:null===(o=this._crtRoom)||void 0===o?void 0:o.getRoomId()},{logSource:i.RTC}),this._crtRoom=null,{code:O.SUCCESS}):(r.warn(L.L_RTC_CLIENT_LEAVE_ROOM_R,{status:A.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:i.RTC}),{code:O.SUCCESS})}))}joinLivingRoomAsAudience(e,t,o){return f(this,void 0,void 0,(function*(){if(r.info(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_T,{roomId:e,livingType:t,useMutilPeerC:o},{logSource:i.RTC}),this._service.detectorMediaSever(),Bt(this._context.getNaviInfo()))return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:O.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:i.RTC}),{code:O.PACKAGE_ENVIRONMENT_ERROR};if(!s("roomId",e,R,!0)||!s("livingType",t,(e=>e===Ri.AUDIO||e===Ri.VIDEO)))return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:O.PACKAGE_ENVIRONMENT_ERROR,msg:"params error -> roomId or livingType"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:O.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:O.REPERT_JOIN_ROOM};if(!this._service.getNaviMS().length)return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:O.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:i.RTC}),{code:O.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:n,data:c}=yield this._context.joinLivingRoomAsAudience(e,mr.LIVE,t);if(n!==a.SUCCESS)return v.error("audienceJoinLivingRoomError:",n),r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:O.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED,msg:"signal error -> audience join room"},{logSource:i.RTC}),{code:O.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};v.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(c)}`);const d=jt(),_=new yi(this._context,this._runtime,this._options,e,c,t,o,d);return this._crtAudienceLivingRoom=_,r.info(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.SUCCESSED,roomData:c},{logSource:i.RTC}),{room:_,code:O.SUCCESS,userIds:_.getRemoteUserIds(),RTCTracks:_.getRemoteRTCTracks(),MCUTracks:_.getRemoteMCUTracks(),CDNUris:_.getCDNInfo()}}))}leaveLivingRoomAsAudience(e){return f(this,void 0,void 0,(function*(){return r.info(L.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_T,{roomId:e.getRoomId(),userId:this._context.getCurrentId()},{logSource:i.RTC}),this._crtAudienceLivingRoom?this._crtAudienceLivingRoom!==e?(r.error(L.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> room"},{logSource:i.RTC}),{code:O.PARAMS_ERROR}):(yield this._crtAudienceLivingRoom.__destroy(!0),this._crtAudienceLivingRoom=null,r.info(L.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:A.SUCCESSED,roomId:e.getRoomId(),userId:this._context.getCurrentId()},{logSource:i.RTC}),{code:O.SUCCESS}):(r.warn(L.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:i.RTC}),{code:O.SUCCESS})}))}upgradeToAnchorRoom(e){return f(this,void 0,void 0,(function*(){if(!s("room",e,(()=>e instanceof yi),!0))return r.error(L.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> room"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(r.info(L.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_T,{roomId:e.getRoomId(),userId:this._context.getCurrentId()},{logSource:i.RTC}),this._crtRoom)return r.error(L.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:A.FAILED,code:O.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:O.REPERT_JOIN_ROOM};const t=e.getRoomId(),o=this._crtRoom=new fi(this._context,this._runtime,t,this._service,this._options,e.livingType,!0,!0,!1,e.getClientSessionId()),n=yield o.__innerInitByIdentityChange();return n!==a.SUCCESS?(v.warn(`change room identity failed -> code: ${n}`),this._crtRoom=null,r.error(L.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:A.FAILED,code:O.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:i.RTC}),{code:O.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):(o.once(si,(()=>{this._crtRoom=null})),yield this._crtAudienceLivingRoom.__destroy(!1),this._crtAudienceLivingRoom=null,{room:o,code:O.SUCCESS,userIds:o.getRemoteUserIds(),tracks:o.getRemoteTracks()})}))}downgradeToAudienceRoom(e){return f(this,void 0,void 0,(function*(){if(r.info(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_T,{roomId:e._roomId,userId:this._context.getCurrentId()},{logSource:i.RTC}),!e.isMainRoom())return v.error("the `downgradeToAudienceRoom` is disabled in PK room"),r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!s("room._roomId",e._roomId,R,!0))return r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> room._roomId"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:O.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:O.REPERT_JOIN_ROOM};const{code:t,data:o}=yield this._context.rtcIdentityChange(e._roomId,Ci.AnchorToViewer,e.getLivingType());if(t!==a.SUCCESS)return v.error("change room identity error",t),r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:O.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:i.RTC}),{code:O.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};v.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(o)}`),r.info(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.SUCCESSED,roomData:o},{logSource:i.RTC});const n=e.getClientSessionId(),c=new yi(this._context,this._runtime,this._options,e._roomId,o,e.getLivingType(),!1,n);return this._crtAudienceLivingRoom=c,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:c,code:O.SUCCESS,userIds:c.getRemoteUserIds(),RTCTracks:c.getRemoteRTCTracks(),MCUTracks:c.getRemoteMCUTracks(),CDNUris:c.getCDNInfo()}}))}getJoinedRoomInfo(){return f(this,void 0,void 0,(function*(){const{code:e,data:t}=yield this._context.getRTCJoinedUserInfo(this._context.getCurrentId());return e!==a.SUCCESS?(v.error("getJoinedUserInfo error",e),r.error(L.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:A.FAILED,code:e,msg:"Switch identity error"},{logSource:i.RTC}),{code:e}):(r.info(L.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:A.SUCCESSED,roomInfo:t},{logSource:i.RTC}),{code:O.SUCCESS,data:t})}))}}var Pi;!function(e){e[e.SERVER_KICK=1]="SERVER_KICK",e[e.OTHER_KICK=2]="OTHER_KICK"}(Pi||(Pi={}));const Mi="rtcRJoin_data",xi="rtcRExit",wi="rtcRInfo",Bi="rtcUData",Vi="rtcUDel",$i="rtcSetData",Fi="userSetData",Gi="rtcQryData",Ki="rtcDelData",Hi="rtcToken",ji="rtcUserState",Ji="rtcUList",Wi="viewerJoinR",qi="viewerExitR",Yi="rtcPullKv",zi="rtcIdentityChange",Qi="rtcInvite",Zi="rtcCancelInvite",Xi="rtcInviteAnswer",eo="rtcEndInvite",to="rtcQueryJoined";var ro;!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"}(ro||(ro={}));const io={[ro.RtcInput]:["roomType","broadcastType","extraInnerData","needSysChatroom","identityChangeType","joinType","innerDatas","outerDatas"],[ro.RtcUserListOutput]:["users","token","sessionId","roomInfo"],[ro.SetUserStatusInput]:["status"],[ro.RtcSetDataInput]:["interior","target","key","value","objectName","content"],[ro.RtcUserSetDataInput]:["valueInfo","objectName","content"],[ro.RtcDataInput]:["interior","target","key","objectName","content"],[ro.RtcSetOutDataInput]:["target","valueInfo","objectName","content"],[ro.MCFollowInput]:["state"],[ro.RtcTokenOutput]:["rtcToken"],[ro.RtcQryOutput]:["outInfo"],[ro.RtcQryUserOutDataInput]:["userId"],[ro.RtcUserOutDataOutput]:["user"],[ro.RtcQueryListInput]:["order"],[ro.RtcRoomInfoOutput]:["roomId","roomData","userCount","list"],[ro.RtcValueInfo]:["key","value"],[ro.RtcKeyDeleteInput]:["key"],[ro.RtcNotifyMsg]:["type","time","roomId"],[ro.RtcPullKV]:["timestamp","roomId"],[ro.RtcKVOutput]:["entries","bFullUpdate","syncTime"],[ro.RtcQueryUserJoinedInput]:["userId"],[ro.RtcQueryUserJoinedOutput]:["info"],[ro.RtcInviteInput]:["invitedUserId","timeoutTime","invitedRoomId","inviteInfo","inviteSessionId"],[ro.RtcCancelInviteInput]:["invitedUserId","invitedRoomId","inviteInfo","inviteSessionId"],[ro.RtcInviteAnswerInput]:["inviteUserId","answerCode","inviteRoomId","inviteSessionId","content","key","value"],[ro.RtcEndInviteInput]:["inviteRoomId","inviteSessionId","inviteContent","inviteRoomKeys"]},oo=`\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 ${ro.SetUserStatusInput}\n {\n optional int32 status=1;\n }\n message ${ro.MCFollowInput}\n {\n required string state = 1;\n }\n message ${ro.RtcQueryListInput}{\n optional int32 order=1;\n }\n message ${ro.RtcKeyDeleteInput}{\n repeated string key=1;\n }\n message ${ro.RtcValueInfo}{\n required string key=1;\n required string value=2;\n }\n message RtcUserInfo{\n required string userId=1;\n repeated ${ro.RtcValueInfo} userData=2; //用户资源信息\n }\n message ${ro.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 ${ro.RtcValueInfo} roomData = 2;\n optional int32 userCount = 3;\n repeated RtcUserInfo list=4;\n }\n message ${ro.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 ${ro.RtcValueInfo} innerDatas = 7; //用户内部inner数据,角色或者连麦信息等\n repeated ${ro.RtcValueInfo} outerDatas = 8; //用户内部outer数据,自定义数据结构RtcInput。\n }\n message ${ro.RtcQryOutput}{\n repeated ${ro.RtcValueInfo} outInfo=1;\n }\n message ${ro.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 ${ro.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 ${ro.RtcUserSetDataInput} {\n repeated ${ro.RtcValueInfo} valueInfo = 1;\n required string objectName = 2;\n repeated ${ro.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 ${ro.RtcTokenOutput}{\n required string rtcToken=1;\n }\n message ${ro.RtcSetOutDataInput}{\n required targetType target=1;\n repeated ${ro.RtcValueInfo} valueInfo=2;\n optional string objectName=3;\n optional string content=4;\n }\n message ${ro.RtcQryUserOutDataInput}{\n repeated string userId = 1;\n }\n message ${ro.RtcUserOutDataOutput}{\n repeated RtcUserInfo user = 1;\n }\n message ${ro.RtcNotifyMsg} \n {\n required int32 type= 1; //(通知类型 1:rtc房间状态KV变更通知)\n optional int64 time= 2; //消息产生时间\n optional string roomId=3; //主播房间id\n }\n message ${ro.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 ${ro.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 ${ro.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 ${ro.RtcQueryUserJoinedOutput}\n {\n repeated RtcJoinedInfo info = 1;\n }\n message ${ro.RtcViewerJoinedOutput}\n {\n required string rtcToken=1;\n repeated RtcKVEntity entries = 2;//KV属性对象集合\n optional int64 syncTime = 3;//所有属性的最大时间戳(下次拉取KV时用)。\n }\n message ${ro.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 ${ro.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 ${ro.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 ${ro.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}\n`,so=(e,t,r,i,o,s)=>{const n=o?Object.keys(o).map((t=>e.encode(ro.RtcValueInfo,{key:t,value:o[t]},!0))):void 0,a=s?Object.keys(s).map((t=>e.encode(ro.RtcValueInfo,{key:t,value:s[t]},!0))):void 0;return e.encode(ro.RtcInput,{roomType:t,broadcastType:r,joinType:i,innerDatas:n,outerDatas:a})},no=(e,t)=>{const r=e.decode(ro.RtcUserListOutput,t),{users:i,token:o,sessionId:s,roomInfo:n,entries:a,offlineKickTime:c}=r,d={};return S(i,(e=>{const{userId:t,userData:r}=e,i={};S(r,(e=>{const{key:t,value:r}=e;i[t]=r})),d[t]=i})),{users:d,token:o,sessionId:s,roomInfo:n,kvEntries:a,offlineKickTime:c}};class ao{constructor(e,t){this.context=e,this.codec=t}joinRTCRoom(e,t,r,i,o,s){return f(this,void 0,void 0,(function*(){const n=so(this.codec,t,r,i,o,s),{code:c,buffer:d}=yield this.context.rtcSignaling(e,Mi,!0,n);let _;return c===a.SUCCESS&&d&&(_=no(this.codec,d)),{code:c,data:_}}))}quitRTCRoom(e){return f(this,void 0,void 0,(function*(){const t=this.codec.encode(ro.SetUserStatusInput,{status:0}),{code:r}=yield this.context.rtcSignaling(e,xi,!0,t);return r}))}getRTCRoomInfo(e){return f(this,void 0,void 0,(function*(){const t=this.codec.encode(ro.RtcQueryListInput,{order:2}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,wi,!0,t);let o;return r===a.SUCCESS&&i&&(o=this.codec.decode(ro.RtcRoomInfoOutput,i)),{code:r,data:o}}))}getRTCUserInfoList(e){return f(this,void 0,void 0,(function*(){const t=this.codec.encode(ro.RtcQueryListInput,{order:2}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,Bi,!0,t);let o;if(r===a.SUCCESS&&i){o={users:no(this.codec,i).users}}return{code:r,data:o}}))}getRTCUserInfo(e){throw new Error("Method not implemented.")}removeRTCUserInfo(e,t){return f(this,void 0,void 0,(function*(){const r=this.codec.encode(ro.RtcKeyDeleteInput,{key:t}),{code:i}=yield this.context.rtcSignaling(e,Vi,!1,r);return i}))}setRTCData(e,t,r,i,o,s){return f(this,void 0,void 0,(function*(){const n=this.codec.encode(ro.RtcSetDataInput,{interior:i,target:o,key:t,value:r,objectName:null==s?void 0:s.name,content:null==s?void 0:s.content}),{code:a}=yield this.context.rtcSignaling(e,$i,!1,n);return a}))}setRTCTotalRes(e,t,r,i,o){return f(this,void 0,void 0,(function*(){const s={objectName:i,content:this.codec.encode(ro.RtcValueInfo,{key:t.name,value:t.content},!0),valueInfo:[this.codec.encode(ro.RtcValueInfo,{key:"uris",value:r},!0)]};o&&s.valueInfo.push(this.codec.encode(ro.RtcValueInfo,{key:"mcu_uris",value:o},!0));const n=this.codec.encode(ro.RtcUserSetDataInput,s),{code:a}=yield this.context.rtcSignaling(e,Fi,!0,n);return a}))}setRTCCDNUris(e,t,r){return f(this,void 0,void 0,(function*(){const i=this.codec.encode(ro.RtcUserSetDataInput,{objectName:t,valueInfo:this.codec.encode(ro.RtcValueInfo,{key:"cdn_uris",value:r},!0)}),{code:o}=yield this.context.rtcSignaling(e,Fi,!0,i);return o}))}getRTCData(e,t,r,i){return f(this,void 0,void 0,(function*(){const o=this.codec.encode(ro.RtcDataInput,{interior:r,target:i,key:t}),{code:s,buffer:n}=yield this.context.rtcSignaling(e,Gi,!0,o);if(s!==a.SUCCESS||!n)return{code:s};const{outInfo:c}=this.codec.decode(ro.RtcQryOutput,n),d={};return c.forEach((e=>{d[e.key]=e.value})),{code:s,data:d}}))}removeRTCData(e,t,r,i,o){return f(this,void 0,void 0,(function*(){const s=this.codec.encode(ro.RtcDataInput,{interior:r,target:i,key:t,objectName:null==o?void 0:o.name,content:null==o?void 0:o.content}),{code:n}=yield this.context.rtcSignaling(e,Ki,!1,s);return n}))}setRTCOutData(e,t,r,i){return f(this,void 0,void 0,(function*(){throw new Error("JSEngine's method not implemented.")}))}getRTCOutData(e,t){return f(this,void 0,void 0,(function*(){throw new Error("JSEngine's method not implemented.")}))}getRTCToken(e,t,r){return f(this,void 0,void 0,(function*(){const i=so(this.codec,t,r),{code:o,buffer:s}=yield this.context.rtcSignaling(e,Hi,!0,i);if(o!==a.SUCCESS||!s)return{code:o};const{rtcToken:n}=this.codec.decode(ro.RtcTokenOutput,s);return{code:o,data:{rtcToken:n}}}))}setRTCState(e,t){return f(this,void 0,void 0,(function*(){const r=this.codec.encode(ro.MCFollowInput,{state:t}),{code:i}=yield this.context.rtcSignaling(e,ji,!0,r);return i}))}getRTCUserList(e){return f(this,void 0,void 0,(function*(){const t=this.codec.encode(ro.RtcQueryListInput,{order:2}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,Ji,!0,t);if(r!==a.SUCCESS||!i)return{code:r};return{code:r,data:no(this.codec,i)}}))}joinLivingRoomAsAudience(e,t,r){return f(this,void 0,void 0,(function*(){const i=so(this.codec,t,r),{code:o,buffer:s}=yield this.context.rtcSignaling(e,Wi,!0,i);if(o!==a.SUCCESS||!s)return{code:o};const{rtcToken:n,entries:c}=this.codec.decode(ro.RtcViewerJoinedOutput,s);return{code:o,data:{token:n,kvEntries:c}}}))}quitLivingRoomAsAudience(e){return f(this,void 0,void 0,(function*(){const t=this.codec.encode(ro.SetUserStatusInput,{status:0}),{code:r}=yield this.context.rtcSignaling(e,qi,!0,t);return r}))}rtcIdentityChange(e,t,r){return f(this,void 0,void 0,(function*(){const i=this.codec.encode(ro.RtcInput,{roomType:mr.LIVE,broadcastType:r,identityChangeType:t,needSysChatroom:!1}),{code:o,buffer:s}=yield this.context.rtcSignaling(e,zi,!0,i);if(o!==a.SUCCESS||!s)return{code:o};return{code:o,data:no(this.codec,s)}}))}requestRoomPK(e){return f(this,void 0,void 0,(function*(){const{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,inviteTimeout:o,inviteInfo:s,roomId:n}=e,a=this.codec.encode(ro.RtcInviteInput,{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,timeoutTime:o,inviteInfo:s}),{code:c}=yield this.context.rtcSignaling(n,Qi,!0,a);return c}))}cancelRoomPK(e){return f(this,void 0,void 0,(function*(){const{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,inviteInfo:o,roomId:s}=e,n=this.codec.encode(ro.RtcCancelInviteInput,{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,inviteInfo:o}),{code:a}=yield this.context.rtcSignaling(s,Zi,!0,n);return a}))}responseRoomPK(e){return f(this,void 0,void 0,(function*(){const{inviteUserId:t,inviteRoomId:r,inviteSessionId:i,content:o,key:s,value:n,agree:a,roomId:c}=e,d=this.codec.encode(ro.RtcInviteAnswerInput,{inviteUserId:t,inviteRoomId:r,inviteSessionId:i,content:o,key:s,value:n,answerCode:a?1:0}),{code:_}=yield this.context.rtcSignaling(c,Xi,!0,d);return _}))}endRoomPK(e){return f(this,void 0,void 0,(function*(){const{endRoomId:t,sessionId:r,content:i,keys:o,roomId:s}=e,n=this.codec.encode(ro.RtcEndInviteInput,{inviteRoomId:t,inviteSessionId:r,inviteContent:i,inviteRoomKeys:o}),{code:a}=yield this.context.rtcSignaling(s,eo,!0,n);return a}))}getRTCJoinedUserInfo(e){return f(this,void 0,void 0,(function*(){const t=this.codec.encode(ro.RtcQueryUserJoinedInput,{userId:e}),{code:r,buffer:i}=yield this.context.rtcSignaling("",to,!0,t);if(r!==a.SUCCESS||!i)return{code:r};return{code:r,data:(this.codec.decode(ro.RtcQueryUserJoinedOutput,i).info||[]).map((e=>({deviceId:e.deviceId,roomId:e.roomId,joinTime:Ft(e.joinTime)})))}}))}pullRTCRoomEntry(e){return f(this,void 0,void 0,(function*(){const t=this.codec.encode(ro.RtcPullKV,{timestamp:0,roomId:e}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,Yi,!0,t);if(r!==a.SUCCESS)return{code:r};const o=this.codec.decode(ro.RtcKVOutput,i);let{entries:s,syncTime:n}=o;return s=(s||[]).map((e=>Object.assign(Object.assign({},e),{timestamp:Ft(e.timestamp)}))),{code:r,data:{kvEntries:s,syncTime:n}}}))}decodeRtcNotify(e){const{time:t,type:r,roomId:i}=this.codec.decode(ro.RtcNotifyMsg,e);return{time:t,type:r,roomId:i}}getCurrentId(){return this.context.getCurrentId()}getNaviInfo(){return this.context.getNaviInfo()}getConnectionStatus(){return this.context.getConnectionStatus()}getAppkey(){return this.context.getAppkey()}rtcPing(e,t,r){return this.context.rtcPing(e,t,r)}sendMessage(e,t,r){return this.context.sendMessage(e,t,r)}registerRTCSignalListener(e){this.context.registerRTCSignalListener(e)}registerConnectionStateChangeListener(e){this.context.onconnectionstatechange=e}registerDisconnectListener(e){this.context.ondisconnect=e}registerDestroyListener(e){this.context.ondestroy=e}registerMessageListener(e){this.context.onmessage=e}getCoreVersion(){return this.context.getCoreVersion()}getPluginContext(){return this.context}}const co={tag:"RCRTC",verify:e=>"browser"!==e.tag?(v.error(`RCRTC Plugin is not support the runtime '${e.tag}'`),!1):Et?(g.add("plugin-rtc","5.5.5"),!!g.validEngine("^5.5.1")||(v.error(`The current engine version '${g.getInfo().engine}' error, plugin-rtc required engine version at least '^5.5.1'.`),!1)):(v.error("Please use the https protocol or use `http://localhost` to open the page!"),!1),setup(e,t,r={}){var i,s,n,a,c,d,_,u;return v.setLogLevel(r.logLevel),v.setLogStdout(r.logStdout),v.warn("RCRTC Version: 5.5.5, Commit: 30c864afb13d4825887598776eea3d4b2521e304"),v.warn(`browserInfo.browser -> ${Pt.browser}`),v.warn(`browserInfo.supportsUnifiedPlan -> ${Pt.supportsUnifiedPlan}`),v.warn(`browserInfo.version -> ${Pt.version}`),m("options.mediaServer",r.mediaServer,(e=>!(!T(e)||"https:"===location.protocol&&!/^https/.test(e)))),m("options.timeout",r.timeout,(e=>o(e)&&e>=5e3&&e<=3e4)),m("options.pingGap",r.pingGap,(e=>o(e)&&e>=3e3&&e<=1e4)),(null==r?void 0:r.audio)&&((null===(i=r.audio)||void 0===i?void 0:i.workletModule)&&(it.workletModule=null===(s=r.audio)||void 0===s?void 0:s.workletModule),(null===(n=r.audio)||void 0===n?void 0:n.workletWasm)&&(it.workletWasm=null===(a=r.audio)||void 0===a?void 0:a.workletWasm),(null===(c=r.audio)||void 0===c?void 0:c.workletModule)&&(null===(d=r.audio)||void 0===d?void 0:d.workletWasm)&&(it.isOpen=!0),void 0!==(null===(_=r.audio)||void 0===_?void 0:_.isOpen)&&(it.isOpen=null===(u=r.audio)||void 0===u?void 0:u.isOpen)),new bi(new ao(e,e.createCodec(io,oo)),t,r)}},_o={DEFAULT:"RongCloudRTC"},uo={transResolution:kt,transFrameRate:bt,parseTrackId:Ot,ifSupportLocalFileTrack:Mt,ifSupportScreenShare:xt};export{ci as BackgroundPictureFillMode,di as MixLayoutMode,_i as MixVideoRenderMode,ni as RCAbstractRoom,Ai as RCAudienceClient,yi as RCAudienceLivingRoom,Ze as RCAudioBitrate,ut as RCCameraVideoTrack,Ge as RCFrameRate,Di as RCInnerCDNPullIsHttps,Ni as RCInnerCDNPullKind,Pi as RCKickReason,fi as RCLivingRoom,Ri as RCLivingType,st as RCLocalAudioTrack,dt as RCLocalFileAudioTrack,at as RCLocalFileTrack,ct as RCLocalFileVideoTrack,ot as RCLocalTrack,nt as RCLocalVideoTrack,hi as RCMCUConfigBuilder,Ui as RCMediaStreamCapture,He as RCMediaType,_t as RCMicphoneAudioTrack,bi as RCRTCClient,O as RCRTCCode,ur as RCRTCLiveRole,Kt as RCRTCPingResult,vi as RCRTCRoom,pt as RCRemoteAudioTrack,Rt as RCRemoteTrack,mt as RCRemoteVideoTrack,Ke as RCResolution,ht as RCScreenAudioTrack,lt as RCScreenVideoTrack,_o as RCTag,Xe as RCTrack,tt as RCVideoBitrate,Cr as RTCJoinType,ze as device,uo as helper,co as installer};
|
|
15
|
+
***************************************************************************** */function f(e,t,r,i){return new(r||(r=Promise))((function(o,s){function n(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,a)}c((i=i.apply(e,t||[])).next())}))}const v=new e("RCRTC");var O,L,A;!function(e){e[e.SUCCESS=1e4]="SUCCESS",e[e.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",e[e.PARAMS_ERROR=50001]="PARAMS_ERROR",e[e.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",e[e.NOT_IN_ROOM=50003]="NOT_IN_ROOM",e[e.SERVICE_INVALID=50004]="SERVICE_INVALID",e[e.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",e[e.SIGNAL_ERROR=53001]="SIGNAL_ERROR",e[e.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",e[e.REQUEST_FAILED=53004]="REQUEST_FAILED",e[e.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",e[e.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",e[e.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",e[e.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",e[e.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",e[e.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",e[e.BROWSER_PERMISSION_DENIED=53012]="BROWSER_PERMISSION_DENIED",e[e.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",e[e.INVALID_TAGS=53014]="INVALID_TAGS",e[e.INVALID_USER_ID=53015]="INVALID_USER_ID",e[e.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",e[e.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",e[e.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",e[e.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",e[e.TRACK_NOT_READY=53020]="TRACK_NOT_READY",e[e.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",e[e.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",e[e.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",e[e.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",e[e.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",e[e.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",e[e.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",e[e.SIGNAL_JOIN_RTC_ROOM_REFUSED=53028]="SIGNAL_JOIN_RTC_ROOM_REFUSED",e[e.NO_PERMISSION_TO_USE_REQUESTED_DEVICE=53029]="NO_PERMISSION_TO_USE_REQUESTED_DEVICE",e[e.THE_FUNCTION_IS_DISABLED_IN_PKROOM=53030]="THE_FUNCTION_IS_DISABLED_IN_PKROOM",e[e.SOME_TRACKS_PUBLISH_FAILED=53031]="SOME_TRACKS_PUBLISH_FAILED",e[e.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO=53032]="MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO",e[e.JWT_TIME_OUT=1004]="JWT_TIME_OUT",e[e.SYSTEM_PERMISSION_DENIED=53033]="SYSTEM_PERMISSION_DENIED",e[e.PUBLISH_TRACKS_IS_INVALID=53034]="PUBLISH_TRACKS_IS_INVALID"}(O||(O={})),function(e){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_TIMEOUT_O="L-pinger_timeout-O",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"}(L||(L={})),function(e){e.FAILED="fail",e.SUCCESSED="success",e.TIMEOUT="timeout",e.INFO="info"}(A||(A={}));let N=!0,D=!0;function k(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function y(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,o=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return o.apply(this,arguments);const s=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,s),o.apply(this,[e,s])};const s=i.removeEventListener;i.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 i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function b(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(N=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function U(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(D=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function P(){if("object"==typeof window){if(N)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function M(e,t){D&&console.warn(e+" is deprecated, please use "+t+" instead.")}function x(e){return"[object Object]"===Object.prototype.toString.call(e)}function w(e){return x(e)?Object.keys(e).reduce((function(t,r){const i=x(e[r]),o=i?w(e[r]):e[r],s=i&&!Object.keys(o).length;return void 0===o||s?t:Object.assign(t,{[r]:o})}),{}):e}function B(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?B(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{B(e,e.get(t),r)}))})))}function V(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",o=new Map;if(null===t)return o;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&B(e,r,o)}))})),o}const $=P;function F(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const o=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[o("min",r)]=i.ideal,t.optional.push(e),e={},e[o("max",r)]=i.ideal,t.optional.push(e)):(e[o("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[o("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[o(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},o=function(e,o){if(t.version>=61)return o(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let 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=i(e.video),$("chrome: "+JSON.stringify(e)),o(e)}))}e.video=i(e.video)}return $("chrome: "+JSON.stringify(e)),o(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,i){o(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return o(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 G(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function K(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const o=new Event("track");o.track=r.track,o.receiver=i,o.transceiver={receiver:i},o.streams=[t.stream],this.dispatchEvent(o)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const o=new Event("track");o.track=r,o.receiver=i,o.transceiver={receiver:i},o.streams=[t.stream],this.dispatchEvent(o)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else y(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function H(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let o=r.apply(this,arguments);return o||(o=t(this,e),this._senders.push(o)),o};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function j(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,i]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const o=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 i=function(e){r(s(o(e)))};return t.apply(this,[i,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(s(o(t)))},r])})).then(r,i)}}function J(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=>V(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),y(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>V(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,i;return this.getSenders().forEach((r=>{r.track===e&&(t?i=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?i=!0:r=t),t.track===e))),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function W(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();r.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const o=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]})),o.apply(this,arguments)}}function q(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return W(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const o=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],o=e._streams[i.id];r=r.replace(new RegExp(o.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function n(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],o=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),o.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},o.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const o=this.getSenders().find((e=>e.track===t));if(o)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 i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=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]=i[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=n(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=c.get.apply(this);return""===e.type?e: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 Y(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function z(e,t){y(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var Q=Object.freeze({__proto__:null,shimMediaStream:G,shimOnTrack:K,shimGetSendersWithDtmf:H,shimGetStats:j,shimSenderReceiverGetStats:J,shimAddTrackRemoveTrackWithNative:W,shimAddTrackRemoveTrack:q,shimPeerConnection:Y,fixNegotiationNeeded:z,shimGetUserMedia:F,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const i=r.video&&r.video.width,o=r.video&&r.video.height,s=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},i&&(r.video.mandatory.maxWidth=i),o&&(r.video.mandatory.maxHeight=o),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});var Z,X,ee=(Z=function(e){var t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},t.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},t.getDescription=function(e){var r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){var r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((function(e){return 0===e.indexOf(r)}))},t.parseCandidate=function(e){for(var t,r={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},i=8;i<t.length;i+=2)switch(t[i]){case"raddr":r.relatedAddress=t[i+1];break;case"rport":r.relatedPort=parseInt(t[i+1],10);break;case"tcptype":r.tcpType=t[i+1];break;case"ufrag":r.ufrag=t[i+1],r.usernameFragment=t[i+1];break;default:r[t[i]]=t[i+1]}return r},t.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substr(14).split(" ")},t.parseRtpMap=function(e){var t=e.substr(9).split(" "),r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){for(var t,r={},i=e.substr(e.indexOf(" ")+1).split(";"),o=0;o<i.length;o++)r[(t=i[o].trim().split("="))[0].trim()]=t[1];return r},t.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var i=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){var t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r},t.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},t.getMid=function(e){var r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substr(6)},t.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){var r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){var t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;var t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){var i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],o=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&o?{usernameFragment:i.substr(12),password:o.substr(10)}:null},t.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},t.parseRtpParameters=function(e){for(var r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" "),o=3;o<i.length;o++){var s=i[o],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 i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" UDP/TLS/RTP/SAVPF ",i+=r.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((function(e){i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));var o=0;return r.codecs.forEach((function(e){e.maxptime>o&&(o=e.maxptime)})),o>0&&(i+="a=maxptime:"+o+"\r\n"),i+="a=rtcp-mux\r\n",r.headerExtensions&&r.headerExtensions.forEach((function(e){i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){var r,i=[],o=t.parseRtpParameters(e),s=-1!==o.fecMechanisms.indexOf("RED"),n=-1!==o.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]),o.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&r&&(t.rtx={ssrc:r}),i.push(t),s&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:n?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&c&&i.push({ssrc:c});var _=t.matchPrefix(e,"b=");return _.length&&(_=0===_[0].indexOf("b=TIAS:")?parseInt(_[0].substr(7),10):0===_[0].indexOf("b=AS:")?1e3*parseInt(_[0].substr(5),10)*.95-16e3:void 0,i.forEach((function(e){e.maxBitrate=_}))),i},t.parseRtcpParameters=function(e){var r={},i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);var o=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=o.length>0,r.compound=0===o.length;var s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.parseMsid=function(e){var r,i=t.matchPrefix(e,"a=msid:");if(1===i.length)return{stream:(r=i[0].substr(7).split(" "))[0],track:r[1]};var o=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return o.length>0?{stream:(r=o[0].value.split(" "))[0],track:r[1]}:void 0},t.parseSctpDescription=function(e){var r,i=t.parseMLine(e),o=t.matchPrefix(e,"a=max-message-size:");o.length>0&&(r=parseInt(o[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:i.fmt,maxMessageSize:r};if(t.matchPrefix(e,"a=sctpmap:").length>0){var n=t.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(n[0],10),protocol:n[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){var r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,r,i){var o=void 0!==r?r:2;return"v=0\r\no="+(i||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,r,i,o){var s=t.writeRtpDescription(e.kind,r);if(s+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===i?"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:"+o.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 i=t.splitLines(e),o=0;o<i.length;o++)switch(i[o]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[o].substr(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substr(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){var r=t.splitLines(e)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){var r=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var r=t.splitLines(e),i=0;i<r.length;i++)if(r[i].length<2||"="!==r[i].charAt(1))return!1;return!0},e.exports=t},Z(X={exports:{}},X.exports),X.exports);function te(e,t,r,i,o){var s=ee.writeRtpDescription(e.kind,t);if(s+=ee.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=ee.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":o||"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:"+(i?i.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:"+ee.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+ee.localCName+"\r\n"),s}function re(e,t){var r={codecs:[],headerExtensions:[],fecMechanisms:[]},i=function(e,t){e=parseInt(e,10);for(var r=0;r<t.length;r++)if(t[r].payloadType===e||t[r].preferredPayloadType===e)return t[r]},o=function(e,t,r,o){var s=i(e.parameters.apt,r),n=i(t.parameters.apt,o);return s&&n&&s.name.toLowerCase()===n.name.toLowerCase()};return e.codecs.forEach((function(i){for(var s=0;s<t.codecs.length;s++){var n=t.codecs[s];if(i.name.toLowerCase()===n.name.toLowerCase()&&i.clockRate===n.clockRate){if("rtx"===i.name.toLowerCase()&&i.parameters&&n.parameters.apt&&!o(i,n,e.codecs,t.codecs))continue;(n=JSON.parse(JSON.stringify(n))).numChannels=Math.min(i.numChannels,n.numChannels),r.codecs.push(n),n.rtcpFeedback=n.rtcpFeedback.filter((function(e){for(var t=0;t<i.rtcpFeedback.length;t++)if(i.rtcpFeedback[t].type===e.type&&i.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var i=0;i<t.headerExtensions.length;i++){var o=t.headerExtensions[i];if(e.uri===o.uri){r.headerExtensions.push(o);break}}})),r}function ie(e,t,r){return-1!=={offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[t][e].indexOf(r)}function oe(e,t){var r=e.getRemoteCandidates().find((function(e){return t.foundation===e.foundation&&t.ip===e.ip&&t.port===e.port&&t.priority===e.priority&&t.protocol===e.protocol&&t.type===e.type}));return r||e.addRemoteCandidate(t),!r}function se(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 ne=function(e,t){function r(t,r){r.addTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function i(t,r,i,o){var s=new Event("track");s.track=r,s.receiver=i,s.transceiver={receiver:i},s.streams=o,e.setTimeout((function(){t._dispatchEvent("track",s)}))}var o=function(r){var i=this,o=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){i[e]=o[e].bind(o)})),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 se("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var i=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var o="string"==typeof i;return o&&(i=[i]),i=i.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||r?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(r=!0,!0)})),delete e.url,e.urls=o?i[0]:i,!!i.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=ee.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(o.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(o.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),o.prototype.onicecandidate=null,o.prototype.onaddstream=null,o.prototype.ontrack=null,o.prototype.onremovestream=null,o.prototype.onsignalingstatechange=null,o.prototype.oniceconnectionstatechange=null,o.prototype.onconnectionstatechange=null,o.prototype.onicegatheringstatechange=null,o.prototype.onnegotiationneeded=null,o.prototype.ondatachannel=null,o.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},o.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},o.prototype.getConfiguration=function(){return this._config},o.prototype.getLocalStreams=function(){return this.localStreams},o.prototype.getRemoteStreams=function(){return this.remoteStreams},o.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,i={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&r)i.iceTransport=this.transceivers[0].iceTransport,i.dtlsTransport=this.transceivers[0].dtlsTransport;else{var o=this._createIceAndDtlsTransports();i.iceTransport=o.iceTransport,i.dtlsTransport=o.dtlsTransport}return t||this.transceivers.push(i),i},o.prototype.addTrack=function(t,r){if(this._isClosed)throw se("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var i;if(this.transceivers.find((function(e){return e.track===t})))throw se("InvalidAccessError","Track already exists.");for(var o=0;o<this.transceivers.length;o++)this.transceivers[o].track||this.transceivers[o].kind!==t.kind||(i=this.transceivers[o]);return i||(i=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),i.track=t,i.stream=r,i.rtpSender=new e.RTCRtpSender(t,i.dtlsTransport),i.rtpSender},o.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var i=e.clone();e.getTracks().forEach((function(e,t){var r=i.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),i.getTracks().forEach((function(e){r.addTrack(e,i)}))}},o.prototype.removeTrack=function(t){if(this._isClosed)throw se("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 se("InvalidAccessError","Sender was not created by this connection.");var i=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(i)&&this.localStreams.indexOf(i)>-1&&this.localStreams.splice(this.localStreams.indexOf(i),1),this._maybeFireNegotiationNeeded()},o.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)}))},o.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},o.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},o.prototype._createIceGatherer=function(t,r){var i=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var o=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(o,"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;o.state=r?"completed":"gathering",null!==i.transceivers[t].bufferedCandidateEvents&&i.transceivers[t].bufferedCandidateEvents.push(e)},o.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),o},o.prototype._gather=function(t,r){var i=this,o=this.transceivers[r].iceGatherer;if(!o.onlocalcandidate){var s=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,o.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),o.onlocalcandidate=function(e){if(!(i.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"!==o.state&&"gathering"!==o.state||(o.state="completed");else{"new"===o.state&&(o.state="gathering"),n.component=1,n.ufrag=o.getLocalParameters().usernameFragment;var c=ee.writeCandidate(n);s.candidate=Object.assign(s.candidate,ee.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=ee.getMediaSections(i._localDescription.sdp);d[s.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",i._localDescription.sdp=ee.getDescription(i._localDescription.sdp)+d.join("");var _=i.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==i.iceGatheringState&&(i.iceGatheringState="gathering",i._emitGatheringStateChange()),a||i._dispatchEvent("icecandidate",s),_&&(i._dispatchEvent("icecandidate",new Event("icecandidate")),i.iceGatheringState="complete",i._emitGatheringStateChange())}},e.setTimeout((function(){s.forEach((function(e){o.onlocalcandidate(e)}))}),0)}},o.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var i=new e.RTCDtlsTransport(r);return i.ondtlsstatechange=function(){t._updateConnectionState()},i.onerror=function(){Object.defineProperty(i,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:i}},o.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var r=this.transceivers[e].iceTransport;r&&(delete r.onicestatechange,delete this.transceivers[e].iceTransport);var i=this.transceivers[e].dtlsTransport;i&&(delete i.ondtlsstatechange,delete i.onerror,delete this.transceivers[e].dtlsTransport)},o.prototype._transceive=function(e,r,i){var o=re(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(o.encodings=e.sendEncodingParameters,o.rtcp={cname:ee.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(o.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(o)),i&&e.rtpReceiver&&o.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?o.encodings=e.recvEncodingParameters:o.encodings=[{}],o.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(o.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(o.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(o))},o.prototype.setLocalDescription=function(e){var t,r,i=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(se("TypeError",'Unsupported type "'+e.type+'"'));if(!ie("setLocalDescription",e.type,i.signalingState)||i._isClosed)return Promise.reject(se("InvalidStateError","Can not set local "+e.type+" in state "+i.signalingState));if("offer"===e.type)t=ee.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=ee.parseRtpParameters(e);i.transceivers[t].localCapabilities=r})),i.transceivers.forEach((function(e,t){i._gather(e.mid,t)}));else if("answer"===e.type){t=ee.splitSections(i._remoteDescription.sdp),r=t.shift();var o=ee.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var s=i.transceivers[t],n=s.iceGatherer,a=s.iceTransport,c=s.dtlsTransport,d=s.localCapabilities,_=s.remoteCapabilities;if(!(ee.isRejected(e)&&0===ee.matchPrefix(e,"a=bundle-only").length)&&!s.rejected){var u=ee.getIceParameters(e,r),l=ee.getDtlsParameters(e,r);o&&(l.role="server"),i.usingBundle&&0!==t||(i._gather(s.mid,t),"new"===a.state&&a.start(n,u,o?"controlling":"controlled"),"new"===c.state&&c.start(l));var h=re(d,_);i._transceive(s,h.codecs.length>0,!1)}}))}return i._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?i._updateSignalingState("have-local-offer"):i._updateSignalingState("stable"),Promise.resolve()},o.prototype.setRemoteDescription=function(o){var s=this;if(-1===["offer","answer"].indexOf(o.type))return Promise.reject(se("TypeError",'Unsupported type "'+o.type+'"'));if(!ie("setRemoteDescription",o.type,s.signalingState)||s._isClosed)return Promise.reject(se("InvalidStateError","Can not set remote "+o.type+" in state "+s.signalingState));var n={};s.remoteStreams.forEach((function(e){n[e.id]=e}));var a=[],c=ee.splitSections(o.sdp),d=c.shift(),_=ee.matchPrefix(d,"a=ice-lite").length>0,u=ee.matchPrefix(d,"a=group:BUNDLE ").length>0;s.usingBundle=u;var l=ee.matchPrefix(d,"a=ice-options:")[0];return s.canTrickleIceCandidates=!!l&&l.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(i,c){var l=ee.splitLines(i),h=ee.getKind(i),R=ee.isRejected(i)&&0===ee.matchPrefix(i,"a=bundle-only").length,p=l[0].substr(2).split(" ")[2],m=ee.getDirection(i,d),C=ee.parseMsid(i),T=ee.getMid(i)||ee.generateIdentifier();if(R||"application"===h&&("DTLS/SCTP"===p||"UDP/DTLS/SCTP"===p))s.transceivers[c]={mid:T,kind:h,protocol:p,rejected:!0};else{var I,E,S,g,f,v,O,L,A;!R&&s.transceivers[c]&&s.transceivers[c].rejected&&(s.transceivers[c]=s._createTransceiver(h,!0));var N,D,k=ee.parseRtpParameters(i);R||(N=ee.getIceParameters(i,d),(D=ee.getDtlsParameters(i,d)).role="client"),O=ee.parseRtpEncodingParameters(i);var y=ee.parseRtcpParameters(i),b=ee.matchPrefix(i,"a=end-of-candidates",d).length>0,U=ee.matchPrefix(i,"a=candidate:").map((function(e){return ee.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===o.type||"answer"===o.type)&&!R&&u&&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"!==o.type||R){if("answer"===o.type&&!R){E=(I=s.transceivers[c]).iceGatherer,S=I.iceTransport,g=I.dtlsTransport,f=I.rtpReceiver,v=I.sendEncodingParameters,L=I.localCapabilities,s.transceivers[c].recvEncodingParameters=O,s.transceivers[c].remoteCapabilities=k,s.transceivers[c].rtcpParameters=y,U.length&&"new"===S.state&&(!_&&!b||u&&0!==c?U.forEach((function(e){oe(I.iceTransport,e)})):S.setRemoteCandidates(U)),u&&0!==c||("new"===S.state&&S.start(E,N,"controlling"),"new"===g.state&&g.start(D)),!re(I.localCapabilities,I.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&I.sendEncodingParameters[0].rtx&&delete I.sendEncodingParameters[0].rtx,s._transceive(I,"sendrecv"===m||"recvonly"===m,"sendrecv"===m||"sendonly"===m),!f||"sendrecv"!==m&&"sendonly"!==m?delete I.rtpReceiver:(A=f.track,C?(n[C.stream]||(n[C.stream]=new e.MediaStream),r(A,n[C.stream]),a.push([A,f,n[C.stream]])):(n.default||(n.default=new e.MediaStream),r(A,n.default),a.push([A,f,n.default])))}}else{(I=s.transceivers[c]||s._createTransceiver(h)).mid=T,I.iceGatherer||(I.iceGatherer=s._createIceGatherer(c,u)),U.length&&"new"===I.iceTransport.state&&(!b||u&&0!==c?U.forEach((function(e){oe(I.iceTransport,e)})):I.iceTransport.setRemoteCandidates(U)),L=e.RTCRtpReceiver.getCapabilities(h),t<15019&&(L.codecs=L.codecs.filter((function(e){return"rtx"!==e.name}))),v=I.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var P,M=!1;if("sendrecv"===m||"sendonly"===m){if(M=!I.rtpReceiver,f=I.rtpReceiver||new e.RTCRtpReceiver(I.dtlsTransport,h),M)A=f.track,C&&"-"===C.stream||(C?(n[C.stream]||(n[C.stream]=new e.MediaStream,Object.defineProperty(n[C.stream],"id",{get:function(){return C.stream}})),Object.defineProperty(A,"id",{get:function(){return C.track}}),P=n[C.stream]):(n.default||(n.default=new e.MediaStream),P=n.default)),P&&(r(A,P),I.associatedRemoteMediaStreams.push(P)),a.push([A,f,P])}else I.rtpReceiver&&I.rtpReceiver.track&&(I.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===I.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),I.associatedRemoteMediaStreams=[]);I.localCapabilities=L,I.remoteCapabilities=k,I.rtpReceiver=f,I.rtcpParameters=y,I.sendEncodingParameters=v,I.recvEncodingParameters=O,s._transceive(s.transceivers[c],!1,M)}}})),void 0===s._dtlsRole&&(s._dtlsRole="offer"===o.type?"active":"passive"),s._remoteDescription={type:o.type,sdp:o.sdp},"offer"===o.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 o=new Event("addstream");o.stream=r,e.setTimeout((function(){s._dispatchEvent("addstream",o)}))}a.forEach((function(e){var t=e[0],o=e[1];r.id===e[2].id&&i(s,t,o,[r])}))}})),a.forEach((function(e){e[2]||i(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()},o.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")},o.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},o.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))},o.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)}},o.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)}},o.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(se("InvalidStateError","Can not call createOffer after close"));var i=r.transceivers.filter((function(e){return"audio"===e.kind})).length,o=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&&(i=!0===s.offerToReceiveAudio?1:!1===s.offerToReceiveAudio?0:s.offerToReceiveAudio),void 0!==s.offerToReceiveVideo&&(o=!0===s.offerToReceiveVideo?1:!1===s.offerToReceiveVideo?0:s.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--i<0&&(e.wantReceive=!1):"video"===e.kind&&--o<0&&(e.wantReceive=!1)}));i>0||o>0;)i>0&&(r._createTransceiver("audio"),i--),o>0&&(r._createTransceiver("video"),o--);var n=ee.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(i,o){var s=i.track,n=i.kind,a=i.mid||ee.generateIdentifier();i.mid=a,i.iceGatherer||(i.iceGatherer=r._createIceGatherer(o,r.usingBundle));var c=e.RTCRtpSender.getCapabilities(n);t<15019&&(c.codecs=c.codecs.filter((function(e){return"rtx"!==e.name}))),c.codecs.forEach((function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1"),i.remoteCapabilities&&i.remoteCapabilities.codecs&&i.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(i.remoteCapabilities&&i.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=i.sendEncodingParameters||[{ssrc:1001*(2*o+1)}];s&&t>=15019&&"video"===n&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),i.wantReceive&&(i.rtpReceiver=new e.RTCRtpReceiver(i.dtlsTransport,n)),i.localCapabilities=c,i.sendEncodingParameters=d})),"max-compat"!==r._config.bundlePolicy&&(n+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),n+="a=ice-options:trickle\r\n",r.transceivers.forEach((function(e,t){n+=te(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="+ee.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)},o.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(se("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(se("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var i=ee.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.usingBundle&&(i+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),i+="a=ice-options:trickle\r\n";var o=ee.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,s){if(!(s+1>o)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?i+="m=application 0 DTLS/SCTP 5000\r\n":i+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?i+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(i+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(i+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var n;if(e.stream)"audio"===e.kind?n=e.stream.getAudioTracks()[0]:"video"===e.kind&&(n=e.stream.getVideoTracks()[0]),n&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1});var a=re(e.localCapabilities,e.remoteCapabilities);!a.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,i+=te(e,a,"answer",e.stream,r._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(i+="a=rtcp-rsize\r\n")}}));var s=new e.RTCSessionDescription({type:"answer",sdp:i});return Promise.resolve(s)},o.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(i,o){if(!r._remoteDescription)return o(se("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 o(se("OperationError","Can not add ICE candidate"));if(a.rejected)return i();var c=Object.keys(e.candidate).length>0?ee.parseCandidate(e.candidate):{};if("tcp"===c.protocol&&(0===c.port||9===c.port))return i();if(c.component&&1!==c.component)return i();if((0===s||s>0&&a.iceTransport!==r.transceivers[0].iceTransport)&&!oe(a.iceTransport,c))return o(se("OperationError","Can not add ICE candidate"));var d=e.candidate.trim();0===d.indexOf("a=")&&(d=d.substr(2)),(t=ee.getMediaSections(r._remoteDescription.sdp))[s]+="a="+(c.type?d:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=ee.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var _=0;_<r.transceivers.length&&(r.transceivers[_].rejected||(r.transceivers[_].iceTransport.addRemoteCandidate({}),(t=ee.getMediaSections(r._remoteDescription.sdp))[_]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=ee.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));_++);i()}))},o.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 se("InvalidAccessError","Invalid selector.");return r.getStats()}var i=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&i.push(e[t].getStats())}))})),Promise.all(i).then((function(e){var t=new Map;return e.forEach((function(e){e.forEach((function(e){t.set(e.id,e)}))})),t}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(t){var r=e[t];if(r&&r.prototype&&r.prototype.getStats){var i=r.prototype.getStats;r.prototype.getStats=function(){return i.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var i;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(i=e[r]).type]||i.type,t.set(r,e[r])})),t}))}}}));var s=["createOffer","createAnswer"];return s.forEach((function(e){var t=o.prototype[e];o.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=o.prototype[e];o.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=o.prototype[e];o.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)}})),o};function ae(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 ce(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 de(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=ne(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&&M("RTCIceServer.url","RTCIceServer.urls");const i="string"==typeof t;return i&&(t=[t]),t=t.filter((e=>{if(0===e.indexOf("stun:"))return!1;const t=e.startsWith("turn")&&!e.startsWith("turn:[")&&e.includes("transport=udp");return t&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=i?t[0]:t,!!t.length}}))}(e.iceServers,t.version),P("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype}function _e(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var ue=Object.freeze({__proto__:null,shimPeerConnection:de,shimReplaceTrack:_e,shimGetUserMedia:ae,shimGetDisplayMedia:ce});function le(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){M("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function he(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 Re(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,o,s]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!o)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(o,s)}}function pe(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function me(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),y(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ce(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){M("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Te(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ie(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],r=e&&"sendEncodings"in e;r&&e.sendEncodings.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function Ee(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Se(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 ge(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 fe=Object.freeze({__proto__:null,shimOnTrack:he,shimPeerConnection:Re,shimSenderGetStats:pe,shimReceiverGetStats:me,shimRemoveStream:Ce,shimRTCDataChannel:Te,shimAddTransceiver:Ie,shimGetParameters:Ee,shimCreateOffer:Se,shimCreateAnswer:ge,shimGetUserMedia:le,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 ve(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 Oe(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 Le(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,o=t.setLocalDescription,s=t.setRemoteDescription,n=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],o=r.apply(this,[i]);return t?(o.then(e,t),Promise.resolve()):o},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],o=i.apply(this,[r]);return t?(o.then(e,t),Promise.resolve()):o};let a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function Ae(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(Ne(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function Ne(e){return e&&void 0!==e.video?Object.assign({},e,{video:w(e.video)}):e}function De(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];!i.hasOwnProperty("urls")&&i.hasOwnProperty("url")?(M("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function ke(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ye(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio"),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video")}return t.apply(this,arguments)}}function be(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Ue=Object.freeze({__proto__:null,shimLocalStreamsAPI:ve,shimRemoteStreamsAPI:Oe,shimCallbacksAPI:Le,shimGetUserMedia:Ae,shimConstraints:Ne,shimRTCIceServerUrls:De,shimTrackEventTransceiver:ke,shimCreateOfferLegacy:ye,shimAudioContext:be});function Pe(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const r=new t(e),i=ee.parseCandidate(e.candidate),o=Object.assign(r,i);return o.toJSON=function(){return{candidate:o.candidate,sdpMid:o.sdpMid,sdpMLineIndex:o.sdpMLineIndex,usernameFragment:o.usernameFragment}},o}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,y(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Me(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=ee.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=ee.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},i=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r},o=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 i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const o=ee.matchPrefix(e.sdp,"a=max-message-size:");return o.length>0?i=parseInt(o[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i},n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){const e=i(arguments[0]),t=o(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 xe(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],o=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&o>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},y(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function we(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 Be(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 Ve(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 $e=Object.freeze({__proto__:null,shimRTCIceCandidate:Pe,shimMaxMessageSize:Me,shimSendThrowTypeError:xe,shimConnectionState:we,removeExtmapAllowMixed:Be,shimAddIceCandidateNullOrEmpty:Ve});const Fe=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=P,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=k(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=k(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=k(r.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=k(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),o={browserDetails:i,commonShim:$e,extractVersion:k,disableLog:b,disableWarnings:U};switch(i.browser){case"chrome":if(!Q||!Y||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),o;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),o;r("adapter.js shimming chrome."),o.browserShim=Q,Ve(e,i),F(e,i),G(e),Y(e,i),K(e),q(e,i),H(e),j(e),J(e),z(e,i),Pe(e),we(e),Me(e,i),xe(e),Be(e,i);break;case"firefox":if(!fe||!Re||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),o;r("adapter.js shimming firefox."),o.browserShim=fe,Ve(e,i),le(e,i),Re(e,i),he(e),Ce(e),pe(e),me(e),Te(e),Ie(e),Ee(e),Se(e),ge(e),Pe(e),we(e),Me(e,i),xe(e);break;case"edge":if(!ue||!de||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),o;r("adapter.js shimming edge."),o.browserShim=ue,ae(e),ce(e),de(e,i),_e(e),Me(e,i),xe(e);break;case"safari":if(!Ue||!t.shimSafari)return r("Safari shim is not included in this adapter release."),o;r("adapter.js shimming safari."),o.browserShim=Ue,Ve(e,i),De(e),ye(e),Le(e),ve(e),Oe(e),ke(e),Ae(e),be(e),Pe(e),Me(e,i),xe(e),Be(e,i);break;default:r("Unsupported browser!")}return o}({window:"undefined"==typeof window?void 0:window});var Ge,Ke,He;!function(e){e.FPS_10="FPS_10",e.FPS_15="FPS_15",e.FPS_24="FPS_24",e.FPS_30="FPS_30"}(Ge||(Ge={})),function(e){e.W176_H132="W176_H132",e.W176_H144="W176_H144",e.W180_H180="W180_H180",e.W240_H180="W240_H180",e.W240_H240="W240_H240",e.W256_H144="W256_H144",e.W320_H180="W320_H180",e.W320_H240="W320_H240",e.W360_H360="W360_H360",e.W480_H360="W480_H360",e.W480_H480="W480_H480",e.W640_H360="W640_H360",e.W640_H480="W640_H480",e.W720_H480="W720_H480",e.W848_H480="W848_H480",e.W960_H720="W960_H720",e.W1280_H720="W1280_H720",e.W1920_H1080="W1920_H1080"}(Ke||(Ke={})),function(e){e[e.AUDIO_ONLY=0]="AUDIO_ONLY",e[e.VIDEO_ONLY=1]="VIDEO_ONLY",e[e.AUDIO_VIDEO=2]="AUDIO_VIDEO"}(He||(He={}));const je={[Ke.W176_H132]:{width:176,height:132,maxBitrate:150,minBitrate:80},[Ke.W176_H144]:{width:176,height:144,maxBitrate:150,minBitrate:80},[Ke.W180_H180]:{width:180,height:180,maxBitrate:200,minBitrate:100},[Ke.W240_H180]:{width:240,height:180,maxBitrate:240,minBitrate:120},[Ke.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[Ke.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[Ke.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[Ke.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[Ke.W360_H360]:{width:360,height:360,maxBitrate:520,minBitrate:140},[Ke.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[Ke.W480_H480]:{width:480,height:480,maxBitrate:800,minBitrate:180},[Ke.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[Ke.W640_H480]:{width:640,height:480,maxBitrate:900,minBitrate:200},[Ke.W720_H480]:{width:720,height:480,maxBitrate:1e3,minBitrate:200},[Ke.W848_H480]:{width:848,height:480,maxBitrate:1860,minBitrate:200},[Ke.W960_H720]:{width:960,height:720,maxBitrate:2e3,minBitrate:250},[Ke.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[Ke.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},Je=e=>{const t={192:180,368:360,1088:1080};return t[e]?t[e]:e},We=(e,t)=>{e=Je(e),t=Je(t);const r=je[`W${e}_H${t}`];if(r)return r;const i=e*t;return Object.keys(je).map((e=>je[e])).sort(((e,t)=>e.height*e.width-t.width*t.height)).filter((e=>e.height*e.width>=i))[0]||je.W1920_H1080},qe={10:1,15:1,24:1.5,30:1.5},Ye=e=>{let t=Number.MAX_VALUE,r=1;for(const i in qe){const o=Math.abs(e-parseInt(i));o<t&&(t=o,r=qe[i])}return r},ze={getCameras:()=>f(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))})),getMicrophones:()=>f(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))})),getSpeakers:()=>f(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audiooutput"===e.kind))}))};var Qe,Ze;!function(e){e.AUDIO="audio",e.VIDEO="video"}(Qe||(Qe={}));class Xe extends t{constructor(e,t,r,i,o){super(),this._tag=e,this._userId=t,this._kind=r,this._isLocalTrack=i,this._roomId=o,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 v.info(`set ${this._id} enabled: false`),r.info(L.L_TRACK_MUTE_O,{status:A.SUCCESSED,id:this._id},{logSource:i.RTC}),this._setLocalMuted(!0)}unmute(){return v.info(`set ${this._id} enabled: true`),r.info(L.L_TRACK_UNMUTE_O,{status:A.SUCCESSED,id:this._id},{logSource:i.RTC}),this._setLocalMuted(!1)}isLocalMuted(){return this._localMuted}isMCUTrack(){return Boolean(this._roomId)}isOwnerMuted(){return this._remoteMuted}play(e,t){return f(this,void 0,void 0,(function*(){if(r.info(L.L_TRACK_PLAY_T,{element:e,options:t},{logSource:i.RTC}),!this._msTrack)return v.warn(`the track is not ready to play -> id: ${this._id}`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:O.TRACK_NOT_READY,msg:`play error -> id: ${this._id}`},{logSource:i.RTC}),{code:O.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&(v.warn(`the track's readyState is 'ended' -> id: ${this._id}`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:"",msg:`the track's readyState is ended -> id: ${this._id}`},{logSource:i.RTC})),null==t?void 0:t.volume){if(!o(null==t?void 0:t.volume))return v.error(`${null==t?void 0:t.volume} is not a number, the valid range of options.volume is 0-100`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> options.volume不是数字"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};(null==t?void 0:t.volume)<0&&(t.volume=0,v.warn("the valid range of options.volume is 0-100, the value of volume has been set 0"),r.warn(L.L_TRACK_PLAY_R,{status:A.FAILED,code:"",msg:"params error -> options.volume < 0"},{logSource:i.RTC})),(null==t?void 0:t.volume)>100&&(t.volume=100,v.warn("the valid range of options.volume is 0-100, the value of volume has been set 100"),r.warn(L.L_TRACK_PLAY_R,{status:A.FAILED,code:"",msg:"params error -> options.volume > 100"},{logSource:i.RTC}))}if(null==t?void 0:t.audioDeviceId){if(!(yield ze.getSpeakers()).map((e=>e.deviceId)).includes(t.audioDeviceId))return v.error(`the options.audioDeviceId is invalid --\x3e ${t.audioDeviceId}`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> options.audioDeviceId"},{logSource:i.RTC}),{code:O.PARAMS_ERROR}}const s=this.isVideoTrack();return!s||e&&(e instanceof HTMLVideoElement||this.__validateVideoNodeName(e))?(this._element=s?e:this._element||new Audio,this._localMuted&&this._setLocalMuted(!1),this._element.srcObject&&this._element.srcObject===this._msStream||this._element.pause(),this._element.onloadstart=e=>{var t,o;v.debug(`HTMLMediaElement onloadstart -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onloadstart -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.ondurationchange=e=>{var t,o;v.debug(`HTMLMediaElement ondurationchange -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement ondurationchange -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onloadedmetadata=e=>{var t,o;v.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onloadedmetadata -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onloadeddata=e=>{var t,o;v.debug(`HTMLMediaElement onloadeddata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onloadeddata -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onabort=e=>{var t,o;v.info(`HTMLMediaElement onabort -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onabort -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.oncanplay=e=>f(this,void 0,void 0,(function*(){var o,n,a;v.info(`HTMLMediaElement oncanplay -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement oncanplay -> id: ${null===(n=e.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:i.RTC});try{yield null===(a=this._element)||void 0===a?void 0:a.play(),(null==t?void 0:t.audioDeviceId)&&!s&&(yield this._element.setSinkId(t.audioDeviceId))}catch(e){if("No permission to use requested device"===e.message)return v.error(`setSinkId failed -> ${e.message}`),void r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:O.NO_PERMISSION_TO_USE_REQUESTED_DEVICE,msg:"No permission"},{logSource:i.RTC});v.error(e),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:O.TRACK_PLAY_ERROR,msg:"play error"},{logSource:i.RTC})}})),this._element.onvolumechange=e=>{var t,o;const s=Math.floor(100*(null===(t=e.target)||void 0===t?void 0:t.volume));v.info(`HTMLMediaElement onvolumechange -> volume: ${s}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onvolumechange -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.srcObject=this._msStream,this._element.autoplay=!0,s&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),s||!(null==t?void 0:t.volume)&&0!==(null==t?void 0:t.volume)||(this._element.volume=(null==t?void 0:t.volume)/100),r.info(L.L_TRACK_PLAY_R,{status:A.SUCCESSED,element:e,options:t},{logSource:i.RTC}),{code:O.SUCCESS}):(v.error(`the video track need an <video> to play -> id: ${this._id}`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> element不是一个video标签"},{logSource:i.RTC}),{code:O.VIDEO_TRACK_MISS_MEDIA_ELEMENT})}))}__innerDestroy(){this.__innerSetMediaStreamTrack(void 0)}__releaseMediaElement(){this._element&&(this._element.remove(),this._element.srcObject=null)}__validateVideoNodeName(e){return e&&e.nodeName&&"VIDEO"===e.nodeName.toUpperCase()}}!function(e){e.Speech="Speech",e.Music="Music",e.MusicHigh="MusicHigh"}(Ze||(Ze={}));const et={[Ze.Music]:{max:64,min:64},[Ze.MusicHigh]:{max:128,min:128},[Ze.Speech]:{max:32,min:32}};var tt;!function(e){e.LEVEL0="LEVEL0",e.LEVEL1="LEVEL1",e.LEVEL2="LEVEL2",e.LEVEL3="LEVEL3",e.LEVEL4="LEVEL4",e.LEVEL5="LEVEL5"}(tt||(tt={}));const rt={[tt.LEVEL0]:{max:150,min:80},[tt.LEVEL1]:{max:280,min:120},[tt.LEVEL2]:{max:650,min:150},[tt.LEVEL3]:{max:1e3,min:200},[tt.LEVEL4]:{max:2200,min:250},[tt.LEVEL5]:{max:4e3,min:400}};class it{static setStatus(e=!0){it.isOpen=e}static setWroklet(e,t){it.workletModule=e,it.workletModule=t}static transformStreamTrack(e){var t;return f(this,void 0,void 0,(function*(){if(!it.isOpen)return new Promise((t=>{t({track:null==e?void 0:e.getAudioTracks()[0],stop:()=>{}})}));let r=new AudioContext({sampleRate:44100}),o=r.createMediaStreamSource(e),s=r.createMediaStreamDestination(),n=null,a=null;if(n=yield r.audioWorklet.addModule(it.workletModule).then((()=>(v.info(L.L_RTC_3ANOISE_NODE_O,{status:A.SUCCESSED,message:{msg:"addModule RC3AnoiseTrack.workletModule success"}},{logSource:i.RTC}),fetch(it.workletWasm,{cache:"force-cache",credentials:"same-origin"}).then((function(e){return e.arrayBuffer()})).catch((e=>{throw new Error(e.message)}))))).then((e=>(a=new AudioWorkletNode(r,"process-worklet",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{binary:e}}),a))).catch((e=>{v.info(L.L_RTC_3ANOISE_NODE_E,{status:A.FAILED,message:{msg:e.message}},{logSource:i.RTC})})),!n)return new Promise((t=>{t({track:null==e?void 0:e.getAudioTracks()[0],stop:()=>{}})}));o.connect(n).connect(s);let c=null===(t=null==s?void 0:s.stream)||void 0===t?void 0:t.getAudioTracks()[0],d=()=>{v.info(L.L_RTC_3ANOISE_NODE_STOP_O,{status:A.SUCCESSED,message:{msg:"call stop RC3AnoiseTrack.workletModule"}},{logSource:i.RTC}),null==n||n.port.postMessage({type:"stop",msg:""}),setTimeout((()=>{const t=null==e?void 0:e.getAudioTracks()[0];null==t||t.stop(),r.suspend(),r.close(),s.disconnect(),n.disconnect(),o.disconnect(),r=null,n=null,s=null,o=null,a=null,e=null,null==c||c.stop(),c=null,d=null}),200)};return{track:c,stop:d}}))}}it.workletModule="https://cdn.ronghub.com/plugin-rtc/wasm/5.0.0-alpha.2/process-worklet.js",it.workletWasm="https://cdn.ronghub.com/plugin-rtc/wasm/5.0.0-alpha.2/AudioProcessing.wasm",it.isOpen=!1;class ot extends Xe{constructor(e,t,r,i){super(e,t,r,!0),this._isDestroyed=!1,this._isPublished=!1,this.__innerSetMediaStreamTrack(i),i.onended=()=>{i.onended=null,this.emit(ot.EVENT_LOCAL_TRACK_END,this),this.removeAll(ot.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(e){return new Promise(((t,o)=>{const s=this._localMuted!==e;super._setLocalMuted(e),this._remoteMuted=this._localMuted,s&&this.emit(ot.__INNER_EVENT_MUTED_CHANGE__,this,t),r.info(L.L_LOCAL_TRACK_SET_LOCAL_MUTED_O,{status:A.SUCCESSED,bool:e},{logSource:i.RTC})}))}__innerSetPublished(e){r.info(L.L_LOCAL_TRACK_INNER_SET_PUBLISHED_O,{status:A.SUCCESSED,bool:e},{logSource:i.RTC}),this._isPublished=e}isPublished(){return this._isPublished}destroy(){var e;v.info(`track is destroyed -> trackId: ${this.getTrackId()}`),this._isDestroyed=!0,null===(e=this._msTrack)||void 0===e||e.stop(),super.__innerDestroy(),this.isAudioTrack()&&super.__releaseMediaElement(),this.emit(ot.__INNER_EVENT_DESTROY__,this),r.info(L.L_LOCAL_TRACK_DESTROY_O,{status:A.SUCCESSED},{logSource:i.RTC})}isDestroyed(){return this._isDestroyed}setBitrate(e=0,t=0,s=0){if(!o(e)||!o(t)||!o(s)||e<=0||t<=0||e<t)return v.error("setBitrate params error ->"),void r.error(L.L_LOCAL_TRACK_SET_BITRATE_O,{status:A.FAILED,code:"",msg:`params error -> max: ${e},min: ${t}, start: ${s}`},{logSource:i.RTC});r.info(L.L_LOCAL_TRACK_SET_BITRATE_O,{status:A.SUCCESSED,max:e,min:t,start:s},{logSource:i.RTC}),this._bitrateInfo={max:e,min:t,start:s}}getBitrate(){var e,t,r,i,o,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)===Qe.VIDEO?({min:a,max:c}=ft(this._msTrack)):(null===(t=this._msTrack)||void 0===t?void 0:t.kind)===Qe.AUDIO&&({min:a,max:c}={min:32,max:32}),(null===(r=this._bitrateInfo)||void 0===r?void 0:r.max)&&(d=.7*(null===(i=this._bitrateInfo)||void 0===i?void 0:i.max)),{min:(null===(o=this._bitrateInfo)||void 0===o?void 0:o.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}}}ot.EVENT_LOCAL_TRACK_END="local-track-end",ot.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",ot.__INNER_EVENT_DESTROY__="inner-destroy";class st extends ot{constructor(e,t,r){super(e,t,"audio",r),this._stopProcess=()=>{}}setRecommendBitrate(e){if(!s("livingType",e,(e=>e in Ze)))return void r.warn(L.L_RTC_SET_RECOMMEND_BITRATE_O,{status:A.FAILED,msg:"params error -> setRecommendBitrate Audio"},{logSource:i.RTC});const t=et[e];this.setBitrate(t.max,t.min,t.start||.7*t.max)}setBitrate(e,...t){const[r=1,i=.7*e||1]=t;super.setBitrate(e,r,i)}__innerSetMediaStreamTrack(e){if(e)if(it.isOpen){const t=new MediaStream([e]);it.transformStreamTrack(t).then((({track:e,stop:t})=>{super.__innerSetMediaStreamTrack(e),this._stopProcess=t}))}else super.__innerSetMediaStreamTrack(e);else super.__innerSetMediaStreamTrack(e),this._stopProcess()}}class nt extends ot{constructor(e,t,r,i=!1){super(e,t,"video",r),this._isTiny=i}__isTiny(){return this._isTiny}getStreamId(){const e=super.getStreamId();return this._isTiny?`${e}_tiny`:e}getTrackId(){const e=super.getTrackId();return this._isTiny?`${e}_tiny`:e}setRecommendBitrate(e){if(!s("livingType",e,(e=>e in tt)))return void r.warn(L.L_RTC_SET_RECOMMEND_BITRATE_O,{status:A.FAILED,msg:"params error -> setRecommendBitrate Video"},{logSource:i.RTC});const t=rt[e];this.setBitrate(t.max,t.min,t.start||.7*t.max)}setBitrate(e,...t){const[r=1,i=.7*e||1]=t;super.setBitrate(e,r,i)}}class at extends ot{constructor(e,t,r,i,o){super(e,t,r,i),this._resource=o,at.__innerSetMapping(this.getTrackId(),o)}static __innerSetMapping(e,t){const r=this._mapping.get(t)||[];r.push(e),this._mapping.set(t,r)}static __innerRemoveMapping(e,t){var r,i;const o=null===(r=this._mapping.get(t))||void 0===r?void 0:r.filter((t=>t!==e));o&&o.length>0?this._mapping.set(t,o):(this._mapping.delete(t),t.pause(),t.src="",null===(i=t.parentNode)||void 0===i||i.removeChild(t))}destroy(){this.isAudioTrack()&&this.mute(),at.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}at._mapping=new Map;class ct extends at{constructor(e,t,r,i){super(e,t,"video",r,i)}}class dt extends at{constructor(e,t,r,i){super(e,t,"audio",r,i),this._stopProcess=()=>{}}_setLocalMuted(e){const t=Object.create(null,{_setLocalMuted:{get:()=>super._setLocalMuted}});return f(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:O.SUCCESS})}__innerSetMediaStreamTrack(e){if(e)if(it.isOpen){const t=new MediaStream([e]);it.transformStreamTrack(t).then((({track:e,stop:t})=>{super.__innerSetMediaStreamTrack(e),this._stopProcess=t}))}else super.__innerSetMediaStreamTrack(e);else super.__innerSetMediaStreamTrack(e),this._stopProcess()}}class _t extends st{}class ut extends nt{}class lt extends nt{}class ht extends st{}class Rt extends Xe{constructor(e,t,r,i){super(e,t,r,!1,i),this._isSubscribed=!1}__innerSetRemoteMuted(e){this._remoteMuted=e}__innerSetSubscribed(e){this._isSubscribed=e,r.info(L.L_REMOTE_TRACK_INNER_SET_SUBSCRIBED_O,{status:A.SUCCESSED,bool:e},{logSource:i.RTC})}isSubscribed(){return this._isSubscribed}}class pt extends Rt{constructor(e,t,r){super(e,t,"audio",r)}}class mt extends Rt{constructor(e,t,r){super(e,t,"video",r),this._isSubTiny=!1}__innerSetIsTinyTrack(e){this._isSubTiny=e}isSubTiny(){return this._isSubTiny}}const Ct=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),Tt=e=>JSON.stringify(e),It=e=>/^[a-zA-Z\d-=]+$/g.test(e),Et="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),St=e=>{if(void 0===e)return 0;if(o(e))return e;const t=e;return t.exact||t.ideal||t.max||0},gt=e=>{const t=e.getSettings(),r=e.getConstraints();return{width:St(r.width)||t.width||0,height:St(r.height)||t.height||0,frameRate:t.frameRate||St(r.frameRate)}},ft=e=>{const{width:t,height:r,frameRate:i}=gt(e),o=We(t||1920,r||1080),s=Ye(i);return{min:o.minBitrate*s,max:o.maxBitrate*s}},vt=e=>[e.msid,e.mediaType].join("_"),Ot=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},Lt=(e,t)=>[e,t].join("_"),At=e=>e.map((e=>Object.assign({},e))),Nt=(e,t,r=!1)=>{e=e.slice();const i=[],o=[],s=[];return t.forEach((t=>{const o=vt(t);let n=e.findIndex((e=>vt(e)===o));if(r&&(n=e.findIndex((e=>e.uri===t.uri))),-1===n)return void i.push(t);const a=e[n];a.uri!==t.uri?i.push(t):a.state!==t.state&&s.push(t),e.splice(n,1)})),o.push(...e),{publishedList:i,unpublishedList:o,modifiedList:s}},Dt=()=>{let e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return e=e.replace(/-/g,"")+"0",e=parseInt(e,16),e=(e=>{const t="0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ+/".split(""),r=t.length+1;let i=+e;const o=[];do{const e=i%r;i=(i-e)/r,o.unshift(t[e])}while(i);return o.join("")})(e),e.length>22&&(e=e.slice(0,22)),e},kt=e=>{if(je[e]){const{width:t,height:r}=je[e];return{width:t,height:r}}const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},yt=e=>!!Ke[e],bt=e=>!!Ge[e],Ut=e=>parseInt(e.replace("FPS_","")),Pt=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=Fe.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function Mt(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function xt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const wt=e=>"[object Null]"===Object.prototype.toString.call(e),Bt=e=>1===e.type,Vt=(e,t)=>{const r={},i=Object.keys(e.users);return i.length&&i.forEach((i=>{const o=[],s=e.users[i];if(s.extra){const e=JSON.parse(s.extra).roomId;if(t!==e)return}if(s.uris)try{o.push(...JSON.parse(s.uris))}catch(e){v.warn(`invalid user data -> userId: ${i}, userData: ${s}`)}r[i]=o})),r},$t=e=>e instanceof Xe?e.getTrackId():e.track.getTrackId(),Ft=e=>{if(!n(e)||void 0===e.low||void 0===e.high)return e;let t=e.low;t<0&&(t+=4294967296),t=t.toString(16);return parseInt(e.high.toString(16)+"00000000".replace(new RegExp("0{"+t.length+"}$"),t),16)};var Gt,Kt;!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"}(Gt||(Gt={})),function(e){e.SUCCESS="Success",e.FAIL="Fail"}(Kt||(Kt={}));class Ht{constructor(e,t,r,i=5e3,o=6e4){this._roomId=e,this._roomMode=t,this._context=r,this._gap=i,this._offlineKickTime=o,this._latestTimestamp=Date.now(),this._started=!1,this._timer=null}start(){this._started||(v.info("rtcping start ->"),r.info(L.L_PINGER_START_O,{status:A.SUCCESSED,interval:this._gap},{logSource:i.RTC}),this._started=!0,this._checkAlive())}_sendPing(){return new Promise((e=>{this._context.rtcPing(this._roomId,this._roomMode).then(e).catch((t=>{v.error(`rtcping receive unknown error -> ${t}`),e(a.UNKNOWN)})),setTimeout(e,5e3,a.TIMEOUT)}))}_checkAlive(){var e,t,o;return f(this,void 0,void 0,(function*(){v.info("rtcping ->");const s=yield this._sendPing(),n=Date.now();return s===a.SUCCESS?(v.info("rtcping success ->"),this._latestTimestamp=n,null===(e=this.onPingResult)||void 0===e||e.call(this,Kt.SUCCESS),void(this._timer=setTimeout((()=>this._checkAlive()),this._gap))):(s===a.TIMEOUT&&r.error(L.L_PINGER_TIMEOUT_O,{status:A.TIMEOUT},{logSource:i.RTC}),v.warn(`rtcping failed -> code: ${s}`),null===(t=this.onPingResult)||void 0===t||t.call(this,Kt.FAIL),40003===s||n-this._latestTimestamp>this._offlineKickTime?(this.stop(),void(null===(o=this.onFailed)||void 0===o||o.call(this,40003===s))):void(this._timer=setTimeout((()=>this._checkAlive()),500)))}))}stop(){this._started&&(v.info("rtcping stop ->"),r.info(L.L_PINGER_STOP_O,{status:A.SUCCESSED},{logSource:i.RTC}),this._started=!1,this._timer&&(clearTimeout(this._timer),this._timer=null))}}const jt=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),Jt=(e,t,r)=>f(void 0,void 0,void 0,(function*(){const i=[];return yield Promise.any(e.map((e=>f(void 0,void 0,void 0,(function*(){const o=`${e.detectorAddr.replace(/^(https?:\/\/)?/,"https://")}/rtc/detector/ping?t=${s=1e3,n=9999,s+Math.floor(Math.random()*(n-s))}`;var s,n;const a={jwt:r},d=yield t.httpReq({url:o,body:JSON.stringify(a),timeout:_,method:c.POST});if(v.info(`ping res => ${JSON.stringify({status:d.status,host:e})}`),200!==d.status)return Promise.reject();i.push(e.clusterId)}))))),i})),Wt=(e,t)=>f(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 v.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 o=i[0];return o.detectorManager?o.detectorManager:""})(t),i=(o=t)&&o.jwt||"";var o;let s=null,n=120,a=0;const _={jwt:i};if(r&&i){const t=yield e.httpReq({url:`${r}/rtc/detector/servers`,body:JSON.stringify(_),headers:{"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${Pt.browser}|${Pt.version}`,ClientVersion:"5.5.6","Client-Session-Id":jt(),"Request-Id":Date.now().toString()},method:c.POST}),o=t.data&&JSON.parse(t.data).detectorAddrs;n=t.data&&JSON.parse(t.data).clientDetectMinute,a=t.data&&JSON.parse(t.data).resultCode,o&&d(o)&&(s=yield Jt(o,e,i))}return{fastMediaUrl:s,clientDetectMinute:n,status:a}})),qt=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${Pt.browser}|${Pt.version}`,ClientVersion:"5.5.6","Client-Session-Id":jt(),"Request-Id":Date.now().toString()});class Yt{constructor(e,t,r,i=5e3){this._runtime=e,this._context=t,this._msUrl=r,this._timeout=i,this._msInNavi=[],this._failedMs=[],this._rtcFinger=void 0,this._clusterId="",this._configUrl="",this._msList=[],Yt.isDetector||t.getConnectionStatus()!==u.CONNECTED||this.detectorMediaSever()}detectorMediaSever(){if(this._msUrl)return;const e=Date.now(),t=Yt.detectValidMinute+Yt.detectorTime>e;Yt.isDetector=t,r.info(`set msInDetector => ${JSON.stringify(Yt.msInDetector)}`);const i=this._context.getNaviInfo();!t&&i&&l(i)&&(this._msList=[],this._getDetectorUrls(i))}_getDetectorUrls(e){return f(this,void 0,void 0,(function*(){if(Yt.isDetector)return;Yt.isDetector=!0;const{fastMediaUrl:t,clientDetectMinute:r,status:i}=yield Wt(this._runtime,e);if(i===O.JWT_TIME_OUT&&Yt.naviRefetchCount<5){this._context.getPluginContext().refetchNaviInfo().then((()=>{this.detectorMediaSever()})),++Yt.naviRefetchCount,v.info(`RCMediaService refetch navi count => ${Yt.naviRefetchCount}`)}Yt.msInDetector=t||[],Yt.detectorTime=Date.now(),Yt.detectValidMinute=60*r*1e3,v.info(`RCMediaService detectorTime => ${Yt.detectorTime}`),v.info(`RCMediaService detectValidMinute => ${Yt.detectValidMinute}`)}))}getNaviMS(){return this._msUrl?[this._msUrl]:(h(this._msList)&&!this._clusterId||(this._msList=this.setMediaServiceList()),this._msList)}setMediaServiceList(){let e=[],t=[];return this._clusterId&&(this._clusterId=this._clusterId.replace(/^(https?:\/\/)?/,"https://"),this._msList.push(this._clusterId)),v.info(`MediaServiceList _clusterId -> ${this._clusterId}`),h(Yt.msInDetector)&&(Yt.msInDetector=Yt.msInDetector.map((e=>e.replace(/^(https?:\/\/)?/,"https://"))),this._msList.push(Yt.msInDetector[0]),e=Yt.msInDetector.concat().splice(1,Yt.msInDetector.length-1)),v.info(`MediaServiceList msInDetector ->${JSON.stringify(Yt.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 v.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 o=i[0],s=[];return o.mediaServer&&s.push(o.mediaServer.replace(/^(https?:\/\/)?/,"https://")),o.backupMediaServer&&o.backupMediaServer.forEach((e=>{s.push(e.replace(/^(https?:\/\/)?/,"https://"))})),s})(this._context.getNaviInfo())):(this._msInNavi.push(...this._failedMs),this._failedMs.length=0)),v.info(`MediaServiceList _msInNavi-> ${JSON.stringify(this._msInNavi)}`),t=this._msInNavi.concat().splice(1,this._msInNavi.length-1),this._msList.push(this._msInNavi[0]),this._msList=[...this._msList,...e,...t],this._msList=[...new Set(this._msList)],v.info(`MediaServiceList msList -> ${JSON.stringify(this._msList)}`),this._msList}_request(e,t,o){return f(this,void 0,void 0,(function*(){const s=this.getNaviMS();if(0===s.length)return v.warn(`request '${e}' failed -> have no valid service address.`),r.error(L.L_MEDIA_SERVICE_REQUEST_R,{status:A.FAILED,code:O.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"invalid navi_url"},{logSource:i.RTC}),{code:O.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(o.rtcFinger=this._rtcFinger);for(let n=0;n<s.length;n+=1){const a=`${s[n]}${e}`,d=qt(),_=Object.assign(Object.assign({},d),t),u=JSON.stringify(o),l=d["Request-Id"];r.info(L.L_MEDIA_SERVICE_REQUEST_T,{path:e,headers:t,body:o,reqId:l},{logSource:i.RTC}),v.info(`request -> Request-Id: ${l}, url: ${a}, headers: ${JSON.stringify(_)}, body: ${u}, timeout: ${this._timeout}`);const{status:h,data:R}=yield this._runtime.httpReq({url:a,body:u,headers:_,method:c.POST,timeout:this._timeout});if(200===h){const e=JSON.parse(R);return e.rtcFinger&&(this._rtcFinger=e.rtcFinger),e.clusterId&&(this._clusterId=e.clusterId),v.info(`request success -> Request-Id: ${l}`),r.info(L.L_MEDIA_SERVICE_REQUEST_R,{status:A.SUCCESSED,url:a,reqId:l},{logSource:i.RTC}),{code:O.SUCCESS,data:e}}v.warn(`request failed -> Request-Id: ${l}, status: ${h}, url: ${a}`),this._failedMs.push(...this._msInNavi.splice(n,1)),r.error(L.L_MEDIA_SERVICE_REQUEST_R,{status:A.FAILED,code:"",reqId:l,url:a,msg:`request error -> Request-Id: ${l}, status: ${h}, url: ${a}`},{logSource:i.RTC})}return{code:O.REQUEST_FAILED}}))}exchange(e,t){var r;return f(this,void 0,void 0,(function*(){const i=yield this._request("/exchange",e,t);if(i.code===O.SUCCESS&&(null===(r=i.data)||void 0===r?void 0:r.resultCode)===O.SUCCESS){const e=i.data.urls;e&&(this._configUrl=e.configUrl)}return i}))}exit(e){return f(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 f(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/broadcast/exit",e,{});return{code:t}}))}setMcuConfig(e,t){return f(this,void 0,void 0,(function*(){if(r.info(L.L_MEDIA_SERVICE_SET_MCU_CONFIG_T,{headers:e,body:t},{logSource:i.RTC}),!this._configUrl)return v.warn("RCMediaService.setMcuConfig failed -> RCRTCCode.MCU_SERVER_NOT_FOUND"),r.error(L.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:A.FAILED,code:O.MCU_SERVER_NOT_FOUND,msg:"MCU not found"},{logSource:i.RTC}),{code:O.MCU_SERVER_NOT_FOUND};const o=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,s=qt(),n=Object.assign(Object.assign({},s),e),a=JSON.stringify(t),d=s["Request-Id"];v.info(`request -> Request-Id: ${d}, url: ${o}, headers: ${JSON.stringify(n)}, body: ${a}`);const{status:_,data:u}=yield this._runtime.httpReq({url:o,headers:n,body:a,method:c.POST});if(200===_){v.info(`request success -> Request-Id: ${d}`);const e=JSON.parse(u);return r.info(L.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:A.SUCCESSED,reqId:d},{logSource:i.RTC}),{code:e.resultCode,res:e}}return v.warn(`request failed -> Request-Id: ${d}, status: ${_}, url: ${o}`),r.error(L.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:A.FAILED,code:O.REQUEST_FAILED,msg:`request error -> Request-Id: ${d}, status: ${_}, url: ${o}`},{logSource:i.RTC}),{code:O.REQUEST_FAILED}}))}getCDNResourceInfo(e,t){return f(this,void 0,void 0,(function*(){r.info(L.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_T,{headers:e,url:t},{logSource:i.RTC});const o=qt(),s=Object.assign(Object.assign({},o),e),n=o["Request-Id"];v.info(`request -> Request-Id: ${n}, url: ${t}, headers: ${JSON.stringify(s)}`);const{status:a,data:d}=yield this._runtime.httpReq({url:t,headers:s,method:c.GET});if(200===a){v.info(`request success -> Request-Id: ${o["Request-Id"]}`);const e=JSON.parse(d);return r.info(L.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:A.SUCCESSED,reqId:o["Request-Id"]},{logSource:i.RTC}),{code:e.resultCode,res:e}}return v.warn(`request failed -> Request-Id: ${o["Request-Id"]}, status: ${a}, url: ${t}`),r.info(L.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:A.FAILED,code:O.REQUEST_FAILED,msg:`request error -> Request-Id: ${o["Request-Id"]}, status: ${a}, url: ${t}`},{logSource:i.RTC}),{code:O.REQUEST_FAILED}}))}}var zt;Yt.isDetector=!1,Yt.msInDetector=[],Yt.detectorTime=0,Yt.detectValidMinute=72e5,Yt.naviRefetchCount=0,function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(zt||(zt={}));const Qt=(e,t)=>Math.round(8*t/e),Zt=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},Xt=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.round(e*r)},er=(e,t,r,i)=>{if(0===t)return 0;if(!r||!i)return Zt(e/t,3);const o=t-i;if(0===o)return 0;const s=e-r;return s<0||o<0?0:Zt(s/o,3)},tr=e=>{const{jitter:t,rtt:r,packetsLostRate:i}=e;return!wt(t)||!wt(r)||0!==i};class rr{constructor(e,t,r){this._rtcPeerConn=e,this._sdpSemantics=t,this._currentUserId=r,this._latestPacketsSent={},this._latestBytesSent={},this._latestBytesRecv={},this._latestPacketsRecv={}}updateBytesSent(e,t,r){let i,o;if(this._latestBytesSent[e]&&t<this._latestBytesSent[e].bytesSent&&this.clearLatestpacketsSent([e]),this._latestBytesSent[e]){const{bytesSent:s,timestamp:n}=this._latestBytesSent[e];i=t-s,o=r-n,this._latestBytesSent[e]={bytesSent:t,timestamp:r}}else i=t,o=1e3,this._latestBytesSent[e]={bytesSent:t,timestamp:r};return Qt(o,i)}updateBytesRecv(e,t,r){let i,o;if(this._latestBytesRecv[e]&&t<this._latestBytesRecv[e].bytesRecv&&this.clearLatestPacketsRecv([e]),this._latestBytesRecv[e]){const{bytesRecv:s,timestamp:n}=this._latestBytesRecv[e];i=t-s,o=r-n,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r}}else i=t,o=1e3,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r};return Qt(o,i)}updateSenderPacketsLost(e,t,r){let i;if(Object.prototype.hasOwnProperty.call(this._latestPacketsSent[e],"packetsSent")){const{packetsLost:o,packetsSent:s}=this._latestPacketsSent[e];i=er(t,r,o,s),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=o===t?s:r}else i=er(t,r),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=r;return i}updateReceiverPacketsLost(e,t,r){let i;if(this._latestPacketsRecv[e]){const{packetsLost:o,packetsRecv:s}=this._latestPacketsRecv[e];i=er(t,r+t,o,s+o)}else i=er(t,r);return this._latestPacketsRecv[e]={packetsLost:t,packetsRecv:r},i}clearLatestpacketsSent(e){e.forEach((e=>{if(parseInt(e.split("_").pop())===He.VIDEO_ONLY){const t=`${e}_tiny`;delete this._latestPacketsSent[t],delete this._latestBytesSent[t]}delete this._latestPacketsSent[e],delete this._latestBytesSent[e]}))}clearLatestPacketsRecv(e){e.forEach((e=>{delete this._latestPacketsRecv[e],delete this._latestBytesRecv[e]}))}parseRTCStatsReport(e){const t=e.keys(),r={};let i=t.next();for(;!i.done;){const o=i.value,s=e.get(o);/^RTCCodec_/.test(o)||(r[o]=s),i=t.next()}return r}formatRCRTCStateReport(e){const t={senders:[],receivers:[]};return r.info(L.L_ABSTRACT_STAT_PARSER_FORMAT_RTC_STATE_REPORT_O,{status:A.SUCCESSED,stats:e,reports:t},{logSource:i.RTC}),t}getAudioLevelList(e){return[]}getResourceIdByParseSdp(e){var t,r;const i=e.ssrc,o=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:${i} msid:(.*?) `);const c=null==s?void 0:s.split("\r\nm="),d=null==c?void 0:c.filter((e=>e.includes(`a=ssrc:${i}`)))[0],_=null==d?void 0:d.match(a);let u=_?_[1]:"";if(u){if("audio"===o)return`${u}_0`;const e=u.replace(`${this._currentUserId}_`,"").split("_");return e.length>1&&"tiny"===e[1]?`${this._currentUserId}_${e[0]}_1_tiny`:`${u}_1`}const l=null==n?void 0:n.split("\r\nm="),h=null==l?void 0:l.filter((e=>e.includes(`a=ssrc:${i}`)))[0],R=null==h?void 0:h.match(a);return u=R?R[1]:"",u?`${u}_${"video"===o?1:0}`:""}isValidSender(e){var t;const r=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}isValidReceiver(e){var t;const r=null===(t=this._rtcPeerConn.currentRemoteDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}}class ir extends rr{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let o=0,s=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const n=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const{id:a,kind:c,transportId:d,mediaSourceId:_,remoteId:u,packetsSent:l,bytesSent:h,trackId:R,encoderImplementation:p,pliCount:m,nackCount:C,firCount:T}=n;if(!R)return;let{framesPerSecond:I,frameWidth:E,frameHeight:S}=n;"video"!==c||E||S||I||(E=e[R].frameWidth,S=e[R].frameHeight,I=_?e[_].framesPerSecond:null);const g=e[u];let f=null,v=null,O=0;g&&(f=g.jitter,v=g.roundTripTime,O=g.packetsLost),o+=O;const L=this.getResourceIdByParseSdp(n);if(!L)return;const A=_?e[_].audioLevel:e[R].audioLevel;let N=null;!this._latestPacketsSent[L]&&(this._latestPacketsSent[L]={}),g?N=this.updateSenderPacketsLost(L,O,l):this._latestPacketsSent[L].crtPacketsSent=l;let D=this.updateBytesSent(L,h,r);D<0&&(D=0),s+=D,t.senders.push({id:a,trackId:L,kind:c,packetsLostRate:N,remoteResource:!1,audioLevel:A||0===A?Xt(A):null,frameWidth:E,frameHeight:S,frameRate:I,bitrate:D,jitter:f?Math.round(1e3*f):f,rtt:v,encoderImplementation:p,pliCount:m,nackCount:C,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));i.filter((e=>/RTCRemoteInboundRtp(Video|Audio)Stream_/.test(e))).forEach((r=>{const{localId:i,jitter:o,roundTripTime:s,packetsLost:n}=e[r],a=t.senders.filter((e=>e.id===i))[0];if(a&&!tr(a)){const t=this.getResourceIdByParseSdp(e[a.id]);a.jitter=Math.round(1e3*o),a.rtt=s;const r=this._latestPacketsSent[t].crtPacketsSent;a.packetsLostRate=this.updateSenderPacketsLost(t,n,r)}}));let n=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const s=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:_,bytesReceived:u,framesPerSecond:l,kind:h,codecImplementationName:R,nackCount:p,pliCount:m}=s;if(!a)return;let{frameWidth:C,frameHeight:T,audioLevel:I}=s;"video"===h?C||T||(C=e[a].frameWidth,T=e[a].frameHeight):I||(I=e[a].audioLevel),o+=c;const E=this.getResourceIdByParseSdp(s),S=this.updateReceiverPacketsLost(E,c,d);let g=this.updateBytesRecv(E,u,r);g<0&&(g=0),n+=g,t.receivers.push({trackId:E,kind:h,packetsLostRate:S,remoteResource:!0,audioLevel:I||0===I?Xt(I):null,frameWidth:C,frameHeight:T,frameRate:l,bitrate:g,jitter:_?Math.round(1e3*_):0,codecImplementationName:R,nackCount:p,pliCount:m,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:_,remoteCandidateId:u}=r,l=e[_],{ip:h,port:R,networkType:p}=l,m=e[u],{ip:C,port:T,protocol:I}=m;t.iceCandidatePair={IP:h,port:R,networkType:p,remoteIP:C,remotePort:T,protocol:I,bitrateRecv:n,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:o},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTPAudioStream_/.test(e))).forEach((r=>{var i;const o=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))return;const{mediaSourceId:s,trackId:n}=o,a=this.getResourceIdByParseSdp(o),c=s&&e[s]?e[s].audioLevel:(null===(i=e[n])||void 0===i?void 0:i.audioLevel)||null;t.push({trackId:a,audioLevel:c||0===c?Xt(c):null})}));return r.filter((e=>/^RTCInboundRTPAudioStream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:o}=i,s=i.audioLevel||e[o].audioLevel,n=this.getResourceIdByParseSdp(i);t.push({trackId:n,audioLevel:s||0===s?Xt(s):null})})),t}}class or extends rr{formatRCRTCStateReport(e){const t=+new Date,r={senders:[],receivers:[],timestamp:t};let i=0,o=0,s=0;for(const n in e){const a=e[n],c=a.type;if("outbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(a))continue;const{id:s,kind:n,bytesSent:c,packetsSent:d,bitrateMean:_,framerateMean:u,nackCount:l,pliCount:h,remoteId:R}=a,{jitter:p,roundTripTime:m,packetsLost:C}=R?e[R]:{jitter:null,roundTripTime:null,packetsLost:0},T=this.getResourceIdByParseSdp(a);i+=C;let I=null;!this._latestPacketsSent[T]&&(this._latestPacketsSent[T]={}),R?I=this.updateSenderPacketsLost(T,C,d):this._latestPacketsSent[T].crtPacketsSent=d;let E=0;"video"===n?_&&(E=Math.floor(_/1e3)):E=this.updateBytesSent(T,c,t),E<0&&(E=0),o+=E,r.senders.push({trackId:T,kind:n,packetsLostRate:I,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:E,jitter:p?Math.round(1e3*p):null,rtt:m,encoderImplementation:null,pliCount:h,nackCount:l,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}if("remote-inbound-rtp"===c){const{localId:t}=a,i=this.getResourceIdByParseSdp(e[t]),o=r.senders.filter((e=>e.trackId===i))[0];o&&tr(o)&&(o.jitter=Math.round(1e3*a.jitter),o.rtt=a.rtt,o.packetsLostRate=this.updateSenderPacketsLost(i,a.packetsLost,this._latestPacketsSent[i].crtPacketsSent))}if("inbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(a))continue;const{id:e,packetsLost:o,bytesReceived:n,packetsReceived:c,jitter:d,framerateMean:_,kind:u,bitrateMean:l,nackCount:h,pliCount:R}=a,p=this.getResourceIdByParseSdp(a);i+=o;const m=this.updateReceiverPacketsLost(p,o,c);let C=0;"video"===u?l&&(C=Math.floor(l/1e3)):C=this.updateBytesRecv(p,n,t),C<0&&(C=0),s+=C,r.receivers.push({trackId:p,kind:u,packetsLostRate:m,remoteResource:!0,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(_),bitrate:C,jitter:d?Math.round(1e3*d):null,codecImplementationName:null,nackCount:h,pliCount:R,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}if("candidate-pair"===c&&"succeeded"===a.state){const t=e[a.localCandidateId],{address:n,port:c}=t,d=e[a.remoteCandidateId],{address:_,port:u,protocol:l}=d;r.iceCandidatePair={IP:n,port:c,networkType:null,remoteIP:_,remotePort:u,protocol:l,bitrateRecv:s,bitrateSend:o,rtt:null,availableOutgoingBitrate:null,availableIncomingBitrate:null,totalPacketsLost:i}}}return r.iceCandidatePair&&(r.iceCandidatePair.bitrateSend=o),r.iceCandidatePair&&(r.iceCandidatePair.bitrateRecv=s),r}getAudioLevelList(e){const t=[];for(const r in e){const i=e[r],o=i.type;if("outbound-rtp"===o){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}if("inbound-rtp"===o){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}}return t}}class sr extends rr{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let o=0,s=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const o=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))return;const n=this.getResourceIdByParseSdp(o),{mediaType:a,transportId:c,remoteId:d,packetsSent:_,bytesSent:u,trackId:l,encoderImplementation:h,pliCount:R,nackCount:p,firCount:m}=o;if(!l)return;const{audioLevel:C,frameHeight:T,frameWidth:I}=e[l];let E=this.updateBytesSent(n,u,r);E<0&&(E=0),s+=E,t.senders.push({trackId:n,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:C||0===C?Xt(C):null,frameWidth:I,frameHeight:T,frameRate:null,bitrate:E,jitter:null,rtt:null,encoderImplementation:h,pliCount:R,nackCount:p,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));let n=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const s=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:_,bytesReceived:u,mediaType:l,nackCount:h,pliCount:R}=s,p=this.getResourceIdByParseSdp(s);if(!a)return;const{frameHeight:m,frameWidth:C,audioLevel:T}=e[a];o+=c;const I=this.updateReceiverPacketsLost(p,c,d);let E=this.updateBytesRecv(p,u,r);E<0&&(E=0),n+=E,t.receivers.push({trackId:p,kind:l,packetsLostRate:I,remoteResource:!0,audioLevel:T||0===T?Xt(T):null,frameWidth:C,frameHeight:m,frameRate:null,bitrate:E,jitter:_,codecImplementationName:null,nackCount:h,pliCount:R,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:_,remoteCandidateId:u}=r,l=e[_],{address:h,port:R}=l,p=e[u],{address:m,port:C,protocol:T}=p;t.iceCandidatePair={IP:h||null,port:R,networkType:null,remoteIP:m,remotePort:C,protocol:T,bitrateRecv:n,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:o},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const{trackId:o,mediaType:s}=i;if("video"===s)return;const n=this.getResourceIdByParseSdp(i),a=e[o];t.push({trackId:n,audioLevel:a||0===a?Xt(a):null})}));return r.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:o,mediaType:s}=i;if(!o||"video"===s)return;const{audioLevel:n}=e[o],a=this.getResourceIdByParseSdp(i);t.push({trackId:a,audioLevel:n||0===n?Xt(n):null})})),t}}class nr{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=RegExp("m=(?:video|audio)","img"),t=new Set([0]);let r;for(;null!==(r=e.exec(this.SDP));)t.add(r.index);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*nr.KBitrate}\r\nb=TIAS:${e*nr.KBitrate*850}`)}setAudiosBitrate(e){return v.info(L.L_RTC_SDP_BITRATE_O,{bitrate:e,msg:"SDP setAudiosBitrate"},{logSource:i.RTC}),this.audioStreams=this.audioStreams.map((t=>this.setAudioItemBitrate(t,e))),this}setAudioBitrateWithStreamId(e,t){return v.info(L.L_RTC_SDP_BITRATE_O,{bitrate:e,streamId:t,msg:"SDP setAudioBitrateWithStreamId"},{logSource:i.RTC}),this.audioStreams=this.audioStreams.map((r=>new RegExp(`\\bmsid:${t}\\b`,"ig").test(r)?this.setAudioItemBitrate(r,e):r)),this}setAudioBitrateWithMid(e,t){return v.info(L.L_RTC_SDP_BITRATE_O,{bitrate:e,mid:t,msg:"SDP setAudioBitrateWithMid"},{logSource:i.RTC}),this.audioStreams=this.audioStreams.map((r=>new RegExp(`\\bmid:${t}\\b`,"ig").test(r)?this.setAudioItemBitrate(r,e):r)),this}setAudioItemBitrate(e,t){if(0===t.max&&/\ba=inactive\b/gi.test(e))return e;if(!/\bmaxaveragebitrate\b/gi.test(e)){const r=["$1","maxaveragebitrate="+t.max*nr.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*nr.KBitrate}\r\nb=TIAS:${t.max*nr.KBitrate*850}`)}setVideosBitrate(e){return v.info(L.L_RTC_SDP_BITRATE_O,{bitrate:e,msg:"SDP setVideosBitrate"},{logSource:i.RTC}),this.videoStreams=this.videoStreams.map((t=>this.setVideoItemBitrate(t,e))),this}setVideoBitrateWithStreamId(e,t){return v.info(L.L_RTC_SDP_BITRATE_O,{bitrate:e,streamId:t,msg:"SDP setVideoBitrateWithStreamId"},{logSource:i.RTC}),this.videoStreams=this.videoStreams.map((r=>new RegExp(`\\bmsid:${t}\\b`,"ig").test(r)?this.setVideoItemBitrate(r,e):r)),this}setVideoBitrateWithMid(e,t){return v.info(L.L_RTC_SDP_BITRATE_O,{bitrate:e,mid:t,msg:"SDP setVideoBitrateWithMid"},{logSource:i.RTC}),this.videoStreams=this.videoStreams.map((r=>new RegExp(`\\bmid:${t}\\b`,"ig").test(r)?this.setVideoItemBitrate(r,e):r)),this}setVideoItemBitrate(e,t){if(0===t.max&&/\ba=inactive\b/gi.test(e))return e;if(!/\bx-google-max-bitrate\b/.test(e)){console.log("old:",e);const r=["$1","x-google-max-bitrate="+t.max*nr.KBitrate,"x-google-min-bitrate="+t.min*nr.KBitrate,`x-google-start-bitrate=${t.start||t.max*nr.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*nr.KBitrate}\r\nb=TIAS:${t.max*nr.KBitrate*850}`)}clearnSsrcWithMid(e,t){return v.info(L.L_RTC_SDP_BITRATE_O,{mid:e,msg:"SDP clearnSsrcWithMid"},{logSource:i.RTC}),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===cr.SENDONLY){if(/\ba=sendonly\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}if(t===cr.RECVONLY){if(/\ba=recvonly\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}if(t===cr.INACTIVE){if(/\ba=inactive\b/.test(e))return e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,"")}return e}}var ar,cr,dr,_r,ur,lr,hr,Rr,pr,mr,Cr,Tr,Ir,Er,Sr;nr.KBitrate=1,function(e){e.PLANB="plan-b",e.UNIFIEDPLAN="unified-plan"}(ar||(ar={})),function(e){e.SENDONLY="sendonly",e.RECVONLY="recvonly",e.INACTIVE="inactive"}(cr||(cr={}));class gr{constructor(e){this._peer=e,this._outboundStreams={}}static setSdpSemantics(e){r.info(L.L_A_SDP_STRATEGY_SET_SDP_SEMANTICS_O,{status:A.SUCCESSED,sdpSemantics:e},{logSource:i.RTC});const{browser:t,version:o,supportsUnifiedPlan:s}=Pt;r.debug(`sdpSemantics, browser: ${t}, version: ${o}, supportsUnifiedPlan: ${s}`),s?/chrome/i.test(t)?this._sdpSemantics=o>92?"unified-plan":o<72?"plan-b":e:/firefox/i.test(t)?this._sdpSemantics="unified-plan":/safari/i.test(t)?this._sdpSemantics=o<12?"plan-b":"unified-plan":this._sdpSemantics="unified-plan":this._sdpSemantics="plan-b"}static getSdpSemantics(){return gr._sdpSemantics}getOutboundVideoInfo(){const e=[];for(const t in this._outboundStreams){const r=this._outboundStreams[t].getVideoTracks()[0];if(!r)continue;const i=/_tiny$/.test(t),{width:o,height:s}=gt(r);e.push({trackId:r.id,simulcast:i?zt.TINY:zt.NORMAL,resolution:`${o}x${s}`})}return e}setRemoteAnswer(e){return f(this,void 0,void 0,(function*(){e=nr.trimBlankLine(e),r.info(`set remote answer -> ${e}`);try{yield this._peer.setRemoteDescription({type:"answer",sdp:e})}catch(e){return v.error(e),r.info(L.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:A.FAILED,code:"",msg:e},{logSource:i.RTC}),O.SET_REMOTE_DESCRIPTION_FAILED}return r.info(L.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:A.SUCCESSED,sdp:e},{logSource:i.RTC}),O.SUCCESS}))}getStatParsr(e,t,r){return/chrome/i.test(Pt.browser)?new ir(e,t,r):/Firefox/i.test(Pt.browser)?new or(e,t,r):/Safari/i.test(Pt.browser)?new sr(e,t,r):null}resetSdp(e){return nr.trimBlankLine(e)}}class fr extends nr{constructor(e){super(e,ar.PLANB),this.SDP=e}stringify(){const e=[this.SDPHeader];[...this.audioStreams,...this.videoStreams].forEach((t=>{const r=t.match(/\ba=mid:(video|audio)\b/),i=nr.clearInactiveOrRecvonly(t);r&&r[1]===Qe.AUDIO&&(e[1]=i),r&&r[1]===Qe.VIDEO&&(e[2]=i)}));const t=e.join("");return nr.trimBlankLine(t)}setAudioBitrateWithStreamId(e,t){return v.warn("plan-b not support set Audio Bitrate With Stream Id"),this}setVideoBitrateWithStreamId(e,t){return v.warn("plan-b not support set Video Bitrate With Stream Id"),this}}class vr extends gr{constructor(){super(...arguments),this.senders={},this._localTracks=[]}addLocalTrack(e){this._localTracks.includes(e)||this._localTracks.push(e);const t=e.getStreamId(),r=e.__innerGetMediaStreamTrack(),i=this._outboundStreams[t]||(this._outboundStreams[t]=new MediaStream);i.getTracks().forEach((e=>{e.kind===r.kind&&i.removeTrack(e)})),i.addTrack(r);const o=e.getTrackId(),s=this.senders[o];s?s.replaceTrack(r):this.senders[o]=this._peer.addTrack(r,i)}removeLocalTrack(e){const t=this._localTracks.findIndex((t=>t===e));t>=0&&this._localTracks.splice(t,1);const r=e.getTrackId(),i=this.senders[r];i&&(i.replaceTrack(null),this._peer.removeTrack(i),delete this.senders[r])}updateSubRemoteTracks(e){}updateRecvTransceiverMap(e,t){}setBitrate(e,t,r){this._maxBitrate=e,this._minBitrate=t,this._startBitrate=r||.7*e}createOffer(e){return f(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0});for(const e in this._outboundStreams){const r=this._outboundStreams[e].id;t.sdp=t.sdp.replace(new RegExp(r,"g"),e)}return t.sdp&&(t.sdp=nr.clearInactiveOrRecvonly(t.sdp)),yield this._peer.setLocalDescription(t),{type:"offer",semantics:"plan-b",sdp:t.sdp}}))}setRemoteAnswer(e){return e=this.resetSdp(e),super.setRemoteAnswer(e)}resetSdp(e){const t=new fr(e),r={max:0,min:0},i={max:0,min:0};return this._localTracks.forEach((e=>{const{min:t,max:o,start:s}=e.getBitrate();e.isAudioTrack()&&(i.max=i.max<o?o:i.max,i.min=i.min>t?t:i.min,i.max===o?i.start=s:i.start=.7*i.max),e.isVideoTrack()&&(r.max=r.max<o?o:r.max,r.min=r.min>t?t:r.min,r.max===o?r.start=s:r.start=.7*r.max)})),t.setAudiosBitrate(i),t.setVideosBitrate(r),t.stringify()}}class Or extends nr{constructor(e){super(e,ar.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 nr.trimBlankLine(t)}}class Lr{static splitSections(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))}static getMediaSections(e){const t=Lr.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=Lr.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 Lr.splitLines(e).filter((e=>0===e.indexOf(t)))}static parseMsid(e){let t;const r=Lr.matchPrefix(e,"a=msid:");if(1===r.length)return t=r[0].substr(7).split(" "),{stream:t[0],track:t[1]};const i=Lr.matchPrefix(e,"a=ssrc:").map((e=>Lr.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return i.length>0&&i[0].value?(t=i[0].value.split(" "),{stream:t[0],track:t[1]}):{stream:"",track:""}}static parseSsrcMedia(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r}static getMid(e){const t=Lr.matchPrefix(e,"a=mid:")[0];if(t)return t.substr(6)}}class Ar extends gr{constructor(){super(...arguments),this._sendTransceiver={},this._localTracks={},this._recvAudio=[],this._recvVideo=[],this._recvTransceiver={},this._subedTracks=[],this.midMsid={}}setBitrate(e,t,r){v.warn("the interface named `setBitrate` is invalid while sdpSemantics value is `unified-plan`")}addLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId(),i=e.__innerGetMediaStreamTrack();this._localTracks[t]=e;const o=this._outboundStreams[r]||(this._outboundStreams[r]=new MediaStream);o.getTracks().forEach((e=>{e.kind===i.kind&&o.removeTrack(e)})),o.addTrack(i);const s=this._sendTransceiver[t];s?(s.sender.replaceTrack(i),s.direction="sendonly"):this._sendTransceiver[t]=this._peer.addTransceiver(i,{direction:"sendonly",streams:[o]})}removeLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId();e.__innerGetMediaStreamTrack(),delete this._localTracks[t];const i=this._sendTransceiver[t];if(!i)return;i.direction="inactive",this._peer.removeTrack(i.sender),i.sender.replaceTrack(null);const o=this._outboundStreams[r];(e.isAudioTrack()?o.getAudioTracks():o.getVideoTracks()).forEach((e=>o.removeTrack(e)));const s=this._sendTransceiver[`${t}_tiny`];if(!s||"inactive"===s.direction)return;s.direction="inactive";const n=s.sender,a=n.track;this._peer.removeTrack(n),n.replaceTrack(null);this._outboundStreams[`${r}_tiny`].removeTrack(a),a.stop()}updateRecvTransceiverMap(e,t){const{mediaType:r}=Ot(e);this._recvTransceiver[e]=t;const i=r===He.AUDIO_ONLY?this._recvAudio:this._recvVideo,o=i.findIndex((e=>e===t));o>=0&&i.splice(o,1)}updateSubRemoteTracks(e){const t=e.slice(),r=this._subedTracks.slice();this._subedTracks=e.slice();for(let e=t.length-1;e>=0;e-=1){const i=t[e],o=r.findIndex((e=>e===i));o>=0&&(t.splice(e,1),r.splice(o,1))}r.length&&r.forEach((e=>{const t=e.getTrackId();e.__innerSetMediaStreamTrack(void 0);const r=this._recvTransceiver[t];r&&(r.direction="inactive")}));const i={audio:0,video:0};t.length&&t.forEach((e=>{const t=e.isAudioTrack()?"audio":"video",r=this._recvTransceiver[e.getTrackId()];r?r.direction="recvonly":i[t]+=1}));for(let e=this._recvAudio.length;e<i.audio;e+=1)this._recvAudio.push(this._peer.addTransceiver("audio",{direction:"recvonly"}));for(let e=this._recvVideo.length;e<i.video;e+=1)this._recvVideo.push(this._peer.addTransceiver("video",{direction:"recvonly"}))}createOffer(e){return f(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e});let r=t.sdp;for(const e in this._outboundStreams){const t=this._outboundStreams[e].id;r=r.replace(new RegExp(t,"g"),e)}return r=this.resetOfferSdp(r),r=r.replace(/(a=ice-options:trickle)/g,"$1\r\na=ice-options:renomination"),t.sdp=r,yield this._peer.setLocalDescription(t),{type:"offer",semantics:"unified-plan",sdp:r}}))}setRemoteAnswer(e){e=this.resetAnswerSdp(e);const t=/[\r\n]+\r\n[\r\n]+/g;return t.test(e)&&(v.warn(`answer sdp invalid -> ${JSON.stringify(e)}`),e=e.replace(t,"\r\n")),super.setRemoteAnswer(e)}resetOfferSdp(e){var t;const r=new Or(e);for(const i in this._sendTransceiver){const o=this._sendTransceiver[i],s=null===(t=o.sender.track)||void 0===t?void 0:t.kind;let{direction:n,mid:a}=o;if(!a){Lr.getMediaSections(e).forEach((e=>{Lr.parseExtmap(e);const{kind:t}=Lr.parseMLine(e);let{stream:r}=Lr.parseMsid(e);const o=Lr.getMid(e);"video"===s?/tiny$/.test(r)?r=r.replace(/tiny$/gi,"1_tiny"):r+="_1":r+="_0",r===i&&s===t&&o&&(a=o)}))}if(a){if(n===cr.SENDONLY){const e=this._localTracks[i],t=null==e?void 0:e.getBitrate();s===Qe.AUDIO&&t&&r.setAudioBitrateWithMid(t,a),s===Qe.VIDEO&&t&&r.setVideoBitrateWithMid(t,a)}n===cr.INACTIVE&&r.clearnSsrcWithMid(a,cr.INACTIVE)}}for(const e in this._recvTransceiver){const t=this._recvTransceiver[e],{direction:i,mid:o}=t;o&&(cr.RECVONLY,i===cr.INACTIVE&&r.clearnSsrcWithMid(o,cr.RECVONLY))}return r.stringify()}resetAnswerSdp(e){var t;const r=new Or(e);for(const e in this._sendTransceiver){const i=this._sendTransceiver[e],{mid:o}=i;if(o){const s=this._localTracks[e],n=null==s?void 0:s.getBitrate(),a=null===(t=i.sender.track)||void 0===t?void 0:t.kind;a===Qe.AUDIO&&n&&r.setAudioBitrateWithMid(n,o),a===Qe.VIDEO&&n&&r.setVideoBitrateWithMid(n,o)}}return r.stringify()}}class Nr extends t{constructor(e,t,r,i){super(),this._pcName=e,this._reTryExchange=t,this._currentUserId=r,this._polarisReport=i,this.pubLocalTracks={},this._reTryExchangeTimer=null,this._reportStatsTimer=null,this._reportR3R4ToPolarisTimer=null,this._isDestroyed=!1,this._reportListener=null;const o=gr.getSdpSemantics(),s=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:o});this._sdpStrategy="plan-b"===o?new vr(s):new Ar(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,o,this._currentUserId)}getName(){return this._pcName}getLocalTracks(){return r.info(L.L_RTC_PEER_CONNECTION_GET_LOCAL_TRACKS_O,{status:A.SUCCESSED,trackIds:Object.keys(this.pubLocalTracks)},{logSource:i.RTC}),Object.values(this.pubLocalTracks)}_onConnectionStateChange(){v.info(`onconnectionstatechange -> ${this._rtcPeerConn.connectionState}, ${this._pcName}`),r.info(L.L_RTC_PEER_CONNECTION_CONNECTION_STATE_S,{status:A.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:i.RTC})}_onICEConnectionStateChange(){var e,t;v.info(`oniceconnectionstatechange -> ${this._rtcPeerConn.iceConnectionState}, ${this._pcName}`),"connected"===this._rtcPeerConn.iceConnectionState&&(this._reportStatsTimer&&clearInterval(this._reportStatsTimer),this._reportStatsTimer=setInterval(this._reportHandle.bind(this),1e3)),"failed"!==this._rtcPeerConn.iceConnectionState&&"disconnected"!==this._rtcPeerConn.iceConnectionState||(v.warn(`${this._pcName} iceconenction state is failed, exchange SDP to try again.`),r.error(L.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:A.FAILED,code:"",msg:`${this._pcName} iceconenction state is failed, exchange SDP to try again.`},{logSource:i.RTC}),this._reTryExchange(),this._reTryExchangeTimer=setInterval(this._reTryExchange,15e3));try{null===(t=null===(e=this._reportListener)||void 0===e?void 0:e.onICEConnectionStateChange)||void 0===t||t.call(e,this._rtcPeerConn.iceConnectionState,this._pcName)}catch(e){v.error("onICEConnectionStateChange error",e,this._pcName),r.error(L.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:A.FAILED,code:"",msg:`${this._pcName}, ${e}`},{logSource:i.RTC})}r.info(L.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:A.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:i.RTC})}_onTrackReady(e){if(!e.streams.length)return;const t=[e.streams[0].id,"audio"===e.receiver.track.kind?He.AUDIO_ONLY:He.VIDEO_ONLY].join("_");this._updateRecvTransceiverMap(t,e.transceiver),this.emit(Nr.__INNER_EVENT_TRACK_READY__,e)}setBitrate(e,t,o){return f(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(e,t,o),r.info(L.L_RTC_PEER_CONNECTION_SET_BITRATE_O,{status:A.SUCCESSED,max:e,min:t,start:o},{logSource:i.RTC})}))}createOffer(e){return f(this,void 0,void 0,(function*(){const t=yield this._sdpStrategy.createOffer(e);return v.debug(`offer -> ${JSON.stringify(t.sdp)}`),r.info(L.L_RTC_PEER_CONNECTION_CREATE_OFFER_O,{status:A.SUCCESSED,offerSDP:t.sdp},{logSource:i.RTC}),t}))}setRemoteAnswer(e){return f(this,void 0,void 0,(function*(){return v.debug(`answer -> ${JSON.stringify(e)}`),r.info(L.L_RTC_PEER_CONNECTION_SET_REMOTE_ANSWER_O,{status:A.SUCCESSED,answer:e},{logSource:i.RTC}),this._sdpStrategy.setRemoteAnswer(e)}))}getLocalTrack(e){return this.pubLocalTracks[e]||null}addLocalTrack(e){this.pubLocalTracks[e.getTrackId()]=e,this._sdpStrategy.addLocalTrack(e),e.off(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.on(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.on(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),r.info(L.L_RTC_PEER_CONNECTION_ADD_LOCAL_TRACK_O,{status:A.SUCCESSED,trackId:e.getTrackId()},{logSource:i.RTC})}removeLocalTrackById(e){const t=this.getLocalTrack(e);t?(r.info(L.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:A.SUCCESSED,trackId:e},{logSource:i.RTC}),this.removeLocalTrack(t)):r.warn(L.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:A.FAILED,code:"",msg:"track not found"},{logSource:i.RTC})}removeAllLocalTrack(){Object.keys(this.pubLocalTracks).forEach((e=>{/_tiny$/.test(e)||this.removeLocalTrackById(e)})),r.info(L.L_RTC_PEER_CONNECTION_REMOVE_ALL_LOCAL_TRACK_O,{status:A.SUCCESSED},{logSource:i.RTC})}removeLocalTrack(e){const t=e.getTrackId();delete this.pubLocalTracks[t],this._sdpStrategy.removeLocalTrack(e),e.__innerSetPublished(!1),e.off(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this);const o=`${t}_tiny`,s=this.getLocalTrack(o);s&&(this._sdpStrategy.removeLocalTrack(s),delete this.pubLocalTracks[o],s.destroy()),r.info(L.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_O,{status:A.SUCCESSED,trackId:t},{logSource:i.RTC})}_updateRecvTransceiverMap(e,t){this._sdpStrategy.updateRecvTransceiverMap(e,t)}updateSubRemoteTracks(e){this._sdpStrategy.updateSubRemoteTracks(e),r.info(L.L_RTC_PEER_CONNECTION_UPDATE_SUB_REMOTE_TRACKS_O,{status:A.SUCCESSED,trackIds:e.map((e=>e.getTrackId()))},{logSource:i.RTC})}getOutboundVideoInfo(){return this._sdpStrategy.getOutboundVideoInfo()}_onLocalTrackMuted(e,t){const o=this.getLocalTrack(`${e.getTrackId()}_tiny`);o&&(o.__innerGetMediaStreamTrack().enabled=!e.isLocalMuted()),this.emit(ot.__INNER_EVENT_MUTED_CHANGE__,e,t),r.info(L.L_RTC_PEER_CONNECTION_LOCAL_TRACK_MUTED_O,{status:A.SUCCESSED,trackId:e.getTrackId()},{logSource:i.RTC})}_onLocalTrackDestroied(e){this.emit(ot.__INNER_EVENT_DESTROY__,e)}registerReportListener(e){this._reportListener=e}_createRCRTCStateReport(e){const{timestamp:t,iceCandidatePair:r,senders:i,receivers:o}=JSON.parse(JSON.stringify(e));null==r||delete r.totalPacketsLost;for(const e in r)wt(r[e])&&delete r[e];return{timestamp:t,iceCandidatePair:r,senders:i.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),receivers: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})),pcName:this._pcName}}_getStatsData(){var e,t;return f(this,void 0,void 0,(function*(){const r=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(r);return null===(t=this.reportParser)||void 0===t?void 0:t.formatRCRTCStateReport(i)}))}getAudioLevelReportData(){var e,t;return f(this,void 0,void 0,(function*(){const r=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(r);if(!i)return[];return null===(t=this.reportParser)||void 0===t?void 0:t.getAudioLevelList(i)}))}_reportHandle(){var e,t;return f(this,void 0,void 0,(function*(){const r=yield this._getStatsData();if(!r)return;const i=this._createRCRTCStateReport(r);null===(t=null===(e=this._reportListener)||void 0===e?void 0:e.onStateReport)||void 0===t||t.call(e,i)}))}_sendR3R4Data(){var e;return f(this,void 0,void 0,(function*(){const t=yield this._getStatsData();return!t||(t.senders.length||t.receivers.length?yield null===(e=this._polarisReport)||void 0===e?void 0:e.sendR3R4Data(t):void 0)}))}__reportR3R4ToPolaris(){return f(this,void 0,void 0,(function*(){clearTimeout(this._reportR3R4ToPolarisTimer),yield this._sendR3R4Data(),this._reportR3R4ToPolarisTimer=setTimeout(this.__reportR3R4ToPolaris.bind(this),2e3)}))}getRTCPeerConn(){return this._rtcPeerConn}destroy(){this.clear(),this.clearReTryExchangeTimer(),clearTimeout(this._reportR3R4ToPolarisTimer),this._reportStatsTimer&&(clearInterval(this._reportStatsTimer),this._reportStatsTimer=null),this.registerReportListener(null),this._rtcPeerConn.close(),this._isDestroyed=!0,this.reportParser=null,r.info(L.L_RTC_PEER_CONNECTION_DESTROY_O,{status:A.SUCCESSED},{logSource:i.RTC})}clearReTryExchangeTimer(){clearInterval(this._reTryExchangeTimer),this._reTryExchangeTimer=null}isDestroyed(){return this._isDestroyed}}Nr.__INNER_EVENT_TRACK_READY__="inner-track-ready",function(e){e[e.DISABLE=0]="DISABLE",e[e.ENABLE=1]="ENABLE"}(dr||(dr={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(_r||(_r={}));class Dr{constructor(e,t,r,i,o=_r.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=i,this._userRole=o}_send(e){return f(this,void 0,void 0,(function*(){let t=!1;if(this._context.getConnectionStatus()!==u.CONNECTED)return t;return t=(yield this._context.setRTCState(this._roomId,e))===a.SUCCESS,t}))}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=Dt(),this._runtime.localStorage.setItem(e,t)),t}_getRealResourceId(e){let t=e;const r=e.indexOf("_tiny");return r>-1&&(t=e.slice(0,r)),t}_getPolarisTrackId(e){let t="";const r=e.split("_");if(e.includes("_tiny")){const e=r.pop(),i=parseInt(r.pop())===He.AUDIO_ONLY?"audio":"video",o=r.pop();t=[r.join("_"),o,e,i].join("_")}else{const e=parseInt(r.pop())===He.AUDIO_ONLY?"audio":"video",i=r.pop();t=[r.join("_"),i,e].join("_")}return t}sendR3R4Data(e){return f(this,void 0,void 0,(function*(){const{iceCandidatePair:t,senders:r,receivers:i}=e,o=(null==t?void 0:t.bitrateSend)||-1,s=(null==t?void 0:t.bitrateRecv)||-1,n=(null==t?void 0:t.networkType)||"unknown",a=(null==t?void 0:t.rtt)||-1,c=`${(null==t?void 0:t.IP)||-1}:${null==t?void 0:t.port}`,d=(null==t||t.remoteIP,null==t||t.remotePort,(null==t?void 0:t.availableIncomingBitrate)||-1),_=(null==t?void 0:t.availableOutgoingBitrate)||-1,u=(null==t?void 0:t.totalPacketsLost)||-1,l=this._context.getCurrentId();let h=`R3\t${o}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${_}\t${u}\t${l}\r`,R=`R4\t${s}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${_}\t${u}\t${l}\r`;const p=r.map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:o,bitrate:s,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:_,jitter:u,nackCount:l,pliCount:h,rtt:R,googFirsSent:p,encoderImplementation:m}=e,C=this._getPolarisTrackId(r),T=this._getRealResourceId(r);return{trackId:C,googCodecName:m||String(-1),audioLevel:i||0===i?i:-1,bitrate:s||0===s?s:-1,packetsLostRate:n||0===n?n:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:h||0===h?h:-1,rtt:R||-1,googFirsSent:p,samplingRate:o,googRenderDelayMs:_,encoderImplementation:m||String(-1),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(T))||void 0===t?void 0:t.isLocalMuted())?dr.DISABLE:dr.ENABLE}})),m=i.filter((e=>!!e.trackId)).map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:o,bitrate:s,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:_,jitter:u,nackCount:l,pliCount:h,rtt:R,googFirsReceived:p,codecImplementationName:m}=e,C=this._getPolarisTrackId(r),T=this._getRealResourceId(r);return{trackId:C,googCodecName:m||String(-1),audioLevel:i||0===i?i:-1,bitrate:s||0===s?s:-1,packetsLostRate:n||0===n?n:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:h||0===h?h:-1,rtt:R||-1,googFirsReceived:p,samplingRate:o,googRenderDelayMs:_,codecImplementationName:m||String(-1),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(T))||void 0===t?void 0:t.isLocalMuted())?dr.DISABLE:dr.ENABLE}}));let C=!1;h+=p.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsSent}\t${e.encoderImplementation}\t${e.trackState}`)).join("\n"),e.senders.length&&(C=yield this._send(h+`\r${this._userRole}`));let T=!1;return R+=m.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsReceived}\t${e.codecImplementationName}\t${e.trackState}`)).join("\n"),e.receivers.length&&(T=yield this._send(R+`\r${this._userRole}`)),!(!C&&!T)}))}sendR1(){const e=`R1\t5.5.6\t${this._context.getCoreVersion()}\tweb\t${navigator.platform}\t-1\t${Pt.browser}\t${Pt.version}\t${this._getClientID()}\t${this._userRole}`;this._send(e)}sendR2(e,t,r){const i=`R2\t${e}\t${t}\t${this._getClientID()}\r${r.join("\t")}\r${this._userRole}`;this._send(i)}}class kr{constructor(e){this._room=e,this._audioLevelChangeHandler=null,this._timer=null}_audioLevelReport(){return f(this,void 0,void 0,(function*(){if(!this._audioLevelChangeHandler)return;const e=[],t=this._room.__getPC();for(let r=0;r<t.length;r++){const i=t[r];if("new"===i.getRTCPeerConn().iceConnectionState)return;const o=(yield i.getAudioLevelReportData()).map((e=>{const{userId:t}=Ot(e.trackId);return{track:this._room.getCrtUserId()===t?this._room.getLocalTrack(e.trackId):this._room.getRemoteTrack(e.trackId),audioLevel:e.audioLevel||0}})).filter((e=>e.track));e.push(...o)}this._audioLevelChangeHandler(e)}))}onAudioLevelChange(e,t){t<300||t>1e3?v.error('the valid range of onAudioLevelChange params "gap" is: > 300 && < 1000'):e?(this._audioLevelChangeHandler=e,this._timer=setInterval(this._audioLevelReport.bind(this),t)):this._audioLevelChangeHandler=null}clearAudioLevelReportTimer(){this._timer&&(clearInterval(this._timer),this._timer=null)}}!function(e){e[e.ANCHOR=1]="ANCHOR",e[e.AUDIENCE=2]="AUDIENCE"}(ur||(ur={}));class yr{constructor(e=!1,t,r,i,o){this._useMutilPeerC=e,this._roomId=t,this._reTryExchange=r,this._currentUserId=i,this._polarisReport=o,this._mutilPeerC={}}get useMutilPeerC(){return this._useMutilPeerC}_isPub(e){if(!e.length)return!1;const{track:t}=e[0]instanceof ot||e[0]instanceof Rt?{track:e[0]}:e[0];return t.isLocalTrack()}_groupTracksByTag(e){const t={};return e.map((e=>{const{track:r}=e instanceof ot?{track:e}:e,i=r.getTag();t[i]?t[i].push(e):t[i]=[e]})),t}_genPCName(e,t){let r=null;return r=e?this._useMutilPeerC?`${this._roomId}_${t}`:`${this._roomId}_pub`:`${this._roomId}_sub`,r}_createOnePeerCItem(e,t){if(this._mutilPeerC[e]&&!this._mutilPeerC[e].pc.isDestroyed())this._mutilPeerC[e].tracks=t;else{const r=this._isPub(t),i=new Nr(e,(()=>this._reTryExchange(e,r)),this._currentUserId,this._polarisReport);this._mutilPeerC[e]={pc:i,tracks:t,isPub:r}}return Object.assign({},this._mutilPeerC[e],{pcName:e})}createPeerCList(e){const t=[],r=this._isPub(e);if(!this._useMutilPeerC){const r=this._genPCName(!0);return t.push(this._createOnePeerCItem(r,e)),t}if(this._useMutilPeerC&&!r){const r=this._genPCName(!1);return t.push(this._createOnePeerCItem(r,e)),t}const i=this._groupTracksByTag(e);for(const e in i){const o=this._genPCName(r,e),s=i[e];t.push(this._createOnePeerCItem(o,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}=Ot(e),i=this._genPCName(t,r);return this._mutilPeerC[i].pc}getPCList(){const e=[];for(const t in this._mutilPeerC)e.push(this._mutilPeerC[t].pc);return e}getMutilPeerCData(){return this._mutilPeerC}setPeerCData(e,t,r){}clear(){this._removeAllLocalTrack(),this._destroyAllPeerC()}}!function(e){e[e.Unknow=0]="Unknow",e[e.Publish=1]="Publish",e[e.UnPublish=2]="UnPublish",e[e.JoinRoom=3]="JoinRoom",e[e.LeaveRoom=4]="LeaveRoom",e[e.UpdateSubscribeTask=5]="UpdateSubscribeTask",e[e.SubscribedTask=6]="SubscribedTask",e[e.UnSubscribedTask=7]="UnSubscribedTask",e.AsyncCommand="AsyncCommand"}(lr||(lr={})),function(e){e.NORMAL="normal",e.MIDDLE="middle",e.TAIL="tail"}(hr||(hr={})),function(e){e[e.LOW=0]="LOW",e[e.NORMAL=1]="NORMAL",e[e.HIGH=2]="HIGH"}(Rr||(Rr={})),function(e){e[e.Destroy=40400]="Destroy"}(pr||(pr={}));class br{get priority(){return Rr.LOW}get kind(){return lr.Unknow}}class Ur extends br{constructor(e=hr.NORMAL){super(),this.state=e}get kind(){return lr.AsyncCommand}setState(e){this.state=e}pickoutSubscribed(e,t){const{unsubscribe:r,subscribe:i}=this.calcSubscribeList(e,t);return Ur.AsyncSubscribeTasks=[],Ur.AsyncUnsubscribeTasks=[],Ur.AsyncUpdateSubscribeTasks=[],{subscribe:i,unsubscribe:r}}calcSubscribeList(e,t){const r=[],i=new Set,o=[],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)||i.has(t)||(r.push(e),i.add(t))})),n.forEach((e=>{const t=`${e.track.getTrackId()}_SUB_${e.subTiny?"0":"1"}`;this.trackInSubscribeList(e,a)||s.has(t)||(o.push(e),s.add(t))})),{unsubscribe:r,subscribe:o}}formateTrack(e){return e.map((e=>e instanceof Rt?{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}}Ur.AsyncSubscribeTasks=[],Ur.AsyncUnsubscribeTasks=[],Ur.AsyncUpdateSubscribeTasks=[];class Pr{constructor(e,t,r,i,o,s,n,a,c){this.context=e,this.service=t,this.peerMgr=r,this.roomId=i,this.crtUserId=o,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 i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getRemoteTracks(){return this._remoteTracks}getSessionId(){return this._sessionId}getAllUserIds(){return Object.keys(this._roomResources)}getRemoteUserIds(){return this.getAllUserIds().filter((e=>e!==this.crtUserId))}getSubscribedList(){return this._subscribedList}getCollectSubscribeList(){return this._collectSubscribeList}getPublishedResourceByTrackId(e){const{userId:t}=Ot(e);return this._roomResources[t].find((t=>vt(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}}class Mr extends Pr{_initRemoteTracks(){for(const e in this._roomResources){const t=this._roomResources[e];e!==this.crtUserId&&0!==t.length&&t.forEach((e=>{const t=vt(e),{tag:r,userId:i,mediaType:o}=Ot(t),s=o===He.AUDIO_ONLY?new pt(r,i):new mt(r,i);s.__innerSetRemoteMuted(0===e.state),this._remoteTracks[t]=s}))}}initWithRoomData(e){this._sessionId=e.sessionId,this._token=e.token,this.isUpgrade?this._roomResources={}:this._roomResources=Vt(e,this.roomId),this._initRemoteTracks(),this.setResourcesByUserId(this.crtUserId,this.getResourcesByUserId(this.crtUserId)||[]),v.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 xr{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 f(this,void 0,void 0,(function*(){if(this._isDestroyed||this._busy||0===this._queue.length)return;this._busy=!0;const{command:e,resolve:t,reject:r}=this._queue.shift();let i;try{i=yield e.execute(this._store,this)}catch(e){return r(e),void this._next()}t(i),this._next()}))}push(e){return new Promise(((t,r)=>{if(this._isDestroyed)return;const i=e.kind;this._queue.length>0&&i===lr.AsyncCommand&&({command:e,resolve:t,reject:r}=this.commandOffset(e,t,r));const o=e.priority;if(o===Rr.LOW)this._queue.push({command:e,resolve:t,reject:r});else{const i=this._queue.findIndex((e=>e.command.priority<o)),s=-1===i?this._queue.length-1:i;this._queue.splice(s,0,{command:e,resolve:t,reject:r})}Promise.resolve().then((()=>{this._execute()}))}))}commandOffset(e,t,r){const i=this._queue.length-1;if(!(this._queue[i].command.kind===lr.AsyncCommand))return{command:e,resolve:t,reject:r};const[o]=this._queue.splice(i,1);o.command instanceof Ur&&(o.command.setState(hr.MIDDLE),e instanceof Ur&&e.setState(hr.TAIL));const s=e.execute;return e.execute=function(t,r){return f(this,void 0,void 0,(function*(){return o.command.execute.call(o.command,t,r),s.call(e,t,r)}))},{command:e,resolve:e=>{o.resolve.call(o,e),t(e)},reject:e=>{o.reject.call(o,e),r(e)}}}isDestroyed(){return this._isDestroyed}destroy(){this._isDestroyed||(this._isDestroyed=!0,this._queue.forEach((e=>{e.resolve({code:this.abortCode})})),this._queue.length=0)}}class wr extends xr{constructor(e,t,r,i,o,s,n,a,c){super(new Mr(e,t,r,i,o,s,n,a,c),O.ROOM_HAS_BEEN_DESTROYED)}get store(){return this._store}destroy(){super.destroy(),this._store.removeRemoteTracks()}}class Br extends br{execute(e){return f(this,void 0,void 0,(function*(){const t=e.getResourcesByUserId(e.crtUserId),r=t.slice();t.length=0,v.info(`unpublish uris before rejoin -> ${JSON.stringify(r)}`);const i=yield e.context.setRTCTotalRes(e.roomId,Ct(Gt.UNPUBLISH,r),Tt([]),Gt.TOTAL_CONTENT_RESOURCE,Tt([]));i!==a.SUCCESS?v.error(`unpublish uris before rejoin failed -> code: ${i}`):v.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"}(mr||(mr={})),function(e){e[e.KICK=0]="KICK",e[e.REFUSE=1]="REFUSE",e[e.COEXIST=2]="COEXIST"}(Cr||(Cr={}));class Vr extends br{constructor(e,t,r,i,o,s){super(),this.roomId=e,this.roomType=t,this.joinType=r,this.livingType=i,this.innerUserDatas=o,this.outerUserDatas=s}get kind(){return lr.JoinRoom}execute(e,t){var o;return f(this,void 0,void 0,(function*(){const{context:c,service:d}=e;let _=L.L_RTC_CLIENT_JOIN_RTC_ROOM_R;if(this.roomType===mr.LIVE?_=L.L_RTC_CLIENT_JOIN_LIVING_ROOM_R:this.roomType===mr.CROSS_MUTI&&(_=L.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_R),c.getConnectionStatus()!==u.CONNECTED)return r.error(_,{status:A.FAILED,code:O.SIGNAL_DISCONNECTED,msg:"im not connected"},{logSource:i.RTC}),{code:O.SIGNAL_DISCONNECTED};if(d.detectorMediaSever(),Bt(c.getNaviInfo()))return r.error(_,{status:A.FAILED,code:O.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_usl error"},{logSource:i.RTC}),{code:O.PACKAGE_ENVIRONMENT_ERROR};if(!s("roomId",this.roomId,R,!0))return r.error(_,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(!s("roomType",this.roomType,(e=>void 0!==mr[e])))return r.error(_,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> roomType"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(!s("outerUserDatas",this.outerUserDatas,n,!1))return r.error(_,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(this.outerUserDatas){if(!Object.keys(this.outerUserDatas).every((e=>s(`outerUserDatas.${e}`,this.outerUserDatas[e],p,!0))))return r.error(_,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:i.RTC}),{code:O.PARAMS_ERROR}}if(!d.getNaviMS().length)return r.error(_,{status:A.FAILED,code:O.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:i.RTC}),{code:O.NOT_OPEN_VIDEO_AUDIO_SERVER};v.info(`joinRoom -> roomId: ${this.roomId}; joinType: ${this.joinType||Cr.KICK}`);const{code:l,data:h}=yield c.joinRTCRoom(this.roomId,this.roomType,this.livingType,this.joinType,this.innerUserDatas,this.outerUserDatas);if(l!==a.SUCCESS||!h){v.warn(`joinRoom failed -> code: ${l}`);const e=40032===l?O.SIGNAL_JOIN_RTC_ROOM_REFUSED:l;return r.error(_,{status:A.FAILED,code:e,msg:`joinRoom failed -> code: ${l}`},{logSource:i.RTC}),{code:e}}v.info(`joinRoom success -> userId: ${c.getCurrentId()}, roomId: ${this.roomId}, data: ${JSON.stringify(h)}`),e.initWithRoomData(h);e.getResourcesByUserId(e.crtUserId).length>0&&t.push(new Br);const m=null===(o=h.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===o?void 0:o.value;return m&&e.setCDNUris(JSON.parse(m)[0]),r.info(_,{status:A.SUCCESSED,userId:e.crtUserId,roomId:this.roomId,data:h},{logSource:i.RTC}),{code:O.SUCCESS,data:h}}))}}function $r(e,t,r,i){return f(this,void 0,void 0,(function*(){return{sdp:yield r.createOffer(t),extend:JSON.stringify({resolutionInfo:r.getOutboundVideoInfo()}),subscribeList:e.filter((e=>{const t=e.track.getTrackId(),{userId:r}=Ot(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?zt.TINY:zt.NORMAL,resolution:"",uri:i.getPublishedResourceByTrackId(e.track.getTrackId()).uri}))),switchstream:!1}}))}function Fr(e,t,r){return f(this,void 0,void 0,(function*(){const i=yield e.setRTCCDNUris(t,Gt.TOTAL_CONTENT_RESOURCE,JSON.stringify([r]));return i!==a.SUCCESS?(v.error(`spreadCDNInfo failed -> code: ${i}`),{code:O.SIGNAL_ERROR}):(v.info("spreadCDNInfo succeed"),{code:O.SUCCESS})}))}function Gr(e,t,r){return f(this,void 0,void 0,(function*(){const i=yield e.setRTCData(t,"cdn_uris",JSON.stringify([r]),!0,Sr.ROOM);return i!==a.SUCCESS?(v.error(`setRoomCDNInfo failed -> code: ${i}`),{code:O.SIGNAL_ERROR}):(v.info("setRoomCDNInfo succeed"),{code:O.SUCCESS})}))}function Kr(e){return f(this,void 0,void 0,(function*(){const t=e.context,o=e.roomId,s=Object.assign({},e.getCDNUris(),{enableInnerCDN:e.getCDNEnable()});r.info(L.L_LIVING_ROOM_SPREAD_CDN_INFO_T,{roomId:o,CDNUris:s},{logSource:i.RTC});const n=(yield Promise.all([Fr(t,o,s),Gr(t,o,s)])).every((e=>e.code===O.SUCCESS));return n?r.info(L.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:A.SUCCESSED,CDNUris:s},{logSource:i.RTC}):r.error(L.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:A.FAILED,code:O.SIGNAL_ERROR,msg:"signal error"},{logSource:i.RTC}),n?{code:O.SUCCESS}:{code:O.SIGNAL_ERROR}}))}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(Tr||(Tr={})),function(e){e.BEGIN="begin",e.END="end"}(Ir||(Ir={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(Er||(Er={})),function(e){e[e.ROOM=1]="ROOM",e[e.PERSON=2]="PERSON"}(Sr||(Sr={}));class Hr extends br{constructor(e,t){super(),this.headers=e,this.reqBody=t}execute(e,t){var r,i;return f(this,void 0,void 0,(function*(){const t=yield e.service.exchange(this.headers,this.reqBody);if(e.roomMode!==mr.LIVE)return t;const o=null===(i=null===(r=t.data)||void 0===r?void 0:r.urls)||void 0===i?void 0:i.pull_url;if(t.code!==O.SUCCESS||!o)return t;const s=JSON.parse(o);if(e.setCDNUris(s),(null==s?void 0:s.broadcast)===Er.SPREAD){e.setCDNEnabel(!0);const t=Object.assign({},s,{enableInnerCDN:!0});Gr(e.context,e.roomId,t)}return t}))}}class jr extends br{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(e,t){return f(this,void 0,void 0,(function*(){const{tracks:r,forceReq:i}=this,o=e.roomId;if(!s("tracks",r,(()=>d(r)&&r.every((e=>e instanceof Rt||e.track instanceof Rt))),!0))return v.warn(`update sublist failed, tracks is invalid -> roomId: ${o}`),{code:O.PARAMS_ERROR};v.info(`update subscribe list -> roomId: ${o}, forceReq: ${i}, tracks: ${r.map($t)}`);let n=r.map((e=>e instanceof Rt?{track:e}:Object.assign({},e)));const a={};n=n.filter((t=>{const r=t.track.getTrackId();return e.getRemoteTrack(r)?!a[r]&&(a[r]=!0):(v.warn(`track cannot found in room -> trackId: ${r}`),!1)})).map((e=>Object.assign({},e)));const c=e.getSubscribedList().map((e=>Object.assign({},e)));if(!i){let e=!1;if(n.forEach((t=>{const r=c.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);c.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),c.length&&(e=!0),!e)return{code:O.SUCCESS}}const{pc:_,pushOtherRooms:u,headers:l}=this.subhook(r);_.updateSubRemoteTracks(n.map((e=>e.track)));const h=yield $r(n,!1,_,e);u&&(h.pushOtherRooms=u);const R=yield new Hr(l,h).execute(e,t),p=n.map((e=>e.track.getTrackId()));if(R.code!==O.SUCCESS)return{code:R.code};const{sdp:m,resultCode:C,message:T,subscribedList:I}=R.data;if(C!==O.SUCCESS)return v.error(`change subscribe list failed: ${C}`),{code:C};v.debug(`subscribe success: ${p.join(",")}`);const E=yield _.setRemoteAnswer(m.sdp);if(E!==O.SUCCESS)return{code:E};const S=null==I?void 0:I.map((e=>`${e.msid}_${e.mediaType}`)),g=n.filter((e=>null==S?void 0:S.includes(e.track.getTrackId()))),f=n.filter((e=>!(null==S?void 0:S.includes(e.track.getTrackId())))),L=e.getRemoteTracks();for(const e in L){const t=g.some((t=>t.track.getTrackId()===e));L[e].__innerSetSubscribed(t);const r=g.some((t=>t.track.getTrackId()===e&&t.subTiny));L[e].isVideoTrack()&&L[e].__innerSetIsTinyTrack(r)}return e.resetSubscribedList(g),f.length?{code:O.SUCCESS,failedList:f}:{code:O.SUCCESS}}))}}class Jr extends br{constructor(e,t){super(),this.tracks=e,this.subhook=t}execute(e,t){return f(this,void 0,void 0,(function*(){const o=this.tracks,n=e.roomId;if(r.info(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:o.map($t)},{logSource:i.RTC}),!s("tracks",o,(()=>d(o)&&o.length>0&&o.every((e=>e instanceof Rt))),!0))return v.warn(`unsubscribe failed, tracks is invalid -> roomId: ${n}`),r.warn(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};v.info(`unsubscribe -> roomId: ${n}, tracks: ${o.map($t)}`);const a=e.getSubscribedList().map((e=>Object.assign({},e))).filter((e=>!o.includes(e.track)));return e.polarisReport.sendR2(Tr.SUBSCRIBE,Ir.END,o.map((e=>e.getTrackId()))),r.info(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:o.map($t),roomId:n},{logSource:i.RTC}),new jr(a,this.subhook,!1).execute(e,t)}))}}class Wr extends br{constructor(e,t){super(),this.msgContent=e,this.subhook=t}get priority(){return Rr.NORMAL}execute(e,t){return f(this,void 0,void 0,(function*(){const r=[],i=[],o=[],s=[],n={joined:r,left:i,upgrade:o,downgrade:s},{users:a}=this.msgContent;if(0===a.length)return n;for(let t=0;t<a.length;t++){const r=a[t];if(r.extra&&r.extra.roomId!==e.roomId)return n;if(1==+r.state&&!e.getRemoteUserIds().includes(r.userId))return n}a.forEach((t=>{const n=t.userId;if(0==+t.state){v.debug(`user joined -> ${n}`);const i=e.getResourcesByUserId(n);i||(t.switchRoleType?o.push(n):r.push(n)),e.setResourcesByUserId(n,i||[])}else v.debug(`user left -> ${n}`),t.switchRoleType?s.push(n):i.push(n)}));const c=[...i,...s];if(c.length){const r=[],i=[];c.forEach((t=>{r.push(...e.getRemoteTracksByUserId(t)),i.push(t)})),r.length&&(yield new Jr(r,this.subhook).execute(e,t),r.forEach((t=>e.removeRemoteTrack(t.getTrackId())))),i.length&&i.forEach((t=>e.removeResourcesByUserId(t)))}return n}))}}class qr extends br{constructor(e,t,r){super(),this.subhook=e,this.tracks=t,this.onTrackUnpublish=r}execute(e,t){return f(this,void 0,void 0,(function*(){const r=this.tracks;yield new Jr(r,this.subhook).execute(e,t),r.forEach((t=>{t.__innerDestroy(),e.removeRemoteTrack(t.getTrackId())})),this.onTrackUnpublish(r)}))}}class Yr extends br{constructor(e,t,r,i,o){super(),this.msgContent=e,this.messageType=t,this.senderId=r,this.subhook=i,this.callback=o}get priority(){return Rr.NORMAL}execute(e,t){var r,i;return f(this,void 0,void 0,(function*(){const{uris:o}=this.msgContent,s=[],n=[],a=[];let c;const d=this.senderId,_=this.messageType,u=e.getResourcesByUserId(d)||[];switch(e.setResourcesByUserId(d,u),_){case Gt.MODIFY:a.push(...o);break;case Gt.PUBLISH:s.push(...o);break;case Gt.UNPUBLISH:n.push(...o);break;case Gt.TOTAL_CONTENT_RESOURCE:c=Nt(u,o),s.push(...c.publishedList),n.push(...c.unpublishedList),a.push(...c.modifiedList)}if(s.length>0){const r=u.map(vt),i=[],o=[];if(s.forEach((t=>{const s=vt(t),n=r.indexOf(s),{userId:a,tag:c,mediaType:d}=Ot(s);n>-1?u[n]=t:u.push(t);let _=e.getRemoteTrack(s);_?_.isSubscribed()&&i.push(_):(_=d===He.AUDIO_ONLY?new pt(c,a):new mt(c,a),e.addRemoteTrack(_),o.push(_)),_.__innerSetRemoteMuted(0===t.state)})),i.length){const r=i.map((e=>e.getTrackId()));v.debug(`resub tracks -> ${JSON.stringify(r)}`);const{code:o}=yield new jr(i,this.subhook).execute(e,t);o!==O.SUCCESS&&v.error(`resub tracks failed -> code: ${o}, ids: ${JSON.stringify(r)}`)}this.callback.onTrackPublish(o)}if(n.length>0){const r=n.map(vt);for(let e=u.length-1;e>=0;e-=1){const t=u[e];r.includes(vt(t))&&u.splice(e,1)}const i=n.map((t=>{const r=vt(t);return e.getRemoteTrack(r)}));yield new qr(this.subhook,i,this.callback.onTrackUnublish).execute(e,t)}if(a.length>0){const t=u.map(vt);for(let r=0;r<a.length;r+=1){const i=a[r],o=vt(i),s=t.indexOf(o);u[s].state=i.state;const n=e.getRemoteTrack(o);n.__innerSetRemoteMuted(0===i.state),n.isAudioTrack()?this.callback.onAudioMute(n):this.callback.onVideoMute(n)}}if(e.roomMode!==mr.LIVE)return;const l=this.msgContent;if(!l.cdn_uris)return;const h=(null===(r=e.getCDNUris())||void 0===r?void 0:r.enableInnerCDN)!==l.cdn_uris[0].enableInnerCDN;e.setCDNUris(l.cdn_uris[0]),h&&this.callback.onCDNEnableChange(!!(null===(i=e.getCDNUris())||void 0===i?void 0:i.enableInnerCDN))}))}}class zr extends br{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(e,t){return f(this,void 0,void 0,(function*(){const{tracks:o,forceReq:n}=this,a=e.roomId;if(r.info(L.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:o.map($t),forceReq:n},{logSource:i.RTC}),!s("tracks",o,(()=>d(o)&&o.length>0&&o.every((e=>e instanceof Rt||e.track instanceof Rt))),!0))return v.warn(`subscribe failed, tracks is invalid -> roomId: ${a}`),r.error(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};v.info(`subscribe -> roomId: ${a}, tracks: ${o.map($t)}`);const c=e.getSubscribedList().map((e=>Object.assign({},e))),_=o.map((e=>e instanceof Rt?{track:e}:e));let u=!1;const l=[];return _.forEach((e=>{const t=e.track.getTrackId();l.push(t);const r=c.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:c.push(e),u=!0)})),u||n?(e.polarisReport.sendR2(Tr.SUBSCRIBE,Ir.BEGIN,l),r.info(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:o.map($t),roomId:a},{logSource:i.RTC}),new jr(c,this.subhook,!0).execute(e,t)):(r.warn(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:"",msg:"repeat subscribe"},{logSource:i.RTC}),{code:O.SUCCESS})}))}}class Qr extends br{constructor(e,t){super(),this.tracks=e,this.pubhook=t}get kind(){return lr.Publish}_removePubFailedTracks(e,t){e.forEach((e=>{const r=e instanceof ot?e:e.track;v.debug(`remove pub failed track from peerconnection -> trackId: ${r.getTrackId()}`),t.removeLocalTrackById(r.getTrackId())}))}__publish(e,t,r,i,o){return f(this,void 0,void 0,(function*(){const{pcName:s,pc:n,headers:a}=t,c=e.roomId,d=[];r.forEach((e=>{const{track:t}=e instanceof ot?{track:e}:e;d.push(t)})),r.sort(((e,t)=>{const{track:r}=e instanceof ot?{track:e}:e,{max:i}=r.getBitrate(),{track:o}=t instanceof ot?{track:t}:t,{max:s}=o.getBitrate();return i-s}));if(n.getLocalTracks().length+((e,t)=>{let r=0;return e.forEach((e=>{const i=e instanceof ot?e.getTrackId():e.track.getTrackId();t.getLocalTrack(i)||(e instanceof ot?r++:e.pubTiny&&e.track.isVideoTrack()&&(r+=2))})),r})(r,n)>10)return v.error(`publish failed, tracks limit exceeded -> roomId: ${c}`),{code:O.PUBLISH_TRACK_LIMIT_EXCEEDED,tracks:d};v.debug(`publish tracks -> roomId: ${c}, tracks: ${r.map($t)}`);for(let e=0;e<r.length;e++){const t=r[e],{track:i,pubTiny:o}=t instanceof ot?{pubTiny:!1,track:t}:t;if(i.isVideoTrack()&&o){let e;try{e=i.__innerGetMediaStreamTrack().clone();const t=o.frameRate||Ge.FPS_15,r=o.resolution||Ke.W176_H144,{width:s,height:n}=kt(r),a=Ut(t);yield e.applyConstraints({width:s,height:n,frameRate:a})}catch(t){null==e||e.stop(),v.warn(`pubTiny failed -> id: ${i.getTrackId()}, msg: ${t.message}`);break}n.addLocalTrack(new nt(i.getTag(),i.getUserId(),e,!0))}n.addLocalTrack(i)}n.clearReTryExchangeTimer();const _=e.useMutilPeerC?[]:e.getSubscribedList(),u=yield $r(_,!1,n,e);i&&(u.pushOtherRooms=i);const l=yield new Hr(a,u).execute(e,o);if(l.code!==O.SUCCESS)return v.error(`publish failed -> roomId: ${c}, code: ${l.code}`),this._removePubFailedTracks(r,n),{code:l.code,tracks:d};const{sdp:h,resultCode:R,message:p}=l.data;if(R!==O.SUCCESS)return v.error(`publish failed -> roomId: ${c}, code: ${R}, msg: ${p}`),this._removePubFailedTracks(r,n),{code:R,tracks:d};const m=yield n.setRemoteAnswer(h.sdp);return m!==O.SUCCESS?{code:m,tracks:d}:Object.assign({},l,{tracks:d})}))}_mergePublishRes(e,t){return f(this,void 0,void 0,(function*(){const r=t.crtUserId,i=t.roomId;let o="";const s=[],n=t.getResourcesByUserId(r),c=[...n];let d=[];e.forEach((e=>{if(e.code!==O.SUCCESS){const{tracks:t}=e;return void s.push({code:e.code,tracks:t})}const{publishList:r,urls:i,mcuPublishList:n}=e.data;o=null==i?void 0:i.liveUrl;r.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:t.getTrackState(vt(e))},e))).forEach((e=>{const{isInclude:t,index:r}=((e,t)=>{let r=!1,i=0;for(let o=0;o<t.length;o++){const s=t[o];if(`${e.msid}_${e.mediaType}`==`${s.msid}_${s.mediaType}`){r=!0,i=o;break}}return{isInclude:r,index:i}})(e,c);t?c.splice(r,1,e):c.push(e)}));const a=(null==n?void 0:n.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))))||[];d=a}));const{publishedList:_}=Nt(n,c),u=Object.assign({},t.getCDNUris(),{enableInnerCDN:t.getCDNEnable()}),l=u&&u.broadcast===Er.SPREAD?JSON.stringify([u]):"",h=yield t.context.setRTCTotalRes(i,Ct(Gt.PUBLISH,_),Tt(c),Gt.TOTAL_CONTENT_RESOURCE,Tt(d),l);if(h!==a.SUCCESS)return v.error(`send publish streams notification failed: ${h}`),{code:O.SIGNAL_ERROR};t.setResourcesByUserId(r,c);const R=_.map((e=>vt(e)));t.polarisReport&&t.polarisReport.sendR2(Tr.PUBLISH,Ir.BEGIN,R),_.forEach((e=>{const r=t.useMutilPeerC?`${i}_${(e=>{const t=e.split("_");return{tag:t.pop(),userId:t.join("_")}})(e.msid).tag}`:`${i}_pub`,{pc:o}=t.peerMgr.getPCItemByPCName(r);o.getLocalTrack(`${e.msid}_${e.mediaType}`).__innerSetPublished(!0)})),v.debug(`publish success: ${R.join(",")}`);const p={code:O.SUCCESS};return o&&(p.liveUrl=o),s.length&&(p.failedTracks=s,p.code=O.SOME_TRACKS_PUBLISH_FAILED),p}))}execute(e,t){return f(this,void 0,void 0,(function*(){let o=this.tracks;const n=e.roomId;if(r.info(L.L_ABSTRACT_ROOM_PUBLISH_T,{trackIds:o.map($t)},{logSource:i.RTC}),!s("tracks",o,(()=>d(o)&&o.length>0&&o.every((e=>e instanceof ot||e.track instanceof ot))),!0))return v.warn(`publish failed, tracks is invalid -> roomId: ${n}`),r.error(L.L_ABSTRACT_ROOM_PUBLISH_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(o=o.filter((e=>{const{track:t}=e instanceof ot?{track:e}:e,i=t.isDestroyed();return i&&r.warn(L.L_ABSTRACT_ROOM_PUBLISH_R,{status:A.FAILED,msg:`track -> ${t.getTrackId()} has beem destroyed`}),!i})),!o.length)return{code:O.PUBLISH_TRACKS_IS_INVALID};const a=[],{plist:c,pushOtherRooms:_}=this.pubhook(o);for(let r=0;r<c.length;r++){const i=c[r];a.push(this.__publish(e,i,i.tracks,_,t))}const u=yield Promise.all(a),l=yield this._mergePublishRes(u,e);return r.info(L.L_ABSTRACT_ROOM_PUBLISH_R,{status:A.SUCCESSED,roomId:n,trackIds:o.map($t)},{logSource:i.RTC}),l}))}}class Zr extends br{constructor(e,t){super(),this.tracks=e,this.unpubhook=t}get kind(){return lr.UnPublish}__unpublish(e,t,r,i){return f(this,void 0,void 0,(function*(){const{pcName:o,pc:s}=r;e.roomId;const n=i.map((e=>e.getTrackId()));if(0===n.map(e.getPublishedResourceByTrackId.bind(e)).filter((e=>!!e)).length)return{code:O.SUCCESS,tracks:i};n.forEach((e=>s.removeLocalTrackById(e))),e.polarisReport.sendR2(Tr.PUBLISH,Ir.END,n),s.clearReTryExchangeTimer();const a=e.useMutilPeerC?[]:e.getSubscribedList(),c=yield $r(a,!1,s,e),{pushOtherRooms:d,headers:_}=this.unpubhook(i,o);d&&(c.pushOtherRooms=d);const u=yield new Hr(_,c).execute(e,t);return u.code!==O.SUCCESS?(v.error(`exchange failed -> code: ${u.code}`),{code:u.code,tracks:i}):Object.assign({},u,{tracks:i})}))}_mergeUnpublishRes(e,t){return f(this,void 0,void 0,(function*(){const r=e.context.getCurrentId(),i=e.roomId,o=[],s=[],n=[],c=[];let d=[];for(let r=0;r<t.length;r++){const i=t[r];if(i.code!==O.SUCCESS){const{tracks:e}=i;s.push({code:i.code,tracks:e});continue}const{resultCode:a,message:_,mcuPublishList:u}=i.data;a!==O.SUCCESS&&v.error(`unpublish streams failed -> code: ${a}, msg: ${_}`);const l=i.tracks.map((e=>e.getTrackId()));c.push(...l);const h=l.map(e.getPublishedResourceByTrackId.bind(e)).filter((e=>!!e));n.push(...h),o.push(i);const R=u?u.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[];d=R}const _=e.getResourcesByUserId(r).filter((e=>!n.includes(e))),u=yield e.context.setRTCTotalRes(i,Ct(Gt.UNPUBLISH,n),Tt(_),Gt.TOTAL_CONTENT_RESOURCE,Tt(d));if(u!==a.SUCCESS)return v.error("send unpublish notification failed:",u),{code:O.SIGNAL_ERROR};v.debug(`unpublish success -> tracks: ${c.join(",")}`),o.forEach((t=>f(this,void 0,void 0,(function*(){const{sdp:r}=t.data,{tracks:i}=t,o=e.peerMgr.getPCByTrackId(i[0].getTrackId());yield o.setRemoteAnswer(r.sdp)})))),e.setResourcesByUserId(r,_);const l={code:O.SUCCESS};return s.length&&(l.failedTracks=s,l.code=O.SOME_TRACKS_PUBLISH_FAILED),l}))}execute(e,t){return f(this,void 0,void 0,(function*(){const{crtUserId:o,roomId:n}=e,a=this.tracks;r.info(L.L_ABSTRACT_ROOM_UNPUBLISH_T,{trackIds:a.map($t)},{logSource:i.RTC});if(!s("tracks",a,(()=>a.every((e=>e.getUserId()===o&&e instanceof ot))),!0))return v.warn(`unpublish failed, tracks is invalid -> roomId: ${n}, tracks: ${a.map($t)}`),r.error(L.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};const c=e.peerMgr.createPeerCList(a),d=[];for(let r=0;r<c.length;r++){const{tracks:i}=c[r];d.push(this.__unpublish(e,t,c[r],i))}const _=yield Promise.all(d);let u=_.length;if(_.forEach((e=>{e.code!==O.SUCCESS||e.data||(u-=1)})),0===u)return{code:O.SUCCESS};const l=yield this._mergeUnpublishRes(e,_);return r.info(L.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:A.SUCCESSED,roomId:n,trackIds:a.map($t)},{logSource:i.RTC}),l}))}}class Xr extends br{constructor(e,t){super(),this.localTrack=e,this._recvSignalResultFn=t}execute(e,t){return f(this,void 0,void 0,(function*(){const{localTrack:t}=this,r=t.getTrackId(),{crtUserId:i,roomId:o}=e,s=[{resourceId:r,enabled:!t.isLocalMuted()}],n=e.getResourcesByUserId(i),c=[];for(let e=0;e<n.length;e+=1){const t=n[e],r=vt(t),i=s.findIndex((e=>e.resourceId===r));if(i>=0){const{enabled:e}=s[i];t.state=e?1:0,c.push(t);break}}const d=yield e.context.setRTCTotalRes(o,Ct(Gt.MODIFY,c),Tt(n),Gt.TOTAL_CONTENT_RESOURCE);this._recvSignalResultFn(d),d!==a.SUCCESS&&v.error("notice `track.enabled` change failed -> code: "+d)}))}}class ei extends br{constructor(e,t,r){super(),this.pcName=e,this.isPub=t,this.retryHook=r}get priority(){return Rr.HIGH}execute(e,t){return f(this,void 0,void 0,(function*(){const{pcName:r,isPub:i}=this,{useMutilPeerC:o}=e,{pc:s}=e.peerMgr.getPCItemByPCName(r),n=i&&o?[]:e.getSubscribedList(),a=yield $r(n,!0,s,e),{pushOtherRooms:c,headers:d}=this.retryHook(r);c&&(a.pushOtherRooms=c);const _=yield new Hr(d,a).execute(e,t);if(_.code!==O.SUCCESS)return void v.error(`reTryExchange failed: ${_.code}, pcName: ${r}`);const{sdp:u,resultCode:l}=_.data;l===O.SUCCESS?(s.clearReTryExchangeTimer(),yield s.setRemoteAnswer(u.sdp)):v.error(`reTryExchange failed: ${l}, pcName: ${r}`)}))}}class ti extends br{constructor(e,t,r){super(),this.subhook=e,this.callbacks=t,this.livingType=r}get priority(){return Rr.HIGH}execute(e,t){return f(this,void 0,void 0,(function*(){const{livingType:o}=this,{roomId:s,crtUserId:n,roomMode:c}=e;r.info(L.L_ABSTRACT_ROOM_RECONNECTED_T,{livingType:o},{logSource:i.RTC});if(e.peerMgr.getPCList().some((e=>"closed"===e.getRTCPeerConn().connectionState)))return v.warn("RTCPeerConnection closed. Please rejoin room to restore services."),r.error(L.L_ABSTRACT_ROOM_RECONNECTED_R,{status:A.FAILED,code:"",msg:"RTCPeerConnection disconnected"},{logSource:i.RTC}),void this.callbacks.onPeerClosed();const{code:d,data:_}=yield e.context.joinRTCRoom(s,c,o);if(d!==a.SUCCESS)return v.error(`RTC __onReconnected getRTCRoomInfo failed: ${d}`),void r.error(L.L_ABSTRACT_ROOM_RECONNECTED_R,{status:A.FAILED,code:d,msg:""},{logSource:i.RTC});v.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(_)}`);const u=[],l={},h={},R={},p=Vt(_,s),m=Object.keys(p),C=e.getAllUserIds();for(let t=m.length-1;t>=0;t-=1){const r=m[t],i=C.indexOf(r);if(-1===i){u.push(r),l[r]=At(p[r]);continue}const o=e.getResourcesByUserId(r),s=p[r],{publishedList:n,modifiedList:a,unpublishedList:c}=Nt(o,s,!0);l[r]=At(n),h[r]=At(c),R[r]=At(a),C.splice(i,1)}C.length&&C.forEach((t=>{e.removeResourcesByUserId(t)})),e.assignRoomData(p),C.length&&this.callbacks.onUserLeave(C),u.length&&this.callbacks.onUserJoin(u);for(const r in h){if(r===n)continue;const i=h[r];if(i.length){const r=i.map((t=>e.getRemoteTrack(vt(t))));yield new qr(this.subhook,r,this.callbacks.onTrackUnpublish).execute(e,t)}}return Object.keys(l).forEach((t=>{const r=l[t];if(0===r.length)return;const i=r.map((t=>{const r=vt(t),{userId:i,tag:o,mediaType:s}=Ot(r),n=s===He.AUDIO_ONLY?new pt(o,i):new mt(o,i);return e.addRemoteTrack(n),n.__innerSetRemoteMuted(0===t.state),n}));this.callbacks.onTrackPublish(i)})),Object.keys(R).forEach((t=>{R[t].forEach((t=>{const r=vt(t),i=e.getRemoteTrack(r);i.__innerSetRemoteMuted(0===t.state),i.isAudioTrack()?this.callbacks.onAudioMuteChange(i):this.callbacks.onVideoMuteChange(i)}))})),e.roomMode===mr.LIVE&&this.executeInLivingRoom(e,_),r.info(L.L_ABSTRACT_ROOM_RECONNECTED_R,{status:A.SUCCESSED,roomData:_},{logSource:i.RTC}),{data:_}}))}executeInLivingRoom(e,t){var o,s;if(r.error(L.L_LIVING_ROOM_RECONNECTED_T,{roomData:t},{logSource:i.RTC}),!t)return void r.info(L.L_LIVING_ROOM_RECONNECTED_R,{status:A.FAILED,code:"",msg:"room not fond"},{logSource:i.RTC});const n=null===(o=t.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===o?void 0:o.value;if(!n)return void r.error(L.L_LIVING_ROOM_RECONNECTED_R,{status:A.FAILED,code:"",msg:"cdn_uris not found"},{logSource:i.RTC});const a=JSON.parse(n),c=(null===(s=e.getCDNUris())||void 0===s?void 0:s.enableInnerCDN)!==a.enableInnerCDN;e.setCDNUris(a),r.info(L.L_LIVING_ROOM_RECONNECTED_R,{status:A.SUCCESSED,roomData:t},{logSource:i.RTC}),c&&this.callbacks.onCDNEnableChange(a.enableInnerCDN)}}class ri extends Ur{constructor(e,t,r,i=hr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var r,i,o;return f(this,void 0,void 0,(function*(){const{tracks:s}=this,n=e.roomId;if(v.info(`unsubscribe -> roomId: ${n}, tracks: ${s.map($t)}`),this.state===hr.NORMAL){const i=e.getSubscribedList().slice(),{code:o,failedList:n}=yield new jr(s,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,i);return null===(r=this.callbacks)||void 0===r||r.onTaskCompleted({code:o,subscribe:c,unsubscribe:d,failedList:n}),{code:o,failedList:n}}if(this.state===hr.TAIL){const{code:r}=yield new ri(this.tracks,this.subhook,this.callbacks,hr.MIDDLE).execute(e,t);if(r===O.SUCCESS){const r=e.getCollectSubscribeList().slice(0),s=e.getSubscribedList().slice(),{code:n,failedList:a}=yield new jr(r,this.subhook).execute(e,t);if(n!==O.SUCCESS)return null===(i=this.callbacks)||void 0===i||i.onTaskCompleted({code:n,subscribe:[],unsubscribe:[],failedList:a}),{code:n,failedList:a};const c=e.getSubscribedList().slice(0),{subscribe:d,unsubscribe:_}=this.pickoutSubscribed(c,s);return null===(o=this.callbacks)||void 0===o||o.onTaskCompleted({code:n,subscribe:d,unsubscribe:_,failedList:a}),{code:n,failedList:a}}return{code:r}}return Ur.AsyncUpdateSubscribeTasks.splice(Ur.AsyncUpdateSubscribeTasks.length,0,...this.tracks),new Promise((t=>{const r=this.formateTrack(s);e.resetCollectSubscribeList(r),t({code:O.SUCCESS})}))}))}}class ii extends Ur{constructor(e,t,r,i=hr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var o;return f(this,void 0,void 0,(function*(){const{tracks:n}=this,a=e.roomId;if(this.state===hr.NORMAL){const r=e.getSubscribedList().slice(),{code:i,failedList:s}=yield new zr(n,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,r);return null===(o=this.callbacks)||void 0===o||o.onTaskCompleted({code:i,subscribe:c,unsubscribe:d,failedList:s}),{code:i,failedList:s}}if(r.info(L.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:n.map($t)},{logSource:i.RTC}),!s("tracks",n,(()=>d(n)&&n.length>0&&n.every((e=>e instanceof Rt||e.track instanceof Rt))),!0))return v.warn(`subscribe failed, tracks is invalid -> roomId: ${a}`),r.error(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};v.info(`subscribe -> roomId: ${a}, tracks: ${n.map($t)}`);const c=this.getSubscribedList(e).map((e=>Object.assign({},e))),_=n.map((e=>e instanceof Rt?{track:e}:e)),u=[];if(_.forEach((e=>{const t=e.track.getTrackId();u.push(t);const r=c.find((e=>e.track.getTrackId()===t));if(r){if(r.subTiny===e.subTiny)return;r.subTiny=e.subTiny}else c.push(e)})),e.polarisReport.sendR2(Tr.SUBSCRIBE,Ir.BEGIN,u),r.info(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:n.map($t),roomId:a},{logSource:i.RTC}),this.state===hr.TAIL){const{code:r}=yield new ii(this.tracks,this.subhook,this.callbacks,hr.MIDDLE).execute(e,t);if(r===O.SUCCESS){const r=e.getCollectSubscribeList().slice(0);return new ri(r,this.subhook,this.callbacks).execute(e,t)}return{code:r}}return Ur.AsyncSubscribeTasks.splice(Ur.AsyncSubscribeTasks.length,0,...this.tracks),new Promise((t=>{e.resetCollectSubscribeList(c),t({code:O.SUCCESS})}))}))}getSubscribedList(e){return this.state===hr.MIDDLE?e.getCollectSubscribeList():e.getSubscribedList()}}class oi extends Ur{constructor(e,t,r,i=hr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var o;return f(this,void 0,void 0,(function*(){const n=this.tracks,a=e.roomId;if(this.state===hr.NORMAL){const r=e.getSubscribedList().slice(),{code:i,failedList:s}=yield new Jr(n,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,r);return null===(o=this.callbacks)||void 0===o||o.onTaskCompleted({code:i,subscribe:c,unsubscribe:d,failedList:s}),{code:i,failedList:s}}if(r.info(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:n.map($t)},{logSource:i.RTC}),!s("tracks",n,(()=>d(n)&&n.length>0&&n.every((e=>e instanceof Rt))),!0))return v.warn(`unsubscribe failed, tracks is invalid -> roomId: ${a}`),r.warn(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};v.info(`unsubscribe -> roomId: ${a}, tracks: ${n.map($t)}`);const c=this.getSubscribedList(e).map((e=>Object.assign({},e))).filter((e=>!n.includes(e.track)));if(e.polarisReport.sendR2(Tr.SUBSCRIBE,Ir.END,n.map((e=>e.getTrackId()))),r.info(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:n.map($t),roomId:a},{logSource:i.RTC}),this.state===hr.TAIL){const{code:r}=yield new oi(this.tracks,this.subhook,this.callbacks,hr.MIDDLE).execute(e,t);if(r===O.SUCCESS){const r=e.getCollectSubscribeList().slice(0).map((e=>e.track));return new ri(r,this.subhook,this.callbacks).execute(e,t)}return{code:r}}return Ur.AsyncUnsubscribeTasks.splice(Ur.AsyncUnsubscribeTasks.length,0,...this.tracks),new Promise((t=>{e.resetCollectSubscribeList(c),t({code:O.SUCCESS})}))}))}getSubscribedList(e){return this.state===hr.MIDDLE?e.getCollectSubscribeList():e.getSubscribedList()}}const si="evt-leave";class ni extends t{constructor(e,t,r,i,o,s,n,a,c,d=jt()){super(),this._context=e,this._runtime=t,this._roomId=r,this._service=o,this._initOptions=s,this._useMutilPeerC=c,this._clientSessionId=d,this._appListener=null,this._reportListener=null,this._onRecvPKMsg=null,this._polarisReport=new Dr(this._context,this._runtime,this._roomId,this),this._peerCManager=new yr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._invoker=new wr(this._context,this._service,this._peerCManager,r,this._context.getCurrentId(),i,this._polarisReport,n,a),this._store=this._invoker.store}__innerInit(e,t,r,i,o){return f(this,void 0,void 0,(function*(){const{code:s,data:n}=yield this._invoker.push(new Vr(this._roomId,e,t,r,i,o));return s!==O.SUCCESS?{code:s}:(this._initWithRoomData(n.offlineKickTime),{code:s,data:n})}))}_initWithRoomData(e){var t;this._pinger=new Ht(this._store.roomId,this._store.roomMode,this._context,this._initOptions.pingGap,1e3*e),this._pinger.onFailed=this._kickoff.bind(this),this._pinger.onPingResult=this._handlePingResult.bind(this),this._pinger.start(),null===(t=this._polarisReport)||void 0===t||t.sendR1()}_handlePingResult(e){this._callAppListener("onPing",e)}setBitrate(e,t,r){if(this._useMutilPeerC)return void v.error("`RCAbstractRoom.setBitrate` is disabled, use `RCLocalTrack.setBitrate` instead.");v.warn("`RCAbstractRoom.setBitrate` will be deprecated, use `RCLocalTrack.setBitrate` instead."),m("max",e,(e=>o(e)&&e>Math.max(t||1,200)),!0),m("min",t,(t=>o(t)&&t>=1&&(!o(e)||t<e)),!0),m("start",r,(r=>o(r)&&r>t&&r<=e));this._peerCManager.getPCList().forEach((i=>{i.setBitrate(e,t,r)}))}_onTrackReady(e){const t=e.streams[0].id,r=e.receiver.track,i=[t,"audio"===r.kind?He.AUDIO_ONLY:He.VIDEO_ONLY].join("_"),o=this._store.getRemoteTrack(i);o?(o.__innerSetMediaStreamTrack(r),this._callAppListener("onTrackReady",o)):v.warn(`cannot found remote track ${r.id}`)}_callAppListener(e,...t){var o;"onPing"!==e&&r.info(L.L_ABSTRACT_ROOM_CALL_APP_LISTENER_O,{status:A.SUCCESSED,eventType:e,attrs:t},{logSource:i.RTC}),"onPing"!==e&&v.info(`${e} callback ->`,...t);const s=null===(o=this._appListener)||void 0===o?void 0:o[e];if(s)try{s(...t)}catch(e){v.error(e)}}_onTrackUnpublish(e){this._callAppListener("onTrackUnpublish",e)}__parseInnerMessage(e){const{targetId:t,conversationType:r}=e;if(r!==C.RTC_ROOM)return!1;if(t!==this._roomId)return!0;v.info(`recv inner msg -> message: ${JSON.stringify(e)} | roomid: ${this._roomId}`);const i=e.content;switch(e.messageType){case Gt.KICK:this._kickoff(!0,i);break;case Gt.STATE:this._stateHandle(i);break;case Gt.MODIFY:case Gt.PUBLISH:case Gt.UNPUBLISH:case Gt.TOTAL_CONTENT_RESOURCE:this._resourceHandle(i,e.messageType,e.senderUserId);break;case Gt.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",e.messageType,e.content);break;case Gt.USER_NOTIFY:v.warn(`TODO: ${Gt.USER_NOTIFY}`);break;case Gt.PK_INVITE:case Gt.PK_CANCEL_INVITE:case Gt.PK_INVITE_TIMEOUT:case Gt.PK_INVITE_ANSWER:case Gt.PK_END:this._onRecvPKMsg&&this._onRecvPKMsg(e);break;case Gt.OTHER_ROOM_OFFLINE:break;default:this._callAppListener("onMessageReceive",e.messageType,i,e.senderUserId,e.messageUId)}return!0}_kickoff(e,t){return f(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;let r,i;v.warn(`onKickOff -> byServer: ${e}`),this.emit(si),this._leaveHandle(!e),e&&((null==t?void 0:t.users)||[]).forEach((e=>{e.userId===this._context.getCurrentId()&&(i=e.type,r=e.kickExtra)})),this._callAppListener("onKickOff",e,i,r)}))}_rtcpeerClosed(){this.emit(si),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,t,r){return f(this,void 0,void 0,(function*(){const{uris:i,ignore:o}=e;!o&&i&&this._invoker.push(new Yr(e,t,r,this._subhook.bind(this),{onAudioMute:this._onAudioMuteChange.bind(this),onVideoMute:this._onVideoMuteChange.bind(this),onTrackPublish:this._onTrackPublish.bind(this),onTrackUnublish:this._onTrackUnpublish.bind(this),onCDNEnableChange:this._callAppListener.bind(this,"onCDNEnableChange")}))}))}_onTrackPublish(e){this._callAppListener("onTrackPublish",e)}_stateHandle(e){var t;return f(this,void 0,void 0,(function*(){const{left:r,joined:i,upgrade:o,downgrade:s}=yield this._invoker.push(new Wr(e,this._subhook.bind(this)));if(null===(t=this._appListener)||void 0===t?void 0:t.onSwitchRole)return o.length&&o.forEach((e=>this._callAppListener("onSwitchRole",e,ur.ANCHOR))),s.length&&s.forEach((e=>this._callAppListener("onSwitchRole",e,ur.AUDIENCE))),i.length&&this._callAppListener("onUserJoin",i),void(r.length&&this._callAppListener("onUserLeave",r));const n=[...i,...o],a=[...r,...s];n.length&&this._callAppListener("onUserJoin",n),a.length&&this._callAppListener("onUserLeave",a)}))}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}__getPC(){return this._store.peerMgr.getPCList()}getRemoteUserIds(){return this._store.getRemoteUserIds()}getRemoteTracks(){const e=[];return this.getRemoteUserIds().forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),e}getRemoteTracksByUserId(e){return this._store.getRemoteTracksByUserId(e)}getSessionId(){return this._store.getSessionId()}sendMessage(e,t){return f(this,void 0,void 0,(function*(){r.info(L.L_ABSTRACT_ROOM_SEND_MESSAGE_T,{name:e,content:t},{logSource:i.RTC});const{code:o}=yield this._context.sendMessage(C.RTC_ROOM,this._roomId,{messageType:e,content:t,isStatusMessage:!0});return o!==a.SUCCESS?(v.error(`send message failed -> code: ${o}`),r.error(L.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:A.FAILED,code:o,msg:""},{logSource:i.RTC}),{code:O.SIGNAL_ERROR}):(r.info(L.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:A.SUCCESSED,name:e,content:t},{logSource:i.RTC}),{code:O.SUCCESS})}))}setRoomAttribute(e,t,o,s=!1){return f(this,void 0,void 0,(function*(){r.info(L.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_T,{roomId:this._roomId,key:e,value:t,message:o,isInner:s},{logSource:i.RTC});const n=yield this._context.setRTCData(this._roomId,e,t,s,Sr.ROOM,o);return n!==a.SUCCESS?(v.error(`SetRoomAttributeValue Failed: ${n}`),r.error(L.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:A.FAILED,code:n,msg:""},{logSource:i.RTC}),{code:O.SIGNAL_ERROR}):(r.info(L.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:A.SUCCESSED,roomId:this._roomId,key:e,value:t,message:o,isInner:s},{logSource:i.RTC}),{code:O.SUCCESS})}))}deleteRoomAttributes(e,t,o=!1){return f(this,void 0,void 0,(function*(){r.info(L.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_T,{roomId:this._roomId,keys:e,message:t,isInner:o},{logSource:i.RTC});const s=yield this._context.removeRTCData(this._roomId,e,o,Sr.ROOM,t);return s!==a.SUCCESS?(v.error(`DeleteRoomAttribute Failed: ${s}`),r.error(L.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:A.FAILED,code:s,msg:""},{logSource:i.RTC}),{code:O.SIGNAL_ERROR}):(r.info(L.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:A.SUCCESSED,roomId:this._roomId,keys:e,message:t,isInner:o},{logSource:i.RTC}),{code:O.SUCCESS})}))}getRoomAttributes(e=[],t=!1){return f(this,void 0,void 0,(function*(){const{code:r,data:i}=yield this._context.getRTCData(this._roomId,e,t,Sr.ROOM);return r!==a.SUCCESS?(v.error(`GetRoomAttributes Failed: ${r}`),{code:O.SIGNAL_ERROR}):{code:O.SUCCESS,data:i}}))}_setUserAttributeValue(e,t,r){return this._context.setRTCData(this._roomId,e,t,!1,Sr.PERSON,r)}_deleteUserAttributes(e,t){return this._context.removeRTCData(this._roomId,e,!1,Sr.PERSON,t)}_getUserAttributes(e){return this._context.getRTCData(this._roomId,e,!1,Sr.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 f(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;this._invoker.destroy(),this._muteRemoteTracksBeforeQuit(),this._muteRemoteTracksBeforeQuit(),null===(t=this._audioLevelReport)||void 0===t||t.clearAudioLevelReportTimer(),e&&(yield this._context.quitRTCRoom(this._roomId)),this._store.isMainRoom&&(yield this._quitAllPKRoom()),this._pinger.stop();const r=[];Object.keys(this._peerCManager.getMutilPeerCData()).forEach((e=>{r.push(this._service.exit(this._getRTCReqestHeaders(e)))})),yield Promise.all(r),this._releasePCManager(),this._polarisReport=null}))}_releasePCManager(){const e=this._peerCManager.getPCList();null==e||e.forEach((e=>{e.off(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)})),this._peerCManager.clear(),this._peerCManager=null}_onLocalTrackDestroied(e){e instanceof nt&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(e,t){return f(this,void 0,void 0,(function*(){this._invoker.push(new Xr(e,t))}))}publish(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new Qr(e,this._pubhook.bind(this)))}))}_getPushOtherRoomsParams(){return[]}_reTryExchange(e,t){return f(this,void 0,void 0,(function*(){this._invoker.push(new ei(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 f(this,void 0,void 0,(function*(){return this._invoker.push(new Zr(e,((e,t)=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(t)}))))}))}_getResourceById(e){return this._store.getPublishedResourceByTrackId(e)}_isValidResourceId(e){var t;const{userId:r}=Ot(e);return!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>vt(t)===e)))}_subhook(e){const{pc:t,pcName:r}=this._peerCManager.createPeerCList(e)[0];return t.on(Nr.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),t.__reportR3R4ToPolaris(),t.registerReportListener(this._reportListener),t.clearReTryExchangeTimer(),{pc:t,pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(r)}}_pubhook(e){return{plist:this._peerCManager.createPeerCList(e).map((e=>{const{pc:t,pcName:r}=e;return t.on(ot.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.on(ot.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),t.registerReportListener(this._reportListener),t.__reportR3R4ToPolaris(),Object.assign(Object.assign({},e),{headers:this._getRTCReqestHeaders(r)})})),pushOtherRooms:this._getPushOtherRoomsParams()}}subscribe(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new zr(e,this._subhook.bind(this)))}))}addSubscribeTask(e){this._invoker.push(new ii(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}unsubscribe(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new Jr(e,this._subhook.bind(this)))}))}addUnsubscribeTask(e){this._invoker.push(new oi(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}updateSubList(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new jr(e,this._subhook.bind(this)))}))}addUpdateSubscribeListTask(e){this._invoker.push(new ri(e,this._subhook.bind(this),{onTaskCompleted:this._onTaskCompleted.bind(this)}))}_onTaskCompleted(e){this._callAppListener("onTaskCompleted",e.code,e.subscribe,e.unsubscribe,e.failedList)}getLocalTrack(e){return this._store.getLocalTrack(e)}getLocalTracks(){return this._store.getLocalTracks()}getRemoteTrack(e){return this._store.getRemoteTrack(e)||null}get subscribedTracks(){return this._store.getSubscribedList().slice()}registerRoomEventListener(e){r.info(L.L_ABSTRACT_ROOM_REGISTER_ROOM_EVENT_LISTENER_O,{status:A.SUCCESSED,listener:e&&Object.keys(e)},{logSource:i.RTC}),this._appListener=e}registerReportListener(e){r.info(L.L_ABSTRACT_ROOM_REGISTER_REPORT_LISTENER_O,{status:A.SUCCESSED,listener:e&&Object.keys(e)},{logSource:i.RTC}),this._reportListener=e}onAudioLevelChange(e,t){var o;r.info(L.L_ABSTRACT_ROOM_AUDIO_LEVEL_O,{status:A.SUCCESSED,handler:null==e?void 0:e.name,gap:t},{logSource:i.RTC}),null===(o=this._audioLevelReport)||void 0===o||o.clearAudioLevelReportTimer(),this._audioLevelReport=new kr(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}__onReconnected(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new ti(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 ai extends br{constructor(e,t){super(),this.data=e,this.cdnValues=t}execute(e,t){var r,i,o,s;return f(this,void 0,void 0,(function*(){const t={"App-Key":e.context.getAppkey(),Token:e.getToken(),RoomId:e.roomId,UserId:e.context.getCurrentId(),SessionId:e.getSessionId()},{code:n,res:a}=yield e.service.setMcuConfig(t,this.data);if(n!==O.SUCCESS)return v.error(`set MCU config failed: ${n}`),{code:n};v.info("set MCU config success"),a.pull_url&&e.setCDNUris(JSON.parse(a.pull_url));const c=this.cdnValues;return n===O.SUCCESS&&((null===(i=null===(r=c.output)||void 0===r?void 0:r.video.normal)||void 0===i?void 0:i.width)||(null===(s=null===(o=c.output)||void 0===o?void 0:o.video.normal)||void 0===s?void 0:s.fps))&&Kr(e),{code:n,res:a}}))}}var ci,di,_i,ui;!function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(ci||(ci={})),function(e){e[e.CUSTOMIZE=1]="CUSTOMIZE",e[e.SUSPENSION=2]="SUSPENSION",e[e.ADAPTATION=3]="ADAPTATION"}(di||(di={})),function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(_i||(_i={})),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"}(ui||(ui={}));const li=()=>({version:2,mode:di.SUSPENSION});class hi{constructor(e,t){this._invoker=e,this._isValidTrackId=t,this._values=li()}setHostVideoTrack(e){if(v.info(`setHostVideoTrack -> videoTrackId: ${e}`),!this._isValidTrackId(e))return v.error(`setHostVideoTrack failed -> videoTrackId is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:A.FAILED,code:"",msg:"params error -> videoTrackId"},{logSource:i.RTC}),this;const{mediaType:t,tag:o,userId:s}=Ot(e);return t!==He.VIDEO_ONLY?(v.error(`setHostVideoTrack failed -> kind of resource is not 'video' -> ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:A.FAILED,code:"",msg:"not video"},{logSource:i.RTC}),this):(this._values.host_stream_id=Lt(s,o),r.info(L.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:A.SUCCESSED,videoTrackId:e},{logSource:i.RTC}),this)}setMixLayoutMode(e){v.info(`setMixLayoutMode -> mode: ${e}`);return[di.CUSTOMIZE,di.SUSPENSION,di.ADAPTATION].includes(e)?(this._values.mode=e,r.info(L.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:A.SUCCESSED,mode:e},{logSource:i.RTC}),this):(v.error(`setMixLayoutMode failed -> mode is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:A.SUCCESSED,code:"",msg:`params error -> mode: ${e}`},{logSource:i.RTC}),this)}_addOutputValue(e,t,r="normal"){const i=this._values.output||(this._values.output={video:{normal:{width:640,height:480}}});if("cdn"===e)return void(i.cdn=t);if("audio"===e)return void(i.audio={bitrate:t});const o=i.video;if("normal"!==r&&"tiny"!==r)if("backgroundColor"!==r)if("exparams"!==r){if("backgroundPicture"===r){const e=o.backgroundPicture||(o.backgroundPicture={fillMode:ci.CROP,picture:[]});Object.assign(e,t)}}else o.exparams={renderMode:t};else o.backgroundColor=t;else{const e=o[r]||(o[r]={});Object.assign(e,t)}}setOutputVideoResolution(e){if(v.info(`setOutputVideoResolution -> resolution: ${e}`),!yt(e))return v.error(`setOutputVideoResolution failed -> resolution is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:A.FAILED,code:"",msg:`params error -> resolution: ${e}`},{logSource:i.RTC}),this;const{width:t,height:o}=kt(e);return this._addOutputValue("video",{width:t,height:o},"normal"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:A.SUCCESSED,resolution:e},{logSource:i.RTC}),this}setOutputVideoFPS(e){if(v.info(`setOutputVideoFPS -> fps: ${e}`),!bt(e))return v.error(`setOutputVideoFPS failed -> fps is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:A.FAILED,code:"",msg:`params error -> fps: ${e}`},{logSource:i.RTC}),this;const t=Ut(e);return this._addOutputValue("video",{fps:t},"normal"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:A.SUCCESSED,fps:e},{logSource:i.RTC}),this}setOutputVideoBitrate(e){return v.info(`setOutputVideoBitrate -> bitrate: ${e}`),!o(e)||e<=0?(v.error(`setOutputVideoBitrate failed -> bitrate is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:A.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:i.RTC})):this._addOutputValue("video",{bitrate:e},"normal"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:A.SUCCESSED,bitrate:e},{logSource:i.RTC}),this}setOutputTinyVideoResolution(e){if(v.info(`setOutputTinyVideoResolution -> resolution: ${e}`),!yt(e))return v.error(`setOutputTinyVideoResolution failed -> resolution is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:A.FAILED,code:"",msg:`params error -> resolution: ${e}`},{logSource:i.RTC}),this;const{width:t,height:o}=kt(e);return this._addOutputValue("video",{width:t,height:o},"tiny"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:A.SUCCESSED,resolution:e},{logSource:i.RTC}),this}setOutputTinyVideoFPS(e){if(v.info(`setOutputTinyVideoFPS -> fps: ${e}`),!bt(e))return v.error(`setOutputTinyVideoFPS failed -> fps is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:A.FAILED,code:"",msg:`params error -> fps: ${e}`},{logSource:i.RTC}),this;const t=Ut(e);return this._addOutputValue("video",{fps:t},"tiny"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:A.SUCCESSED,fps:e},{logSource:i.RTC}),this}setOutputTinyVideoBitrate(e){return v.info(`setOutputTinyVideoBitrate -> bitrate: ${e}`),!o(e)||e<=0?(v.error(`setOutputTinyVideoBitrate failed -> bitrate is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:A.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:i.RTC})):this._addOutputValue("video",{bitrate:e},"tiny"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:A.SUCCESSED,bitrate:e},{logSource:i.RTC}),this}setOutputVideoRenderMode(e){return v.info(`setOutputVideoRenderMode -> renderMode: ${e}`),[_i.CROP,_i.WHOLE].includes(e)?this._addOutputValue("video",e,"exparams"):(v.error(`setOutputVideoRenderMode failed -> renderMode is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:A.FAILED,code:"",msg:`params error -> renderMode: ${e}`},{logSource:i.RTC})),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:A.SUCCESSED,renderMode:e},{logSource:i.RTC}),this}setOutputAudioBitrate(e){return v.info(`setOutputAudioBitrate -> bitrate: ${e}`),o(e)&&e>0?this._addOutputValue("audio",e):(v.error(`setOutputAudioBitrate failed -> bitrate is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:A.FAILED,code:"",msg:`params error -> bitrate: ${e}`},{logSource:i.RTC})),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:A.SUCCESSED,bitrate:e},{logSource:i.RTC}),this}setOutputBackgroundColor(e){return v.info(`setOutputBackgroundColor -> color: ${e}`),/^0x[a-fA-F0-9]{6}$/.test(e)?this._addOutputValue("video",e,"backgroundColor"):(v.error(`setOutputBackgroundColor failed -> color is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:A.FAILED,code:"",msg:`params error -> color: ${e}`},{logSource:i.RTC})),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:A.SUCCESSED,color:e},{logSource:i.RTC}),this}addOutputBackgroundPicture(e,t,s,n,a){var c,d,_;if(v.info(`addOutputBackgroundPicture -> uri: ${e}, x: ${t}, y: ${s}, w: ${n}, h: ${a}`),!T(e))return v.error(`addOutputBackgroundPicture failed -> uri is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:A.FAILED,code:"",msg:`params error -> uri: ${e}`},{logSource:i.RTC}),this;if([t,s,n,a].some((e=>!o(e)||e<0||e>1)))return v.error(`addOutputBackgroundPicture failed -> some attrs of (x, y, w, h) is invalid: ${t}, ${s}, ${n}, ${a}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:A.FAILED,code:"",msg:`params error -> x: ${t}, y: ${s}, w: ${n}, h: ${a}`},{logSource:i.RTC}),this;const u=(null===(_=null===(d=null===(c=this._values.output)||void 0===c?void 0:c.video)||void 0===d?void 0:d.backgroundPicture)||void 0===_?void 0:_.picture)||[];return u.push({uri:e,w:n,h:a,x:t,y:s}),this._addOutputValue("video",{picture:u},"backgroundPicture"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:A.SUCCESSED,uri:e,x:t,y:s,w:n,h:a},{logSource:i.RTC}),this}removeOutputBackgroundPicture(e){var t,o,s;if(v.info(`removeOutputBackgroundPicture -> uri: ${e}`),!T(e))return v.error(`removeOutputBackgroundPicture failed -> uri is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:A.FAILED,code:"",msg:`params error -> uri: ${e}`},{logSource:i.RTC}),this;let n=null===(s=null===(o=null===(t=this._values.output)||void 0===t?void 0:t.video)||void 0===o?void 0:o.backgroundPicture)||void 0===s?void 0:s.picture;return n&&(n=n.filter((t=>t.uri!==e)),this._addOutputValue("video",{pictures:n},"backgroundPicture")),r.info(L.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:A.SUCCESSED,uri:e},{logSource:i.RTC}),this}clearOutputBackgroundPicture(){return v.info("clearOutputBackgroundPicture ->"),this._addOutputValue("video",{pictures:[]},"backgroundPicture"),r.info(L.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:A.SUCCESSED},{logSource:i.RTC}),this}setOutputBackgroundPictureFillMode(e){return v.info(`setOutputBackgroundPictureFillMode -> fillMode: ${e}`),[ci.CROP,ci.WHOLE].includes(e)?this._addOutputValue("video",{fillMode:e},"backgroundPicture"):(v.error(`setOutputBackgroundPictureFillMode failed -> fillMode is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:A.FAILED,code:"",msg:`params error -> fillMode: ${e}`},{logSource:i.RTC})),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:A.SUCCESSED,fillMode:e},{logSource:i.RTC}),this}addPublishStreamUrls(e){var t,o;v.info(`addPublishStreamUrls -> urls: ${e.join(",")}`);const s=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!s.test(e))))return v.error(`addPublishStreamUrls failed -> urls is invalid: ${e.join(",")}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:A.FAILED,code:"",msg:`params error -> urls: ${e.join(",")}`},{logSource:i.RTC}),this;const n=(null===(o=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===o?void 0:o.concat())||[];let a=!1;return e.forEach((e=>{n.some((t=>t.pushurl===e))||(a=!0,n.push({pushurl:e}))})),n.length>5?(v.error("addPublishStreamUrls failed -> publish stream urls no more than 5!"),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:A.FAILED,code:"",msg:`params error -> publish stream urls no more than 5, length: ${e.length}`},{logSource:i.RTC}),this):(a&&this._addOutputValue("cdn",n),r.info(L.L_MCU_CONFIG_BUILDER_ADD_PUBLISH_STREAM_URLS_O,{status:A.SUCCESSED,urls:e},{logSource:i.RTC}),this)}removePublishStreamUrls(e){var t,o;v.info(`removePublishStreamUrls -> urls: ${e.join(",")}`);const s=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!s.test(e))))return v.error(`removePublishStreamUrls failed -> urls contain invalid items: ${e.join(",")}`),r.error(L.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:A.FAILED,code:"",msg:`params error -> urls: ${e.join(",")}`},{logSource:i.RTC}),this;const n=(null===(o=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===o?void 0:o.concat())||[];for(let t=n.length-1;t>=0;t-=1){const{pushurl:r}=n[t],i=e.indexOf(r);i>=0&&(e.splice(i,1),n.splice(t,1))}return this._addOutputValue("cdn",n),r.info(L.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:A.SUCCESSED,urls:e},{logSource:i.RTC}),this}clearPublishStreamUrls(){return v.info("clearPublishStreamUrls ->"),this._addOutputValue("cdn",[]),r.info(L.L_MCU_CONFIG_BUILDER_CLEAR_PUBLISH_STREAM_URLS_O,{status:A.SUCCESSED},{logSource:i.RTC}),this}addCustomizeLayoutVideo(e,t,s,n,a){if(v.info(`addCustomizeLayoutVideo -> trackId: ${e}, x: ${t}, y: ${s}, width: ${n}, height: ${a}`),!R(e)||!this._isValidTrackId(e))return v.error(`addCustomizeLayoutVideo failed -> trackId is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;if(!o(t)||!o(s))return v.error(`addCustomizeLayoutVideo failed -> some attrs of (x, y) is invalid: ${t}, ${s}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:`params error -> x: ${t}, y: ${s}`},{logSource:i.RTC}),this;if([n,a].some((e=>!o(e)||e<0)))return v.error(`addCustomizeLayoutVideo failed -> some attrs of (width, height) is invalid: ${n}, ${a}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:`params error -> width: ${n}, height: ${a}`},{logSource:i.RTC}),this;const{userId:c,tag:d,mediaType:_}=Ot(e);if(_!==He.VIDEO_ONLY)return v.error(`addCustomizeLayoutVideo failed -> kind of trackId is not 'video': ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}的资源不是视频`},{logSource:i.RTC}),this;const u=Lt(c,d),l=this._values.input||(this._values.input={}),h=l.video||(l.video=[]);return h.some((e=>e.height===a&&e.width===n&&e.stream_id===u&&e.user_id===c&&e.x===t&&e.y===s))?(r.warn(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:"Duplicate configuration item ignored"},{logSource:i.RTC}),this):(h.push({user_id:c,stream_id:u,x:t,y:s,width:n,height:a}),r.info(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.SUCCESSED,trackId:e,x:t,y:s,width:n,height:a},{logSource:i.RTC}),this)}removeCustomizeLayoutVideo(e){if(v.info(`clearCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return v.error(`clearCustomizeInputAudio failed -> trackId is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const{userId:t,tag:o,mediaType:s}=Ot(e);if(s!==He.VIDEO_ONLY)return v.error(`clearCustomizeInputAudio failed -> kind of trackId is not 'video': ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}的资源不是视频`},{logSource:i.RTC}),this;const n=Lt(t,o),a=this._values.input;return(null==a?void 0:a.video)&&a.video.length>0&&(a.video=a.video.filter((e=>e.stream_id===n))),r.info(L.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.SUCCESSED,trackId:e},{logSource:i.RTC}),this}clearCustomizeLayoutVideo(){v.info("clearCustomizeLayoutVideo ->");const e=this._values.input;return null==e||delete e.video,r.info(L.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.SUCCESSED},{logSource:i.RTC}),this}setCustomizeInputAudio(e){if(v.info(`setCustomizeInputAudio -> trackIds: ${e.join(",")}`),e.some((e=>this._isValidTrackId(e))))return v.warn(`setCustomizeInputAudio failed -> trackIds contain invalid items: $${e.join(",")}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:A.FAILED,code:"",msg:`params error -> trackIds: ${e.join(",")}`},{logSource:i.RTC}),this;return(this._values.input||(this._values.input={})).audio=e.map((e=>{const{userId:t,tag:r}=Ot(e);return{stream_id:Lt(t,r),user_id:t}})),this._values.inputFilterMode=ui.AUDIO_INPUT_VIDEO_ALL,r.info(L.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:A.SUCCESSED,trackIds:e},{logSource:i.RTC}),this}addCustomizeInputAudio(e){if(v.info(`addCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return v.warn(`addCustomizeInputAudio failed -> trackId is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const t=this._values.input||(this._values.input={}),o=t.audio||(t.audio=[]),{userId:s,tag:n}=Ot(e),a=Lt(s,n);return o.some((e=>e.stream_id===a&&e.user_id===s))?(r.warn(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:A.FAILED,code:"",msg:`trackId:${e} is exist`},{logSource:i.RTC}),this):(o.push({user_id:s,stream_id:a}),this._values.inputFilterMode=ui.AUDIO_INPUT_VIDEO_ALL,r.info(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:A.SUCCESSED,trackId:e},{logSource:i.RTC}),this)}removeCustomizeInputAudio(e){if(v.info(`removeCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return v.error(`removeCustomizeInputAudio failed -> trackId is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const t=this._values.input;if(!(null==t?void 0:t.audio)||0===t.audio.length)return r.error(L.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:A.FAILED,code:"",msg:"not audio"},{logSource:i.RTC}),this;const{userId:o,tag:s}=Ot(e),n=Lt(o,s);return t.audio=t.audio.filter((e=>o!==e.user_id||n!==e.stream_id)),r.info(L.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:A.SUCCESSED,trackId:e},{logSource:i.RTC}),this}clearCustomizeInputAudio(){v.info("clearCustomizeInputAudio ->");const e=this._values.input;return(null==e?void 0:e.audio)&&delete e.audio,this._values.inputFilterMode=ui.AUDIO_VIDEO_ALL,r.info(L.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_INPUT_AUDIO_O,{status:A.SUCCESSED},{logSource:i.RTC}),this}addPictureWaterMark(e,t,s,n,a,c){if(v.info(`addPictureWaterMark -> trackId: ${e} uri: ${t}, x: ${s}, y: ${n}, w: ${a}, h: ${c}`),!this._isValidTrackId(e))return v.warn(`addPictureWaterMark failed -> trackId is invalid: ${e}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;if(!T(t))return v.error(`addPictureWaterMark failed -> uri is invalid: ${t}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:A.FAILED,code:"",msg:`params error -> uri: ${t}`},{logSource:i.RTC}),this;if([s,n,a,c].some((e=>!o(e)||e<0||e>1)))return v.error(`addPictureWaterMark failed -> some attrs of (x, y, w, h) is invalid: ${s}, ${n}, ${a}, ${c}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:A.FAILED,code:"",msg:`params error -> x: ${s}, y: ${n}, w: ${a}, h: ${c}`},{logSource:i.RTC}),this;const{userId:d,tag:_}=Ot(e),u=Lt(d,_),l=(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen;v.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(l)}`);const h=l.filter((e=>e.streamId===u))[0];return v.info(`addPictureWaterMark target-> : ${h}`),h?h.picture.push({uri:t,w:a,h:c,x:s,y:n}):l.push({streamId:u,picture:[{uri:t,w:a,h:c,x:s,y:n}]}),v.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(l)}`),this._values.waterMark.singleScreen=l,v.info(`addPictureWaterMark this._values.waterMark.singleScreen-> : ${JSON.stringify(this._values.waterMark.singleScreen)}`),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:A.SUCCESSED,trackId:e,uri:t,x:s,y:n,w:a,h:c},{logSource:i.RTC}),this}clearPictureWaterMark(){v.info("clearOutputBackgroundPicture ->");return(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen=[],r.info(L.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:A.SUCCESSED},{logSource:i.RTC}),this}removePictureWaterMark(e,t){if(!R(e)||!this._isValidTrackId(e))return r.error(L.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O,{status:A.FAILED,code:"",msg:`params error -> trackId: ${e}`},{logSource:i.RTC}),this;const{userId:o,tag:s}=Ot(e),n=Lt(o,s);return(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen.forEach((e=>{e.streamId===n&&(e.picture=e.picture.filter((e=>e.uri!==t)))})),r.info(L.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O,{status:A.SUCCESSED,trackId:e,uri:t},{logSource:i.RTC}),this}reset(){return v.info("MCUConfigBuilder.reset ->"),this._values=li(),r.info(L.L_MCU_CONFIG_BUILDER_RESET_O,{status:A.SUCCESSED},{logSource:i.RTC}),this}flush(e=!0){return f(this,void 0,void 0,(function*(){const t=JSON.parse(JSON.stringify(this._values)),{code:o}=yield this._invoker.push(new ai(t,this._values));return e&&(this._values=li()),r.info(L.L_MCU_CONFIG_BUILDER_FLUSH_O,{status:A.SUCCESSED},{logSource:i.RTC}),{code:o}}))}__innerGetValues(){return JSON.parse(JSON.stringify(this._values))}}var Ri,pi,mi,Ci;!function(e){e[e.VIDEO=0]="VIDEO",e[e.AUDIO=1]="AUDIO"}(Ri||(Ri={})),function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(pi||(pi={}));class Ti extends br{constructor(e,t,r){super(),this.roomId=e,this.hooks=t,this.roomPKHandler=r}_exchangeWithPushOtherRoom(e,t){return f(this,void 0,void 0,(function*(){if(!e.getLocalTracks().length)return;const r=Object.values(e.peerMgr.getMutilPeerCData()),i=Object.keys(e.peerMgr.getMutilPeerCData());for(let o=0;o<r.length;o++){const{pc:s,isPub:n}=r[o],a=n&&e.useMutilPeerC?[]:e.getSubscribedList(),c=yield $r(a,!1,s,e),{pushOtherRooms:d,headers:_}=this.hooks(i[o]);c.pushOtherRooms=d;const u=yield new Hr(_,c).execute(e,t);if(u.code!==O.SUCCESS)return void v.error(`exchange with pushOtherRoom failed: ${u.code}`);const{sdp:l,resultCode:h}=u.data;if(h!==O.SUCCESS)return void v.error(`exchange with pushOtherRoom failed: ${h}`);s.setRemoteAnswer(l.sdp)}}))}execute(e,t){return f(this,void 0,void 0,(function*(){const{roomId:o}=this;if(r.info(L.L_LIVING_ROOM_JOINED_PK_ROOM_T,{roomId:o,userId:e.crtUserId},{logSource:i.RTC}),!this.roomPKHandler)return void r.error(L.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:A.FAILED,code:"",msg:"_roomPKHandler not exist"},{logSource:i.RTC});const s=this.roomPKHandler.getPKInfo(o);if(!s)return v.warn(`exchange to update pushOtherRoom cancel, pkInfo lost -> roomId: ${o}`),void r.error(L.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:A.FAILED,code:"",msg:"PKInfo not exist"},{logSource:i.RTC});yield this._exchangeWithPushOtherRoom(e,t),r.info(L.L_LIVING_ROOM_JOINED_PK_ROOM_T,{status:A.SUCCESSED,roomId:o,userId:e.crtUserId,PKInfo:s},{logSource:i.RTC})}))}}class Ii extends br{constructor(e,t,r,i,o,s){super(),this.pkHandler=e,this.room=t,this._PKInfo=r,this.hooks=i,this._joinedPKRooms=o,this.isQuitPK=s}get kind(){return lr.LeaveRoom}quitRoomPK(e,t){return f(this,void 0,void 0,(function*(){if(!this._PKInfo[e])return;const{inviterRoomId:r,inviteeRoomId:i,inviterUserId:o,inviteSessionId:s}=this._PKInfo[e],n={inviteeRoomId:i,inviterRoomId:r,userId:t.crtUserId},c={roomId:t.roomId,endRoomId:e,sessionId:s,content:JSON.stringify(n),keys:[`${r}|${o}`]};v.info(`quitRoomPK -> params: ${JSON.stringify(c)}`);const d=yield t.context.endRoomPK(c);return d!==a.SUCCESS?(v.error(`quitRoomPK failed: ${d}`),{code:O.SIGNAL_ERROR}):(v.info("quitRoomPK success"),delete this._PKInfo[e],{code:O.SUCCESS})}))}execute(e,t){return f(this,void 0,void 0,(function*(){const{room:o,isQuitPK:s}=this,n=o.getRoomId();return v.info(`leavePKRoom -> userId: ${e.crtUserId} , roomId: ${n}`),r.info(L.L_LIVING_ROOM_LEAVE_PK_ROOM_T,{roomId:n,userId:e.crtUserId,isQuitPK:s},{logSource:i.RTC}),yield o.__destroy(!0),delete this._joinedPKRooms[n],yield new Ti(n,this.hooks,this.pkHandler).execute(e,t),s&&this.quitRoomPK(n,e),r.info(L.L_LIVING_ROOM_LEAVE_PK_ROOM_R,{status:A.SUCCESSED,roomId:n,userId:e.crtUserId,isQuitPK:s},{logSource:i.RTC}),{code:O.SUCCESS}}))}}class Ei{constructor(e,t,r,i,o,s,n,a,c,d,_){this._invoker=e,this._PKInfo=t,this._hooks=r,this._context=i,this._runtime=o,this._service=s,this._initOptions=n,this._mainLivingRoom=a,this._registerPKMsgListener=c,this._onJoinedPKRoom=d,this._clientSessionId=_,this._inviteTimeout=30,this._appListener=null,this._joinedPKRooms={},this._registerPKMsgListener(this._onRecvPKMsg.bind(this)),this._mainRoomId=this._mainLivingRoom.getRoomId()}_callAppListener(e,...t){var r;v.info(`${e} callback ->`,...t);const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){v.error(e)}}_onInvite(e){const t=e.inviteInfo||{},{inviterRoomId:r,inviterUserId:i,extra:o}=t,s={inviterRoomId:r,inviterUserId:i,extra:o};this._PKInfo[r]=t,this._callAppListener("onRequestJoinOtherRoom",s)}_onCancelInvite(e){const{inviterRoomId:t,inviterUserId:r,extra:i}=e.inviteInfo||{},o={inviterRoomId:t,inviterUserId:r,extra:i};delete this._PKInfo[t],this._callAppListener("onCancelRequestOtherRoom",o)}_onInviteTimeout(e){}_onInviteAnswer(e){const{answerCode:t,inviteContent:r}=e,{inviteSessionId:i,inviterUserId:o,inviterRoomId:s,inviteeUserId:n,inviterUserAutoMix:a,inviteeUserAutoMix:c,inviteeRoomId:d,extra:_}=r,u={agree:1===t,inviterRoomId:s,inviterUserId:o,inviteeRoomId:d,inviteeUserId:n,extra:_};this._PKInfo[d]=this._PKInfo[d]||{inviteSessionId:i,inviterRoomId:s,inviterUserId:o,inviterUserAutoMix:a,inviteeRoomId:d},this._PKInfo[d].inviteeUserAutoMix=c,this._callAppListener("onResponseJoinOtherRoom",u)}createLeaveOtherRoomCommand(e,t){return new Ii(this,e,this._PKInfo,this._hooks,this._joinedPKRooms,t)}_onPKEnd(e){return f(this,void 0,void 0,(function*(){const{inviteeRoomId:t,inviterRoomId:r,userId:i}=e.inviteInfo,o=r===this._mainRoomId?t:r,s={endRoomId:o,endUserId:i},n=this._joinedPKRooms[o];n&&(yield this._invoker.push(this.createLeaveOtherRoomCommand(n))),delete this._PKInfo[o],this._callAppListener("onFinishOtherRoom",s)}))}_onRecvPKMsg(e){const{targetId:t,content:r,messageType:i}=e;switch(i){case Gt.PK_INVITE:this._onInvite(r);break;case Gt.PK_CANCEL_INVITE:this._onCancelInvite(r);break;case Gt.PK_INVITE_TIMEOUT:this._onInviteTimeout(r);break;case Gt.PK_INVITE_ANSWER:this._onInviteAnswer(r);break;case Gt.PK_END:this._onPKEnd(r)}}registerRoomPKEventListener(e){r.info(L.L_LIVING_PK_HANDLER_REGISTER_ROOM_PK_EVENT_LISTENER_O,{status:A.SUCCESSED,listener:e&&Object.keys(e)},{logSource:i.RTC}),this._appListener=e}requestJoinOtherRoom(e,t,o){return f(this,void 0,void 0,(function*(){if(r.info(L.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:e,inviteeUserId:t,options:o},{logSource:i.RTC}),!s("inviteeRoomId",e,R,!0)||!s("inviteeUserId",t,R,!0))return r.error(L.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> inviteeRoomId 或 inviteeUserId"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};v.info(`requestRoomPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; options: ${JSON.stringify(o||{})}`);const n=jt(),c=!I(null==o?void 0:o.autoMix)||(null==o?void 0:o.autoMix),d={inviteSessionId:n,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:c,inviteeRoomId:e,inviteeUserId:t,inviteeTimeoutTime:this._inviteTimeout,extra:(null==o?void 0:o.extra)||""},_={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteTimeout:this._inviteTimeout,inviteInfo:JSON.stringify(d),inviteSessionId:n};v.info(`requestRoomPK -> params: ${JSON.stringify(_)}`);const u=yield this._context.requestRoomPK(_);return u!==a.SUCCESS?(v.error(`requestRoomPK failed: ${u}`),r.error(L.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:u,msg:""},{logSource:i.RTC}),{code:u}):(v.info("requestRoomPK success"),this._PKInfo[e]={inviteSessionId:n,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:c,inviteeRoomId:e},r.info(L.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{inviteeRoomId:e,inviteeUserId:t,options:o},{logSource:i.RTC}),{code:O.SUCCESS})}))}cancelRequestJoinOtherRoom(e,t,o){return f(this,void 0,void 0,(function*(){if(r.info(L.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:e,inviteeUserId:t,extra:o,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),!s("inviteeRoomId",e,R,!0)||!s("inviteeUserId",t,R,!0))return r.error(L.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> inviteeRoomId or inviteeUserId"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(!this._PKInfo[e])return v.error(`The request to connect with ${t} user in room ${e} is not initiated`),r.error(L.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:`The request to connect with ${t} user in room ${e} is not initiated`},{logSource:i.RTC}),{code:O.PARAMS_ERROR};v.info(`canceRequestJoinPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; extra: ${o}`);const n={inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviteeRoomId:e,inviteeUserId:t,extra:o||""},c={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteSessionId:this._PKInfo[e].inviteSessionId,inviteInfo:JSON.stringify(n)};v.info(`canceRequestJoinPK -> params: ${JSON.stringify(c)}`);const d=yield this._context.cancelRoomPK(c);return d!==a.SUCCESS?(v.error(`canceRequestJoinPK failed: ${d}`),r.error(L.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:d,msg:`The request to connect with ${t} user in room ${e} is not initiated`},{logSource:i.RTC}),{code:d}):(v.info("canceRequestJoinPK success"),r.info(L.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:A.SUCCESSED,inviteeRoomId:e,inviteeUserId:t,extra:o},{logSource:i.RTC}),delete this._PKInfo[e],{code:O.SUCCESS})}))}responseJoinOtherRoom(e,t,o,n){return f(this,void 0,void 0,(function*(){if(r.info(L.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_T,{inviterRoomId:e,inviterUserId:t,agree:o,options:n,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),!s("inviterRoomId",e,R,!0)||!s("inviterUserId",t,R,!0))return r.error(L.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> inviterRoomId or inviterUserId"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(!this._PKInfo[e])return v.error(`User ${t} in room ${e} did not send a request for connection`),r.error(L.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:`User ${t} in room ${e} did not send a request for connection`},{logSource:i.RTC}),{code:O.PARAMS_ERROR};v.info(`responseRoomPK -> inviterRoomId: ${e}; inviterUserId: ${t}; agree: ${o}; options: ${JSON.stringify(n||{})}`);const{inviteSessionId:c,inviterUserAutoMix:d}=this._PKInfo[e],_=!I(null==n?void 0:n.autoMix)||(null==n?void 0:n.autoMix),u={inviteSessionId:c,inviterRoomId:e,inviterUserId:t,inviterUserAutoMix:d,inviteeRoomId:this._mainRoomId,inviteeUserId:this._context.getCurrentId(),inviteeUserAutoMix:_},l=Object.assign(u,{inviterUserAutoMix:d}),h=o?Object.assign(u,{MultiRoomKey:`${e}|${this._mainRoomId}`,MultiRoomValue:JSON.stringify(l)}):u;!E(null==n?void 0:n.extra)&&Object.assign(h,{extra:n.extra});const p={agree:o,roomId:this._mainRoomId,inviteSessionId:c,inviteRoomId:e,inviteUserId:t,content:JSON.stringify(h),key:`${e}|${this._mainRoomId}`,value:JSON.stringify(u)};v.info(`responseRoomPK -> params: ${JSON.stringify(p)}`);const m=yield this._context.responseRoomPK(p);return m!==a.SUCCESS?(v.error(`responseRoomPK failed: ${m}`),r.error(L.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:m,msg:""},{logSource:i.RTC}),{code:m}):(v.info("responseRoomPK success"),r.info(L.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:A.SUCCESSED,inviterRoomId:e,inviterUserId:t,agree:o,options:n,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),this._PKInfo[e].inviteeUserAutoMix=_,{code:O.SUCCESS})}))}joinOtherRoom(e){return f(this,void 0,void 0,(function*(){if(r.info(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_T,{roomId:e,userId:this._context.getCurrentId()},{logSource:i.RTC}),!s("roomId",e,R,!0))return r.error(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(this._context.getConnectionStatus()!==u.CONNECTED)return r.error(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.SIGNAL_DISCONNECTED,msg:"IM disconnected"},{logSource:i.RTC}),{code:O.SIGNAL_DISCONNECTED};if(v.info(`JoinPKRoom, roomId: ${e}`),this._joinedPKRooms[e])return r.warn(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:O.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:O.REPERT_JOIN_ROOM};const t=Ri.VIDEO,o={extra:`{"roomId": "${this._mainRoomId}"}`},n=new fi(this._context,this._runtime,e,this._service,this._initOptions,t,!1,!1,!1,this._clientSessionId),{code:a,data:c}=yield n.__innerInit(mr.LIVE,void 0,t,o);return a!==O.SUCCESS?(v.error(`JoinPKRoom failed -> code: ${a}`),r.error(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:a,msg:""},{logSource:i.RTC}),{code:a}):(v.info(`JoinPKRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(c)}`),this._joinedPKRooms[e]=n,yield this._onJoinedPKRoom(e,n),r.info(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.SUCCESSED,roomId:e,userId:this._context.getCurrentId()},{logSource:i.RTC}),{room:n,code:O.SUCCESS,userIds:n.getRemoteUserIds(),tracks:n.getRemoteTracks()})}))}leaveOtherRoom(e,t){return f(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"}(mi||(mi={}));class Si extends br{constructor(e,t){super(),this.cdnValues=e,this.enable=t}execute(e,t){return f(this,void 0,void 0,(function*(){const{enable:o}=this;if(r.info(L.L_LIVING_ROOM_ENABLE_INNER_CDN_T,{roomId:e.roomId,enable:o},{logSource:i.RTC}),!e.isMainRoom)return v.error("the `enableInnerCDN` is disabled in PK room"),r.error(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.FAILED,code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!I(o))return v.error("`enable` is invalid"),r.error(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> enable"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};e.setCDNEnabel(o);const s={version:2,output:{inCDNModel:o?mi.OPEN:mi.STOP}},{code:n}=yield new ai(s,this.cdnValues).execute(e,t);if(n!==O.SUCCESS)return v.error(`enableInnerCDN failed -> code: ${n}`),r.error(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.FAILED,code:n,msg:"signal error"},{logSource:i.RTC}),{code:O.SIGNAL_ERROR};const a=e.getCDNUris();if(a&&a.broadcast!==Er.SPREAD)return v.info("enableInnerCDN succeed"),r.info(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.SUCCESSED,enable:o},{logSource:i.RTC}),{code:O.SUCCESS};const{code:c}=yield Kr(e);return c===O.SUCCESS?(v.info("enableInnerCDN succeed"),r.info(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.SUCCESSED,enable:o},{logSource:i.RTC}),{code:O.SUCCESS}):(v.error(`enableInnerCDN failed -> code: ${c}`),r.error(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.FAILED,code:c,msg:""},{logSource:i.RTC}),{code:c})}))}}!function(e){e[e.AnchorToViewer=1]="AnchorToViewer",e[e.ViewerToAnchor=2]="ViewerToAnchor"}(Ci||(Ci={}));class gi extends br{constructor(e){super(),this.livingType=e}execute(e,t){var r;return f(this,void 0,void 0,(function*(){const{code:i,data:o}=yield e.context.rtcIdentityChange(e.roomId,Ci.ViewerToAnchor,this.livingType);if(i!==a.SUCCESS||!o)return{code:i};e.initWithRoomData(o);e.getResourcesByUserId(e.crtUserId).length>0&&t.push(new Br);const s=null===(r=o.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===r?void 0:r.value;return s&&e.setCDNUris(JSON.parse(s)[0]),{code:i,data:o}}))}}class fi extends ni{constructor(e,t,r,i,o,s,n,a,c,d){super(e,t,r,mr.LIVE,i,o,n,a,c,d),this._livingType=s,this._mcuConfigBuilder=new hi(this._invoker,this._isValidResourceId.bind(this))}_initAfterCatchRoomData(e){if(this._store.isUpgrade&&this._afterChangedRole(e),this._store.isMainRoom){const t=((e,t)=>{const r={};return t.forEach((t=>{const i=JSON.parse(t.value),{inviterRoomId:o,inviteeRoomId:s}=i;r[e===o?s:o]=JSON.parse(t.value)})),r})(this._roomId,e.roomInfo);this._roomPKHandler=new Ei(this._invoker,t,(e=>({headers:this._getRTCReqestHeaders(e),pushOtherRooms:this._getPushOtherRoomsParams()})),this._context,this._runtime,this._service,this._initOptions,this,super._registerPKMsgListener.bind(this),this._onJoinedPKRoom.bind(this),this._clientSessionId)}}__innerInit(e,t,o,n,a){const c=Object.create(null,{__innerInit:{get:()=>super.__innerInit}});return f(this,void 0,void 0,(function*(){if(!s("livingType",o,(e=>e===Ri.AUDIO||e===Ri.VIDEO)))return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> livingType"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};const{code:d,data:_}=yield c.__innerInit.call(this,e,t,o,n,a);return d===O.SUCCESS&&_&&this._initAfterCatchRoomData(_),{code:d,data:_}}))}__innerInitByIdentityChange(){return f(this,void 0,void 0,(function*(){const{code:e,data:t}=yield this._invoker.push(new gi(this._livingType));return e===a.SUCCESS&&t&&(this._initAfterCatchRoomData(t),this._initWithRoomData(t.offlineKickTime),r.info(L.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:A.SUCCESSED,roomData:t},{logSource:i.RTC})),e}))}publish(e){const t=Object.create(null,{publish:{get:()=>super.publish}});return f(this,void 0,void 0,(function*(){return this._store.isMainRoom?t.publish.call(this,e):(v.warn("the `publish` is disabled in PK room "),r.error(L.L_ABSTRACT_ROOM_PUBLISH_R,{status:A.FAILED,code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}unpublish(e){const t=Object.create(null,{unpublish:{get:()=>super.unpublish}});return f(this,void 0,void 0,(function*(){return this._store.isMainRoom?t.unpublish.call(this,e):(v.warn("the `unpublish` is disabled in PK room "),r.error(L.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:A.FAILED,code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}_isValidResourceId(e){var t;const{userId:r}=Ot(e),i=!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>vt(t)===e)));let o=!1;const{code:s,roomPKHandler:n}=this.getRoomPKHandler();if(s!==O.SUCCESS||!n)return i;const a=n.getJoinedPKRooms(),c=[];return Object.values(a).map((e=>{c.push(...e.getRemoteTracks())})),o=c.some((t=>e===t.getTrackId())),i||o}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._store.isMainRoom?this._mcuConfigBuilder:(v.error("the `getMCUConfigBuilder` is disabled in PK room"),{code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}enableInnerCDN(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new Si(this._mcuConfigBuilder.__innerGetValues(),e))}))}_resourceHandle(e,t,r){const i=Object.create(null,{_resourceHandle:{get:()=>super._resourceHandle}});return f(this,void 0,void 0,(function*(){i._resourceHandle.call(this,e,t,r)}))}_afterChangedRole(e){const t=Vt(e,this._roomId),r=this._context.getCurrentId(),i=Object.keys(t);setTimeout((()=>{var o;const s=i.filter((e=>e!==r));s.length>0&&this._callAppListener("onUserJoin",s);for(const e in t)e!==r&&this._resourceHandle({uris:t[e]},Gt.TOTAL_CONTENT_RESOURCE,e);if(!(null===(o=e.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===o?void 0:o.value))return;const n=this._store.getCDNUris();(null==n?void 0:n.push_mode)===pi.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 f(this,void 0,void 0,(function*(){this._invoker.push(new Ti(e,(e=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(e)})),this._roomPKHandler))}))}_getPushOtherRoomsParams(){const e=[];if(!this.isMainRoom()||!this._roomPKHandler)return e;const t=this._roomPKHandler.getJoinedPKRooms();for(const r in t){const i=t[r].getSessionId(),o=this._roomPKHandler.getPKInfo(r);if(!o)continue;const{inviterUserAutoMix:s,inviteeUserAutoMix:n,inviterUserId:a}=o,c=this._context.getCurrentId()===a;e.push({roomId:r,sessionId:i,autoMix:c?!!s:!!n})}return e}getRoomPKHandler(){return this._store.isMainRoom?(r.info(L.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:A.SUCCESSED},{logSource:i.RTC}),{code:O.SUCCESS,roomPKHandler:this._roomPKHandler}):(v.error("the `getRoomPKHandler` is disabled in PK room"),r.error(L.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:A.SUCCESSED,code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}_quitAllPKRoom(){return f(this,void 0,void 0,(function*(){const e=this._roomPKHandler.getJoinedPKRooms();for(const t in e)this._roomPKHandler.leaveOtherRoom(e[t]);r.info(L.L_LIVING_ROOM_QUIT_ALL_PK_ROOM_O,{status:A.SUCCESSED,roomIds:Object.keys(e)},{logSource:i.RTC})}))}isMainRoom(){return this._store.isMainRoom}}class vi extends ni{constructor(e,t,r,i,o,s,n,a,c,d=mr.RTC){super(e,t,r,d,i,o,s,n,a,c)}}const Oi=new class{constructor(){this.queue=[],this.locked=!1,this.taskCount=0}checkToStart(){return f(this,void 0,void 0,(function*(){if(0===this.queue.length||this.locked)return;this.locked=!0;const{resolve:e,task:t,reject:r}=this.queue.shift();let i;try{i=yield t(),e(i)}catch(e){r(e)}this.locked=!1,this.checkToStart()}))}push(e,t=""){const r=new Promise(((t,r)=>{this.queue.push({resolve:t,task:e,reject:r})}));return this.checkToStart(),r}},Li=(e,t="")=>Oi.push(e,t);class Ai{constructor(e,t,r,i){this._context=e,this._useMutilPeerC=i,this._rtcToken="",this._liveUrl="",this._subTracks=[],this._clientSessionId=jt(),this._livingType=null,this._mediaType=null,this._subTiny=!1,this._fromRetry=!1,this._appListener=null,this._service=new Yt(t,e,r.mediaServer),this._peerCManager=new yr(this._useMutilPeerC,this._context.getCurrentId(),this._reTryExchange.bind(this),this._context.getCurrentId())}_getReqHeaders(e){return f(this,void 0,void 0,(function*(){const t=this._context.getCurrentId(),r=t;if(!this._rtcToken){const{code:t,data:i}=yield this._context.getRTCToken(r,mr.LIVE,e);if(t!==a.SUCCESS)return v.error(`getRTCToken failed: ${t}`),{code:O.SIGNAL_ERROR};this._rtcToken=i.rtcToken}return{code:O.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:t,RoomId:r,RoomType:mr.LIVE,Token:this._rtcToken,"Peer-Connection-Id":this._pcName,"Client-Session-Id":this._clientSessionId}}}))}_clearSubscribeInfo(){var e;this._liveUrl="",this._livingType=null,this._mediaType=null,this._subTiny=!1,this._subTracks.length=0,null===(e=this._pc)||void 0===e||e.destroy(),this._pc=null}_reTryExchange(){var e;return f(this,void 0,void 0,(function*(){this._fromRetry=!0;const{code:t}=yield this.subscribe(this._liveUrl,this._livingType,this._mediaType,this._subTiny);t===O.SUCCESS&&(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer())}))}subscribe(e,t,r,i=!1){return f(this,void 0,void 0,(function*(){return Li((()=>this.__subscribe(e,t,r,i)),"audience-client-sub")}))}__subscribe(e,t,o,s=!1){var n;return f(this,void 0,void 0,(function*(){r.info(L.L_AUDIENCE_CLIENT_SUBSCRIBE_T,{liveUrl:e,livingType:t,mediaType:o,subTiny:s},{logSource:i.RTC});const a=[];if(Bt(this._context.getNaviInfo()))return r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:O.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:i.RTC}),{code:O.PACKAGE_ENVIRONMENT_ERROR,tracks:a};if(!this._fromRetry&&(null===(n=this._pc)||void 0===n||n.clearReTryExchangeTimer()),this._fromRetry=!1,!p(e))return v.error(`liveUrl is invalid: ${e}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:`params error -> liveUrl: ${e}`},{logSource:i.RTC}),{code:O.PARAMS_ERROR,tracks:a};if(![Ri.AUDIO,Ri.VIDEO].includes(t))return v.error(`livingType is invalid: ${t}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:`params error -> livingType: ${t}`},{logSource:i.RTC}),{code:O.PARAMS_ERROR,tracks:a};if(![He.AUDIO_ONLY,He.VIDEO_ONLY,He.AUDIO_VIDEO].includes(o))return v.error(`mediaType is invalid: ${o}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:`params error -> -> mediaType: ${o}`},{logSource:i.RTC}),{code:O.PARAMS_ERROR,tracks:a};if(this._liveUrl&&this._liveUrl!==e)return r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:O.BROADCAST_SUB_LIST_NOT_EMPTY,msg:"repeat subscribe"},{logSource:i.RTC}),{code:O.BROADCAST_SUB_LIST_NOT_EMPTY,tracks:a};if(!this._pc){const{pcName:e,pc:t}=this._peerCManager.createPeerCList(a)[0];this._pc=t,this._pcName=e,this._pc.on(Nr.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this._pc.registerReportListener(this._reportListener),this._pc.__reportR3R4ToPolaris()}this._liveUrl=e;const{code:c,headers:d}=yield this._getReqHeaders(t);if(c!==O.SUCCESS)return r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:c,msg:""},{logSource:i.RTC}),{code:c,tracks:a};const _=`rc_mcu_${Date.now()}`,u="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new pt(u,_),new mt(u,_)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const l={sdp:yield this._pc.createOffer(!0),liveUrl:e,mediaType:o,simulcast:s?zt.TINY:zt.NORMAL,switchstream:!1},h=yield this._service.broadcastSubscribe(d,l);if(h.code!==O.SUCCESS)return v.error(`andience subscribe failed: ${h.code}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:h.code,msg:""},{logSource:i.RTC}),{code:h.code,tracks:a};const R=h.data;if(R.resultCode!==O.SUCCESS)return v.error(`andience subscribe failed! code: ${R.resultCode}; message: ${R.message}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:R.resultCode,msg:""},{logSource:i.RTC}),{code:R.resultCode,tracks:a};v.debug(`andience subscribe success: ${e}`),this._livingType=t,this._mediaType=o,this._subTiny=s;const{sdp:m,subscribedList:C}=R,T=[];return C.forEach((e=>{const{mediaType:t}=e,r=this._subTracks[t];T.push(r),r.__innerSetRemoteMuted(!0)})),this._pc.setRemoteAnswer(m.sdp),r.info(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.SUCCESSED,liveUrl:e},{logSource:i.RTC}),{code:O.SUCCESS,tracks:T}}))}unsubscribe(){return f(this,void 0,void 0,(function*(){return Li((()=>this.__unsubscribe()),"audience-client-unsub")}))}__unsubscribe(){var e;return f(this,void 0,void 0,(function*(){if(r.info(L.L_AUDIENCE_CLIENT_UNSUBSCRIBE_T,{liveUrl:this._liveUrl},{logSource:i.RTC}),null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer(),!this._rtcToken||!this._liveUrl)return r.warn(L.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:A.FAILED,code:"",msg:"Address does not exist, without unsubscribe"},{logSource:i.RTC}),{code:O.SUCCESS};const{headers:t}=yield this._getReqHeaders(),{code:o}=yield this._service.broadcastExit(t);return o!==O.SUCCESS?(v.error(`broadcast unsubscribe failed: ${o}`),r.error(L.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:A.FAILED,code:o,msg:""},{logSource:i.RTC})):(v.debug("broadcast unsubscribe success"),r.info(L.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:A.SUCCESSED,liveUrl:this._liveUrl},{logSource:i.RTC})),this._clearSubscribeInfo(),{code:o}}))}registerReportListener(e){this._reportListener=e}registerTrackEventListener(e){this._appListener=e}_onTrackReady(e){var t,r;const i=e.receiver.track,o="audio"===i.kind?He.AUDIO_ONLY:He.VIDEO_ONLY,s=this._subTracks[o];s.__innerSetMediaStreamTrack(i);try{null===(r=null===(t=this._appListener)||void 0===t?void 0:t.onTrackReady)||void 0===r||r.call(t,s)}catch(e){v.error(e)}}}var Ni,Di;!function(e){e.RTMP="rtmp",e.FLV="flv",e.HLS="hls"}(Ni||(Ni={})),function(e){e[e.NOT_HTTPS=0]="NOT_HTTPS",e[e.HTTPS=1]="HTTPS"}(Di||(Di={}));const ki=Object.assign(Object.assign({},kt(Ke.W176_H144)),{frameRate:Ut(Ge.FPS_15)});class yi{constructor(e,t,r,i,o,s,n,a=jt()){this._context=e,this._runtime=t,this._initOptions=r,this._roomId=i,this._joinResData=o,this.livingType=s,this._useMutilPeerC=n,this._clientSessionId=a,this._roomAnchorList=[],this._roomRes={},this._roomAnchorRes={},this._remoteTracks={},this._appListener=null,this._pc=null,this._subscribedList=[],this._sessionId="",this._destroyed=!1,this._isPulling=!1,this._pullTime=0,this._reportListener=null,this._setInitData(),this._service=new Yt(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new Dr(this._context,this._runtime,this._roomId,this,_r.Audience),this._polarisReport.sendR1(),this._peerCManager=new yr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._context.registerRTCSignalListener((e=>f(this,void 0,void 0,(function*(){const{time:t,type:r,roomId:i}=this._context.decodeRtcNotify(e);if(v.warn(`registerRTCSignalListener -> ${JSON.stringify({time:t,type:r,roomId:i})}`),1===r)this._startPull(i,t)}))))}_startPull(e,t){return f(this,void 0,void 0,(function*(){if(this._isPulling)return;this._isPulling=!0;if(this._pullTime>t)return void(this._isPulling=!1);const{code:r,data:i}=yield this._context.pullRTCRoomEntry(e);if(r===a.SUCCESS){this._isPulling=!1,this._pullTime=i.syncTime||0;const t=(null==i?void 0:i.kvEntries)||[];v.info(`_startPull -> ${JSON.stringify(t)}`),this.singalDataChange(t,e)}}))}_setInitData(){const{sessionId:e,remoteUserIds:t,remoteRTCUris:r,remoteMUCUris:i,remoteTracks:o,CDNUris:s}=((e,t)=>{const r=t.filter((e=>"RC_RTC_SESSIONID"===e.key))[0],i=r?r.value:"",o=t.filter((e=>"RC_ANCHOR_LIST"===e.key)).map((e=>JSON.parse(e.value||"[]")))[0],s=t.filter((e=>e.key.includes("RC_RES_"))).map((e=>JSON.parse(e.value||"{}"))),n=s.length?JSON.parse(s[0].mcu_uris||"[]"):[],a=[];n.forEach((t=>{const{mediaType:r,tag:i}=t,o=r===He.AUDIO_ONLY?new pt(i,"",e):new mt(i,"",e);a.push(o)}));const c=[],d=[];s.forEach((e=>{const t=JSON.parse(e.uris||"[]");c.push(...t),t.forEach((e=>{const{mediaType:t,tag:r,msid:i}=e,o=i.split("_")[0],s=t===He.AUDIO_ONLY?new pt(r,o):new mt(r,o);d.push(s)}))}));const _=t.filter((e=>"RC_CDN"===e.key)).map((e=>{const t=JSON.parse(e.value||"[]");return JSON.parse(t.cdn_uris)[0]}))[0];return{sessionId:i,remoteUserIds:o||[],remoteRTCUris:c,remoteMUCUris:n,remoteRTCTracks:d,remoteMCUTracks:a,remoteTracks:[...d,...a],CDNUris:_||{}}})(this._roomId,this._joinResData.kvEntries);this._sessionId=e,this._roomAnchorList=t,o.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]})),i.forEach((e=>{const{mediaType:t,tag:r}=e,i=[this._roomId,r,t].join("_");this._roomRes[i]=e})),r.forEach((e=>{const t=vt(e);this._roomRes[t]=e}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinLivingRoomAsAudience` to catch another instance.";return v.warn(e),O.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(e,t){var o;if(r.info(L.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_T,{singalData:e,roomId:t,userId:this._context.getCurrentId()},{logSource:i.RTC}),t!==this._roomId)return v.warn(`singalDataChange -> not the current room data: data roomId: ${t}, current roomId: ${this._roomId}`),void r.error(L.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:A.FAILED,code:"",msg:`id inconsistency -> params id:${t},current id:${this._roomId}`},{logSource:i.RTC});v.debug("singalDataChange -> singalData:",JSON.stringify(e||{}));const s=[],n=null===(o=e.filter((e=>"RC_CDN"===e.key))[0])||void 0===o?void 0:o.value;n&&this._diffCDNUris(JSON.parse(JSON.parse(n).cdn_uris)[0]),e.forEach((e=>{const{key:t,value:r,timestamp:i,uid:o}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),i=JSON.parse(e.uris||"[]");return s.push(...t),void this._diffAnchorResource(i,o)}if("RC_ANCHOR_LIST"===t){const e=JSON.parse(r||"[]"),{joinUserIds:t,leftUserIds:i}=this._diffAnchorList(e);t.length>0&&this._handleNewJoinedAnchor(t),i.length>0&&this._handleLeftedAnchor(i)}})),this._diffRoomResource(s),r.info(L.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:A.SUCCESSED,singalData:e,roomId:t,userId:this._context.getCurrentId()},{logSource:i.RTC})}_diffAnchorList(e){const t=e.filter((e=>this._roomAnchorList.indexOf(e)<0));return{leftUserIds:this._roomAnchorList.filter((t=>e.indexOf(t)<0)),joinUserIds:t}}_handleNewJoinedAnchor(e){this._roomAnchorList.push(...e),this._callAppListener("onAnchorJoin",e)}_handleLeftedAnchor(e){return f(this,void 0,void 0,(function*(){this._roomAnchorList=this._roomAnchorList.filter((t=>!(e.indexOf(t)>-1)));const t=[];e.forEach((e=>{t.push(...this.getRemoteTracksByUserId(e)),delete this._roomAnchorRes[e]})),t.length&&(yield this.unsubscribe(t),t.forEach((e=>delete this._remoteTracks[e.getTrackId()]))),this._callAppListener("onAnchorLeave",e)}))}_diffRoomResource(e){return f(this,void 0,void 0,(function*(){const t=[],r=[],i=[];e.forEach((e=>{const r=vt(e),{userId:o,tag:s,mediaType:n}=Ot(r),a=[this._roomId,s,n].join("_");if(!this._remoteTracks[a]){const r=n===He.AUDIO_ONLY?new pt(s,"",this._roomId):new mt(s,"",this._roomId);t.push(r),this._remoteTracks[a]=r,this._roomRes[r.getTrackId()]=e}i.push(a)})),Object.keys(this._remoteTracks).forEach((e=>{i.indexOf(e)<0&&this._remoteTracks[e].isMCUTrack()&&r.push(this._remoteTracks[e])})),t.length>0&&this._callAppListener("onTrackPublish",t),r.length>0&&this._onUserUnpublish(r,"onTrackUnpublish")}))}_diffAnchorResource(e,t){return f(this,void 0,void 0,(function*(){const r=this._roomAnchorRes[t]||(this._roomAnchorRes[t]=[]),{publishedList:i,unpublishedList:o,modifiedList:s}=Nt(r,e);if(i.length){const e=r.map(vt),t=[],o=[];if(i.forEach((i=>{const s=vt(i),n=e.indexOf(s),{userId:a,tag:c,mediaType:d}=Ot(s);n>-1?r[n]=i:r.push(i);let _=this._remoteTracks[s];this._roomRes[s]=i,_?_.isSubscribed()&&t.push(_):(_=d===He.AUDIO_ONLY?new pt(c,a):new mt(c,a),this._remoteTracks[s]=_,o.push(_)),_.__innerSetRemoteMuted(0===i.state)})),t.length){const e=t.map((e=>e.getTrackId()));v.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:r}=yield Li((()=>this._subscribeHandle(t,!0)));r!==O.SUCCESS&&v.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(e)}`)}this._callAppListener("onAnchorTrackPublish",o)}if(o.length){const e=o.map(vt);for(let t=r.length-1;t>=0;t-=1){const i=r[t];e.includes(vt(i))&&r.splice(t,1)}const t=o.map((e=>{const t=vt(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t,"onAnchorTrackUnpublish")}if(s.length){const e=r.map(vt);for(let t=0;t<s.length;t++){const i=s[t],o=vt(i),n=e.indexOf(o);r[n].state=i.state;const a=this._remoteTracks[o];a.__innerSetRemoteMuted(0===i.state),a.isAudioTrack()?this._callAppListener("onAudioMuteChange",a):this._callAppListener("onVideoMuteChange",a)}}}))}_onUserUnpublish(e,t){return f(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;v.info(`${e} callback ->`,...t);const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){v.error(e)}}_reTryExchange(){return f(this,void 0,void 0,(function*(){Li((()=>f(this,void 0,void 0,(function*(){var e;const{reqBody:t}=yield this._createSubscribeParams(this._subscribedList,{},!0),r=yield this._exchangeHandle(t);if(r.code!==O.SUCCESS)return v.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:o}=r.data;if(o!==O.SUCCESS)return v.error(`reTryExchange failed: ${o}`),{code:o};this._pc.clearReTryExchangeTimer();const s=this._subscribedList.filter((e=>e.track.isMCUTrack()));if(s.length>0){const t=s[0].track.getTrackId(),r=null===(e=this._roomRes[t])||void 0===e?void 0:e.msid,o=[this._roomId,"RongCloudRTC"].join("_");i.sdp=i.sdp.replace(new RegExp(r,"g"),o)}const n=yield this._pc.setRemoteAnswer(i.sdp);return n!==O.SUCCESS?{code:n}:void 0}))),"audience-retry-exchange")}))}_createSubscribeParams(e,t,r){return f(this,void 0,void 0,(function*(){const i=yield this._pc.createOffer(r),o={resolutionInfo:[]},s={min:0,max:0};Object.keys(t).forEach((e=>{const{mediaStream:r,tinyStream:n}=t[e];[r,n].forEach(((t,r)=>{var n;const a=1===r?[e,"tiny"].join("_"):e;i.sdp=null===(n=i.sdp)||void 0===n?void 0:n.replace(new RegExp(t.id,"g"),a);const c=t.getVideoTracks()[0];if(!c)return;const d=0===r,{width:_,height:u,frameRate:l}=d?gt(c):ki;o.resolutionInfo.push({trackId:c.id,simulcast:d?zt.NORMAL:zt.TINY,resolution:`${_}x${u}`});const h=We(_,u),R=Ye(l);s.min+=h.minBitrate*R,s.max+=h.maxBitrate*R}))}));return{reqBody:{sdp:i,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?zt.TINY:zt.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:s,offer:i}}))}_subscribeHandle(e,t=!1){var o;return f(this,void 0,void 0,(function*(){r.info(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_T,{trackIds:e.map($t),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:t},{logSource:i.RTC});if(this._assertRoomDestroyed())return r.error(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:O.ROOM_HAS_BEEN_DESTROYED,msg:"room destroyed"},{logSource:i.RTC}),{code:O.ROOM_HAS_BEEN_DESTROYED};if(!s("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof Rt||e.track instanceof Rt))),!0))return r.error(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};const{pc:n,pcName:a}=this._peerCManager.createPeerCList(e)[0];this._pc=n,this._pc.__reportR3R4ToPolaris(),this._pcName=a,this._pc.registerReportListener(this._reportListener),this._addPeerCEvent();const c=this._subscribedList.map((e=>Object.assign({},e))),_=e.map((e=>e instanceof Rt?{track:e}:e));let u=!1;const l=[];return _.forEach((e=>{const t=e.track.getTrackId();l.push(t);const r=c.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:c.push(e),u=!0)})),u||t?(null===(o=this._polarisReport)||void 0===o||o.sendR2(Tr.SUBSCRIBE,Ir.BEGIN,l),r.info(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:A.SUCCESSED,trackIds:e.map($t),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:t},{logSource:i.RTC}),this._updateSubListHandle(c,!0)):(r.warn(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:"",msg:"repeat subscribe"},{logSource:i.RTC}),{code:O.SUCCESS})}))}_addPeerCEvent(){this._pc.on(Nr.__INNER_EVENT_TRACK_READY__,(e=>{const t=e.streams[0].id,r=e.receiver.track,i=[t,"audio"===r.kind?He.AUDIO_ONLY:He.VIDEO_ONLY].join("_"),o=this._remoteTracks[i];o?(o.__innerSetMediaStreamTrack(r),this._callAppListener("onTrackReady",o)):v.warn("cannot found RCRemoteTrack:",r.id)}))}_getReqHeaders(){const e=this._context.getCurrentId();return{"App-Key":this._context.getAppkey(),RoomId:e,Token:this._joinResData.token,RoomType:mr.LIVE,UserId:e,"Session-Id":this._sessionId,"Peer-Connection-Id":this._pcName,"Client-Session-Id":this._clientSessionId}}_exchangeHandle(e){return this._service.broadcastSubscribe(this._getReqHeaders(),e)}_updateSubListHandle(e,t=!1){var r;return f(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:O.ROOM_HAS_BEEN_DESTROYED};if(!s("resources",e,(()=>d(e)&&e.every((e=>e instanceof Rt||e.track instanceof Rt))),!0))return{code:O.PARAMS_ERROR};let i=e.map((e=>e instanceof Rt?{track:e}:Object.assign({},e)));const o={};i=i.filter((e=>{const t=e.track.getTrackId();return!o[t]&&(o[t]=!0)})).map((e=>Object.assign({},e)));const n=this._subscribedList.map((e=>Object.assign({},e)));if(!t){let e=!1;if(i.forEach((t=>{const r=n.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);n.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),n.length&&(e=!0),!e)return{code:O.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(i.map((e=>e.track)));const{reqBody:a}=yield this._createSubscribeParams(i,{},!1),c=yield this._exchangeHandle(a);if(n.length){const e=[];n.forEach((t=>{e.push(t.track.getTrackId())})),null===(r=this._pc.reportParser)||void 0===r||r.clearLatestPacketsRecv(e)}if(c.code!==O.SUCCESS)return{code:c.code};const{sdp:_,resultCode:u,message:l,subscribedList:h}=c.data;if(u!==O.SUCCESS)return v.error("change subscribe list failed:",l,u),{code:u};i.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:i}=Ot(t.getTrackId()),o=[i,r].join("_");_.sdp=_.sdp.replace(new RegExp(e,"g"),o)}}));const R=yield this._pc.setRemoteAnswer(_.sdp);if(R!==O.SUCCESS)return{code:R};const p=null==h?void 0:h.map((e=>`${e.msid}_${e.mediaType}`)),m=i.filter((e=>{if(e.track.isMCUTrack()){const t=this._roomRes[e.track.getTrackId()],r=`${t.msid}_${t.mediaType}`;return p.includes(r)}return null==p?void 0:p.includes(e.track.getTrackId())})),C=null==m?void 0:m.map((e=>`${e.track.getTrackId()}`)),T=i.filter((e=>!(null==C?void 0:C.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=m.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...m),T.length?{code:O.SUCCESS,failedList:T}:{code:O.SUCCESS}}))}_diffCDNUris(e){return f(this,void 0,void 0,(function*(){if(this._CDNUris.url&&!e.url)return this._callAppListener("onCDNInfoDisable"),void(this._CDNUris=e);(!this._CDNUris||!this._CDNUris.url&&e.url)&&this._callAppListener("onCDNInfoEnable",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`});const t=this._CDNUris.w&&e.w&&this._CDNUris.w!==e.w,r=this._CDNUris.h&&e.h&&this._CDNUris.h!==e.h,i=this._CDNUris.fps&&e.fps&&this._CDNUris.fps!==e.fps;(t||r||i)&&this._callAppListener("onCDNInfoChange",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`}),this._CDNUris=e}))}_getCDNPlayUrl(e){return f(this,void 0,void 0,(function*(){const{w:t,h:r,fps:i}=e,o=this._initOptions.pullInnerCDNProtocol||Ni.FLV,s=this._initOptions.pullInnerCDNUseHttps===Di.NOT_HTTPS?Di.NOT_HTTPS:Di.HTTPS;if(!this._CDNUris.url)return v.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${O.CDN_RESOURCE_IS_EMPTY}`),{code:O.CDN_RESOURCE_IS_EMPTY};const n={"App-Key":this._context.getAppkey(),Token:this._joinResData.token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},a=[];t&&a.push(`w=${t}`),r&&a.push(`h=${r}`),i&&a.push(`fps=${i}`),a.push(`kind=${o}`),a.push(`is_https=${s}`);const c=a.join("&");let d=`${this._CDNUris.url}?`;c&&(d+=c);const{code:_,res:u}=yield this._service.getCDNResourceInfo(n,d);return _!==O.SUCCESS?(v.error(`getCDNPlayUrl failed: ${_}`),{code:_}):(v.info(`getCDNPlayUrl success: ${null==u?void 0:u.data.pull_url}`),{code:_,CDNPlayUrl:null==u?void 0:u.data.pull_url})}))}getCDNPlayUrl(e,t){return f(this,void 0,void 0,(function*(){if(r.info(L.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_T,{resolution:e,fps:t},{logSource:i.RTC}),e&&!yt(e))return v.error("`resolution` is invalid"),r.error(L.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> resolution"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(t&&!bt(t))return v.error("`fps` is invalid"),r.error(L.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> fps"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};const{width:o,height:s}=e?kt(e):{width:null,height:null},n=t?Ut(t):null,a={};return o&&(a.w=o),s&&(a.h=s),n&&(a.fps=n),r.info(L.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:A.SUCCESSED,resolution:e,fps:t},{logSource:i.RTC}),this._getCDNPlayUrl(a)}))}subscribe(e){return f(this,void 0,void 0,(function*(){return Li((()=>this._subscribeHandle(e,!1)),"audience-sub")}))}addSubscribeTask(e){return f(this,void 0,void 0,(function*(){return Li((()=>this._subscribeHandle(e,!1)),"audience-sub")}))}__unsubscribe(e){var t;return f(this,void 0,void 0,(function*(){if(r.info(L.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_T,{trackIds:e.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:i.RTC}),!s("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof Rt))),!0))return v.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),r.error(L.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};const o=this._subscribedList.map((e=>Object.assign({},e))).filter((t=>!e.includes(t.track)));return null===(t=this._polarisReport)||void 0===t||t.sendR2(Tr.SUBSCRIBE,Ir.END,e.map((e=>e.getTrackId()))),r.info(L.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:A.SUCCESSED,trackIds:e.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:i.RTC}),this._updateSubListHandle(o,!1)}))}unsubscribe(e){return f(this,void 0,void 0,(function*(){return Li((()=>this.__unsubscribe(e)),"audience-unsub")}))}addUnsubscribeTask(e){return f(this,void 0,void 0,(function*(){return Li((()=>this.__unsubscribe(e)),"audience-unsub")}))}__destroy(e){var t,r;return f(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(t=this._audioLevelReport)||void 0===t||t.clearAudioLevelReportTimer(),e&&(yield this._context.quitLivingRoomAsAudience(this._roomId)),yield this._service.broadcastExit(this._getReqHeaders()),null===(r=this._pc)||void 0===r||r.destroy(),this._polarisReport=null,this._context.registerRTCSignalListener(void 0))}))}getRemoteTrack(e){return this._remoteTracks[e]}__getPC(){return this._peerCManager.getPCList()}getLocalTrack(e){return{}}__onReconnected(){return f(this,void 0,void 0,(function*(){const{code:e}=yield this._context.joinLivingRoomAsAudience(this._roomId,mr.LIVE);e!==a.SUCCESS&&v.error("join living room error when on reconnected")}))}registerRoomEventListener(e){this._appListener=e}onAudioLevelChange(e,t){var o;null===(o=this._audioLevelReport)||void 0===o||o.clearAudioLevelReportTimer(),this._audioLevelReport=new kr(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3),r.info(L.L_AUDIENCE_LIVING_ROOM_AUDIO_LEVEL_CHANGE_O,{status:A.SUCCESSED,handler:null==e?void 0:e.name,gap:t},{logSource:i.RTC})}registerReportListener(e){this._reportListener=e}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}getSessionId(){return this._sessionId}getRemoteUserIds(){return this._roomAnchorList}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getRemoteTracks(){const e=[],t=[];for(const e in this._remoteTracks){if(2===t.length)break;const r=this._remoteTracks[e];r.isMCUTrack()&&t.push(r)}return this._roomAnchorList.forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),[...t,...e]}getRemoteRTCTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()||e.push(r)}return e}getRemoteMCUTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()&&e.push(r)}return e}getCDNInfo(){return this._CDNUris.w?{resolution:`W${this._CDNUris.w}_H${this._CDNUris.h}`,fps:`FPS_${this._CDNUris.fps}`,CDNEnable:this._CDNUris.enableInnerCDN}:{CDNEnable:!1}}getClientSessionId(){return this._clientSessionId}}class bi{constructor(e){this._context=e,this._isElectron=/Electron/.test(navigator.userAgent)}_getMediaStream(e,t="getUserMedia"){return f(this,void 0,void 0,(function*(){try{const r=this.setConstraintsConfig(e),i=yield navigator.mediaDevices[t](r);return{code:O.SUCCESS,stream:i}}catch(e){if("Permission denied"===e.message)return{code:O.BROWSER_PERMISSION_DENIED};if("Permission denied by system"===e.message)return{code:O.SYSTEM_PERMISSION_DENIED};v.error(`get user media failed -> ${e.message}`)}return{code:"getUserMedia"===t?O.GET_USER_MEDIA_FAILED:O.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),v.info(`browser supported -> ${JSON.stringify(t)}`)}return e}createMicrophoneAudioTrack(e="RongCloudRTC",t){return f(this,void 0,void 0,(function*(){if(!It(e))return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS};const o=this._context.getCurrentId();if(!o)return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID};const{stream:s,code:n}=yield this._getMediaStream({audio:{deviceId:null==t?void 0:t.micphoneId,sampleRate:null==t?void 0:t.sampleRate}});if(n!==O.SUCCESS)return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:A.FAILED,code:n,msg:"Failed to get microphone audio stream"},{logSource:i.RTC}),{code:n};const a=s.getAudioTracks()[0],c=new _t(e,o,a);return r.info(L.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:A.SUCCESSED,trackId:c.getTrackId()},{logSource:i.RTC}),{code:n,track:c}}))}createCameraVideoTrack(e="RongCloudRTC",t){return f(this,void 0,void 0,(function*(){if(!It(e))return r.error(L.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS};const o=this._context.getCurrentId();if(!o)return r.error(L.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID};const s=yt(null==t?void 0:t.resolution)?t.resolution:Ke.W640_H480,{width:n,height:a}=kt(s),{stream:c,code:d}=yield this._getMediaStream({video:{deviceId:null==t?void 0:t.cameraId,frameRate:Ut((null==t?void 0:t.frameRate)||Ge.FPS_15),width:n,height:a,facingMode:null==t?void 0:t.faceMode}});if(d!==O.SUCCESS)return r.error(L.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"Failed to get camera video stream"},{logSource:i.RTC}),{code:d};const _=c.getVideoTracks()[0],u=new ut(e,o,_);return r.info(L.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:A.SUCCESSED,trackId:u.getTrackId()},{logSource:i.RTC}),{code:d,track:u}}))}createMicrophoneAndCameraTracks(e="RongCloudRTC",t){var o,s,n,a,c,d;return f(this,void 0,void 0,(function*(){const _=[];if(!It(e))return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS,tracks:_};const u=this._context.getCurrentId();if(!u)return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID,tracks:_};const l=yt(null===(o=null==t?void 0:t.video)||void 0===o?void 0:o.resolution)?t.video.resolution:Ke.W640_H480,{width:h,height:R}=kt(l),{stream:p,code:m}=yield this._getMediaStream({video:{deviceId:null===(s=null==t?void 0:t.video)||void 0===s?void 0:s.cameraId,frameRate:Ut((null===(n=null==t?void 0:t.video)||void 0===n?void 0:n.frameRate)||Ge.FPS_15),width:h,height:R,facingMode:null===(a=null==t?void 0:t.video)||void 0===a?void 0:a.faceMode},audio:{deviceId:null===(c=null==t?void 0:t.audio)||void 0===c?void 0:c.micphoneId,sampleRate:null===(d=null==t?void 0:t.audio)||void 0===d?void 0:d.sampleRate}});return m!==O.SUCCESS?(r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:A.FAILED,code:m,msg:"Failed to get audio and video stream of camera and microphone"},{logSource:i.RTC}),{code:m,tracks:_}):(p.getTracks().forEach((t=>{"video"===t.kind?_.push(new ut(e,u,t)):_.unshift(new _t(e,u,t))})),r.info(L.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:A.SUCCESSED,trackIds:_.map((e=>e.getTrackId()))},{logSource:i.RTC}),{code:m,tracks:_})}))}createScreenVideoTrack(e="screenshare",t){return f(this,void 0,void 0,(function*(){const r=yield this._createScreenTracks(e,!1,L.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,t);return r.code===O.SUCCESS?{code:r.code,track:r.tracks[0]}:r}))}createScreenWithAudioTracks(e="screenshare",t){return f(this,void 0,void 0,(function*(){return this._createScreenTracks(e,!0,L.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_AND_AUDIO_TRACKS_O,t)}))}_createScreenTracks(e,t,o,s){var n,a;return f(this,void 0,void 0,(function*(){if(!It(e))return r.error(o,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS};const c=this._context.getCurrentId();if(!c)return r.error(o,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID};if(!xt())return r.error(L.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:A.FAILED,code:O.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:i.RTC}),{code:O.BROWSER_NOT_SUPPORT};const d=/macintosh|mac os x/i.test(navigator.userAgent);this._isElectron&&d&&t&&r.warn(o,{status:A.INFO,code:O.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO,msg:"mac in electron not support screen share with audio"});const _=(!this._isElectron||!d)&&t;if(this._isElectron&&!E(null==s?void 0:s.chromeMediaSourceId)&&!p(null==s?void 0:s.chromeMediaSourceId))return r.error(o,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> options.chromeMediaSourceId type is string"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};const u=yt(null==s?void 0:s.resolution)?s.resolution:Ke.W1280_H720,{width:l,height:h}=kt(u),R=this._isElectron?{mandatory:{chromeMediaSourceId:null==s?void 0:s.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:l,maxWidth:l,minHeight:h,maxHeight:h}}:{frameRate:Ut((null==s?void 0:s.frameRate)||Ge.FPS_15),width:l,height:h};!(null==s?void 0:s.chromeMediaSourceId)&&this._isElectron&&(null===(n=R.mandatory)||void 0===n||delete n.chromeMediaSourceId);let m=null;_&&this._isElectron&&(null===(a=R.mandatory)||void 0===a||delete a.chromeMediaSourceId,m={mandatory:{chromeMediaSource:"desktop"}});const{stream:C,code:T}=yield this._getMediaStream({video:R,audio:m||_},this._isElectron?"getUserMedia":"getDisplayMedia");if(T!==O.SUCCESS)return r.error(o,{status:A.FAILED,code:T,msg:"Failed to get shared screen video stream"},{logSource:i.RTC}),{code:T};const I=C.getVideoTracks()[0],S=[new lt(e,c,I)];if(_){const t=C.getAudioTracks()[0];t&&S.push(new ht(e,c,t))}return r.info(o,{status:A.SUCCESSED,trackIds:S.map((e=>e.getTrackId()))},{logSource:i.RTC}),{code:T,tracks:S}}))}createLocalAudioTrack(e,t){return f(this,void 0,void 0,(function*(){if(!It(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"audio"!==t.kind)return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"Failed to create custom stream"},{logSource:i.RTC}),{code:O.CREATE_CUSTOM_TRACK_FAILED};const o=this._context.getCurrentId();if(!o)return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID};const s=new st(e,o,t);return r.info(L.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:A.SUCCESSED,trackId:s.getTrackId()},{logSource:i.RTC}),{code:O.SUCCESS,track:s}}))}createLocalVideoTrack(e,t){return f(this,void 0,void 0,(function*(){if(!It(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"video"!==t.kind)return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:A.FAILED,code:O.CREATE_CUSTOM_TRACK_FAILED,msg:"Failed to create custom stream"},{logSource:i.RTC}),{code:O.CREATE_CUSTOM_TRACK_FAILED};const o=this._context.getCurrentId();if(!o)return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID};const s=new nt(e,o,t);return r.info(L.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:A.SUCCESSED,trackId:s.getTrackId()},{logSource:i.RTC}),{code:O.SUCCESS,track:s}}))}createLocalFileTracks(e,t,o){return f(this,void 0,void 0,(function*(){if(!It(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS,tracks:[]};if(!Mt())return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:O.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:i.RTC}),{code:O.BROWSER_NOT_SUPPORT,tracks:[]};const s=t instanceof File?URL.createObjectURL(t):t;if(!T(s)&&!/^blob:/.test(s))return v.warn(`createLocalFileTracks failed: params error -> url: ${s}`),r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> file"},{logSource:i.RTC}),{code:O.PARAMS_ERROR,tracks:[]};const n=this._context.getCurrentId();return n?new Promise((t=>{const a=document.createElement("video");(null==o?void 0:o.withoutAudio)&&(a.muted=!0),a.onloadedmetadata=()=>{const c=[];let d;try{const e=a.mozCaptureStream?"mozCaptureStream":"captureStream";d=a[e]()}catch(e){v.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${s}`),v.error(e),r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:O.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:i.RTC}),t({code:O.CREATE_FILE_TRACK_FAILED,tracks:c})}const[_,u]=bi.getTracksWithOptions(d,o);_&&c.push(new dt(e,n,_,a)),u&&c.push(new ct(e,n,u,a)),0===c.length&&(a.pause(),a.src=""),a.onerror=null,r.info(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.SUCCESSED,trackIds:c.map((e=>e.getTrackId()))},{logSource:i.RTC}),t({code:O.SUCCESS,tracks:c})},a.onerror=()=>{v.error(`create RCLocalFileTrack failed -> url: ${s}`),r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:O.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:i.RTC}),t({code:O.CREATE_FILE_TRACK_FAILED,tracks:[]})},a.src=s,a.loop=!0,a.play()})):(r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID,tracks:[]})}))}createLocalTracks(e,t,o){return f(this,void 0,void 0,(function*(){const s=[];if(!It(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:A.FAILED,code:O.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:O.INVALID_TAGS,tracks:s};if(!(t instanceof MediaStream))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> stream"},{logSource:i.RTC}),{code:O.PARAMS_ERROR,tracks:s};const n=this._context.getCurrentId();if(!n)return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:A.FAILED,code:O.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:O.INVALID_USER_ID,tracks:s};const[a,c]=bi.getTracksWithOptions(t,o);return a&&s.push(new st(e,n,a)),c&&s.push(new nt(e,n,c)),r.info(L.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:A.SUCCESSED,trackIds:s.map((e=>e.getTrackId()))},{logSource:i.RTC}),{code:O.SUCCESS,tracks:s}}))}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 Ui extends bi{constructor(e,t,r){super(e),this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,gr.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new Yt(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){var t;if(e.conversationType!==C.RTC_ROOM)return!1;if(this._crtRoom instanceof fi){this._getJoinedPKRoomList().forEach((t=>{t.__parseInnerMessage(e)}))}return null===(t=this._crtRoom)||void 0===t||t.__parseInnerMessage(e),r.info(L.L_RTC_CLIENT_MESSAGE_O,{status:A.SUCCESSED,message:Object.assign(e,{content:"内容涉及隐私不予显示"})},{logSource:i.RTC}),!0}naviDataChange(e){r.info(`on navi change data => ${JSON.stringify(e)}`),this._service.detectorMediaSever()}_getJoinedPKRoomList(){const{code:e,roomPKHandler:t}=this._crtRoom.getRoomPKHandler();if(e===O.SUCCESS&&t){const e=t.getJoinedPKRooms()||{};return Object.values(e)}return[]}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(e,t,o,s,n=mr.RTC){return f(this,void 0,void 0,(function*(){if(r.info(L.L_RTC_CLIENT_JOIN_RTC_ROOM_T,{roomId:e,joinType:t,outerUserDatas:o,useMutilPeerC:s,roomType:n},{logSource:i.RTC}),this._crtRoom)return r.error(L.L_RTC_CLIENT_JOIN_RTC_ROOM_R,{status:A.FAILED,code:O.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:O.REPERT_JOIN_ROOM};const a=this._crtRoom=new vi(this._context,this._runtime,e,this._service,this._options,!1,!1,s,jt()),{code:c}=yield a.__innerInit(n,t,void 0,void 0,o);return c!==O.SUCCESS?(this._crtRoom=null,{code:c}):(a.once(si,(()=>{this._crtRoom=null})),{code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()})}))}joinCrossRTCRoom(e,t,o,s,n=mr.CROSS_MUTI){return f(this,void 0,void 0,(function*(){if(r.info(L.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_T,{roomId:e,joinType:t,outerUserDatas:o,useMutilPeerC:s,roomType:n},{logSource:i.RTC}),this._crtRoom)return r.error(L.L_RTC_CLIENT_JOIN_CROSS_RTC_ROOM_R,{status:A.FAILED,code:O.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:O.REPERT_JOIN_ROOM};const a=this._crtRoom=new vi(this._context,this._runtime,e,this._service,this._options,!1,!1,s,jt(),n),{code:c}=yield a.__innerInit(n,t,void 0,void 0,o);return c!==O.SUCCESS?(this._crtRoom=null,{code:c}):(a.once(si,(()=>{this._crtRoom=null})),{code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()})}))}joinLivingRoom(e,t,o,s,n){return f(this,void 0,void 0,(function*(){if(r.info(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_T,{roomId:e,livingType:t,joinType:o,outerUserDatas:s,useMutilPeerC:n},{logSource:i.RTC}),this._crtRoom)return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:A.FAILED,code:O.REPERT_JOIN_ROOM,msg:`Join the room repeatedly -> roomId: ${e}`},{logSource:i.RTC}),{code:O.REPERT_JOIN_ROOM};const a=this._crtRoom=new fi(this._context,this._runtime,e,this._service,this._options,t,!1,!0,n),{code:c}=yield a.__innerInit(mr.LIVE,o,t,void 0,s);if(c!==O.SUCCESS)return this._crtRoom=null,{code:c};a.once(si,(()=>{this._crtRoom=null}));const d={code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()};return a.__getCDNPushMode()===pi.MANUAL&&Object.assign(d,{CDNEnable:a.__getCDNEnable()}),d}))}getAudienceClient(e){return this._audience||(this._audience=new Ai(this._context,this._runtime,this._options,e)),r.info(L.L_RTC_CLIENT_GET_AUDIENCE_CLIENT_O,{status:A.SUCCESSED},{logSource:i.RTC}),this._audience}_onIMStatusChange(e){if(v.debug(`signal server connection state change: ${e}`),r.info(L.L_RTC_CLIENT_CONNECTION_STATE_S,{status:A.SUCCESSED,data:e},{logSource:i.RTC}),e===u.CONNECTED){if(this._service.detectorMediaSever(),this._crtRoom instanceof fi){this._getJoinedPKRoomList().forEach((e=>{e.__onReconnected()}))}this._crtRoom&&this._crtRoom.__onReconnected()}}_onIMDisconnect(){r.info(L.L_RTC_CLIENT_DISCONNECT_S,{status:A.SUCCESSED},{logSource:i.RTC}),v.debug("TODO -> on IM disconnect")}_onIMUninit(){r.info(L.L_RTC_CLIENT_DESTROY_S,{status:A.SUCCESSED},{logSource:i.RTC}),v.debug("TODO -> on IM client ondestroy")}leaveRoom(e){var t,o;return f(this,void 0,void 0,(function*(){return r.info(L.L_RTC_CLIENT_LEAVE_ROOM_T,{userId:this._context.getCurrentId(),roomId:null===(t=this._crtRoom)||void 0===t?void 0:t.getRoomId()},{logSource:i.RTC}),this._crtRoom?(yield this._crtRoom.__destroy(!0),v.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),this._service.detectorMediaSever(),r.info(L.L_RTC_CLIENT_LEAVE_ROOM_R,{status:A.SUCCESSED,userId:this._context.getCurrentId(),roomId:null===(o=this._crtRoom)||void 0===o?void 0:o.getRoomId()},{logSource:i.RTC}),this._crtRoom=null,{code:O.SUCCESS}):(r.warn(L.L_RTC_CLIENT_LEAVE_ROOM_R,{status:A.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:i.RTC}),{code:O.SUCCESS})}))}joinLivingRoomAsAudience(e,t,o){return f(this,void 0,void 0,(function*(){if(r.info(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_T,{roomId:e,livingType:t,useMutilPeerC:o},{logSource:i.RTC}),this._service.detectorMediaSever(),Bt(this._context.getNaviInfo()))return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:O.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:i.RTC}),{code:O.PACKAGE_ENVIRONMENT_ERROR};if(!s("roomId",e,R,!0)||!s("livingType",t,(e=>e===Ri.AUDIO||e===Ri.VIDEO)))return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:O.PACKAGE_ENVIRONMENT_ERROR,msg:"params error -> roomId or livingType"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:O.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:O.REPERT_JOIN_ROOM};if(!this._service.getNaviMS().length)return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:O.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:i.RTC}),{code:O.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:n,data:c}=yield this._context.joinLivingRoomAsAudience(e,mr.LIVE,t);if(n!==a.SUCCESS)return v.error("audienceJoinLivingRoomError:",n),r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:O.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED,msg:"signal error -> audience join room"},{logSource:i.RTC}),{code:O.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};v.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(c)}`);const d=jt(),_=new yi(this._context,this._runtime,this._options,e,c,t,o,d);return this._crtAudienceLivingRoom=_,r.info(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.SUCCESSED,roomData:c},{logSource:i.RTC}),{room:_,code:O.SUCCESS,userIds:_.getRemoteUserIds(),RTCTracks:_.getRemoteRTCTracks(),MCUTracks:_.getRemoteMCUTracks(),CDNUris:_.getCDNInfo()}}))}leaveLivingRoomAsAudience(e){return f(this,void 0,void 0,(function*(){return r.info(L.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_T,{roomId:e.getRoomId(),userId:this._context.getCurrentId()},{logSource:i.RTC}),this._crtAudienceLivingRoom?this._crtAudienceLivingRoom!==e?(r.error(L.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> room"},{logSource:i.RTC}),{code:O.PARAMS_ERROR}):(yield this._crtAudienceLivingRoom.__destroy(!0),this._crtAudienceLivingRoom=null,r.info(L.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:A.SUCCESSED,roomId:e.getRoomId(),userId:this._context.getCurrentId()},{logSource:i.RTC}),{code:O.SUCCESS}):(r.warn(L.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:i.RTC}),{code:O.SUCCESS})}))}upgradeToAnchorRoom(e){return f(this,void 0,void 0,(function*(){if(!s("room",e,(()=>e instanceof yi),!0))return r.error(L.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> room"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(r.info(L.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_T,{roomId:e.getRoomId(),userId:this._context.getCurrentId()},{logSource:i.RTC}),this._crtRoom)return r.error(L.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:A.FAILED,code:O.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:O.REPERT_JOIN_ROOM};const t=e.getRoomId(),o=this._crtRoom=new fi(this._context,this._runtime,t,this._service,this._options,e.livingType,!0,!0,!1,e.getClientSessionId()),n=yield o.__innerInitByIdentityChange();return n!==a.SUCCESS?(v.warn(`change room identity failed -> code: ${n}`),this._crtRoom=null,r.error(L.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:A.FAILED,code:O.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:i.RTC}),{code:O.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):(o.once(si,(()=>{this._crtRoom=null})),yield this._crtAudienceLivingRoom.__destroy(!1),this._crtAudienceLivingRoom=null,{room:o,code:O.SUCCESS,userIds:o.getRemoteUserIds(),tracks:o.getRemoteTracks()})}))}downgradeToAudienceRoom(e){return f(this,void 0,void 0,(function*(){if(r.info(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_T,{roomId:e._roomId,userId:this._context.getCurrentId()},{logSource:i.RTC}),!e.isMainRoom())return v.error("the `downgradeToAudienceRoom` is disabled in PK room"),r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:O.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!s("room._roomId",e._roomId,R,!0))return r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:O.PARAMS_ERROR,msg:"params error -> room._roomId"},{logSource:i.RTC}),{code:O.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:O.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:O.REPERT_JOIN_ROOM};const{code:t,data:o}=yield this._context.rtcIdentityChange(e._roomId,Ci.AnchorToViewer,e.getLivingType());if(t!==a.SUCCESS)return v.error("change room identity error",t),r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:O.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:i.RTC}),{code:O.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};v.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(o)}`),r.info(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.SUCCESSED,roomData:o},{logSource:i.RTC});const n=e.getClientSessionId(),c=new yi(this._context,this._runtime,this._options,e._roomId,o,e.getLivingType(),!1,n);return this._crtAudienceLivingRoom=c,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:c,code:O.SUCCESS,userIds:c.getRemoteUserIds(),RTCTracks:c.getRemoteRTCTracks(),MCUTracks:c.getRemoteMCUTracks(),CDNUris:c.getCDNInfo()}}))}getJoinedRoomInfo(){return f(this,void 0,void 0,(function*(){const{code:e,data:t}=yield this._context.getRTCJoinedUserInfo(this._context.getCurrentId());return e!==a.SUCCESS?(v.error("getJoinedUserInfo error",e),r.error(L.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:A.FAILED,code:e,msg:"Switch identity error"},{logSource:i.RTC}),{code:e}):(r.info(L.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:A.SUCCESSED,roomInfo:t},{logSource:i.RTC}),{code:O.SUCCESS,data:t})}))}}var Pi;!function(e){e[e.SERVER_KICK=1]="SERVER_KICK",e[e.OTHER_KICK=2]="OTHER_KICK"}(Pi||(Pi={}));const Mi="rtcRJoin_data",xi="rtcRExit",wi="rtcRInfo",Bi="rtcUData",Vi="rtcUDel",$i="rtcSetData",Fi="userSetData",Gi="rtcQryData",Ki="rtcDelData",Hi="rtcToken",ji="rtcUserState",Ji="rtcUList",Wi="viewerJoinR",qi="viewerExitR",Yi="rtcPullKv",zi="rtcIdentityChange",Qi="rtcInvite",Zi="rtcCancelInvite",Xi="rtcInviteAnswer",eo="rtcEndInvite",to="rtcQueryJoined";var ro;!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"}(ro||(ro={}));const io={[ro.RtcInput]:["roomType","broadcastType","extraInnerData","needSysChatroom","identityChangeType","joinType","innerDatas","outerDatas"],[ro.RtcUserListOutput]:["users","token","sessionId","roomInfo"],[ro.SetUserStatusInput]:["status"],[ro.RtcSetDataInput]:["interior","target","key","value","objectName","content"],[ro.RtcUserSetDataInput]:["valueInfo","objectName","content"],[ro.RtcDataInput]:["interior","target","key","objectName","content"],[ro.RtcSetOutDataInput]:["target","valueInfo","objectName","content"],[ro.MCFollowInput]:["state"],[ro.RtcTokenOutput]:["rtcToken"],[ro.RtcQryOutput]:["outInfo"],[ro.RtcQryUserOutDataInput]:["userId"],[ro.RtcUserOutDataOutput]:["user"],[ro.RtcQueryListInput]:["order"],[ro.RtcRoomInfoOutput]:["roomId","roomData","userCount","list"],[ro.RtcValueInfo]:["key","value"],[ro.RtcKeyDeleteInput]:["key"],[ro.RtcNotifyMsg]:["type","time","roomId"],[ro.RtcPullKV]:["timestamp","roomId"],[ro.RtcKVOutput]:["entries","bFullUpdate","syncTime"],[ro.RtcQueryUserJoinedInput]:["userId"],[ro.RtcQueryUserJoinedOutput]:["info"],[ro.RtcInviteInput]:["invitedUserId","timeoutTime","invitedRoomId","inviteInfo","inviteSessionId"],[ro.RtcCancelInviteInput]:["invitedUserId","invitedRoomId","inviteInfo","inviteSessionId"],[ro.RtcInviteAnswerInput]:["inviteUserId","answerCode","inviteRoomId","inviteSessionId","content","key","value"],[ro.RtcEndInviteInput]:["inviteRoomId","inviteSessionId","inviteContent","inviteRoomKeys"]},oo=`\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 ${ro.SetUserStatusInput}\n {\n optional int32 status=1;\n }\n message ${ro.MCFollowInput}\n {\n required string state = 1;\n }\n message ${ro.RtcQueryListInput}{\n optional int32 order=1;\n }\n message ${ro.RtcKeyDeleteInput}{\n repeated string key=1;\n }\n message ${ro.RtcValueInfo}{\n required string key=1;\n required string value=2;\n }\n message RtcUserInfo{\n required string userId=1;\n repeated ${ro.RtcValueInfo} userData=2; //用户资源信息\n }\n message ${ro.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 ${ro.RtcValueInfo} roomData = 2;\n optional int32 userCount = 3;\n repeated RtcUserInfo list=4;\n }\n message ${ro.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 ${ro.RtcValueInfo} innerDatas = 7; //用户内部inner数据,角色或者连麦信息等\n repeated ${ro.RtcValueInfo} outerDatas = 8; //用户内部outer数据,自定义数据结构RtcInput。\n }\n message ${ro.RtcQryOutput}{\n repeated ${ro.RtcValueInfo} outInfo=1;\n }\n message ${ro.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 ${ro.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 ${ro.RtcUserSetDataInput} {\n repeated ${ro.RtcValueInfo} valueInfo = 1;\n required string objectName = 2;\n repeated ${ro.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 ${ro.RtcTokenOutput}{\n required string rtcToken=1;\n }\n message ${ro.RtcSetOutDataInput}{\n required targetType target=1;\n repeated ${ro.RtcValueInfo} valueInfo=2;\n optional string objectName=3;\n optional string content=4;\n }\n message ${ro.RtcQryUserOutDataInput}{\n repeated string userId = 1;\n }\n message ${ro.RtcUserOutDataOutput}{\n repeated RtcUserInfo user = 1;\n }\n message ${ro.RtcNotifyMsg} \n {\n required int32 type= 1; //(通知类型 1:rtc房间状态KV变更通知)\n optional int64 time= 2; //消息产生时间\n optional string roomId=3; //主播房间id\n }\n message ${ro.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 ${ro.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 ${ro.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 ${ro.RtcQueryUserJoinedOutput}\n {\n repeated RtcJoinedInfo info = 1;\n }\n message ${ro.RtcViewerJoinedOutput}\n {\n required string rtcToken=1;\n repeated RtcKVEntity entries = 2;//KV属性对象集合\n optional int64 syncTime = 3;//所有属性的最大时间戳(下次拉取KV时用)。\n }\n message ${ro.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 ${ro.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 ${ro.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 ${ro.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}\n`,so=(e,t,r,i,o,s)=>{const n=o?Object.keys(o).map((t=>e.encode(ro.RtcValueInfo,{key:t,value:o[t]},!0))):void 0,a=s?Object.keys(s).map((t=>e.encode(ro.RtcValueInfo,{key:t,value:s[t]},!0))):void 0;return e.encode(ro.RtcInput,{roomType:t,broadcastType:r,joinType:i,innerDatas:n,outerDatas:a})},no=(e,t)=>{const r=e.decode(ro.RtcUserListOutput,t),{users:i,token:o,sessionId:s,roomInfo:n,entries:a,offlineKickTime:c}=r,d={};return S(i,(e=>{const{userId:t,userData:r}=e,i={};S(r,(e=>{const{key:t,value:r}=e;i[t]=r})),d[t]=i})),{users:d,token:o,sessionId:s,roomInfo:n,kvEntries:a,offlineKickTime:c}};class ao{constructor(e,t){this.context=e,this.codec=t}joinRTCRoom(e,t,r,i,o,s){return f(this,void 0,void 0,(function*(){const n=so(this.codec,t,r,i,o,s),{code:c,buffer:d}=yield this.context.rtcSignaling(e,Mi,!0,n);let _;return c===a.SUCCESS&&d&&(_=no(this.codec,d)),{code:c,data:_}}))}quitRTCRoom(e){return f(this,void 0,void 0,(function*(){const t=this.codec.encode(ro.SetUserStatusInput,{status:0}),{code:r}=yield this.context.rtcSignaling(e,xi,!0,t);return r}))}getRTCRoomInfo(e){return f(this,void 0,void 0,(function*(){const t=this.codec.encode(ro.RtcQueryListInput,{order:2}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,wi,!0,t);let o;return r===a.SUCCESS&&i&&(o=this.codec.decode(ro.RtcRoomInfoOutput,i)),{code:r,data:o}}))}getRTCUserInfoList(e){return f(this,void 0,void 0,(function*(){const t=this.codec.encode(ro.RtcQueryListInput,{order:2}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,Bi,!0,t);let o;if(r===a.SUCCESS&&i){o={users:no(this.codec,i).users}}return{code:r,data:o}}))}getRTCUserInfo(e){throw new Error("Method not implemented.")}removeRTCUserInfo(e,t){return f(this,void 0,void 0,(function*(){const r=this.codec.encode(ro.RtcKeyDeleteInput,{key:t}),{code:i}=yield this.context.rtcSignaling(e,Vi,!1,r);return i}))}setRTCData(e,t,r,i,o,s){return f(this,void 0,void 0,(function*(){const n=this.codec.encode(ro.RtcSetDataInput,{interior:i,target:o,key:t,value:r,objectName:null==s?void 0:s.name,content:null==s?void 0:s.content}),{code:a}=yield this.context.rtcSignaling(e,$i,!1,n);return a}))}setRTCTotalRes(e,t,r,i,o,s){return f(this,void 0,void 0,(function*(){const n={objectName:i,content:this.codec.encode(ro.RtcValueInfo,{key:t.name,value:t.content},!0),valueInfo:[this.codec.encode(ro.RtcValueInfo,{key:"uris",value:r},!0)]};o&&n.valueInfo.push(this.codec.encode(ro.RtcValueInfo,{key:"mcu_uris",value:o},!0)),s&&n.valueInfo.push(this.codec.encode(ro.RtcValueInfo,{key:"cdn_uris",value:s},!0));const a=this.codec.encode(ro.RtcUserSetDataInput,n),{code:c}=yield this.context.rtcSignaling(e,Fi,!0,a);return c}))}setRTCCDNUris(e,t,r){return f(this,void 0,void 0,(function*(){const i=this.codec.encode(ro.RtcUserSetDataInput,{objectName:t,valueInfo:this.codec.encode(ro.RtcValueInfo,{key:"cdn_uris",value:r},!0)}),{code:o}=yield this.context.rtcSignaling(e,Fi,!0,i);return o}))}getRTCData(e,t,r,i){return f(this,void 0,void 0,(function*(){const o=this.codec.encode(ro.RtcDataInput,{interior:r,target:i,key:t}),{code:s,buffer:n}=yield this.context.rtcSignaling(e,Gi,!0,o);if(s!==a.SUCCESS||!n)return{code:s};const{outInfo:c}=this.codec.decode(ro.RtcQryOutput,n),d={};return c.forEach((e=>{d[e.key]=e.value})),{code:s,data:d}}))}removeRTCData(e,t,r,i,o){return f(this,void 0,void 0,(function*(){const s=this.codec.encode(ro.RtcDataInput,{interior:r,target:i,key:t,objectName:null==o?void 0:o.name,content:null==o?void 0:o.content}),{code:n}=yield this.context.rtcSignaling(e,Ki,!1,s);return n}))}setRTCOutData(e,t,r,i){return f(this,void 0,void 0,(function*(){throw new Error("JSEngine's method not implemented.")}))}getRTCOutData(e,t){return f(this,void 0,void 0,(function*(){throw new Error("JSEngine's method not implemented.")}))}getRTCToken(e,t,r){return f(this,void 0,void 0,(function*(){const i=so(this.codec,t,r),{code:o,buffer:s}=yield this.context.rtcSignaling(e,Hi,!0,i);if(o!==a.SUCCESS||!s)return{code:o};const{rtcToken:n}=this.codec.decode(ro.RtcTokenOutput,s);return{code:o,data:{rtcToken:n}}}))}setRTCState(e,t){return f(this,void 0,void 0,(function*(){const r=this.codec.encode(ro.MCFollowInput,{state:t}),{code:i}=yield this.context.rtcSignaling(e,ji,!0,r);return i}))}getRTCUserList(e){return f(this,void 0,void 0,(function*(){const t=this.codec.encode(ro.RtcQueryListInput,{order:2}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,Ji,!0,t);if(r!==a.SUCCESS||!i)return{code:r};return{code:r,data:no(this.codec,i)}}))}joinLivingRoomAsAudience(e,t,r){return f(this,void 0,void 0,(function*(){const i=so(this.codec,t,r),{code:o,buffer:s}=yield this.context.rtcSignaling(e,Wi,!0,i);if(o!==a.SUCCESS||!s)return{code:o};const{rtcToken:n,entries:c}=this.codec.decode(ro.RtcViewerJoinedOutput,s);return{code:o,data:{token:n,kvEntries:c}}}))}quitLivingRoomAsAudience(e){return f(this,void 0,void 0,(function*(){const t=this.codec.encode(ro.SetUserStatusInput,{status:0}),{code:r}=yield this.context.rtcSignaling(e,qi,!0,t);return r}))}rtcIdentityChange(e,t,r){return f(this,void 0,void 0,(function*(){const i=this.codec.encode(ro.RtcInput,{roomType:mr.LIVE,broadcastType:r,identityChangeType:t,needSysChatroom:!1}),{code:o,buffer:s}=yield this.context.rtcSignaling(e,zi,!0,i);if(o!==a.SUCCESS||!s)return{code:o};return{code:o,data:no(this.codec,s)}}))}requestRoomPK(e){return f(this,void 0,void 0,(function*(){const{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,inviteTimeout:o,inviteInfo:s,roomId:n}=e,a=this.codec.encode(ro.RtcInviteInput,{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,timeoutTime:o,inviteInfo:s}),{code:c}=yield this.context.rtcSignaling(n,Qi,!0,a);return c}))}cancelRoomPK(e){return f(this,void 0,void 0,(function*(){const{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,inviteInfo:o,roomId:s}=e,n=this.codec.encode(ro.RtcCancelInviteInput,{invitedRoomId:t,invitedUserId:r,inviteSessionId:i,inviteInfo:o}),{code:a}=yield this.context.rtcSignaling(s,Zi,!0,n);return a}))}responseRoomPK(e){return f(this,void 0,void 0,(function*(){const{inviteUserId:t,inviteRoomId:r,inviteSessionId:i,content:o,key:s,value:n,agree:a,roomId:c}=e,d=this.codec.encode(ro.RtcInviteAnswerInput,{inviteUserId:t,inviteRoomId:r,inviteSessionId:i,content:o,key:s,value:n,answerCode:a?1:0}),{code:_}=yield this.context.rtcSignaling(c,Xi,!0,d);return _}))}endRoomPK(e){return f(this,void 0,void 0,(function*(){const{endRoomId:t,sessionId:r,content:i,keys:o,roomId:s}=e,n=this.codec.encode(ro.RtcEndInviteInput,{inviteRoomId:t,inviteSessionId:r,inviteContent:i,inviteRoomKeys:o}),{code:a}=yield this.context.rtcSignaling(s,eo,!0,n);return a}))}getRTCJoinedUserInfo(e){return f(this,void 0,void 0,(function*(){const t=this.codec.encode(ro.RtcQueryUserJoinedInput,{userId:e}),{code:r,buffer:i}=yield this.context.rtcSignaling("",to,!0,t);if(r!==a.SUCCESS||!i)return{code:r};return{code:r,data:(this.codec.decode(ro.RtcQueryUserJoinedOutput,i).info||[]).map((e=>({deviceId:e.deviceId,roomId:e.roomId,joinTime:Ft(e.joinTime)})))}}))}pullRTCRoomEntry(e){return f(this,void 0,void 0,(function*(){const t=this.codec.encode(ro.RtcPullKV,{timestamp:0,roomId:e}),{code:r,buffer:i}=yield this.context.rtcSignaling(e,Yi,!0,t);if(r!==a.SUCCESS)return{code:r};const o=this.codec.decode(ro.RtcKVOutput,i);let{entries:s,syncTime:n}=o;return s=(s||[]).map((e=>Object.assign(Object.assign({},e),{timestamp:Ft(e.timestamp)}))),{code:r,data:{kvEntries:s,syncTime:Ft(n)}}}))}decodeRtcNotify(e){const{time:t,type:r,roomId:i}=this.codec.decode(ro.RtcNotifyMsg,e);return{time:Ft(t),type:r,roomId:i}}getCurrentId(){return this.context.getCurrentId()}getNaviInfo(){return this.context.getNaviInfo()}getConnectionStatus(){return this.context.getConnectionStatus()}getAppkey(){return this.context.getAppkey()}rtcPing(e,t,r){return this.context.rtcPing(e,t,r)}sendMessage(e,t,r){return this.context.sendMessage(e,t,r)}registerRTCSignalListener(e){this.context.registerRTCSignalListener(e)}registerConnectionStateChangeListener(e){this.context.onconnectionstatechange=e}registerDisconnectListener(e){this.context.ondisconnect=e}registerDestroyListener(e){this.context.ondestroy=e}registerMessageListener(e){this.context.onmessage=e}getCoreVersion(){return this.context.getCoreVersion()}getPluginContext(){return this.context}}const co={tag:"RCRTC",verify:e=>"browser"!==e.tag?(v.error(`RCRTC Plugin is not support the runtime '${e.tag}'`),!1):Et?(g.add("plugin-rtc","5.5.6"),!!g.validEngine("^5.5.1")||(v.error(`The current engine version '${g.getInfo().engine}' error, plugin-rtc required engine version at least '^5.5.1'.`),!1)):(v.error("Please use the https protocol or use `http://localhost` to open the page!"),!1),setup(e,t,r={}){var i,s,n,a,c,d,_,u;return v.setLogLevel(r.logLevel),v.setLogStdout(r.logStdout),v.warn("RCRTC Version: 5.5.6, Commit: bdde7363c1a0707e32aa8e4383c0ab3796755c6c"),v.warn(`browserInfo.browser -> ${Pt.browser}`),v.warn(`browserInfo.supportsUnifiedPlan -> ${Pt.supportsUnifiedPlan}`),v.warn(`browserInfo.version -> ${Pt.version}`),m("options.mediaServer",r.mediaServer,(e=>!(!T(e)||"https:"===location.protocol&&!/^https/.test(e)))),m("options.timeout",r.timeout,(e=>o(e)&&e>=5e3&&e<=3e4)),m("options.pingGap",r.pingGap,(e=>o(e)&&e>=3e3&&e<=1e4)),(null==r?void 0:r.audio)&&((null===(i=r.audio)||void 0===i?void 0:i.workletModule)&&(it.workletModule=null===(s=r.audio)||void 0===s?void 0:s.workletModule),(null===(n=r.audio)||void 0===n?void 0:n.workletWasm)&&(it.workletWasm=null===(a=r.audio)||void 0===a?void 0:a.workletWasm),(null===(c=r.audio)||void 0===c?void 0:c.workletModule)&&(null===(d=r.audio)||void 0===d?void 0:d.workletWasm)&&(it.isOpen=!0),void 0!==(null===(_=r.audio)||void 0===_?void 0:_.isOpen)&&(it.isOpen=null===(u=r.audio)||void 0===u?void 0:u.isOpen)),new Ui(new ao(e,e.createCodec(io,oo)),t,r)}},_o={DEFAULT:"RongCloudRTC"},uo={transResolution:kt,transFrameRate:Ut,parseTrackId:Ot,ifSupportLocalFileTrack:Mt,ifSupportScreenShare:xt};export{ci as BackgroundPictureFillMode,di as MixLayoutMode,_i as MixVideoRenderMode,ni as RCAbstractRoom,Ai as RCAudienceClient,yi as RCAudienceLivingRoom,Ze as RCAudioBitrate,ut as RCCameraVideoTrack,Ge as RCFrameRate,Di as RCInnerCDNPullIsHttps,Ni as RCInnerCDNPullKind,Pi as RCKickReason,fi as RCLivingRoom,Ri as RCLivingType,st as RCLocalAudioTrack,dt as RCLocalFileAudioTrack,at as RCLocalFileTrack,ct as RCLocalFileVideoTrack,ot as RCLocalTrack,nt as RCLocalVideoTrack,hi as RCMCUConfigBuilder,bi as RCMediaStreamCapture,He as RCMediaType,_t as RCMicphoneAudioTrack,Ui as RCRTCClient,O as RCRTCCode,ur as RCRTCLiveRole,Kt as RCRTCPingResult,vi as RCRTCRoom,pt as RCRemoteAudioTrack,Rt as RCRemoteTrack,mt as RCRemoteVideoTrack,Ke as RCResolution,ht as RCScreenAudioTrack,lt as RCScreenVideoTrack,_o as RCTag,Xe as RCTrack,tt as RCVideoBitrate,Cr as RTCJoinType,ze as device,uo as helper,co as installer};
|