@rongcloud/plugin-rtc 5.4.3 → 5.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/core/Invoker.d.ts +8 -0
  2. package/dist/core/Store.d.ts +8 -4
  3. package/dist/core/command/AsyncCommand.d.ts +55 -0
  4. package/dist/core/command/AsyncSubscribeCommand.d.ts +28 -0
  5. package/dist/core/command/AsyncUnsubscribeCommand.d.ts +28 -0
  6. package/dist/core/command/AsyncUpdateSubscribeListCommand.d.ts +25 -0
  7. package/dist/core/command/BaseCommand.d.ts +9 -0
  8. package/dist/core/command/JoinRoomCommand.d.ts +2 -0
  9. package/dist/core/command/LeaveOtherRoomCommand.d.ts +2 -0
  10. package/dist/core/command/OnRemoteUserUnpubCommand.d.ts +2 -2
  11. package/dist/core/command/OnSignalReconnectedCommand.d.ts +2 -2
  12. package/dist/core/command/ParseRemoteResCommand.d.ts +5 -5
  13. package/dist/core/command/ParseUserStateCommand.d.ts +2 -2
  14. package/dist/core/command/{PubCommand.d.ts → PublishCommand.d.ts} +4 -2
  15. package/dist/core/command/{SubCommand.d.ts → SubscribeCommand.d.ts} +4 -4
  16. package/dist/core/command/{UnpubCommand.d.ts → UnpublishCommand.d.ts} +4 -2
  17. package/dist/core/command/UnpublishPrevCommand.d.ts +11 -0
  18. package/dist/core/command/{UnsubCommand.d.ts → UnsubscribeCommand.d.ts} +4 -4
  19. package/dist/core/command/{UpdateSubListCommand.d.ts → UpdateSubscribeListCommand.d.ts} +5 -5
  20. package/dist/core/enums/RCCommandKind.d.ts +12 -0
  21. package/dist/core/enums/RCLinkedListPoint.d.ts +6 -0
  22. package/dist/core/enums/RCLoggerTag.d.ts +13 -1
  23. package/dist/core/enums/RCRTCCode.d.ts +4 -2
  24. package/dist/core/enums/inner/RCRTCMessageType.d.ts +5 -1
  25. package/dist/core/interfaces.d.ts +19 -0
  26. package/dist/core/room/RCAbstractRoom.d.ts +30 -7
  27. package/dist/core/room/RCAudienceLivingRoom.d.ts +8 -0
  28. package/dist/core/tracks/RC3AnoiseTrack.d.ts +27 -0
  29. package/dist/core/tracks/RCLocalTrack.d.ts +14 -0
  30. package/dist/core/tracks/RCRemoteTrack.d.ts +6 -0
  31. package/dist/core/tracks/RCTrack.d.ts +5 -1
  32. package/dist/core/webrtc/RCRTCPeerCManager.d.ts +2 -0
  33. package/dist/core/webrtc/RCRTCPeerConnection.d.ts +2 -0
  34. package/dist/index.d.ts +130 -17
  35. package/dist/index.esm.js +2 -2
  36. package/dist/index.js +1 -1
  37. package/dist/index.umd.js +1 -1
  38. package/package.json +2 -2
  39. package/dist/core/command/UnpubPrevCommand.d.ts +0 -6
package/dist/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import{Logger as e,EventEmitter as t,logger as r,LogSource as i,isNumber as o,validate as s,ErrorCode as n,HttpMethod as a,ConnectionStatus as c,RTCMode as _,notEmptyString as d,isObject as u,isString as l,RTCJoinType as h,RTCApiType as R,isArray as p,assert as m,ConversationType as C,isHttpUrl as T,isBoolean as E,isUndefined as I,RTCIdentityChangeType as S,VersionManage as g}from"@rongcloud/engine";export{RTCJoinType}from"@rongcloud/engine";
1
+ import{Logger as e,EventEmitter as t,logger as r,LogSource as i,isNumber as s,validate as o,ErrorCode as n,HttpMethod as a,ConnectionStatus as c,RTCMode as d,notEmptyString as _,isObject as u,isString as l,RTCJoinType as h,RTCApiType as R,isArray as p,assert as m,ConversationType as C,isHttpUrl as T,isBoolean as E,isUndefined as I,RTCIdentityChangeType as S,VersionManage as g}from"@rongcloud/engine";export{RTCJoinType}from"@rongcloud/engine";
2
2
  /*! *****************************************************************************
3
3
  Copyright (c) Microsoft Corporation.
4
4
 
@@ -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 O=new e("RCRTC");var v,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.PERMISSION_DENIED=53012]="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"}(v||(v={})),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"}(L||(L={})),function(e){e.FAILED="fail",e.SUCCESSED="success",e.TIMEOUT="timeout",e.INFO="info"}(A||(A={}));let N=!0,D=!0;function U(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function k(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 P(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 y(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 M(){if("object"==typeof window){if(N)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function b(e,t){D&&console.warn(e+" is deprecated, please use "+t+" instead.")}function x(e){return"[object Object]"===Object.prototype.toString.call(e)}function B(e){return x(e)?Object.keys(e).reduce((function(t,r){const i=x(e[r]),o=i?B(e[r]):e[r],s=i&&!Object.keys(o).length;return void 0===o||s?t:Object.assign(t,{[r]:o})}),{}):e}function w(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?w(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{w(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&&w(e,r,o)}))})),o}const F=M;function $(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),F("chrome: "+JSON.stringify(e)),o(e)}))}e.video=i(e.video)}return F("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 k(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}),k(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 Y(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return W(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const 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 q(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function z(e,t){k(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:Y,shimPeerConnection:q,fixNegotiationNeeded:z,shimGetUserMedia:$,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,_=t.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));_.length>0&&_[0].length>1&&_[0][0]===c&&(r=_[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 d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substr(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substr(5),10)*.95-16e3:void 0,i.forEach((function(e){e.maxBitrate=d}))),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 _=ee.getMediaSections(i._localDescription.sdp);_[s.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",i._localDescription.sdp=ee.getDescription(i._localDescription.sdp)+_.join("");var d=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),d&&(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,_=s.localCapabilities,d=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),_=c.shift(),d=ee.matchPrefix(_,"a=ice-lite").length>0,u=ee.matchPrefix(_,"a=group:BUNDLE ").length>0;s.usingBundle=u;var l=ee.matchPrefix(_,"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,_),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 E,I,S,g,f,O,v,L,A;!R&&s.transceivers[c]&&s.transceivers[c].rejected&&(s.transceivers[c]=s._createTransceiver(h,!0));var N,D,U=ee.parseRtpParameters(i);R||(N=ee.getIceParameters(i,_),(D=ee.getDtlsParameters(i,_)).role="client"),v=ee.parseRtpEncodingParameters(i);var k=ee.parseRtcpParameters(i),P=ee.matchPrefix(i,"a=end-of-candidates",_).length>0,y=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){I=(E=s.transceivers[c]).iceGatherer,S=E.iceTransport,g=E.dtlsTransport,f=E.rtpReceiver,O=E.sendEncodingParameters,L=E.localCapabilities,s.transceivers[c].recvEncodingParameters=v,s.transceivers[c].remoteCapabilities=U,s.transceivers[c].rtcpParameters=k,y.length&&"new"===S.state&&(!d&&!P||u&&0!==c?y.forEach((function(e){oe(E.iceTransport,e)})):S.setRemoteCandidates(y)),u&&0!==c||("new"===S.state&&S.start(I,N,"controlling"),"new"===g.state&&g.start(D)),!re(E.localCapabilities,E.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&E.sendEncodingParameters[0].rtx&&delete E.sendEncodingParameters[0].rtx,s._transceive(E,"sendrecv"===m||"recvonly"===m,"sendrecv"===m||"sendonly"===m),!f||"sendrecv"!==m&&"sendonly"!==m?delete E.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{(E=s.transceivers[c]||s._createTransceiver(h)).mid=T,E.iceGatherer||(E.iceGatherer=s._createIceGatherer(c,u)),y.length&&"new"===E.iceTransport.state&&(!P||u&&0!==c?y.forEach((function(e){oe(E.iceTransport,e)})):E.iceTransport.setRemoteCandidates(y)),L=e.RTCRtpReceiver.getCapabilities(h),t<15019&&(L.codecs=L.codecs.filter((function(e){return"rtx"!==e.name}))),O=E.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var M,b=!1;if("sendrecv"===m||"sendonly"===m){if(b=!E.rtpReceiver,f=E.rtpReceiver||new e.RTCRtpReceiver(E.dtlsTransport,h),b)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}}),M=n[C.stream]):(n.default||(n.default=new e.MediaStream),M=n.default)),M&&(r(A,M),E.associatedRemoteMediaStreams.push(M)),a.push([A,f,M])}else E.rtpReceiver&&E.rtpReceiver.track&&(E.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===E.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),E.associatedRemoteMediaStreams=[]);E.localCapabilities=L,E.remoteCapabilities=U,E.rtpReceiver=f,E.rtcpParameters=k,E.sendEncodingParameters=O,E.recvEncodingParameters=v,s._transceive(s.transceivers[c],!1,b)}}})),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 _=i.sendEncodingParameters||[{ssrc:1001*(2*o+1)}];s&&t>=15019&&"video"===n&&!_[0].rtx&&(_[0].rtx={ssrc:_[0].ssrc+1}),i.wantReceive&&(i.rtpReceiver=new e.RTCRtpReceiver(i.dtlsTransport,n)),i.localCapabilities=c,i.sendEncodingParameters=_})),"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 _=e.candidate.trim();0===_.indexOf("a=")&&(_=_.substr(2)),(t=ee.getMediaSections(r._remoteDescription.sdp))[s]+="a="+(c.type?_:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=ee.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var d=0;d<r.transceivers.length&&(r.transceivers[d].rejected||(r.transceivers[d].iceTransport.addRemoteCandidate({}),(t=ee.getMediaSections(r._remoteDescription.sdp))[d]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=ee.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));d++);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 _e(e,t){if(e.RTCIceGatherer&&(e.RTCIceCandidate||(e.RTCIceCandidate=function(e){return e}),e.RTCSessionDescription||(e.RTCSessionDescription=function(e){return e}),t.version<15025)){const t=Object.getOwnPropertyDescriptor(e.MediaStreamTrack.prototype,"enabled");Object.defineProperty(e.MediaStreamTrack.prototype,"enabled",{set(e){t.set.call(this,e);const r=new Event("enabled");r.enabled=e,this.dispatchEvent(r)}})}e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)&&Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new e.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),e.RTCDtmfSender&&!e.RTCDTMFSender&&(e.RTCDTMFSender=e.RTCDtmfSender);const r=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&&b("RTCIceServer.url","RTCIceServer.urls");const i="string"==typeof t;return i&&(t=[t]),t=t.filter((e=>{if(0===e.indexOf("stun:"))return!1;const t=e.startsWith("turn")&&!e.startsWith("turn:[")&&e.includes("transport=udp");return t&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=i?t[0]:t,!!t.length}}))}(e.iceServers,t.version),M("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype}function de(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var ue=Object.freeze({__proto__:null,shimPeerConnection:_e,shimReplaceTrack:de,shimGetUserMedia:ae,shimGetDisplayMedia:ce});function le(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){b("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}),k(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){b("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 Ee(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 Ie(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:Ee,shimGetParameters:Ie,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 Oe(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function ve(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:B(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")?(b("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 Ue(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 ke(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 Pe(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ye=Object.freeze({__proto__:null,shimLocalStreamsAPI:Oe,shimRemoteStreamsAPI:ve,shimCallbacksAPI:Le,shimGetUserMedia:Ae,shimConstraints:Ne,shimRTCIceServerUrls:De,shimTrackEventTransceiver:Ue,shimCreateOfferLegacy:ke,shimAudioContext:Pe});function Me(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const r=new t(e),i=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,k(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function be(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},k(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Be(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function we(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 Fe=Object.freeze({__proto__:null,shimRTCIceCandidate:Me,shimMaxMessageSize:be,shimSendThrowTypeError:xe,shimConnectionState:Be,removeExtmapAllowMixed:we,shimAddIceCandidateNullOrEmpty:Ve});const $e=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=M,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=U(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=U(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=U(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=U(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),o={browserDetails:i,commonShim:Fe,extractVersion:U,disableLog:P,disableWarnings:y};switch(i.browser){case"chrome":if(!Q||!q||!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),$(e,i),G(e),q(e,i),K(e),Y(e,i),H(e),j(e),J(e),z(e,i),Me(e),Be(e),be(e,i),xe(e),we(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),Ee(e),Ie(e),Se(e),ge(e),Me(e),Be(e),be(e,i),xe(e);break;case"edge":if(!ue||!_e||!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),_e(e,i),de(e),be(e,i),xe(e);break;case"safari":if(!ye||!t.shimSafari)return r("Safari shim is not included in this adapter release."),o;r("adapter.js shimming safari."),o.browserShim=ye,Ve(e,i),De(e),ke(e),Le(e),Oe(e),ve(e),Ue(e),Ae(e),Pe(e),Me(e),be(e,i),xe(e),we(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.W256_H144="W256_H144",e.W320_H180="W320_H180",e.W240_H240="W240_H240",e.W320_H240="W320_H240",e.W480_H360="W480_H360",e.W640_H360="W640_H360",e.W480_H480="W480_H480",e.W640_H480="W640_H480",e.W720_H480="W720_H480",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:160,minBitrate:80},[Ke.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[Ke.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[Ke.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[Ke.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[Ke.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[Ke.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[Ke.W480_H480]:{width:480,height:480,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.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[Ke.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},Je=(e,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},We={10:1,15:1,24:1.5,30:1.5},Ye=e=>{let t=Number.MAX_VALUE,r=1;for(const i in We){const o=Math.abs(e-parseInt(i));o<t&&(t=o,r=We[i])}return r},qe={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 ze,Qe;!function(e){e.AUDIO="audio",e.VIDEO="video"}(ze||(ze={}));class Ze 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}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(){O.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(){O.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={autoplay:!0}){var s,n;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 O.warn(`the track is not ready to play -> id: ${this._id}`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:v.TRACK_NOT_READY,msg:`play error -> id: ${this._id}`},{logSource:i.RTC}),{code:v.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&(O.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 O.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:v.PARAMS_ERROR,msg:"params error -> options.volume不是数字"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};(null==t?void 0:t.volume)<0&&(t.volume=0,O.warn("the valid range of options.volume is 0-100, the value of volume has been set 0"),r.warn(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,O.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 qe.getSpeakers()).map((e=>e.deviceId)).includes(t.audioDeviceId))return O.error(`the options.audioDeviceId is invalid --\x3e ${t.audioDeviceId}`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> options.audioDeviceId"},{logSource:i.RTC}),{code:v.PARAMS_ERROR}}const a=this.isVideoTrack();if(a&&(!e||!(e instanceof HTMLVideoElement||this.__validateVideoNodeName(e))))return O.error(`the video track need an <video> to play -> id: ${this._id}`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> element不是一个video标签"},{logSource:i.RTC}),{code:v.VIDEO_TRACK_MISS_MEDIA_ELEMENT};this._element=a?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;O.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;O.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;O.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;O.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;O.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})};const c=null===(null===(s=this._element)||void 0===s?void 0:s.getAttribute("autoplay"))?t.autoplay:null===(n=this._element)||void 0===n?void 0:n.autoplay;return this._element.oncanplay=e=>f(this,void 0,void 0,(function*(){var t,o,s;if(O.info(`HTMLMediaElement oncanplay -> 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 oncanplay -> id: ${null===(o=e.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`},{logSource:i.RTC}),c)try{null===(s=this._element)||void 0===s||s.play()}catch(e){if("No permission to use requested device"===e.message)return O.error(`setSinkId failed -> ${e.message}`),void r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:v.NO_PERMISSION_TO_USE_REQUESTED_DEVICE,msg:"No permission"},{logSource:i.RTC});O.error(e),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:v.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));O.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=c,a&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),(null==t?void 0:t.audioDeviceId)&&!a&&(yield this._element.setSinkId(t.audioDeviceId)),a||!(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:v.SUCCESS}}))}__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"}(Qe||(Qe={}));const Xe={[Qe.Music]:{max:64e3,min:64e3},[Qe.MusicHigh]:{max:128e3,min:128e3},[Qe.Speech]:{max:32e3,min:32e3}};var et;!function(e){e.LEVEL0="LEVEL0",e.LEVEL1="LEVEL1",e.LEVEL2="LEVEL2",e.LEVEL3="LEVEL3",e.LEVEL4="LEVEL4",e.LEVEL5="LEVEL5"}(et||(et={}));const tt={[et.LEVEL0]:{max:150,min:80},[et.LEVEL1]:{max:280,min:120},[et.LEVEL2]:{max:650,min:150},[et.LEVEL3]:{max:1e3,min:200},[et.LEVEL4]:{max:2200,min:250},[et.LEVEL5]:{max:4e3,min:400}};class rt extends Ze{constructor(e,t,r,i){super(e,t,r,!0),this._isPublished=!1,this.__innerSetMediaStreamTrack(i),i.onended=()=>{i.onended=null,this.emit(rt.EVENT_LOCAL_TRACK_END,this),this.removeAll(rt.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(e){const t=this._localMuted!==e;super._setLocalMuted(e),this._remoteMuted=this._localMuted,t&&this.emit(rt.__INNER_EVENT_MUTED_CHANGE__,this),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;O.info(`track is destroyed -> trackId: ${this.getTrackId()}`),null===(e=this._msTrack)||void 0===e||e.stop(),super.__innerDestroy(),this.isAudioTrack()&&super.__releaseMediaElement(),this.emit(rt.__INNER_EVENT_DESTROY__,this),r.info(L.L_LOCAL_TRACK_DESTROY_O,{status:A.SUCCESSED},{logSource:i.RTC})}setBitrate(e=0,t=0,s=0){if(!o(e)||!o(t)||!o(s)||e<=0||t<=0||e<t)return O.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:_}={min:0,max:0,start:0};return(null===(e=this._msTrack)||void 0===e?void 0:e.kind)===ze.VIDEO?({min:a,max:c}=St(this._msTrack)):(null===(t=this._msTrack)||void 0===t?void 0:t.kind)===ze.AUDIO&&({min:a,max:c}={min:32e3,max:32e3}),(null===(r=this._bitrateInfo)||void 0===r?void 0:r.max)&&(_=.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)||_}}}rt.EVENT_LOCAL_TRACK_END="local-track-end",rt.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",rt.__INNER_EVENT_DESTROY__="inner-destroy";class it extends rt{constructor(e,t,r){super(e,t,"audio",r)}setRecommendBitrate(e){if(!s("livingType",e,(e=>e in Qe)))return void r.warn(L.L_RTC_SET_RECOMMEND_BITRATE_O,{status:A.FAILED,msg:"params error -> setRecommendBitrate Audio"},{logSource:i.RTC});const t=Xe[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 ot extends rt{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 et)))return void r.warn(L.L_RTC_SET_RECOMMEND_BITRATE_O,{status:A.FAILED,msg:"params error -> setRecommendBitrate Video"},{logSource:i.RTC});const t=tt[e];this.setBitrate(t.max,t.min,t.start||.7*t.max)}setBitrate(e,...t){const[r=1,i=.7*e||1]=t;super.setBitrate(e,r,i)}}class st extends rt{constructor(e,t,r,i,o){super(e,t,r,i),this._resource=o,st.__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(),st.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}st._mapping=new Map;class nt extends st{constructor(e,t,r,i){super(e,t,"video",r,i)}}class at extends st{constructor(e,t,r,i){super(e,t,"audio",r,i)}_setLocalMuted(e){this._resource&&(this._resource.muted=e),super._setLocalMuted(e)}play(){return this._setLocalMuted(!1),Promise.resolve({code:v.SUCCESS})}}class ct extends it{}class _t extends ot{}class dt extends ot{}class ut extends it{}class lt extends Ze{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 ht extends lt{constructor(e,t,r){super(e,t,"audio",r)}}class Rt extends lt{constructor(e,t,r){super(e,t,"video",r)}}const pt=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),mt=e=>JSON.stringify(e),Ct=e=>/^[a-zA-Z\d-=]+$/g.test(e),Tt="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),Et=e=>{if(void 0===e)return 0;if(o(e))return e;const t=e;return t.exact||t.ideal||t.max||0},It=e=>{const t=e.getSettings(),r=e.getConstraints();return{width:t.width||Et(r.width),height:t.height||Et(r.height),frameRate:t.frameRate||Et(r.frameRate)}},St=e=>{const{width:t,height:r,frameRate:i}=It(e),o=Je(t||1920,r||1080),s=Ye(i);return{min:o.minBitrate*s,max:o.maxBitrate*s}},gt=e=>[e.msid,e.mediaType].join("_"),ft=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},Ot=(e,t)=>[e,t].join("_"),vt=e=>e.map((e=>Object.assign({},e))),Lt=(e,t,r=!1)=>{e=e.slice();const i=[],o=[],s=[];return t.forEach((t=>{const o=gt(t);let n=e.findIndex((e=>gt(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}},At=()=>{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},Nt=e=>{const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},Dt=e=>!!Ke[e],Ut=e=>!!Ge[e],kt=e=>parseInt(e.replace("FPS_","")),Pt=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=$e.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function yt(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function Mt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const bt=e=>"[object Null]"===Object.prototype.toString.call(e),xt=e=>1===e.type,Bt=(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){O.warn(`invalid user data -> userId: ${i}, userData: ${s}`)}r[i]=o})),r},wt=e=>e instanceof Ze?e.getTrackId():e.track.getTrackId();var Vt,Ft;!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"}(Vt||(Vt={})),function(e){e.SUCCESS="Success",e.FAIL="Fail"}(Ft||(Ft={}));class $t{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||(O.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=>{O.error(`rtcping receive unknown error -> ${t}`),e(n.UNKNOWN)})),setTimeout(e,5e3,n.TIMEOUT)}))}_checkAlive(){var e,t,o;return f(this,void 0,void 0,(function*(){O.info("rtcping ->");const s=yield this._sendPing(),a=Date.now();return s===n.SUCCESS?(O.info("rtcping success ->"),this._latestTimestamp=a,null===(e=this.onPingResult)||void 0===e||e.call(this,Ft.SUCCESS),void(this._timer=setTimeout((()=>this._checkAlive()),this._gap))):(s===n.TIMEOUT&&r.error(L.L_PINGER_TIMEOUT_O,{status:A.TIMEOUT},{logSource:i.RTC}),O.warn(`rtcping failed -> code: ${s}`),null===(t=this.onPingResult)||void 0===t||t.call(this,Ft.FAIL),40003===s||a-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&&(O.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 Gt=()=>"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)})),Kt=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${Pt.browser}|${Pt.version}`,ClientVersion:"5.4.3","Client-Session-Id":Gt(),"Request-Id":Date.now().toString()});class Ht{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=""}getNaviMS(){return this._msUrl?[this._msUrl]:this._clusterId?[`https://${this._clusterId}`]:(0===this._msInNavi.length&&(0===this._failedMs.length?this._msInNavi.push(...(e=>{var t;if(!e)return[];let r;try{r=JSON.parse(e.voipCallInfo||'{ "strategy": 0 }')}catch(t){return O.warn("parse `voipCallInfo` of navi failed: "+e.voipCallInfo),[]}if(0===r.strategy)return[];const i=null===(t=r.callEngine)||void 0===t?void 0:t.filter((e=>4===e.engineType));if(!i||0===i.length)return[];const 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)),this._msInNavi.map((e=>e.trim())))}_request(e,t,o){return f(this,void 0,void 0,(function*(){const s=this.getNaviMS();if(0===s.length)return O.warn(`request '${e}' failed -> have no valid service address.`),r.error(L.L_MEDIA_SERVICE_REQUEST_R,{status:A.FAILED,code:v.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"invalid navi_url"},{logSource:i.RTC}),{code:v.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(o.rtcFinger=this._rtcFinger);for(let n=0;n<s.length;n+=1){const c=`${s[n]}${e}`,_=Kt(),d=Object.assign(Object.assign({},_),t),u=JSON.stringify(o),l=_["Request-Id"];r.info(L.L_MEDIA_SERVICE_REQUEST_T,{path:e,headers:t,body:o,reqId:l},{logSource:i.RTC}),O.info(`request -> Request-Id: ${l}, url: ${c}, headers: ${JSON.stringify(d)}, body: ${u}`);const{status:h,data:R}=yield this._runtime.httpReq({url:c,body:u,headers:d,method:a.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),O.info(`request success -> Request-Id: ${l}`),r.info(L.L_MEDIA_SERVICE_REQUEST_R,{status:A.SUCCESSED,reqId:l},{logSource:i.RTC}),{code:v.SUCCESS,data:e}}O.warn(`request failed -> Request-Id: ${l}, status: ${h}, url: ${c}`),this._failedMs.push(...this._msInNavi.splice(n,1)),r.error(L.L_MEDIA_SERVICE_REQUEST_R,{status:A.FAILED,code:"",reqId:l,msg:`request error -> Request-Id: ${l}, status: ${h}, url: ${c}`},{logSource:i.RTC})}return{code:v.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===v.SUCCESS&&(null===(r=i.data)||void 0===r?void 0:r.resultCode)===v.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 O.warn("RCMediaService.setMcuConfig failed -> RCRTCCode.MCU_SERVER_NOT_FOUND"),r.error(L.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:A.FAILED,code:v.MCU_SERVER_NOT_FOUND,msg:"MCU not found"},{logSource:i.RTC}),{code:v.MCU_SERVER_NOT_FOUND};const o=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,s=Kt(),n=Object.assign(Object.assign({},s),e),c=JSON.stringify(t),_=s["Request-Id"];O.info(`request -> Request-Id: ${_}, url: ${o}, headers: ${JSON.stringify(n)}, body: ${c}`);const{status:d,data:u}=yield this._runtime.httpReq({url:o,headers:n,body:c,method:a.POST});if(200===d){O.info(`request success -> Request-Id: ${_}`);const e=JSON.parse(u);return r.info(L.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:A.SUCCESSED,reqId:_},{logSource:i.RTC}),{code:e.resultCode,res:e}}return O.warn(`request failed -> Request-Id: ${_}, status: ${d}, url: ${o}`),r.error(L.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:A.FAILED,code:v.REQUEST_FAILED,msg:`request error -> Request-Id: ${_}, status: ${d}, url: ${o}`},{logSource:i.RTC}),{code:v.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=Kt(),s=Object.assign(Object.assign({},o),e),n=o["Request-Id"];O.info(`request -> Request-Id: ${n}, url: ${t}, headers: ${JSON.stringify(s)}`);const{status:c,data:_}=yield this._runtime.httpReq({url:t,headers:s,method:a.GET});if(200===c){O.info(`request success -> Request-Id: ${o["Request-Id"]}`);const e=JSON.parse(_);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 O.warn(`request failed -> Request-Id: ${o["Request-Id"]}, status: ${c}, url: ${t}`),r.info(L.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:A.FAILED,code:v.REQUEST_FAILED,msg:`request error -> Request-Id: ${o["Request-Id"]}, status: ${c}, url: ${t}`},{logSource:i.RTC}),{code:v.REQUEST_FAILED}}))}}var jt;!function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(jt||(jt={}));const Jt=(e,t)=>Math.round(8*t/e),Wt=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},Yt=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.ceil(e*r)},qt=(e,t,r,i)=>{if(0===t)return 0;if(!r||!i)return Wt(e/t,3);const o=t-i;if(0===o)return 0;const s=e-r;return s<0||o<0?0:Wt(s/o,3)},zt=e=>{const{jitter:t,rtt:r,packetsLostRate:i}=e;return!bt(t)||!bt(r)||0!==i};class Qt{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 Jt(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 Jt(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=qt(t,r,o,s),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=o===t?s:r}else i=qt(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=qt(t,r+t,o,s+o)}else i=qt(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="),_=null==c?void 0:c.filter((e=>e.includes(`a=ssrc:${i}`)))[0],d=null==_?void 0:_.match(a);let u=d?d[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 Zt extends Qt{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:_,mediaSourceId:d,remoteId:u,packetsSent:l,bytesSent:h,trackId:R,encoderImplementation:p,pliCount:m,nackCount:C,firCount:T}=n;if(!R)return;let{framesPerSecond:E,frameWidth:I,frameHeight:S}=n;"video"!==c||I||S||E||(I=e[R].frameWidth,S=e[R].frameHeight,E=d?e[d].framesPerSecond:null);const g=e[u];let f=null,O=null,v=0;g&&(f=g.jitter,O=g.roundTripTime,v=g.packetsLost),o+=v;const L=this.getResourceIdByParseSdp(n);if(!L)return;const A=d?e[d].audioLevel:e[R].audioLevel;let N=null;!this._latestPacketsSent[L]&&(this._latestPacketsSent[L]={}),g?N=this.updateSenderPacketsLost(L,v,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?Yt(A):null,frameWidth:I,frameHeight:S,frameRate:E,bitrate:D,jitter:f?Math.round(1e3*f):f,rtt:O,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&&!zt(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:_,jitter:d,bytesReceived:u,framesPerSecond:l,kind:h,codecImplementationName:R,nackCount:p,pliCount:m}=s;if(!a)return;let{frameWidth:C,frameHeight:T,audioLevel:E}=s;"video"===h?C||T||(C=e[a].frameWidth,T=e[a].frameHeight):E||(E=e[a].audioLevel),o+=c;const I=this.getResourceIdByParseSdp(s),S=this.updateReceiverPacketsLost(I,c,_);let g=this.updateBytesRecv(I,u,r);g<0&&(g=0),n+=g,t.receivers.push({trackId:I,kind:h,packetsLostRate:S,remoteResource:!0,audioLevel:E||0===E?Yt(E):null,frameWidth:C,frameHeight:T,frameRate:l,bitrate:g,jitter:d?Math.round(1e3*d):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:_,localCandidateId:d,remoteCandidateId:u}=r,l=e[d],{ip:h,port:R,networkType:p}=l,m=e[u],{ip:C,port:T,protocol:E}=m;t.iceCandidatePair={IP:h,port:R,networkType:p,remoteIP:C,remotePort:T,protocol:E,bitrateRecv:n,bitrateSend:s,rtt:1e3*_,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:o},t.receivers.forEach((e=>{e.rtt=_}))}}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?Yt(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?Yt(s):null})})),t}}class Xt extends Qt{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:_,bitrateMean:d,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 E=null;!this._latestPacketsSent[T]&&(this._latestPacketsSent[T]={}),R?E=this.updateSenderPacketsLost(T,C,_):this._latestPacketsSent[T].crtPacketsSent=_;let I=0;"video"===n?d&&(I=Math.floor(d/1e3)):I=this.updateBytesSent(T,c,t),I<0&&(I=0),o+=I,r.senders.push({trackId:T,kind:n,packetsLostRate:E,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:I,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&&zt(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:_,framerateMean:d,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(d),bitrate:C,jitter:_?Math.round(1e3*_):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,_=e[a.remoteCandidateId],{address:d,port:u,protocol:l}=_;r.iceCandidatePair={IP:n,port:c,networkType:null,remoteIP:d,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 er extends Qt{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:_,packetsSent:d,bytesSent:u,trackId:l,encoderImplementation:h,pliCount:R,nackCount:p,firCount:m}=o;if(!l)return;const{audioLevel:C,frameHeight:T,frameWidth:E}=e[l];let I=this.updateBytesSent(n,u,r);I<0&&(I=0),s+=I,t.senders.push({trackId:n,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:C||0===C?Yt(C):null,frameWidth:E,frameHeight:T,frameRate:null,bitrate:I,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:_,jitter:d,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 E=this.updateReceiverPacketsLost(p,c,_);let I=this.updateBytesRecv(p,u,r);I<0&&(I=0),n+=I,t.receivers.push({trackId:p,kind:l,packetsLostRate:E,remoteResource:!0,audioLevel:T||0===T?Yt(T):null,frameWidth:C,frameHeight:m,frameRate:null,bitrate:I,jitter:d,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:_,localCandidateId:d,remoteCandidateId:u}=r,l=e[d],{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*_,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:o},t.receivers.forEach((e=>{e.rtt=_}))}}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?Yt(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?Yt(n):null})})),t}}class tr{constructor(e,t){this.SDP=e,this.type=t,this.SDPHeader="",this.videoStreams=[],this.audioStreams=[];const r=this.getStreamIndex();this.spliteStreams(r)}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]);for(let t=1;t<e.length;t++){const r=this.SDP.substring(e[t],e[t+1]);this.clearInactiveOrRecvonly(r)&&(/^\bm=video\b/.test(r)?this.videoStreams.push(r):this.audioStreams.push(r))}}clearInactiveOrRecvonly(e){return/\ba=(recvonly|inactive)\b/.test(e)?e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,""):e}setAudiosBitrate(e){return O.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 O.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}setAudioItemBitrate(e,t){if(0===t.max)return e;if(!/\bmaxaveragebitrate\b/gi.test(e)){const r=["$1",`maxaveragebitrate=${t.max}`];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(/^(m=audio[^\r\n]+)/,`$1\r\nb=AS:${t.max}`)}setVideosBitrate(e){return O.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 O.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}setVideoItemBitrate(e,t){if(0===t.max)return e;if(!/\bx-google-max-bitrate\b/.test(e)){const r=["$1",`x-google-max-bitrate=${t.max}`,`x-google-min-bitrate=${t.min}`,`x-google-start-bitrate=${t.start||.7*t.max}`];e=e.replace(/(\bprofile-level-id=[^\r\n]+)/gi,r.join(";"))}return this.addVideoBlineAS(e,t)}addVideoBlineAS(e,t){return/\bb=AS:\d+\b/gi.test(e)?e:e.replace(/^(m=video[^\r\n]+)/,`$1\r\nb=AS:${t.max}`)}}var rr,ir,or,sr,nr,ar,cr,_r;!function(e){e.PLANB="plan-b",e.UNIFIEDPLAN="unified-plan"}(rr||(rr={}));class dr{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 dr._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}=It(r);e.push({trackId:r.id,simulcast:i?jt.TINY:jt.NORMAL,resolution:`${o}x${s}`})}return e}setRemoteAnswer(e){return f(this,void 0,void 0,(function*(){e=tr.trimBlankLine(e),r.info(`set remote answer -> ${e}`);try{yield this._peer.setRemoteDescription({type:"answer",sdp:e})}catch(e){return O.error(e),r.info(L.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:A.FAILED,code:"",msg:e},{logSource:i.RTC}),v.SET_REMOTE_DESCRIPTION_FAILED}return r.info(L.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:A.SUCCESSED,sdp:e},{logSource:i.RTC}),v.SUCCESS}))}getStatParsr(e,t,r){return/chrome/i.test(Pt.browser)?new Zt(e,t,r):/Firefox/i.test(Pt.browser)?new Xt(e,t,r):/Safari/i.test(Pt.browser)?new er(e,t,r):null}resetSdp(e){return tr.trimBlankLine(e)}}class ur extends tr{constructor(e){super(e,rr.PLANB),this.SDP=e}stringify(){const e=[this.SDPHeader];[...this.audioStreams,...this.videoStreams].forEach((t=>{const r=t.match(/\ba=mid:(video|audio)\b/);r&&r[1]===ze.AUDIO&&(e[1]=t),r&&r[1]===ze.VIDEO&&(e[2]=t)}));const t=e.join("");return tr.trimBlankLine(t)}setAudioBitrateWithStreamId(e,t){return O.warn("plan-b not support set Audio Bitrate With Stream Id"),this}setVideoBitrateWithStreamId(e,t){return O.warn("plan-b not support set Video Bitrate With Stream Id"),this}}class lr extends dr{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=this.resetSdp(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 ur(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 hr extends tr{constructor(e){super(e,rr.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)}));const t=e.join("");return tr.trimBlankLine(t)}}class Rr extends dr{constructor(){super(...arguments),this._sendTransceiver={},this._localTracks={},this._recvAudio=[],this._recvVideo=[],this._recvTransceiver={},this._subedTracks=[]}setBitrate(e,t,r){O.warn("the interface named `setBitrate` is invalid while sdpSemantics value is `unified-plan`")}addLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId(),i=e.__innerGetMediaStreamTrack();this._localTracks[t]=e;const 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}=ft(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.resetSdp(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.resetSdp(e);const t=/[\r\n]+\r\n[\r\n]+/g;return t.test(e)&&(O.warn(`answer sdp invalid -> ${JSON.stringify(e)}`),e=e.replace(t,"\r\n")),super.setRemoteAnswer(e)}resetSdp(e){const t=new hr(e);for(const e in this._sendTransceiver){const r=this._localTracks[e],i=null==r?void 0:r.getBitrate(),o=null==r?void 0:r.getStreamId();i&&o&&(r.isVideoTrack()&&t.setVideoBitrateWithStreamId(i,o),r.isAudioTrack()&&t.setAudioBitrateWithStreamId(i,o))}return t.stringify()}}class pr 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._reportListener=null;const o=dr.getSdpSemantics(),s=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:o});this._sdpStrategy="plan-b"===o?new lr(s):new Rr(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(){O.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;O.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||(O.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){O.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(pr.__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 O.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 O.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(rt.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(rt.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.on(rt.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.on(rt.__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(rt.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(rt.__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){const t=this.getLocalTrack(`${e.getTrackId()}_tiny`);t&&(t.__innerGetMediaStreamTrack().enabled=!e.isLocalMuted()),this.emit(rt.__INNER_EVENT_MUTED_CHANGE__,e),r.info(L.L_RTC_PEER_CONNECTION_LOCAL_TRACK_MUTED_O,{status:A.SUCCESSED,trackId:e.getTrackId()},{logSource:i.RTC})}_onLocalTrackDestroied(e){this.emit(rt.__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)bt(r[e])&&delete r[e];return{timestamp:t,iceCandidatePair:r,senders:i.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),receivers: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 o=yield this._rtcPeerConn.getStats(),s=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(o),n=null===(t=this.reportParser)||void 0===t?void 0:t.formatRCRTCStateReport(s);return r.info(L.L_RTC_PEER_CONNECTION_GET_STATS_DATA_O,{status:A.SUCCESSED,formatData:n},{logSource:i.RTC}),n}))}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*(){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.reportParser=null,r.info(L.L_RTC_PEER_CONNECTION_DESTROY_O,{status:A.SUCCESSED},{logSource:i.RTC})}clearReTryExchangeTimer(){clearInterval(this._reTryExchangeTimer),this._reTryExchangeTimer=null}}pr.__INNER_EVENT_TRACK_READY__="inner-track-ready",function(e){e[e.DISABLE=0]="DISABLE",e[e.ENABLE=1]="ENABLE"}(ir||(ir={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(or||(or={}));class mr{constructor(e,t,r,i,o=or.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()!==c.CONNECTED)return t;return t=(yield this._context.setRTCState(this._roomId,e))===n.SUCCESS,t}))}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=At(),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}`,_=(null==t||t.remoteIP,null==t||t.remotePort,(null==t?void 0:t.availableIncomingBitrate)||-1),d=(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${_}\t${d}\t${u}\t${l}\r`,R=`R4\t${s}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${_}\t${d}\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:_,googRenderDelayMs:d,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&&_?`${c} * ${_}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:h||0===h?h:-1,rtt:R||-1,googFirsSent:p,samplingRate:o,googRenderDelayMs:d,encoderImplementation:m||String(-1),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(T))||void 0===t?void 0:t.isLocalMuted())?ir.DISABLE:ir.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:_,googRenderDelayMs:d,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&&_?`${c} * ${_}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:h||0===h?h:-1,rtt:R||-1,googFirsReceived:p,samplingRate:o,googRenderDelayMs:d,codecImplementationName:m||String(-1),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(T))||void 0===t?void 0:t.isLocalMuted())?ir.DISABLE:ir.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.4.3\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 Cr{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}=ft(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?O.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"}(sr||(sr={}));class Tr{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 rt||e[0]instanceof lt?{track:e[0]}:e[0];return t.isLocalTrack()}_groupTracksByTag(e){const t={};return e.map((e=>{const{track:r}=e instanceof rt?{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].tracks=t),!this._mutilPeerC[e]){const r=this._isPub(t),i=new pr(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}=ft(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.LOW=0]="LOW",e[e.NORMAL=1]="NORMAL",e[e.HIGH=2]="HIGH"}(nr||(nr={}));class Er{get priority(){return nr.LOW}}class Ir extends class{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._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}getPublishedResourceByTrackId(e){const{userId:t}=ft(e);return this._roomResources[t].find((t=>gt(t)===e))}getToken(){return this._token}getLocalTrack(e){return this.peerMgr.getPCByTrackId(e).getLocalTrack(e)}getLocalTracks(){const e=[];return this.peerMgr.getPCList().forEach((t=>{e.push(...t.getLocalTracks())})),e}getTrackState(e){var t;return(null===(t=this.getLocalTrack(e))||void 0===t?void 0:t.isLocalMuted())?0:1}getCDNEnable(){return this._CDNEnable}getCDNUris(){return this._CDNUris}}{_initRemoteTracks(){for(const e in this._roomResources){const t=this._roomResources[e];e!==this.crtUserId&&0!==t.length&&t.forEach((e=>{const t=gt(e),{tag:r,userId:i,mediaType:o}=ft(t),s=o===He.AUDIO_ONLY?new ht(r,i):new Rt(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=Bt(e,this.roomId),this._initRemoteTracks(),this.setResourcesByUserId(this.crtUserId,this.getResourcesByUserId(this.crtUserId)||[]),O.info(`room data -> ${JSON.stringify(this._roomResources)}`)}assignRoomData(e){Object.assign(this._roomResources,e)}setResourcesByUserId(e,t){this._roomResources[e]=t}removeRemoteTrack(e){delete this._remoteTracks[e]}removeResourcesByUserId(e){delete this._roomResources[e]}addRemoteTrack(e){this._remoteTracks[e.getTrackId()]=e}removeRemoteTracks(){const e=Object.values(this._remoteTracks);e.length&&(e.forEach((e=>{e.isAudioTrack()&&e.__releaseMediaElement()})),this._remoteTracks={})}setCDNEnabel(e){this._CDNEnable=e}setCDNUris(e){this._CDNUris=e}}class Sr extends class{constructor(e,t){this._store=e,this.abortCode=t,this._queue=[],this._busy=!1,this._isDestroyed=!1}_next(){this._busy=!1,this._execute()}_execute(){return 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.priority;if(i===nr.LOW)this._queue.push({command:e,resolve:t,reject:r});else{const o=this._queue.findIndex((e=>e.command.priority<i)),s=-1===o?this._queue.length-1:o;this._queue.splice(s,0,{command:e,resolve:t,reject:r})}this._execute()}))}isDestroyed(){return this._isDestroyed}destroy(){this._isDestroyed||(this._isDestroyed=!0,this._queue.forEach((e=>{e.resolve({code:this.abortCode})})),this._queue.length=0)}}{constructor(e,t,r,i,o,s,n,a,c){super(new Ir(e,t,r,i,o,s,n,a,c),v.ROOM_HAS_BEEN_DESTROYED)}get store(){return this._store}destroy(){super.destroy(),this._store.removeRemoteTracks()}}class gr extends Er{execute(e){return f(this,void 0,void 0,(function*(){const t=e.getResourcesByUserId(e.crtUserId),r=t.slice();t.length=0,O.info(`unpublish uris before rejoin -> ${JSON.stringify(r)}`);const i=yield e.context.setRTCTotalRes(e.roomId,pt(Vt.UNPUBLISH,r),mt([]),Vt.TOTAL_CONTENT_RESOURCE,mt([]));i!==n.SUCCESS?O.error(`unpublish uris before rejoin failed -> code: ${i}`):O.info("unpublish uris before rejoin success")}))}}class fr extends Er{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}execute(e,t){var o;return f(this,void 0,void 0,(function*(){const{context:a,service:R}=e,p=this.roomType===_.LIVE?L.L_RTC_CLIENT_JOIN_LIVING_ROOM_R:L.L_RTC_CLIENT_JOIN_RTC_ROOM_R;if(a.getConnectionStatus()!==c.CONNECTED)return r.error(p,{status:A.FAILED,code:v.SIGNAL_DISCONNECTED,msg:"im not connected"},{logSource:i.RTC}),{code:v.SIGNAL_DISCONNECTED};if(xt(a.getNaviInfo()))return r.error(p,{status:A.FAILED,code:v.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_usl error"},{logSource:i.RTC}),{code:v.PACKAGE_ENVIRONMENT_ERROR};if(!s("roomId",this.roomId,d,!0))return r.error(p,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(!s("roomType",this.roomType,(e=>void 0!==_[e])))return r.error(p,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> roomType"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(!s("outerUserDatas",this.outerUserDatas,u,!1))return r.error(p,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(this.outerUserDatas){if(!Object.keys(this.outerUserDatas).every((e=>s(`outerUserDatas.${e}`,this.outerUserDatas[e],l,!0))))return r.error(p,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:i.RTC}),{code:v.PARAMS_ERROR}}if(!R.getNaviMS().length)return r.error(p,{status:A.FAILED,code:v.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:i.RTC}),{code:v.NOT_OPEN_VIDEO_AUDIO_SERVER};O.info(`joinRoom -> roomId: ${this.roomId}; joinType: ${this.joinType||h.KICK}`);const{code:m,data:C}=yield a.joinRTCRoom(this.roomId,this.roomType,this.livingType,this.joinType,this.innerUserDatas,this.outerUserDatas);if(m!==n.SUCCESS||!C){O.warn(`joinRoom failed -> code: ${m}`);const e=40032===m?v.SIGNAL_JOIN_RTC_ROOM_REFUSED:m;return r.error(p,{status:A.FAILED,code:e,msg:`joinRoom failed -> code: ${m}`},{logSource:i.RTC}),{code:e}}O.info(`joinRoom success -> userId: ${a.getCurrentId()}, roomId: ${this.roomId}, data: ${JSON.stringify(C)}`),e.initWithRoomData(C);e.getResourcesByUserId(e.crtUserId).length>0&&t.push(new gr);const T=null===(o=C.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===o?void 0:o.value;return T&&e.setCDNUris(JSON.parse(T)[0]),r.info(p,{status:A.SUCCESSED,userId:e.crtUserId,roomId:this.roomId,data:C},{logSource:i.RTC}),{code:v.SUCCESS,data:C}}))}}function Or(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}=ft(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?jt.TINY:jt.NORMAL,resolution:"",uri:i.getPublishedResourceByTrackId(e.track.getTrackId()).uri}))),switchstream:!1}}))}function vr(e,t,r){return f(this,void 0,void 0,(function*(){const i=yield e.setRTCCDNUris(t,Vt.TOTAL_CONTENT_RESOURCE,JSON.stringify([r]));return i!==n.SUCCESS?(O.error(`spreadCDNInfo failed -> code: ${i}`),{code:v.SIGNAL_ERROR}):(O.info("spreadCDNInfo succeed"),{code:v.SUCCESS})}))}function Lr(e,t,r){return f(this,void 0,void 0,(function*(){const i=yield e.setRTCData(t,"cdn_uris",JSON.stringify([r]),!0,R.ROOM);return i!==n.SUCCESS?(O.error(`setRoomCDNInfo failed -> code: ${i}`),{code:v.SIGNAL_ERROR}):(O.info("setRoomCDNInfo succeed"),{code:v.SUCCESS})}))}function Ar(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([vr(t,o,s),Lr(t,o,s)])).every((e=>e.code===v.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:v.SIGNAL_ERROR,msg:"signal error"},{logSource:i.RTC}),n?{code:v.SUCCESS}:{code:v.SIGNAL_ERROR}}))}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(ar||(ar={})),function(e){e.BEGIN="begin",e.END="end"}(cr||(cr={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(_r||(_r={}));class Nr extends Er{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!==_.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!==v.SUCCESS||!o)return t;const s=JSON.parse(o);return e.setCDNUris(s),(null==s?void 0:s.broadcast)===_r.SPREAD&&(e.setCDNEnabel(!0),Ar(e)),t}))}}class Dr extends Er{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,(()=>p(r)&&r.every((e=>e instanceof lt||e.track instanceof lt))),!0))return O.warn(`update sublist failed, tracks is invalid -> roomId: ${o}`),{code:v.PARAMS_ERROR};O.info(`update subscribe list -> roomId: ${o}, forceReq: ${i}, tracks: ${r.map(wt)}`);let n=r.map((e=>e instanceof lt?{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):(O.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:v.SUCCESS}}const{pc:_,pushOtherRooms:d,headers:u}=this.subhook(r);_.updateSubRemoteTracks(n.map((e=>e.track)));const l=yield Or(n,!1,_,e);d&&(l.pushOtherRooms=d);const h=yield new Nr(u,l).execute(e,t),R=n.map((e=>e.track.getTrackId()));if(h.code!==v.SUCCESS)return{code:h.code};const{sdp:m,resultCode:C,message:T,subscribedList:E}=h.data;if(C!==v.SUCCESS)return O.error(`change subscribe list failed: ${C}`),{code:C};O.debug(`subscribe success: ${R.join(",")}`);const I=yield _.setRemoteAnswer(m.sdp);if(I!==v.SUCCESS)return{code:I};const S=null==E?void 0:E.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 A=e.getSubscribedList();return A.splice(0,A.length,...g),f.length?{code:v.SUCCESS,failedList:f}:{code:v.SUCCESS}}))}}class Ur extends Er{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(wt)},{logSource:i.RTC}),!s("tracks",o,(()=>p(o)&&o.length>0&&o.every((e=>e instanceof lt))),!0))return O.warn(`unsubscribe failed, tracks is invalid -> roomId: ${n}`),r.warn(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};O.info(`unsubscribe -> roomId: ${n}, tracks: ${o.map(wt)}`);const a=e.getSubscribedList().map((e=>Object.assign({},e))).filter((e=>!o.includes(e.track)));return e.polarisReport.sendR2(ar.SUBSCRIBE,cr.END,o.map((e=>e.getTrackId()))),r.info(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:o.map(wt),roomId:n},{logSource:i.RTC}),new Dr(a,this.subhook,!1).execute(e,t)}))}}class kr extends Er{constructor(e,t){super(),this.msgContent=e,this.subhook=t}get priority(){return nr.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){O.debug(`user joined -> ${n}`);const i=e.getResourcesByUserId(n);i||(t.switchRoleType?o.push(n):r.push(n)),e.setResourcesByUserId(n,i||[])}else O.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 Ur(r,this.subhook).execute(e,t),r.forEach((t=>e.removeRemoteTrack(t.getTrackId())))),i.length&&i.forEach((t=>e.removeResourcesByUserId(t)))}return n}))}}class Pr extends Er{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 Ur(r,this.subhook).execute(e,t),r.forEach((t=>{t.__innerDestroy(),e.removeRemoteTrack(t.getTrackId())})),this.onTrackUnpublish(r)}))}}class yr extends Er{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(wt),forceReq:n},{logSource:i.RTC}),!s("tracks",o,(()=>p(o)&&o.length>0&&o.every((e=>e instanceof lt||e.track instanceof lt))),!0))return O.warn(`subscribe failed, tracks is invalid -> roomId: ${a}`),r.error(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};O.info(`subscribe -> roomId: ${a}, tracks: ${o.map(wt)}`);const c=e.getSubscribedList().map((e=>Object.assign({},e))),_=o.map((e=>e instanceof lt?{track:e}:e));let d=!1;const u=[];return _.forEach((e=>{const t=e.track.getTrackId();u.push(t);const r=c.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:c.push(e),d=!0)})),d||n?(e.polarisReport.sendR2(ar.SUBSCRIBE,cr.BEGIN,u),r.info(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:o.map(wt),roomId:a},{logSource:i.RTC}),new Dr(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:v.SUCCESS})}))}}class Mr extends Er{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 nr.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,u=this.messageType,l=e.getResourcesByUserId(d)||[];switch(e.setResourcesByUserId(d,l),u){case Vt.MODIFY:a.push(...o);break;case Vt.PUBLISH:s.push(...o);break;case Vt.UNPUBLISH:n.push(...o);break;case Vt.TOTAL_CONTENT_RESOURCE:c=Lt(l,o),s.push(...c.publishedList),n.push(...c.unpublishedList),a.push(...c.modifiedList)}if(s.length>0){const r=l.map(gt),i=[],o=[];if(s.forEach((t=>{const s=gt(t),n=r.indexOf(s),{userId:a,tag:c,mediaType:_}=ft(s);n>-1?l[n]=t:l.push(t);let d=e.getRemoteTrack(s);d?d.isSubscribed()&&i.push(d):(d=_===He.AUDIO_ONLY?new ht(c,a):new Rt(c,a),e.addRemoteTrack(d),o.push(d)),d.__innerSetRemoteMuted(0===t.state)})),i.length){const r=i.map((e=>e.getTrackId()));O.debug(`resub tracks -> ${JSON.stringify(r)}`);const{code:o}=yield new yr(i,this.subhook,!0).execute(e,t);o!==v.SUCCESS&&O.error(`resub tracks failed -> code: ${o}, ids: ${JSON.stringify(r)}`)}this.callback.onTrackPublish(o)}if(n.length>0){const r=n.map(gt);for(let e=l.length-1;e>=0;e-=1){const t=l[e];r.includes(gt(t))&&l.splice(e,1)}const i=n.map((t=>{const r=gt(t);return e.getRemoteTrack(r)}));yield new Pr(this.subhook,i,this.callback.onTrackUnublish).execute(e,t)}if(a.length>0){const t=l.map(gt);for(let r=0;r<a.length;r+=1){const i=a[r],o=gt(i),s=t.indexOf(o);l[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!==_.LIVE)return;const h=this.msgContent;if(!h.cdn_uris)return;const R=(null===(r=e.getCDNUris())||void 0===r?void 0:r.enableInnerCDN)!==h.cdn_uris[0].enableInnerCDN;e.setCDNUris(h.cdn_uris[0]),R&&this.callback.onCDNEnableChange(!!(null===(i=e.getCDNUris())||void 0===i?void 0:i.enableInnerCDN))}))}}class br extends Er{constructor(e,t){super(),this.tracks=e,this.pubhook=t}_removePubFailedTracks(e,t){e.forEach((e=>{const r=e instanceof rt?e:e.track;O.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,_=[];r.forEach((e=>{const{track:t}=e instanceof rt?{track:e}:e;_.push(t)}));if(n.getLocalTracks().length+((e,t)=>{let r=0;return e.forEach((e=>{const i=e instanceof rt?e.getTrackId():e.track.getTrackId();t.getLocalTrack(i)||(e instanceof rt?r++:e.pubTiny&&e.track.isVideoTrack()&&(r+=2))})),r})(r,n)>10)return O.error(`publish failed, tracks limit exceeded -> roomId: ${c}`),{code:v.PUBLISH_TRACK_LIMIT_EXCEEDED,tracks:_};O.debug(`publish tracks -> roomId: ${c}, tracks: ${r.map(wt)}`),r.forEach((e=>{const{track:t,pubTiny:r}=e instanceof rt?{pubTiny:!1,track:e}:e;if(n.addLocalTrack(t),t.isVideoTrack()&&r){let e;try{e=t.__innerGetMediaStreamTrack().clone();const i=r.frameRate||Ge.FPS_15,o=r.resolution||Ke.W176_H144,{width:s,height:n}=Nt(o),a=kt(i);e.applyConstraints({width:s,height:n,frameRate:a})}catch(r){return null==e||e.stop(),void O.warn(`pubTiny failed -> id: ${t.getTrackId()}, msg: ${r.message}`)}n.addLocalTrack(new ot(t.getTag(),t.getUserId(),e,!0))}})),n.clearReTryExchangeTimer();const d=e.useMutilPeerC?[]:e.getSubscribedList(),u=yield Or(d,!1,n,e);i&&(u.pushOtherRooms=i);const l=yield new Nr(a,u).execute(e,o);if(l.code!==v.SUCCESS)return O.error(`publish failed -> roomId: ${c}, code: ${l.code}`),this._removePubFailedTracks(r,n),{code:l.code,tracks:_};const{sdp:h,resultCode:R,message:p}=l.data;if(R!==v.SUCCESS)return O.error(`publish failed -> roomId: ${c}, code: ${R}, msg: ${p}`),this._removePubFailedTracks(r,n),{code:R,tracks:_};const m=yield n.setRemoteAnswer(h.sdp);return m!==v.SUCCESS?{code:m,tracks:_}:Object.assign({},l,{tracks:_})}))}_mergePublishRes(e,t){return f(this,void 0,void 0,(function*(){const r=t.crtUserId,i=t.roomId;let o="";const s=[],a=t.getResourcesByUserId(r),c=[...a];let _=[];e.forEach((e=>{if(e.code!==v.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(gt(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))))||[];_=a}));const{publishedList:d}=Lt(a,c),u=yield t.context.setRTCTotalRes(i,pt(Vt.PUBLISH,d),mt(c),Vt.TOTAL_CONTENT_RESOURCE,mt(_));if(u!==n.SUCCESS)return O.error(`send publish streams notification failed: ${u}`),{code:v.SIGNAL_ERROR};t.setResourcesByUserId(r,c);const l=d.map((e=>gt(e)));t.polarisReport&&t.polarisReport.sendR2(ar.PUBLISH,cr.BEGIN,l),d.forEach((e=>{const r=t.useMutilPeerC?`${i}_${e.msid.split("_")[1]}`:`${i}_pub`,{pc:o}=t.peerMgr.getPCItemByPCName(r);o.getLocalTrack(`${e.msid}_${e.mediaType}`).__innerSetPublished(!0)})),O.debug(`publish success: ${l.join(",")}`);const h={code:v.SUCCESS};return o&&(h.liveUrl=o),s.length&&(h.failedTracks=s,h.code=v.SOME_TRACKS_PUBLISH_FAILED),h}))}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_PUBLISH_T,{trackIds:o.map(wt)},{logSource:i.RTC}),!s("tracks",o,(()=>p(o)&&o.length>0&&o.every((e=>e instanceof rt||e.track instanceof rt))),!0))return O.warn(`publish failed, tracks is invalid -> roomId: ${n}`),r.error(L.L_ABSTRACT_ROOM_PUBLISH_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};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 d=yield Promise.all(a),u=yield this._mergePublishRes(d,e);return r.info(L.L_ABSTRACT_ROOM_PUBLISH_R,{status:A.SUCCESSED,roomId:n,trackIds:o.map(wt)},{logSource:i.RTC}),u}))}}class xr extends Er{constructor(e,t){super(),this.tracks=e,this.unpubhook=t}__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:v.SUCCESS,tracks:i};n.forEach((e=>s.removeLocalTrackById(e))),e.polarisReport.sendR2(ar.PUBLISH,cr.END,n),s.clearReTryExchangeTimer();const a=e.useMutilPeerC?[]:e.getSubscribedList(),c=yield Or(a,!1,s,e),{pushOtherRooms:_,headers:d}=this.unpubhook(i,o);_&&(c.pushOtherRooms=_);const u=yield new Nr(d,c).execute(e,t);return u.code!==v.SUCCESS?(O.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=[],a=[],c=[];let _=[];for(let r=0;r<t.length;r++){const i=t[r];if(i.code!==v.SUCCESS){const{tracks:e}=i;s.push({code:i.code,tracks:e});continue}const{resultCode:n,message:d,mcuPublishList:u}=i.data;n!==v.SUCCESS&&O.error(`unpublish streams failed -> code: ${n}, msg: ${d}`);const l=i.tracks.map((e=>e.getTrackId()));c.push(...l);const h=l.map(e.getPublishedResourceByTrackId.bind(e)).filter((e=>!!e));a.push(...h),o.push(i);const R=u?u.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[];_=R}const d=e.getResourcesByUserId(r).filter((e=>!a.includes(e))),u=yield e.context.setRTCTotalRes(i,pt(Vt.UNPUBLISH,a),mt(d),Vt.TOTAL_CONTENT_RESOURCE,mt(_));if(u!==n.SUCCESS)return O.error("send unpublish notification failed:",u),{code:v.SIGNAL_ERROR};O.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,d);const l={code:v.SUCCESS};return s.length&&(l.failedTracks=s,l.code=v.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(wt)},{logSource:i.RTC});if(!s("tracks",a,(()=>a.every((e=>e.getUserId()===o&&e instanceof rt))),!0))return O.warn(`unpublish failed, tracks is invalid -> roomId: ${n}, tracks: ${a.map(wt)}`),r.error(L.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};const c=e.peerMgr.createPeerCList(a),_=[];for(let r=0;r<c.length;r++){const{tracks:i}=c[r];_.push(this.__unpublish(e,t,c[r],i))}const d=yield Promise.all(_),u=yield this._mergeUnpublishRes(e,d);return r.info(L.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:A.SUCCESSED,roomId:n,trackIds:a.map(wt)},{logSource:i.RTC}),u}))}}class Br extends Er{constructor(e){super(),this.localTrack=e}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()}],a=e.getResourcesByUserId(i),c=[];for(let e=0;e<a.length;e+=1){const t=a[e],r=gt(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 _=yield e.context.setRTCTotalRes(o,pt(Vt.MODIFY,c),mt(a),Vt.TOTAL_CONTENT_RESOURCE);_!==n.SUCCESS&&O.error("notice `track.enabled` change failed -> code: "+_)}))}}class wr extends Er{constructor(e,t,r){super(),this.pcName=e,this.isPub=t,this.retryHook=r}get priority(){return nr.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 Or(n,!0,s,e),{pushOtherRooms:c,headers:_}=this.retryHook(r);c&&(a.pushOtherRooms=c);const d=yield new Nr(_,a).execute(e,t);if(d.code!==v.SUCCESS)return void O.error(`reTryExchange failed: ${d.code}, pcName: ${r}`);const{sdp:u,resultCode:l}=d.data;l===v.SUCCESS?(s.clearReTryExchangeTimer(),yield s.setRemoteAnswer(u.sdp)):O.error(`reTryExchange failed: ${l}, pcName: ${r}`)}))}}class Vr extends Er{constructor(e,t,r){super(),this.subhook=e,this.callbacks=t,this.livingType=r}get priority(){return nr.HIGH}execute(e,t){return f(this,void 0,void 0,(function*(){const{livingType:o}=this,{roomId:s,crtUserId:a,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 O.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:u}=yield e.context.joinRTCRoom(s,c,o);if(d!==n.SUCCESS)return O.error(`RTC __onReconnected getRTCRoomInfo failed: ${d}`),void r.error(L.L_ABSTRACT_ROOM_RECONNECTED_R,{status:A.FAILED,code:d,msg:""},{logSource:i.RTC});O.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(u)}`);const l=[],h={},R={},p={},m=Bt(u,s),C=Object.keys(m),T=e.getAllUserIds();for(let t=C.length-1;t>=0;t-=1){const r=C[t],i=T.indexOf(r);if(-1===i){l.push(r),h[r]=vt(m[r]);continue}const o=e.getResourcesByUserId(r),s=m[r],{publishedList:n,modifiedList:a,unpublishedList:c}=Lt(o,s,!0);h[r]=vt(n),R[r]=vt(c),p[r]=vt(a),T.splice(i,1)}T.length&&T.forEach((t=>{e.removeResourcesByUserId(t)})),e.assignRoomData(m),T.length&&this.callbacks.onUserLeave(T),l.length&&this.callbacks.onUserJoin(l);for(const r in R){if(r===a)continue;const i=R[r];if(i.length){const r=i.map((t=>e.getRemoteTrack(gt(t))));yield new Pr(this.subhook,r,this.callbacks.onTrackUnpublish).execute(e,t)}}return Object.keys(h).forEach((t=>{const r=h[t];if(0===r.length)return;const i=r.map((t=>{const r=gt(t),{userId:i,tag:o,mediaType:s}=ft(r),n=s===He.AUDIO_ONLY?new ht(o,i):new Rt(o,i);return e.addRemoteTrack(n),n.__innerSetRemoteMuted(0===t.state),n}));this.callbacks.onTrackPublish(i)})),Object.keys(p).forEach((t=>{p[t].forEach((t=>{const r=gt(t),i=e.getRemoteTrack(r);i.__innerSetRemoteMuted(0===t.state),i.isAudioTrack()?this.callbacks.onAudioMuteChange(i):this.callbacks.onVideoMuteChange(i)}))})),e.roomMode===_.LIVE&&this.executeInLivingRoom(e,u),r.info(L.L_ABSTRACT_ROOM_RECONNECTED_R,{status:A.SUCCESSED,roomData:u},{logSource:i.RTC}),{data:u}}))}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)}}const Fr="evt-leave";class $r extends t{constructor(e,t,r,i,o,s,n,a,c,_=Gt()){super(),this._context=e,this._runtime=t,this._roomId=r,this._service=o,this._initOptions=s,this._useMutilPeerC=c,this._clientSessionId=_,this._appListener=null,this._reportListener=null,this._onRecvPKMsg=null,this._polarisReport=new mr(this._context,this._runtime,this._roomId,this),this._peerCManager=new Tr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._invoker=new Sr(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 fr(this._roomId,e,t,r,i,o));return s!==v.SUCCESS?{code:s}:(this._initWithRoomData(n.offlineKickTime),{code:s,data:n})}))}_initWithRoomData(e){var t;this._pinger=new $t(this._store.roomId,this._store.roomMode,this._context,this._initOptions.pingGap,1e3*e),this._pinger.onFailed=this._kickoff.bind(this),this._pinger.onPingResult=this._handlePingResult.bind(this),this._pinger.start(),null===(t=this._polarisReport)||void 0===t||t.sendR1()}_handlePingResult(e){this._callAppListener("onPing",e)}setBitrate(e,t,r){if(this._useMutilPeerC)return void O.error("`RCAbstractRoom.setBitrate` is disabled, use `RCLocalTrack.setBitrate` instead.");O.warn("`RCAbstractRoom.setBitrate` will be deprecated, use `RCLocalTrack.setBitrate` instead."),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)):O.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&&O.info(`${e} callback ->`,...t);const s=null===(o=this._appListener)||void 0===o?void 0:o[e];if(s)try{s(...t)}catch(e){O.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;O.info(`recv inner msg -> message: ${JSON.stringify(e)} | roomid: ${this._roomId}`);const i=e.content;switch(e.messageType){case Vt.KICK:this._kickoff(!0,i);break;case Vt.STATE:this._stateHandle(i);break;case Vt.MODIFY:case Vt.PUBLISH:case Vt.UNPUBLISH:case Vt.TOTAL_CONTENT_RESOURCE:this._resourceHandle(i,e.messageType,e.senderUserId);break;case Vt.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",e.messageType,e.content);break;case Vt.USER_NOTIFY:O.warn(`TODO: ${Vt.USER_NOTIFY}`);break;case Vt.PK_INVITE:case Vt.PK_CANCEL_INVITE:case Vt.PK_INVITE_TIMEOUT:case Vt.PK_INVITE_ANSWER:case Vt.PK_END:this._onRecvPKMsg&&this._onRecvPKMsg(e);break;case Vt.OTHER_ROOM_OFFLINE:break;default:this._callAppListener("onMessageReceive",e.messageType,e.content,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;O.warn(`onKickOff -> byServer: ${e}`),this.emit(Fr),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(Fr),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 Mr(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 kr(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,sr.ANCHOR))),s.length&&s.forEach((e=>this._callAppListener("onSwitchRole",e,sr.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!==n.SUCCESS?(O.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:v.SIGNAL_ERROR}):(r.info(L.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:A.SUCCESSED,name:e,content:t},{logSource:i.RTC}),{code:v.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 a=yield this._context.setRTCData(this._roomId,e,t,s,R.ROOM,o);return a!==n.SUCCESS?(O.error(`SetRoomAttributeValue Failed: ${a}`),r.error(L.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:A.FAILED,code:a,msg:""},{logSource:i.RTC}),{code:v.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:v.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,R.ROOM,t);return s!==n.SUCCESS?(O.error(`DeleteRoomAttribute Failed: ${s}`),r.error(L.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:A.FAILED,code:s,msg:""},{logSource:i.RTC}),{code:v.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:v.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,R.ROOM);return r!==n.SUCCESS?(O.error(`GetRoomAttributes Failed: ${r}`),{code:v.SIGNAL_ERROR}):{code:v.SUCCESS,data:i}}))}_setUserAttributeValue(e,t,r){return this._context.setRTCData(this._roomId,e,t,!1,R.PERSON,r)}_deleteUserAttributes(e,t){return this._context.removeRTCData(this._roomId,e,!1,R.PERSON,t)}_getUserAttributes(e){return this._context.getRTCData(this._roomId,e,!1,R.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(rt.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(rt.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)})),this._peerCManager.clear(),this._peerCManager=null}_onLocalTrackDestroied(e){e instanceof ot&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(e){return f(this,void 0,void 0,(function*(){this._invoker.push(new Br(e))}))}publish(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new br(e,this._pubhook.bind(this)))}))}_getPushOtherRoomsParams(){return[]}_reTryExchange(e,t){return f(this,void 0,void 0,(function*(){this._invoker.push(new wr(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 xr(e,((e,t)=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(t)}))))}))}_getResourceById(e){return this._store.getPublishedResourceByTrackId(e)}_isValidResourceId(e){var t;const{userId:r}=ft(e);return!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>gt(t)===e)))}_subhook(e){const{pc:t,pcName:r}=this._peerCManager.createPeerCList(e)[0];return t.on(pr.__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(rt.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.on(rt.__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 yr(e,this._subhook.bind(this),!1))}))}unsubscribe(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new Ur(e,this._subhook.bind(this)))}))}getLocalTrack(e){return this._store.getLocalTrack(e)}getLocalTracks(){return this._store.getLocalTracks()}getRemoteTrack(e){return this._store.getRemoteTrack(e)||null}updateSubList(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new Dr(e,this._subhook.bind(this),!1))}))}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 Cr(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}__onReconnected(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new Vr(this._subhook.bind(this),{onPeerClosed:this._rtcpeerClosed.bind(this),onAudioMuteChange:this._onAudioMuteChange.bind(this),onVideoMuteChange:this._onVideoMuteChange.bind(this),onUserJoin:this._callAppListener.bind(this,"onUserJoin"),onUserLeave:this._callAppListener.bind(this,"onUserLeave"),onTrackPublish:this._onTrackPublish.bind(this),onTrackUnpublish:this._onTrackUnpublish.bind(this),onCDNEnableChange:this._callAppListener.bind(this,"onCDNEnableChange")},e))}))}_onAudioMuteChange(e){this._callAppListener("onAudioMuteChange",e)}_onVideoMuteChange(e){this._callAppListener("onVideoMuteChange",e)}_registerPKMsgListener(e){this._onRecvPKMsg=e}_quitAllPKRoom(){}getClientSessionId(){return this._clientSessionId}}class Gr extends Er{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!==v.SUCCESS)return O.error(`set MCU config failed: ${n}`),{code:n};O.info("set MCU config success"),a.pull_url&&e.setCDNUris(JSON.parse(a.pull_url));const c=this.cdnValues;return n===v.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))&&Ar(e),{code:n,res:a}}))}}var Kr,Hr,jr,Jr;!function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(Kr||(Kr={})),function(e){e[e.CUSTOMIZE=1]="CUSTOMIZE",e[e.SUSPENSION=2]="SUSPENSION",e[e.ADAPTATION=3]="ADAPTATION"}(Hr||(Hr={})),function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(jr||(jr={})),function(e){e[e.AUDIO_VIDEO_ALL=0]="AUDIO_VIDEO_ALL",e[e.AUDIO_VIDEO_NO=1]="AUDIO_VIDEO_NO",e[e.AUDIO_ALL_VIDEO_NO=2]="AUDIO_ALL_VIDEO_NO",e[e.AUDIO_NO_VIDEO_ALL=3]="AUDIO_NO_VIDEO_ALL",e[e.AUDIO_VIDEO_INPUT=4]="AUDIO_VIDEO_INPUT",e[e.AUDIO_ALL_VIDEO_INPUT=5]="AUDIO_ALL_VIDEO_INPUT",e[e.AUDIO_NO_VIDEO_INPUT=6]="AUDIO_NO_VIDEO_INPUT",e[e.AUDIO_INPUT_VIDEO_ALL=7]="AUDIO_INPUT_VIDEO_ALL",e[e.AUDIO_INPUT_VIDEO_NO=8]="AUDIO_INPUT_VIDEO_NO",e[e.ROOM_AUDIO_VIDEO_APPEND=9]="ROOM_AUDIO_VIDEO_APPEND",e[e.ROOM_AUDIO_VIDEO_NOT_APPEND=10]="ROOM_AUDIO_VIDEO_NOT_APPEND",e[e.ROOM_AUDIO_APPEND=11]="ROOM_AUDIO_APPEND",e[e.ROOM_AUDIO_NOT_APPEND=12]="ROOM_AUDIO_NOT_APPEND",e[e.ROOM_VIDEO_APPEND=13]="ROOM_VIDEO_APPEND",e[e.ROOM_VIDEO_NOT_APPEND=14]="ROOM_VIDEO_NOT_APPEND"}(Jr||(Jr={}));const Wr=()=>({version:2,mode:Hr.SUSPENSION});class Yr{constructor(e,t){this._invoker=e,this._isValidTrackId=t,this._values=Wr()}setHostVideoTrack(e){if(O.info(`setHostVideoTrack -> videoTrackId: ${e}`),!this._isValidTrackId(e))return O.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}=ft(e);return t!==He.VIDEO_ONLY?(O.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=Ot(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){O.info(`setMixLayoutMode -> mode: ${e}`);return[Hr.CUSTOMIZE,Hr.SUSPENSION,Hr.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):(O.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:Kr.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(O.info(`setOutputVideoResolution -> resolution: ${e}`),!Dt(e))return O.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}=Nt(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(O.info(`setOutputVideoFPS -> fps: ${e}`),!Ut(e))return O.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=kt(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 O.info(`setOutputVideoBitrate -> bitrate: ${e}`),!o(e)||e<=0?(O.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(O.info(`setOutputTinyVideoResolution -> resolution: ${e}`),!Dt(e))return O.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}=Nt(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(O.info(`setOutputTinyVideoFPS -> fps: ${e}`),!Ut(e))return O.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=kt(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 O.info(`setOutputTinyVideoBitrate -> bitrate: ${e}`),!o(e)||e<=0?(O.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 O.info(`setOutputVideoRenderMode -> renderMode: ${e}`),[jr.CROP,jr.WHOLE].includes(e)?this._addOutputValue("video",e,"exparams"):(O.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 O.info(`setOutputAudioBitrate -> bitrate: ${e}`),o(e)&&e>0?this._addOutputValue("audio",e):(O.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 O.info(`setOutputBackgroundColor -> color: ${e}`),/^0x[a-fA-F0-9]{6}$/.test(e)?this._addOutputValue("video",e,"backgroundColor"):(O.error(`setOutputBackgroundColor failed -> color is invalid: ${e}`),r.error(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(O.info(`addOutputBackgroundPicture -> uri: ${e}, x: ${t}, y: ${s}, w: ${n}, h: ${a}`),!T(e))return O.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 O.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===(d=null===(_=null===(c=this._values.output)||void 0===c?void 0:c.video)||void 0===_?void 0:_.backgroundPicture)||void 0===d?void 0:d.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(O.info(`removeOutputBackgroundPicture -> uri: ${e}`),!T(e))return O.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 O.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 O.info(`setOutputBackgroundPictureFillMode -> fillMode: ${e}`),[Kr.CROP,Kr.WHOLE].includes(e)?this._addOutputValue("video",{fillMode:e},"backgroundPicture"):(O.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;O.info(`addPublishStreamUrls -> urls: ${e.join(",")}`);const s=/^rtmp:\/\/.+/;if(!p(e)||0===e.length||e.some((e=>!s.test(e))))return O.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?(O.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;O.info(`removePublishStreamUrls -> urls: ${e.join(",")}`);const s=/^rtmp:\/\/.+/;if(!p(e)||0===e.length||e.some((e=>!s.test(e))))return O.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 O.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(O.info(`addCustomizeLayoutVideo -> trackId: ${e}, x: ${t}, y: ${s}, width: ${n}, height: ${a}`),!d(e)||!this._isValidTrackId(e))return O.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 O.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 O.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:_,mediaType:u}=ft(e);if(u!==He.VIDEO_ONLY)return O.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 l=Ot(c,_),h=this._values.input||(this._values.input={}),R=h.video||(h.video=[]);return R.some((e=>e.height===a&&e.width===n&&e.stream_id===l&&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):(R.push({user_id:c,stream_id:l,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(O.info(`clearCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return O.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}=ft(e);if(s!==He.VIDEO_ONLY)return O.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=Ot(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(){O.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(O.info(`setCustomizeInputAudio -> trackIds: ${e.join(",")}`),e.some((e=>this._isValidTrackId(e))))return O.warn(`setCustomizeInputAudio failed -> trackIds contain invalid items: $${e.join(",")}`),r.error(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}=ft(e);return{stream_id:Ot(t,r),user_id:t}})),this._values.inputFilterMode=Jr.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(O.info(`addCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return O.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}=ft(e),a=Ot(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=Jr.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(O.info(`removeCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return O.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}=ft(e),n=Ot(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(){O.info("clearCustomizeInputAudio ->");const e=this._values.input;return(null==e?void 0:e.audio)&&delete e.audio,this._values.inputFilterMode=Jr.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(O.info(`addPictureWaterMark -> trackId: ${e} uri: ${t}, x: ${s}, y: ${n}, w: ${a}, h: ${c}`),!this._isValidTrackId(e))return O.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 O.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 O.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:_,tag:d}=ft(e),u=Ot(_,d),l=(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen;O.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(l)}`);const h=l.filter((e=>e.streamId===u))[0];return O.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}]}),O.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(l)}`),this._values.waterMark.singleScreen=l,O.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(){O.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(!d(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}=ft(e),n=Ot(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 O.info("MCUConfigBuilder.reset ->"),this._values=Wr(),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 Gr(t,this._values));return e&&(this._values=Wr()),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 qr,zr,Qr;!function(e){e[e.VIDEO=0]="VIDEO",e[e.AUDIO=1]="AUDIO"}(qr||(qr={})),function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(zr||(zr={}));class Zr extends Er{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 Or(a,!1,s,e),{pushOtherRooms:_,headers:d}=this.hooks(i[o]);c.pushOtherRooms=_;const u=yield new Nr(d,c).execute(e,t);if(u.code!==v.SUCCESS)return void O.error(`exchange with pushOtherRoom failed: ${u.code}`);const{sdp:l,resultCode:h}=u.data;if(h!==v.SUCCESS)return void O.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 O.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 Xr extends Er{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}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],a={inviteeRoomId:i,inviterRoomId:r,userId:t.crtUserId},c={roomId:t.roomId,endRoomId:e,sessionId:s,content:JSON.stringify(a),keys:[`${r}|${o}`]};O.info(`quitRoomPK -> params: ${JSON.stringify(c)}`);const _=yield t.context.endRoomPK(c);return _!==n.SUCCESS?(O.error(`quitRoomPK failed: ${_}`),{code:v.SIGNAL_ERROR}):(O.info("quitRoomPK success"),delete this._PKInfo[e],{code:v.SUCCESS})}))}execute(e,t){return f(this,void 0,void 0,(function*(){const{room:o,isQuitPK:s}=this,n=o.getRoomId();return O.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 Zr(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:v.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=_,this._clientSessionId=d,this._inviteTimeout=30,this._appListener=null,this._joinedPKRooms={},this._registerPKMsgListener(this._onRecvPKMsg.bind(this)),this._mainRoomId=this._mainLivingRoom.getRoomId()}_callAppListener(e,...t){var r;O.info(`${e} callback ->`,...t);const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){O.error(e)}}_onInvite(e){const t=e.inviteInfo||{},{inviterRoomId:r,inviterUserId:i,extra: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:_,extra:d}=r,u={agree:1===t,inviterRoomId:s,inviterUserId:o,inviteeRoomId:_,inviteeUserId:n,extra:d};this._PKInfo[_]=this._PKInfo[_]||{inviteSessionId:i,inviterRoomId:s,inviterUserId:o,inviterUserAutoMix:a,inviteeRoomId:_},this._PKInfo[_].inviteeUserAutoMix=c,this._callAppListener("onResponseJoinOtherRoom",u)}createLeaveOtherRoomCommand(e,t){return new Xr(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 Vt.PK_INVITE:this._onInvite(r);break;case Vt.PK_CANCEL_INVITE:this._onCancelInvite(r);break;case Vt.PK_INVITE_TIMEOUT:this._onInviteTimeout(r);break;case Vt.PK_INVITE_ANSWER:this._onInviteAnswer(r);break;case Vt.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,d,!0)||!s("inviteeUserId",t,d,!0))return r.error(L.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> inviteeRoomId 或 inviteeUserId"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};O.info(`requestRoomPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; options: ${JSON.stringify(o||{})}`);const a=Gt(),c=!E(null==o?void 0:o.autoMix)||(null==o?void 0:o.autoMix),_={inviteSessionId:a,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:c,inviteeRoomId:e,inviteeUserId:t,inviteeTimeoutTime:this._inviteTimeout,extra:(null==o?void 0:o.extra)||""},u={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteTimeout:this._inviteTimeout,inviteInfo:JSON.stringify(_),inviteSessionId:a};O.info(`requestRoomPK -> params: ${JSON.stringify(u)}`);const l=yield this._context.requestRoomPK(u);return l!==n.SUCCESS?(O.error(`requestRoomPK failed: ${l}`),r.error(L.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:l,msg:""},{logSource:i.RTC}),{code:l}):(O.info("requestRoomPK success"),this._PKInfo[e]={inviteSessionId:a,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:v.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,d,!0)||!s("inviteeUserId",t,d,!0))return r.error(L.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> inviteeRoomId or inviteeUserId"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(!this._PKInfo[e])return O.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:v.PARAMS_ERROR,msg:`The request to connect with ${t} user in room ${e} is not initiated`},{logSource:i.RTC}),{code:v.PARAMS_ERROR};O.info(`canceRequestJoinPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; extra: ${o}`);const a={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(a)};O.info(`canceRequestJoinPK -> params: ${JSON.stringify(c)}`);const _=yield this._context.cancelRoomPK(c);return _!==n.SUCCESS?(O.error(`canceRequestJoinPK failed: ${_}`),r.error(L.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:_,msg:`The request to connect with ${t} user in room ${e} is not initiated`},{logSource:i.RTC}),{code:_}):(O.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:v.SUCCESS})}))}responseJoinOtherRoom(e,t,o,a){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:a,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),!s("inviterRoomId",e,d,!0)||!s("inviterUserId",t,d,!0))return r.error(L.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> inviterRoomId or inviterUserId"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(!this._PKInfo[e])return O.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:v.PARAMS_ERROR,msg:`User ${t} in room ${e} did not send a request for connection`},{logSource:i.RTC}),{code:v.PARAMS_ERROR};O.info(`responseRoomPK -> inviterRoomId: ${e}; inviterUserId: ${t}; agree: ${o}; options: ${JSON.stringify(a||{})}`);const{inviteSessionId:c,inviterUserAutoMix:_}=this._PKInfo[e],u=!E(null==a?void 0:a.autoMix)||(null==a?void 0:a.autoMix),l={inviteSessionId:c,inviterRoomId:e,inviterUserId:t,inviterUserAutoMix:_,inviteeRoomId:this._mainRoomId,inviteeUserId:this._context.getCurrentId(),inviteeUserAutoMix:u},h=Object.assign(l,{inviterUserAutoMix:_}),R=o?Object.assign(l,{MultiRoomKey:`${e}|${this._mainRoomId}`,MultiRoomValue:JSON.stringify(h)}):l;!I(null==a?void 0:a.extra)&&Object.assign(R,{extra:a.extra});const p={agree:o,roomId:this._mainRoomId,inviteSessionId:c,inviteRoomId:e,inviteUserId:t,content:JSON.stringify(R),key:`${e}|${this._mainRoomId}`,value:JSON.stringify(l)};O.info(`responseRoomPK -> params: ${JSON.stringify(p)}`);const m=yield this._context.responseRoomPK(p);return m!==n.SUCCESS?(O.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}):(O.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:a,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),this._PKInfo[e].inviteeUserAutoMix=u,{code:v.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,d,!0))return r.error(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(this._context.getConnectionStatus()!==c.CONNECTED)return r.error(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:v.SIGNAL_DISCONNECTED,msg:"IM disconnected"},{logSource:i.RTC}),{code:v.SIGNAL_DISCONNECTED};if(O.info(`JoinPKRoom, roomId: ${e}`),this._joinedPKRooms[e])return r.warn(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:v.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:v.REPERT_JOIN_ROOM};const t=qr.VIDEO,o={extra:`{"roomId": "${this._mainRoomId}"}`},n=new ii(this._context,this._runtime,e,this._service,this._initOptions,t,!1,!1,!1,this._clientSessionId),{code:a,data:u}=yield n.__innerInit(_.LIVE,void 0,t,o);return a!==v.SUCCESS?(O.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}):(O.info(`JoinPKRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(u)}`),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:v.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"}(Qr||(Qr={}));class ti extends Er{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 O.error("the `enableInnerCDN` is disabled in PK room"),r.error(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.FAILED,code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!E(o))return O.error("`enable` is invalid"),r.error(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> enable"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};e.setCDNEnabel(o);const s={version:2,output:{inCDNModel:o?Qr.OPEN:Qr.STOP}},{code:n}=yield new Gr(s,this.cdnValues).execute(e,t);if(n!==v.SUCCESS)return O.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:v.SIGNAL_ERROR};const a=e.getCDNUris();if(a&&a.broadcast!==_r.SPREAD)return O.info("enableInnerCDN succeed"),r.info(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.SUCCESSED,enable:o},{logSource:i.RTC}),{code:v.SUCCESS};const{code:c}=yield Ar(e);return c===v.SUCCESS?(O.info("enableInnerCDN succeed"),r.info(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.SUCCESSED,enable:o},{logSource:i.RTC}),{code:v.SUCCESS}):(O.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})}))}}class ri extends Er{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,S.ViewerToAnchor,this.livingType);if(i!==n.SUCCESS||!o)return{code:i};e.initWithRoomData(o);e.getResourcesByUserId(e.crtUserId).length>0&&t.push(new gr);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 ii extends $r{constructor(e,t,r,i,o,s,n,a,c,d){super(e,t,r,_.LIVE,i,o,n,a,c,d),this._livingType=s,this._mcuConfigBuilder=new Yr(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===qr.AUDIO||e===qr.VIDEO)))return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> livingType"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};const{code:_,data:d}=yield c.__innerInit.call(this,e,t,o,n,a);return _===v.SUCCESS&&d&&this._initAfterCatchRoomData(d),{code:_,data:d}}))}__innerInitByIdentityChange(){return f(this,void 0,void 0,(function*(){const{code:e,data:t}=yield this._invoker.push(new ri(this._livingType));return e===n.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):(O.warn("the `publish` is disabled in PK room "),r.error(L.L_ABSTRACT_ROOM_PUBLISH_R,{status:A.FAILED,code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:v.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):(O.warn("the `unpublish` is disabled in PK room "),r.error(L.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:A.FAILED,code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}_isValidResourceId(e){var t;const{userId:r}=ft(e),i=!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>gt(t)===e)));let o=!1;const{code:s,roomPKHandler:n}=this.getRoomPKHandler();if(s!==v.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:(O.error("the `getMCUConfigBuilder` is disabled in PK room"),{code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}enableInnerCDN(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new ti(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=Bt(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]},Vt.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)===zr.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 Zr(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:v.SUCCESS,roomPKHandler:this._roomPKHandler}):(O.error("the `getRoomPKHandler` is disabled in PK room"),r.error(L.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:A.SUCCESSED,code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:v.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 oi extends $r{constructor(e,t,r,i,o,s,n,a,c){super(e,t,r,_.RTC,i,o,s,n,a,c)}}const si=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}},ni=(e,t="")=>si.push(e,t);class ai{constructor(e,t,r,i){this._context=e,this._useMutilPeerC=i,this._rtcToken="",this._liveUrl="",this._subTracks=[],this._clientSessionId=Gt(),this._livingType=null,this._mediaType=null,this._subTiny=!1,this._fromRetry=!1,this._appListener=null,this._service=new Ht(t,e,r.mediaServer),this._peerCManager=new Tr(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,_.LIVE,e);if(t!==n.SUCCESS)return O.error(`getRTCToken failed: ${t}`),{code:v.SIGNAL_ERROR};this._rtcToken=i.rtcToken}return{code:v.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:t,RoomId:r,RoomType:_.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===v.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 ni((()=>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(xt(this._context.getNaviInfo()))return r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:v.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:i.RTC}),{code:v.PACKAGE_ENVIRONMENT_ERROR,tracks:a};if(!this._fromRetry&&(null===(n=this._pc)||void 0===n||n.clearReTryExchangeTimer()),this._fromRetry=!1,!l(e))return O.error(`liveUrl is invalid: ${e}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:`params error -> liveUrl: ${e}`},{logSource:i.RTC}),{code:v.PARAMS_ERROR,tracks:a};if(![qr.AUDIO,qr.VIDEO].includes(t))return O.error(`livingType is invalid: ${t}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:`params error -> livingType: ${t}`},{logSource:i.RTC}),{code:v.PARAMS_ERROR,tracks:a};if(![He.AUDIO_ONLY,He.VIDEO_ONLY,He.AUDIO_VIDEO].includes(o))return O.error(`mediaType is invalid: ${o}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:`params error -> -> mediaType: ${o}`},{logSource:i.RTC}),{code:v.PARAMS_ERROR,tracks:a};if(this._liveUrl&&this._liveUrl!==e)return r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:v.BROADCAST_SUB_LIST_NOT_EMPTY,msg:"repeat subscribe"},{logSource:i.RTC}),{code:v.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(pr.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this._pc.registerReportListener(this._reportListener),this._pc.__reportR3R4ToPolaris()}this._liveUrl=e;const{code:c,headers:_}=yield this._getReqHeaders(t);if(c!==v.SUCCESS)return r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:c,msg:""},{logSource:i.RTC}),{code:c,tracks:a};const d=`rc_mcu_${Date.now()}`,u="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new ht(u,d),new Rt(u,d)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const h={sdp:yield this._pc.createOffer(!0),liveUrl:e,mediaType:o,simulcast:s?jt.TINY:jt.NORMAL,switchstream:!1},R=yield this._service.broadcastSubscribe(_,h);if(R.code!==v.SUCCESS)return O.error(`andience subscribe failed: ${R.code}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:R.code,msg:""},{logSource:i.RTC}),{code:R.code,tracks:a};const p=R.data;if(p.resultCode!==v.SUCCESS)return O.error(`andience subscribe failed! code: ${p.resultCode}; message: ${p.message}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:p.resultCode,msg:""},{logSource:i.RTC}),{code:p.resultCode,tracks:a};O.debug(`andience subscribe success: ${e}`),this._livingType=t,this._mediaType=o,this._subTiny=s;const{sdp:m,subscribedList:C}=p,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:v.SUCCESS,tracks:T}}))}unsubscribe(){return f(this,void 0,void 0,(function*(){return ni((()=>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:v.SUCCESS};const{headers:t}=yield this._getReqHeaders(),{code:o}=yield this._service.broadcastExit(t);return o!==v.SUCCESS?(O.error(`broadcast unsubscribe failed: ${o}`),r.error(L.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:A.FAILED,code:o,msg:""},{logSource:i.RTC})):(O.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){O.error(e)}}}var ci,_i;!function(e){e.RTMP="rtmp",e.FLV="flv",e.HLS="hls"}(ci||(ci={})),function(e){e[e.NOT_HTTPS=0]="NOT_HTTPS",e[e.HTTPS=1]="HTTPS"}(_i||(_i={}));const di=Object.assign(Object.assign({},Nt(Ke.W176_H144)),{frameRate:kt(Ge.FPS_15)});class ui{constructor(e,t,r,i,o,s,n,a=Gt()){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._reportListener=null,this._setInitData(),this._service=new Ht(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new mr(this._context,this._runtime,this._roomId,this,or.Audience),this._polarisReport.sendR1(),this._peerCManager=new Tr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._context.onrtcdatachange=this.singalDataChange.bind(this)}_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 ht(i,"",e):new Rt(i,"",e);a.push(o)}));const c=[],_=[];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 ht(r,o):new Rt(r,o);_.push(s)}))}));const d=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:_,remoteMCUTracks:a,remoteTracks:[..._,...a],CDNUris:d||{}}})(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=gt(e);this._roomRes[t]=e}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinLivingRoomAsAudience` to catch another instance.";return O.warn(e),v.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 O.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});O.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=gt(e),{userId:o,tag:s,mediaType:n}=ft(r),a=[this._roomId,s,n].join("_");if(!this._remoteTracks[a]){const r=n===He.AUDIO_ONLY?new ht(s,"",this._roomId):new Rt(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}=Lt(r,e);if(i.length){const e=r.map(gt),t=[],o=[];if(i.forEach((i=>{const s=gt(i),n=e.indexOf(s),{userId:a,tag:c,mediaType:_}=ft(s);n>-1?r[n]=i:r.push(i);let d=this._remoteTracks[s];this._roomRes[s]=i,d?d.isSubscribed()&&t.push(d):(d=_===He.AUDIO_ONLY?new ht(c,a):new Rt(c,a),this._remoteTracks[s]=d,o.push(d)),d.__innerSetRemoteMuted(0===i.state)})),t.length){const e=t.map((e=>e.getTrackId()));O.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:r}=yield ni((()=>this._subscribeHandle(t,!0)));r!==v.SUCCESS&&O.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(e)}`)}this._callAppListener("onAnchorTrackPublish",o)}if(o.length){const e=o.map(gt);for(let t=r.length-1;t>=0;t-=1){const i=r[t];e.includes(gt(i))&&r.splice(t,1)}const t=o.map((e=>{const t=gt(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t,"onAnchorTrackUnpublish")}if(s.length){const e=r.map(gt);for(let t=0;t<s.length;t++){const i=s[t],o=gt(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;O.info(`${e} callback ->`,...t);const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){O.error(e)}}_reTryExchange(){return f(this,void 0,void 0,(function*(){ni((()=>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!==v.SUCCESS)return O.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:o}=r.data;if(o!==v.SUCCESS)return O.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!==v.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 _=0===r,{width:d,height:u,frameRate:l}=_?It(c):di;o.resolutionInfo.push({trackId:c.id,simulcast:_?jt.NORMAL:jt.TINY,resolution:`${d}x${u}`});const h=Je(d,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?jt.TINY:jt.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(wt),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:v.ROOM_HAS_BEEN_DESTROYED,msg:"room destroyed"},{logSource:i.RTC}),{code:v.ROOM_HAS_BEEN_DESTROYED};if(!s("tracks",e,(()=>p(e)&&e.length>0&&e.every((e=>e instanceof lt||e.track instanceof lt))),!0))return r.error(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:v.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 lt?{track:e}:e));let d=!1;const u=[];return _.forEach((e=>{const t=e.track.getTrackId();u.push(t);const r=c.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:c.push(e),d=!0)})),d||t?(null===(o=this._polarisReport)||void 0===o||o.sendR2(ar.SUBSCRIBE,cr.BEGIN,u),r.info(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:A.SUCCESSED,trackIds:e.map(wt),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:v.SUCCESS})}))}_addPeerCEvent(){this._pc.on(pr.__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)):O.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:_.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:v.ROOM_HAS_BEEN_DESTROYED};if(!s("resources",e,(()=>p(e)&&e.every((e=>e instanceof lt||e.track instanceof lt))),!0))return{code:v.PARAMS_ERROR};let i=e.map((e=>e instanceof lt?{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:v.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!==v.SUCCESS)return{code:c.code};const{sdp:_,resultCode:d,message:u,subscribedList:l}=c.data;if(d!==v.SUCCESS)return O.error("change subscribe list failed:",u,d),{code:d};i.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:i}=ft(t.getTrackId()),o=[i,r].join("_");_.sdp=_.sdp.replace(new RegExp(e,"g"),o)}}));const h=yield this._pc.setRemoteAnswer(_.sdp);if(h!==v.SUCCESS)return{code:h};const R=null==l?void 0:l.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 R.includes(r)}return null==R?void 0:R.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:v.SUCCESS,failedList:T}:{code:v.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||ci.FLV,s=this._initOptions.pullInnerCDNUseHttps===_i.NOT_HTTPS?_i.NOT_HTTPS:_i.HTTPS;if(!this._CDNUris.url)return O.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${v.CDN_RESOURCE_IS_EMPTY}`),{code:v.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 _=`${this._CDNUris.url}?`;c&&(_+=c);const{code:d,res:u}=yield this._service.getCDNResourceInfo(n,_);return d!==v.SUCCESS?(O.error(`getCDNPlayUrl failed: ${d}`),{code:d}):(O.info(`getCDNPlayUrl success: ${null==u?void 0:u.data.pull_url}`),{code:d,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&&!Dt(e))return O.error("`resolution` is invalid"),r.error(L.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> resolution"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(t&&!Ut(t))return O.error("`fps` is invalid"),r.error(L.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> fps"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};const{width:o,height:s}=e?Nt(e):{width:null,height:null},n=t?kt(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 ni((()=>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,(()=>p(e)&&e.length>0&&e.every((e=>e instanceof lt))),!0))return O.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),r.error(L.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:v.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(ar.SUBSCRIBE,cr.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 ni((()=>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.onrtcdatachange=()=>{})}))}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,_.LIVE);e!==n.SUCCESS&&O.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 Cr(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 li{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:v.SUCCESS,stream:i}}catch(e){if("Permission denied"===e.message)return{code:v.PERMISSION_DENIED};O.error(`get user media failed -> ${e.message}`)}return{code:"getUserMedia"===t?v.GET_USER_MEDIA_FAILED:v.GET_DISPLAY_MEDIA_FAILED}}))}setConstraintsConfig(e){if((null==e?void 0:e.audio)&&!this._isElectron){"boolean"==typeof e.audio&&(e.audio={});const t=navigator.mediaDevices.getSupportedConstraints();t.noiseSuppression&&(e.audio.noiseSuppression=!!t.noiseSuppression),t.autoGainControl&&(e.audio.autoGainControl=!!t.autoGainControl),t.echoCancellation&&(e.audio.echoCancellation=!!t.echoCancellation),O.info(`browser supported -> ${JSON.stringify(t)}`)}return e}createMicrophoneAudioTrack(e="RongCloudRTC",t){return f(this,void 0,void 0,(function*(){if(!Ct(e))return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.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:v.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.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!==v.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 ct(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(!Ct(e))return r.error(L.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.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:v.INVALID_TAGS,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID};const s=Dt(null==t?void 0:t.resolution)?t.resolution:Ke.W640_H480,{width:n,height:a}=Nt(s),{stream:c,code:_}=yield this._getMediaStream({video:{deviceId:null==t?void 0:t.cameraId,frameRate:kt((null==t?void 0:t.frameRate)||Ge.FPS_15),width:n,height:a,facingMode:null==t?void 0:t.faceMode}});if(_!==v.SUCCESS)return r.error(L.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"Failed to get camera video stream"},{logSource:i.RTC}),{code:_};const d=c.getVideoTracks()[0],u=new _t(e,o,d);return r.info(L.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:A.SUCCESSED,trackId:u.getTrackId()},{logSource:i.RTC}),{code:_,track:u}}))}createMicrophoneAndCameraTracks(e="RongCloudRTC",t){var o,s,n,a,c,_;return f(this,void 0,void 0,(function*(){const d=[];if(!Ct(e))return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.INVALID_TAGS,tracks:d};const u=this._context.getCurrentId();if(!u)return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:A.FAILED,code:v.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID,tracks:d};const l=Dt(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}=Nt(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:kt((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===(_=null==t?void 0:t.audio)||void 0===_?void 0:_.sampleRate}});return m!==v.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:d}):(p.getTracks().forEach((t=>{"video"===t.kind?d.push(new _t(e,u,t)):d.unshift(new ct(e,u,t))})),r.info(L.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:A.SUCCESSED,trackIds:d.map((e=>e.getTrackId()))},{logSource:i.RTC}),{code:m,tracks:d})}))}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===v.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(!Ct(e))return r.error(o,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.INVALID_TAGS};const c=this._context.getCurrentId();if(!c)return r.error(o,{status:A.FAILED,code:v.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID};if(!Mt())return r.error(L.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:A.FAILED,code:v.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:i.RTC}),{code:v.BROWSER_NOT_SUPPORT};const _=/macintosh|mac os x/i.test(navigator.userAgent);this._isElectron&&_&&t&&r.warn(o,{status:A.INFO,code:v.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO,msg:"mac in electron not support screen share with audio"});const d=(!this._isElectron||!_)&&t;if(this._isElectron&&!I(null==s?void 0:s.chromeMediaSourceId)&&!l(null==s?void 0:s.chromeMediaSourceId))return r.error(o,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> options.chromeMediaSourceId type is string"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};const u=Dt(null==s?void 0:s.resolution)?s.resolution:Ke.W1280_H720,{width:h,height:R}=Nt(u),p=this._isElectron?{mandatory:{chromeMediaSourceId:null==s?void 0:s.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:h,maxWidth:h,minHeight:R,maxHeight:R}}:{frameRate:kt((null==s?void 0:s.frameRate)||Ge.FPS_15),width:h,height:R};!(null==s?void 0:s.chromeMediaSourceId)&&this._isElectron&&(null===(n=p.mandatory)||void 0===n||delete n.chromeMediaSourceId);let m=null;d&&this._isElectron&&(null===(a=p.mandatory)||void 0===a||delete a.chromeMediaSourceId,m={mandatory:{chromeMediaSource:"desktop"}});const{stream:C,code:T}=yield this._getMediaStream({video:p,audio:m||d},this._isElectron?"getUserMedia":"getDisplayMedia");if(T!==v.SUCCESS)return r.error(o,{status:A.FAILED,code:T,msg:"Failed to get shared screen video stream"},{logSource:i.RTC}),{code:T};const E=C.getVideoTracks()[0],S=[new dt(e,c,E)];if(d){const t=C.getAudioTracks()[0];t&&S.push(new ut(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(!Ct(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.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:v.INVALID_USER_ID,msg:"Failed to create custom stream"},{logSource:i.RTC}),{code:v.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:v.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID};const s=new it(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:v.SUCCESS,track:s}}))}createLocalVideoTrack(e,t){return f(this,void 0,void 0,(function*(){if(!Ct(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.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:v.CREATE_CUSTOM_TRACK_FAILED,msg:"Failed to create custom stream"},{logSource:i.RTC}),{code:v.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:v.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID};const s=new ot(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:v.SUCCESS,track:s}}))}createLocalFileTracks(e,t,o){return f(this,void 0,void 0,(function*(){if(!Ct(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.INVALID_TAGS,tracks:[]};if(!yt())return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:v.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:i.RTC}),{code:v.BROWSER_NOT_SUPPORT,tracks:[]};const s=t instanceof File?URL.createObjectURL(t):t;if(!T(s)&&!/^blob:/.test(s))return O.warn(`createLocalFileTracks failed: params error -> url: ${s}`),r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> file"},{logSource:i.RTC}),{code:v.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 _;try{const e=a.mozCaptureStream?"mozCaptureStream":"captureStream";_=a[e]()}catch(e){O.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${s}`),O.error(e),r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:v.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:i.RTC}),t({code:v.CREATE_FILE_TRACK_FAILED,tracks:c})}const[d,u]=li.getTracksWithOptions(_,o);d&&c.push(new at(e,n,d,a)),u&&c.push(new nt(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:v.SUCCESS,tracks:c})},a.onerror=()=>{O.error(`create RCLocalFileTrack failed -> url: ${s}`),r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:v.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:i.RTC}),t({code:v.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:v.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID,tracks:[]})}))}createLocalTracks(e,t,o){return f(this,void 0,void 0,(function*(){const s=[];if(!Ct(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.INVALID_TAGS,tracks:s};if(!(t instanceof MediaStream))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> stream"},{logSource:i.RTC}),{code:v.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:v.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID,tracks:s};const[a,c]=li.getTracksWithOptions(t,o);return a&&s.push(new it(e,n,a)),c&&s.push(new ot(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:v.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 hi extends li{constructor(e,t,r){super(e),this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,dr.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new Ht(this._runtime,this._context,this._options.mediaServer,this._options.timeout),this._context.onconnectionstatechange=this._onIMStatusChange.bind(this),this._context.ondisconnect=this._onIMDisconnect.bind(this),this._context.ondestroy=this._onIMUninit.bind(this),this._context.onmessage=this._handleMessage.bind(this)}_handleMessage(e){var t;if(e.conversationType!==C.RTC_ROOM)return!1;if(this._crtRoom instanceof ii){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}_getJoinedPKRoomList(){const{code:e,roomPKHandler:t}=this._crtRoom.getRoomPKHandler();if(e===v.SUCCESS&&t){const e=t.getJoinedPKRooms()||{};return Object.values(e)}return[]}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(e,t,o,s,n=_.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:v.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:v.REPERT_JOIN_ROOM};const a=this._crtRoom=new oi(this._context,this._runtime,e,this._service,this._options,!1,!1,s,Gt()),{code:c}=yield a.__innerInit(n,t,void 0,void 0,o);return c!==v.SUCCESS?(this._crtRoom=null,{code:c}):(a.once(Fr,(()=>{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:v.REPERT_JOIN_ROOM,msg:`Join the room repeatedly -> roomId: ${e}`},{logSource:i.RTC}),{code:v.REPERT_JOIN_ROOM};const a=this._crtRoom=new ii(this._context,this._runtime,e,this._service,this._options,t,!1,!0,n),{code:c}=yield a.__innerInit(_.LIVE,o,t,void 0,s);if(c!==v.SUCCESS)return this._crtRoom=null,{code:c};a.once(Fr,(()=>{this._crtRoom=null}));const d={code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()};return a.__getCDNPushMode()===zr.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(O.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===c.CONNECTED){if(this._crtRoom instanceof ii){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}),O.debug("TODO -> on IM disconnect")}_onIMUninit(){r.info(L.L_RTC_CLIENT_DESTROY_S,{status:A.SUCCESSED},{logSource:i.RTC}),O.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),O.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),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:v.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:v.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}),xt(this._context.getNaviInfo()))return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:v.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:i.RTC}),{code:v.PACKAGE_ENVIRONMENT_ERROR};if(!s("roomId",e,d,!0)||!s("livingType",t,(e=>e===qr.AUDIO||e===qr.VIDEO)))return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:v.PACKAGE_ENVIRONMENT_ERROR,msg:"params error -> roomId or livingType"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:v.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:v.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:v.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:i.RTC}),{code:v.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:a,data:c}=yield this._context.joinLivingRoomAsAudience(e,_.LIVE,t);if(a!==n.SUCCESS)return O.error("audienceJoinLivingRoomError:",a),r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:v.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED,msg:"signal error -> audience join room"},{logSource:i.RTC}),{code:v.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};O.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(c)}`);const u=Gt(),l=new ui(this._context,this._runtime,this._options,e,c,t,o,u);return this._crtAudienceLivingRoom=l,r.info(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.SUCCESSED,roomData:c},{logSource:i.RTC}),{room:l,code:v.SUCCESS,userIds:l.getRemoteUserIds(),RTCTracks:l.getRemoteRTCTracks(),MCUTracks:l.getRemoteMCUTracks(),CDNUris:l.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:v.PARAMS_ERROR,msg:"params error -> room"},{logSource:i.RTC}),{code:v.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:v.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:v.SUCCESS})}))}upgradeToAnchorRoom(e){return f(this,void 0,void 0,(function*(){if(!s("room",e,(()=>e instanceof ui),!0))return r.error(L.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> room"},{logSource:i.RTC}),{code:v.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:v.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:v.REPERT_JOIN_ROOM};const t=e.getRoomId(),o=this._crtRoom=new ii(this._context,this._runtime,t,this._service,this._options,e.livingType,!0,!0,!1,e.getClientSessionId()),a=yield o.__innerInitByIdentityChange();return a!==n.SUCCESS?(O.warn(`change room identity failed -> code: ${a}`),this._crtRoom=null,r.error(L.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:A.FAILED,code:v.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:i.RTC}),{code:v.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):(o.once(Fr,(()=>{this._crtRoom=null})),yield this._crtAudienceLivingRoom.__destroy(!1),this._crtAudienceLivingRoom=null,{room:o,code:v.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 O.error("the `downgradeToAudienceRoom` is disabled in PK room"),r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!s("room._roomId",e._roomId,d,!0))return r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> room._roomId"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:v.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:v.REPERT_JOIN_ROOM};const{code:t,data:o}=yield this._context.rtcIdentityChange(e._roomId,S.AnchorToViewer,e.getLivingType());if(t!==n.SUCCESS)return O.error("change room identity error",t),r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:v.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:i.RTC}),{code:v.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};O.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 a=e.getClientSessionId(),c=new ui(this._context,this._runtime,this._options,e._roomId,o,e.getLivingType(),!1,a);return this._crtAudienceLivingRoom=c,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:c,code:v.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!==n.SUCCESS?(O.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:v.SUCCESS,data:t})}))}}var Ri;!function(e){e[e.SERVER_KICK=1]="SERVER_KICK",e[e.OTHER_KICK=2]="OTHER_KICK"}(Ri||(Ri={}));const pi={tag:"RCRTC",verify:e=>"browser"!==e.tag?(O.error(`RCRTC Plugin is not support the runtime '${e.tag}'`),!1):Tt?(g.add("plugin-rtc","5.4.3"),!!g.validEngine(">=5.3.3-beem-alpha.2 || >=5.3.4")||(O.error(`The current engine version '${g.getInfo().engine}' error, plugin-rtc required engine version at least '>=5.3.3-beem-alpha.2 || >=5.3.4'.`),!1)):(O.error("Please use the https protocol or use `http://localhost` to open the page!"),!1),setup:(e,t,r={})=>(O.setLogLevel(r.logLevel),O.setLogStdout(r.logStdout),O.warn("RCRTC Version: 5.4.3, Commit: 14f0acc9bca79c93547703c573d297dbd301594c"),O.warn(`browserInfo.browser -> ${Pt.browser}`),O.warn(`browserInfo.supportsUnifiedPlan -> ${Pt.supportsUnifiedPlan}`),O.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)),new hi(e,t,r))},mi={DEFAULT:"RongCloudRTC"},Ci={transResolution:Nt,transFrameRate:kt,parseTrackId:ft,ifSupportLocalFileTrack:yt,ifSupportScreenShare:Mt};export{Kr as BackgroundPictureFillMode,Hr as MixLayoutMode,jr as MixVideoRenderMode,$r as RCAbstractRoom,ai as RCAudienceClient,ui as RCAudienceLivingRoom,Qe as RCAudioBitrate,_t as RCCameraVideoTrack,Ge as RCFrameRate,_i as RCInnerCDNPullIsHttps,ci as RCInnerCDNPullKind,Ri as RCKickReason,ii as RCLivingRoom,qr as RCLivingType,it as RCLocalAudioTrack,at as RCLocalFileAudioTrack,st as RCLocalFileTrack,nt as RCLocalFileVideoTrack,rt as RCLocalTrack,ot as RCLocalVideoTrack,Yr as RCMCUConfigBuilder,li as RCMediaStreamCapture,He as RCMediaType,ct as RCMicphoneAudioTrack,hi as RCRTCClient,v as RCRTCCode,sr as RCRTCLiveRole,Ft as RCRTCPingResult,oi as RCRTCRoom,ht as RCRemoteAudioTrack,lt as RCRemoteTrack,Rt as RCRemoteVideoTrack,Ke as RCResolution,ut as RCScreenAudioTrack,dt as RCScreenVideoTrack,mi as RCTag,Ze as RCTrack,et as RCVideoBitrate,qe as device,Ci as helper,pi as installer};
15
+ ***************************************************************************** */function f(e,t,r,i){return new(r||(r=Promise))((function(s,o){function n(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,a)}c((i=i.apply(e,t||[])).next())}))}const O=new e("RCRTC");var v,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.SYSTEM_PERMISSION_DENIED=53033]="SYSTEM_PERMISSION_DENIED"}(v||(v={})),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"}(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 b(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return s.apply(this,arguments);const o=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),s.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(r))return o.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function U(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(N=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function P(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(D=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function y(){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]),s=i?w(e[r]):e[r],o=i&&!Object.keys(s).length;return void 0===s||o?t:Object.assign(t,{[r]:s})}),{}):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",s=new Map;if(null===t)return s;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&B(e,r,s)}))})),s}const F=y;function $(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[s("min",r)]=i.ideal,t.optional.push(e),e={},e[s("max",r)]=i.ideal,t.optional.push(e)):(e[s("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const n=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||n)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{let n=(r=r.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!n&&r.length&&t.includes("back")&&(n=r[r.length-1]),n&&(e.video.deviceId=o.exact?{exact:n.deviceId}:{ideal:n.deviceId}),e.video=i(e.video),F("chrome: "+JSON.stringify(e)),s(e)}))}e.video=i(e.video)}return F("chrome: "+JSON.stringify(e)),s(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,i){s(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(o(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return s(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function 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 s=new Event("track");s.track=r.track,s.receiver=i,s.transceiver={receiver:i},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const s=new Event("track");s.track=r,s.receiver=i,s.transceiver={receiver:i},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else b(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function H(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let s=r.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function j(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,i]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const s=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const i=function(e){r(o(s(e)))};return t.apply(this,[i,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(o(s(t)))},r])})).then(r,i)}}function 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}),b(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 s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function Y(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return W(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],s=e._streams[i.id];r=r.replace(new RegExp(s.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function n(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],s=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const s=this.getSenders().find((e=>e.track===t));if(s)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[r.id];if(o)o.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=o(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=n(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=c.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function q(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function z(e,t){b(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:Y,shimPeerConnection:q,fixNegotiationNeeded:z,shimGetUserMedia:$,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const i=r.video&&r.video.width,s=r.video&&r.video.height,o=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},i&&(r.video.mandatory.maxWidth=i),s&&(r.video.mandatory.maxHeight=s),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});var 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(";"),s=0;s<i.length;s++)r[(t=i[s].trim().split("="))[0].trim()]=t[1];return r},t.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var i=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){var t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r},t.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},t.getMid=function(e){var r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substr(6)},t.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){var r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){var t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;var t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){var i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],s=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&s?{usernameFragment:i.substr(12),password:s.substr(10)}:null},t.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},t.parseRtpParameters=function(e){for(var r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" "),s=3;s<i.length;s++){var o=i[s],n=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(n){var a=t.parseRtpMap(n),c=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(a.parameters=c.length?t.parseFmtp(c[0]):{},a.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),r.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(a.name.toUpperCase())}}}return t.matchPrefix(e,"a=extmap:").forEach((function(e){r.headerExtensions.push(t.parseExtmap(e))})),r},t.writeRtpDescription=function(e,r){var i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" UDP/TLS/RTP/SAVPF ",i+=r.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((function(e){i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));var s=0;return r.codecs.forEach((function(e){e.maxptime>s&&(s=e.maxptime)})),s>0&&(i+="a=maxptime:"+s+"\r\n"),i+="a=rtcp-mux\r\n",r.headerExtensions&&r.headerExtensions.forEach((function(e){i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){var r,i=[],s=t.parseRtpParameters(e),o=-1!==s.fecMechanisms.indexOf("RED"),n=-1!==s.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute})),c=a.length>0&&a[0].ssrc,d=t.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));d.length>0&&d[0].length>1&&d[0][0]===c&&(r=d[0][1]),s.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&r&&(t.rtx={ssrc:r}),i.push(t),o&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:n?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&c&&i.push({ssrc:c});var _=t.matchPrefix(e,"b=");return _.length&&(_=0===_[0].indexOf("b=TIAS:")?parseInt(_[0].substr(7),10):0===_[0].indexOf("b=AS:")?1e3*parseInt(_[0].substr(5),10)*.95-16e3:void 0,i.forEach((function(e){e.maxBitrate=_}))),i},t.parseRtcpParameters=function(e){var r={},i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);var s=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=s.length>0,r.compound=0===s.length;var o=t.matchPrefix(e,"a=rtcp-mux");return r.mux=o.length>0,r},t.parseMsid=function(e){var r,i=t.matchPrefix(e,"a=msid:");if(1===i.length)return{stream:(r=i[0].substr(7).split(" "))[0],track:r[1]};var s=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return s.length>0?{stream:(r=s[0].value.split(" "))[0],track:r[1]}:void 0},t.parseSctpDescription=function(e){var r,i=t.parseMLine(e),s=t.matchPrefix(e,"a=max-message-size:");s.length>0&&(r=parseInt(s[0].substr(19),10)),isNaN(r)&&(r=65536);var o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substr(12),10),protocol:i.fmt,maxMessageSize:r};if(t.matchPrefix(e,"a=sctpmap:").length>0){var n=t.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(n[0],10),protocol:n[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){var r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,r,i){var s=void 0!==r?r:2;return"v=0\r\no="+(i||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,r,i,s){var o=t.writeRtpDescription(e.kind,r);if(o+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),o+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===i?"actpass":"active"),o+="a=mid:"+e.mid+"\r\n",e.direction?o+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?o+="a=sendrecv\r\n":e.rtpSender?o+="a=sendonly\r\n":e.rtpReceiver?o+="a=recvonly\r\n":o+="a=inactive\r\n",e.rtpSender){var n="msid:"+s.id+" "+e.rtpSender.track.id+"\r\n";o+="a="+n,o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+n,e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+n,o+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+t.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+t.localCName+"\r\n"),o},t.getDirection=function(e,r){for(var i=t.splitLines(e),s=0;s<i.length;s++)switch(i[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[s].substr(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substr(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){var r=t.splitLines(e)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){var r=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var r=t.splitLines(e),i=0;i<r.length;i++)if(r[i].length<2||"="!==r[i].charAt(1))return!1;return!0},e.exports=t},Z(X={exports:{}},X.exports),X.exports);function te(e,t,r,i,s){var o=ee.writeRtpDescription(e.kind,t);if(o+=ee.writeIceParameters(e.iceGatherer.getLocalParameters()),o+=ee.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":s||"active"),o+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?o+="a=sendrecv\r\n":e.rtpSender?o+="a=sendonly\r\n":e.rtpReceiver?o+="a=recvonly\r\n":o+="a=inactive\r\n",e.rtpSender){var n=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=n;var a="msid:"+(i?i.id:"-")+" "+n+"\r\n";o+="a="+a,o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,o+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+ee.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+ee.localCName+"\r\n"),o}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]},s=function(e,t,r,s){var o=i(e.parameters.apt,r),n=i(t.parameters.apt,s);return o&&n&&o.name.toLowerCase()===n.name.toLowerCase()};return e.codecs.forEach((function(i){for(var o=0;o<t.codecs.length;o++){var n=t.codecs[o];if(i.name.toLowerCase()===n.name.toLowerCase()&&i.clockRate===n.clockRate){if("rtx"===i.name.toLowerCase()&&i.parameters&&n.parameters.apt&&!s(i,n,e.codecs,t.codecs))continue;(n=JSON.parse(JSON.stringify(n))).numChannels=Math.min(i.numChannels,n.numChannels),r.codecs.push(n),n.rtcpFeedback=n.rtcpFeedback.filter((function(e){for(var t=0;t<i.rtcpFeedback.length;t++)if(i.rtcpFeedback[t].type===e.type&&i.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var i=0;i<t.headerExtensions.length;i++){var s=t.headerExtensions[i];if(e.uri===s.uri){r.headerExtensions.push(s);break}}})),r}function 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 se(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 oe(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,s){var o=new Event("track");o.track=r,o.receiver=i,o.transceiver={receiver:i},o.streams=s,e.setTimeout((function(){t._dispatchEvent("track",o)}))}var s=function(r){var i=this,s=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){i[e]=s[e].bind(s)})),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",r=JSON.parse(JSON.stringify(r||{})),this.usingBundle="max-bundle"===r.bundlePolicy,"negotiate"===r.rtcpMuxPolicy)throw oe("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var i=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var s="string"==typeof i;return s&&(i=[i]),i=i.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||r?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(r=!0,!0)})),delete e.url,e.urls=s?i[0]:i,!!i.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var o=r.iceCandidatePoolSize;o>0;o--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=ee.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(s.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(s.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),s.prototype.onicecandidate=null,s.prototype.onaddstream=null,s.prototype.ontrack=null,s.prototype.onremovestream=null,s.prototype.onsignalingstatechange=null,s.prototype.oniceconnectionstatechange=null,s.prototype.onconnectionstatechange=null,s.prototype.onicegatheringstatechange=null,s.prototype.onnegotiationneeded=null,s.prototype.ondatachannel=null,s.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},s.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},s.prototype.getConfiguration=function(){return this._config},s.prototype.getLocalStreams=function(){return this.localStreams},s.prototype.getRemoteStreams=function(){return this.remoteStreams},s.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,i={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&r)i.iceTransport=this.transceivers[0].iceTransport,i.dtlsTransport=this.transceivers[0].dtlsTransport;else{var s=this._createIceAndDtlsTransports();i.iceTransport=s.iceTransport,i.dtlsTransport=s.dtlsTransport}return t||this.transceivers.push(i),i},s.prototype.addTrack=function(t,r){if(this._isClosed)throw oe("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var i;if(this.transceivers.find((function(e){return e.track===t})))throw oe("InvalidAccessError","Track already exists.");for(var s=0;s<this.transceivers.length;s++)this.transceivers[s].track||this.transceivers[s].kind!==t.kind||(i=this.transceivers[s]);return i||(i=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),i.track=t,i.stream=r,i.rtpSender=new e.RTCRtpSender(t,i.dtlsTransport),i.rtpSender},s.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var i=e.clone();e.getTracks().forEach((function(e,t){var r=i.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),i.getTracks().forEach((function(e){r.addTrack(e,i)}))}},s.prototype.removeTrack=function(t){if(this._isClosed)throw oe("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 oe("InvalidAccessError","Sender was not created by this connection.");var i=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(i)&&this.localStreams.indexOf(i)>-1&&this.localStreams.splice(this.localStreams.indexOf(i),1),this._maybeFireNegotiationNeeded()},s.prototype.removeStream=function(e){var t=this;e.getTracks().forEach((function(e){var r=t.getSenders().find((function(t){return t.track===e}));r&&t.removeTrack(r)}))},s.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},s.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},s.prototype._createIceGatherer=function(t,r){var i=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var s=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(s,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(e){var r=!e.candidate||0===Object.keys(e.candidate).length;s.state=r?"completed":"gathering",null!==i.transceivers[t].bufferedCandidateEvents&&i.transceivers[t].bufferedCandidateEvents.push(e)},s.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),s},s.prototype._gather=function(t,r){var i=this,s=this.transceivers[r].iceGatherer;if(!s.onlocalcandidate){var o=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,s.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),s.onlocalcandidate=function(e){if(!(i.usingBundle&&r>0)){var o=new Event("icecandidate");o.candidate={sdpMid:t,sdpMLineIndex:r};var n=e.candidate,a=!n||0===Object.keys(n).length;if(a)"new"!==s.state&&"gathering"!==s.state||(s.state="completed");else{"new"===s.state&&(s.state="gathering"),n.component=1,n.ufrag=s.getLocalParameters().usernameFragment;var c=ee.writeCandidate(n);o.candidate=Object.assign(o.candidate,ee.parseCandidate(c)),o.candidate.candidate=c,o.candidate.toJSON=function(){return{candidate:o.candidate.candidate,sdpMid:o.candidate.sdpMid,sdpMLineIndex:o.candidate.sdpMLineIndex,usernameFragment:o.candidate.usernameFragment}}}var d=ee.getMediaSections(i._localDescription.sdp);d[o.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+o.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",o),_&&(i._dispatchEvent("icecandidate",new Event("icecandidate")),i.iceGatheringState="complete",i._emitGatheringStateChange())}},e.setTimeout((function(){o.forEach((function(e){s.onlocalcandidate(e)}))}),0)}},s.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var i=new e.RTCDtlsTransport(r);return i.ondtlsstatechange=function(){t._updateConnectionState()},i.onerror=function(){Object.defineProperty(i,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:i}},s.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var r=this.transceivers[e].iceTransport;r&&(delete r.onicestatechange,delete this.transceivers[e].iceTransport);var i=this.transceivers[e].dtlsTransport;i&&(delete i.ondtlsstatechange,delete i.onerror,delete this.transceivers[e].dtlsTransport)},s.prototype._transceive=function(e,r,i){var s=re(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(s.encodings=e.sendEncodingParameters,s.rtcp={cname:ee.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(s.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(s)),i&&e.rtpReceiver&&s.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?s.encodings=e.recvEncodingParameters:s.encodings=[{}],s.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(s.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(s.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(s))},s.prototype.setLocalDescription=function(e){var t,r,i=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(oe("TypeError",'Unsupported type "'+e.type+'"'));if(!ie("setLocalDescription",e.type,i.signalingState)||i._isClosed)return Promise.reject(oe("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 s=ee.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var o=i.transceivers[t],n=o.iceGatherer,a=o.iceTransport,c=o.dtlsTransport,d=o.localCapabilities,_=o.remoteCapabilities;if(!(ee.isRejected(e)&&0===ee.matchPrefix(e,"a=bundle-only").length)&&!o.rejected){var u=ee.getIceParameters(e,r),l=ee.getDtlsParameters(e,r);s&&(l.role="server"),i.usingBundle&&0!==t||(i._gather(o.mid,t),"new"===a.state&&a.start(n,u,s?"controlling":"controlled"),"new"===c.state&&c.start(l));var h=re(d,_);i._transceive(o,h.codecs.length>0,!1)}}))}return i._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?i._updateSignalingState("have-local-offer"):i._updateSignalingState("stable"),Promise.resolve()},s.prototype.setRemoteDescription=function(s){var o=this;if(-1===["offer","answer"].indexOf(s.type))return Promise.reject(oe("TypeError",'Unsupported type "'+s.type+'"'));if(!ie("setRemoteDescription",s.type,o.signalingState)||o._isClosed)return Promise.reject(oe("InvalidStateError","Can not set remote "+s.type+" in state "+o.signalingState));var n={};o.remoteStreams.forEach((function(e){n[e.id]=e}));var a=[],c=ee.splitSections(s.sdp),d=c.shift(),_=ee.matchPrefix(d,"a=ice-lite").length>0,u=ee.matchPrefix(d,"a=group:BUNDLE ").length>0;o.usingBundle=u;var l=ee.matchPrefix(d,"a=ice-options:")[0];return o.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))o.transceivers[c]={mid:T,kind:h,protocol:p,rejected:!0};else{var E,I,S,g,f,O,v,L,A;!R&&o.transceivers[c]&&o.transceivers[c].rejected&&(o.transceivers[c]=o._createTransceiver(h,!0));var N,D,k=ee.parseRtpParameters(i);R||(N=ee.getIceParameters(i,d),(D=ee.getDtlsParameters(i,d)).role="client"),v=ee.parseRtpEncodingParameters(i);var b=ee.parseRtcpParameters(i),U=ee.matchPrefix(i,"a=end-of-candidates",d).length>0,P=ee.matchPrefix(i,"a=candidate:").map((function(e){return ee.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===s.type||"answer"===s.type)&&!R&&u&&c>0&&o.transceivers[c]&&(o._disposeIceAndDtlsTransports(c),o.transceivers[c].iceGatherer=o.transceivers[0].iceGatherer,o.transceivers[c].iceTransport=o.transceivers[0].iceTransport,o.transceivers[c].dtlsTransport=o.transceivers[0].dtlsTransport,o.transceivers[c].rtpSender&&o.transceivers[c].rtpSender.setTransport(o.transceivers[0].dtlsTransport),o.transceivers[c].rtpReceiver&&o.transceivers[c].rtpReceiver.setTransport(o.transceivers[0].dtlsTransport)),"offer"!==s.type||R){if("answer"===s.type&&!R){I=(E=o.transceivers[c]).iceGatherer,S=E.iceTransport,g=E.dtlsTransport,f=E.rtpReceiver,O=E.sendEncodingParameters,L=E.localCapabilities,o.transceivers[c].recvEncodingParameters=v,o.transceivers[c].remoteCapabilities=k,o.transceivers[c].rtcpParameters=b,P.length&&"new"===S.state&&(!_&&!U||u&&0!==c?P.forEach((function(e){se(E.iceTransport,e)})):S.setRemoteCandidates(P)),u&&0!==c||("new"===S.state&&S.start(I,N,"controlling"),"new"===g.state&&g.start(D)),!re(E.localCapabilities,E.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&E.sendEncodingParameters[0].rtx&&delete E.sendEncodingParameters[0].rtx,o._transceive(E,"sendrecv"===m||"recvonly"===m,"sendrecv"===m||"sendonly"===m),!f||"sendrecv"!==m&&"sendonly"!==m?delete E.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{(E=o.transceivers[c]||o._createTransceiver(h)).mid=T,E.iceGatherer||(E.iceGatherer=o._createIceGatherer(c,u)),P.length&&"new"===E.iceTransport.state&&(!U||u&&0!==c?P.forEach((function(e){se(E.iceTransport,e)})):E.iceTransport.setRemoteCandidates(P)),L=e.RTCRtpReceiver.getCapabilities(h),t<15019&&(L.codecs=L.codecs.filter((function(e){return"rtx"!==e.name}))),O=E.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var y,M=!1;if("sendrecv"===m||"sendonly"===m){if(M=!E.rtpReceiver,f=E.rtpReceiver||new e.RTCRtpReceiver(E.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}}),y=n[C.stream]):(n.default||(n.default=new e.MediaStream),y=n.default)),y&&(r(A,y),E.associatedRemoteMediaStreams.push(y)),a.push([A,f,y])}else E.rtpReceiver&&E.rtpReceiver.track&&(E.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===E.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),E.associatedRemoteMediaStreams=[]);E.localCapabilities=L,E.remoteCapabilities=k,E.rtpReceiver=f,E.rtcpParameters=b,E.sendEncodingParameters=O,E.recvEncodingParameters=v,o._transceive(o.transceivers[c],!1,M)}}})),void 0===o._dtlsRole&&(o._dtlsRole="offer"===s.type?"active":"passive"),o._remoteDescription={type:s.type,sdp:s.sdp},"offer"===s.type?o._updateSignalingState("have-remote-offer"):o._updateSignalingState("stable"),Object.keys(n).forEach((function(t){var r=n[t];if(r.getTracks().length){if(-1===o.remoteStreams.indexOf(r)){o.remoteStreams.push(r);var s=new Event("addstream");s.stream=r,e.setTimeout((function(){o._dispatchEvent("addstream",s)}))}a.forEach((function(e){var t=e[0],s=e[1];r.id===e[2].id&&i(o,t,s,[r])}))}})),a.forEach((function(e){e[2]||i(o,e[0],e[1],[])})),e.setTimeout((function(){o&&o.transceivers&&o.transceivers.forEach((function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},s.prototype.close=function(){this.transceivers.forEach((function(e){e.iceTransport&&e.iceTransport.stop(),e.dtlsTransport&&e.dtlsTransport.stop(),e.rtpSender&&e.rtpSender.stop(),e.rtpReceiver&&e.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},s.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},s.prototype._maybeFireNegotiationNeeded=function(){var t=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,e.setTimeout((function(){if(t.needNegotiation){t.needNegotiation=!1;var e=new Event("negotiationneeded");t._dispatchEvent("negotiationneeded",e)}}),0))},s.prototype._updateIceConnectionState=function(){var e,t={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&!e.rejected&&t[e.iceTransport.state]++})),e="new",t.failed>0?e="failed":t.checking>0?e="checking":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0?e="connected":t.completed>0&&(e="completed"),e!==this.iceConnectionState){this.iceConnectionState=e;var r=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",r)}},s.prototype._updateConnectionState=function(){var e,t={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&e.dtlsTransport&&!e.rejected&&(t[e.iceTransport.state]++,t[e.dtlsTransport.state]++)})),t.connected+=t.completed,e="new",t.failed>0?e="failed":t.connecting>0?e="connecting":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0&&(e="connected"),e!==this.connectionState){this.connectionState=e;var r=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",r)}},s.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(oe("InvalidStateError","Can not call createOffer after close"));var i=r.transceivers.filter((function(e){return"audio"===e.kind})).length,s=r.transceivers.filter((function(e){return"video"===e.kind})).length,o=arguments[0];if(o){if(o.mandatory||o.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==o.offerToReceiveAudio&&(i=!0===o.offerToReceiveAudio?1:!1===o.offerToReceiveAudio?0:o.offerToReceiveAudio),void 0!==o.offerToReceiveVideo&&(s=!0===o.offerToReceiveVideo?1:!1===o.offerToReceiveVideo?0:o.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--i<0&&(e.wantReceive=!1):"video"===e.kind&&--s<0&&(e.wantReceive=!1)}));i>0||s>0;)i>0&&(r._createTransceiver("audio"),i--),s>0&&(r._createTransceiver("video"),s--);var n=ee.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(i,s){var o=i.track,n=i.kind,a=i.mid||ee.generateIdentifier();i.mid=a,i.iceGatherer||(i.iceGatherer=r._createIceGatherer(s,r.usingBundle));var c=e.RTCRtpSender.getCapabilities(n);t<15019&&(c.codecs=c.codecs.filter((function(e){return"rtx"!==e.name}))),c.codecs.forEach((function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1"),i.remoteCapabilities&&i.remoteCapabilities.codecs&&i.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(i.remoteCapabilities&&i.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=i.sendEncodingParameters||[{ssrc:1001*(2*s+1)}];o&&t>=15019&&"video"===n&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),i.wantReceive&&(i.rtpReceiver=new e.RTCRtpReceiver(i.dtlsTransport,n)),i.localCapabilities=c,i.sendEncodingParameters=d})),"max-compat"!==r._config.bundlePolicy&&(n+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),n+="a=ice-options:trickle\r\n",r.transceivers.forEach((function(e,t){n+=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)},s.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(oe("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(oe("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 s=ee.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,o){if(!(o+1>s)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?i+="m=application 0 DTLS/SCTP 5000\r\n":i+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?i+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(i+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(i+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var n;if(e.stream)"audio"===e.kind?n=e.stream.getAudioTracks()[0]:"video"===e.kind&&(n=e.stream.getVideoTracks()[0]),n&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1});var a=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 o=new e.RTCSessionDescription({type:"answer",sdp:i});return Promise.resolve(o)},s.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(i,s){if(!r._remoteDescription)return s(oe("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var o=e.sdpMLineIndex;if(e.sdpMid)for(var n=0;n<r.transceivers.length;n++)if(r.transceivers[n].mid===e.sdpMid){o=n;break}var a=r.transceivers[o];if(!a)return s(oe("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===o||o>0&&a.iceTransport!==r.transceivers[0].iceTransport)&&!se(a.iceTransport,c))return s(oe("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))[o]+="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()}))},s.prototype.getStats=function(t){if(t&&t instanceof e.MediaStreamTrack){var r=null;if(this.transceivers.forEach((function(e){e.rtpSender&&e.rtpSender.track===t?r=e.rtpSender:e.rtpReceiver&&e.rtpReceiver.track===t&&(r=e.rtpReceiver)})),!r)throw oe("InvalidAccessError","Invalid selector.");return r.getStats()}var i=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&i.push(e[t].getStats())}))})),Promise.all(i).then((function(e){var t=new Map;return e.forEach((function(e){e.forEach((function(e){t.set(e.id,e)}))})),t}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(t){var r=e[t];if(r&&r.prototype&&r.prototype.getStats){var i=r.prototype.getStats;r.prototype.getStats=function(){return i.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var i;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(i=e[r]).type]||i.type,t.set(r,e[r])})),t}))}}}));var o=["createOffer","createAnswer"];return o.forEach((function(e){var t=s.prototype[e];s.prototype[e]=function(){var e=arguments;return"function"==typeof e[0]||"function"==typeof e[1]?t.apply(this,[arguments[2]]).then((function(t){"function"==typeof e[0]&&e[0].apply(null,[t])}),(function(t){"function"==typeof e[1]&&e[1].apply(null,[t])})):t.apply(this,arguments)}})),(o=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=s.prototype[e];s.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]||"function"==typeof e[2]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)}),(function(t){"function"==typeof e[2]&&e[2].apply(null,[t])})):t.apply(this,arguments)}})),["getStats"].forEach((function(e){var t=s.prototype[e];s.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)})):t.apply(this,arguments)}})),s};function 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),y("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,s,o]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(s,o)}}function pe(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function 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}),b(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 Ee(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 Ie(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:Ee,shimGetParameters:Ie,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 Oe(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function ve(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,s=t.setLocalDescription,o=t.setRemoteDescription,n=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=r.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[r]);return t?(s.then(e,t),Promise.resolve()):s};let a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function 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 be(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio"),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video")}return t.apply(this,arguments)}}function Ue(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Pe=Object.freeze({__proto__:null,shimLocalStreamsAPI:Oe,shimRemoteStreamsAPI:ve,shimCallbacksAPI:Le,shimGetUserMedia:Ae,shimConstraints:Ne,shimRTCIceServerUrls:De,shimTrackEventTransceiver:ke,shimCreateOfferLegacy:be,shimAudioContext:Ue});function ye(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),s=Object.assign(r,i);return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,b(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},s=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r},o=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const s=ee.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?i=parseInt(s[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i},n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){const e=i(arguments[0]),t=s(e),r=o(arguments[0],e);let n;n=0===t&&0===r?Number.POSITIVE_INFINITY:0===t||0===r?Math.max(t,r):Math.min(t,r);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>n}),this._sctp=a}return n.apply(this,arguments)}}function 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],s=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},b(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 Fe=Object.freeze({__proto__:null,shimRTCIceCandidate:ye,shimMaxMessageSize:Me,shimSendThrowTypeError:xe,shimConnectionState:we,removeExtmapAllowMixed:Be,shimAddIceCandidateNullOrEmpty:Ve});const $e=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=y,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=k(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=k(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=k(r.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=k(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:i,commonShim:Fe,extractVersion:k,disableLog:U,disableWarnings:P};switch(i.browser){case"chrome":if(!Q||!q||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),s;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),s;r("adapter.js shimming chrome."),s.browserShim=Q,Ve(e,i),$(e,i),G(e),q(e,i),K(e),Y(e,i),H(e),j(e),J(e),z(e,i),ye(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."),s;r("adapter.js shimming firefox."),s.browserShim=fe,Ve(e,i),le(e,i),Re(e,i),he(e),Ce(e),pe(e),me(e),Te(e),Ee(e),Ie(e),Se(e),ge(e),ye(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."),s;r("adapter.js shimming edge."),s.browserShim=ue,ae(e),ce(e),de(e,i),_e(e),Me(e,i),xe(e);break;case"safari":if(!Pe||!t.shimSafari)return r("Safari shim is not included in this adapter release."),s;r("adapter.js shimming safari."),s.browserShim=Pe,Ve(e,i),De(e),be(e),Le(e),Oe(e),ve(e),ke(e),Ae(e),Ue(e),ye(e),Me(e,i),xe(e),Be(e,i);break;default:r("Unsupported browser!")}return s}({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.W256_H144="W256_H144",e.W320_H180="W320_H180",e.W240_H240="W240_H240",e.W320_H240="W320_H240",e.W480_H360="W480_H360",e.W640_H360="W640_H360",e.W480_H480="W480_H480",e.W640_H480="W640_H480",e.W720_H480="W720_H480",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:160,minBitrate:80},[Ke.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[Ke.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[Ke.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[Ke.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[Ke.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[Ke.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[Ke.W480_H480]:{width:480,height:480,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.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[Ke.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},Je=(e,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},We={10:1,15:1,24:1.5,30:1.5},Ye=e=>{let t=Number.MAX_VALUE,r=1;for(const i in We){const s=Math.abs(e-parseInt(i));s<t&&(t=s,r=We[i])}return r},qe={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 ze,Qe;!function(e){e.AUDIO="audio",e.VIDEO="video"}(ze||(ze={}));class Ze extends t{constructor(e,t,r,i,s){super(),this._tag=e,this._userId=t,this._kind=r,this._isLocalTrack=i,this._roomId=s,this._localMuted=!1,this._remoteMuted=!1,this._streamId=[this._userId||this._roomId,this._tag].join("_"),this._id=[this._streamId,this.isAudioTrack()?0:1].join("_")}getStreamId(){return this._streamId}getTrackId(){return this._id}getUserId(){return this._userId}__innerGetMediaStreamTrack(){return this._msTrack}get streamTrack(){return this._msTrack}getTag(){return this._tag}isLocalTrack(){return this._isLocalTrack}isVideoTrack(){return"video"===this._kind}isAudioTrack(){return"audio"===this._kind}isReady(){var e;return"live"===(null===(e=this._msTrack)||void 0===e?void 0:e.readyState)}__innerSetMediaStreamTrack(e){this._msTrack=e,this._setLocalMuted(this._localMuted);const t=this._msStream=this._msStream||new MediaStream,r=t.getTracks()[0];r&&t.removeTrack(r),e?t.addTrack(e):this._element&&(this._element.pause(),this._element.srcObject=null)}_setLocalMuted(e){this._msTrack&&(this._msTrack.enabled=!e),this._localMuted=e}mute(){O.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(){O.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 O.warn(`the track is not ready to play -> id: ${this._id}`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:v.TRACK_NOT_READY,msg:`play error -> id: ${this._id}`},{logSource:i.RTC}),{code:v.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&(O.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(!s(null==t?void 0:t.volume))return O.error(`${null==t?void 0:t.volume} is not a number, the valid range of options.volume is 0-100`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> options.volume不是数字"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};(null==t?void 0:t.volume)<0&&(t.volume=0,O.warn("the valid range of options.volume is 0-100, the value of volume has been set 0"),r.warn(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,O.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 qe.getSpeakers()).map((e=>e.deviceId)).includes(t.audioDeviceId))return O.error(`the options.audioDeviceId is invalid --\x3e ${t.audioDeviceId}`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> options.audioDeviceId"},{logSource:i.RTC}),{code:v.PARAMS_ERROR}}const o=this.isVideoTrack();return!o||e&&(e instanceof HTMLVideoElement||this.__validateVideoNodeName(e))?(this._element=o?e:this._element||new Audio,this._localMuted&&this._setLocalMuted(!1),this._element.srcObject&&this._element.srcObject===this._msStream||this._element.pause(),this._element.onloadstart=e=>{var t,s;O.debug(`HTMLMediaElement onloadstart -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onloadstart -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.ondurationchange=e=>{var t,s;O.debug(`HTMLMediaElement ondurationchange -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement ondurationchange -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onloadedmetadata=e=>{var t,s;O.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onloadedmetadata -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onloadeddata=e=>{var t,s;O.debug(`HTMLMediaElement onloadeddata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onloadeddata -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.onabort=e=>{var t,s;O.info(`HTMLMediaElement onabort -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onabort -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.oncanplay=e=>f(this,void 0,void 0,(function*(){var t,s,o;O.info(`HTMLMediaElement oncanplay -> 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 oncanplay -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC});try{null===(o=this._element)||void 0===o||o.play()}catch(e){if("No permission to use requested device"===e.message)return O.error(`setSinkId failed -> ${e.message}`),void r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:v.NO_PERMISSION_TO_USE_REQUESTED_DEVICE,msg:"No permission"},{logSource:i.RTC});O.error(e),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:v.TRACK_PLAY_ERROR,msg:"play error"},{logSource:i.RTC})}})),this._element.onvolumechange=e=>{var t,s;const o=Math.floor(100*(null===(t=e.target)||void 0===t?void 0:t.volume));O.info(`HTMLMediaElement onvolumechange -> volume: ${o}, trackId: ${this._id}`),r.info(L.L_TRACK_PLAY_R,{status:A.INFO,msg:`HTMLMediaElement onvolumechange -> id: ${null===(s=e.target)||void 0===s?void 0:s.id}, trackId: ${this._id}`},{logSource:i.RTC})},this._element.srcObject=this._msStream,this._element.autoplay=!0,o&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),(null==t?void 0:t.audioDeviceId)&&!o&&(yield this._element.setSinkId(t.audioDeviceId)),o||!(null==t?void 0:t.volume)&&0!==(null==t?void 0:t.volume)||(this._element.volume=(null==t?void 0:t.volume)/100),r.info(L.L_TRACK_PLAY_R,{status:A.SUCCESSED,element:e,options:t},{logSource:i.RTC}),{code:v.SUCCESS}):(O.error(`the video track need an <video> to play -> id: ${this._id}`),r.error(L.L_TRACK_PLAY_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> element不是一个video标签"},{logSource:i.RTC}),{code:v.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"}(Qe||(Qe={}));const Xe={[Qe.Music]:{max:64e3,min:64e3},[Qe.MusicHigh]:{max:128e3,min:128e3},[Qe.Speech]:{max:32e3,min:32e3}};var et;!function(e){e.LEVEL0="LEVEL0",e.LEVEL1="LEVEL1",e.LEVEL2="LEVEL2",e.LEVEL3="LEVEL3",e.LEVEL4="LEVEL4",e.LEVEL5="LEVEL5"}(et||(et={}));const tt={[et.LEVEL0]:{max:150,min:80},[et.LEVEL1]:{max:280,min:120},[et.LEVEL2]:{max:650,min:150},[et.LEVEL3]:{max:1e3,min:200},[et.LEVEL4]:{max:2200,min:250},[et.LEVEL5]:{max:4e3,min:400}};class rt{static setStatus(e=!0){rt.isOpen=e}static setWroklet(e,t){rt.workletModule=e,rt.workletModule=t}static transformStreamTrack(e){var t;return f(this,void 0,void 0,(function*(){if(!rt.isOpen)return new Promise((t=>{t({track:null==e?void 0:e.getAudioTracks()[0],stop:()=>{}})}));const r=new AudioContext({sampleRate:44100}),s=r.createMediaStreamSource(e),o=r.createMediaStreamDestination(),n=yield r.audioWorklet.addModule(rt.workletModule).then((()=>(O.info(L.L_RTC_3ANOISE_NODE_O,{status:A.SUCCESSED,message:{msg:"addModule RC3AnoiseTrack.workletModule success"}},{logSource:i.RTC}),fetch(rt.workletWasm,{credentials:"same-origin"}).then((function(e){return e.arrayBuffer()})).catch((e=>{throw new Error(e.message)}))))).then((e=>new AudioWorkletNode(r,"process-worklet",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{binary:e}}))).catch((e=>{O.info(L.L_RTC_3ANOISE_NODE_E,{status:A.FAILED,message:{msg:e.message}},{logSource:i.RTC})}));if(!n)return new Promise((t=>{t({track:null==e?void 0:e.getAudioTracks()[0],stop:()=>{}})}));s.connect(n).connect(o);return{track:null===(t=null==o?void 0:o.stream)||void 0===t?void 0:t.getAudioTracks()[0],stop:()=>{O.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:""})}}}))}}rt.workletModule="https://cdn.ronghub.com/plugin-rtc/wasm/5.0.0-alpha.1/process-worklet.js",rt.workletWasm="https://cdn.ronghub.com/plugin-rtc/wasm/5.0.0-alpha.1/AudioProcessing.wasm",rt.isOpen=!1;class it extends Ze{constructor(e,t,r,i){super(e,t,r,!0),this._isPublished=!1,this.__innerSetMediaStreamTrack(i),i.onended=()=>{i.onended=null,this.emit(it.EVENT_LOCAL_TRACK_END,this),this.removeAll(it.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(e){const t=this._localMuted!==e;super._setLocalMuted(e),this._remoteMuted=this._localMuted,t&&this.emit(it.__INNER_EVENT_MUTED_CHANGE__,this),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;O.info(`track is destroyed -> trackId: ${this.getTrackId()}`),null===(e=this._msTrack)||void 0===e||e.stop(),super.__innerDestroy(),this.isAudioTrack()&&super.__releaseMediaElement(),this.emit(it.__INNER_EVENT_DESTROY__,this),r.info(L.L_LOCAL_TRACK_DESTROY_O,{status:A.SUCCESSED},{logSource:i.RTC})}setBitrate(e=0,t=0,o=0){if(!s(e)||!s(t)||!s(o)||e<=0||t<=0||e<t)return O.error("setBitrate params error ->"),void r.error(L.L_LOCAL_TRACK_SET_BITRATE_O,{status:A.FAILED,code:"",msg:`params error -> max: ${e},min: ${t}, start: ${o}`},{logSource:i.RTC});r.info(L.L_LOCAL_TRACK_SET_BITRATE_O,{status:A.SUCCESSED,max:e,min:t,start:o},{logSource:i.RTC}),this._bitrateInfo={max:e,min:t,start:o}}getBitrate(){var e,t,r,i,s,o,n;let{min:a,max:c,start:d}={min:0,max:0,start:0};return(null===(e=this._msTrack)||void 0===e?void 0:e.kind)===ze.VIDEO?({min:a,max:c}=gt(this._msTrack)):(null===(t=this._msTrack)||void 0===t?void 0:t.kind)===ze.AUDIO&&({min:a,max:c}={min:32e3,max:32e3}),(null===(r=this._bitrateInfo)||void 0===r?void 0:r.max)&&(d=.7*(null===(i=this._bitrateInfo)||void 0===i?void 0:i.max)),{min:(null===(s=this._bitrateInfo)||void 0===s?void 0:s.min)||a,max:(null===(o=this._bitrateInfo)||void 0===o?void 0:o.max)||c,start:(null===(n=this._bitrateInfo)||void 0===n?void 0:n.start)||d}}}it.EVENT_LOCAL_TRACK_END="local-track-end",it.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",it.__INNER_EVENT_DESTROY__="inner-destroy";class st extends it{constructor(e,t,r){super(e,t,"audio",r),this._stopProcess=()=>{}}setRecommendBitrate(e){if(!o("livingType",e,(e=>e in Qe)))return void r.warn(L.L_RTC_SET_RECOMMEND_BITRATE_O,{status:A.FAILED,msg:"params error -> setRecommendBitrate Audio"},{logSource:i.RTC});const t=Xe[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(rt.isOpen){const t=new MediaStream([e]);rt.transformStreamTrack(t).then((({track:e,stop:t})=>{super.__innerSetMediaStreamTrack(e),this._stopProcess=t}))}else super.__innerSetMediaStreamTrack(e);else super.__innerSetMediaStreamTrack(e),this._stopProcess()}}class ot extends it{constructor(e,t,r,i=!1){super(e,t,"video",r),this._isTiny=i}__isTiny(){return this._isTiny}getStreamId(){const e=super.getStreamId();return this._isTiny?`${e}_tiny`:e}getTrackId(){const e=super.getTrackId();return this._isTiny?`${e}_tiny`:e}setRecommendBitrate(e){if(!o("livingType",e,(e=>e in et)))return void r.warn(L.L_RTC_SET_RECOMMEND_BITRATE_O,{status:A.FAILED,msg:"params error -> setRecommendBitrate Video"},{logSource:i.RTC});const t=tt[e];this.setBitrate(t.max,t.min,t.start||.7*t.max)}setBitrate(e,...t){const[r=1,i=.7*e||1]=t;super.setBitrate(e,r,i)}}class nt extends it{constructor(e,t,r,i,s){super(e,t,r,i),this._resource=s,nt.__innerSetMapping(this.getTrackId(),s)}static __innerSetMapping(e,t){const r=this._mapping.get(t)||[];r.push(e),this._mapping.set(t,r)}static __innerRemoveMapping(e,t){var r,i;const s=null===(r=this._mapping.get(t))||void 0===r?void 0:r.filter((t=>t!==e));s&&s.length>0?this._mapping.set(t,s):(this._mapping.delete(t),t.pause(),t.src="",null===(i=t.parentNode)||void 0===i||i.removeChild(t))}destroy(){this.isAudioTrack()&&this.mute(),nt.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}nt._mapping=new Map;class at extends nt{constructor(e,t,r,i){super(e,t,"video",r,i)}}class ct extends nt{constructor(e,t,r,i){super(e,t,"audio",r,i),this._stopProcess=()=>{}}_setLocalMuted(e){this._resource&&(this._resource.muted=e),super._setLocalMuted(e)}play(){return this._setLocalMuted(!1),Promise.resolve({code:v.SUCCESS})}__innerSetMediaStreamTrack(e){if(e)if(rt.isOpen){const t=new MediaStream([e]);rt.transformStreamTrack(t).then((({track:e,stop:t})=>{super.__innerSetMediaStreamTrack(e),this._stopProcess=t}))}else super.__innerSetMediaStreamTrack(e);else super.__innerSetMediaStreamTrack(e),this._stopProcess()}}class dt extends st{}class _t extends ot{}class ut extends ot{}class lt extends st{}class ht extends Ze{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 Rt extends ht{constructor(e,t,r){super(e,t,"audio",r)}}class pt extends ht{constructor(e,t,r){super(e,t,"video",r),this._isSubTiny=!1}__innerSetIsTinyTrack(e){this._isSubTiny=e}isSubTiny(){return this._isSubTiny}}const mt=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),Ct=e=>JSON.stringify(e),Tt=e=>/^[a-zA-Z\d-=]+$/g.test(e),Et="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),It=e=>{if(void 0===e)return 0;if(s(e))return e;const t=e;return t.exact||t.ideal||t.max||0},St=e=>{const t=e.getSettings(),r=e.getConstraints();return{width:t.width||It(r.width),height:t.height||It(r.height),frameRate:t.frameRate||It(r.frameRate)}},gt=e=>{const{width:t,height:r,frameRate:i}=St(e),s=Je(t||1920,r||1080),o=Ye(i);return{min:s.minBitrate*o,max:s.maxBitrate*o}},ft=e=>[e.msid,e.mediaType].join("_"),Ot=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},vt=(e,t)=>[e,t].join("_"),Lt=e=>e.map((e=>Object.assign({},e))),At=(e,t,r=!1)=>{e=e.slice();const i=[],s=[],o=[];return t.forEach((t=>{const s=ft(t);let n=e.findIndex((e=>ft(e)===s));if(r&&(n=e.findIndex((e=>e.uri===t.uri))),-1===n)return void i.push(t);const a=e[n];a.uri!==t.uri?i.push(t):a.state!==t.state&&o.push(t),e.splice(n,1)})),s.push(...e),{publishedList:i,unpublishedList:s,modifiedList:o}},Nt=()=>{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 s=[];do{const e=i%r;i=(i-e)/r,s.unshift(t[e])}while(i);return s.join("")})(e),e.length>22&&(e=e.slice(0,22)),e},Dt=e=>{const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},kt=e=>!!Ke[e],bt=e=>!!Ge[e],Ut=e=>parseInt(e.replace("FPS_","")),Pt=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=$e.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function yt(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function Mt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const xt=e=>"[object Null]"===Object.prototype.toString.call(e),wt=e=>1===e.type,Bt=(e,t)=>{const r={},i=Object.keys(e.users);return i.length&&i.forEach((i=>{const s=[],o=e.users[i];if(o.extra){const e=JSON.parse(o.extra).roomId;if(t!==e)return}if(o.uris)try{s.push(...JSON.parse(o.uris))}catch(e){O.warn(`invalid user data -> userId: ${i}, userData: ${o}`)}r[i]=s})),r},Vt=e=>e instanceof Ze?e.getTrackId():e.track.getTrackId();var Ft,$t;!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"}(Ft||(Ft={})),function(e){e.SUCCESS="Success",e.FAIL="Fail"}($t||($t={}));class Gt{constructor(e,t,r,i=5e3,s=6e4){this._roomId=e,this._roomMode=t,this._context=r,this._gap=i,this._offlineKickTime=s,this._latestTimestamp=Date.now(),this._started=!1,this._timer=null}start(){this._started||(O.info("rtcping start ->"),r.info(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=>{O.error(`rtcping receive unknown error -> ${t}`),e(n.UNKNOWN)})),setTimeout(e,5e3,n.TIMEOUT)}))}_checkAlive(){var e,t,s;return f(this,void 0,void 0,(function*(){O.info("rtcping ->");const o=yield this._sendPing(),a=Date.now();return o===n.SUCCESS?(O.info("rtcping success ->"),this._latestTimestamp=a,null===(e=this.onPingResult)||void 0===e||e.call(this,$t.SUCCESS),void(this._timer=setTimeout((()=>this._checkAlive()),this._gap))):(o===n.TIMEOUT&&r.error(L.L_PINGER_TIMEOUT_O,{status:A.TIMEOUT},{logSource:i.RTC}),O.warn(`rtcping failed -> code: ${o}`),null===(t=this.onPingResult)||void 0===t||t.call(this,$t.FAIL),40003===o||a-this._latestTimestamp>this._offlineKickTime?(this.stop(),void(null===(s=this.onFailed)||void 0===s||s.call(this,40003===o))):void(this._timer=setTimeout((()=>this._checkAlive()),500)))}))}stop(){this._started&&(O.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 Kt=()=>"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)})),Ht=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${Pt.browser}|${Pt.version}`,ClientVersion:"5.4.4","Client-Session-Id":Kt(),"Request-Id":Date.now().toString()});class jt{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=""}getNaviMS(){return this._msUrl?[this._msUrl]:this._clusterId?[`https://${this._clusterId}`]:(0===this._msInNavi.length&&(0===this._failedMs.length?this._msInNavi.push(...(e=>{var t;if(!e)return[];let r;try{r=JSON.parse(e.voipCallInfo||'{ "strategy": 0 }')}catch(t){return O.warn("parse `voipCallInfo` of navi failed: "+e.voipCallInfo),[]}if(0===r.strategy)return[];const i=null===(t=r.callEngine)||void 0===t?void 0:t.filter((e=>4===e.engineType));if(!i||0===i.length)return[];const s=i[0],o=[];return s.mediaServer&&o.push(s.mediaServer.replace(/^(https?:\/\/)?/,"https://")),s.backupMediaServer&&s.backupMediaServer.forEach((e=>{o.push(e.replace(/^(https?:\/\/)?/,"https://"))})),o})(this._context.getNaviInfo())):(this._msInNavi.push(...this._failedMs),this._failedMs.length=0)),this._msInNavi.map((e=>e.trim())))}_request(e,t,s){return f(this,void 0,void 0,(function*(){const o=this.getNaviMS();if(0===o.length)return O.warn(`request '${e}' failed -> have no valid service address.`),r.error(L.L_MEDIA_SERVICE_REQUEST_R,{status:A.FAILED,code:v.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"invalid navi_url"},{logSource:i.RTC}),{code:v.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(s.rtcFinger=this._rtcFinger);for(let n=0;n<o.length;n+=1){const c=`${o[n]}${e}`,d=Ht(),_=Object.assign(Object.assign({},d),t),u=JSON.stringify(s),l=d["Request-Id"];r.info(L.L_MEDIA_SERVICE_REQUEST_T,{path:e,headers:t,body:s,reqId:l},{logSource:i.RTC}),O.info(`request -> Request-Id: ${l}, url: ${c}, headers: ${JSON.stringify(_)}, body: ${u}`);const{status:h,data:R}=yield this._runtime.httpReq({url:c,body:u,headers:_,method:a.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),O.info(`request success -> Request-Id: ${l}`),r.info(L.L_MEDIA_SERVICE_REQUEST_R,{status:A.SUCCESSED,reqId:l},{logSource:i.RTC}),{code:v.SUCCESS,data:e}}O.warn(`request failed -> Request-Id: ${l}, status: ${h}, url: ${c}`),this._failedMs.push(...this._msInNavi.splice(n,1)),r.error(L.L_MEDIA_SERVICE_REQUEST_R,{status:A.FAILED,code:"",reqId:l,msg:`request error -> Request-Id: ${l}, status: ${h}, url: ${c}`},{logSource:i.RTC})}return{code:v.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===v.SUCCESS&&(null===(r=i.data)||void 0===r?void 0:r.resultCode)===v.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 O.warn("RCMediaService.setMcuConfig failed -> RCRTCCode.MCU_SERVER_NOT_FOUND"),r.error(L.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:A.FAILED,code:v.MCU_SERVER_NOT_FOUND,msg:"MCU not found"},{logSource:i.RTC}),{code:v.MCU_SERVER_NOT_FOUND};const s=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,o=Ht(),n=Object.assign(Object.assign({},o),e),c=JSON.stringify(t),d=o["Request-Id"];O.info(`request -> Request-Id: ${d}, url: ${s}, headers: ${JSON.stringify(n)}, body: ${c}`);const{status:_,data:u}=yield this._runtime.httpReq({url:s,headers:n,body:c,method:a.POST});if(200===_){O.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 O.warn(`request failed -> Request-Id: ${d}, status: ${_}, url: ${s}`),r.error(L.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:A.FAILED,code:v.REQUEST_FAILED,msg:`request error -> Request-Id: ${d}, status: ${_}, url: ${s}`},{logSource:i.RTC}),{code:v.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 s=Ht(),o=Object.assign(Object.assign({},s),e),n=s["Request-Id"];O.info(`request -> Request-Id: ${n}, url: ${t}, headers: ${JSON.stringify(o)}`);const{status:c,data:d}=yield this._runtime.httpReq({url:t,headers:o,method:a.GET});if(200===c){O.info(`request success -> Request-Id: ${s["Request-Id"]}`);const e=JSON.parse(d);return r.info(L.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:A.SUCCESSED,reqId:s["Request-Id"]},{logSource:i.RTC}),{code:e.resultCode,res:e}}return O.warn(`request failed -> Request-Id: ${s["Request-Id"]}, status: ${c}, url: ${t}`),r.info(L.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:A.FAILED,code:v.REQUEST_FAILED,msg:`request error -> Request-Id: ${s["Request-Id"]}, status: ${c}, url: ${t}`},{logSource:i.RTC}),{code:v.REQUEST_FAILED}}))}}var Jt;!function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(Jt||(Jt={}));const Wt=(e,t)=>Math.round(8*t/e),Yt=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},qt=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.round(e*r)},zt=(e,t,r,i)=>{if(0===t)return 0;if(!r||!i)return Yt(e/t,3);const s=t-i;if(0===s)return 0;const o=e-r;return o<0||s<0?0:Yt(o/s,3)},Qt=e=>{const{jitter:t,rtt:r,packetsLostRate:i}=e;return!xt(t)||!xt(r)||0!==i};class Zt{constructor(e,t,r){this._rtcPeerConn=e,this._sdpSemantics=t,this._currentUserId=r,this._latestPacketsSent={},this._latestBytesSent={},this._latestBytesRecv={},this._latestPacketsRecv={}}updateBytesSent(e,t,r){let i,s;if(this._latestBytesSent[e]&&t<this._latestBytesSent[e].bytesSent&&this.clearLatestpacketsSent([e]),this._latestBytesSent[e]){const{bytesSent:o,timestamp:n}=this._latestBytesSent[e];i=t-o,s=r-n,this._latestBytesSent[e]={bytesSent:t,timestamp:r}}else i=t,s=1e3,this._latestBytesSent[e]={bytesSent:t,timestamp:r};return Wt(s,i)}updateBytesRecv(e,t,r){let i,s;if(this._latestBytesRecv[e]&&t<this._latestBytesRecv[e].bytesRecv&&this.clearLatestPacketsRecv([e]),this._latestBytesRecv[e]){const{bytesRecv:o,timestamp:n}=this._latestBytesRecv[e];i=t-o,s=r-n,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r}}else i=t,s=1e3,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r};return Wt(s,i)}updateSenderPacketsLost(e,t,r){let i;if(Object.prototype.hasOwnProperty.call(this._latestPacketsSent[e],"packetsSent")){const{packetsLost:s,packetsSent:o}=this._latestPacketsSent[e];i=zt(t,r,s,o),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=s===t?o:r}else i=zt(t,r),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=r;return i}updateReceiverPacketsLost(e,t,r){let i;if(this._latestPacketsRecv[e]){const{packetsLost:s,packetsRecv:o}=this._latestPacketsRecv[e];i=zt(t,r+t,s,o+s)}else i=zt(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 s=i.value,o=e.get(s);/^RTCCodec_/.test(s)||(r[s]=o),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,s=e.kind||e.mediaType,o=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,n=null===(r=this._rtcPeerConn.currentRemoteDescription)||void 0===r?void 0:r.sdp;let a;a="unified-plan"===this._sdpSemantics?new RegExp("a=msid:(.*?) "):new RegExp(`a=ssrc:${i} msid:(.*?) `);const c=null==o?void 0:o.split("\r\nm="),d=null==c?void 0:c.filter((e=>e.includes(`a=ssrc:${i}`)))[0],_=null==d?void 0:d.match(a);let u=_?_[1]:"";if(u){if("audio"===s)return`${u}_0`;const e=u.replace(`${this._currentUserId}_`,"").split("_");return e.length>1&&"tiny"===e[1]?`${this._currentUserId}_${e[0]}_1_tiny`:`${u}_1`}const l=null==n?void 0:n.split("\r\nm="),h=null==l?void 0:l.filter((e=>e.includes(`a=ssrc:${i}`)))[0],R=null==h?void 0:h.match(a);return u=R?R[1]:"",u?`${u}_${"video"===s?1:0}`:""}isValidSender(e){var t;const r=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}isValidReceiver(e){var t;const r=null===(t=this._rtcPeerConn.currentRemoteDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}}class Xt extends Zt{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let s=0,o=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const n=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const{id:a,kind:c,transportId:d,mediaSourceId:_,remoteId:u,packetsSent:l,bytesSent:h,trackId:R,encoderImplementation:p,pliCount:m,nackCount:C,firCount:T}=n;if(!R)return;let{framesPerSecond:E,frameWidth:I,frameHeight:S}=n;"video"!==c||I||S||E||(I=e[R].frameWidth,S=e[R].frameHeight,E=_?e[_].framesPerSecond:null);const g=e[u];let f=null,O=null,v=0;g&&(f=g.jitter,O=g.roundTripTime,v=g.packetsLost),s+=v;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,v,l):this._latestPacketsSent[L].crtPacketsSent=l;let D=this.updateBytesSent(L,h,r);D<0&&(D=0),o+=D,t.senders.push({id:a,trackId:L,kind:c,packetsLostRate:N,remoteResource:!1,audioLevel:A||0===A?qt(A):null,frameWidth:I,frameHeight:S,frameRate:E,bitrate:D,jitter:f?Math.round(1e3*f):f,rtt:O,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:s,roundTripTime:o,packetsLost:n}=e[r],a=t.senders.filter((e=>e.id===i))[0];if(a&&!Qt(a)){const t=this.getResourceIdByParseSdp(e[a.id]);a.jitter=Math.round(1e3*s),a.rtt=o;const r=this._latestPacketsSent[t].crtPacketsSent;a.packetsLostRate=this.updateSenderPacketsLost(t,n,r)}}));let n=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const o=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:_,bytesReceived:u,framesPerSecond:l,kind:h,codecImplementationName:R,nackCount:p,pliCount:m}=o;if(!a)return;let{frameWidth:C,frameHeight:T,audioLevel:E}=o;"video"===h?C||T||(C=e[a].frameWidth,T=e[a].frameHeight):E||(E=e[a].audioLevel),s+=c;const I=this.getResourceIdByParseSdp(o),S=this.updateReceiverPacketsLost(I,c,d);let g=this.updateBytesRecv(I,u,r);g<0&&(g=0),n+=g,t.receivers.push({trackId:I,kind:h,packetsLostRate:S,remoteResource:!0,audioLevel:E||0===E?qt(E):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:E}=m;t.iceCandidatePair={IP:h,port:R,networkType:p,remoteIP:C,remotePort:T,protocol:E,bitrateRecv:n,bitrateSend:o,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:s},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTPAudioStream_/.test(e))).forEach((r=>{var i;const s=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(s))return;const{mediaSourceId:o,trackId:n}=s,a=this.getResourceIdByParseSdp(s),c=o&&e[o]?e[o].audioLevel:(null===(i=e[n])||void 0===i?void 0:i.audioLevel)||null;t.push({trackId:a,audioLevel:c||0===c?qt(c):null})}));return r.filter((e=>/^RTCInboundRTPAudioStream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:s}=i,o=i.audioLevel||e[s].audioLevel,n=this.getResourceIdByParseSdp(i);t.push({trackId:n,audioLevel:o||0===o?qt(o):null})})),t}}class er extends Zt{formatRCRTCStateReport(e){const t=+new Date,r={senders:[],receivers:[],timestamp:t};let i=0,s=0,o=0;for(const n in e){const a=e[n],c=a.type;if("outbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(a))continue;const{id:o,kind:n,bytesSent:c,packetsSent:d,bitrateMean:_,framerateMean:u,nackCount:l,pliCount:h,remoteId:R}=a,{jitter:p,roundTripTime:m,packetsLost:C}=R?e[R]:{jitter:null,roundTripTime:null,packetsLost:0},T=this.getResourceIdByParseSdp(a);i+=C;let E=null;!this._latestPacketsSent[T]&&(this._latestPacketsSent[T]={}),R?E=this.updateSenderPacketsLost(T,C,d):this._latestPacketsSent[T].crtPacketsSent=d;let I=0;"video"===n?_&&(I=Math.floor(_/1e3)):I=this.updateBytesSent(T,c,t),I<0&&(I=0),s+=I,r.senders.push({trackId:T,kind:n,packetsLostRate:E,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:I,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]),s=r.senders.filter((e=>e.trackId===i))[0];s&&Qt(s)&&(s.jitter=Math.round(1e3*a.jitter),s.rtt=a.rtt,s.packetsLostRate=this.updateSenderPacketsLost(i,a.packetsLost,this._latestPacketsSent[i].crtPacketsSent))}if("inbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(a))continue;const{id:e,packetsLost:s,bytesReceived:n,packetsReceived:c,jitter:d,framerateMean:_,kind:u,bitrateMean:l,nackCount:h,pliCount:R}=a,p=this.getResourceIdByParseSdp(a);i+=s;const m=this.updateReceiverPacketsLost(p,s,c);let C=0;"video"===u?l&&(C=Math.floor(l/1e3)):C=this.updateBytesRecv(p,n,t),C<0&&(C=0),o+=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:o,bitrateSend:s,rtt:null,availableOutgoingBitrate:null,availableIncomingBitrate:null,totalPacketsLost:i}}}return r.iceCandidatePair&&(r.iceCandidatePair.bitrateSend=s),r.iceCandidatePair&&(r.iceCandidatePair.bitrateRecv=o),r}getAudioLevelList(e){const t=[];for(const r in e){const i=e[r],s=i.type;if("outbound-rtp"===s){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}if("inbound-rtp"===s){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}}return t}}class tr extends Zt{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let s=0,o=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const s=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(s))return;const n=this.getResourceIdByParseSdp(s),{mediaType:a,transportId:c,remoteId:d,packetsSent:_,bytesSent:u,trackId:l,encoderImplementation:h,pliCount:R,nackCount:p,firCount:m}=s;if(!l)return;const{audioLevel:C,frameHeight:T,frameWidth:E}=e[l];let I=this.updateBytesSent(n,u,r);I<0&&(I=0),o+=I,t.senders.push({trackId:n,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:C||0===C?qt(C):null,frameWidth:E,frameHeight:T,frameRate:null,bitrate:I,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 o=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:_,bytesReceived:u,mediaType:l,nackCount:h,pliCount:R}=o,p=this.getResourceIdByParseSdp(o);if(!a)return;const{frameHeight:m,frameWidth:C,audioLevel:T}=e[a];s+=c;const E=this.updateReceiverPacketsLost(p,c,d);let I=this.updateBytesRecv(p,u,r);I<0&&(I=0),n+=I,t.receivers.push({trackId:p,kind:l,packetsLostRate:E,remoteResource:!0,audioLevel:T||0===T?qt(T):null,frameWidth:C,frameHeight:m,frameRate:null,bitrate:I,jitter:_,codecImplementationName:null,nackCount:h,pliCount:R,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:_,remoteCandidateId:u}=r,l=e[_],{address:h,port:R}=l,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:o,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:s},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const{trackId:s,mediaType:o}=i;if("video"===o)return;const n=this.getResourceIdByParseSdp(i),a=e[s];t.push({trackId:n,audioLevel:a||0===a?qt(a):null})}));return r.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:s,mediaType:o}=i;if(!s||"video"===o)return;const{audioLevel:n}=e[s],a=this.getResourceIdByParseSdp(i);t.push({trackId:a,audioLevel:n||0===n?qt(n):null})})),t}}class rr{constructor(e,t){this.SDP=e,this.type=t,this.SDPHeader="",this.videoStreams=[],this.audioStreams=[];const r=this.getStreamIndex();this.spliteStreams(r)}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]);for(let t=1;t<e.length;t++){const r=this.SDP.substring(e[t],e[t+1]);this.clearInactiveOrRecvonly(r)&&(/^\bm=video\b/.test(r)?this.videoStreams.push(r):this.audioStreams.push(r))}}clearInactiveOrRecvonly(e){return/\ba=(recvonly|inactive)\b/.test(e)?e.replace(/\r\na=(ssrc|msid)[^\r\n]+/gi,""):e}setAudiosBitrate(e){return O.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 O.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}setAudioItemBitrate(e,t){if(0===t.max)return e;if(!/\bmaxaveragebitrate\b/gi.test(e)){const r=["$1",`maxaveragebitrate=${t.max}`];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(/^(m=audio[^\r\n]+)/,`$1\r\nb=AS:${t.max}`)}setVideosBitrate(e){return O.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 O.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}setVideoItemBitrate(e,t){if(0===t.max)return e;if(!/\bx-google-max-bitrate\b/.test(e)){const r=["$1",`x-google-max-bitrate=${t.max}`,`x-google-min-bitrate=${t.min}`,`x-google-start-bitrate=${t.start||.7*t.max}`];e=e.replace(/(\bprofile-level-id=[^\r\n]+)/gi,r.join(";"))}return this.addVideoBlineAS(e,t)}addVideoBlineAS(e,t){return/\bb=AS:\d+\b/gi.test(e)?e:e.replace(/^(m=video[^\r\n]+)/,`$1\r\nb=AS:${t.max}`)}}var ir,sr,or,nr,ar,cr,dr,_r,ur,lr,hr;!function(e){e.PLANB="plan-b",e.UNIFIEDPLAN="unified-plan"}(ir||(ir={}));class Rr{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:s,supportsUnifiedPlan:o}=Pt;r.debug(`sdpSemantics, browser: ${t}, version: ${s}, supportsUnifiedPlan: ${o}`),o?/chrome/i.test(t)?this._sdpSemantics=s>92?"unified-plan":s<72?"plan-b":e:/firefox/i.test(t)?this._sdpSemantics="unified-plan":/safari/i.test(t)?this._sdpSemantics=s<12?"plan-b":"unified-plan":this._sdpSemantics="unified-plan":this._sdpSemantics="plan-b"}static getSdpSemantics(){return Rr._sdpSemantics}getOutboundVideoInfo(){const e=[];for(const t in this._outboundStreams){const r=this._outboundStreams[t].getVideoTracks()[0];if(!r)continue;const i=/_tiny$/.test(t),{width:s,height:o}=St(r);e.push({trackId:r.id,simulcast:i?Jt.TINY:Jt.NORMAL,resolution:`${s}x${o}`})}return e}setRemoteAnswer(e){return f(this,void 0,void 0,(function*(){e=rr.trimBlankLine(e),r.info(`set remote answer -> ${e}`);try{yield this._peer.setRemoteDescription({type:"answer",sdp:e})}catch(e){return O.error(e),r.info(L.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:A.FAILED,code:"",msg:e},{logSource:i.RTC}),v.SET_REMOTE_DESCRIPTION_FAILED}return r.info(L.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:A.SUCCESSED,sdp:e},{logSource:i.RTC}),v.SUCCESS}))}getStatParsr(e,t,r){return/chrome/i.test(Pt.browser)?new Xt(e,t,r):/Firefox/i.test(Pt.browser)?new er(e,t,r):/Safari/i.test(Pt.browser)?new tr(e,t,r):null}resetSdp(e){return rr.trimBlankLine(e)}}class pr extends rr{constructor(e){super(e,ir.PLANB),this.SDP=e}stringify(){const e=[this.SDPHeader];[...this.audioStreams,...this.videoStreams].forEach((t=>{const r=t.match(/\ba=mid:(video|audio)\b/);r&&r[1]===ze.AUDIO&&(e[1]=t),r&&r[1]===ze.VIDEO&&(e[2]=t)}));const t=e.join("");return rr.trimBlankLine(t)}setAudioBitrateWithStreamId(e,t){return O.warn("plan-b not support set Audio Bitrate With Stream Id"),this}setVideoBitrateWithStreamId(e,t){return O.warn("plan-b not support set Video Bitrate With Stream Id"),this}}class mr extends Rr{constructor(){super(...arguments),this.senders={},this._localTracks=[]}addLocalTrack(e){this._localTracks.includes(e)||this._localTracks.push(e);const t=e.getStreamId(),r=e.__innerGetMediaStreamTrack(),i=this._outboundStreams[t]||(this._outboundStreams[t]=new MediaStream);i.getTracks().forEach((e=>{e.kind===r.kind&&i.removeTrack(e)})),i.addTrack(r);const s=e.getTrackId(),o=this.senders[s];o?o.replaceTrack(r):this.senders[s]=this._peer.addTrack(r,i)}removeLocalTrack(e){const t=this._localTracks.findIndex((t=>t===e));t>=0&&this._localTracks.splice(t,1);const r=e.getTrackId(),i=this.senders[r];i&&(i.replaceTrack(null),this._peer.removeTrack(i),delete this.senders[r])}updateSubRemoteTracks(e){}updateRecvTransceiverMap(e,t){}setBitrate(e,t,r){this._maxBitrate=e,this._minBitrate=t,this._startBitrate=r||.7*e}createOffer(e){return 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=this.resetSdp(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 pr(e),r={max:0,min:0},i={max:0,min:0};return this._localTracks.forEach((e=>{const{min:t,max:s,start:o}=e.getBitrate();e.isAudioTrack()&&(i.max=i.max<s?s:i.max,i.min=i.min>t?t:i.min,i.max===s?i.start=o:i.start=.7*i.max),e.isVideoTrack()&&(r.max=r.max<s?s:r.max,r.min=r.min>t?t:r.min,r.max===s?r.start=o:r.start=.7*r.max)})),t.setAudiosBitrate(i),t.setVideosBitrate(r),t.stringify()}}class Cr extends rr{constructor(e){super(e,ir.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)}));const t=e.join("");return rr.trimBlankLine(t)}}class Tr extends Rr{constructor(){super(...arguments),this._sendTransceiver={},this._localTracks={},this._recvAudio=[],this._recvVideo=[],this._recvTransceiver={},this._subedTracks=[]}setBitrate(e,t,r){O.warn("the interface named `setBitrate` is invalid while sdpSemantics value is `unified-plan`")}addLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId(),i=e.__innerGetMediaStreamTrack();this._localTracks[t]=e;const s=this._outboundStreams[r]||(this._outboundStreams[r]=new MediaStream);s.getTracks().forEach((e=>{e.kind===i.kind&&s.removeTrack(e)})),s.addTrack(i);const o=this._sendTransceiver[t];o?(o.sender.replaceTrack(i),o.direction="sendonly"):this._sendTransceiver[t]=this._peer.addTransceiver(i,{direction:"sendonly",streams:[s]})}removeLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId();e.__innerGetMediaStreamTrack(),delete this._localTracks[t];const i=this._sendTransceiver[t];if(!i)return;i.direction="inactive",this._peer.removeTrack(i.sender),i.sender.replaceTrack(null);const s=this._outboundStreams[r];(e.isAudioTrack()?s.getAudioTracks():s.getVideoTracks()).forEach((e=>s.removeTrack(e)));const o=this._sendTransceiver[`${t}_tiny`];if(!o||"inactive"===o.direction)return;o.direction="inactive";const n=o.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,s=i.findIndex((e=>e===t));s>=0&&i.splice(s,1)}updateSubRemoteTracks(e){const t=e.slice(),r=this._subedTracks.slice();this._subedTracks=e.slice();for(let e=t.length-1;e>=0;e-=1){const i=t[e],s=r.findIndex((e=>e===i));s>=0&&(t.splice(e,1),r.splice(s,1))}r.length&&r.forEach((e=>{const t=e.getTrackId();e.__innerSetMediaStreamTrack(void 0);const r=this._recvTransceiver[t];r&&(r.direction="inactive")}));const i={audio:0,video:0};t.length&&t.forEach((e=>{const t=e.isAudioTrack()?"audio":"video",r=this._recvTransceiver[e.getTrackId()];r?r.direction="recvonly":i[t]+=1}));for(let e=this._recvAudio.length;e<i.audio;e+=1)this._recvAudio.push(this._peer.addTransceiver("audio",{direction:"recvonly"}));for(let e=this._recvVideo.length;e<i.video;e+=1)this._recvVideo.push(this._peer.addTransceiver("video",{direction:"recvonly"}))}createOffer(e){return 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.resetSdp(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.resetSdp(e);const t=/[\r\n]+\r\n[\r\n]+/g;return t.test(e)&&(O.warn(`answer sdp invalid -> ${JSON.stringify(e)}`),e=e.replace(t,"\r\n")),super.setRemoteAnswer(e)}resetSdp(e){const t=new Cr(e);for(const e in this._sendTransceiver){const r=this._localTracks[e],i=null==r?void 0:r.getBitrate(),s=null==r?void 0:r.getStreamId();i&&s&&(r.isVideoTrack()&&t.setVideoBitrateWithStreamId(i,s),r.isAudioTrack()&&t.setAudioBitrateWithStreamId(i,s))}return t.stringify()}}class Er 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 s=Rr.getSdpSemantics(),o=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:s});this._sdpStrategy="plan-b"===s?new mr(o):new Tr(o),this._rtcPeerConn.oniceconnectionstatechange=this._onICEConnectionStateChange.bind(this),this._rtcPeerConn.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._rtcPeerConn.ontrack=this._onTrackReady.bind(this),this.reportParser=this._sdpStrategy.getStatParsr(this._rtcPeerConn,s,this._currentUserId)}getName(){return this._pcName}getLocalTracks(){return r.info(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(){O.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;O.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||(O.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){O.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(Er.__INNER_EVENT_TRACK_READY__,e)}setBitrate(e,t,s){return f(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(e,t,s),r.info(L.L_RTC_PEER_CONNECTION_SET_BITRATE_O,{status:A.SUCCESSED,max:e,min:t,start:s},{logSource:i.RTC})}))}createOffer(e){return f(this,void 0,void 0,(function*(){const t=yield this._sdpStrategy.createOffer(e);return O.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 O.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(it.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(it.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.on(it.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.on(it.__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(it.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(it.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this);const s=`${t}_tiny`,o=this.getLocalTrack(s);o&&(this._sdpStrategy.removeLocalTrack(o),delete this.pubLocalTracks[s],o.destroy()),r.info(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){const t=this.getLocalTrack(`${e.getTrackId()}_tiny`);t&&(t.__innerGetMediaStreamTrack().enabled=!e.isLocalMuted()),this.emit(it.__INNER_EVENT_MUTED_CHANGE__,e),r.info(L.L_RTC_PEER_CONNECTION_LOCAL_TRACK_MUTED_O,{status:A.SUCCESSED,trackId:e.getTrackId()},{logSource:i.RTC})}_onLocalTrackDestroied(e){this.emit(it.__INNER_EVENT_DESTROY__,e)}registerReportListener(e){this._reportListener=e}_createRCRTCStateReport(e){const{timestamp:t,iceCandidatePair:r,senders:i,receivers:s}=JSON.parse(JSON.stringify(e));null==r||delete r.totalPacketsLost;for(const e in r)xt(r[e])&&delete r[e];return{timestamp:t,iceCandidatePair:r,senders:i.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),receivers:s.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),pcName:this._pcName}}_getStatsData(){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*(){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}}Er.__INNER_EVENT_TRACK_READY__="inner-track-ready",function(e){e[e.DISABLE=0]="DISABLE",e[e.ENABLE=1]="ENABLE"}(sr||(sr={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(or||(or={}));class Ir{constructor(e,t,r,i,s=or.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=i,this._userRole=s}_send(e){return f(this,void 0,void 0,(function*(){let t=!1;if(this._context.getConnectionStatus()!==c.CONNECTED)return t;return t=(yield this._context.setRTCState(this._roomId,e))===n.SUCCESS,t}))}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=Nt(),this._runtime.localStorage.setItem(e,t)),t}_getRealResourceId(e){let t=e;const r=e.indexOf("_tiny");return r>-1&&(t=e.slice(0,r)),t}_getPolarisTrackId(e){let t="";const r=e.split("_");if(e.includes("_tiny")){const e=r.pop(),i=parseInt(r.pop())===He.AUDIO_ONLY?"audio":"video",s=r.pop();t=[r.join("_"),s,e,i].join("_")}else{const e=parseInt(r.pop())===He.AUDIO_ONLY?"audio":"video",i=r.pop();t=[r.join("_"),i,e].join("_")}return t}sendR3R4Data(e){return f(this,void 0,void 0,(function*(){const{iceCandidatePair:t,senders:r,receivers:i}=e,s=(null==t?void 0:t.bitrateSend)||-1,o=(null==t?void 0:t.bitrateRecv)||-1,n=(null==t?void 0:t.networkType)||"unknown",a=(null==t?void 0:t.rtt)||-1,c=`${(null==t?void 0:t.IP)||-1}:${null==t?void 0:t.port}`,d=(null==t||t.remoteIP,null==t||t.remotePort,(null==t?void 0:t.availableIncomingBitrate)||-1),_=(null==t?void 0:t.availableOutgoingBitrate)||-1,u=(null==t?void 0:t.totalPacketsLost)||-1,l=this._context.getCurrentId();let h=`R3\t${s}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${_}\t${u}\t${l}\r`,R=`R4\t${o}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${_}\t${u}\t${l}\r`;const p=r.map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:s,bitrate:o,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:_,jitter:u,nackCount:l,pliCount:h,rtt:R,googFirsSent: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:o||0===o?o:-1,packetsLostRate:n||0===n?n:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:h||0===h?h:-1,rtt:R||-1,googFirsSent:p,samplingRate:s,googRenderDelayMs:_,encoderImplementation:m||String(-1),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(T))||void 0===t?void 0:t.isLocalMuted())?sr.DISABLE:sr.ENABLE}})),m=i.filter((e=>!!e.trackId)).map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:s,bitrate:o,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:_,jitter:u,nackCount:l,pliCount:h,rtt:R,googFirsReceived: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:o||0===o?o:-1,packetsLostRate:n||0===n?n:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:h||0===h?h:-1,rtt:R||-1,googFirsReceived:p,samplingRate:s,googRenderDelayMs:_,codecImplementationName:m||String(-1),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(T))||void 0===t?void 0:t.isLocalMuted())?sr.DISABLE:sr.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.4.4\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 Sr{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 s=(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(...s)}this._audioLevelChangeHandler(e)}))}onAudioLevelChange(e,t){t<300||t>1e3?O.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"}(nr||(nr={}));class gr{constructor(e=!1,t,r,i,s){this._useMutilPeerC=e,this._roomId=t,this._reTryExchange=r,this._currentUserId=i,this._polarisReport=s,this._mutilPeerC={}}get useMutilPeerC(){return this._useMutilPeerC}_isPub(e){if(!e.length)return!1;const{track:t}=e[0]instanceof it||e[0]instanceof ht?{track:e[0]}:e[0];return t.isLocalTrack()}_groupTracksByTag(e){const t={};return e.map((e=>{const{track:r}=e instanceof it?{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 Er(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 s=this._genPCName(r,e),o=i[e];t.push(this._createOnePeerCItem(s,o))}return t}_removeAllLocalTrack(){this.getPCList().forEach((e=>e.removeAllLocalTrack()))}destroyPeerC(e){this._mutilPeerC[e].pc.destroy()}_destroyAllPeerC(){this.getPCList().forEach((e=>e.destroy()))}getPCItemByPCName(e){return this._mutilPeerC[e]}getPCByTrackId(e,t=!0){const{tag:r}=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"}(ar||(ar={})),function(e){e.NORMAL="normal",e.MIDDLE="middle",e.TAIL="tail"}(cr||(cr={})),function(e){e[e.LOW=0]="LOW",e[e.NORMAL=1]="NORMAL",e[e.HIGH=2]="HIGH"}(dr||(dr={})),function(e){e[e.Destroy=40400]="Destroy"}(_r||(_r={}));class fr{get priority(){return dr.LOW}get kind(){return ar.Unknow}}class Or extends fr{constructor(e=cr.NORMAL){super(),this.state=e}get kind(){return ar.AsyncCommand}setState(e){this.state=e}pickoutSubscribed(e,t){const{unsubscribe:r,subscribe:i}=this.calcSubscribeList(e,t);return Or.AsyncSubscribeTasks=[],Or.AsyncUnsubscribeTasks=[],Or.AsyncUpdateSubscribeTasks=[],{subscribe:i,unsubscribe:r}}calcSubscribeList(e,t){const r=[],i=new Set,s=[],o=new Set,n=this.formateTrack(e),a=this.formateTrack(t);return a.forEach((e=>{const t=`${e.track.getTrackId()}_SUB_${e.subTiny?"0":"1"}`;this.trackInSubscribeList(e,n)||i.has(t)||(r.push(e),i.add(t))})),n.forEach((e=>{const t=`${e.track.getTrackId()}_SUB_${e.subTiny?"0":"1"}`;this.trackInSubscribeList(e,a)||o.has(t)||(s.push(e),o.add(t))})),{unsubscribe:r,subscribe:s}}formateTrack(e){return e.map((e=>e instanceof ht?{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}}Or.AsyncSubscribeTasks=[],Or.AsyncUnsubscribeTasks=[],Or.AsyncUpdateSubscribeTasks=[];class vr extends class{constructor(e,t,r,i,s,o,n,a,c){this.context=e,this.service=t,this.peerMgr=r,this.roomId=i,this.crtUserId=s,this.roomMode=o,this.polarisReport=n,this.isUpgrade=a,this.isMainRoom=c,this._remoteTracks={},this._subscribedList=[],this._collectSubscribeList=[],this._CDNUris=null,this._CDNEnable=!1,this._destroyed=!1}get useMutilPeerC(){return this.peerMgr.useMutilPeerC}getResourcesByUserId(e){return this._roomResources[e]}getRemoteTrack(e){return this._remoteTracks[e]}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getRemoteTracks(){return this._remoteTracks}getSessionId(){return this._sessionId}getAllUserIds(){return Object.keys(this._roomResources)}getRemoteUserIds(){return this.getAllUserIds().filter((e=>e!==this.crtUserId))}getSubscribedList(){return this._subscribedList}getCollectSubscribeList(){return this._collectSubscribeList}getPublishedResourceByTrackId(e){const{userId:t}=Ot(e);return this._roomResources[t].find((t=>ft(t)===e))}getToken(){return this._token}getLocalTrack(e){return this.peerMgr.getPCByTrackId(e).getLocalTrack(e)}getLocalTracks(){const e=[];return this.peerMgr.getPCList().forEach((t=>{e.push(...t.getLocalTracks())})),e}getTrackState(e){var t;return(null===(t=this.getLocalTrack(e))||void 0===t?void 0:t.isLocalMuted())?0:1}getCDNEnable(){return this._CDNEnable}getCDNUris(){return this._CDNUris}}{_initRemoteTracks(){for(const e in this._roomResources){const t=this._roomResources[e];e!==this.crtUserId&&0!==t.length&&t.forEach((e=>{const t=ft(e),{tag:r,userId:i,mediaType:s}=Ot(t),o=s===He.AUDIO_ONLY?new Rt(r,i):new pt(r,i);o.__innerSetRemoteMuted(0===e.state),this._remoteTracks[t]=o}))}}initWithRoomData(e){this._sessionId=e.sessionId,this._token=e.token,this.isUpgrade?this._roomResources={}:this._roomResources=Bt(e,this.roomId),this._initRemoteTracks(),this.setResourcesByUserId(this.crtUserId,this.getResourcesByUserId(this.crtUserId)||[]),O.info(`room data -> ${JSON.stringify(this._roomResources)}`)}assignRoomData(e){Object.assign(this._roomResources,e)}setResourcesByUserId(e,t){this._roomResources[e]=t}removeRemoteTrack(e){delete this._remoteTracks[e]}removeResourcesByUserId(e){delete this._roomResources[e]}addRemoteTrack(e){this._remoteTracks[e.getTrackId()]=e}removeRemoteTracks(){const e=Object.values(this._remoteTracks);e.length&&(e.forEach((e=>{e.isAudioTrack()&&e.__releaseMediaElement()})),this._remoteTracks={})}setCDNEnabel(e){this._CDNEnable=e}setCDNUris(e){this._CDNUris=e}resetSubscribedList(e){this._subscribedList.splice(0,this._subscribedList.length,...e),this.resetCollectSubscribeList(e)}resetCollectSubscribeList(e){this._collectSubscribeList.splice(0,this._collectSubscribeList.length,...e)}}class Lr extends class{constructor(e,t){this._store=e,this.abortCode=t,this._queue=[],this._busy=!1,this._isDestroyed=!1}_next(){this._busy=!1,this._execute()}_execute(){return 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===ar.AsyncCommand&&({command:e,resolve:t,reject:r}=this.commandOffset(e,t,r));const s=e.priority;if(s===dr.LOW)this._queue.push({command:e,resolve:t,reject:r});else{const i=this._queue.findIndex((e=>e.command.priority<s)),o=-1===i?this._queue.length-1:i;this._queue.splice(o,0,{command:e,resolve:t,reject:r})}Promise.resolve().then((()=>{this._execute()}))}))}commandOffset(e,t,r){const i=this._queue.length-1;if(!(this._queue[i].command.kind===ar.AsyncCommand))return{command:e,resolve:t,reject:r};const[s]=this._queue.splice(i,1);s.command instanceof Or&&(s.command.setState(cr.MIDDLE),e instanceof Or&&e.setState(cr.TAIL));const o=e.execute;return e.execute=function(t,r){return f(this,void 0,void 0,(function*(){return s.command.execute.call(s.command,t,r),o.call(e,t,r)}))},{command:e,resolve:e=>{s.resolve.call(s,e),t(e)},reject:e=>{s.reject.call(s,e),r(e)}}}isDestroyed(){return this._isDestroyed}destroy(){this._isDestroyed||(this._isDestroyed=!0,this._queue.forEach((e=>{e.resolve({code:this.abortCode})})),this._queue.length=0)}}{constructor(e,t,r,i,s,o,n,a,c){super(new vr(e,t,r,i,s,o,n,a,c),v.ROOM_HAS_BEEN_DESTROYED)}get store(){return this._store}destroy(){super.destroy(),this._store.removeRemoteTracks()}}class Ar extends fr{execute(e){return f(this,void 0,void 0,(function*(){const t=e.getResourcesByUserId(e.crtUserId),r=t.slice();t.length=0,O.info(`unpublish uris before rejoin -> ${JSON.stringify(r)}`);const i=yield e.context.setRTCTotalRes(e.roomId,mt(Ft.UNPUBLISH,r),Ct([]),Ft.TOTAL_CONTENT_RESOURCE,Ct([]));i!==n.SUCCESS?O.error(`unpublish uris before rejoin failed -> code: ${i}`):O.info("unpublish uris before rejoin success")}))}}class Nr extends fr{constructor(e,t,r,i,s,o){super(),this.roomId=e,this.roomType=t,this.joinType=r,this.livingType=i,this.innerUserDatas=s,this.outerUserDatas=o}get kind(){return ar.JoinRoom}execute(e,t){var s;return f(this,void 0,void 0,(function*(){const{context:a,service:R}=e,p=this.roomType===d.LIVE?L.L_RTC_CLIENT_JOIN_LIVING_ROOM_R:L.L_RTC_CLIENT_JOIN_RTC_ROOM_R;if(a.getConnectionStatus()!==c.CONNECTED)return r.error(p,{status:A.FAILED,code:v.SIGNAL_DISCONNECTED,msg:"im not connected"},{logSource:i.RTC}),{code:v.SIGNAL_DISCONNECTED};if(wt(a.getNaviInfo()))return r.error(p,{status:A.FAILED,code:v.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_usl error"},{logSource:i.RTC}),{code:v.PACKAGE_ENVIRONMENT_ERROR};if(!o("roomId",this.roomId,_,!0))return r.error(p,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(!o("roomType",this.roomType,(e=>void 0!==d[e])))return r.error(p,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> roomType"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(!o("outerUserDatas",this.outerUserDatas,u,!1))return r.error(p,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(this.outerUserDatas){if(!Object.keys(this.outerUserDatas).every((e=>o(`outerUserDatas.${e}`,this.outerUserDatas[e],l,!0))))return r.error(p,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:i.RTC}),{code:v.PARAMS_ERROR}}if(!R.getNaviMS().length)return r.error(p,{status:A.FAILED,code:v.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:i.RTC}),{code:v.NOT_OPEN_VIDEO_AUDIO_SERVER};O.info(`joinRoom -> roomId: ${this.roomId}; joinType: ${this.joinType||h.KICK}`);const{code:m,data:C}=yield a.joinRTCRoom(this.roomId,this.roomType,this.livingType,this.joinType,this.innerUserDatas,this.outerUserDatas);if(m!==n.SUCCESS||!C){O.warn(`joinRoom failed -> code: ${m}`);const e=40032===m?v.SIGNAL_JOIN_RTC_ROOM_REFUSED:m;return r.error(p,{status:A.FAILED,code:e,msg:`joinRoom failed -> code: ${m}`},{logSource:i.RTC}),{code:e}}O.info(`joinRoom success -> userId: ${a.getCurrentId()}, roomId: ${this.roomId}, data: ${JSON.stringify(C)}`),e.initWithRoomData(C);e.getResourcesByUserId(e.crtUserId).length>0&&t.push(new Ar);const T=null===(s=C.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===s?void 0:s.value;return T&&e.setCDNUris(JSON.parse(T)[0]),r.info(p,{status:A.SUCCESSED,userId:e.crtUserId,roomId:this.roomId,data:C},{logSource:i.RTC}),{code:v.SUCCESS,data:C}}))}}function Dr(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),s=i.getResourcesByUserId(r);if(!s)return!1;const o=s.filter((e=>t===`${e.msid}_${e.mediaType}`)).length;return o})).map((e=>({simulcast:e.subTiny?Jt.TINY:Jt.NORMAL,resolution:"",uri:i.getPublishedResourceByTrackId(e.track.getTrackId()).uri}))),switchstream:!1}}))}function kr(e,t,r){return f(this,void 0,void 0,(function*(){const i=yield e.setRTCCDNUris(t,Ft.TOTAL_CONTENT_RESOURCE,JSON.stringify([r]));return i!==n.SUCCESS?(O.error(`spreadCDNInfo failed -> code: ${i}`),{code:v.SIGNAL_ERROR}):(O.info("spreadCDNInfo succeed"),{code:v.SUCCESS})}))}function br(e,t,r){return f(this,void 0,void 0,(function*(){const i=yield e.setRTCData(t,"cdn_uris",JSON.stringify([r]),!0,R.ROOM);return i!==n.SUCCESS?(O.error(`setRoomCDNInfo failed -> code: ${i}`),{code:v.SIGNAL_ERROR}):(O.info("setRoomCDNInfo succeed"),{code:v.SUCCESS})}))}function Ur(e){return f(this,void 0,void 0,(function*(){const t=e.context,s=e.roomId,o=Object.assign({},e.getCDNUris(),{enableInnerCDN:e.getCDNEnable()});r.info(L.L_LIVING_ROOM_SPREAD_CDN_INFO_T,{roomId:s,CDNUris:o},{logSource:i.RTC});const n=(yield Promise.all([kr(t,s,o),br(t,s,o)])).every((e=>e.code===v.SUCCESS));return n?r.info(L.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:A.SUCCESSED,CDNUris:o},{logSource:i.RTC}):r.error(L.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:A.FAILED,code:v.SIGNAL_ERROR,msg:"signal error"},{logSource:i.RTC}),n?{code:v.SUCCESS}:{code:v.SIGNAL_ERROR}}))}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(ur||(ur={})),function(e){e.BEGIN="begin",e.END="end"}(lr||(lr={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(hr||(hr={}));class Pr extends fr{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!==d.LIVE)return t;const s=null===(i=null===(r=t.data)||void 0===r?void 0:r.urls)||void 0===i?void 0:i.pull_url;if(t.code!==v.SUCCESS||!s)return t;const o=JSON.parse(s);return e.setCDNUris(o),(null==o?void 0:o.broadcast)===hr.SPREAD&&(e.setCDNEnabel(!0),Ur(e)),t}))}}class yr extends fr{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,s=e.roomId;if(!o("tracks",r,(()=>p(r)&&r.every((e=>e instanceof ht||e.track instanceof ht))),!0))return O.warn(`update sublist failed, tracks is invalid -> roomId: ${s}`),{code:v.PARAMS_ERROR};O.info(`update subscribe list -> roomId: ${s}, forceReq: ${i}, tracks: ${r.map(Vt)}`);let n=r.map((e=>e instanceof ht?{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):(O.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:v.SUCCESS}}const{pc:d,pushOtherRooms:_,headers:u}=this.subhook(r);d.updateSubRemoteTracks(n.map((e=>e.track)));const l=yield Dr(n,!1,d,e);_&&(l.pushOtherRooms=_);const h=yield new Pr(u,l).execute(e,t),R=n.map((e=>e.track.getTrackId()));if(h.code!==v.SUCCESS)return{code:h.code};const{sdp:m,resultCode:C,message:T,subscribedList:E}=h.data;if(C!==v.SUCCESS)return O.error(`change subscribe list failed: ${C}`),{code:C};O.debug(`subscribe success: ${R.join(",")}`);const I=yield d.setRemoteAnswer(m.sdp);if(I!==v.SUCCESS)return{code:I};const S=null==E?void 0:E.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:v.SUCCESS,failedList:f}:{code:v.SUCCESS}}))}}class Mr extends fr{constructor(e,t){super(),this.tracks=e,this.subhook=t}execute(e,t){return f(this,void 0,void 0,(function*(){const s=this.tracks,n=e.roomId;if(r.info(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:s.map(Vt)},{logSource:i.RTC}),!o("tracks",s,(()=>p(s)&&s.length>0&&s.every((e=>e instanceof ht))),!0))return O.warn(`unsubscribe failed, tracks is invalid -> roomId: ${n}`),r.warn(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};O.info(`unsubscribe -> roomId: ${n}, tracks: ${s.map(Vt)}`);const a=e.getSubscribedList().map((e=>Object.assign({},e))).filter((e=>!s.includes(e.track)));return e.polarisReport.sendR2(ur.SUBSCRIBE,lr.END,s.map((e=>e.getTrackId()))),r.info(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:s.map(Vt),roomId:n},{logSource:i.RTC}),new yr(a,this.subhook,!1).execute(e,t)}))}}class xr extends fr{constructor(e,t){super(),this.msgContent=e,this.subhook=t}get priority(){return dr.NORMAL}execute(e,t){return f(this,void 0,void 0,(function*(){const r=[],i=[],s=[],o=[],n={joined:r,left:i,upgrade:s,downgrade:o},{users:a}=this.msgContent;if(0===a.length)return n;for(let t=0;t<a.length;t++){const r=a[t];if(r.extra&&r.extra.roomId!==e.roomId)return n;if(1==+r.state&&!e.getRemoteUserIds().includes(r.userId))return n}a.forEach((t=>{const n=t.userId;if(0==+t.state){O.debug(`user joined -> ${n}`);const i=e.getResourcesByUserId(n);i||(t.switchRoleType?s.push(n):r.push(n)),e.setResourcesByUserId(n,i||[])}else O.debug(`user left -> ${n}`),t.switchRoleType?o.push(n):i.push(n)}));const c=[...i,...o];if(c.length){const r=[],i=[];c.forEach((t=>{r.push(...e.getRemoteTracksByUserId(t)),i.push(t)})),r.length&&(yield new Mr(r,this.subhook).execute(e,t),r.forEach((t=>e.removeRemoteTrack(t.getTrackId())))),i.length&&i.forEach((t=>e.removeResourcesByUserId(t)))}return n}))}}class wr extends fr{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 Mr(r,this.subhook).execute(e,t),r.forEach((t=>{t.__innerDestroy(),e.removeRemoteTrack(t.getTrackId())})),this.onTrackUnpublish(r)}))}}class Br extends fr{constructor(e,t,r,i,s){super(),this.msgContent=e,this.messageType=t,this.senderId=r,this.subhook=i,this.callback=s}get priority(){return dr.NORMAL}execute(e,t){var r,i;return f(this,void 0,void 0,(function*(){const{uris:s}=this.msgContent,o=[],n=[],a=[];let c;const _=this.senderId,u=this.messageType,l=e.getResourcesByUserId(_)||[];switch(e.setResourcesByUserId(_,l),u){case Ft.MODIFY:a.push(...s);break;case Ft.PUBLISH:o.push(...s);break;case Ft.UNPUBLISH:n.push(...s);break;case Ft.TOTAL_CONTENT_RESOURCE:c=At(l,s),o.push(...c.publishedList),n.push(...c.unpublishedList),a.push(...c.modifiedList)}if(o.length>0){const r=l.map(ft),i=[],s=[];if(o.forEach((t=>{const o=ft(t),n=r.indexOf(o),{userId:a,tag:c,mediaType:d}=Ot(o);n>-1?l[n]=t:l.push(t);let _=e.getRemoteTrack(o);_?_.isSubscribed()&&i.push(_):(_=d===He.AUDIO_ONLY?new Rt(c,a):new pt(c,a),e.addRemoteTrack(_),s.push(_)),_.__innerSetRemoteMuted(0===t.state)})),i.length){const r=i.map((e=>e.getTrackId()));O.debug(`resub tracks -> ${JSON.stringify(r)}`);const{code:s}=yield new yr(i,this.subhook).execute(e,t);s!==v.SUCCESS&&O.error(`resub tracks failed -> code: ${s}, ids: ${JSON.stringify(r)}`)}this.callback.onTrackPublish(s)}if(n.length>0){const r=n.map(ft);for(let e=l.length-1;e>=0;e-=1){const t=l[e];r.includes(ft(t))&&l.splice(e,1)}const i=n.map((t=>{const r=ft(t);return e.getRemoteTrack(r)}));yield new wr(this.subhook,i,this.callback.onTrackUnublish).execute(e,t)}if(a.length>0){const t=l.map(ft);for(let r=0;r<a.length;r+=1){const i=a[r],s=ft(i),o=t.indexOf(s);l[o].state=i.state;const n=e.getRemoteTrack(s);n.__innerSetRemoteMuted(0===i.state),n.isAudioTrack()?this.callback.onAudioMute(n):this.callback.onVideoMute(n)}}if(e.roomMode!==d.LIVE)return;const h=this.msgContent;if(!h.cdn_uris)return;const R=(null===(r=e.getCDNUris())||void 0===r?void 0:r.enableInnerCDN)!==h.cdn_uris[0].enableInnerCDN;e.setCDNUris(h.cdn_uris[0]),R&&this.callback.onCDNEnableChange(!!(null===(i=e.getCDNUris())||void 0===i?void 0:i.enableInnerCDN))}))}}class Vr extends fr{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:s,forceReq:n}=this,a=e.roomId;if(r.info(L.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:s.map(Vt),forceReq:n},{logSource:i.RTC}),!o("tracks",s,(()=>p(s)&&s.length>0&&s.every((e=>e instanceof ht||e.track instanceof ht))),!0))return O.warn(`subscribe failed, tracks is invalid -> roomId: ${a}`),r.error(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};O.info(`subscribe -> roomId: ${a}, tracks: ${s.map(Vt)}`);const c=e.getSubscribedList().map((e=>Object.assign({},e))),d=s.map((e=>e instanceof ht?{track:e}:e));let _=!1;const u=[];return d.forEach((e=>{const t=e.track.getTrackId();u.push(t);const r=c.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:c.push(e),_=!0)})),_||n?(e.polarisReport.sendR2(ur.SUBSCRIBE,lr.BEGIN,u),r.info(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:s.map(Vt),roomId:a},{logSource:i.RTC}),new yr(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:v.SUCCESS})}))}}class Fr extends fr{constructor(e,t){super(),this.tracks=e,this.pubhook=t}get kind(){return ar.Publish}_removePubFailedTracks(e,t){e.forEach((e=>{const r=e instanceof it?e:e.track;O.debug(`remove pub failed track from peerconnection -> trackId: ${r.getTrackId()}`),t.removeLocalTrackById(r.getTrackId())}))}__publish(e,t,r,i,s){return f(this,void 0,void 0,(function*(){const{pcName:o,pc:n,headers:a}=t,c=e.roomId,d=[];r.forEach((e=>{const{track:t}=e instanceof it?{track:e}:e;d.push(t)}));if(n.getLocalTracks().length+((e,t)=>{let r=0;return e.forEach((e=>{const i=e instanceof it?e.getTrackId():e.track.getTrackId();t.getLocalTrack(i)||(e instanceof it?r++:e.pubTiny&&e.track.isVideoTrack()&&(r+=2))})),r})(r,n)>10)return O.error(`publish failed, tracks limit exceeded -> roomId: ${c}`),{code:v.PUBLISH_TRACK_LIMIT_EXCEEDED,tracks:d};O.debug(`publish tracks -> roomId: ${c}, tracks: ${r.map(Vt)}`),r.forEach((e=>{const{track:t,pubTiny:r}=e instanceof it?{pubTiny:!1,track:e}:e;if(n.addLocalTrack(t),t.isVideoTrack()&&r){let e;try{e=t.__innerGetMediaStreamTrack().clone();const i=r.frameRate||Ge.FPS_15,s=r.resolution||Ke.W176_H144,{width:o,height:n}=Dt(s),a=Ut(i);e.applyConstraints({width:o,height:n,frameRate:a})}catch(r){return null==e||e.stop(),void O.warn(`pubTiny failed -> id: ${t.getTrackId()}, msg: ${r.message}`)}n.addLocalTrack(new ot(t.getTag(),t.getUserId(),e,!0))}})),n.clearReTryExchangeTimer();const _=e.useMutilPeerC?[]:e.getSubscribedList(),u=yield Dr(_,!1,n,e);i&&(u.pushOtherRooms=i);const l=yield new Pr(a,u).execute(e,s);if(l.code!==v.SUCCESS)return O.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!==v.SUCCESS)return O.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!==v.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 s="";const o=[],a=t.getResourcesByUserId(r),c=[...a];let d=[];e.forEach((e=>{if(e.code!==v.SUCCESS){const{tracks:t}=e;return void o.push({code:e.code,tracks:t})}const{publishList:r,urls:i,mcuPublishList:n}=e.data;s=null==i?void 0:i.liveUrl;r.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:t.getTrackState(ft(e))},e))).forEach((e=>{const{isInclude:t,index:r}=((e,t)=>{let r=!1,i=0;for(let s=0;s<t.length;s++){const o=t[s];if(`${e.msid}_${e.mediaType}`==`${o.msid}_${o.mediaType}`){r=!0,i=s;break}}return{isInclude:r,index:i}})(e,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:_}=At(a,c),u=yield t.context.setRTCTotalRes(i,mt(Ft.PUBLISH,_),Ct(c),Ft.TOTAL_CONTENT_RESOURCE,Ct(d));if(u!==n.SUCCESS)return O.error(`send publish streams notification failed: ${u}`),{code:v.SIGNAL_ERROR};t.setResourcesByUserId(r,c);const l=_.map((e=>ft(e)));t.polarisReport&&t.polarisReport.sendR2(ur.PUBLISH,lr.BEGIN,l),_.forEach((e=>{const r=t.useMutilPeerC?`${i}_${e.msid.split("_")[1]}`:`${i}_pub`,{pc:s}=t.peerMgr.getPCItemByPCName(r);s.getLocalTrack(`${e.msid}_${e.mediaType}`).__innerSetPublished(!0)})),O.debug(`publish success: ${l.join(",")}`);const h={code:v.SUCCESS};return s&&(h.liveUrl=s),o.length&&(h.failedTracks=o,h.code=v.SOME_TRACKS_PUBLISH_FAILED),h}))}execute(e,t){return f(this,void 0,void 0,(function*(){const s=this.tracks,n=e.roomId;if(r.info(L.L_ABSTRACT_ROOM_PUBLISH_T,{trackIds:s.map(Vt)},{logSource:i.RTC}),!o("tracks",s,(()=>p(s)&&s.length>0&&s.every((e=>e instanceof it||e.track instanceof it))),!0))return O.warn(`publish failed, tracks is invalid -> roomId: ${n}`),r.error(L.L_ABSTRACT_ROOM_PUBLISH_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};const a=[],{plist:c,pushOtherRooms:d}=this.pubhook(s);for(let r=0;r<c.length;r++){const i=c[r];a.push(this.__publish(e,i,i.tracks,d,t))}const _=yield Promise.all(a),u=yield this._mergePublishRes(_,e);return r.info(L.L_ABSTRACT_ROOM_PUBLISH_R,{status:A.SUCCESSED,roomId:n,trackIds:s.map(Vt)},{logSource:i.RTC}),u}))}}class $r extends fr{constructor(e,t){super(),this.tracks=e,this.unpubhook=t}get kind(){return ar.UnPublish}__unpublish(e,t,r,i){return f(this,void 0,void 0,(function*(){const{pcName:s,pc:o}=r;e.roomId;const n=i.map((e=>e.getTrackId()));if(0===n.map(e.getPublishedResourceByTrackId.bind(e)).filter((e=>!!e)).length)return{code:v.SUCCESS,tracks:i};n.forEach((e=>o.removeLocalTrackById(e))),e.polarisReport.sendR2(ur.PUBLISH,lr.END,n),o.clearReTryExchangeTimer();const a=e.useMutilPeerC?[]:e.getSubscribedList(),c=yield Dr(a,!1,o,e),{pushOtherRooms:d,headers:_}=this.unpubhook(i,s);d&&(c.pushOtherRooms=d);const u=yield new Pr(_,c).execute(e,t);return u.code!==v.SUCCESS?(O.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,s=[],o=[],a=[],c=[];let d=[];for(let r=0;r<t.length;r++){const i=t[r];if(i.code!==v.SUCCESS){const{tracks:e}=i;o.push({code:i.code,tracks:e});continue}const{resultCode:n,message:_,mcuPublishList:u}=i.data;n!==v.SUCCESS&&O.error(`unpublish streams failed -> code: ${n}, msg: ${_}`);const l=i.tracks.map((e=>e.getTrackId()));c.push(...l);const h=l.map(e.getPublishedResourceByTrackId.bind(e)).filter((e=>!!e));a.push(...h),s.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=>!a.includes(e))),u=yield e.context.setRTCTotalRes(i,mt(Ft.UNPUBLISH,a),Ct(_),Ft.TOTAL_CONTENT_RESOURCE,Ct(d));if(u!==n.SUCCESS)return O.error("send unpublish notification failed:",u),{code:v.SIGNAL_ERROR};O.debug(`unpublish success -> tracks: ${c.join(",")}`),s.forEach((t=>f(this,void 0,void 0,(function*(){const{sdp:r}=t.data,{tracks:i}=t,s=e.peerMgr.getPCByTrackId(i[0].getTrackId());yield s.setRemoteAnswer(r.sdp)})))),e.setResourcesByUserId(r,_);const l={code:v.SUCCESS};return o.length&&(l.failedTracks=o,l.code=v.SOME_TRACKS_PUBLISH_FAILED),l}))}execute(e,t){return f(this,void 0,void 0,(function*(){const{crtUserId:s,roomId:n}=e,a=this.tracks;r.info(L.L_ABSTRACT_ROOM_UNPUBLISH_T,{trackIds:a.map(Vt)},{logSource:i.RTC});if(!o("tracks",a,(()=>a.every((e=>e.getUserId()===s&&e instanceof it))),!0))return O.warn(`unpublish failed, tracks is invalid -> roomId: ${n}, tracks: ${a.map(Vt)}`),r.error(L.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:v.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),u=yield this._mergeUnpublishRes(e,_);return r.info(L.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:A.SUCCESSED,roomId:n,trackIds:a.map(Vt)},{logSource:i.RTC}),u}))}}class Gr extends fr{constructor(e){super(),this.localTrack=e}execute(e,t){return f(this,void 0,void 0,(function*(){const{localTrack:t}=this,r=t.getTrackId(),{crtUserId:i,roomId:s}=e,o=[{resourceId:r,enabled:!t.isLocalMuted()}],a=e.getResourcesByUserId(i),c=[];for(let e=0;e<a.length;e+=1){const t=a[e],r=ft(t),i=o.findIndex((e=>e.resourceId===r));if(i>=0){const{enabled:e}=o[i];t.state=e?1:0,c.push(t);break}}const d=yield e.context.setRTCTotalRes(s,mt(Ft.MODIFY,c),Ct(a),Ft.TOTAL_CONTENT_RESOURCE);d!==n.SUCCESS&&O.error("notice `track.enabled` change failed -> code: "+d)}))}}class Kr extends fr{constructor(e,t,r){super(),this.pcName=e,this.isPub=t,this.retryHook=r}get priority(){return dr.HIGH}execute(e,t){return f(this,void 0,void 0,(function*(){const{pcName:r,isPub:i}=this,{useMutilPeerC:s}=e,{pc:o}=e.peerMgr.getPCItemByPCName(r),n=i&&s?[]:e.getSubscribedList(),a=yield Dr(n,!0,o,e),{pushOtherRooms:c,headers:d}=this.retryHook(r);c&&(a.pushOtherRooms=c);const _=yield new Pr(d,a).execute(e,t);if(_.code!==v.SUCCESS)return void O.error(`reTryExchange failed: ${_.code}, pcName: ${r}`);const{sdp:u,resultCode:l}=_.data;l===v.SUCCESS?(o.clearReTryExchangeTimer(),yield o.setRemoteAnswer(u.sdp)):O.error(`reTryExchange failed: ${l}, pcName: ${r}`)}))}}class Hr extends fr{constructor(e,t,r){super(),this.subhook=e,this.callbacks=t,this.livingType=r}get priority(){return dr.HIGH}execute(e,t){return f(this,void 0,void 0,(function*(){const{livingType:s}=this,{roomId:o,crtUserId:a,roomMode:c}=e;r.info(L.L_ABSTRACT_ROOM_RECONNECTED_T,{livingType:s},{logSource:i.RTC});if(e.peerMgr.getPCList().some((e=>"closed"===e.getRTCPeerConn().connectionState)))return O.warn("RTCPeerConnection closed. Please rejoin room to restore services."),r.error(L.L_ABSTRACT_ROOM_RECONNECTED_R,{status:A.FAILED,code:"",msg:"RTCPeerConnection disconnected"},{logSource:i.RTC}),void this.callbacks.onPeerClosed();const{code:_,data:u}=yield e.context.joinRTCRoom(o,c,s);if(_!==n.SUCCESS)return O.error(`RTC __onReconnected getRTCRoomInfo failed: ${_}`),void r.error(L.L_ABSTRACT_ROOM_RECONNECTED_R,{status:A.FAILED,code:_,msg:""},{logSource:i.RTC});O.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(u)}`);const l=[],h={},R={},p={},m=Bt(u,o),C=Object.keys(m),T=e.getAllUserIds();for(let t=C.length-1;t>=0;t-=1){const r=C[t],i=T.indexOf(r);if(-1===i){l.push(r),h[r]=Lt(m[r]);continue}const s=e.getResourcesByUserId(r),o=m[r],{publishedList:n,modifiedList:a,unpublishedList:c}=At(s,o,!0);h[r]=Lt(n),R[r]=Lt(c),p[r]=Lt(a),T.splice(i,1)}T.length&&T.forEach((t=>{e.removeResourcesByUserId(t)})),e.assignRoomData(m),T.length&&this.callbacks.onUserLeave(T),l.length&&this.callbacks.onUserJoin(l);for(const r in R){if(r===a)continue;const i=R[r];if(i.length){const r=i.map((t=>e.getRemoteTrack(ft(t))));yield new wr(this.subhook,r,this.callbacks.onTrackUnpublish).execute(e,t)}}return Object.keys(h).forEach((t=>{const r=h[t];if(0===r.length)return;const i=r.map((t=>{const r=ft(t),{userId:i,tag:s,mediaType:o}=Ot(r),n=o===He.AUDIO_ONLY?new Rt(s,i):new pt(s,i);return e.addRemoteTrack(n),n.__innerSetRemoteMuted(0===t.state),n}));this.callbacks.onTrackPublish(i)})),Object.keys(p).forEach((t=>{p[t].forEach((t=>{const r=ft(t),i=e.getRemoteTrack(r);i.__innerSetRemoteMuted(0===t.state),i.isAudioTrack()?this.callbacks.onAudioMuteChange(i):this.callbacks.onVideoMuteChange(i)}))})),e.roomMode===d.LIVE&&this.executeInLivingRoom(e,u),r.info(L.L_ABSTRACT_ROOM_RECONNECTED_R,{status:A.SUCCESSED,roomData:u},{logSource:i.RTC}),{data:u}}))}executeInLivingRoom(e,t){var s,o;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===(s=t.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===s?void 0:s.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===(o=e.getCDNUris())||void 0===o?void 0:o.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 jr extends Or{constructor(e,t,r,i=cr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var r,i,s;return f(this,void 0,void 0,(function*(){const{tracks:o}=this,n=e.roomId;if(O.info(`unsubscribe -> roomId: ${n}, tracks: ${o.map(Vt)}`),this.state===cr.NORMAL){const i=e.getSubscribedList().slice(),{code:s,failedList:n}=yield new yr(o,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,i);return null===(r=this.callbacks)||void 0===r||r.onTaskCompleted({code:s,subscribe:c,unsubscribe:d,failedList:n}),{code:s,failedList:n}}if(this.state===cr.TAIL){const{code:r}=yield new jr(this.tracks,this.subhook,this.callbacks,cr.MIDDLE).execute(e,t);if(r===v.SUCCESS){const r=e.getCollectSubscribeList().slice(0).map((e=>e.track)),o=e.getSubscribedList().slice(),{code:n,failedList:a}=yield new yr(r,this.subhook).execute(e,t);if(n!==v.SUCCESS)return null===(i=this.callbacks)||void 0===i||i.onTaskCompleted({code:n,subscribe:[],unsubscribe:[],failedList:a}),{code:n,failedList:a};const c=e.getSubscribedList().slice(0),{subscribe:d,unsubscribe:_}=this.pickoutSubscribed(c,o);return null===(s=this.callbacks)||void 0===s||s.onTaskCompleted({code:n,subscribe:d,unsubscribe:_,failedList:a}),{code:n,failedList:a}}return{code:r}}return Or.AsyncUpdateSubscribeTasks.splice(Or.AsyncUpdateSubscribeTasks.length,0,...this.tracks),new Promise((t=>{const r=o.map((e=>e instanceof ht?{track:e}:e));e.resetCollectSubscribeList(r),t({code:v.SUCCESS})}))}))}}class Jr extends Or{constructor(e,t,r,i=cr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var s;return f(this,void 0,void 0,(function*(){const{tracks:n}=this,a=e.roomId;if(this.state===cr.NORMAL){const r=e.getSubscribedList().slice(),{code:i,failedList:o}=yield new Vr(n,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,r);return null===(s=this.callbacks)||void 0===s||s.onTaskCompleted({code:i,subscribe:c,unsubscribe:d,failedList:o}),{code:i,failedList:o}}if(r.info(L.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:n.map(Vt)},{logSource:i.RTC}),!o("tracks",n,(()=>p(n)&&n.length>0&&n.every((e=>e instanceof ht||e.track instanceof ht))),!0))return O.warn(`subscribe failed, tracks is invalid -> roomId: ${a}`),r.error(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};O.info(`subscribe -> roomId: ${a}, tracks: ${n.map(Vt)}`);const c=this.getSubscribedList(e).map((e=>Object.assign({},e))),d=n.map((e=>e instanceof ht?{track:e}:e)),_=[];if(d.forEach((e=>{const t=e.track.getTrackId();_.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(ur.SUBSCRIBE,lr.BEGIN,_),r.info(L.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:n.map(Vt),roomId:a},{logSource:i.RTC}),this.state===cr.TAIL){const{code:r}=yield new Jr(this.tracks,this.subhook,this.callbacks,cr.MIDDLE).execute(e,t);if(r===v.SUCCESS){const r=e.getCollectSubscribeList().slice(0);return new jr(r,this.subhook,this.callbacks).execute(e,t)}return{code:r}}return Or.AsyncSubscribeTasks.splice(Or.AsyncSubscribeTasks.length,0,...this.tracks),new Promise((t=>{e.resetCollectSubscribeList(c),t({code:v.SUCCESS})}))}))}getSubscribedList(e){return this.state===cr.MIDDLE?e.getCollectSubscribeList():e.getSubscribedList()}}class Wr extends Or{constructor(e,t,r,i=cr.NORMAL){super(i),this.tracks=e,this.subhook=t,this.callbacks=r}execute(e,t){var s;return f(this,void 0,void 0,(function*(){const n=this.tracks,a=e.roomId;if(this.state===cr.NORMAL){const r=e.getSubscribedList().slice(),{code:i,failedList:o}=yield new Mr(n,this.subhook).execute(e,t),a=e.getSubscribedList().slice(),{subscribe:c,unsubscribe:d}=this.pickoutSubscribed(a,r);return null===(s=this.callbacks)||void 0===s||s.onTaskCompleted({code:i,subscribe:c,unsubscribe:d,failedList:o}),{code:i,failedList:o}}if(r.info(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:n.map(Vt)},{logSource:i.RTC}),!o("tracks",n,(()=>p(n)&&n.length>0&&n.every((e=>e instanceof ht))),!0))return O.warn(`unsubscribe failed, tracks is invalid -> roomId: ${a}`),r.warn(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};O.info(`unsubscribe -> roomId: ${a}, tracks: ${n.map(Vt)}`);const c=this.getSubscribedList(e).map((e=>Object.assign({},e))).filter((e=>!n.includes(e.track)));if(e.polarisReport.sendR2(ur.SUBSCRIBE,lr.END,n.map((e=>e.getTrackId()))),r.info(L.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:n.map(Vt),roomId:a},{logSource:i.RTC}),this.state===cr.TAIL){const{code:r}=yield new Wr(this.tracks,this.subhook,this.callbacks,cr.MIDDLE).execute(e,t);if(r===v.SUCCESS){const r=e.getCollectSubscribeList().slice(0).map((e=>e.track));return new jr(r,this.subhook,this.callbacks).execute(e,t)}return{code:r}}return Or.AsyncUnsubscribeTasks.splice(Or.AsyncUnsubscribeTasks.length,0,...this.tracks),new Promise((t=>{e.resetCollectSubscribeList(c),t({code:v.SUCCESS})}))}))}getSubscribedList(e){return this.state===cr.MIDDLE?e.getCollectSubscribeList():e.getSubscribedList()}}const Yr="evt-leave";class qr extends t{constructor(e,t,r,i,s,o,n,a,c,d=Kt()){super(),this._context=e,this._runtime=t,this._roomId=r,this._service=s,this._initOptions=o,this._useMutilPeerC=c,this._clientSessionId=d,this._appListener=null,this._reportListener=null,this._onRecvPKMsg=null,this._polarisReport=new Ir(this._context,this._runtime,this._roomId,this),this._peerCManager=new gr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._invoker=new Lr(this._context,this._service,this._peerCManager,r,this._context.getCurrentId(),i,this._polarisReport,n,a),this._store=this._invoker.store}__innerInit(e,t,r,i,s){return f(this,void 0,void 0,(function*(){const{code:o,data:n}=yield this._invoker.push(new Nr(this._roomId,e,t,r,i,s));return o!==v.SUCCESS?{code:o}:(this._initWithRoomData(n.offlineKickTime),{code:o,data:n})}))}_initWithRoomData(e){var t;this._pinger=new Gt(this._store.roomId,this._store.roomMode,this._context,this._initOptions.pingGap,1e3*e),this._pinger.onFailed=this._kickoff.bind(this),this._pinger.onPingResult=this._handlePingResult.bind(this),this._pinger.start(),null===(t=this._polarisReport)||void 0===t||t.sendR1()}_handlePingResult(e){this._callAppListener("onPing",e)}setBitrate(e,t,r){if(this._useMutilPeerC)return void O.error("`RCAbstractRoom.setBitrate` is disabled, use `RCLocalTrack.setBitrate` instead.");O.warn("`RCAbstractRoom.setBitrate` will be deprecated, use `RCLocalTrack.setBitrate` instead."),m("max",e,(e=>s(e)&&e>Math.max(t||1,200)),!0),m("min",t,(t=>s(t)&&t>=1&&(!s(e)||t<e)),!0),m("start",r,(r=>s(r)&&r>t&&r<=e));this._peerCManager.getPCList().forEach((i=>{i.setBitrate(e,t,r)}))}_onTrackReady(e){const t=e.streams[0].id,r=e.receiver.track,i=[t,"audio"===r.kind?He.AUDIO_ONLY:He.VIDEO_ONLY].join("_"),s=this._store.getRemoteTrack(i);s?(s.__innerSetMediaStreamTrack(r),this._callAppListener("onTrackReady",s)):O.warn(`cannot found remote track ${r.id}`)}_callAppListener(e,...t){var s;"onPing"!==e&&r.info(L.L_ABSTRACT_ROOM_CALL_APP_LISTENER_O,{status:A.SUCCESSED,eventType:e,attrs:t},{logSource:i.RTC}),"onPing"!==e&&O.info(`${e} callback ->`,...t);const o=null===(s=this._appListener)||void 0===s?void 0:s[e];if(o)try{o(...t)}catch(e){O.error(e)}}_onTrackUnpublish(e){this._callAppListener("onTrackUnpublish",e)}__parseInnerMessage(e){const{targetId:t,conversationType:r}=e;if(r!==C.RTC_ROOM)return!1;if(t!==this._roomId)return!0;O.info(`recv inner msg -> message: ${JSON.stringify(e)} | roomid: ${this._roomId}`);const i=e.content;switch(e.messageType){case Ft.KICK:this._kickoff(!0,i);break;case Ft.STATE:this._stateHandle(i);break;case Ft.MODIFY:case Ft.PUBLISH:case Ft.UNPUBLISH:case Ft.TOTAL_CONTENT_RESOURCE:this._resourceHandle(i,e.messageType,e.senderUserId);break;case Ft.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",e.messageType,e.content);break;case Ft.USER_NOTIFY:O.warn(`TODO: ${Ft.USER_NOTIFY}`);break;case Ft.PK_INVITE:case Ft.PK_CANCEL_INVITE:case Ft.PK_INVITE_TIMEOUT:case Ft.PK_INVITE_ANSWER:case Ft.PK_END:this._onRecvPKMsg&&this._onRecvPKMsg(e);break;case Ft.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;O.warn(`onKickOff -> byServer: ${e}`),this.emit(Yr),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(Yr),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,t,r){return f(this,void 0,void 0,(function*(){const{uris:i,ignore:s}=e;!s&&i&&this._invoker.push(new Br(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:s,downgrade:o}=yield this._invoker.push(new xr(e,this._subhook.bind(this)));if(null===(t=this._appListener)||void 0===t?void 0:t.onSwitchRole)return s.length&&s.forEach((e=>this._callAppListener("onSwitchRole",e,nr.ANCHOR))),o.length&&o.forEach((e=>this._callAppListener("onSwitchRole",e,nr.AUDIENCE))),i.length&&this._callAppListener("onUserJoin",i),void(r.length&&this._callAppListener("onUserLeave",r));const n=[...i,...s],a=[...r,...o];n.length&&this._callAppListener("onUserJoin",n),a.length&&this._callAppListener("onUserLeave",a)}))}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}__getPC(){return this._store.peerMgr.getPCList()}getRemoteUserIds(){return this._store.getRemoteUserIds()}getRemoteTracks(){const e=[];return this.getRemoteUserIds().forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),e}getRemoteTracksByUserId(e){return this._store.getRemoteTracksByUserId(e)}getSessionId(){return this._store.getSessionId()}sendMessage(e,t){return 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:s}=yield this._context.sendMessage(C.RTC_ROOM,this._roomId,{messageType:e,content:t,isStatusMessage:!0});return s!==n.SUCCESS?(O.error(`send message failed -> code: ${s}`),r.error(L.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:A.FAILED,code:s,msg:""},{logSource:i.RTC}),{code:v.SIGNAL_ERROR}):(r.info(L.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:A.SUCCESSED,name:e,content:t},{logSource:i.RTC}),{code:v.SUCCESS})}))}setRoomAttribute(e,t,s,o=!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:s,isInner:o},{logSource:i.RTC});const a=yield this._context.setRTCData(this._roomId,e,t,o,R.ROOM,s);return a!==n.SUCCESS?(O.error(`SetRoomAttributeValue Failed: ${a}`),r.error(L.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:A.FAILED,code:a,msg:""},{logSource:i.RTC}),{code:v.SIGNAL_ERROR}):(r.info(L.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:A.SUCCESSED,roomId:this._roomId,key:e,value:t,message:s,isInner:o},{logSource:i.RTC}),{code:v.SUCCESS})}))}deleteRoomAttributes(e,t,s=!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:s},{logSource:i.RTC});const o=yield this._context.removeRTCData(this._roomId,e,s,R.ROOM,t);return o!==n.SUCCESS?(O.error(`DeleteRoomAttribute Failed: ${o}`),r.error(L.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:A.FAILED,code:o,msg:""},{logSource:i.RTC}),{code:v.SIGNAL_ERROR}):(r.info(L.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:A.SUCCESSED,roomId:this._roomId,keys:e,message:t,isInner:s},{logSource:i.RTC}),{code:v.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,R.ROOM);return r!==n.SUCCESS?(O.error(`GetRoomAttributes Failed: ${r}`),{code:v.SIGNAL_ERROR}):{code:v.SUCCESS,data:i}}))}_setUserAttributeValue(e,t,r){return this._context.setRTCData(this._roomId,e,t,!1,R.PERSON,r)}_deleteUserAttributes(e,t){return this._context.removeRTCData(this._roomId,e,!1,R.PERSON,t)}_getUserAttributes(e){return this._context.getRTCData(this._roomId,e,!1,R.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(it.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(it.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)})),this._peerCManager.clear(),this._peerCManager=null}_onLocalTrackDestroied(e){e instanceof ot&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(e){return f(this,void 0,void 0,(function*(){this._invoker.push(new Gr(e))}))}publish(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new Fr(e,this._pubhook.bind(this)))}))}_getPushOtherRoomsParams(){return[]}_reTryExchange(e,t){return f(this,void 0,void 0,(function*(){this._invoker.push(new Kr(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 $r(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=>ft(t)===e)))}_subhook(e){const{pc:t,pcName:r}=this._peerCManager.createPeerCList(e)[0];return t.on(Er.__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(it.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.on(it.__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 Vr(e,this._subhook.bind(this)))}))}addSubscribeTask(e){this._invoker.push(new Jr(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 Mr(e,this._subhook.bind(this)))}))}addUnsubscribeTask(e){this._invoker.push(new Wr(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 yr(e,this._subhook.bind(this)))}))}addUpdateSubscribeListTask(e){this._invoker.push(new jr(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 s;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===(s=this._audioLevelReport)||void 0===s||s.clearAudioLevelReportTimer(),this._audioLevelReport=new Sr(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}__onReconnected(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new Hr(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 zr extends fr{constructor(e,t){super(),this.data=e,this.cdnValues=t}execute(e,t){var r,i,s,o;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!==v.SUCCESS)return O.error(`set MCU config failed: ${n}`),{code:n};O.info("set MCU config success"),a.pull_url&&e.setCDNUris(JSON.parse(a.pull_url));const c=this.cdnValues;return n===v.SUCCESS&&((null===(i=null===(r=c.output)||void 0===r?void 0:r.video.normal)||void 0===i?void 0:i.width)||(null===(o=null===(s=c.output)||void 0===s?void 0:s.video.normal)||void 0===o?void 0:o.fps))&&Ur(e),{code:n,res:a}}))}}var Qr,Zr,Xr,ei;!function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(Qr||(Qr={})),function(e){e[e.CUSTOMIZE=1]="CUSTOMIZE",e[e.SUSPENSION=2]="SUSPENSION",e[e.ADAPTATION=3]="ADAPTATION"}(Zr||(Zr={})),function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(Xr||(Xr={})),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"}(ei||(ei={}));const ti=()=>({version:2,mode:Zr.SUSPENSION});class ri{constructor(e,t){this._invoker=e,this._isValidTrackId=t,this._values=ti()}setHostVideoTrack(e){if(O.info(`setHostVideoTrack -> videoTrackId: ${e}`),!this._isValidTrackId(e))return O.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:s,userId:o}=Ot(e);return t!==He.VIDEO_ONLY?(O.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=vt(o,s),r.info(L.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:A.SUCCESSED,videoTrackId:e},{logSource:i.RTC}),this)}setMixLayoutMode(e){O.info(`setMixLayoutMode -> mode: ${e}`);return[Zr.CUSTOMIZE,Zr.SUSPENSION,Zr.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):(O.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 s=i.video;if("normal"!==r&&"tiny"!==r)if("backgroundColor"!==r)if("exparams"!==r){if("backgroundPicture"===r){const e=s.backgroundPicture||(s.backgroundPicture={fillMode:Qr.CROP,picture:[]});Object.assign(e,t)}}else s.exparams={renderMode:t};else s.backgroundColor=t;else{const e=s[r]||(s[r]={});Object.assign(e,t)}}setOutputVideoResolution(e){if(O.info(`setOutputVideoResolution -> resolution: ${e}`),!kt(e))return O.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:s}=Dt(e);return this._addOutputValue("video",{width:t,height:s},"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(O.info(`setOutputVideoFPS -> fps: ${e}`),!bt(e))return O.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 O.info(`setOutputVideoBitrate -> bitrate: ${e}`),!s(e)||e<=0?(O.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(O.info(`setOutputTinyVideoResolution -> resolution: ${e}`),!kt(e))return O.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:s}=Dt(e);return this._addOutputValue("video",{width:t,height:s},"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(O.info(`setOutputTinyVideoFPS -> fps: ${e}`),!bt(e))return O.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 O.info(`setOutputTinyVideoBitrate -> bitrate: ${e}`),!s(e)||e<=0?(O.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 O.info(`setOutputVideoRenderMode -> renderMode: ${e}`),[Xr.CROP,Xr.WHOLE].includes(e)?this._addOutputValue("video",e,"exparams"):(O.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 O.info(`setOutputAudioBitrate -> bitrate: ${e}`),s(e)&&e>0?this._addOutputValue("audio",e):(O.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 O.info(`setOutputBackgroundColor -> color: ${e}`),/^0x[a-fA-F0-9]{6}$/.test(e)?this._addOutputValue("video",e,"backgroundColor"):(O.error(`setOutputBackgroundColor failed -> color is invalid: ${e}`),r.error(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,o,n,a){var c,d,_;if(O.info(`addOutputBackgroundPicture -> uri: ${e}, x: ${t}, y: ${o}, w: ${n}, h: ${a}`),!T(e))return O.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,o,n,a].some((e=>!s(e)||e<0||e>1)))return O.error(`addOutputBackgroundPicture failed -> some attrs of (x, y, w, h) is invalid: ${t}, ${o}, ${n}, ${a}`),r.error(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:A.FAILED,code:"",msg:`params error -> x: ${t}, y: ${o}, w: ${n}, h: ${a}`},{logSource:i.RTC}),this;const u=(null===(_=null===(d=null===(c=this._values.output)||void 0===c?void 0:c.video)||void 0===d?void 0:d.backgroundPicture)||void 0===_?void 0:_.picture)||[];return u.push({uri:e,w:n,h:a,x:t,y:o}),this._addOutputValue("video",{picture:u},"backgroundPicture"),r.info(L.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:A.SUCCESSED,uri:e,x:t,y:o,w:n,h:a},{logSource:i.RTC}),this}removeOutputBackgroundPicture(e){var t,s,o;if(O.info(`removeOutputBackgroundPicture -> uri: ${e}`),!T(e))return O.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===(o=null===(s=null===(t=this._values.output)||void 0===t?void 0:t.video)||void 0===s?void 0:s.backgroundPicture)||void 0===o?void 0:o.picture;return n&&(n=n.filter((t=>t.uri!==e)),this._addOutputValue("video",{pictures:n},"backgroundPicture")),r.info(L.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:A.SUCCESSED,uri:e},{logSource:i.RTC}),this}clearOutputBackgroundPicture(){return O.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 O.info(`setOutputBackgroundPictureFillMode -> fillMode: ${e}`),[Qr.CROP,Qr.WHOLE].includes(e)?this._addOutputValue("video",{fillMode:e},"backgroundPicture"):(O.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,s;O.info(`addPublishStreamUrls -> urls: ${e.join(",")}`);const o=/^rtmp:\/\/.+/;if(!p(e)||0===e.length||e.some((e=>!o.test(e))))return O.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===(s=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===s?void 0:s.concat())||[];let a=!1;return e.forEach((e=>{n.some((t=>t.pushurl===e))||(a=!0,n.push({pushurl:e}))})),n.length>5?(O.error("addPublishStreamUrls failed -> publish stream urls no more than 5!"),r.error(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,s;O.info(`removePublishStreamUrls -> urls: ${e.join(",")}`);const o=/^rtmp:\/\/.+/;if(!p(e)||0===e.length||e.some((e=>!o.test(e))))return O.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===(s=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===s?void 0:s.concat())||[];for(let t=n.length-1;t>=0;t-=1){const{pushurl:r}=n[t],i=e.indexOf(r);i>=0&&(e.splice(i,1),n.splice(t,1))}return this._addOutputValue("cdn",n),r.info(L.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:A.SUCCESSED,urls:e},{logSource:i.RTC}),this}clearPublishStreamUrls(){return O.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,o,n,a){if(O.info(`addCustomizeLayoutVideo -> trackId: ${e}, x: ${t}, y: ${o}, width: ${n}, height: ${a}`),!_(e)||!this._isValidTrackId(e))return O.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(!s(t)||!s(o))return O.error(`addCustomizeLayoutVideo failed -> some attrs of (x, y) is invalid: ${t}, ${o}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.FAILED,code:"",msg:`params error -> x: ${t}, y: ${o}`},{logSource:i.RTC}),this;if([n,a].some((e=>!s(e)||e<0)))return O.error(`addCustomizeLayoutVideo failed -> some attrs of (width, height) is invalid: ${n}, ${a}`),r.error(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:u}=Ot(e);if(u!==He.VIDEO_ONLY)return O.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 l=vt(c,d),h=this._values.input||(this._values.input={}),R=h.video||(h.video=[]);return R.some((e=>e.height===a&&e.width===n&&e.stream_id===l&&e.user_id===c&&e.x===t&&e.y===o))?(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):(R.push({user_id:c,stream_id:l,x:t,y:o,width:n,height:a}),r.info(L.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:A.SUCCESSED,trackId:e,x:t,y:o,width:n,height:a},{logSource:i.RTC}),this)}removeCustomizeLayoutVideo(e){if(O.info(`clearCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return O.error(`clearCustomizeInputAudio failed -> trackId is invalid: ${e}`),r.error(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:s,mediaType:o}=Ot(e);if(o!==He.VIDEO_ONLY)return O.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=vt(t,s),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(){O.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(O.info(`setCustomizeInputAudio -> trackIds: ${e.join(",")}`),e.some((e=>this._isValidTrackId(e))))return O.warn(`setCustomizeInputAudio failed -> trackIds contain invalid items: $${e.join(",")}`),r.error(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:vt(t,r),user_id:t}})),this._values.inputFilterMode=ei.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(O.info(`addCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return O.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={}),s=t.audio||(t.audio=[]),{userId:o,tag:n}=Ot(e),a=vt(o,n);return s.some((e=>e.stream_id===a&&e.user_id===o))?(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):(s.push({user_id:o,stream_id:a}),this._values.inputFilterMode=ei.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(O.info(`removeCustomizeInputAudio -> trackId: ${e}`),!this._isValidTrackId(e))return O.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:s,tag:o}=Ot(e),n=vt(s,o);return t.audio=t.audio.filter((e=>s!==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(){O.info("clearCustomizeInputAudio ->");const e=this._values.input;return(null==e?void 0:e.audio)&&delete e.audio,this._values.inputFilterMode=ei.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,o,n,a,c){if(O.info(`addPictureWaterMark -> trackId: ${e} uri: ${t}, x: ${o}, y: ${n}, w: ${a}, h: ${c}`),!this._isValidTrackId(e))return O.warn(`addPictureWaterMark failed -> trackId is invalid: ${e}`),r.error(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 O.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([o,n,a,c].some((e=>!s(e)||e<0||e>1)))return O.error(`addPictureWaterMark failed -> some attrs of (x, y, w, h) is invalid: ${o}, ${n}, ${a}, ${c}`),r.error(L.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:A.FAILED,code:"",msg:`params error -> x: ${o}, y: ${n}, w: ${a}, h: ${c}`},{logSource:i.RTC}),this;const{userId:d,tag:_}=Ot(e),u=vt(d,_),l=(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen;O.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(l)}`);const h=l.filter((e=>e.streamId===u))[0];return O.info(`addPictureWaterMark target-> : ${h}`),h?h.picture.push({uri:t,w:a,h:c,x:o,y:n}):l.push({streamId:u,picture:[{uri:t,w:a,h:c,x:o,y:n}]}),O.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(l)}`),this._values.waterMark.singleScreen=l,O.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:o,y:n,w:a,h:c},{logSource:i.RTC}),this}clearPictureWaterMark(){O.info("clearOutputBackgroundPicture ->");return(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen=[],r.info(L.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:A.SUCCESSED},{logSource:i.RTC}),this}removePictureWaterMark(e,t){if(!_(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:s,tag:o}=Ot(e),n=vt(s,o);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 O.info("MCUConfigBuilder.reset ->"),this._values=ti(),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:s}=yield this._invoker.push(new zr(t,this._values));return e&&(this._values=ti()),r.info(L.L_MCU_CONFIG_BUILDER_FLUSH_O,{status:A.SUCCESSED},{logSource:i.RTC}),{code:s}}))}__innerGetValues(){return JSON.parse(JSON.stringify(this._values))}}var ii,si,oi;!function(e){e[e.VIDEO=0]="VIDEO",e[e.AUDIO=1]="AUDIO"}(ii||(ii={})),function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(si||(si={}));class ni extends fr{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 s=0;s<r.length;s++){const{pc:o,isPub:n}=r[s],a=n&&e.useMutilPeerC?[]:e.getSubscribedList(),c=yield Dr(a,!1,o,e),{pushOtherRooms:d,headers:_}=this.hooks(i[s]);c.pushOtherRooms=d;const u=yield new Pr(_,c).execute(e,t);if(u.code!==v.SUCCESS)return void O.error(`exchange with pushOtherRoom failed: ${u.code}`);const{sdp:l,resultCode:h}=u.data;if(h!==v.SUCCESS)return void O.error(`exchange with pushOtherRoom failed: ${h}`);o.setRemoteAnswer(l.sdp)}}))}execute(e,t){return f(this,void 0,void 0,(function*(){const{roomId:s}=this;if(r.info(L.L_LIVING_ROOM_JOINED_PK_ROOM_T,{roomId:s,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 o=this.roomPKHandler.getPKInfo(s);if(!o)return O.warn(`exchange to update pushOtherRoom cancel, pkInfo lost -> roomId: ${s}`),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:s,userId:e.crtUserId,PKInfo:o},{logSource:i.RTC})}))}}class ai extends fr{constructor(e,t,r,i,s,o){super(),this.pkHandler=e,this.room=t,this._PKInfo=r,this.hooks=i,this._joinedPKRooms=s,this.isQuitPK=o}get kind(){return ar.LeaveRoom}quitRoomPK(e,t){return f(this,void 0,void 0,(function*(){if(!this._PKInfo[e])return;const{inviterRoomId:r,inviteeRoomId:i,inviterUserId:s,inviteSessionId:o}=this._PKInfo[e],a={inviteeRoomId:i,inviterRoomId:r,userId:t.crtUserId},c={roomId:t.roomId,endRoomId:e,sessionId:o,content:JSON.stringify(a),keys:[`${r}|${s}`]};O.info(`quitRoomPK -> params: ${JSON.stringify(c)}`);const d=yield t.context.endRoomPK(c);return d!==n.SUCCESS?(O.error(`quitRoomPK failed: ${d}`),{code:v.SIGNAL_ERROR}):(O.info("quitRoomPK success"),delete this._PKInfo[e],{code:v.SUCCESS})}))}execute(e,t){return f(this,void 0,void 0,(function*(){const{room:s,isQuitPK:o}=this,n=s.getRoomId();return O.info(`leavePKRoom -> userId: ${e.crtUserId} , roomId: ${n}`),r.info(L.L_LIVING_ROOM_LEAVE_PK_ROOM_T,{roomId:n,userId:e.crtUserId,isQuitPK:o},{logSource:i.RTC}),yield s.__destroy(!0),delete this._joinedPKRooms[n],yield new ni(n,this.hooks,this.pkHandler).execute(e,t),o&&this.quitRoomPK(n,e),r.info(L.L_LIVING_ROOM_LEAVE_PK_ROOM_R,{status:A.SUCCESSED,roomId:n,userId:e.crtUserId,isQuitPK:o},{logSource:i.RTC}),{code:v.SUCCESS}}))}}class ci{constructor(e,t,r,i,s,o,n,a,c,d,_){this._invoker=e,this._PKInfo=t,this._hooks=r,this._context=i,this._runtime=s,this._service=o,this._initOptions=n,this._mainLivingRoom=a,this._registerPKMsgListener=c,this._onJoinedPKRoom=d,this._clientSessionId=_,this._inviteTimeout=30,this._appListener=null,this._joinedPKRooms={},this._registerPKMsgListener(this._onRecvPKMsg.bind(this)),this._mainRoomId=this._mainLivingRoom.getRoomId()}_callAppListener(e,...t){var r;O.info(`${e} callback ->`,...t);const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){O.error(e)}}_onInvite(e){const t=e.inviteInfo||{},{inviterRoomId:r,inviterUserId:i,extra:s}=t,o={inviterRoomId:r,inviterUserId:i,extra:s};this._PKInfo[r]=t,this._callAppListener("onRequestJoinOtherRoom",o)}_onCancelInvite(e){const{inviterRoomId:t,inviterUserId:r,extra:i}=e.inviteInfo||{},s={inviterRoomId:t,inviterUserId:r,extra:i};delete this._PKInfo[t],this._callAppListener("onCancelRequestOtherRoom",s)}_onInviteTimeout(e){}_onInviteAnswer(e){const{answerCode:t,inviteContent:r}=e,{inviteSessionId:i,inviterUserId:s,inviterRoomId:o,inviteeUserId:n,inviterUserAutoMix:a,inviteeUserAutoMix:c,inviteeRoomId:d,extra:_}=r,u={agree:1===t,inviterRoomId:o,inviterUserId:s,inviteeRoomId:d,inviteeUserId:n,extra:_};this._PKInfo[d]=this._PKInfo[d]||{inviteSessionId:i,inviterRoomId:o,inviterUserId:s,inviterUserAutoMix:a,inviteeRoomId:d},this._PKInfo[d].inviteeUserAutoMix=c,this._callAppListener("onResponseJoinOtherRoom",u)}createLeaveOtherRoomCommand(e,t){return new ai(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,s=r===this._mainRoomId?t:r,o={endRoomId:s,endUserId:i},n=this._joinedPKRooms[s];n&&(yield this._invoker.push(this.createLeaveOtherRoomCommand(n))),delete this._PKInfo[s],this._callAppListener("onFinishOtherRoom",o)}))}_onRecvPKMsg(e){const{targetId:t,content:r,messageType:i}=e;switch(i){case Ft.PK_INVITE:this._onInvite(r);break;case Ft.PK_CANCEL_INVITE:this._onCancelInvite(r);break;case Ft.PK_INVITE_TIMEOUT:this._onInviteTimeout(r);break;case Ft.PK_INVITE_ANSWER:this._onInviteAnswer(r);break;case Ft.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,s){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:s},{logSource:i.RTC}),!o("inviteeRoomId",e,_,!0)||!o("inviteeUserId",t,_,!0))return r.error(L.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> inviteeRoomId 或 inviteeUserId"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};O.info(`requestRoomPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; options: ${JSON.stringify(s||{})}`);const a=Kt(),c=!E(null==s?void 0:s.autoMix)||(null==s?void 0:s.autoMix),d={inviteSessionId:a,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:c,inviteeRoomId:e,inviteeUserId:t,inviteeTimeoutTime:this._inviteTimeout,extra:(null==s?void 0:s.extra)||""},u={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteTimeout:this._inviteTimeout,inviteInfo:JSON.stringify(d),inviteSessionId:a};O.info(`requestRoomPK -> params: ${JSON.stringify(u)}`);const l=yield this._context.requestRoomPK(u);return l!==n.SUCCESS?(O.error(`requestRoomPK failed: ${l}`),r.error(L.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:l,msg:""},{logSource:i.RTC}),{code:l}):(O.info("requestRoomPK success"),this._PKInfo[e]={inviteSessionId:a,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:s},{logSource:i.RTC}),{code:v.SUCCESS})}))}cancelRequestJoinOtherRoom(e,t,s){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:s,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),!o("inviteeRoomId",e,_,!0)||!o("inviteeUserId",t,_,!0))return r.error(L.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> inviteeRoomId or inviteeUserId"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(!this._PKInfo[e])return O.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:v.PARAMS_ERROR,msg:`The request to connect with ${t} user in room ${e} is not initiated`},{logSource:i.RTC}),{code:v.PARAMS_ERROR};O.info(`canceRequestJoinPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; extra: ${s}`);const a={inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviteeRoomId:e,inviteeUserId:t,extra:s||""},c={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteSessionId:this._PKInfo[e].inviteSessionId,inviteInfo:JSON.stringify(a)};O.info(`canceRequestJoinPK -> params: ${JSON.stringify(c)}`);const d=yield this._context.cancelRoomPK(c);return d!==n.SUCCESS?(O.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}):(O.info("canceRequestJoinPK success"),r.info(L.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:A.SUCCESSED,inviteeRoomId:e,inviteeUserId:t,extra:s},{logSource:i.RTC}),delete this._PKInfo[e],{code:v.SUCCESS})}))}responseJoinOtherRoom(e,t,s,a){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:s,options:a,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),!o("inviterRoomId",e,_,!0)||!o("inviterUserId",t,_,!0))return r.error(L.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> inviterRoomId or inviterUserId"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(!this._PKInfo[e])return O.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:v.PARAMS_ERROR,msg:`User ${t} in room ${e} did not send a request for connection`},{logSource:i.RTC}),{code:v.PARAMS_ERROR};O.info(`responseRoomPK -> inviterRoomId: ${e}; inviterUserId: ${t}; agree: ${s}; options: ${JSON.stringify(a||{})}`);const{inviteSessionId:c,inviterUserAutoMix:d}=this._PKInfo[e],u=!E(null==a?void 0:a.autoMix)||(null==a?void 0:a.autoMix),l={inviteSessionId:c,inviterRoomId:e,inviterUserId:t,inviterUserAutoMix:d,inviteeRoomId:this._mainRoomId,inviteeUserId:this._context.getCurrentId(),inviteeUserAutoMix:u},h=Object.assign(l,{inviterUserAutoMix:d}),R=s?Object.assign(l,{MultiRoomKey:`${e}|${this._mainRoomId}`,MultiRoomValue:JSON.stringify(h)}):l;!I(null==a?void 0:a.extra)&&Object.assign(R,{extra:a.extra});const p={agree:s,roomId:this._mainRoomId,inviteSessionId:c,inviteRoomId:e,inviteUserId:t,content:JSON.stringify(R),key:`${e}|${this._mainRoomId}`,value:JSON.stringify(l)};O.info(`responseRoomPK -> params: ${JSON.stringify(p)}`);const m=yield this._context.responseRoomPK(p);return m!==n.SUCCESS?(O.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}):(O.info("responseRoomPK success"),r.info(L.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:A.SUCCESSED,inviterRoomId:e,inviterUserId:t,agree:s,options:a,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:i.RTC}),this._PKInfo[e].inviteeUserAutoMix=u,{code:v.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}),!o("roomId",e,_,!0))return r.error(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(this._context.getConnectionStatus()!==c.CONNECTED)return r.error(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:v.SIGNAL_DISCONNECTED,msg:"IM disconnected"},{logSource:i.RTC}),{code:v.SIGNAL_DISCONNECTED};if(O.info(`JoinPKRoom, roomId: ${e}`),this._joinedPKRooms[e])return r.warn(L.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:A.FAILED,code:v.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:v.REPERT_JOIN_ROOM};const t=ii.VIDEO,s={extra:`{"roomId": "${this._mainRoomId}"}`},n=new ui(this._context,this._runtime,e,this._service,this._initOptions,t,!1,!1,!1,this._clientSessionId),{code:a,data:u}=yield n.__innerInit(d.LIVE,void 0,t,s);return a!==v.SUCCESS?(O.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}):(O.info(`JoinPKRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(u)}`),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:v.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"}(oi||(oi={}));class di extends fr{constructor(e,t){super(),this.cdnValues=e,this.enable=t}execute(e,t){return f(this,void 0,void 0,(function*(){const{enable:s}=this;if(r.info(L.L_LIVING_ROOM_ENABLE_INNER_CDN_T,{roomId:e.roomId,enable:s},{logSource:i.RTC}),!e.isMainRoom)return O.error("the `enableInnerCDN` is disabled in PK room"),r.error(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.FAILED,code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!E(s))return O.error("`enable` is invalid"),r.error(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> enable"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};e.setCDNEnabel(s);const o={version:2,output:{inCDNModel:s?oi.OPEN:oi.STOP}},{code:n}=yield new zr(o,this.cdnValues).execute(e,t);if(n!==v.SUCCESS)return O.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:v.SIGNAL_ERROR};const a=e.getCDNUris();if(a&&a.broadcast!==hr.SPREAD)return O.info("enableInnerCDN succeed"),r.info(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.SUCCESSED,enable:s},{logSource:i.RTC}),{code:v.SUCCESS};const{code:c}=yield Ur(e);return c===v.SUCCESS?(O.info("enableInnerCDN succeed"),r.info(L.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:A.SUCCESSED,enable:s},{logSource:i.RTC}),{code:v.SUCCESS}):(O.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})}))}}class _i extends fr{constructor(e){super(),this.livingType=e}execute(e,t){var r;return f(this,void 0,void 0,(function*(){const{code:i,data:s}=yield e.context.rtcIdentityChange(e.roomId,S.ViewerToAnchor,this.livingType);if(i!==n.SUCCESS||!s)return{code:i};e.initWithRoomData(s);e.getResourcesByUserId(e.crtUserId).length>0&&t.push(new Ar);const o=null===(r=s.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===r?void 0:r.value;return o&&e.setCDNUris(JSON.parse(o)[0]),{code:i,data:s}}))}}class ui extends qr{constructor(e,t,r,i,s,o,n,a,c,_){super(e,t,r,d.LIVE,i,s,n,a,c,_),this._livingType=o,this._mcuConfigBuilder=new ri(this._invoker,this._isValidResourceId.bind(this))}_initAfterCatchRoomData(e){if(this._store.isUpgrade&&this._afterChangedRole(e),this._store.isMainRoom){const t=((e,t)=>{const r={};return t.forEach((t=>{const i=JSON.parse(t.value),{inviterRoomId:s,inviteeRoomId:o}=i;r[e===s?o:s]=JSON.parse(t.value)})),r})(this._roomId,e.roomInfo);this._roomPKHandler=new ci(this._invoker,t,(e=>({headers:this._getRTCReqestHeaders(e),pushOtherRooms:this._getPushOtherRoomsParams()})),this._context,this._runtime,this._service,this._initOptions,this,super._registerPKMsgListener.bind(this),this._onJoinedPKRoom.bind(this),this._clientSessionId)}}__innerInit(e,t,s,n,a){const c=Object.create(null,{__innerInit:{get:()=>super.__innerInit}});return f(this,void 0,void 0,(function*(){if(!o("livingType",s,(e=>e===ii.AUDIO||e===ii.VIDEO)))return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> livingType"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};const{code:d,data:_}=yield c.__innerInit.call(this,e,t,s,n,a);return d===v.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 _i(this._livingType));return e===n.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):(O.warn("the `publish` is disabled in PK room "),r.error(L.L_ABSTRACT_ROOM_PUBLISH_R,{status:A.FAILED,code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:v.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):(O.warn("the `unpublish` is disabled in PK room "),r.error(L.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:A.FAILED,code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:v.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=>ft(t)===e)));let s=!1;const{code:o,roomPKHandler:n}=this.getRoomPKHandler();if(o!==v.SUCCESS||!n)return i;const a=n.getJoinedPKRooms(),c=[];return Object.values(a).map((e=>{c.push(...e.getRemoteTracks())})),s=c.some((t=>e===t.getTrackId())),i||s}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._store.isMainRoom?this._mcuConfigBuilder:(O.error("the `getMCUConfigBuilder` is disabled in PK room"),{code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}enableInnerCDN(e){return f(this,void 0,void 0,(function*(){return this._invoker.push(new di(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=Bt(e,this._roomId),r=this._context.getCurrentId(),i=Object.keys(t);setTimeout((()=>{var s;const o=i.filter((e=>e!==r));o.length>0&&this._callAppListener("onUserJoin",o);for(const e in t)e!==r&&this._resourceHandle({uris:t[e]},Ft.TOTAL_CONTENT_RESOURCE,e);if(!(null===(s=e.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===s?void 0:s.value))return;const n=this._store.getCDNUris();(null==n?void 0:n.push_mode)===si.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 ni(e,(e=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(e)})),this._roomPKHandler))}))}_getPushOtherRoomsParams(){const e=[];if(!this.isMainRoom()||!this._roomPKHandler)return e;const t=this._roomPKHandler.getJoinedPKRooms();for(const r in t){const i=t[r].getSessionId(),s=this._roomPKHandler.getPKInfo(r);if(!s)continue;const{inviterUserAutoMix:o,inviteeUserAutoMix:n,inviterUserId:a}=s,c=this._context.getCurrentId()===a;e.push({roomId:r,sessionId:i,autoMix:c?!!o:!!n})}return e}getRoomPKHandler(){return this._store.isMainRoom?(r.info(L.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:A.SUCCESSED},{logSource:i.RTC}),{code:v.SUCCESS,roomPKHandler:this._roomPKHandler}):(O.error("the `getRoomPKHandler` is disabled in PK room"),r.error(L.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:A.SUCCESSED,code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:v.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 li extends qr{constructor(e,t,r,i,s,o,n,a,c){super(e,t,r,d.RTC,i,s,o,n,a,c)}}const hi=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}},Ri=(e,t="")=>hi.push(e,t);class pi{constructor(e,t,r,i){this._context=e,this._useMutilPeerC=i,this._rtcToken="",this._liveUrl="",this._subTracks=[],this._clientSessionId=Kt(),this._livingType=null,this._mediaType=null,this._subTiny=!1,this._fromRetry=!1,this._appListener=null,this._service=new jt(t,e,r.mediaServer),this._peerCManager=new gr(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,d.LIVE,e);if(t!==n.SUCCESS)return O.error(`getRTCToken failed: ${t}`),{code:v.SIGNAL_ERROR};this._rtcToken=i.rtcToken}return{code:v.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:t,RoomId:r,RoomType:d.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===v.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 Ri((()=>this.__subscribe(e,t,r,i)),"audience-client-sub")}))}__subscribe(e,t,s,o=!1){var n;return f(this,void 0,void 0,(function*(){r.info(L.L_AUDIENCE_CLIENT_SUBSCRIBE_T,{liveUrl:e,livingType:t,mediaType:s,subTiny:o},{logSource:i.RTC});const a=[];if(wt(this._context.getNaviInfo()))return r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:v.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:i.RTC}),{code:v.PACKAGE_ENVIRONMENT_ERROR,tracks:a};if(!this._fromRetry&&(null===(n=this._pc)||void 0===n||n.clearReTryExchangeTimer()),this._fromRetry=!1,!l(e))return O.error(`liveUrl is invalid: ${e}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:`params error -> liveUrl: ${e}`},{logSource:i.RTC}),{code:v.PARAMS_ERROR,tracks:a};if(![ii.AUDIO,ii.VIDEO].includes(t))return O.error(`livingType is invalid: ${t}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:`params error -> livingType: ${t}`},{logSource:i.RTC}),{code:v.PARAMS_ERROR,tracks:a};if(![He.AUDIO_ONLY,He.VIDEO_ONLY,He.AUDIO_VIDEO].includes(s))return O.error(`mediaType is invalid: ${s}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:`params error -> -> mediaType: ${s}`},{logSource:i.RTC}),{code:v.PARAMS_ERROR,tracks:a};if(this._liveUrl&&this._liveUrl!==e)return r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:v.BROADCAST_SUB_LIST_NOT_EMPTY,msg:"repeat subscribe"},{logSource:i.RTC}),{code:v.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(Er.__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!==v.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 Rt(u,_),new pt(u,_)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const h={sdp:yield this._pc.createOffer(!0),liveUrl:e,mediaType:s,simulcast:o?Jt.TINY:Jt.NORMAL,switchstream:!1},R=yield this._service.broadcastSubscribe(d,h);if(R.code!==v.SUCCESS)return O.error(`andience subscribe failed: ${R.code}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:R.code,msg:""},{logSource:i.RTC}),{code:R.code,tracks:a};const p=R.data;if(p.resultCode!==v.SUCCESS)return O.error(`andience subscribe failed! code: ${p.resultCode}; message: ${p.message}`),r.error(L.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:A.FAILED,code:p.resultCode,msg:""},{logSource:i.RTC}),{code:p.resultCode,tracks:a};O.debug(`andience subscribe success: ${e}`),this._livingType=t,this._mediaType=s,this._subTiny=o;const{sdp:m,subscribedList:C}=p,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:v.SUCCESS,tracks:T}}))}unsubscribe(){return f(this,void 0,void 0,(function*(){return Ri((()=>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:v.SUCCESS};const{headers:t}=yield this._getReqHeaders(),{code:s}=yield this._service.broadcastExit(t);return s!==v.SUCCESS?(O.error(`broadcast unsubscribe failed: ${s}`),r.error(L.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:A.FAILED,code:s,msg:""},{logSource:i.RTC})):(O.debug("broadcast unsubscribe success"),r.info(L.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:A.SUCCESSED,liveUrl:this._liveUrl},{logSource:i.RTC})),this._clearSubscribeInfo(),{code:s}}))}registerReportListener(e){this._reportListener=e}registerTrackEventListener(e){this._appListener=e}_onTrackReady(e){var t,r;const i=e.receiver.track,s="audio"===i.kind?He.AUDIO_ONLY:He.VIDEO_ONLY,o=this._subTracks[s];o.__innerSetMediaStreamTrack(i);try{null===(r=null===(t=this._appListener)||void 0===t?void 0:t.onTrackReady)||void 0===r||r.call(t,o)}catch(e){O.error(e)}}}var mi,Ci;!function(e){e.RTMP="rtmp",e.FLV="flv",e.HLS="hls"}(mi||(mi={})),function(e){e[e.NOT_HTTPS=0]="NOT_HTTPS",e[e.HTTPS=1]="HTTPS"}(Ci||(Ci={}));const Ti=Object.assign(Object.assign({},Dt(Ke.W176_H144)),{frameRate:Ut(Ge.FPS_15)});class Ei{constructor(e,t,r,i,s,o,n,a=Kt()){this._context=e,this._runtime=t,this._initOptions=r,this._roomId=i,this._joinResData=s,this.livingType=o,this._useMutilPeerC=n,this._clientSessionId=a,this._roomAnchorList=[],this._roomRes={},this._roomAnchorRes={},this._remoteTracks={},this._appListener=null,this._pc=null,this._subscribedList=[],this._sessionId="",this._destroyed=!1,this._reportListener=null,this._setInitData(),this._service=new jt(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new Ir(this._context,this._runtime,this._roomId,this,or.Audience),this._polarisReport.sendR1(),this._peerCManager=new gr(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._context.onrtcdatachange=this.singalDataChange.bind(this)}_setInitData(){const{sessionId:e,remoteUserIds:t,remoteRTCUris:r,remoteMUCUris:i,remoteTracks:s,CDNUris:o}=((e,t)=>{const r=t.filter((e=>"RC_RTC_SESSIONID"===e.key))[0],i=r?r.value:"",s=t.filter((e=>"RC_ANCHOR_LIST"===e.key)).map((e=>JSON.parse(e.value||"[]")))[0],o=t.filter((e=>e.key.includes("RC_RES_"))).map((e=>JSON.parse(e.value||"{}"))),n=o.length?JSON.parse(o[0].mcu_uris||"[]"):[],a=[];n.forEach((t=>{const{mediaType:r,tag:i}=t,s=r===He.AUDIO_ONLY?new Rt(i,"",e):new pt(i,"",e);a.push(s)}));const c=[],d=[];o.forEach((e=>{const t=JSON.parse(e.uris||"[]");c.push(...t),t.forEach((e=>{const{mediaType:t,tag:r,msid:i}=e,s=i.split("_")[0],o=t===He.AUDIO_ONLY?new Rt(r,s):new pt(r,s);d.push(o)}))}));const _=t.filter((e=>"RC_CDN"===e.key)).map((e=>{const t=JSON.parse(e.value||"[]");return JSON.parse(t.cdn_uris)[0]}))[0];return{sessionId:i,remoteUserIds:s||[],remoteRTCUris:c,remoteMUCUris:n,remoteRTCTracks:d,remoteMCUTracks:a,remoteTracks:[...d,...a],CDNUris:_||{}}})(this._roomId,this._joinResData.kvEntries);this._sessionId=e,this._roomAnchorList=t,s.forEach((e=>{this._remoteTracks[e.getTrackId()]=e})),this._CDNUris=o,r.forEach((e=>{const t=e.msid.split("_")[0];this._roomAnchorRes[t]?this._roomAnchorRes[t].push(e):this._roomAnchorRes[t]=[e]})),i.forEach((e=>{const{mediaType:t,tag:r}=e,i=[this._roomId,r,t].join("_");this._roomRes[i]=e})),r.forEach((e=>{const t=ft(e);this._roomRes[t]=e}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinLivingRoomAsAudience` to catch another instance.";return O.warn(e),v.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(e,t){var s;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 O.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});O.debug("singalDataChange -> singalData:",JSON.stringify(e||{}));const o=[],n=null===(s=e.filter((e=>"RC_CDN"===e.key))[0])||void 0===s?void 0:s.value;n&&this._diffCDNUris(JSON.parse(JSON.parse(n).cdn_uris)[0]),e.forEach((e=>{const{key:t,value:r,timestamp:i,uid:s}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),i=JSON.parse(e.uris||"[]");return o.push(...t),void this._diffAnchorResource(i,s)}if("RC_ANCHOR_LIST"===t){const e=JSON.parse(r||"[]"),{joinUserIds:t,leftUserIds:i}=this._diffAnchorList(e);t.length>0&&this._handleNewJoinedAnchor(t),i.length>0&&this._handleLeftedAnchor(i)}})),this._diffRoomResource(o),r.info(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=ft(e),{userId:s,tag:o,mediaType:n}=Ot(r),a=[this._roomId,o,n].join("_");if(!this._remoteTracks[a]){const r=n===He.AUDIO_ONLY?new Rt(o,"",this._roomId):new pt(o,"",this._roomId);t.push(r),this._remoteTracks[a]=r,this._roomRes[r.getTrackId()]=e}i.push(a)})),Object.keys(this._remoteTracks).forEach((e=>{i.indexOf(e)<0&&this._remoteTracks[e].isMCUTrack()&&r.push(this._remoteTracks[e])})),t.length>0&&this._callAppListener("onTrackPublish",t),r.length>0&&this._onUserUnpublish(r,"onTrackUnpublish")}))}_diffAnchorResource(e,t){return f(this,void 0,void 0,(function*(){const r=this._roomAnchorRes[t]||(this._roomAnchorRes[t]=[]),{publishedList:i,unpublishedList:s,modifiedList:o}=At(r,e);if(i.length){const e=r.map(ft),t=[],s=[];if(i.forEach((i=>{const o=ft(i),n=e.indexOf(o),{userId:a,tag:c,mediaType:d}=Ot(o);n>-1?r[n]=i:r.push(i);let _=this._remoteTracks[o];this._roomRes[o]=i,_?_.isSubscribed()&&t.push(_):(_=d===He.AUDIO_ONLY?new Rt(c,a):new pt(c,a),this._remoteTracks[o]=_,s.push(_)),_.__innerSetRemoteMuted(0===i.state)})),t.length){const e=t.map((e=>e.getTrackId()));O.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:r}=yield Ri((()=>this._subscribeHandle(t,!0)));r!==v.SUCCESS&&O.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(e)}`)}this._callAppListener("onAnchorTrackPublish",s)}if(s.length){const e=s.map(ft);for(let t=r.length-1;t>=0;t-=1){const i=r[t];e.includes(ft(i))&&r.splice(t,1)}const t=s.map((e=>{const t=ft(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t,"onAnchorTrackUnpublish")}if(o.length){const e=r.map(ft);for(let t=0;t<o.length;t++){const i=o[t],s=ft(i),n=e.indexOf(s);r[n].state=i.state;const a=this._remoteTracks[s];a.__innerSetRemoteMuted(0===i.state),a.isAudioTrack()?this._callAppListener("onAudioMuteChange",a):this._callAppListener("onVideoMuteChange",a)}}}))}_onUserUnpublish(e,t){return 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;O.info(`${e} callback ->`,...t);const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){O.error(e)}}_reTryExchange(){return f(this,void 0,void 0,(function*(){Ri((()=>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!==v.SUCCESS)return O.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:s}=r.data;if(s!==v.SUCCESS)return O.error(`reTryExchange failed: ${s}`),{code:s};this._pc.clearReTryExchangeTimer();const o=this._subscribedList.filter((e=>e.track.isMCUTrack()));if(o.length>0){const t=o[0].track.getTrackId(),r=null===(e=this._roomRes[t])||void 0===e?void 0:e.msid,s=[this._roomId,"RongCloudRTC"].join("_");i.sdp=i.sdp.replace(new RegExp(r,"g"),s)}const n=yield this._pc.setRemoteAnswer(i.sdp);return n!==v.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),s={resolutionInfo:[]},o={min:0,max:0};Object.keys(t).forEach((e=>{const{mediaStream:r,tinyStream:n}=t[e];[r,n].forEach(((t,r)=>{var n;const a=1===r?[e,"tiny"].join("_"):e;i.sdp=null===(n=i.sdp)||void 0===n?void 0:n.replace(new RegExp(t.id,"g"),a);const c=t.getVideoTracks()[0];if(!c)return;const d=0===r,{width:_,height:u,frameRate:l}=d?St(c):Ti;s.resolutionInfo.push({trackId:c.id,simulcast:d?Jt.NORMAL:Jt.TINY,resolution:`${_}x${u}`});const h=Je(_,u),R=Ye(l);o.min+=h.minBitrate*R,o.max+=h.maxBitrate*R}))}));return{reqBody:{sdp:i,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?Jt.TINY:Jt.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:o,offer:i}}))}_subscribeHandle(e,t=!1){var s;return f(this,void 0,void 0,(function*(){r.info(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_T,{trackIds:e.map(Vt),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:v.ROOM_HAS_BEEN_DESTROYED,msg:"room destroyed"},{logSource:i.RTC}),{code:v.ROOM_HAS_BEEN_DESTROYED};if(!o("tracks",e,(()=>p(e)&&e.length>0&&e.every((e=>e instanceof ht||e.track instanceof ht))),!0))return r.error(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:v.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))),d=e.map((e=>e instanceof ht?{track:e}:e));let _=!1;const u=[];return d.forEach((e=>{const t=e.track.getTrackId();u.push(t);const r=c.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:c.push(e),_=!0)})),_||t?(null===(s=this._polarisReport)||void 0===s||s.sendR2(ur.SUBSCRIBE,lr.BEGIN,u),r.info(L.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:A.SUCCESSED,trackIds:e.map(Vt),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:v.SUCCESS})}))}_addPeerCEvent(){this._pc.on(Er.__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("_"),s=this._remoteTracks[i];s?(s.__innerSetMediaStreamTrack(r),this._callAppListener("onTrackReady",s)):O.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:d.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:v.ROOM_HAS_BEEN_DESTROYED};if(!o("resources",e,(()=>p(e)&&e.every((e=>e instanceof ht||e.track instanceof ht))),!0))return{code:v.PARAMS_ERROR};let i=e.map((e=>e instanceof ht?{track:e}:Object.assign({},e)));const s={};i=i.filter((e=>{const t=e.track.getTrackId();return!s[t]&&(s[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:v.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!==v.SUCCESS)return{code:c.code};const{sdp:d,resultCode:_,message:u,subscribedList:l}=c.data;if(_!==v.SUCCESS)return O.error("change subscribe list failed:",u,_),{code:_};i.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:i}=Ot(t.getTrackId()),s=[i,r].join("_");d.sdp=d.sdp.replace(new RegExp(e,"g"),s)}}));const h=yield this._pc.setRemoteAnswer(d.sdp);if(h!==v.SUCCESS)return{code:h};const R=null==l?void 0:l.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 R.includes(r)}return null==R?void 0:R.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:v.SUCCESS,failedList:T}:{code:v.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,s=this._initOptions.pullInnerCDNProtocol||mi.FLV,o=this._initOptions.pullInnerCDNUseHttps===Ci.NOT_HTTPS?Ci.NOT_HTTPS:Ci.HTTPS;if(!this._CDNUris.url)return O.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${v.CDN_RESOURCE_IS_EMPTY}`),{code:v.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=${s}`),a.push(`is_https=${o}`);const c=a.join("&");let d=`${this._CDNUris.url}?`;c&&(d+=c);const{code:_,res:u}=yield this._service.getCDNResourceInfo(n,d);return _!==v.SUCCESS?(O.error(`getCDNPlayUrl failed: ${_}`),{code:_}):(O.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&&!kt(e))return O.error("`resolution` is invalid"),r.error(L.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> resolution"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(t&&!bt(t))return O.error("`fps` is invalid"),r.error(L.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> fps"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};const{width:s,height:o}=e?Dt(e):{width:null,height:null},n=t?Ut(t):null,a={};return s&&(a.w=s),o&&(a.h=o),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 Ri((()=>this._subscribeHandle(e,!1)),"audience-sub")}))}addSubscribeTask(e){return f(this,void 0,void 0,(function*(){return Ri((()=>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}),!o("tracks",e,(()=>p(e)&&e.length>0&&e.every((e=>e instanceof ht))),!0))return O.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),r.error(L.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};const s=this._subscribedList.map((e=>Object.assign({},e))).filter((t=>!e.includes(t.track)));return null===(t=this._polarisReport)||void 0===t||t.sendR2(ur.SUBSCRIBE,lr.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(s,!1)}))}unsubscribe(e){return f(this,void 0,void 0,(function*(){return Ri((()=>this.__unsubscribe(e)),"audience-unsub")}))}addUnsubscribeTask(e){return f(this,void 0,void 0,(function*(){return Ri((()=>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.onrtcdatachange=()=>{})}))}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,d.LIVE);e!==n.SUCCESS&&O.error("join living room error when on reconnected")}))}registerRoomEventListener(e){this._appListener=e}onAudioLevelChange(e,t){var s;null===(s=this._audioLevelReport)||void 0===s||s.clearAudioLevelReportTimer(),this._audioLevelReport=new Sr(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 Ii{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:v.SUCCESS,stream:i}}catch(e){if("Permission denied"===e.message)return{code:v.BROWSER_PERMISSION_DENIED};if("Permission denied by system"===e.message)return{code:v.SYSTEM_PERMISSION_DENIED};O.error(`get user media failed -> ${e.message}`)}return{code:"getUserMedia"===t?v.GET_USER_MEDIA_FAILED:v.GET_DISPLAY_MEDIA_FAILED}}))}setConstraintsConfig(e){if((null==e?void 0:e.audio)&&!this._isElectron){"boolean"==typeof e.audio&&(e.audio={});const t=navigator.mediaDevices.getSupportedConstraints();t.noiseSuppression&&(e.audio.noiseSuppression=!!t.noiseSuppression),t.autoGainControl&&(e.audio.autoGainControl=!!t.autoGainControl),t.echoCancellation&&(e.audio.echoCancellation=!!t.echoCancellation),O.info(`browser supported -> ${JSON.stringify(t)}`)}return e}createMicrophoneAudioTrack(e="RongCloudRTC",t){return f(this,void 0,void 0,(function*(){if(!Tt(e))return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.INVALID_TAGS};const s=this._context.getCurrentId();if(!s)return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:A.FAILED,code:v.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID};const{stream:o,code:n}=yield this._getMediaStream({audio:{deviceId:null==t?void 0:t.micphoneId,sampleRate:null==t?void 0:t.sampleRate}});if(n!==v.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=o.getAudioTracks()[0],c=new dt(e,s,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(!Tt(e))return r.error(L.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.INVALID_TAGS};const s=this._context.getCurrentId();if(!s)return r.error(L.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID};const o=kt(null==t?void 0:t.resolution)?t.resolution:Ke.W640_H480,{width:n,height:a}=Dt(o),{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!==v.SUCCESS)return r.error(L.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"Failed to get camera video stream"},{logSource:i.RTC}),{code:d};const _=c.getVideoTracks()[0],u=new _t(e,s,_);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 s,o,n,a,c,d;return f(this,void 0,void 0,(function*(){const _=[];if(!Tt(e))return r.error(L.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.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:v.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID,tracks:_};const l=kt(null===(s=null==t?void 0:t.video)||void 0===s?void 0:s.resolution)?t.video.resolution:Ke.W640_H480,{width:h,height:R}=Dt(l),{stream:p,code:m}=yield this._getMediaStream({video:{deviceId:null===(o=null==t?void 0:t.video)||void 0===o?void 0:o.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!==v.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 _t(e,u,t)):_.unshift(new dt(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===v.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,s,o){var n,a;return f(this,void 0,void 0,(function*(){if(!Tt(e))return r.error(s,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.INVALID_TAGS};const c=this._context.getCurrentId();if(!c)return r.error(s,{status:A.FAILED,code:v.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID};if(!Mt())return r.error(L.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:A.FAILED,code:v.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:i.RTC}),{code:v.BROWSER_NOT_SUPPORT};const d=/macintosh|mac os x/i.test(navigator.userAgent);this._isElectron&&d&&t&&r.warn(s,{status:A.INFO,code:v.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&&!I(null==o?void 0:o.chromeMediaSourceId)&&!l(null==o?void 0:o.chromeMediaSourceId))return r.error(s,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> options.chromeMediaSourceId type is string"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};const u=kt(null==o?void 0:o.resolution)?o.resolution:Ke.W1280_H720,{width:h,height:R}=Dt(u),p=this._isElectron?{mandatory:{chromeMediaSourceId:null==o?void 0:o.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:h,maxWidth:h,minHeight:R,maxHeight:R}}:{frameRate:Ut((null==o?void 0:o.frameRate)||Ge.FPS_15),width:h,height:R};!(null==o?void 0:o.chromeMediaSourceId)&&this._isElectron&&(null===(n=p.mandatory)||void 0===n||delete n.chromeMediaSourceId);let m=null;_&&this._isElectron&&(null===(a=p.mandatory)||void 0===a||delete a.chromeMediaSourceId,m={mandatory:{chromeMediaSource:"desktop"}});const{stream:C,code:T}=yield this._getMediaStream({video:p,audio:m||_},this._isElectron?"getUserMedia":"getDisplayMedia");if(T!==v.SUCCESS)return r.error(s,{status:A.FAILED,code:T,msg:"Failed to get shared screen video stream"},{logSource:i.RTC}),{code:T};const E=C.getVideoTracks()[0],S=[new ut(e,c,E)];if(_){const t=C.getAudioTracks()[0];t&&S.push(new lt(e,c,t))}return r.info(s,{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(!Tt(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.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:v.INVALID_USER_ID,msg:"Failed to create custom stream"},{logSource:i.RTC}),{code:v.CREATE_CUSTOM_TRACK_FAILED};const s=this._context.getCurrentId();if(!s)return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:A.FAILED,code:v.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID};const o=new st(e,s,t);return r.info(L.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:A.SUCCESSED,trackId:o.getTrackId()},{logSource:i.RTC}),{code:v.SUCCESS,track:o}}))}createLocalVideoTrack(e,t){return f(this,void 0,void 0,(function*(){if(!Tt(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.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:v.CREATE_CUSTOM_TRACK_FAILED,msg:"Failed to create custom stream"},{logSource:i.RTC}),{code:v.CREATE_CUSTOM_TRACK_FAILED};const s=this._context.getCurrentId();if(!s)return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:A.FAILED,code:v.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID};const o=new ot(e,s,t);return r.info(L.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:A.SUCCESSED,trackId:o.getTrackId()},{logSource:i.RTC}),{code:v.SUCCESS,track:o}}))}createLocalFileTracks(e,t,s){return f(this,void 0,void 0,(function*(){if(!Tt(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.INVALID_TAGS,tracks:[]};if(!yt())return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:v.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:i.RTC}),{code:v.BROWSER_NOT_SUPPORT,tracks:[]};const o=t instanceof File?URL.createObjectURL(t):t;if(!T(o)&&!/^blob:/.test(o))return O.warn(`createLocalFileTracks failed: params error -> url: ${o}`),r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> file"},{logSource:i.RTC}),{code:v.PARAMS_ERROR,tracks:[]};const n=this._context.getCurrentId();return n?new Promise((t=>{const a=document.createElement("video");(null==s?void 0:s.withoutAudio)&&(a.muted=!0),a.onloadedmetadata=()=>{const c=[];let d;try{const e=a.mozCaptureStream?"mozCaptureStream":"captureStream";d=a[e]()}catch(e){O.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${o}`),O.error(e),r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:v.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:i.RTC}),t({code:v.CREATE_FILE_TRACK_FAILED,tracks:c})}const[_,u]=Ii.getTracksWithOptions(d,s);_&&c.push(new ct(e,n,_,a)),u&&c.push(new at(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:v.SUCCESS,tracks:c})},a.onerror=()=>{O.error(`create RCLocalFileTrack failed -> url: ${o}`),r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:v.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:i.RTC}),t({code:v.CREATE_FILE_TRACK_FAILED,tracks:[]})},a.src=o,a.loop=!0,a.play()})):(r.error(L.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:A.FAILED,code:v.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID,tracks:[]})}))}createLocalTracks(e,t,s){return f(this,void 0,void 0,(function*(){const o=[];if(!Tt(e))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:A.FAILED,code:v.INVALID_TAGS,msg:"invalid tag"},{logSource:i.RTC}),{code:v.INVALID_TAGS,tracks:o};if(!(t instanceof MediaStream))return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> stream"},{logSource:i.RTC}),{code:v.PARAMS_ERROR,tracks:o};const n=this._context.getCurrentId();if(!n)return r.error(L.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:A.FAILED,code:v.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:i.RTC}),{code:v.INVALID_USER_ID,tracks:o};const[a,c]=Ii.getTracksWithOptions(t,s);return a&&o.push(new st(e,n,a)),c&&o.push(new ot(e,n,c)),r.info(L.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:A.SUCCESSED,trackIds:o.map((e=>e.getTrackId()))},{logSource:i.RTC}),{code:v.SUCCESS,tracks:o}}))}static getTracksWithOptions(e,t){const r=[];return r[0]=(null==t?void 0:t.withoutAudio)?void 0:e.getAudioTracks()[0],r[1]=(null==t?void 0:t.withoutVideo)?void 0:e.getVideoTracks()[0],r}}class Si extends Ii{constructor(e,t,r){super(e),this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,Rr.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new jt(this._runtime,this._context,this._options.mediaServer,this._options.timeout),this._context.onconnectionstatechange=this._onIMStatusChange.bind(this),this._context.ondisconnect=this._onIMDisconnect.bind(this),this._context.ondestroy=this._onIMUninit.bind(this),this._context.onmessage=this._handleMessage.bind(this)}_handleMessage(e){var t;if(e.conversationType!==C.RTC_ROOM)return!1;if(this._crtRoom instanceof ui){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}_getJoinedPKRoomList(){const{code:e,roomPKHandler:t}=this._crtRoom.getRoomPKHandler();if(e===v.SUCCESS&&t){const e=t.getJoinedPKRooms()||{};return Object.values(e)}return[]}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(e,t,s,o,n=d.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:s,useMutilPeerC:o,roomType:n},{logSource:i.RTC}),this._crtRoom)return r.error(L.L_RTC_CLIENT_JOIN_RTC_ROOM_R,{status:A.FAILED,code:v.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:v.REPERT_JOIN_ROOM};const a=this._crtRoom=new li(this._context,this._runtime,e,this._service,this._options,!1,!1,o,Kt()),{code:c}=yield a.__innerInit(n,t,void 0,void 0,s);return c!==v.SUCCESS?(this._crtRoom=null,{code:c}):(a.once(Yr,(()=>{this._crtRoom=null})),{code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()})}))}joinLivingRoom(e,t,s,o,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:s,outerUserDatas:o,useMutilPeerC:n},{logSource:i.RTC}),this._crtRoom)return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:A.FAILED,code:v.REPERT_JOIN_ROOM,msg:`Join the room repeatedly -> roomId: ${e}`},{logSource:i.RTC}),{code:v.REPERT_JOIN_ROOM};const a=this._crtRoom=new ui(this._context,this._runtime,e,this._service,this._options,t,!1,!0,n),{code:c}=yield a.__innerInit(d.LIVE,s,t,void 0,o);if(c!==v.SUCCESS)return this._crtRoom=null,{code:c};a.once(Yr,(()=>{this._crtRoom=null}));const _={code:c,room:a,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()};return a.__getCDNPushMode()===si.MANUAL&&Object.assign(_,{CDNEnable:a.__getCDNEnable()}),_}))}getAudienceClient(e){return this._audience||(this._audience=new pi(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(O.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===c.CONNECTED){if(this._crtRoom instanceof ui){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}),O.debug("TODO -> on IM disconnect")}_onIMUninit(){r.info(L.L_RTC_CLIENT_DESTROY_S,{status:A.SUCCESSED},{logSource:i.RTC}),O.debug("TODO -> on IM client ondestroy")}leaveRoom(e){var t,s;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),O.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),r.info(L.L_RTC_CLIENT_LEAVE_ROOM_R,{status:A.SUCCESSED,userId:this._context.getCurrentId(),roomId:null===(s=this._crtRoom)||void 0===s?void 0:s.getRoomId()},{logSource:i.RTC}),this._crtRoom=null,{code:v.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:v.SUCCESS})}))}joinLivingRoomAsAudience(e,t,s){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:s},{logSource:i.RTC}),wt(this._context.getNaviInfo()))return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:v.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:i.RTC}),{code:v.PACKAGE_ENVIRONMENT_ERROR};if(!o("roomId",e,_,!0)||!o("livingType",t,(e=>e===ii.AUDIO||e===ii.VIDEO)))return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:v.PACKAGE_ENVIRONMENT_ERROR,msg:"params error -> roomId or livingType"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:v.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:v.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:v.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:i.RTC}),{code:v.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:a,data:c}=yield this._context.joinLivingRoomAsAudience(e,d.LIVE,t);if(a!==n.SUCCESS)return O.error("audienceJoinLivingRoomError:",a),r.error(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.FAILED,code:v.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED,msg:"signal error -> audience join room"},{logSource:i.RTC}),{code:v.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};O.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(c)}`);const u=Kt(),l=new Ei(this._context,this._runtime,this._options,e,c,t,s,u);return this._crtAudienceLivingRoom=l,r.info(L.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:A.SUCCESSED,roomData:c},{logSource:i.RTC}),{room:l,code:v.SUCCESS,userIds:l.getRemoteUserIds(),RTCTracks:l.getRemoteRTCTracks(),MCUTracks:l.getRemoteMCUTracks(),CDNUris:l.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:v.PARAMS_ERROR,msg:"params error -> room"},{logSource:i.RTC}),{code:v.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:v.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:v.SUCCESS})}))}upgradeToAnchorRoom(e){return f(this,void 0,void 0,(function*(){if(!o("room",e,(()=>e instanceof Ei),!0))return r.error(L.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> room"},{logSource:i.RTC}),{code:v.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:v.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:v.REPERT_JOIN_ROOM};const t=e.getRoomId(),s=this._crtRoom=new ui(this._context,this._runtime,t,this._service,this._options,e.livingType,!0,!0,!1,e.getClientSessionId()),a=yield s.__innerInitByIdentityChange();return a!==n.SUCCESS?(O.warn(`change room identity failed -> code: ${a}`),this._crtRoom=null,r.error(L.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:A.FAILED,code:v.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:i.RTC}),{code:v.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):(s.once(Yr,(()=>{this._crtRoom=null})),yield this._crtAudienceLivingRoom.__destroy(!1),this._crtAudienceLivingRoom=null,{room:s,code:v.SUCCESS,userIds:s.getRemoteUserIds(),tracks:s.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 O.error("the `downgradeToAudienceRoom` is disabled in PK room"),r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:i.RTC}),{code:v.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!o("room._roomId",e._roomId,_,!0))return r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:v.PARAMS_ERROR,msg:"params error -> room._roomId"},{logSource:i.RTC}),{code:v.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:v.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:i.RTC}),{code:v.REPERT_JOIN_ROOM};const{code:t,data:s}=yield this._context.rtcIdentityChange(e._roomId,S.AnchorToViewer,e.getLivingType());if(t!==n.SUCCESS)return O.error("change room identity error",t),r.error(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.FAILED,code:v.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:i.RTC}),{code:v.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};O.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(s)}`),r.info(L.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:A.SUCCESSED,roomData:s},{logSource:i.RTC});const a=e.getClientSessionId(),c=new Ei(this._context,this._runtime,this._options,e._roomId,s,e.getLivingType(),!1,a);return this._crtAudienceLivingRoom=c,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:c,code:v.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!==n.SUCCESS?(O.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:v.SUCCESS,data:t})}))}}var gi;!function(e){e[e.SERVER_KICK=1]="SERVER_KICK",e[e.OTHER_KICK=2]="OTHER_KICK"}(gi||(gi={}));const fi={tag:"RCRTC",verify:e=>"browser"!==e.tag?(O.error(`RCRTC Plugin is not support the runtime '${e.tag}'`),!1):Et?(g.add("plugin-rtc","5.4.4"),!!g.validEngine(">=5.3.3-beem-alpha.2 || >=5.3.4")||(O.error(`The current engine version '${g.getInfo().engine}' error, plugin-rtc required engine version at least '>=5.3.3-beem-alpha.2 || >=5.3.4'.`),!1)):(O.error("Please use the https protocol or use `http://localhost` to open the page!"),!1),setup(e,t,r={}){var i,o,n,a,c,d,_,u;return O.setLogLevel(r.logLevel),O.setLogStdout(r.logStdout),O.warn("RCRTC Version: 5.4.4, Commit: bc1f8f530851278c199d53868ad7c199d465f45e"),O.warn(`browserInfo.browser -> ${Pt.browser}`),O.warn(`browserInfo.supportsUnifiedPlan -> ${Pt.supportsUnifiedPlan}`),O.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=>s(e)&&e>=5e3&&e<=3e4)),m("options.pingGap",r.pingGap,(e=>s(e)&&e>=3e3&&e<=1e4)),(null==r?void 0:r.audio)&&((null===(i=r.audio)||void 0===i?void 0:i.workletModule)&&(rt.workletModule=null===(o=r.audio)||void 0===o?void 0:o.workletModule),(null===(n=r.audio)||void 0===n?void 0:n.workletWasm)&&(rt.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)&&(rt.isOpen=!0),void 0!==(null===(_=r.audio)||void 0===_?void 0:_.isOpen)&&(rt.isOpen=null===(u=r.audio)||void 0===u?void 0:u.isOpen)),new Si(e,t,r)}},Oi={DEFAULT:"RongCloudRTC"},vi={transResolution:Dt,transFrameRate:Ut,parseTrackId:Ot,ifSupportLocalFileTrack:yt,ifSupportScreenShare:Mt};export{Qr as BackgroundPictureFillMode,Zr as MixLayoutMode,Xr as MixVideoRenderMode,qr as RCAbstractRoom,pi as RCAudienceClient,Ei as RCAudienceLivingRoom,Qe as RCAudioBitrate,_t as RCCameraVideoTrack,Ge as RCFrameRate,Ci as RCInnerCDNPullIsHttps,mi as RCInnerCDNPullKind,gi as RCKickReason,ui as RCLivingRoom,ii as RCLivingType,st as RCLocalAudioTrack,ct as RCLocalFileAudioTrack,nt as RCLocalFileTrack,at as RCLocalFileVideoTrack,it as RCLocalTrack,ot as RCLocalVideoTrack,ri as RCMCUConfigBuilder,Ii as RCMediaStreamCapture,He as RCMediaType,dt as RCMicphoneAudioTrack,Si as RCRTCClient,v as RCRTCCode,nr as RCRTCLiveRole,$t as RCRTCPingResult,li as RCRTCRoom,Rt as RCRemoteAudioTrack,ht as RCRemoteTrack,pt as RCRemoteVideoTrack,Ke as RCResolution,lt as RCScreenAudioTrack,ut as RCScreenVideoTrack,Oi as RCTag,Ze as RCTrack,et as RCVideoBitrate,qe as device,vi as helper,fi as installer};