@rongcloud/plugin-rtc 5.4.2 → 5.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/dist/async-task-queue.d.ts +9 -0
  2. package/dist/core/Invoker.d.ts +46 -0
  3. package/dist/core/PolarisReporter.d.ts +35 -0
  4. package/dist/core/RCAudienceClient.d.ts +89 -0
  5. package/dist/core/RCMediaStreamCapture.d.ts +124 -0
  6. package/dist/core/RCRTCClient.d.ts +126 -0
  7. package/dist/core/Store.d.ts +80 -0
  8. package/dist/core/command/BaseCommand.d.ts +22 -0
  9. package/dist/core/command/EnabelInnerCDNCommand.d.ts +16 -0
  10. package/dist/core/command/ExchangeCommand.d.ts +18 -0
  11. package/dist/core/command/ExchangeWithPushOtherRoomCommand.d.ts +22 -0
  12. package/dist/core/command/JoinRoomCommand.d.ts +26 -0
  13. package/dist/core/command/LeaveOtherRoomCommand.d.ts +30 -0
  14. package/dist/core/command/LocalTrackMuteCommand.d.ts +10 -0
  15. package/dist/core/command/MCUConfigFlushCommand.d.ts +18 -0
  16. package/dist/core/command/OnRemoteUserUnpubCommand.d.ts +13 -0
  17. package/dist/core/command/OnSignalReconnectedCommand.d.ts +38 -0
  18. package/dist/core/command/ParseRemoteResCommand.d.ts +38 -0
  19. package/dist/core/command/ParseUserStateCommand.d.ts +57 -0
  20. package/dist/core/command/PubCommand.d.ts +34 -0
  21. package/dist/core/command/RTCIdentityChangeCommand.d.ts +17 -0
  22. package/dist/core/command/RetryExchangeCommand.d.ts +18 -0
  23. package/dist/core/command/SubCommand.d.ts +21 -0
  24. package/dist/core/command/UnpubCommand.d.ts +20 -0
  25. package/dist/core/command/UnpubPrevCommand.d.ts +6 -0
  26. package/dist/core/command/UnsubCommand.d.ts +20 -0
  27. package/dist/core/command/UpdateSubListCommand.d.ts +28 -0
  28. package/dist/core/command/helper.d.ts +20 -0
  29. package/dist/core/constants.d.ts +2 -0
  30. package/dist/core/enums/BackgroundPictureFillMode.d.ts +14 -0
  31. package/dist/core/enums/MixLayoutMode.d.ts +18 -0
  32. package/dist/core/enums/MixVideoRenderMode.d.ts +14 -0
  33. package/dist/core/enums/RCBitrate.d.ts +48 -0
  34. package/dist/core/enums/RCFrameRate.d.ts +7 -0
  35. package/dist/core/enums/RCInnerCDNBroadcast.d.ts +5 -0
  36. package/dist/core/enums/RCInnerCDNModel.d.ts +5 -0
  37. package/dist/core/enums/RCInnerCDNPullIsHttps.d.ts +5 -0
  38. package/dist/core/enums/RCInnerCDNPullKind.d.ts +6 -0
  39. package/dist/core/enums/RCInnerCDNPushMode.d.ts +5 -0
  40. package/dist/core/enums/RCKickType.d.ts +11 -0
  41. package/dist/core/enums/RCLivingType.d.ts +14 -0
  42. package/dist/core/enums/RCLoggerTag.d.ts +629 -0
  43. package/dist/core/enums/RCMediaType.d.ts +18 -0
  44. package/dist/core/enums/RCMixInputFilterMode.d.ts +35 -0
  45. package/dist/core/enums/RCRTCCode.d.ts +86 -0
  46. package/dist/core/enums/RCRTCLiveRole.d.ts +14 -0
  47. package/dist/core/enums/RCRTCPingResult.d.ts +5 -0
  48. package/dist/core/enums/RCRTCResolution.d.ts +102 -0
  49. package/dist/core/enums/RCResolution.d.ts +16 -0
  50. package/dist/core/enums/inner/PolarisRole.d.ts +14 -0
  51. package/dist/core/enums/inner/R2Action.d.ts +14 -0
  52. package/dist/core/enums/inner/R2Status.d.ts +11 -0
  53. package/dist/core/enums/inner/RCRTCMessageType.d.ts +66 -0
  54. package/dist/core/enums/inner/RCStreamType.d.ts +14 -0
  55. package/dist/core/enums/inner/TrackState.d.ts +14 -0
  56. package/dist/core/interfaces.d.ts +912 -0
  57. package/dist/core/room/Pinger.d.ts +35 -0
  58. package/dist/core/room/RCAbstractRoom.d.ts +327 -0
  59. package/dist/core/room/RCAudienceLivingRoom.d.ts +321 -0
  60. package/dist/core/room/RCAudioLevelReport.d.ts +16 -0
  61. package/dist/core/room/RCLivingPKHandler.d.ts +164 -0
  62. package/dist/core/room/RCLivingRoom.d.ts +108 -0
  63. package/dist/core/room/RCLocalMediaStream.d.ts +8 -0
  64. package/dist/core/room/RCMCUConfigBuilder.d.ts +211 -0
  65. package/dist/core/room/RCRTCRoom.d.ts +15 -0
  66. package/dist/core/service/RCMediaService.d.ts +96 -0
  67. package/dist/core/service/helper.d.ts +8 -0
  68. package/dist/core/service/index.d.ts +6 -0
  69. package/dist/core/service/interface.d.ts +323 -0
  70. package/dist/core/service/mcu-interface.d.ts +293 -0
  71. package/dist/core/tracks/RCLocalTrack.d.ts +121 -0
  72. package/dist/core/tracks/RCRemoteTrack.d.ts +23 -0
  73. package/dist/core/tracks/RCTrack.d.ts +91 -0
  74. package/dist/core/webrtc/RCRTCPeerCManager.d.ts +159 -0
  75. package/dist/core/webrtc/RCRTCPeerConnection.d.ts +110 -0
  76. package/dist/core/webrtc/helper.d.ts +26 -0
  77. package/dist/core/webrtc/sdp/ASdpBuilder.d.ts +98 -0
  78. package/dist/core/webrtc/sdp/ASdpStrategy.d.ts +48 -0
  79. package/dist/core/webrtc/sdp/PlanBSdpBuilder.d.ts +20 -0
  80. package/dist/core/webrtc/sdp/PlanBStrategy.d.ts +26 -0
  81. package/dist/core/webrtc/sdp/UnifiedPlanSdpBuilder.d.ts +11 -0
  82. package/dist/core/webrtc/sdp/UnifiedPlanStrategy.d.ts +21 -0
  83. package/dist/core/webrtc/stat-parser/AbstractStatParser.d.ts +117 -0
  84. package/dist/core/webrtc/stat-parser/ChromeStatParser.d.ts +14 -0
  85. package/dist/core/webrtc/stat-parser/FirefoxStatParser.d.ts +14 -0
  86. package/dist/core/webrtc/stat-parser/IStatParser.d.ts +24 -0
  87. package/dist/core/webrtc/stat-parser/SafariStatParser.d.ts +14 -0
  88. package/dist/device.d.ts +6 -0
  89. package/dist/helper.d.ts +189 -0
  90. package/dist/index.d.ts +193 -155
  91. package/dist/index.esm.js +2 -2
  92. package/dist/index.js +1 -1
  93. package/dist/index.umd.js +1 -1
  94. package/dist/logger.d.ts +4 -0
  95. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -12,4 +12,4 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
12
12
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13
13
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14
14
  PERFORMANCE OF THIS SOFTWARE.
15
- ***************************************************************************** */function t(e,t,r,o){return new(r||(r=Promise))((function(i,s){function n(e){try{c(o.next(e))}catch(e){s(e)}}function a(e){try{c(o.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,a)}c((o=o.apply(e,t||[])).next())}))}const r=new e.Logger("RCRTC");var o,i,s;exports.RCRTCCode=void 0,(o=exports.RCRTCCode||(exports.RCRTCCode={}))[o.SUCCESS=1e4]="SUCCESS",o[o.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",o[o.PARAMS_ERROR=50001]="PARAMS_ERROR",o[o.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",o[o.NOT_IN_ROOM=50003]="NOT_IN_ROOM",o[o.SERVICE_INVALID=50004]="SERVICE_INVALID",o[o.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",o[o.SIGNAL_ERROR=53001]="SIGNAL_ERROR",o[o.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",o[o.REQUEST_FAILED=53004]="REQUEST_FAILED",o[o.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",o[o.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",o[o.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",o[o.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",o[o.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",o[o.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",o[o.PERMISSION_DENIED=53012]="PERMISSION_DENIED",o[o.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",o[o.INVALID_TAGS=53014]="INVALID_TAGS",o[o.INVALID_USER_ID=53015]="INVALID_USER_ID",o[o.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",o[o.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",o[o.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",o[o.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",o[o.TRACK_NOT_READY=53020]="TRACK_NOT_READY",o[o.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",o[o.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",o[o.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",o[o.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",o[o.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",o[o.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",o[o.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",o[o.SIGNAL_JOIN_RTC_ROOM_REFUSED=53028]="SIGNAL_JOIN_RTC_ROOM_REFUSED",o[o.NO_PERMISSION_TO_USE_REQUESTED_DEVICE=53029]="NO_PERMISSION_TO_USE_REQUESTED_DEVICE",o[o.THE_FUNCTION_IS_DISABLED_IN_PKROOM=53030]="THE_FUNCTION_IS_DISABLED_IN_PKROOM",o[o.SOME_TRACKS_PUBLISH_FAILED=53031]="SOME_TRACKS_PUBLISH_FAILED",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_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_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"}(i||(i={})),function(e){e.FAILED="fail",e.SUCCESSED="success",e.TIMEOUT="timeout",e.INFO="info"}(s||(s={}));let n=!0,a=!0;function c(e,t,r){const o=e.match(t);return o&&o.length>=r&&parseInt(o[r],10)}function d(e,t,r){if(!e.RTCPeerConnection)return;const o=e.RTCPeerConnection.prototype,i=o.addEventListener;o.addEventListener=function(e,o){if(e!==t)return i.apply(this,arguments);const s=e=>{const t=r(e);t&&(o.handleEvent?o.handleEvent(t):o(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(o,s),i.apply(this,[e,s])};const s=o.removeEventListener;o.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const o=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,o])},Object.defineProperty(o,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function _(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(n=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function u(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(a=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function l(){if("object"==typeof window){if(n)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function R(e,t){a&&console.warn(e+" is deprecated, please use "+t+" instead.")}function C(e){return"[object Object]"===Object.prototype.toString.call(e)}function p(e){return C(e)?Object.keys(e).reduce((function(t,r){const o=C(e[r]),i=o?p(e[r]):e[r],s=o&&!Object.keys(i).length;return void 0===i||s?t:Object.assign(t,{[r]:i})}),{}):e}function h(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((o=>{o.endsWith("Id")?h(e,e.get(t[o]),r):o.endsWith("Ids")&&t[o].forEach((t=>{h(e,e.get(t),r)}))})))}function T(e,t,r){const o=r?"outbound-rtp":"inbound-rtp",i=new Map;if(null===t)return i;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===o&&r.trackId===t.id&&h(e,r,i)}))})),i}const g=l;function m(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const o=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const o="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==o.exact&&"number"==typeof o.exact&&(o.min=o.max=o.exact);const i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==o.ideal){t.optional=t.optional||[];let e={};"number"==typeof o.ideal?(e[i("min",r)]=o.ideal,t.optional.push(e),e={},e[i("max",r)]=o.ideal,t.optional.push(e)):(e[i("",r)]=o.ideal,t.optional.push(e))}void 0!==o.exact&&"number"!=typeof o.exact?(t.mandatory=t.mandatory||{},t.mandatory[i("",r)]=o.exact):["min","max"].forEach((e=>{void 0!==o[e]&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,r)]=o[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=o(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const n=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||n)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{let n=(r=r.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!n&&r.length&&t.includes("back")&&(n=r[r.length-1]),n&&(e.video.deviceId=s.exact?{exact:n.deviceId}:{ideal:n.deviceId}),e.video=o(e.video),g("chrome: "+JSON.stringify(e)),i(e)}))}e.video=o(e.video)}return g("chrome: "+JSON.stringify(e)),i(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,o){i(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{o&&o(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return i(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function E(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function S(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(r=>{let o;o=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const i=new Event("track");i.track=r.track,i.receiver=o,i.transceiver={receiver:o},i.streams=[t.stream],this.dispatchEvent(i)})),t.stream.getTracks().forEach((r=>{let o;o=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const i=new Event("track");i.track=r,i.receiver=o,i.transceiver={receiver:o},i.streams=[t.stream],this.dispatchEvent(i)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else d(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function I(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,o){let i=r.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};const o=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){o.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const o=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],o.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function f(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,o]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const i=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const o=function(e){r(s(i(e)))};return t.apply(this,[o,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(s(i(t)))},r])})).then(r,o)}}function L(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>T(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}),d(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>T(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,o;return this.getSenders().forEach((r=>{r.track===e&&(t?o=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?o=!0:r=t),t.track===e))),o||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function O(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const o=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(o)&&this._shimmedLocalStreams[r.id].push(o):this._shimmedLocalStreams[r.id]=[r,o],o};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();r.apply(this,arguments);const o=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(o)};const o=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],o.apply(this,arguments)};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),i.apply(this,arguments)}}function v(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return O(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const o=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}o.apply(this,[t])};const i=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const o=e._reverseStreams[t],i=e._streams[o.id];r=r.replace(new RegExp(i.id,"g"),o.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function n(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const o=e._reverseStreams[t],i=e._streams[o.id];r=r.replace(new RegExp(o.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const o=[].slice.call(arguments,1);if(1!==o.length||!o[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const i=this.getSenders().find((e=>e.track===t));if(i)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[r.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const o=new e.MediaStream([t]);this._streams[r.id]=o,this._reverseStreams[o.id]=r,this.addStream(o)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],o={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=o[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=n(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=c.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function A(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],o={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=o[t]}))}function N(e,t){d(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var D=Object.freeze({__proto__:null,shimMediaStream:E,shimOnTrack:S,shimGetSendersWithDtmf:I,shimGetStats:f,shimSenderReceiverGetStats:L,shimAddTrackRemoveTrackWithNative:O,shimAddTrackRemoveTrack:v,shimPeerConnection:A,fixNegotiationNeeded:N,shimGetUserMedia:m,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const o=r.video&&r.video.width,i=r.video&&r.video.height,s=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},o&&(r.video.mandatory.maxWidth=o),i&&(r.video.mandatory.maxHeight=i),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});var y,P,k=(y=function(e){var t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},t.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},t.getDescription=function(e){var r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){var r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((function(e){return 0===e.indexOf(r)}))},t.parseCandidate=function(e){for(var t,r={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},o=8;o<t.length;o+=2)switch(t[o]){case"raddr":r.relatedAddress=t[o+1];break;case"rport":r.relatedPort=parseInt(t[o+1],10);break;case"tcptype":r.tcpType=t[o+1];break;case"ufrag":r.ufrag=t[o+1],r.usernameFragment=t[o+1];break;default:r[t[o]]=t[o+1]}return r},t.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substr(14).split(" ")},t.parseRtpMap=function(e){var t=e.substr(9).split(" "),r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){for(var t,r={},o=e.substr(e.indexOf(" ")+1).split(";"),i=0;i<o.length;i++)r[(t=o[i].trim().split("="))[0].trim()]=t[1];return r},t.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var o=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?o.push(t+"="+e.parameters[t]):o.push(t)})),t+="a=fmtp:"+r+" "+o.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){var t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},o=e.indexOf(":",t);return o>-1?(r.attribute=e.substr(t+1,o-t-1),r.value=e.substr(o+1)):r.attribute=e.substr(t+1),r},t.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},t.getMid=function(e){var r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substr(6)},t.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){var r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){var t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;var t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){var o=t.matchPrefix(e+r,"a=ice-ufrag:")[0],i=t.matchPrefix(e+r,"a=ice-pwd:")[0];return o&&i?{usernameFragment:o.substr(12),password:i.substr(10)}:null},t.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},t.parseRtpParameters=function(e){for(var r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},o=t.splitLines(e)[0].split(" "),i=3;i<o.length;i++){var s=o[i],n=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(n){var a=t.parseRtpMap(n),c=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(a.parameters=c.length?t.parseFmtp(c[0]):{},a.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(a.name.toUpperCase())}}}return t.matchPrefix(e,"a=extmap:").forEach((function(e){r.headerExtensions.push(t.parseExtmap(e))})),r},t.writeRtpDescription=function(e,r){var o="";o+="m="+e+" ",o+=r.codecs.length>0?"9":"0",o+=" UDP/TLS/RTP/SAVPF ",o+=r.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",o+="c=IN IP4 0.0.0.0\r\n",o+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((function(e){o+=t.writeRtpMap(e),o+=t.writeFmtp(e),o+=t.writeRtcpFb(e)}));var i=0;return r.codecs.forEach((function(e){e.maxptime>i&&(i=e.maxptime)})),i>0&&(o+="a=maxptime:"+i+"\r\n"),o+="a=rtcp-mux\r\n",r.headerExtensions&&r.headerExtensions.forEach((function(e){o+=t.writeExtmap(e)})),o},t.parseRtpEncodingParameters=function(e){var r,o=[],i=t.parseRtpParameters(e),s=-1!==i.fecMechanisms.indexOf("RED"),n=-1!==i.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute})),c=a.length>0&&a[0].ssrc,d=t.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));d.length>0&&d[0].length>1&&d[0][0]===c&&(r=d[0][1]),i.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&r&&(t.rtx={ssrc:r}),o.push(t),s&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:n?"red+ulpfec":"red"},o.push(t))}})),0===o.length&&c&&o.push({ssrc:c});var _=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,o.forEach((function(e){e.maxBitrate=_}))),o},t.parseRtcpParameters=function(e){var r={},o=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];o&&(r.cname=o.value,r.ssrc=o.ssrc);var i=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=i.length>0,r.compound=0===i.length;var s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.parseMsid=function(e){var r,o=t.matchPrefix(e,"a=msid:");if(1===o.length)return{stream:(r=o[0].substr(7).split(" "))[0],track:r[1]};var i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return i.length>0?{stream:(r=i[0].value.split(" "))[0],track:r[1]}:void 0},t.parseSctpDescription=function(e){var r,o=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");i.length>0&&(r=parseInt(i[0].substr(19),10)),isNaN(r)&&(r=65536);var s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substr(12),10),protocol:o.fmt,maxMessageSize:r};if(t.matchPrefix(e,"a=sctpmap:").length>0){var n=t.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(n[0],10),protocol:n[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){var r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,r,o){var i=void 0!==r?r:2;return"v=0\r\no="+(o||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+i+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,r,o,i){var s=t.writeRtpDescription(e.kind,r);if(s+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===o?"actpass":"active"),s+="a=mid:"+e.mid+"\r\n",e.direction?s+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var n="msid:"+i.id+" "+e.rtpSender.track.id+"\r\n";s+="a="+n,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+n,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+n,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+t.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+t.localCName+"\r\n"),s},t.getDirection=function(e,r){for(var o=t.splitLines(e),i=0;i<o.length;i++)switch(o[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return o[i].substr(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substr(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){var r=t.splitLines(e)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){var r=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var r=t.splitLines(e),o=0;o<r.length;o++)if(r[o].length<2||"="!==r[o].charAt(1))return!1;return!0},e.exports=t},y(P={exports:{}},P.exports),P.exports);function U(e,t,r,o,i){var s=k.writeRtpDescription(e.kind,t);if(s+=k.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=k.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":i||"active"),s+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var n=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=n;var a="msid:"+(o?o.id:"-")+" "+n+"\r\n";s+="a="+a,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+k.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+k.localCName+"\r\n"),s}function M(e,t){var r={codecs:[],headerExtensions:[],fecMechanisms:[]},o=function(e,t){e=parseInt(e,10);for(var r=0;r<t.length;r++)if(t[r].payloadType===e||t[r].preferredPayloadType===e)return t[r]},i=function(e,t,r,i){var s=o(e.parameters.apt,r),n=o(t.parameters.apt,i);return s&&n&&s.name.toLowerCase()===n.name.toLowerCase()};return e.codecs.forEach((function(o){for(var s=0;s<t.codecs.length;s++){var n=t.codecs[s];if(o.name.toLowerCase()===n.name.toLowerCase()&&o.clockRate===n.clockRate){if("rtx"===o.name.toLowerCase()&&o.parameters&&n.parameters.apt&&!i(o,n,e.codecs,t.codecs))continue;(n=JSON.parse(JSON.stringify(n))).numChannels=Math.min(o.numChannels,n.numChannels),r.codecs.push(n),n.rtcpFeedback=n.rtcpFeedback.filter((function(e){for(var t=0;t<o.rtcpFeedback.length;t++)if(o.rtcpFeedback[t].type===e.type&&o.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var o=0;o<t.headerExtensions.length;o++){var i=t.headerExtensions[o];if(e.uri===i.uri){r.headerExtensions.push(i);break}}})),r}function b(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 x(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 B(e,t){var r=new Error(t);return r.name=e,r.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[e],r}var w=function(e,t){function r(t,r){r.addTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function o(t,r,o,i){var s=new Event("track");s.track=r,s.receiver=o,s.transceiver={receiver:o},s.streams=i,e.setTimeout((function(){t._dispatchEvent("track",s)}))}var i=function(r){var o=this,i=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){o[e]=i[e].bind(i)})),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",r=JSON.parse(JSON.stringify(r||{})),this.usingBundle="max-bundle"===r.bundlePolicy,"negotiate"===r.rtcpMuxPolicy)throw B("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var o=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var i="string"==typeof o;return i&&(o=[o]),o=o.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||r?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(r=!0,!0)})),delete e.url,e.urls=i?o[0]:o,!!o.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var s=r.iceCandidatePoolSize;s>0;s--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=k.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(i.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(i.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),i.prototype.onicecandidate=null,i.prototype.onaddstream=null,i.prototype.ontrack=null,i.prototype.onremovestream=null,i.prototype.onsignalingstatechange=null,i.prototype.oniceconnectionstatechange=null,i.prototype.onconnectionstatechange=null,i.prototype.onicegatheringstatechange=null,i.prototype.onnegotiationneeded=null,i.prototype.ondatachannel=null,i.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},i.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},i.prototype.getConfiguration=function(){return this._config},i.prototype.getLocalStreams=function(){return this.localStreams},i.prototype.getRemoteStreams=function(){return this.remoteStreams},i.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,o={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&r)o.iceTransport=this.transceivers[0].iceTransport,o.dtlsTransport=this.transceivers[0].dtlsTransport;else{var i=this._createIceAndDtlsTransports();o.iceTransport=i.iceTransport,o.dtlsTransport=i.dtlsTransport}return t||this.transceivers.push(o),o},i.prototype.addTrack=function(t,r){if(this._isClosed)throw B("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var o;if(this.transceivers.find((function(e){return e.track===t})))throw B("InvalidAccessError","Track already exists.");for(var i=0;i<this.transceivers.length;i++)this.transceivers[i].track||this.transceivers[i].kind!==t.kind||(o=this.transceivers[i]);return o||(o=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),o.track=t,o.stream=r,o.rtpSender=new e.RTCRtpSender(t,o.dtlsTransport),o.rtpSender},i.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var o=e.clone();e.getTracks().forEach((function(e,t){var r=o.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),o.getTracks().forEach((function(e){r.addTrack(e,o)}))}},i.prototype.removeTrack=function(t){if(this._isClosed)throw B("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 B("InvalidAccessError","Sender was not created by this connection.");var o=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(o)&&this.localStreams.indexOf(o)>-1&&this.localStreams.splice(this.localStreams.indexOf(o),1),this._maybeFireNegotiationNeeded()},i.prototype.removeStream=function(e){var t=this;e.getTracks().forEach((function(e){var r=t.getSenders().find((function(t){return t.track===e}));r&&t.removeTrack(r)}))},i.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},i.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},i.prototype._createIceGatherer=function(t,r){var o=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var i=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(i,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(e){var r=!e.candidate||0===Object.keys(e.candidate).length;i.state=r?"completed":"gathering",null!==o.transceivers[t].bufferedCandidateEvents&&o.transceivers[t].bufferedCandidateEvents.push(e)},i.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),i},i.prototype._gather=function(t,r){var o=this,i=this.transceivers[r].iceGatherer;if(!i.onlocalcandidate){var s=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,i.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),i.onlocalcandidate=function(e){if(!(o.usingBundle&&r>0)){var s=new Event("icecandidate");s.candidate={sdpMid:t,sdpMLineIndex:r};var n=e.candidate,a=!n||0===Object.keys(n).length;if(a)"new"!==i.state&&"gathering"!==i.state||(i.state="completed");else{"new"===i.state&&(i.state="gathering"),n.component=1,n.ufrag=i.getLocalParameters().usernameFragment;var c=k.writeCandidate(n);s.candidate=Object.assign(s.candidate,k.parseCandidate(c)),s.candidate.candidate=c,s.candidate.toJSON=function(){return{candidate:s.candidate.candidate,sdpMid:s.candidate.sdpMid,sdpMLineIndex:s.candidate.sdpMLineIndex,usernameFragment:s.candidate.usernameFragment}}}var d=k.getMediaSections(o._localDescription.sdp);d[s.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",o._localDescription.sdp=k.getDescription(o._localDescription.sdp)+d.join("");var _=o.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==o.iceGatheringState&&(o.iceGatheringState="gathering",o._emitGatheringStateChange()),a||o._dispatchEvent("icecandidate",s),_&&(o._dispatchEvent("icecandidate",new Event("icecandidate")),o.iceGatheringState="complete",o._emitGatheringStateChange())}},e.setTimeout((function(){s.forEach((function(e){i.onlocalcandidate(e)}))}),0)}},i.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var o=new e.RTCDtlsTransport(r);return o.ondtlsstatechange=function(){t._updateConnectionState()},o.onerror=function(){Object.defineProperty(o,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:o}},i.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var r=this.transceivers[e].iceTransport;r&&(delete r.onicestatechange,delete this.transceivers[e].iceTransport);var o=this.transceivers[e].dtlsTransport;o&&(delete o.ondtlsstatechange,delete o.onerror,delete this.transceivers[e].dtlsTransport)},i.prototype._transceive=function(e,r,o){var i=M(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(i.encodings=e.sendEncodingParameters,i.rtcp={cname:k.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(i.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(i)),o&&e.rtpReceiver&&i.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?i.encodings=e.recvEncodingParameters:i.encodings=[{}],i.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(i.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(i.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(i))},i.prototype.setLocalDescription=function(e){var t,r,o=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(B("TypeError",'Unsupported type "'+e.type+'"'));if(!b("setLocalDescription",e.type,o.signalingState)||o._isClosed)return Promise.reject(B("InvalidStateError","Can not set local "+e.type+" in state "+o.signalingState));if("offer"===e.type)t=k.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=k.parseRtpParameters(e);o.transceivers[t].localCapabilities=r})),o.transceivers.forEach((function(e,t){o._gather(e.mid,t)}));else if("answer"===e.type){t=k.splitSections(o._remoteDescription.sdp),r=t.shift();var i=k.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var s=o.transceivers[t],n=s.iceGatherer,a=s.iceTransport,c=s.dtlsTransport,d=s.localCapabilities,_=s.remoteCapabilities;if(!(k.isRejected(e)&&0===k.matchPrefix(e,"a=bundle-only").length)&&!s.rejected){var u=k.getIceParameters(e,r),l=k.getDtlsParameters(e,r);i&&(l.role="server"),o.usingBundle&&0!==t||(o._gather(s.mid,t),"new"===a.state&&a.start(n,u,i?"controlling":"controlled"),"new"===c.state&&c.start(l));var R=M(d,_);o._transceive(s,R.codecs.length>0,!1)}}))}return o._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?o._updateSignalingState("have-local-offer"):o._updateSignalingState("stable"),Promise.resolve()},i.prototype.setRemoteDescription=function(i){var s=this;if(-1===["offer","answer"].indexOf(i.type))return Promise.reject(B("TypeError",'Unsupported type "'+i.type+'"'));if(!b("setRemoteDescription",i.type,s.signalingState)||s._isClosed)return Promise.reject(B("InvalidStateError","Can not set remote "+i.type+" in state "+s.signalingState));var n={};s.remoteStreams.forEach((function(e){n[e.id]=e}));var a=[],c=k.splitSections(i.sdp),d=c.shift(),_=k.matchPrefix(d,"a=ice-lite").length>0,u=k.matchPrefix(d,"a=group:BUNDLE ").length>0;s.usingBundle=u;var l=k.matchPrefix(d,"a=ice-options:")[0];return s.canTrickleIceCandidates=!!l&&l.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(o,c){var l=k.splitLines(o),R=k.getKind(o),C=k.isRejected(o)&&0===k.matchPrefix(o,"a=bundle-only").length,p=l[0].substr(2).split(" ")[2],h=k.getDirection(o,d),T=k.parseMsid(o),g=k.getMid(o)||k.generateIdentifier();if(C||"application"===R&&("DTLS/SCTP"===p||"UDP/DTLS/SCTP"===p))s.transceivers[c]={mid:g,kind:R,protocol:p,rejected:!0};else{var m,E,S,I,f,L,O,v,A;!C&&s.transceivers[c]&&s.transceivers[c].rejected&&(s.transceivers[c]=s._createTransceiver(R,!0));var N,D,y=k.parseRtpParameters(o);C||(N=k.getIceParameters(o,d),(D=k.getDtlsParameters(o,d)).role="client"),O=k.parseRtpEncodingParameters(o);var P=k.parseRtcpParameters(o),U=k.matchPrefix(o,"a=end-of-candidates",d).length>0,b=k.matchPrefix(o,"a=candidate:").map((function(e){return k.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===i.type||"answer"===i.type)&&!C&&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"!==i.type||C){if("answer"===i.type&&!C){E=(m=s.transceivers[c]).iceGatherer,S=m.iceTransport,I=m.dtlsTransport,f=m.rtpReceiver,L=m.sendEncodingParameters,v=m.localCapabilities,s.transceivers[c].recvEncodingParameters=O,s.transceivers[c].remoteCapabilities=y,s.transceivers[c].rtcpParameters=P,b.length&&"new"===S.state&&(!_&&!U||u&&0!==c?b.forEach((function(e){x(m.iceTransport,e)})):S.setRemoteCandidates(b)),u&&0!==c||("new"===S.state&&S.start(E,N,"controlling"),"new"===I.state&&I.start(D)),!M(m.localCapabilities,m.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&m.sendEncodingParameters[0].rtx&&delete m.sendEncodingParameters[0].rtx,s._transceive(m,"sendrecv"===h||"recvonly"===h,"sendrecv"===h||"sendonly"===h),!f||"sendrecv"!==h&&"sendonly"!==h?delete m.rtpReceiver:(A=f.track,T?(n[T.stream]||(n[T.stream]=new e.MediaStream),r(A,n[T.stream]),a.push([A,f,n[T.stream]])):(n.default||(n.default=new e.MediaStream),r(A,n.default),a.push([A,f,n.default])))}}else{(m=s.transceivers[c]||s._createTransceiver(R)).mid=g,m.iceGatherer||(m.iceGatherer=s._createIceGatherer(c,u)),b.length&&"new"===m.iceTransport.state&&(!U||u&&0!==c?b.forEach((function(e){x(m.iceTransport,e)})):m.iceTransport.setRemoteCandidates(b)),v=e.RTCRtpReceiver.getCapabilities(R),t<15019&&(v.codecs=v.codecs.filter((function(e){return"rtx"!==e.name}))),L=m.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var B,w=!1;if("sendrecv"===h||"sendonly"===h){if(w=!m.rtpReceiver,f=m.rtpReceiver||new e.RTCRtpReceiver(m.dtlsTransport,R),w)A=f.track,T&&"-"===T.stream||(T?(n[T.stream]||(n[T.stream]=new e.MediaStream,Object.defineProperty(n[T.stream],"id",{get:function(){return T.stream}})),Object.defineProperty(A,"id",{get:function(){return T.track}}),B=n[T.stream]):(n.default||(n.default=new e.MediaStream),B=n.default)),B&&(r(A,B),m.associatedRemoteMediaStreams.push(B)),a.push([A,f,B])}else m.rtpReceiver&&m.rtpReceiver.track&&(m.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===m.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),m.associatedRemoteMediaStreams=[]);m.localCapabilities=v,m.remoteCapabilities=y,m.rtpReceiver=f,m.rtcpParameters=P,m.sendEncodingParameters=L,m.recvEncodingParameters=O,s._transceive(s.transceivers[c],!1,w)}}})),void 0===s._dtlsRole&&(s._dtlsRole="offer"===i.type?"active":"passive"),s._remoteDescription={type:i.type,sdp:i.sdp},"offer"===i.type?s._updateSignalingState("have-remote-offer"):s._updateSignalingState("stable"),Object.keys(n).forEach((function(t){var r=n[t];if(r.getTracks().length){if(-1===s.remoteStreams.indexOf(r)){s.remoteStreams.push(r);var i=new Event("addstream");i.stream=r,e.setTimeout((function(){s._dispatchEvent("addstream",i)}))}a.forEach((function(e){var t=e[0],i=e[1];r.id===e[2].id&&o(s,t,i,[r])}))}})),a.forEach((function(e){e[2]||o(s,e[0],e[1],[])})),e.setTimeout((function(){s&&s.transceivers&&s.transceivers.forEach((function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},i.prototype.close=function(){this.transceivers.forEach((function(e){e.iceTransport&&e.iceTransport.stop(),e.dtlsTransport&&e.dtlsTransport.stop(),e.rtpSender&&e.rtpSender.stop(),e.rtpReceiver&&e.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},i.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},i.prototype._maybeFireNegotiationNeeded=function(){var t=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,e.setTimeout((function(){if(t.needNegotiation){t.needNegotiation=!1;var e=new Event("negotiationneeded");t._dispatchEvent("negotiationneeded",e)}}),0))},i.prototype._updateIceConnectionState=function(){var e,t={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&!e.rejected&&t[e.iceTransport.state]++})),e="new",t.failed>0?e="failed":t.checking>0?e="checking":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0?e="connected":t.completed>0&&(e="completed"),e!==this.iceConnectionState){this.iceConnectionState=e;var r=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",r)}},i.prototype._updateConnectionState=function(){var e,t={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&e.dtlsTransport&&!e.rejected&&(t[e.iceTransport.state]++,t[e.dtlsTransport.state]++)})),t.connected+=t.completed,e="new",t.failed>0?e="failed":t.connecting>0?e="connecting":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0&&(e="connected"),e!==this.connectionState){this.connectionState=e;var r=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",r)}},i.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(B("InvalidStateError","Can not call createOffer after close"));var o=r.transceivers.filter((function(e){return"audio"===e.kind})).length,i=r.transceivers.filter((function(e){return"video"===e.kind})).length,s=arguments[0];if(s){if(s.mandatory||s.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==s.offerToReceiveAudio&&(o=!0===s.offerToReceiveAudio?1:!1===s.offerToReceiveAudio?0:s.offerToReceiveAudio),void 0!==s.offerToReceiveVideo&&(i=!0===s.offerToReceiveVideo?1:!1===s.offerToReceiveVideo?0:s.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--o<0&&(e.wantReceive=!1):"video"===e.kind&&--i<0&&(e.wantReceive=!1)}));o>0||i>0;)o>0&&(r._createTransceiver("audio"),o--),i>0&&(r._createTransceiver("video"),i--);var n=k.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(o,i){var s=o.track,n=o.kind,a=o.mid||k.generateIdentifier();o.mid=a,o.iceGatherer||(o.iceGatherer=r._createIceGatherer(i,r.usingBundle));var c=e.RTCRtpSender.getCapabilities(n);t<15019&&(c.codecs=c.codecs.filter((function(e){return"rtx"!==e.name}))),c.codecs.forEach((function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1"),o.remoteCapabilities&&o.remoteCapabilities.codecs&&o.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(o.remoteCapabilities&&o.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=o.sendEncodingParameters||[{ssrc:1001*(2*i+1)}];s&&t>=15019&&"video"===n&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),o.wantReceive&&(o.rtpReceiver=new e.RTCRtpReceiver(o.dtlsTransport,n)),o.localCapabilities=c,o.sendEncodingParameters=d})),"max-compat"!==r._config.bundlePolicy&&(n+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),n+="a=ice-options:trickle\r\n",r.transceivers.forEach((function(e,t){n+=U(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="+k.writeCandidate(e)+"\r\n"})),"completed"===e.iceGatherer.state&&(n+="a=end-of-candidates\r\n"))}));var a=new e.RTCSessionDescription({type:"offer",sdp:n});return Promise.resolve(a)},i.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(B("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(B("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var o=k.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.usingBundle&&(o+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),o+="a=ice-options:trickle\r\n";var i=k.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,s){if(!(s+1>i)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?o+="m=application 0 DTLS/SCTP 5000\r\n":o+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?o+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(o+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(o+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var n;if(e.stream)"audio"===e.kind?n=e.stream.getAudioTracks()[0]:"video"===e.kind&&(n=e.stream.getVideoTracks()[0]),n&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1});var a=M(e.localCapabilities,e.remoteCapabilities);!a.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,o+=U(e,a,"answer",e.stream,r._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(o+="a=rtcp-rsize\r\n")}}));var s=new e.RTCSessionDescription({type:"answer",sdp:o});return Promise.resolve(s)},i.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(o,i){if(!r._remoteDescription)return i(B("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var s=e.sdpMLineIndex;if(e.sdpMid)for(var n=0;n<r.transceivers.length;n++)if(r.transceivers[n].mid===e.sdpMid){s=n;break}var a=r.transceivers[s];if(!a)return i(B("OperationError","Can not add ICE candidate"));if(a.rejected)return o();var c=Object.keys(e.candidate).length>0?k.parseCandidate(e.candidate):{};if("tcp"===c.protocol&&(0===c.port||9===c.port))return o();if(c.component&&1!==c.component)return o();if((0===s||s>0&&a.iceTransport!==r.transceivers[0].iceTransport)&&!x(a.iceTransport,c))return i(B("OperationError","Can not add ICE candidate"));var d=e.candidate.trim();0===d.indexOf("a=")&&(d=d.substr(2)),(t=k.getMediaSections(r._remoteDescription.sdp))[s]+="a="+(c.type?d:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=k.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var _=0;_<r.transceivers.length&&(r.transceivers[_].rejected||(r.transceivers[_].iceTransport.addRemoteCandidate({}),(t=k.getMediaSections(r._remoteDescription.sdp))[_]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=k.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));_++);o()}))},i.prototype.getStats=function(t){if(t&&t instanceof e.MediaStreamTrack){var r=null;if(this.transceivers.forEach((function(e){e.rtpSender&&e.rtpSender.track===t?r=e.rtpSender:e.rtpReceiver&&e.rtpReceiver.track===t&&(r=e.rtpReceiver)})),!r)throw B("InvalidAccessError","Invalid selector.");return r.getStats()}var o=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&o.push(e[t].getStats())}))})),Promise.all(o).then((function(e){var t=new Map;return e.forEach((function(e){e.forEach((function(e){t.set(e.id,e)}))})),t}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(t){var r=e[t];if(r&&r.prototype&&r.prototype.getStats){var o=r.prototype.getStats;r.prototype.getStats=function(){return o.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var o;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(o=e[r]).type]||o.type,t.set(r,e[r])})),t}))}}}));var s=["createOffer","createAnswer"];return s.forEach((function(e){var t=i.prototype[e];i.prototype[e]=function(){var e=arguments;return"function"==typeof e[0]||"function"==typeof e[1]?t.apply(this,[arguments[2]]).then((function(t){"function"==typeof e[0]&&e[0].apply(null,[t])}),(function(t){"function"==typeof e[1]&&e[1].apply(null,[t])})):t.apply(this,arguments)}})),(s=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=i.prototype[e];i.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]||"function"==typeof e[2]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)}),(function(t){"function"==typeof e[2]&&e[2].apply(null,[t])})):t.apply(this,arguments)}})),["getStats"].forEach((function(e){var t=i.prototype[e];i.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)})):t.apply(this,arguments)}})),i};function V(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 F(e){"getDisplayMedia"in e.navigator&&e.navigator.mediaDevices&&(e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=e.navigator.getDisplayMedia.bind(e.navigator)))}function $(e,t){if(e.RTCIceGatherer&&(e.RTCIceCandidate||(e.RTCIceCandidate=function(e){return e}),e.RTCSessionDescription||(e.RTCSessionDescription=function(e){return e}),t.version<15025)){const t=Object.getOwnPropertyDescriptor(e.MediaStreamTrack.prototype,"enabled");Object.defineProperty(e.MediaStreamTrack.prototype,"enabled",{set(e){t.set.call(this,e);const r=new Event("enabled");r.enabled=e,this.dispatchEvent(r)}})}e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)&&Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new e.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),e.RTCDtmfSender&&!e.RTCDTMFSender&&(e.RTCDTMFSender=e.RTCDtmfSender);const r=w(e,t.version);e.RTCPeerConnection=function(e){return e&&e.iceServers&&(e.iceServers=function(e,t){let r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((e=>{if(e&&(e.urls||e.url)){let t=e.urls||e.url;e.url&&!e.urls&&R("RTCIceServer.url","RTCIceServer.urls");const o="string"==typeof t;return o&&(t=[t]),t=t.filter((e=>{if(0===e.indexOf("stun:"))return!1;const t=e.startsWith("turn")&&!e.startsWith("turn:[")&&e.includes("transport=udp");return t&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=o?t[0]:t,!!t.length}}))}(e.iceServers,t.version),l("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype}function G(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var K=Object.freeze({__proto__:null,shimPeerConnection:$,shimReplaceTrack:G,shimGetUserMedia:V,shimGetDisplayMedia:F});function H(e,t){const r=e&&e.navigator,o=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,o){R("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,o)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},o&&o.prototype.getSettings){const t=o.prototype.getSettings;o.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(o&&o.prototype.applyConstraints){const t=o.prototype.applyConstraints;o.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function j(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function J(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],o={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=o[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},o=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,s]=arguments;return o.apply(this,[e||null]).then((e=>{if(t.version<53&&!i)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,o)=>{e.set(o,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(i,s)}}function Y(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function q(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),d(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function W(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){R("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function z(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Q(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],r=e&&"sendEncodings"in e;r&&e.sendEncodings.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const o=t.apply(this,arguments);if(r){const{sender:t}=o,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return o})}function Z(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function X(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 ee(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 te=Object.freeze({__proto__:null,shimOnTrack:j,shimPeerConnection:J,shimSenderGetStats:Y,shimReceiverGetStats:q,shimRemoveStream:W,shimRTCDataChannel:z,shimAddTransceiver:Q,shimGetParameters:Z,shimCreateOffer:X,shimCreateAnswer:ee,shimGetUserMedia:H,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 re(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function oe(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function ie(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,o=t.createAnswer,i=t.setLocalDescription,s=t.setRemoteDescription,n=t.addIceCandidate;t.createOffer=function(e,t){const o=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[o]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],i=o.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i};let a=function(e,t,r){const o=i.apply(this,[e]);return r?(o.then(t,r),Promise.resolve()):o};t.setLocalDescription=a,a=function(e,t,r){const o=s.apply(this,[e]);return r?(o.then(t,r),Promise.resolve()):o},t.setRemoteDescription=a,a=function(e,t,r){const o=n.apply(this,[e]);return r?(o.then(t,r),Promise.resolve()):o},t.addIceCandidate=a}function se(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,o){t.mediaDevices.getUserMedia(e).then(r,o)}.bind(t))}function ne(e){return e&&void 0!==e.video?Object.assign({},e,{video:p(e.video)}):e}function ae(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let o=e.iceServers[r];!o.hasOwnProperty("urls")&&o.hasOwnProperty("url")?(R("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,t.push(o)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function ce(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 de(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 _e(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ue=Object.freeze({__proto__:null,shimLocalStreamsAPI:re,shimRemoteStreamsAPI:oe,shimCallbacksAPI:ie,shimGetUserMedia:se,shimConstraints:ne,shimRTCIceServerUrls:ae,shimTrackEventTransceiver:ce,shimCreateOfferLegacy:de,shimAudioContext:_e});function le(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const r=new t(e),o=k.parseCandidate(e.candidate),i=Object.assign(r,o);return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,d(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Re(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=k.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=k.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},o=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r},i=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r},s=function(e,r){let o=65536;"firefox"===t.browser&&57===t.version&&(o=65535);const i=k.matchPrefix(e.sdp,"a=max-message-size:");return i.length>0?o=parseInt(i[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(o=2147483637),o},n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){const e=o(arguments[0]),t=i(e),r=s(arguments[0],e);let n;n=0===t&&0===r?Number.POSITIVE_INFINITY:0===t||0===r?Math.max(t,r):Math.min(t,r);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>n}),this._sctp=a}return n.apply(this,arguments)}}function Ce(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const o=arguments[0],i=o.length||o.size||o.byteLength;if("open"===e.readyState&&t.sctp&&i>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},d(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function pe(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function he(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function Te(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 ge=Object.freeze({__proto__:null,shimRTCIceCandidate:le,shimMaxMessageSize:Re,shimSendThrowTypeError:Ce,shimConnectionState:pe,removeExtmapAllowMixed:he,shimAddIceCandidateNullOrEmpty:Te});const me=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=l,o=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=c(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=c(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=c(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=c(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),i={browserDetails:o,commonShim:ge,extractVersion:c,disableLog:_,disableWarnings:u};switch(o.browser){case"chrome":if(!D||!A||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),i;if(null===o.version)return r("Chrome shim can not determine version, not shimming."),i;r("adapter.js shimming chrome."),i.browserShim=D,Te(e,o),m(e,o),E(e),A(e,o),S(e),v(e,o),I(e),f(e),L(e),N(e,o),le(e),pe(e),Re(e,o),Ce(e),he(e,o);break;case"firefox":if(!te||!J||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=te,Te(e,o),H(e,o),J(e,o),j(e),W(e),Y(e),q(e),z(e),Q(e),Z(e),X(e),ee(e),le(e),pe(e),Re(e,o),Ce(e);break;case"edge":if(!K||!$||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),i;r("adapter.js shimming edge."),i.browserShim=K,V(e),F(e),$(e,o),G(e),Re(e,o),Ce(e);break;case"safari":if(!ue||!t.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=ue,Te(e,o),ae(e),de(e),ie(e),re(e),oe(e),ce(e),se(e),_e(e),le(e),Re(e,o),Ce(e),he(e,o);break;default:r("Unsupported browser!")}return i}({window:"undefined"==typeof window?void 0:window});var Ee,Se,Ie;exports.RCFrameRate=void 0,(Ee=exports.RCFrameRate||(exports.RCFrameRate={})).FPS_10="FPS_10",Ee.FPS_15="FPS_15",Ee.FPS_24="FPS_24",Ee.FPS_30="FPS_30",exports.RCResolution=void 0,(Se=exports.RCResolution||(exports.RCResolution={})).W176_H132="W176_H132",Se.W176_H144="W176_H144",Se.W256_H144="W256_H144",Se.W320_H180="W320_H180",Se.W240_H240="W240_H240",Se.W320_H240="W320_H240",Se.W480_H360="W480_H360",Se.W640_H360="W640_H360",Se.W480_H480="W480_H480",Se.W640_H480="W640_H480",Se.W720_H480="W720_H480",Se.W1280_H720="W1280_H720",Se.W1920_H1080="W1920_H1080",exports.RCMediaType=void 0,(Ie=exports.RCMediaType||(exports.RCMediaType={}))[Ie.AUDIO_ONLY=0]="AUDIO_ONLY",Ie[Ie.VIDEO_ONLY=1]="VIDEO_ONLY",Ie[Ie.AUDIO_VIDEO=2]="AUDIO_VIDEO";const fe={[exports.RCResolution.W176_H132]:{width:176,height:132,maxBitrate:150,minBitrate:80},[exports.RCResolution.W176_H144]:{width:176,height:144,maxBitrate:160,minBitrate:80},[exports.RCResolution.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[exports.RCResolution.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[exports.RCResolution.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[exports.RCResolution.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[exports.RCResolution.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[exports.RCResolution.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[exports.RCResolution.W480_H480]:{width:480,height:480,maxBitrate:800,minBitrate:180},[exports.RCResolution.W640_H480]:{width:640,height:480,maxBitrate:900,minBitrate:200},[exports.RCResolution.W720_H480]:{width:720,height:480,maxBitrate:1e3,minBitrate:200},[exports.RCResolution.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[exports.RCResolution.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},Le=(e,t)=>{const r=fe[`W${e}_H${t}`];if(r)return r;const o=e*t;return Object.keys(fe).map((e=>fe[e])).sort(((e,t)=>e.height*e.width-t.width*t.height)).filter((e=>e.height*e.width>=o))[0]||fe.W1920_H1080},Oe={10:1,15:1,24:1.5,30:1.5},ve=e=>{let t=Number.MAX_VALUE,r=1;for(const o in Oe){const i=Math.abs(e-parseInt(o));i<t&&(t=i,r=Oe[o])}return r},Ae={getCameras:()=>t(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))})),getMicrophones:()=>t(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))})),getSpeakers:()=>t(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audiooutput"===e.kind))}))};class Ne extends e.EventEmitter{constructor(e,t,r,o,i){super(),this._tag=e,this._userId=t,this._kind=r,this._isLocalTrack=o,this._roomId=i,this._localMuted=!1,this._remoteMuted=!1,this._streamId=[this._userId||this._roomId,this._tag].join("_"),this._id=[this._streamId,this.isAudioTrack()?0:1].join("_")}getStreamId(){return this._streamId}getTrackId(){return this._id}getUserId(){return this._userId}__innerGetMediaStreamTrack(){return this._msTrack}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(){r.info(`set ${this._id} enabled: false`),e.logger.info(i.L_TRACK_MUTE_O,{status:s.SUCCESSED,id:this._id},{logSource:e.LogSource.RTC}),this._setLocalMuted(!0)}unmute(){r.info(`set ${this._id} enabled: true`),e.logger.info(i.L_TRACK_UNMUTE_O,{status:s.SUCCESSED,id:this._id},{logSource:e.LogSource.RTC}),this._setLocalMuted(!1)}isLocalMuted(){return this._localMuted}isMCUTrack(){return Boolean(this._roomId)}isOwnerMuted(){return this._remoteMuted}play(o,n){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_TRACK_PLAY_T,{element:o,options:n},{logSource:e.LogSource.RTC}),!this._msTrack)return r.warn(`the track is not ready to play -> id: ${this._id}`),e.logger.error(i.L_TRACK_PLAY_R,{status:s.FAILED,code:exports.RCRTCCode.TRACK_NOT_READY,msg:`play error -> id: ${this._id}`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&(r.warn(`the track's readyState is 'ended' -> id: ${this._id}`),e.logger.error(i.L_TRACK_PLAY_R,{status:s.FAILED,code:"",msg:`the track's readyState is ended -> id: ${this._id}`},{logSource:e.LogSource.RTC})),null==n?void 0:n.volume){if(!e.isNumber(null==n?void 0:n.volume))return r.error(`${null==n?void 0:n.volume} is not a number, the valid range of options.volume is 0-100`),e.logger.error(i.L_TRACK_PLAY_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> options.volume不是数字"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};(null==n?void 0:n.volume)<0&&(n.volume=0,r.warn("the valid range of options.volume is 0-100, the value of volume has been set 0"),e.logger.warn(i.L_TRACK_PLAY_R,{status:s.FAILED,code:"",msg:"params error -> options.volume < 0"},{logSource:e.LogSource.RTC})),(null==n?void 0:n.volume)>100&&(n.volume=100,r.warn("the valid range of options.volume is 0-100, the value of volume has been set 100"),e.logger.warn(i.L_TRACK_PLAY_R,{status:s.FAILED,code:"",msg:"params error -> options.volume > 100"},{logSource:e.LogSource.RTC}))}if(null==n?void 0:n.audioDeviceId){if(!(yield Ae.getSpeakers()).map((e=>e.deviceId)).includes(n.audioDeviceId))return r.error(`the options.audioDeviceId is invalid --\x3e ${n.audioDeviceId}`),e.logger.error(i.L_TRACK_PLAY_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> options.audioDeviceId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR}}const t=this.isVideoTrack();if(t&&(!o||!(o instanceof HTMLVideoElement||this.__validateVideoNodeName(o))))return r.error(`the video track need an <video> to play -> id: ${this._id}`),e.logger.error(i.L_TRACK_PLAY_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> element不是一个video标签"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.VIDEO_TRACK_MISS_MEDIA_ELEMENT};this._element=t?o:this._element||new Audio,this._localMuted&&this._setLocalMuted(!1),this._element.srcObject&&this._element.srcObject===this._msStream||this._element.pause(),this._element.onloadstart=t=>{var o,n;r.debug(`HTMLMediaElement onloadstart -> id: ${null===(o=t.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`),e.logger.info(i.L_TRACK_PLAY_R,{status:s.INFO,msg:`HTMLMediaElement onloadstart -> id: ${null===(n=t.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:e.LogSource.RTC})},this._element.ondurationchange=t=>{var o,n;r.debug(`HTMLMediaElement ondurationchange -> id: ${null===(o=t.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`),e.logger.info(i.L_TRACK_PLAY_R,{status:s.INFO,msg:`HTMLMediaElement ondurationchange -> id: ${null===(n=t.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:e.LogSource.RTC})},this._element.onloadedmetadata=t=>{var o,n;r.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(o=t.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`),e.logger.info(i.L_TRACK_PLAY_R,{status:s.INFO,msg:`HTMLMediaElement onloadedmetadata -> id: ${null===(n=t.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:e.LogSource.RTC})},this._element.onloadeddata=t=>{var o,n;r.debug(`HTMLMediaElement onloadeddata -> id: ${null===(o=t.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`),e.logger.info(i.L_TRACK_PLAY_R,{status:s.INFO,msg:`HTMLMediaElement onloadeddata -> id: ${null===(n=t.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:e.LogSource.RTC})},this._element.onabort=t=>{var o,n;r.info(`HTMLMediaElement onabort -> id: ${null===(o=t.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`),e.logger.info(i.L_TRACK_PLAY_R,{status:s.INFO,msg:`HTMLMediaElement onabort -> id: ${null===(n=t.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:e.LogSource.RTC})},this._element.oncanplay=t=>{var o,n;r.info(`HTMLMediaElement oncanplay -> id: ${null===(o=t.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`),e.logger.info(i.L_TRACK_PLAY_R,{status:s.INFO,msg:`HTMLMediaElement oncanplay -> id: ${null===(n=t.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:e.LogSource.RTC})},this._element.onvolumechange=t=>{var o,n;const a=Math.floor(100*(null===(o=t.target)||void 0===o?void 0:o.volume));r.info(`HTMLMediaElement onvolumechange -> volume: ${a}, trackId: ${this._id}`),e.logger.info(i.L_TRACK_PLAY_R,{status:s.INFO,msg:`HTMLMediaElement onvolumechange -> id: ${null===(n=t.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:e.LogSource.RTC})},this._element.srcObject=this._msStream,this._element.autoplay=!0,t&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),t||!(null==n?void 0:n.volume)&&0!==(null==n?void 0:n.volume)||(this._element.volume=(null==n?void 0:n.volume)/100);try{(null==n?void 0:n.audioDeviceId)&&!t?yield this._element.setSinkId(n.audioDeviceId):this._element.play()}catch(t){return"No permission to use requested device"===t.message?(r.error(`setSinkId failed -> ${t.message}`),e.logger.error(i.L_TRACK_PLAY_R,{status:s.FAILED,code:exports.RCRTCCode.NO_PERMISSION_TO_USE_REQUESTED_DEVICE,msg:"No permission"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.NO_PERMISSION_TO_USE_REQUESTED_DEVICE}):(r.error(t),e.logger.error(i.L_TRACK_PLAY_R,{status:s.FAILED,code:exports.RCRTCCode.TRACK_PLAY_ERROR,msg:"play error"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.TRACK_PLAY_ERROR})}return e.logger.info(i.L_TRACK_PLAY_R,{status:s.SUCCESSED,element:o,options:n},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.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()}}class De extends Ne{constructor(e,t,r,o){super(e,t,r,!0),this._isPublished=!1,this.__innerSetMediaStreamTrack(o),o.onended=()=>{o.onended=null,this.emit(De.EVENT_LOCAL_TRACK_END,this),this.removeAll(De.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(t){const r=this._localMuted!==t;super._setLocalMuted(t),this._remoteMuted=this._localMuted,r&&this.emit(De.__INNER_EVENT_MUTED_CHANGE__,this),e.logger.info(i.L_LOCAL_TRACK_SET_LOCAL_MUTED_O,{status:s.SUCCESSED,bool:t},{logSource:e.LogSource.RTC})}__innerSetPublished(t){e.logger.info(i.L_LOCAL_TRACK_INNER_SET_PUBLISHED_O,{status:s.SUCCESSED,bool:t},{logSource:e.LogSource.RTC}),this._isPublished=t}isPublished(){return this._isPublished}destroy(){var t;r.info(`track is destroyed -> trackId: ${this.getTrackId()}`),null===(t=this._msTrack)||void 0===t||t.stop(),super.__innerDestroy(),this.isAudioTrack()&&super.__releaseMediaElement(),this.emit(De.__INNER_EVENT_DESTROY__,this),e.logger.info(i.L_LOCAL_TRACK_DESTROY_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC})}setBitrate(t=0,o=0,n=0){if(!e.isNumber(t)||!e.isNumber(o)||!e.isNumber(n)||t<=0||o<=0||t<o)return r.error("setBitrate params error ->"),void e.logger.error(i.L_LOCAL_TRACK_SET_BITRATE_O,{status:s.FAILED,code:"",msg:`params error -> max: ${t},min: ${o}, start: ${n}`},{logSource:e.LogSource.RTC});e.logger.info(i.L_LOCAL_TRACK_SET_BITRATE_O,{status:s.SUCCESSED,max:t,min:o,start:n},{logSource:e.LogSource.RTC}),this._bitrateInfo={max:t,min:o,start:n}}getBitrate(){var e,t;const{min:r,max:o}=this._msTrack?Ye(this._msTrack):{min:0,max:0};return{min:(null===(e=this._bitrateInfo)||void 0===e?void 0:e.min)||r,max:(null===(t=this._bitrateInfo)||void 0===t?void 0:t.max)||o}}}De.EVENT_LOCAL_TRACK_END="local-track-end",De.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",De.__INNER_EVENT_DESTROY__="inner-destroy";class ye extends De{constructor(e,t,r){super(e,t,"audio",r)}setBitrate(e,t,o){r.warn("`setBitrate` invalid for audio track")}getBitrate(){return{start:32,max:32,min:32}}}class Pe extends De{constructor(e,t,r,o=!1){super(e,t,"video",r),this._isTiny=o}__isTiny(){return this._isTiny}getStreamId(){const e=super.getStreamId();return this._isTiny?`${e}_tiny`:e}getTrackId(){const e=super.getTrackId();return this._isTiny?`${e}_tiny`:e}}class ke extends De{constructor(e,t,r,o,i){super(e,t,r,o),this._resource=i,ke.__innerSetMapping(this.getTrackId(),i)}static __innerSetMapping(e,t){const r=this._mapping.get(t)||[];r.push(e),this._mapping.set(t,r)}static __innerRemoveMapping(e,t){var r,o;const i=null===(r=this._mapping.get(t))||void 0===r?void 0:r.filter((t=>t!==e));i&&i.length>0?this._mapping.set(t,i):(this._mapping.delete(t),t.pause(),t.src="",null===(o=t.parentNode)||void 0===o||o.removeChild(t))}destroy(){this.isAudioTrack()&&this.mute(),ke.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}ke._mapping=new Map;class Ue extends ke{constructor(e,t,r,o){super(e,t,"video",r,o)}}class Me extends ke{constructor(e,t,r,o){super(e,t,"audio",r,o)}_setLocalMuted(e){this._resource&&(this._resource.muted=e),super._setLocalMuted(e)}play(){return this._setLocalMuted(!1),Promise.resolve({code:exports.RCRTCCode.SUCCESS})}}class be extends ye{}class xe extends Pe{}class Be extends Pe{}class we extends Ne{constructor(e,t,r,o){super(e,t,r,!1,o),this._isSubscribed=!1}__innerSetRemoteMuted(e){this._remoteMuted=e}__innerSetSubscribed(t){this._isSubscribed=t,e.logger.info(i.L_REMOTE_TRACK_INNER_SET_SUBSCRIBED_O,{status:s.SUCCESSED,bool:t},{logSource:e.LogSource.RTC})}isSubscribed(){return this._isSubscribed}}class Ve extends we{constructor(e,t,r){super(e,t,"audio",r)}}class Fe extends we{constructor(e,t,r){super(e,t,"video",r)}}const $e=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),Ge=e=>JSON.stringify(e),Ke=e=>/^[a-zA-Z\d-=]+$/g.test(e),He="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),je=t=>{if(void 0===t)return 0;if(e.isNumber(t))return t;const r=t;return r.exact||r.ideal||r.max||0},Je=e=>{const t=e.getSettings(),r=e.getConstraints();return{width:t.width||je(r.width),height:t.height||je(r.height),frameRate:t.frameRate||je(r.frameRate)}},Ye=e=>{const{width:t,height:r,frameRate:o}=Je(e),i=Le(t||1920,r||1080),s=ve(o);return{min:i.minBitrate*s,max:i.maxBitrate*s}},qe=e=>[e.msid,e.mediaType].join("_"),We=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},ze=(e,t)=>[e,t].join("_"),Qe=e=>e.map((e=>Object.assign({},e))),Ze=(e,t,r=!1)=>{e=e.slice();const o=[],i=[],s=[];return t.forEach((t=>{const i=qe(t);let n=e.findIndex((e=>qe(e)===i));if(r&&(n=e.findIndex((e=>e.uri===t.uri))),-1===n)return void o.push(t);const a=e[n];a.uri!==t.uri?o.push(t):a.state!==t.state&&s.push(t),e.splice(n,1)})),i.push(...e),{publishedList:o,unpublishedList:i,modifiedList:s}},Xe=()=>{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 o=+e;const i=[];do{const e=o%r;o=(o-e)/r,i.unshift(t[e])}while(o);return i.join("")})(e),e.length>22&&(e=e.slice(0,22)),e},et=e=>{const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},tt=e=>!!exports.RCResolution[e],rt=e=>!!exports.RCFrameRate[e],ot=e=>parseInt(e.replace("FPS_","")),it=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=me.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function st(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function nt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const at=e=>"[object Null]"===Object.prototype.toString.call(e),ct=e=>1===e.type,dt=(e,t)=>{const o={},i=Object.keys(e.users);return i.length&&i.forEach((i=>{const s=[],n=e.users[i];if(n.extra){const e=JSON.parse(n.extra).roomId;if(t!==e)return}if(n.uris)try{s.push(...JSON.parse(n.uris))}catch(e){r.warn(`invalid user data -> userId: ${i}, userData: ${n}`)}o[i]=s})),o},_t=e=>e instanceof Ne?e.getTrackId():e.track.getTrackId();var ut,lt;!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"}(ut||(ut={})),exports.RCRTCPingResult=void 0,(lt=exports.RCRTCPingResult||(exports.RCRTCPingResult={})).SUCCESS="Success",lt.FAIL="Fail";class Rt{constructor(e,t,r,o=5e3,i=6e4){this._roomId=e,this._roomMode=t,this._context=r,this._gap=o,this._offlineKickTime=i,this._latestTimestamp=Date.now(),this._started=!1,this._timer=null}start(){this._started||(r.info("rtcping start ->"),e.logger.info(i.L_PINGER_START_O,{status:s.SUCCESSED,interval:this._gap},{logSource:e.LogSource.RTC}),this._started=!0,this._checkAlive())}_sendPing(){return new Promise((t=>{this._context.rtcPing(this._roomId,this._roomMode).then(t).catch((o=>{r.error(`rtcping receive unknown error -> ${o}`),t(e.ErrorCode.UNKNOWN)})),setTimeout(t,5e3,e.ErrorCode.TIMEOUT)}))}_checkAlive(){var o,n,a;return t(this,void 0,void 0,(function*(){r.info("rtcping ->");const t=yield this._sendPing(),c=Date.now();return t===e.ErrorCode.SUCCESS?(r.info("rtcping success ->"),this._latestTimestamp=c,null===(o=this.onPingResult)||void 0===o||o.call(this,exports.RCRTCPingResult.SUCCESS),void(this._timer=setTimeout((()=>this._checkAlive()),this._gap))):(t===e.ErrorCode.TIMEOUT&&e.logger.error(i.L_PINGER_TIMEOUT_O,{status:s.TIMEOUT},{logSource:e.LogSource.RTC}),r.warn(`rtcping failed -> code: ${t}`),null===(n=this.onPingResult)||void 0===n||n.call(this,exports.RCRTCPingResult.FAIL),40003===t||c-this._latestTimestamp>this._offlineKickTime?(this.stop(),void(null===(a=this.onFailed)||void 0===a||a.call(this,40003===t))):void(this._timer=setTimeout((()=>this._checkAlive()),500)))}))}stop(){this._started&&(r.info("rtcping stop ->"),e.logger.info(i.L_PINGER_STOP_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this._started=!1,this._timer&&(clearTimeout(this._timer),this._timer=null))}}const Ct=()=>"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)})),pt=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${it.browser}|${it.version}`,ClientVersion:"5.4.2","Client-Session-Id":Ct(),"Request-Id":Date.now().toString()});class ht{constructor(e,t,r,o=5e3){this._runtime=e,this._context=t,this._msUrl=r,this._timeout=o,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 o;try{o=JSON.parse(e.voipCallInfo||'{ "strategy": 0 }')}catch(t){return r.warn("parse `voipCallInfo` of navi failed: "+e.voipCallInfo),[]}if(0===o.strategy)return[];const i=null===(t=o.callEngine)||void 0===t?void 0:t.filter((e=>4===e.engineType));if(!i||0===i.length)return[];const s=i[0],n=[];return s.mediaServer&&n.push(s.mediaServer.replace(/^(https?:\/\/)?/,"https://")),s.backupMediaServer&&s.backupMediaServer.forEach((e=>{n.push(e.replace(/^(https?:\/\/)?/,"https://"))})),n})(this._context.getNaviInfo())):(this._msInNavi.push(...this._failedMs),this._failedMs.length=0)),this._msInNavi.map((e=>e.trim())))}_request(o,n,a){return t(this,void 0,void 0,(function*(){e.logger.info(i.L_MEDIA_SERVICE_REQUEST_T,{path:o,headers:n,body:a},{logSource:e.LogSource.RTC});const t=this.getNaviMS();if(0===t.length)return r.warn(`request '${o}' failed -> have no valid service address.`),e.logger.error(i.L_MEDIA_SERVICE_REQUEST_R,{status:s.FAILED,code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"invalid navi_url"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(a.rtcFinger=this._rtcFinger);for(let c=0;c<t.length;c+=1){const d=`${t[c]}${o}`,_=pt(),u=Object.assign(Object.assign({},_),n),l=JSON.stringify(a),R=_["Request-Id"];r.info(`request -> Request-Id: ${R}, url: ${d}, headers: ${JSON.stringify(u)}, body: ${l}`);const{status:C,data:p}=yield this._runtime.httpReq({url:d,body:l,headers:u,method:e.HttpMethod.POST,timeout:this._timeout});if(200===C){const t=JSON.parse(p);return t.rtcFinger&&(this._rtcFinger=t.rtcFinger),t.clusterId&&(this._clusterId=t.clusterId),r.info(`request success -> Request-Id: ${R}`),e.logger.info(i.L_MEDIA_SERVICE_REQUEST_R,{status:s.SUCCESSED,data:t},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,data:t}}r.warn(`request failed -> Request-Id: ${R}, status: ${C}, url: ${d}`),this._failedMs.push(...this._msInNavi.splice(c,1)),e.logger.error(i.L_MEDIA_SERVICE_REQUEST_R,{status:s.FAILED,code:"",msg:`request error -> Request-Id: ${R}, status: ${C}, url: ${d}`},{logSource:e.LogSource.RTC})}return{code:exports.RCRTCCode.REQUEST_FAILED}}))}exchange(e,r){var o;return t(this,void 0,void 0,(function*(){const t=yield this._request("/exchange",e,r);if(t.code===exports.RCRTCCode.SUCCESS&&(null===(o=t.data)||void 0===o?void 0:o.resultCode)===exports.RCRTCCode.SUCCESS){const e=t.data.urls;e&&(this._configUrl=e.configUrl)}return t}))}exit(e){return t(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 t(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/broadcast/exit",e,{});return{code:t}}))}setMcuConfig(o,n){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_MEDIA_SERVICE_SET_MCU_CONFIG_T,{headers:o,body:n},{logSource:e.LogSource.RTC}),!this._configUrl)return r.warn("RCMediaService.setMcuConfig failed -> RCRTCCode.MCU_SERVER_NOT_FOUND"),e.logger.error(i.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:s.FAILED,code:exports.RCRTCCode.MCU_SERVER_NOT_FOUND,msg:"MCU not found"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.MCU_SERVER_NOT_FOUND};const t=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,a=pt(),c=Object.assign(Object.assign({},a),o),d=JSON.stringify(n),_=a["Request-Id"];r.info(`request -> Request-Id: ${_}, url: ${t}, headers: ${JSON.stringify(c)}, body: ${d}`);const{status:u,data:l}=yield this._runtime.httpReq({url:t,headers:c,body:d,method:e.HttpMethod.POST});if(200===u){r.info(`request success -> Request-Id: ${_}`);const t=JSON.parse(l);return e.logger.info(i.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:s.SUCCESSED,data:t},{logSource:e.LogSource.RTC}),{code:t.resultCode,res:t}}return r.warn(`request failed -> Request-Id: ${_}, status: ${u}, url: ${t}`),e.logger.error(i.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:s.FAILED,code:exports.RCRTCCode.REQUEST_FAILED,msg:`request error -> Request-Id: ${_}, status: ${u}, url: ${t}`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REQUEST_FAILED}}))}getCDNResourceInfo(o,n){return t(this,void 0,void 0,(function*(){e.logger.info(i.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_T,{headers:o,url:n},{logSource:e.LogSource.RTC});const t=pt(),a=Object.assign(Object.assign({},t),o),c=t["Request-Id"];r.info(`request -> Request-Id: ${c}, url: ${n}, headers: ${JSON.stringify(a)}`);const{status:d,data:_}=yield this._runtime.httpReq({url:n,headers:a,method:e.HttpMethod.GET});if(200===d){r.info(`request success -> Request-Id: ${t["Request-Id"]}`);const o=JSON.parse(_);return e.logger.info(i.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:s.SUCCESSED,data:o},{logSource:e.LogSource.RTC}),{code:o.resultCode,res:o}}return r.warn(`request failed -> Request-Id: ${t["Request-Id"]}, status: ${d}, url: ${n}`),e.logger.info(i.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:s.FAILED,code:exports.RCRTCCode.REQUEST_FAILED,msg:`request error -> Request-Id: ${t["Request-Id"]}, status: ${d}, url: ${n}`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REQUEST_FAILED}}))}}var Tt;!function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(Tt||(Tt={}));const gt=(e,t)=>Math.round(8*t/e),mt=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},Et=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.ceil(e*r)},St=(e,t,r,o)=>{if(0===t)return 0;if(!r||!o)return mt(e/t,3);const i=t-o;if(0===i)return 0;const s=e-r;return s<0||i<0?0:mt(s/i,3)},It=e=>{const{jitter:t,rtt:r,packetsLostRate:o}=e;return!at(t)||!at(r)||0!==o};class ft{constructor(e,t,r){this._rtcPeerConn=e,this._sdpSemantics=t,this._currentUserId=r,this._latestPacketsSent={},this._latestBytesSent={},this._latestBytesRecv={},this._latestPacketsRecv={}}updateBytesSent(e,t,r){let o,i;if(this._latestBytesSent[e]&&t<this._latestBytesSent[e].bytesSent&&this.clearLatestpacketsSent([e]),this._latestBytesSent[e]){const{bytesSent:s,timestamp:n}=this._latestBytesSent[e];o=t-s,i=r-n,this._latestBytesSent[e]={bytesSent:t,timestamp:r}}else o=t,i=1e3,this._latestBytesSent[e]={bytesSent:t,timestamp:r};return gt(i,o)}updateBytesRecv(e,t,r){let o,i;if(this._latestBytesRecv[e]&&t<this._latestBytesRecv[e].bytesRecv&&this.clearLatestPacketsRecv([e]),this._latestBytesRecv[e]){const{bytesRecv:s,timestamp:n}=this._latestBytesRecv[e];o=t-s,i=r-n,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r}}else o=t,i=1e3,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r};return gt(i,o)}updateSenderPacketsLost(e,t,r){let o;if(Object.prototype.hasOwnProperty.call(this._latestPacketsSent[e],"packetsSent")){const{packetsLost:i,packetsSent:s}=this._latestPacketsSent[e];o=St(t,r,i,s),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=i===t?s:r}else o=St(t,r),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=r;return o}updateReceiverPacketsLost(e,t,r){let o;if(this._latestPacketsRecv[e]){const{packetsLost:i,packetsRecv:s}=this._latestPacketsRecv[e];o=St(t,r+t,i,s+i)}else o=St(t,r);return this._latestPacketsRecv[e]={packetsLost:t,packetsRecv:r},o}clearLatestpacketsSent(e){e.forEach((e=>{if(parseInt(e.split("_").pop())===exports.RCMediaType.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 o=t.next();for(;!o.done;){const i=o.value,s=e.get(i);/^RTCCodec_/.test(i)||(r[i]=s),o=t.next()}return r}formatRCRTCStateReport(t){const r={senders:[],receivers:[]};return e.logger.info(i.L_ABSTRACT_STAT_PARSER_FORMAT_RTC_STATE_REPORT_O,{status:s.SUCCESSED,stats:t,reports:r},{logSource:e.LogSource.RTC}),r}getAudioLevelList(e){return[]}getResourceIdByParseSdp(e){var t,r;const o=e.ssrc,i=e.kind||e.mediaType,s=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,n=null===(r=this._rtcPeerConn.currentRemoteDescription)||void 0===r?void 0:r.sdp;let a;a="unified-plan"===this._sdpSemantics?new RegExp("a=msid:(.*?) "):new RegExp(`a=ssrc:${o} msid:(.*?) `);const c=null==s?void 0:s.split("\r\nm="),d=null==c?void 0:c.filter((e=>e.includes(`a=ssrc:${o}`)))[0],_=null==d?void 0:d.match(a);let u=_?_[1]:"";if(u){if("audio"===i)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="),R=null==l?void 0:l.filter((e=>e.includes(`a=ssrc:${o}`)))[0],C=null==R?void 0:R.match(a);return u=C?C[1]:"",u?`${u}_${"video"===i?1:0}`:""}isValidSender(e){var t;const r=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,{ssrc:o}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(o)&&e.includes("a=inactive"))))}isValidReceiver(e){var t;const r=null===(t=this._rtcPeerConn.currentRemoteDescription)||void 0===t?void 0:t.sdp,{ssrc:o}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(o)&&e.includes("a=inactive"))))}}class Lt extends ft{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const o=Object.keys(e);let i=0,s=0;o.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const n=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const{id:a,kind:c,transportId:d,mediaSourceId:_,remoteId:u,packetsSent:l,bytesSent:R,trackId:C,encoderImplementation:p,pliCount:h,nackCount:T,firCount:g}=n;if(!C)return;let{framesPerSecond:m,frameWidth:E,frameHeight:S}=n;"video"!==c||E||S||m||(E=e[C].frameWidth,S=e[C].frameHeight,m=_?e[_].framesPerSecond:null);const I=e[u];let f=null,L=null,O=0;I&&(f=I.jitter,L=I.roundTripTime,O=I.packetsLost),i+=O;const v=this.getResourceIdByParseSdp(n);if(!v)return;const A=_?e[_].audioLevel:e[C].audioLevel;let N=null;!this._latestPacketsSent[v]&&(this._latestPacketsSent[v]={}),I?N=this.updateSenderPacketsLost(v,O,l):this._latestPacketsSent[v].crtPacketsSent=l;let D=this.updateBytesSent(v,R,r);D<0&&(D=0),s+=D,t.senders.push({id:a,trackId:v,kind:c,packetsLostRate:N,remoteResource:!1,audioLevel:A||0===A?Et(A):null,frameWidth:E,frameHeight:S,frameRate:m,bitrate:D,jitter:f?Math.round(1e3*f):f,rtt:L,encoderImplementation:p,pliCount:h,nackCount:T,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));o.filter((e=>/RTCRemoteInboundRtp(Video|Audio)Stream_/.test(e))).forEach((r=>{const{localId:o,jitter:i,roundTripTime:s,packetsLost:n}=e[r],a=t.senders.filter((e=>e.id===o))[0];if(a&&!It(a)){const t=this.getResourceIdByParseSdp(e[a.id]);a.jitter=Math.round(1e3*i),a.rtt=s;const r=this._latestPacketsSent[t].crtPacketsSent;a.packetsLostRate=this.updateSenderPacketsLost(t,n,r)}}));let n=0;o.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const s=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:_,bytesReceived:u,framesPerSecond:l,kind:R,codecImplementationName:C,nackCount:p,pliCount:h}=s;if(!a)return;let{frameWidth:T,frameHeight:g,audioLevel:m}=s;"video"===R?T||g||(T=e[a].frameWidth,g=e[a].frameHeight):m||(m=e[a].audioLevel),i+=c;const E=this.getResourceIdByParseSdp(s),S=this.updateReceiverPacketsLost(E,c,d);let I=this.updateBytesRecv(E,u,r);I<0&&(I=0),n+=I,t.receivers.push({trackId:E,kind:R,packetsLostRate:S,remoteResource:!0,audioLevel:m||0===m?Et(m):null,frameWidth:T,frameHeight:g,frameRate:l,bitrate:I,jitter:_?Math.round(1e3*_):0,codecImplementationName:C,nackCount:p,pliCount:h,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=o.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:o}=r;if(o){const r=e[o],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:_,remoteCandidateId:u}=r,l=e[_],{ip:R,port:C,networkType:p}=l,h=e[u],{ip:T,port:g,protocol:m}=h;t.iceCandidatePair={IP:R,port:C,networkType:p,remoteIP:T,remotePort:g,protocol:m,bitrateRecv:n,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:i},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTPAudioStream_/.test(e))).forEach((r=>{var o;const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const{mediaSourceId:s,trackId:n}=i,a=this.getResourceIdByParseSdp(i),c=s&&e[s]?e[s].audioLevel:(null===(o=e[n])||void 0===o?void 0:o.audioLevel)||null;t.push({trackId:a,audioLevel:c||0===c?Et(c):null})}));return r.filter((e=>/^RTCInboundRTPAudioStream_/.test(e))).forEach((r=>{const o=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:i}=o,s=o.audioLevel||e[i].audioLevel,n=this.getResourceIdByParseSdp(o);t.push({trackId:n,audioLevel:s||0===s?Et(s):null})})),t}}class Ot extends ft{formatRCRTCStateReport(e){const t=+new Date,r={senders:[],receivers:[],timestamp:t};let o=0,i=0,s=0;for(const n in e){const a=e[n],c=a.type;if("outbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(a))continue;const{id:s,kind:n,bytesSent:c,packetsSent:d,bitrateMean:_,framerateMean:u,nackCount:l,pliCount:R,remoteId:C}=a,{jitter:p,roundTripTime:h,packetsLost:T}=C?e[C]:{jitter:null,roundTripTime:null,packetsLost:0},g=this.getResourceIdByParseSdp(a);o+=T;let m=null;!this._latestPacketsSent[g]&&(this._latestPacketsSent[g]={}),C?m=this.updateSenderPacketsLost(g,T,d):this._latestPacketsSent[g].crtPacketsSent=d;let E=0;"video"===n?_&&(E=Math.floor(_/1e3)):E=this.updateBytesSent(g,c,t),E<0&&(E=0),i+=E,r.senders.push({trackId:g,kind:n,packetsLostRate:m,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:E,jitter:p?Math.round(1e3*p):null,rtt:h,encoderImplementation:null,pliCount:R,nackCount:l,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}if("remote-inbound-rtp"===c){const{localId:t}=a,o=this.getResourceIdByParseSdp(e[t]),i=r.senders.filter((e=>e.trackId===o))[0];i&&It(i)&&(i.jitter=Math.round(1e3*a.jitter),i.rtt=a.rtt,i.packetsLostRate=this.updateSenderPacketsLost(o,a.packetsLost,this._latestPacketsSent[o].crtPacketsSent))}if("inbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(a))continue;const{id:e,packetsLost:i,bytesReceived:n,packetsReceived:c,jitter:d,framerateMean:_,kind:u,bitrateMean:l,nackCount:R,pliCount:C}=a,p=this.getResourceIdByParseSdp(a);o+=i;const h=this.updateReceiverPacketsLost(p,i,c);let T=0;"video"===u?l&&(T=Math.floor(l/1e3)):T=this.updateBytesRecv(p,n,t),T<0&&(T=0),s+=T,r.receivers.push({trackId:p,kind:u,packetsLostRate:h,remoteResource:!0,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(_),bitrate:T,jitter:d?Math.round(1e3*d):null,codecImplementationName:null,nackCount:R,pliCount:C,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}if("candidate-pair"===c&&"succeeded"===a.state){const t=e[a.localCandidateId],{address:n,port:c}=t,d=e[a.remoteCandidateId],{address:_,port:u,protocol:l}=d;r.iceCandidatePair={IP:n,port:c,networkType:null,remoteIP:_,remotePort:u,protocol:l,bitrateRecv:s,bitrateSend:i,rtt:null,availableOutgoingBitrate:null,availableIncomingBitrate:null,totalPacketsLost:o}}}return r.iceCandidatePair&&(r.iceCandidatePair.bitrateSend=i),r.iceCandidatePair&&(r.iceCandidatePair.bitrateRecv=s),r}getAudioLevelList(e){const t=[];for(const r in e){const o=e[r],i=o.type;if("outbound-rtp"===i){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))continue;const{kind:e}=o;if("video"===e)continue;const r=this.getResourceIdByParseSdp(o);t.push({trackId:r,audioLevel:null})}if("inbound-rtp"===i){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))continue;const{kind:e}=o;if("video"===e)continue;const r=this.getResourceIdByParseSdp(o);t.push({trackId:r,audioLevel:null})}}return t}}class vt extends ft{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const o=Object.keys(e);let i=0,s=0;o.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const i=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const n=this.getResourceIdByParseSdp(i),{mediaType:a,transportId:c,remoteId:d,packetsSent:_,bytesSent:u,trackId:l,encoderImplementation:R,pliCount:C,nackCount:p,firCount:h}=i;if(!l)return;const{audioLevel:T,frameHeight:g,frameWidth:m}=e[l];let E=this.updateBytesSent(n,u,r);E<0&&(E=0),s+=E,t.senders.push({trackId:n,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:T||0===T?Et(T):null,frameWidth:m,frameHeight:g,frameRate:null,bitrate:E,jitter:null,rtt:null,encoderImplementation:R,pliCount:C,nackCount:p,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));let n=0;o.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const s=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:_,bytesReceived:u,mediaType:l,nackCount:R,pliCount:C}=s,p=this.getResourceIdByParseSdp(s);if(!a)return;const{frameHeight:h,frameWidth:T,audioLevel:g}=e[a];i+=c;const m=this.updateReceiverPacketsLost(p,c,d);let E=this.updateBytesRecv(p,u,r);E<0&&(E=0),n+=E,t.receivers.push({trackId:p,kind:l,packetsLostRate:m,remoteResource:!0,audioLevel:g||0===g?Et(g):null,frameWidth:T,frameHeight:h,frameRate:null,bitrate:E,jitter:_,codecImplementationName:null,nackCount:R,pliCount:C,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=o.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:o}=r;if(o){const r=e[o],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:_,remoteCandidateId:u}=r,l=e[_],{address:R,port:C}=l,p=e[u],{address:h,port:T,protocol:g}=p;t.iceCandidatePair={IP:R||null,port:C,networkType:null,remoteIP:h,remotePort:T,protocol:g,bitrateRecv:n,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:i},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const o=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))return;const{trackId:i,mediaType:s}=o;if("video"===s)return;const n=this.getResourceIdByParseSdp(o),a=e[i];t.push({trackId:n,audioLevel:a||0===a?Et(a):null})}));return r.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const o=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:i,mediaType:s}=o;if(!i||"video"===s)return;const{audioLevel:n}=e[i],a=this.getResourceIdByParseSdp(o);t.push({trackId:a,audioLevel:n||0===n?Et(n):null})})),t}}class At{constructor(e){this._peer=e,this._outboundStreams={}}static setSdpSemantics(t){e.logger.info(i.L_A_SDP_STRATEGY_SET_SDP_SEMANTICS_O,{status:s.SUCCESSED,sdpSemantics:t},{logSource:e.LogSource.RTC});const{browser:r,version:o,supportsUnifiedPlan:n}=it;n?/chrome/i.test(r)?this._sdpSemantics=o>92?"unified-plan":o<72?"plan-b":t:/firefox/i.test(r)?this._sdpSemantics="unified-plan":/safari/i.test(r)?this._sdpSemantics=o<12?"plan-b":"unified-plan":this._sdpSemantics="unified-plan":this._sdpSemantics="plan-b"}static getSdpSemantics(){return At._sdpSemantics}getOutboundVideoInfo(){const e=[];for(const t in this._outboundStreams){const r=this._outboundStreams[t].getVideoTracks()[0];if(!r)continue;const o=/_tiny$/.test(t),{width:i,height:s}=Je(r);e.push({trackId:r.id,simulcast:o?Tt.TINY:Tt.NORMAL,resolution:`${i}x${s}`})}return e}setRemoteAnswer(o){return t(this,void 0,void 0,(function*(){o=o.replace(/\s+\r\n/g,"\r\n");try{yield this._peer.setRemoteDescription({type:"answer",sdp:o})}catch(t){return r.error(t),e.logger.info(i.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:s.FAILED,code:"",msg:t},{logSource:e.LogSource.RTC}),exports.RCRTCCode.SET_REMOTE_DESCRIPTION_FAILED}return e.logger.info(i.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:s.SUCCESSED,sdp:o},{logSource:e.LogSource.RTC}),exports.RCRTCCode.SUCCESS}))}getStatParsr(e,t,r){return/chrome/i.test(it.browser)?new Lt(e,t,r):/Firefox/i.test(it.browser)?new Ot(e,t,r):/Safari/i.test(it.browser)?new vt(e,t,r):null}}class Nt extends At{constructor(){super(...arguments),this.senders={},this._localTracks=[]}addLocalTrack(e){this._localTracks.includes(e)||this._localTracks.push(e);const t=e.getStreamId(),r=e.__innerGetMediaStreamTrack(),o=this._outboundStreams[t]||(this._outboundStreams[t]=new MediaStream);o.getTracks().forEach((e=>{e.kind===r.kind&&o.removeTrack(e)})),o.addTrack(r);const i=e.getTrackId(),s=this.senders[i];s?s.replaceTrack(r):this.senders[i]=this._peer.addTrack(r,o)}removeLocalTrack(e){const t=this._localTracks.findIndex((t=>t===e));t>=0&&this._localTracks.splice(t,1);const r=e.getTrackId(),o=this.senders[r];o&&(o.replaceTrack(null),this._peer.removeTrack(o),delete this.senders[r])}updateSubRemoteTracks(e){}updateRecvTransceiverMap(e,t){}setBitrate(e,t,r){this._maxBitrate=e,this._minBitrate=t,this._startBitrate=r||.7*e}createOffer(e){return t(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 yield this._peer.setLocalDescription(t),{type:"offer",semantics:"plan-b",sdp:t.sdp}}))}setRemoteAnswer(e){let t=0,r=0;this._localTracks.forEach((e=>{const{min:o,max:i}=e.getBitrate();r+=o,t+=i})),t=this._maxBitrate&&this._maxBitrate>0?Math.min(t,this._maxBitrate):t,r=this._minBitrate&&this._minBitrate>0?Math.max(r,this._minBitrate):r;const o=this._startBitrate||Math.round(.7*t),i=`b=AS:${t}`;e=e.replace(/[\r\n]+m=video[^\r\n]+/,(e=>`${e}\r\n${i}`));const s=[`;x-google-min-bitrate=${r}`,`;x-google-max-bitrate=${t}`,`;x-google-start-bitrate=${o}`].join("");return e=e.replace(/[\r\n]+[^\r\n]+profile-level-id[^\r\n]+/g,(e=>e+s)),super.setRemoteAnswer(e)}}class Dt extends At{constructor(){super(...arguments),this._sendTransceiver={},this._localTracks={},this._recvAudio=[],this._recvVideo=[],this._recvTransceiver={},this._subedTracks=[]}setBitrate(e,t,o){r.warn("the interface named `setBitrate` is invalid while sdpSemantics value is `unified-plan`")}addLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId(),o=e.__innerGetMediaStreamTrack();this._localTracks[t]=e;const i=this._outboundStreams[r]||(this._outboundStreams[r]=new MediaStream);i.getTracks().forEach((e=>{e.kind===o.kind&&i.removeTrack(e)})),i.addTrack(o);const s=this._sendTransceiver[t];s?(s.sender.replaceTrack(o),s.direction="sendonly"):this._sendTransceiver[t]=this._peer.addTransceiver(o,{direction:"sendonly",streams:[i]})}removeLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId();e.__innerGetMediaStreamTrack(),delete this._localTracks[t];const o=this._sendTransceiver[t];if(!o)return;o.direction="inactive",this._peer.removeTrack(o.sender),o.sender.replaceTrack(null);const i=this._outboundStreams[r];(e.isAudioTrack()?i.getAudioTracks():i.getVideoTracks()).forEach((e=>i.removeTrack(e)));const s=this._sendTransceiver[`${t}_tiny`];if(!s||"inactive"===s.direction)return;s.direction="inactive";const 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}=We(e);this._recvTransceiver[e]=t;const o=r===exports.RCMediaType.AUDIO_ONLY?this._recvAudio:this._recvVideo,i=o.findIndex((e=>e===t));i>=0&&o.splice(i,1)}updateSubRemoteTracks(e){const t=e.slice(),r=this._subedTracks.slice();this._subedTracks=e.slice();for(let e=t.length-1;e>=0;e-=1){const o=t[e],i=r.findIndex((e=>e===o));i>=0&&(t.splice(e,1),r.splice(i,1))}r.length&&r.forEach((e=>{const t=e.getTrackId();e.__innerSetMediaStreamTrack(void 0);const r=this._recvTransceiver[t];r&&(r.direction="inactive")}));const o={audio:0,video:0};t.length&&t.forEach((e=>{const t=e.isAudioTrack()?"audio":"video",r=this._recvTransceiver[e.getTrackId()];r?r.direction="recvonly":o[t]+=1}));for(let e=this._recvAudio.length;e<o.audio;e+=1)this._recvAudio.push(this._peer.addTransceiver("audio",{direction:"recvonly"}));for(let e=this._recvVideo.length;e<o.video;e+=1)this._recvVideo.push(this._peer.addTransceiver("video",{direction:"recvonly"}))}createOffer(e){return t(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=(e=>e.split(/\r\n(?=m=)/).map((e=>(e=>/a=(recvonly|inactive)/.test(e)?e.replace(/\r\na=(ssrc|msid)[^\r\n]+/g,""):e)(e))).join("\r\n"))(r),r=r.replace(/a=ice-options:trickle/g,"a=ice-options:trickle\r\na=ice-options:renomination"),t.sdp=r,yield this._peer.setLocalDescription(t),{type:"offer",semantics:"unified-plan",sdp:r}}))}setRemoteAnswer(e){e=e.split(/\r\n(?=m=)/).map((e=>{var t;const r=e.match(/a=mid:[^\s]+/);if(!r)return e;const o=r[0].replace("a=mid:","");let i="";for(const e in this._sendTransceiver){if(this._sendTransceiver[e].mid===o){i=e;break}}if(!i)return e;const s=null===(t=this._localTracks[i])||void 0===t?void 0:t.getBitrate();if(!s)return e;const{max:n,min:a}=s,c=n&&n>0?s.start||.7*n:0,d=[];if(n&&n>0&&d.push(`;x-google-max-bitrate=${n}`),a&&a>0&&d.push(`;x-google-min-bitrate=${a}`),c>0&&d.push(`;x-google-start-bitrate=${c}`),0===d.length)return e;const _=d.join("");return e.replace(/[\r\n]+[^\r\n]+profile-level-id[^\r\n]+/g,(e=>e+_))})).join("\r\n");const t=/[\r\n]+\r\n[\r\n]+/g;return t.test(e)&&(r.warn(`answer sdp invalid -> ${JSON.stringify(e)}`),e=e.replace(t,"\r\n")),super.setRemoteAnswer(e)}}class yt extends e.EventEmitter{constructor(e,t,r,o){super(),this._pcName=e,this._reTryExchange=t,this._currentUserId=r,this._polarisReport=o,this.pubLocalTracks={},this._reTryExchangeTimer=null,this._reportStatsTimer=null,this._reportR3R4ToPolarisTimer=null,this._reportListener=null;const i=At.getSdpSemantics(),s=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:i});this._sdpStrategy="plan-b"===i?new Nt(s):new Dt(s),this._rtcPeerConn.oniceconnectionstatechange=this._onICEConnectionStateChange.bind(this),this._rtcPeerConn.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._rtcPeerConn.ontrack=this._onTrackReady.bind(this),this.reportParser=this._sdpStrategy.getStatParsr(this._rtcPeerConn,i,this._currentUserId)}getName(){return this._pcName}getLocalTracks(){return e.logger.info(i.L_RTC_PEER_CONNECTION_GET_LOCAL_TRACKS_O,{status:s.SUCCESSED,trackIds:Object.keys(this.pubLocalTracks)},{logSource:e.LogSource.RTC}),Object.values(this.pubLocalTracks)}_onConnectionStateChange(){r.info(`onconnectionstatechange -> ${this._rtcPeerConn.connectionState}, ${this._pcName}`),e.logger.info(i.L_RTC_PEER_CONNECTION_CONNECTION_STATE_S,{status:s.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:e.LogSource.RTC})}_onICEConnectionStateChange(){var t,o;r.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||(r.warn(`${this._pcName} iceconenction state is failed, exchange SDP to try again.`),e.logger.error(i.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:s.FAILED,code:"",msg:`${this._pcName} iceconenction state is failed, exchange SDP to try again.`},{logSource:e.LogSource.RTC}),this._reTryExchange(),this._reTryExchangeTimer=setInterval(this._reTryExchange,15e3));try{null===(o=null===(t=this._reportListener)||void 0===t?void 0:t.onICEConnectionStateChange)||void 0===o||o.call(t,this._rtcPeerConn.iceConnectionState,this._pcName)}catch(t){r.error("onICEConnectionStateChange error",t,this._pcName),e.logger.error(i.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:s.FAILED,code:"",msg:`${this._pcName}, ${t}`},{logSource:e.LogSource.RTC})}e.logger.info(i.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:s.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:e.LogSource.RTC})}_onTrackReady(e){if(!e.streams.length)return;const t=[e.streams[0].id,"audio"===e.receiver.track.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY].join("_");this._updateRecvTransceiverMap(t,e.transceiver),this.emit(yt.__INNER_EVENT_TRACK_READY__,e)}setBitrate(r,o,n){return t(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(r,o,n),e.logger.info(i.L_RTC_PEER_CONNECTION_SET_BITRATE_O,{status:s.SUCCESSED,max:r,min:o,start:n},{logSource:e.LogSource.RTC})}))}createOffer(o){return t(this,void 0,void 0,(function*(){const t=yield this._sdpStrategy.createOffer(o);return r.debug(`offer -> ${JSON.stringify(t.sdp)}`),e.logger.info(i.L_RTC_PEER_CONNECTION_CREATE_OFFER_O,{status:s.SUCCESSED,offerSDP:t.sdp},{logSource:e.LogSource.RTC}),t}))}setRemoteAnswer(o){return t(this,void 0,void 0,(function*(){return r.debug(`answer -> ${JSON.stringify(o)}`),e.logger.info(i.L_RTC_PEER_CONNECTION_SET_REMOTE_ANSWER_O,{status:s.SUCCESSED,answer:o},{logSource:e.LogSource.RTC}),this._sdpStrategy.setRemoteAnswer(o)}))}getLocalTrack(e){return this.pubLocalTracks[e]||null}addLocalTrack(t){this.pubLocalTracks[t.getTrackId()]=t,this._sdpStrategy.addLocalTrack(t),t.off(De.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.off(De.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),t.on(De.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.on(De.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.logger.info(i.L_RTC_PEER_CONNECTION_ADD_LOCAL_TRACK_O,{status:s.SUCCESSED,trackId:t.getTrackId()},{logSource:e.LogSource.RTC})}removeLocalTrackById(t){const r=this.getLocalTrack(t);r?(e.logger.info(i.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:s.SUCCESSED,trackId:t},{logSource:e.LogSource.RTC}),this.removeLocalTrack(r)):e.logger.warn(i.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:s.FAILED,code:"",msg:"track not found"},{logSource:e.LogSource.RTC})}removeAllLocalTrack(){Object.keys(this.pubLocalTracks).forEach((e=>{/_tiny$/.test(e)||this.removeLocalTrackById(e)})),e.logger.info(i.L_RTC_PEER_CONNECTION_REMOVE_ALL_LOCAL_TRACK_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC})}removeLocalTrack(t){const r=t.getTrackId();delete this.pubLocalTracks[r],this._sdpStrategy.removeLocalTrack(t),t.__innerSetPublished(!1),t.off(De.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.off(De.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this);const o=`${r}_tiny`,n=this.getLocalTrack(o);n&&(this._sdpStrategy.removeLocalTrack(n),delete this.pubLocalTracks[o],n.destroy()),e.logger.info(i.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_O,{status:s.SUCCESSED,trackId:r},{logSource:e.LogSource.RTC})}_updateRecvTransceiverMap(e,t){this._sdpStrategy.updateRecvTransceiverMap(e,t)}updateSubRemoteTracks(t){this._sdpStrategy.updateSubRemoteTracks(t),e.logger.info(i.L_RTC_PEER_CONNECTION_UPDATE_SUB_REMOTE_TRACKS_O,{status:s.SUCCESSED,trackIds:t.map((e=>e.getTrackId()))},{logSource:e.LogSource.RTC})}getOutboundVideoInfo(){return this._sdpStrategy.getOutboundVideoInfo()}_onLocalTrackMuted(t){const r=this.getLocalTrack(`${t.getTrackId()}_tiny`);r&&(r.__innerGetMediaStreamTrack().enabled=!t.isLocalMuted()),this.emit(De.__INNER_EVENT_MUTED_CHANGE__,t),e.logger.info(i.L_RTC_PEER_CONNECTION_LOCAL_TRACK_MUTED_O,{status:s.SUCCESSED,trackId:t.getTrackId()},{logSource:e.LogSource.RTC})}_onLocalTrackDestroied(e){this.emit(De.__INNER_EVENT_DESTROY__,e)}registerReportListener(e){this._reportListener=e}_createRCRTCStateReport(e){const{timestamp:t,iceCandidatePair:r,senders:o,receivers:i}=JSON.parse(JSON.stringify(e));null==r||delete r.totalPacketsLost;for(const e in r)at(r[e])&&delete r[e];return{timestamp:t,iceCandidatePair:r,senders:o.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),receivers:i.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t}))}}_getStatsData(){var r,o;return t(this,void 0,void 0,(function*(){const t=yield this._rtcPeerConn.getStats(),n=null===(r=this.reportParser)||void 0===r?void 0:r.parseRTCStatsReport(t),a=null===(o=this.reportParser)||void 0===o?void 0:o.formatRCRTCStateReport(n);return e.logger.info(i.L_RTC_PEER_CONNECTION_GET_STATS_DATA_O,{status:s.SUCCESSED,formatData:a},{logSource:e.LogSource.RTC}),a}))}getAudioLevelReportData(){var e,r;return t(this,void 0,void 0,(function*(){const t=yield this._rtcPeerConn.getStats(),o=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(t);if(!o)return[];return null===(r=this.reportParser)||void 0===r?void 0:r.getAudioLevelList(o)}))}_reportHandle(){var e,r;return t(this,void 0,void 0,(function*(){const t=yield this._getStatsData();if(!t)return;const o=this._createRCRTCStateReport(t);null===(r=null===(e=this._reportListener)||void 0===e?void 0:e.onStateReport)||void 0===r||r.call(e,o)}))}_sendR3R4Data(){var e;return t(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 t(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,e.logger.info(i.L_RTC_PEER_CONNECTION_DESTROY_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC})}clearReTryExchangeTimer(){clearInterval(this._reTryExchangeTimer),this._reTryExchangeTimer=null}}var Pt,kt,Ut,Mt,bt,xt,Bt;yt.__INNER_EVENT_TRACK_READY__="inner-track-ready",function(e){e[e.DISABLE=0]="DISABLE",e[e.ENABLE=1]="ENABLE"}(Pt||(Pt={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(kt||(kt={}));class wt{constructor(e,t,r,o,i=kt.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=o,this._userRole=i}_send(r){return t(this,void 0,void 0,(function*(){let t=!1;if(this._context.getConnectionStatus()!==e.ConnectionStatus.CONNECTED)return t;return t=(yield this._context.setRTCState(this._roomId,r))===e.ErrorCode.SUCCESS,t}))}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=Xe(),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(),o=parseInt(r.pop())===exports.RCMediaType.AUDIO_ONLY?"audio":"video",i=r.pop();t=[r.join("_"),i,e,o].join("_")}else{const e=parseInt(r.pop())===exports.RCMediaType.AUDIO_ONLY?"audio":"video",o=r.pop();t=[r.join("_"),o,e].join("_")}return t}sendR3R4Data(e){return t(this,void 0,void 0,(function*(){const{iceCandidatePair:t,senders:r,receivers:o}=e,i=(null==t?void 0:t.bitrateSend)||-1,s=(null==t?void 0:t.bitrateRecv)||-1,n=(null==t?void 0:t.networkType)||"unknown",a=(null==t?void 0:t.rtt)||-1,c=`${(null==t?void 0:t.IP)||-1}:${null==t?void 0:t.port}`,d=(null==t||t.remoteIP,null==t||t.remotePort,(null==t?void 0:t.availableIncomingBitrate)||-1),_=(null==t?void 0:t.availableOutgoingBitrate)||-1,u=(null==t?void 0:t.totalPacketsLost)||-1,l=this._context.getCurrentId();let R=`R3\t${i}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${_}\t${u}\t${l}\r`,C=`R4\t${s}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${_}\t${u}\t${l}\r`;const p=r.map((e=>{var t;const{trackId:r,audioLevel:o,samplingRate:i,bitrate:s,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:_,jitter:u,nackCount:l,pliCount:R,rtt:C,googFirsSent:p,encoderImplementation:h}=e,T=this._getPolarisTrackId(r),g=this._getRealResourceId(r);return{trackId:T,googCodecName:h||String(-1),audioLevel:o||0===o?o:-1,bitrate:s||0===s?s:-1,packetsLostRate:n||0===n?n:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:R||0===R?R:-1,rtt:C||-1,googFirsSent:p,samplingRate:i,googRenderDelayMs:_,encoderImplementation:h||String(-1),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(g))||void 0===t?void 0:t.isLocalMuted())?Pt.DISABLE:Pt.ENABLE}})),h=o.filter((e=>!!e.trackId)).map((e=>{var t;const{trackId:r,audioLevel:o,samplingRate:i,bitrate:s,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:_,jitter:u,nackCount:l,pliCount:R,rtt:C,googFirsReceived:p,codecImplementationName:h}=e,T=this._getPolarisTrackId(r),g=this._getRealResourceId(r);return{trackId:T,googCodecName:h||String(-1),audioLevel:o||0===o?o:-1,bitrate:s||0===s?s:-1,packetsLostRate:n||0===n?n:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:R||0===R?R:-1,rtt:C||-1,googFirsReceived:p,samplingRate:i,googRenderDelayMs:_,codecImplementationName:h||String(-1),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(g))||void 0===t?void 0:t.isLocalMuted())?Pt.DISABLE:Pt.ENABLE}}));let T=!1;R+=p.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsSent}\t${e.encoderImplementation}\t${e.trackState}`)).join("\n"),e.senders.length&&(T=yield this._send(R+`\r${this._userRole}`));let g=!1;return C+=h.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsReceived}\t${e.codecImplementationName}\t${e.trackState}`)).join("\n"),e.receivers.length&&(g=yield this._send(C+`\r${this._userRole}`)),!(!T&&!g)}))}sendR1(){const e=`R1\t5.4.2\t${this._context.getCoreVersion()}\tweb\t${navigator.platform}\t-1\t${it.browser}\t${it.version}\t${this._getClientID()}\t${this._userRole}`;this._send(e)}sendR2(e,t,r){const o=`R2\t${e}\t${t}\t${this._getClientID()}\r${r.join("\t")}\r${this._userRole}`;this._send(o)}}class Vt{constructor(e){this._room=e,this._audioLevelChangeHandler=null,this._timer=null}_audioLevelReport(){return t(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 o=t[r];if("new"===o.getRTCPeerConn().iceConnectionState)return;const i=(yield o.getAudioLevelReportData()).map((e=>{const{userId:t}=We(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(...i)}this._audioLevelChangeHandler(e)}))}onAudioLevelChange(e,t){t<300||t>1e3?r.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)}}exports.RCRTCLiveRole=void 0,(Ut=exports.RCRTCLiveRole||(exports.RCRTCLiveRole={}))[Ut.ANCHOR=1]="ANCHOR",Ut[Ut.AUDIENCE=2]="AUDIENCE";class Ft{constructor(e=!1,t,r,o,i){this._useMutilPeerC=e,this._roomId=t,this._reTryExchange=r,this._currentUserId=o,this._polarisReport=i,this._mutilPeerC={}}get useMutilPeerC(){return this._useMutilPeerC}_isPub(e){if(!e.length)return!1;const{track:t}=e[0]instanceof De||e[0]instanceof we?{track:e[0]}:e[0];return t.isLocalTrack()}_groupTracksByTag(e){const t={};return e.map((e=>{const{track:r}=e instanceof De?{track:e}:e,o=r.getTag();t[o]?t[o].push(e):t[o]=[e]})),t}_genPCName(e,t){let r=null;return r=e?this._useMutilPeerC?`${this._roomId}_${t}`:`${this._roomId}_pub`:`${this._roomId}_sub`,r}_createOnePeerCItem(e,t){if(this._mutilPeerC[e]&&(this._mutilPeerC[e].tracks=t),!this._mutilPeerC[e]){const r=this._isPub(t),o=new yt(e,(()=>this._reTryExchange(e,r)),this._currentUserId,this._polarisReport);this._mutilPeerC[e]={pc:o,tracks:t,isPub:r}}return Object.assign({},this._mutilPeerC[e],{pcName:e})}createPeerCList(e){const t=[],r=this._isPub(e);if(!this._useMutilPeerC||!r){const o=this._genPCName(r);return t.push(this._createOnePeerCItem(o,e)),t}const o=this._groupTracksByTag(e);for(const e in o){const i=this._genPCName(r,e),s=o[e];t.push(this._createOnePeerCItem(i,s))}return t}_removeAllLocalTrack(){this.getPCList().forEach((e=>e.removeAllLocalTrack()))}destroyPeerC(e){this._mutilPeerC[e].pc.destroy()}_destroyAllPeerC(){this.getPCList().forEach((e=>e.destroy()))}getPCItemByPCName(e){return this._mutilPeerC[e]}getPCByTrackId(e,t=!0){const{tag:r}=We(e),o=this._genPCName(t,r);return this._mutilPeerC[o].pc}getPCList(){const e=[];for(const t in this._mutilPeerC)e.push(this._mutilPeerC[t].pc);return e}getMutilPeerCData(){return this._mutilPeerC}setPeerCData(e,t,r){}clear(){this._removeAllLocalTrack(),this._destroyAllPeerC()}}!function(e){e[e.LOW=0]="LOW",e[e.NORMAL=1]="NORMAL",e[e.HIGH=2]="HIGH"}(Mt||(Mt={}));class $t{get priority(){return Mt.LOW}}class Gt extends class{constructor(e,t,r,o,i,s,n,a,c){this.context=e,this.service=t,this.peerMgr=r,this.roomId=o,this.crtUserId=i,this.roomMode=s,this.polarisReport=n,this.isUpgrade=a,this.isMainRoom=c,this._remoteTracks={},this._subscribedList=[],this._CDNUris=null,this._CDNEnable=!1,this._destroyed=!1}get useMutilPeerC(){return this.peerMgr.useMutilPeerC}getResourcesByUserId(e){return this._roomResources[e]}getRemoteTrack(e){return this._remoteTracks[e]}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const o=this._remoteTracks[r];o.getUserId()===e&&t.push(o)}return t}getRemoteTracks(){return this._remoteTracks}getSessionId(){return this._sessionId}getAllUserIds(){return Object.keys(this._roomResources)}getRemoteUserIds(){return this.getAllUserIds().filter((e=>e!==this.crtUserId))}getSubscribedList(){return this._subscribedList}getPublishedResourceByTrackId(e){const{userId:t}=We(e);return this._roomResources[t].find((t=>qe(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=qe(e),{tag:r,userId:o,mediaType:i}=We(t),s=i===exports.RCMediaType.AUDIO_ONLY?new Ve(r,o):new Fe(r,o);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=dt(e,this.roomId),this._initRemoteTracks(),this.setResourcesByUserId(this.crtUserId,this.getResourcesByUserId(this.crtUserId)||[]),r.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 Kt 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 t(this,void 0,void 0,(function*(){if(this._isDestroyed||this._busy||0===this._queue.length)return;this._busy=!0;const{command:e,resolve:t,reject:r}=this._queue.shift();let o;try{o=yield e.execute(this._store,this)}catch(e){return r(e),void this._next()}t(o),this._next()}))}push(e){return new Promise(((t,r)=>{if(this._isDestroyed)return;const o=e.priority;if(o===Mt.LOW)this._queue.push({command:e,resolve:t,reject:r});else{const i=this._queue.findIndex((e=>e.command.priority<o)),s=-1===i?this._queue.length-1:i;this._queue.splice(s,0,{command:e,resolve:t,reject:r})}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,o,i,s,n,a,c){super(new Gt(e,t,r,o,i,s,n,a,c),exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED)}get store(){return this._store}destroy(){super.destroy(),this._store.removeRemoteTracks()}}class Ht extends $t{execute(o){return t(this,void 0,void 0,(function*(){const t=o.getResourcesByUserId(o.crtUserId),i=t.slice();t.length=0,r.info(`unpublish uris before rejoin -> ${JSON.stringify(i)}`);const s=yield o.context.setRTCTotalRes(o.roomId,$e(ut.UNPUBLISH,i),Ge([]),ut.TOTAL_CONTENT_RESOURCE,Ge([]));s!==e.ErrorCode.SUCCESS?r.error(`unpublish uris before rejoin failed -> code: ${s}`):r.info("unpublish uris before rejoin success")}))}}class jt extends $t{constructor(e,t,r,o,i,s){super(),this.roomId=e,this.mode=t,this.joinType=r,this.livingType=o,this.innerUserDatas=i,this.outerUserDatas=s}execute(o,n){var a;return t(this,void 0,void 0,(function*(){const{context:t,service:c}=o,d=this.mode===e.RTCMode.LIVE?i.L_RTC_CLIENT_JOIN_LIVING_ROOM_R:i.L_RTC_CLIENT_JOIN_RTC_ROOM_R;if(t.getConnectionStatus()!==e.ConnectionStatus.CONNECTED)return e.logger.error(d,{status:s.FAILED,code:exports.RCRTCCode.SIGNAL_DISCONNECTED,msg:"im not connected"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_DISCONNECTED};if(ct(t.getNaviInfo()))return e.logger.error(d,{status:s.FAILED,code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_usl error"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR};if(!e.validate("roomId",this.roomId,e.notEmptyString,!0))return e.logger.error(d,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(!e.validate("outerUserDatas",this.outerUserDatas,e.isObject,!1))return e.logger.error(d,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(this.outerUserDatas){if(!Object.keys(this.outerUserDatas).every((t=>e.validate(`outerUserDatas.${t}`,this.outerUserDatas[t],e.isString,!0))))return e.logger.error(d,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR}}if(!c.getNaviMS().length)return e.logger.error(d,{status:s.FAILED,code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};r.info(`joinRoom -> roomId: ${this.roomId}; joinType: ${this.joinType||e.RTCJoinType.KICK}`);const{code:_,data:u}=yield t.joinRTCRoom(this.roomId,this.mode,this.livingType,this.joinType,this.innerUserDatas,this.outerUserDatas);if(_!==e.ErrorCode.SUCCESS||!u){r.warn(`joinRoom failed -> code: ${_}`);const t=40032===_?exports.RCRTCCode.SIGNAL_JOIN_RTC_ROOM_REFUSED:_;return e.logger.error(d,{status:s.FAILED,code:t,msg:`joinRoom failed -> code: ${_}`},{logSource:e.LogSource.RTC}),{code:t}}r.info(`joinRoom success -> userId: ${t.getCurrentId()}, roomId: ${this.roomId}, data: ${JSON.stringify(u)}`),o.initWithRoomData(u);o.getResourcesByUserId(o.crtUserId).length>0&&n.push(new Ht);const l=null===(a=u.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===a?void 0:a.value;return l&&o.setCDNUris(JSON.parse(l)[0]),e.logger.info(d,{status:s.SUCCESSED,userId:o.crtUserId,roomId:this.roomId,data:u},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,data:u}}))}}function Jt(e,r,o,i){return t(this,void 0,void 0,(function*(){return{sdp:yield o.createOffer(r),extend:JSON.stringify({resolutionInfo:o.getOutboundVideoInfo()}),subscribeList:e.filter((e=>{const t=e.track.getTrackId(),{userId:r}=We(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?Tt.TINY:Tt.NORMAL,resolution:"",uri:i.getPublishedResourceByTrackId(e.track.getTrackId()).uri}))),switchstream:!1}}))}function Yt(o,i,s){return t(this,void 0,void 0,(function*(){const t=yield o.setRTCCDNUris(i,ut.TOTAL_CONTENT_RESOURCE,JSON.stringify([s]));return t!==e.ErrorCode.SUCCESS?(r.error(`spreadCDNInfo failed -> code: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):(r.info("spreadCDNInfo succeed"),{code:exports.RCRTCCode.SUCCESS})}))}function qt(o,i,s){return t(this,void 0,void 0,(function*(){const t=yield o.setRTCData(i,"cdn_uris",JSON.stringify([s]),!0,e.RTCApiType.ROOM);return t!==e.ErrorCode.SUCCESS?(r.error(`setRoomCDNInfo failed -> code: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):(r.info("setRoomCDNInfo succeed"),{code:exports.RCRTCCode.SUCCESS})}))}function Wt(r){return t(this,void 0,void 0,(function*(){const t=r.context,o=r.roomId,n=Object.assign({},r.getCDNUris(),{enableInnerCDN:r.getCDNEnable()});e.logger.info(i.L_LIVING_ROOM_SPREAD_CDN_INFO_T,{roomId:o,CDNUris:n},{logSource:e.LogSource.RTC});const a=(yield Promise.all([Yt(t,o,n),qt(t,o,n)])).every((e=>e.code===exports.RCRTCCode.SUCCESS));return a?e.logger.info(i.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:s.SUCCESSED,CDNUris:n},{logSource:e.LogSource.RTC}):e.logger.error(i.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:s.FAILED,code:exports.RCRTCCode.SIGNAL_ERROR,msg:"signal error"},{logSource:e.LogSource.RTC}),a?{code:exports.RCRTCCode.SUCCESS}:{code:exports.RCRTCCode.SIGNAL_ERROR}}))}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(bt||(bt={})),function(e){e.BEGIN="begin",e.END="end"}(xt||(xt={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(Bt||(Bt={}));class zt extends $t{constructor(e,t){super(),this.headers=e,this.reqBody=t}execute(r,o){var i,s;return t(this,void 0,void 0,(function*(){const t=yield r.service.exchange(this.headers,this.reqBody);if(r.roomMode!==e.RTCMode.LIVE)return t;const o=null===(s=null===(i=t.data)||void 0===i?void 0:i.urls)||void 0===s?void 0:s.pull_url;if(t.code!==exports.RCRTCCode.SUCCESS||!o)return t;const n=JSON.parse(o);return r.setCDNUris(n),(null==n?void 0:n.broadcast)===Bt.SPREAD&&(r.setCDNEnabel(!0),Wt(r)),t}))}}class Qt extends $t{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(o,i){return t(this,void 0,void 0,(function*(){const{tracks:t,forceReq:s}=this,n=o.roomId;if(!e.validate("tracks",t,(()=>e.isArray(t)&&t.every((e=>e instanceof we||e.track instanceof we))),!0))return r.warn(`update sublist failed, tracks is invalid -> roomId: ${n}`),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`update subscribe list -> roomId: ${n}, forceReq: ${s}, tracks: ${t.map(_t)}`);let a=t.map((e=>e instanceof we?{track:e}:Object.assign({},e)));const c={};a=a.filter((e=>{const t=e.track.getTrackId();return o.getRemoteTrack(t)?!c[t]&&(c[t]=!0):(r.warn(`track cannot found in room -> trackId: ${t}`),!1)})).map((e=>Object.assign({},e)));const d=o.getSubscribedList().map((e=>Object.assign({},e)));if(!s){let e=!1;if(a.forEach((t=>{const r=d.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);d.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),d.length&&(e=!0),!e)return{code:exports.RCRTCCode.SUCCESS}}const{pc:_,pushOtherRooms:u,headers:l}=this.subhook(t);_.updateSubRemoteTracks(a.map((e=>e.track)));const R=yield Jt(a,!1,_,o);u&&(R.pushOtherRooms=u);const C=yield new zt(l,R).execute(o,i),p=a.map((e=>e.track.getTrackId()));if(C.code!==exports.RCRTCCode.SUCCESS)return{code:C.code};const{sdp:h,resultCode:T,message:g,subscribedList:m}=C.data;if(T!==exports.RCRTCCode.SUCCESS)return r.error(`change subscribe list failed: ${T}`),{code:T};r.debug(`subscribe success: ${p.join(",")}`);const E=yield _.setRemoteAnswer(h.sdp);if(E!==exports.RCRTCCode.SUCCESS)return{code:E};const S=null==m?void 0:m.map((e=>`${e.msid}_${e.mediaType}`)),I=a.filter((e=>null==S?void 0:S.includes(e.track.getTrackId()))),f=a.filter((e=>!(null==S?void 0:S.includes(e.track.getTrackId())))),L=o.getRemoteTracks();for(const e in L){const t=I.some((t=>t.track.getTrackId()===e));L[e].__innerSetSubscribed(t)}const O=o.getSubscribedList();return O.splice(0,O.length,...I),f.length?{code:exports.RCRTCCode.SUCCESS,failedList:f}:{code:exports.RCRTCCode.SUCCESS}}))}}class Zt extends $t{constructor(e,t){super(),this.tracks=e,this.subhook=t}execute(o,n){return t(this,void 0,void 0,(function*(){const t=this.tracks,a=o.roomId;if(e.logger.info(i.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:t.map(_t)},{logSource:e.LogSource.RTC}),!e.validate("tracks",t,(()=>e.isArray(t)&&t.length>0&&t.every((e=>e instanceof we))),!0))return r.warn(`unsubscribe failed, tracks is invalid -> roomId: ${a}`),e.logger.warn(i.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`unsubscribe -> roomId: ${a}, tracks: ${t.map(_t)}`);const c=o.getSubscribedList().map((e=>Object.assign({},e))).filter((e=>!t.includes(e.track)));return o.polarisReport.sendR2(bt.SUBSCRIBE,xt.END,t.map((e=>e.getTrackId()))),e.logger.info(i.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:t.map(_t),roomId:a},{logSource:e.LogSource.RTC}),new Qt(c,this.subhook,!1).execute(o,n)}))}}class Xt extends $t{constructor(e,t){super(),this.msgContent=e,this.subhook=t}get priority(){return Mt.NORMAL}execute(e,o){return t(this,void 0,void 0,(function*(){const t=[],i=[],s=[],n=[],a={joined:t,left:i,upgrade:s,downgrade:n},{users:c}=this.msgContent;if(0===c.length)return a;for(let t=0;t<c.length;t++){const r=c[t];if(r.extra&&r.extra.roomId!==e.roomId)return a;if(1==+r.state&&!e.getRemoteUserIds().includes(r.userId))return a}c.forEach((o=>{const a=o.userId;if(0==+o.state){r.debug(`user joined -> ${a}`);const i=e.getResourcesByUserId(a);i||(o.switchRoleType?s.push(a):t.push(a)),e.setResourcesByUserId(a,i||[])}else r.debug(`user left -> ${a}`),o.switchRoleType?n.push(a):i.push(a)}));const d=[...i,...n];if(d.length){const t=[],r=[];d.forEach((o=>{t.push(...e.getRemoteTracksByUserId(o)),r.push(o)})),t.length&&(yield new Zt(t,this.subhook).execute(e,o),t.forEach((t=>e.removeRemoteTrack(t.getTrackId())))),r.length&&r.forEach((t=>e.removeResourcesByUserId(t)))}return a}))}}class er extends $t{constructor(e,t,r){super(),this.subhook=e,this.tracks=t,this.onTrackUnpublish=r}execute(e,r){return t(this,void 0,void 0,(function*(){const t=this.tracks;yield new Zt(t,this.subhook).execute(e,r),t.forEach((t=>{t.__innerDestroy(),e.removeRemoteTrack(t.getTrackId())})),this.onTrackUnpublish(t)}))}}class tr extends $t{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(o,n){return t(this,void 0,void 0,(function*(){const{tracks:t,forceReq:a}=this,c=o.roomId;if(e.logger.info(i.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:t.map(_t),forceReq:a},{logSource:e.LogSource.RTC}),!e.validate("tracks",t,(()=>e.isArray(t)&&t.length>0&&t.every((e=>e instanceof we||e.track instanceof we))),!0))return r.warn(`subscribe failed, tracks is invalid -> roomId: ${c}`),e.logger.error(i.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`subscribe -> roomId: ${c}, tracks: ${t.map(_t)}`);const d=o.getSubscribedList().map((e=>Object.assign({},e))),_=t.map((e=>e instanceof we?{track:e}:e));let u=!1;const l=[];return _.forEach((e=>{const t=e.track.getTrackId();l.push(t);const r=d.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:d.push(e),u=!0)})),u||a?(o.polarisReport.sendR2(bt.SUBSCRIBE,xt.BEGIN,l),e.logger.info(i.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:t.map(_t),roomId:c},{logSource:e.LogSource.RTC}),new Qt(d,this.subhook,!0).execute(o,n)):(e.logger.warn(i.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:s.FAILED,code:"",msg:"repeat subscribe"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}}class rr extends $t{constructor(e,t,r,o,i){super(),this.msgContent=e,this.messageType=t,this.senderId=r,this.subhook=o,this.callback=i}get priority(){return Mt.NORMAL}execute(o,i){var s,n;return t(this,void 0,void 0,(function*(){const{uris:t}=this.msgContent,a=[],c=[],d=[];let _;const u=this.senderId,l=this.messageType,R=o.getResourcesByUserId(u)||[];switch(o.setResourcesByUserId(u,R),l){case ut.MODIFY:d.push(...t);break;case ut.PUBLISH:a.push(...t);break;case ut.UNPUBLISH:c.push(...t);break;case ut.TOTAL_CONTENT_RESOURCE:_=Ze(R,t),a.push(..._.publishedList),c.push(..._.unpublishedList),d.push(..._.modifiedList)}if(a.length>0){const e=R.map(qe),t=[],s=[];if(a.forEach((r=>{const i=qe(r),n=e.indexOf(i),{userId:a,tag:c,mediaType:d}=We(i);n>-1?R[n]=r:R.push(r);let _=o.getRemoteTrack(i);_?_.isSubscribed()&&t.push(_):(_=d===exports.RCMediaType.AUDIO_ONLY?new Ve(c,a):new Fe(c,a),o.addRemoteTrack(_),s.push(_)),_.__innerSetRemoteMuted(0===r.state)})),t.length){const e=t.map((e=>e.getTrackId()));r.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:s}=yield new tr(t,this.subhook,!0).execute(o,i);s!==exports.RCRTCCode.SUCCESS&&r.error(`resub tracks failed -> code: ${s}, ids: ${JSON.stringify(e)}`)}this.callback.onTrackPublish(s)}if(c.length>0){const e=c.map(qe);for(let t=R.length-1;t>=0;t-=1){const r=R[t];e.includes(qe(r))&&R.splice(t,1)}const t=c.map((e=>{const t=qe(e);return o.getRemoteTrack(t)}));yield new er(this.subhook,t,this.callback.onTrackUnublish).execute(o,i)}if(d.length>0){const e=R.map(qe);for(let t=0;t<d.length;t+=1){const r=d[t],i=qe(r),s=e.indexOf(i);R[s].state=r.state;const n=o.getRemoteTrack(i);n.__innerSetRemoteMuted(0===r.state),n.isAudioTrack()?this.callback.onAudioMute(n):this.callback.onVideoMute(n)}}if(o.roomMode!==e.RTCMode.LIVE)return;const C=this.msgContent;if(!C.cdn_uris)return;const p=(null===(s=o.getCDNUris())||void 0===s?void 0:s.enableInnerCDN)!==C.cdn_uris[0].enableInnerCDN;o.setCDNUris(C.cdn_uris[0]),p&&this.callback.onCDNEnableChange(!!(null===(n=o.getCDNUris())||void 0===n?void 0:n.enableInnerCDN))}))}}class or extends $t{constructor(e,t){super(),this.tracks=e,this.pubhook=t}_removePubFailedTracks(e,t){e.forEach((e=>{const o=e instanceof De?e:e.track;r.debug(`remove pub failed track from peerconnection -> trackId: ${o.getTrackId()}`),t.removeLocalTrackById(o.getTrackId())}))}__publish(e,o,i,s,n){return t(this,void 0,void 0,(function*(){const{pcName:t,pc:a,headers:c}=o,d=e.roomId,_=[];i.forEach((e=>{const{track:t}=e instanceof De?{track:e}:e;_.push(t)}));if(a.getLocalTracks().length+((e,t)=>{let r=0;return e.forEach((e=>{const o=e instanceof De?e.getTrackId():e.track.getTrackId();t.getLocalTrack(o)||(e instanceof De?r++:e.pubTiny&&e.track.isVideoTrack()&&(r+=2))})),r})(i,a)>10)return r.error(`publish failed, tracks limit exceeded -> roomId: ${d}`),{code:exports.RCRTCCode.PUBLISH_TRACK_LIMIT_EXCEEDED,tracks:_};r.debug(`publish tracks -> roomId: ${d}, tracks: ${i.map(_t)}`),i.forEach((e=>{const{track:t,pubTiny:o}=e instanceof De?{pubTiny:!1,track:e}:e;if(a.addLocalTrack(t),t.isVideoTrack()&&o){let e;try{e=t.__innerGetMediaStreamTrack().clone();const r=o.frameRate||exports.RCFrameRate.FPS_15,i=o.resolution||exports.RCResolution.W176_H144,{width:s,height:n}=et(i),a=ot(r);e.applyConstraints({width:s,height:n,frameRate:a})}catch(o){return null==e||e.stop(),void r.warn(`pubTiny failed -> id: ${t.getTrackId()}, msg: ${o.message}`)}a.addLocalTrack(new Pe(t.getTag(),t.getUserId(),e,!0))}})),a.clearReTryExchangeTimer();const u=e.useMutilPeerC?[]:e.getSubscribedList(),l=yield Jt(u,!1,a,e);s&&(l.pushOtherRooms=s);const R=yield new zt(c,l).execute(e,n);if(R.code!==exports.RCRTCCode.SUCCESS)return r.error(`publish failed -> roomId: ${d}, code: ${R.code}`),this._removePubFailedTracks(i,a),{code:R.code,tracks:_};const{sdp:C,resultCode:p,message:h}=R.data;if(p!==exports.RCRTCCode.SUCCESS)return r.error(`publish failed -> roomId: ${d}, code: ${p}, msg: ${h}`),this._removePubFailedTracks(i,a),{code:p,tracks:_};const T=yield a.setRemoteAnswer(C.sdp);return T!==exports.RCRTCCode.SUCCESS?{code:T,tracks:_}:Object.assign({},R,{tracks:_})}))}_mergePublishRes(o,i){return t(this,void 0,void 0,(function*(){const t=i.crtUserId,s=i.roomId;let n="";const a=[],c=i.getResourcesByUserId(t),d=[...c];let _=[];o.forEach((e=>{if(e.code!==exports.RCRTCCode.SUCCESS){const{tracks:t}=e;return void a.push({code:e.code,tracks:t})}const{publishList:t,urls:r,mcuPublishList:o}=e.data;n=null==r?void 0:r.liveUrl;t.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:i.getTrackState(qe(e))},e))).forEach((e=>{const{isInclude:t,index:r}=((e,t)=>{let r=!1,o=0;for(let i=0;i<t.length;i++){const s=t[i];if(`${e.msid}_${e.mediaType}`==`${s.msid}_${s.mediaType}`){r=!0,o=i;break}}return{isInclude:r,index:o}})(e,d);t?d.splice(r,1,e):d.push(e)}));const s=(null==o?void 0:o.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))))||[];_=s}));const{publishedList:u}=Ze(c,d),l=yield i.context.setRTCTotalRes(s,$e(ut.PUBLISH,u),Ge(d),ut.TOTAL_CONTENT_RESOURCE,Ge(_));if(l!==e.ErrorCode.SUCCESS)return r.error(`send publish streams notification failed: ${l}`),{code:exports.RCRTCCode.SIGNAL_ERROR};i.setResourcesByUserId(t,d);const R=u.map((e=>qe(e)));i.polarisReport&&i.polarisReport.sendR2(bt.PUBLISH,xt.BEGIN,R),u.forEach((e=>{const t=i.useMutilPeerC?`${s}_${e.msid.split("_")[1]}`:`${s}_pub`,{pc:r}=i.peerMgr.getPCItemByPCName(t);r.getLocalTrack(`${e.msid}_${e.mediaType}`).__innerSetPublished(!0)})),r.debug(`publish success: ${R.join(",")}`);const C={code:exports.RCRTCCode.SUCCESS};return n&&(C.liveUrl=n),a.length&&(C.failedTracks=a,C.code=exports.RCRTCCode.SOME_TRACKS_PUBLISH_FAILED),C}))}execute(o,n){return t(this,void 0,void 0,(function*(){const t=this.tracks,a=o.roomId;if(e.logger.info(i.L_ABSTRACT_ROOM_PUBLISH_T,{trackIds:t.map(_t)},{logSource:e.LogSource.RTC}),!e.validate("tracks",t,(()=>e.isArray(t)&&t.length>0&&t.every((e=>e instanceof De||e.track instanceof De))),!0))return r.warn(`publish failed, tracks is invalid -> roomId: ${a}`),e.logger.error(i.L_ABSTRACT_ROOM_PUBLISH_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};const c=[],{plist:d,pushOtherRooms:_}=this.pubhook(t);for(let e=0;e<d.length;e++){const t=d[e];c.push(this.__publish(o,t,t.tracks,_,n))}const u=yield Promise.all(c),l=yield this._mergePublishRes(u,o);return e.logger.info(i.L_ABSTRACT_ROOM_PUBLISH_R,{status:s.SUCCESSED,roomId:a,trackIds:t.map(_t)},{logSource:e.LogSource.RTC}),l}))}}class ir extends $t{constructor(e,t){super(),this.tracks=e,this.unpubhook=t}__unpublish(e,o,i,s){return t(this,void 0,void 0,(function*(){const{pcName:t,pc:n}=i;e.roomId;const a=s.map((e=>e.getTrackId()));if(0===a.map(e.getPublishedResourceByTrackId.bind(e)).filter((e=>!!e)).length)return{code:exports.RCRTCCode.SUCCESS,tracks:s};a.forEach((e=>n.removeLocalTrackById(e))),e.polarisReport.sendR2(bt.PUBLISH,xt.END,a),n.clearReTryExchangeTimer();const c=e.useMutilPeerC?[]:e.getSubscribedList(),d=yield Jt(c,!1,n,e),{pushOtherRooms:_,headers:u}=this.unpubhook(s,t);_&&(d.pushOtherRooms=_);const l=yield new zt(u,d).execute(e,o);return l.code!==exports.RCRTCCode.SUCCESS?(r.error(`exchange failed -> code: ${l.code}`),{code:l.code,tracks:s}):Object.assign({},l,{tracks:s})}))}_mergeUnpublishRes(o,i){return t(this,void 0,void 0,(function*(){const s=o.context.getCurrentId(),n=o.roomId,a=[],c=[],d=[],_=[];let u=[];for(let e=0;e<i.length;e++){const t=i[e];if(t.code!==exports.RCRTCCode.SUCCESS){const{tracks:e}=t;c.push({code:t.code,tracks:e});continue}const{resultCode:s,message:n,mcuPublishList:l}=t.data;s!==exports.RCRTCCode.SUCCESS&&r.error(`unpublish streams failed -> code: ${s}, msg: ${n}`);const R=t.tracks.map((e=>e.getTrackId()));_.push(...R);const C=R.map(o.getPublishedResourceByTrackId.bind(o)).filter((e=>!!e));d.push(...C),a.push(t);const p=l?l.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[];u=p}const l=o.getResourcesByUserId(s).filter((e=>!d.includes(e))),R=yield o.context.setRTCTotalRes(n,$e(ut.UNPUBLISH,d),Ge(l),ut.TOTAL_CONTENT_RESOURCE,Ge(u));if(R!==e.ErrorCode.SUCCESS)return r.error("send unpublish notification failed:",R),{code:exports.RCRTCCode.SIGNAL_ERROR};r.debug(`unpublish success -> tracks: ${_.join(",")}`),a.forEach((e=>t(this,void 0,void 0,(function*(){const{sdp:t}=e.data,{tracks:r}=e,i=o.peerMgr.getPCByTrackId(r[0].getTrackId());yield i.setRemoteAnswer(t.sdp)})))),o.setResourcesByUserId(s,l);const C={code:exports.RCRTCCode.SUCCESS};return c.length&&(C.failedTracks=c,C.code=exports.RCRTCCode.SOME_TRACKS_PUBLISH_FAILED),C}))}execute(o,n){return t(this,void 0,void 0,(function*(){const{crtUserId:t,roomId:a}=o,c=this.tracks;e.logger.info(i.L_ABSTRACT_ROOM_UNPUBLISH_T,{trackIds:c.map(_t)},{logSource:e.LogSource.RTC});if(!e.validate("tracks",c,(()=>c.every((e=>e.getUserId()===t&&e instanceof De))),!0))return r.warn(`unpublish failed, tracks is invalid -> roomId: ${a}, tracks: ${c.map(_t)}`),e.logger.error(i.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};const d=o.peerMgr.createPeerCList(c),_=[];for(let e=0;e<d.length;e++){const{tracks:t}=d[e];_.push(this.__unpublish(o,n,d[e],t))}const u=yield Promise.all(_),l=yield this._mergeUnpublishRes(o,u);return e.logger.info(i.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:s.SUCCESSED,roomId:a,trackIds:c.map(_t)},{logSource:e.LogSource.RTC}),l}))}}class sr extends $t{constructor(e){super(),this.localTrack=e}execute(o,i){return t(this,void 0,void 0,(function*(){const{localTrack:t}=this,i=t.getTrackId(),{crtUserId:s,roomId:n}=o,a=[{resourceId:i,enabled:!t.isLocalMuted()}],c=o.getResourcesByUserId(s),d=[];for(let e=0;e<c.length;e+=1){const t=c[e],r=qe(t),o=a.findIndex((e=>e.resourceId===r));if(o>=0){const{enabled:e}=a[o];t.state=e?1:0,d.push(t);break}}const _=yield o.context.setRTCTotalRes(n,$e(ut.MODIFY,d),Ge(c),ut.TOTAL_CONTENT_RESOURCE);_!==e.ErrorCode.SUCCESS&&r.error("notice `track.enabled` change failed -> code: "+_)}))}}class nr extends $t{constructor(e,t,r){super(),this.pcName=e,this.isPub=t,this.retryHook=r}get priority(){return Mt.HIGH}execute(e,o){return t(this,void 0,void 0,(function*(){const{pcName:t,isPub:i}=this,{useMutilPeerC:s}=e,{pc:n}=e.peerMgr.getPCItemByPCName(t),a=i&&s?[]:e.getSubscribedList(),c=yield Jt(a,!0,n,e),{pushOtherRooms:d,headers:_}=this.retryHook(t);d&&(c.pushOtherRooms=d);const u=yield new zt(_,c).execute(e,o);if(u.code!==exports.RCRTCCode.SUCCESS)return void r.error(`reTryExchange failed: ${u.code}, pcName: ${t}`);const{sdp:l,resultCode:R}=u.data;R===exports.RCRTCCode.SUCCESS?(n.clearReTryExchangeTimer(),yield n.setRemoteAnswer(l.sdp)):r.error(`reTryExchange failed: ${R}, pcName: ${t}`)}))}}class ar extends $t{constructor(e,t,r){super(),this.subhook=e,this.callbacks=t,this.livingType=r}get priority(){return Mt.HIGH}execute(o,n){return t(this,void 0,void 0,(function*(){const{livingType:t}=this,{roomId:a,crtUserId:c,roomMode:d}=o;e.logger.info(i.L_ABSTRACT_ROOM_RECONNECTED_T,{livingType:t},{logSource:e.LogSource.RTC});if(o.peerMgr.getPCList().some((e=>"closed"===e.getRTCPeerConn().connectionState)))return r.warn("RTCPeerConnection closed. Please rejoin room to restore services."),e.logger.error(i.L_ABSTRACT_ROOM_RECONNECTED_R,{status:s.FAILED,code:"",msg:"RTCPeerConnection disconnected"},{logSource:e.LogSource.RTC}),void this.callbacks.onPeerClosed();const{code:_,data:u}=yield o.context.joinRTCRoom(a,d,t);if(_!==e.ErrorCode.SUCCESS)return r.error(`RTC __onReconnected getRTCRoomInfo failed: ${_}`),void e.logger.error(i.L_ABSTRACT_ROOM_RECONNECTED_R,{status:s.FAILED,code:_,msg:""},{logSource:e.LogSource.RTC});r.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(u)}`);const l=[],R={},C={},p={},h=dt(u,a),T=Object.keys(h),g=o.getAllUserIds();for(let e=T.length-1;e>=0;e-=1){const t=T[e],r=g.indexOf(t);if(-1===r){l.push(t),R[t]=Qe(h[t]);continue}const i=o.getResourcesByUserId(t),s=h[t],{publishedList:n,modifiedList:a,unpublishedList:c}=Ze(i,s,!0);R[t]=Qe(n),C[t]=Qe(c),p[t]=Qe(a),g.splice(r,1)}g.length&&g.forEach((e=>{o.removeResourcesByUserId(e)})),o.assignRoomData(h),g.length&&this.callbacks.onUserLeave(g),l.length&&this.callbacks.onUserJoin(l);for(const e in C){if(e===c)continue;const t=C[e];if(t.length){const e=t.map((e=>o.getRemoteTrack(qe(e))));yield new er(this.subhook,e,this.callbacks.onTrackUnpublish).execute(o,n)}}return Object.keys(R).forEach((e=>{const t=R[e];if(0===t.length)return;const r=t.map((e=>{const t=qe(e),{userId:r,tag:i,mediaType:s}=We(t),n=s===exports.RCMediaType.AUDIO_ONLY?new Ve(i,r):new Fe(i,r);return o.addRemoteTrack(n),n.__innerSetRemoteMuted(0===e.state),n}));this.callbacks.onTrackPublish(r)})),Object.keys(p).forEach((e=>{p[e].forEach((e=>{const t=qe(e),r=o.getRemoteTrack(t);r.__innerSetRemoteMuted(0===e.state),r.isAudioTrack()?this.callbacks.onAudioMuteChange(r):this.callbacks.onVideoMuteChange(r)}))})),o.roomMode===e.RTCMode.LIVE&&this.executeInLivingRoom(o,u),e.logger.info(i.L_ABSTRACT_ROOM_RECONNECTED_R,{status:s.SUCCESSED,roomData:u},{logSource:e.LogSource.RTC}),{data:u}}))}executeInLivingRoom(t,r){var o,n;if(e.logger.error(i.L_LIVING_ROOM_RECONNECTED_T,{roomData:r},{logSource:e.LogSource.RTC}),!r)return void e.logger.info(i.L_LIVING_ROOM_RECONNECTED_R,{status:s.FAILED,code:"",msg:"room not fond"},{logSource:e.LogSource.RTC});const a=null===(o=r.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===o?void 0:o.value;if(!a)return void e.logger.error(i.L_LIVING_ROOM_RECONNECTED_R,{status:s.FAILED,code:"",msg:"cdn_uris not found"},{logSource:e.LogSource.RTC});const c=JSON.parse(a),d=(null===(n=t.getCDNUris())||void 0===n?void 0:n.enableInnerCDN)!==c.enableInnerCDN;t.setCDNUris(c),e.logger.info(i.L_LIVING_ROOM_RECONNECTED_R,{status:s.SUCCESSED,roomData:r},{logSource:e.LogSource.RTC}),d&&this.callbacks.onCDNEnableChange(c.enableInnerCDN)}}const cr="evt-leave";class dr extends e.EventEmitter{constructor(e,t,r,o,i,s,n,a,c,d=Ct()){super(),this._context=e,this._runtime=t,this._roomId=r,this._service=i,this._initOptions=s,this._useMutilPeerC=c,this._clientSessionId=d,this._appListener=null,this._reportListener=null,this._onRecvPKMsg=null,this._polarisReport=new wt(this._context,this._runtime,this._roomId,this),this._peerCManager=new Ft(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._invoker=new Kt(this._context,this._service,this._peerCManager,r,this._context.getCurrentId(),o,this._polarisReport,n,a),this._store=this._invoker.store}__innerInit(e,r,o,i,s){return t(this,void 0,void 0,(function*(){const{code:t,data:n}=yield this._invoker.push(new jt(this._roomId,e,r,o,i,s));return t!==exports.RCRTCCode.SUCCESS?{code:t}:(this._initWithRoomData(n.offlineKickTime),{code:t,data:n})}))}_initWithRoomData(e){var t;this._pinger=new Rt(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(t,o,i){if(this._useMutilPeerC)return void r.error("`RCAbstractRoom.setBitrate` is disabled, use `RCLocalTrack.setBitrate` instead.");r.warn("`RCAbstractRoom.setBitrate` will be deprecated, use `RCLocalTrack.setBitrate` instead."),e.assert("max",t,(t=>e.isNumber(t)&&t>Math.max(o||1,200)),!0),e.assert("min",o,(r=>e.isNumber(r)&&r>=1&&(!e.isNumber(t)||r<t)),!0),e.assert("start",i,(r=>e.isNumber(r)&&r>o&&r<=t));this._peerCManager.getPCList().forEach((e=>{e.setBitrate(t,o,i)}))}_onTrackReady(e){const t=e.streams[0].id,o=e.receiver.track,i=[t,"audio"===o.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY].join("_"),s=this._store.getRemoteTrack(i);s?(s.__innerSetMediaStreamTrack(o),this._callAppListener("onTrackReady",s)):r.warn(`cannot found remote track ${o.id}`)}_callAppListener(t,...o){var n;"onPing"!==t&&e.logger.info(i.L_ABSTRACT_ROOM_CALL_APP_LISTENER_O,{status:s.SUCCESSED,eventType:t,attrs:o},{logSource:e.LogSource.RTC}),"onPing"!==t&&r.info(`${t} callback ->`,...o);const a=null===(n=this._appListener)||void 0===n?void 0:n[t];if(a)try{a(...o)}catch(e){r.error(e)}}_onTrackUnpublish(e){this._callAppListener("onTrackUnpublish",e)}__parseInnerMessage(t){const{targetId:o,conversationType:i}=t;if(i!==e.ConversationType.RTC_ROOM)return!1;if(o!==this._roomId)return!0;r.info(`recv inner msg -> message: ${JSON.stringify(t)} | roomid: ${this._roomId}`);const s=t.content;switch(t.messageType){case ut.KICK:this._kickoff(!0,s);break;case ut.STATE:this._stateHandle(s);break;case ut.MODIFY:case ut.PUBLISH:case ut.UNPUBLISH:case ut.TOTAL_CONTENT_RESOURCE:this._resourceHandle(s,t.messageType,t.senderUserId);break;case ut.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",t.messageType,t.content);break;case ut.USER_NOTIFY:r.warn(`TODO: ${ut.USER_NOTIFY}`);break;case ut.PK_INVITE:case ut.PK_CANCEL_INVITE:case ut.PK_INVITE_TIMEOUT:case ut.PK_INVITE_ANSWER:case ut.PK_END:this._onRecvPKMsg&&this._onRecvPKMsg(t);break;case ut.OTHER_ROOM_OFFLINE:break;default:this._callAppListener("onMessageReceive",t.messageType,t.content,t.senderUserId,t.messageUId)}return!0}_kickoff(e,o){return t(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;let t;r.warn(`onKickOff -> byServer: ${e}`),this.emit(cr),this._leaveHandle(!e),e&&((null==o?void 0:o.users)||[]).forEach((e=>{e.userId===this._context.getCurrentId()&&(t=e.type)})),this._callAppListener("onKickOff",e,t)}))}_rtcpeerClosed(){this.emit(cr),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,r,o){return t(this,void 0,void 0,(function*(){const{uris:t,ignore:i}=e;!i&&t&&this._invoker.push(new rr(e,r,o,this._subhook.bind(this),{onAudioMute:this._onAudioMuteChange.bind(this),onVideoMute:this._onVideoMuteChange.bind(this),onTrackPublish:this._onTrackPublish.bind(this),onTrackUnublish:this._onTrackUnpublish.bind(this),onCDNEnableChange:this._callAppListener.bind(this,"onCDNEnableChange")}))}))}_onTrackPublish(e){this._callAppListener("onTrackPublish",e)}_stateHandle(e){var r;return t(this,void 0,void 0,(function*(){const{left:t,joined:o,upgrade:i,downgrade:s}=yield this._invoker.push(new Xt(e,this._subhook.bind(this)));if(null===(r=this._appListener)||void 0===r?void 0:r.onSwitchRole)return i.length&&i.forEach((e=>this._callAppListener("onSwitchRole",e,exports.RCRTCLiveRole.ANCHOR))),s.length&&s.forEach((e=>this._callAppListener("onSwitchRole",e,exports.RCRTCLiveRole.AUDIENCE))),o.length&&this._callAppListener("onUserJoin",o),void(t.length&&this._callAppListener("onUserLeave",t));const n=[...o,...i],a=[...t,...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(o,n){return t(this,void 0,void 0,(function*(){e.logger.info(i.L_ABSTRACT_ROOM_SEND_MESSAGE_T,{name:o,content:n},{logSource:e.LogSource.RTC});const{code:t}=yield this._context.sendMessage(e.ConversationType.RTC_ROOM,this._roomId,{messageType:o,content:n,isStatusMessage:!0});return t!==e.ErrorCode.SUCCESS?(r.error(`send message failed -> code: ${t}`),e.logger.error(i.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:s.FAILED,code:t,msg:""},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_ERROR}):(e.logger.info(i.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:s.SUCCESSED,name:o,content:n},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}setRoomAttribute(o,n,a,c=!1){return t(this,void 0,void 0,(function*(){e.logger.info(i.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_T,{roomId:this._roomId,key:o,value:n,message:a,isInner:c},{logSource:e.LogSource.RTC});const t=yield this._context.setRTCData(this._roomId,o,n,c,e.RTCApiType.ROOM,a);return t!==e.ErrorCode.SUCCESS?(r.error(`SetRoomAttributeValue Failed: ${t}`),e.logger.error(i.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:s.FAILED,code:t,msg:""},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_ERROR}):(e.logger.info(i.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:s.SUCCESSED,roomId:this._roomId,key:o,value:n,message:a,isInner:c},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}deleteRoomAttributes(o,n,a=!1){return t(this,void 0,void 0,(function*(){e.logger.info(i.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_T,{roomId:this._roomId,keys:o,message:n,isInner:a},{logSource:e.LogSource.RTC});const t=yield this._context.removeRTCData(this._roomId,o,a,e.RTCApiType.ROOM,n);return t!==e.ErrorCode.SUCCESS?(r.error(`DeleteRoomAttribute Failed: ${t}`),e.logger.error(i.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:s.FAILED,code:t,msg:""},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_ERROR}):(e.logger.info(i.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:s.SUCCESSED,roomId:this._roomId,keys:o,message:n,isInner:a},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}getRoomAttributes(o=[],i=!1){return t(this,void 0,void 0,(function*(){const{code:t,data:s}=yield this._context.getRTCData(this._roomId,o,i,e.RTCApiType.ROOM);return t!==e.ErrorCode.SUCCESS?(r.error(`GetRoomAttributes Failed: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):{code:exports.RCRTCCode.SUCCESS,data:s}}))}_setUserAttributeValue(t,r,o){return this._context.setRTCData(this._roomId,t,r,!1,e.RTCApiType.PERSON,o)}_deleteUserAttributes(t,r){return this._context.removeRTCData(this._roomId,t,!1,e.RTCApiType.PERSON,r)}_getUserAttributes(t){return this._context.getRTCData(this._roomId,t,!1,e.RTCApiType.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 r;return t(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;this._invoker.destroy(),this._muteRemoteTracksBeforeQuit(),null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),e&&(yield this._context.quitRTCRoom(this._roomId)),this._store.isMainRoom&&(yield this._quitAllPKRoom()),this._pinger.stop();const t=[];Object.keys(this._peerCManager.getMutilPeerCData()).forEach((e=>{t.push(this._service.exit(this._getRTCReqestHeaders(e)))})),yield Promise.all(t),this._releasePCManager(),this._polarisReport=null}))}_releasePCManager(){const e=this._peerCManager.getPCList();null==e||e.forEach((e=>{e.off(De.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(De.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)})),this._peerCManager.clear(),this._peerCManager=null}_onLocalTrackDestroied(e){e instanceof Pe&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(e){return t(this,void 0,void 0,(function*(){this._invoker.push(new sr(e))}))}publish(e){return t(this,void 0,void 0,(function*(){return this._invoker.push(new or(e,this._pubhook.bind(this)))}))}_getPushOtherRoomsParams(){return[]}_reTryExchange(e,r){return t(this,void 0,void 0,(function*(){this._invoker.push(new nr(e,r,(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 t(this,void 0,void 0,(function*(){return this._invoker.push(new ir(e,((e,t)=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(t)}))))}))}_getResourceById(e){return this._store.getPublishedResourceByTrackId(e)}_isValidResourceId(e){var t;const{userId:r}=We(e);return!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>qe(t)===e)))}_subhook(e){const{pc:t,pcName:r}=this._peerCManager.createPeerCList(e)[0];return t.on(yt.__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(De.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.on(De.__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 t(this,void 0,void 0,(function*(){return this._invoker.push(new tr(e,this._subhook.bind(this),!1))}))}unsubscribe(e){return t(this,void 0,void 0,(function*(){return this._invoker.push(new Zt(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 t(this,void 0,void 0,(function*(){return this._invoker.push(new Qt(e,this._subhook.bind(this),!1))}))}registerRoomEventListener(t){e.logger.info(i.L_ABSTRACT_ROOM_REGISTER_ROOM_EVENT_LISTENER_O,{status:s.SUCCESSED,listener:t&&Object.keys(t)},{logSource:e.LogSource.RTC}),this._appListener=t}registerReportListener(t){e.logger.info(i.L_ABSTRACT_ROOM_REGISTER_REPORT_LISTENER_O,{status:s.SUCCESSED,listener:t&&Object.keys(t)},{logSource:e.LogSource.RTC}),this._reportListener=t}onAudioLevelChange(t,r){var o;e.logger.info(i.L_ABSTRACT_ROOM_AUDIO_LEVEL_O,{status:s.SUCCESSED,handler:null==t?void 0:t.name,gap:r},{logSource:e.LogSource.RTC}),null===(o=this._audioLevelReport)||void 0===o||o.clearAudioLevelReportTimer(),this._audioLevelReport=new Vt(this),this._audioLevelReport.onAudioLevelChange(t,r||1e3)}__onReconnected(e){return t(this,void 0,void 0,(function*(){return this._invoker.push(new ar(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 _r extends $t{constructor(e,t){super(),this.data=e,this.cdnValues=t}execute(e,o){var i,s,n,a;return t(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:o,res:c}=yield e.service.setMcuConfig(t,this.data);if(o!==exports.RCRTCCode.SUCCESS)return r.error(`set MCU config failed: ${o}`),{code:o};r.info("set MCU config success"),c.pull_url&&e.setCDNUris(JSON.parse(c.pull_url));const d=this.cdnValues;return o===exports.RCRTCCode.SUCCESS&&((null===(s=null===(i=d.output)||void 0===i?void 0:i.video.normal)||void 0===s?void 0:s.width)||(null===(a=null===(n=d.output)||void 0===n?void 0:n.video.normal)||void 0===a?void 0:a.fps))&&Wt(e),{code:o,res:c}}))}}var ur,lr,Rr,Cr;exports.BackgroundPictureFillMode=void 0,(ur=exports.BackgroundPictureFillMode||(exports.BackgroundPictureFillMode={}))[ur.CROP=1]="CROP",ur[ur.WHOLE=2]="WHOLE",exports.MixLayoutMode=void 0,(lr=exports.MixLayoutMode||(exports.MixLayoutMode={}))[lr.CUSTOMIZE=1]="CUSTOMIZE",lr[lr.SUSPENSION=2]="SUSPENSION",lr[lr.ADAPTATION=3]="ADAPTATION",exports.MixVideoRenderMode=void 0,(Rr=exports.MixVideoRenderMode||(exports.MixVideoRenderMode={}))[Rr.CROP=1]="CROP",Rr[Rr.WHOLE=2]="WHOLE",function(e){e[e.AUDIO_VIDEO_ALL=0]="AUDIO_VIDEO_ALL",e[e.AUDIO_VIDEO_NO=1]="AUDIO_VIDEO_NO",e[e.AUDIO_ALL_VIDEO_NO=2]="AUDIO_ALL_VIDEO_NO",e[e.AUDIO_NO_VIDEO_ALL=3]="AUDIO_NO_VIDEO_ALL",e[e.AUDIO_VIDEO_INPUT=4]="AUDIO_VIDEO_INPUT",e[e.AUDIO_ALL_VIDEO_INPUT=5]="AUDIO_ALL_VIDEO_INPUT",e[e.AUDIO_NO_VIDEO_INPUT=6]="AUDIO_NO_VIDEO_INPUT",e[e.AUDIO_INPUT_VIDEO_ALL=7]="AUDIO_INPUT_VIDEO_ALL",e[e.AUDIO_INPUT_VIDEO_NO=8]="AUDIO_INPUT_VIDEO_NO",e[e.ROOM_AUDIO_VIDEO_APPEND=9]="ROOM_AUDIO_VIDEO_APPEND",e[e.ROOM_AUDIO_VIDEO_NOT_APPEND=10]="ROOM_AUDIO_VIDEO_NOT_APPEND",e[e.ROOM_AUDIO_APPEND=11]="ROOM_AUDIO_APPEND",e[e.ROOM_AUDIO_NOT_APPEND=12]="ROOM_AUDIO_NOT_APPEND",e[e.ROOM_VIDEO_APPEND=13]="ROOM_VIDEO_APPEND",e[e.ROOM_VIDEO_NOT_APPEND=14]="ROOM_VIDEO_NOT_APPEND"}(Cr||(Cr={}));const pr=()=>({version:1,mode:exports.MixLayoutMode.SUSPENSION});class hr{constructor(e,t){this._invoker=e,this._isValidTrackId=t,this._values=pr()}setHostVideoTrack(t){if(r.info(`setHostVideoTrack -> videoTrackId: ${t}`),!this._isValidTrackId(t))return r.error(`setHostVideoTrack failed -> videoTrackId is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:s.FAILED,code:"",msg:"params error -> videoTrackId"},{logSource:e.LogSource.RTC}),this;const{mediaType:o,tag:n,userId:a}=We(t);return o!==exports.RCMediaType.VIDEO_ONLY?(r.error(`setHostVideoTrack failed -> kind of resource is not 'video' -> ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:s.FAILED,code:"",msg:"not video"},{logSource:e.LogSource.RTC}),this):(this._values.host_stream_id=ze(a,n),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:s.SUCCESSED,videoTrackId:t},{logSource:e.LogSource.RTC}),this)}setMixLayoutMode(t){r.info(`setMixLayoutMode -> mode: ${t}`);return[exports.MixLayoutMode.CUSTOMIZE,exports.MixLayoutMode.SUSPENSION,exports.MixLayoutMode.ADAPTATION].includes(t)?(this._values.mode=t,e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:s.SUCCESSED,mode:t},{logSource:e.LogSource.RTC}),this):(r.error(`setMixLayoutMode failed -> mode is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:s.SUCCESSED,code:"",msg:`params error -> mode: ${t}`},{logSource:e.LogSource.RTC}),this)}_addOutputValue(e,t,r="normal"){const o=this._values.output||(this._values.output={video:{normal:{width:640,height:480}}});if("cdn"===e)return void(o.cdn=t);if("audio"===e)return void(o.audio={bitrate:t});const i=o.video;if("normal"!==r&&"tiny"!==r)if("backgroundColor"!==r)if("exparams"!==r){if("backgroundPicture"===r){const e=i.backgroundPicture||(i.backgroundPicture={fillMode:exports.BackgroundPictureFillMode.CROP,picture:[]});Object.assign(e,t)}}else i.exparams={renderMode:t};else i.backgroundColor=t;else{const e=i[r]||(i[r]={});Object.assign(e,t)}}setOutputVideoResolution(t){if(r.info(`setOutputVideoResolution -> resolution: ${t}`),!tt(t))return r.error(`setOutputVideoResolution failed -> resolution is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:s.FAILED,code:"",msg:`params error -> resolution: ${t}`},{logSource:e.LogSource.RTC}),this;const{width:o,height:n}=et(t);return this._addOutputValue("video",{width:o,height:n},"normal"),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:s.SUCCESSED,resolution:t},{logSource:e.LogSource.RTC}),this}setOutputVideoFPS(t){if(r.info(`setOutputVideoFPS -> fps: ${t}`),!rt(t))return r.error(`setOutputVideoFPS failed -> fps is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:s.FAILED,code:"",msg:`params error -> fps: ${t}`},{logSource:e.LogSource.RTC}),this;const o=ot(t);return this._addOutputValue("video",{fps:o},"normal"),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:s.SUCCESSED,fps:t},{logSource:e.LogSource.RTC}),this}setOutputVideoBitrate(t){return r.info(`setOutputVideoBitrate -> bitrate: ${t}`),!e.isNumber(t)||t<=0?(r.error(`setOutputVideoBitrate failed -> bitrate is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:s.FAILED,code:"",msg:`params error -> bitrate: ${t}`},{logSource:e.LogSource.RTC})):this._addOutputValue("video",{bitrate:t},"normal"),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:s.SUCCESSED,bitrate:t},{logSource:e.LogSource.RTC}),this}setOutputTinyVideoResolution(t){if(r.info(`setOutputTinyVideoResolution -> resolution: ${t}`),!tt(t))return r.error(`setOutputTinyVideoResolution failed -> resolution is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:s.FAILED,code:"",msg:`params error -> resolution: ${t}`},{logSource:e.LogSource.RTC}),this;const{width:o,height:n}=et(t);return this._addOutputValue("video",{width:o,height:n},"tiny"),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:s.SUCCESSED,resolution:t},{logSource:e.LogSource.RTC}),this}setOutputTinyVideoFPS(t){if(r.info(`setOutputTinyVideoFPS -> fps: ${t}`),!rt(t))return r.error(`setOutputTinyVideoFPS failed -> fps is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:s.FAILED,code:"",msg:`params error -> fps: ${t}`},{logSource:e.LogSource.RTC}),this;const o=ot(t);return this._addOutputValue("video",{fps:o},"tiny"),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:s.SUCCESSED,fps:t},{logSource:e.LogSource.RTC}),this}setOutputTinyVideoBitrate(t){return r.info(`setOutputTinyVideoBitrate -> bitrate: ${t}`),!e.isNumber(t)||t<=0?(r.error(`setOutputTinyVideoBitrate failed -> bitrate is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:s.FAILED,code:"",msg:`params error -> bitrate: ${t}`},{logSource:e.LogSource.RTC})):this._addOutputValue("video",{bitrate:t},"tiny"),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:s.SUCCESSED,bitrate:t},{logSource:e.LogSource.RTC}),this}setOutputVideoRenderMode(t){return r.info(`setOutputVideoRenderMode -> renderMode: ${t}`),[exports.MixVideoRenderMode.CROP,exports.MixVideoRenderMode.WHOLE].includes(t)?this._addOutputValue("video",t,"exparams"):(r.error(`setOutputVideoRenderMode failed -> renderMode is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:s.FAILED,code:"",msg:`params error -> renderMode: ${t}`},{logSource:e.LogSource.RTC})),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:s.SUCCESSED,renderMode:t},{logSource:e.LogSource.RTC}),this}setOutputAudioBitrate(t){return r.info(`setOutputAudioBitrate -> bitrate: ${t}`),e.isNumber(t)&&t>0?this._addOutputValue("audio",t):(r.error(`setOutputAudioBitrate failed -> bitrate is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:s.FAILED,code:"",msg:`params error -> bitrate: ${t}`},{logSource:e.LogSource.RTC})),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:s.SUCCESSED,bitrate:t},{logSource:e.LogSource.RTC}),this}setOutputBackgroundColor(t){return r.info(`setOutputBackgroundColor -> color: ${t}`),/^0x[a-fA-F0-9]{6}$/.test(t)?this._addOutputValue("video",t,"backgroundColor"):(r.error(`setOutputBackgroundColor failed -> color is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:s.FAILED,code:"",msg:`params error -> color: ${t}`},{logSource:e.LogSource.RTC})),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:s.SUCCESSED,color:t},{logSource:e.LogSource.RTC}),this}addOutputBackgroundPicture(t,o,n,a,c){var d,_,u;if(r.info(`addOutputBackgroundPicture -> uri: ${t}, x: ${o}, y: ${n}, w: ${a}, h: ${c}`),!e.isHttpUrl(t))return r.error(`addOutputBackgroundPicture failed -> uri is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:s.FAILED,code:"",msg:`params error -> uri: ${t}`},{logSource:e.LogSource.RTC}),this;if([o,n,a,c].some((t=>!e.isNumber(t)||t<0||t>1)))return r.error(`addOutputBackgroundPicture failed -> some attrs of (x, y, w, h) is invalid: ${o}, ${n}, ${a}, ${c}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:s.FAILED,code:"",msg:`params error -> x: ${o}, y: ${n}, w: ${a}, h: ${c}`},{logSource:e.LogSource.RTC}),this;const l=(null===(u=null===(_=null===(d=this._values.output)||void 0===d?void 0:d.video)||void 0===_?void 0:_.backgroundPicture)||void 0===u?void 0:u.picture)||[];return l.push({uri:t,w:a,h:c,x:o,y:n}),this._addOutputValue("video",{picture:l},"backgroundPicture"),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:s.SUCCESSED,uri:t,x:o,y:n,w:a,h:c},{logSource:e.LogSource.RTC}),this}removeOutputBackgroundPicture(t){var o,n,a;if(r.info(`removeOutputBackgroundPicture -> uri: ${t}`),!e.isHttpUrl(t))return r.error(`removeOutputBackgroundPicture failed -> uri is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:s.FAILED,code:"",msg:`params error -> uri: ${t}`},{logSource:e.LogSource.RTC}),this;let c=null===(a=null===(n=null===(o=this._values.output)||void 0===o?void 0:o.video)||void 0===n?void 0:n.backgroundPicture)||void 0===a?void 0:a.picture;return c&&(c=c.filter((e=>e.uri!==t)),this._addOutputValue("video",{pictures:c},"backgroundPicture")),e.logger.info(i.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:s.SUCCESSED,uri:t},{logSource:e.LogSource.RTC}),this}clearOutputBackgroundPicture(){return r.info("clearOutputBackgroundPicture ->"),this._addOutputValue("video",{pictures:[]},"backgroundPicture"),e.logger.info(i.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this}setOutputBackgroundPictureFillMode(t){return r.info(`setOutputBackgroundPictureFillMode -> fillMode: ${t}`),[exports.BackgroundPictureFillMode.CROP,exports.BackgroundPictureFillMode.WHOLE].includes(t)?this._addOutputValue("video",{fillMode:t},"backgroundPicture"):(r.error(`setOutputBackgroundPictureFillMode failed -> fillMode is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:s.FAILED,code:"",msg:`params error -> fillMode: ${t}`},{logSource:e.LogSource.RTC})),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:s.SUCCESSED,fillMode:t},{logSource:e.LogSource.RTC}),this}addPublishStreamUrls(t){var o,n;r.info(`addPublishStreamUrls -> urls: ${t.join(",")}`);const a=/^rtmp:\/\/.+/;if(!e.isArray(t)||0===t.length||t.some((e=>!a.test(e))))return r.error(`addPublishStreamUrls failed -> urls is invalid: ${t.join(",")}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:s.FAILED,code:"",msg:`params error -> urls: ${t.join(",")}`},{logSource:e.LogSource.RTC}),this;const c=(null===(n=null===(o=this._values.output)||void 0===o?void 0:o.cdn)||void 0===n?void 0:n.concat())||[];let d=!1;return t.forEach((e=>{c.some((t=>t.pushurl===e))||(d=!0,c.push({pushurl:e}))})),c.length>5?(r.error("addPublishStreamUrls failed -> publish stream urls no more than 5!"),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:s.FAILED,code:"",msg:`params error -> publish stream urls no more than 5, length: ${t.length}`},{logSource:e.LogSource.RTC}),this):(d&&this._addOutputValue("cdn",c),e.logger.info(i.L_MCU_CONFIG_BUILDER_ADD_PUBLISH_STREAM_URLS_O,{status:s.SUCCESSED,urls:t},{logSource:e.LogSource.RTC}),this)}removePublishStreamUrls(t){var o,n;r.info(`removePublishStreamUrls -> urls: ${t.join(",")}`);const a=/^rtmp:\/\/.+/;if(!e.isArray(t)||0===t.length||t.some((e=>!a.test(e))))return r.error(`removePublishStreamUrls failed -> urls contain invalid items: ${t.join(",")}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:s.FAILED,code:"",msg:`params error -> urls: ${t.join(",")}`},{logSource:e.LogSource.RTC}),this;const c=(null===(n=null===(o=this._values.output)||void 0===o?void 0:o.cdn)||void 0===n?void 0:n.concat())||[];for(let e=c.length-1;e>=0;e-=1){const{pushurl:r}=c[e],o=t.indexOf(r);o>=0&&(t.splice(o,1),c.splice(e,1))}return this._addOutputValue("cdn",c),e.logger.info(i.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:s.SUCCESSED,urls:t},{logSource:e.LogSource.RTC}),this}clearPublishStreamUrls(){return r.info("clearPublishStreamUrls ->"),this._addOutputValue("cdn",[]),e.logger.info(i.L_MCU_CONFIG_BUILDER_CLEAR_PUBLISH_STREAM_URLS_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this}addCustomizeLayoutVideo(t,o,n,a,c){if(r.info(`addCustomizeLayoutVideo -> trackId: ${t}, x: ${o}, y: ${n}, width: ${a}, height: ${c}`),!e.notEmptyString(t)||!this._isValidTrackId(t))return r.error(`addCustomizeLayoutVideo failed -> trackId is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.FAILED,code:"",msg:`params error -> trackId: ${t}`},{logSource:e.LogSource.RTC}),this;if(!e.isNumber(o)||!e.isNumber(n))return r.error(`addCustomizeLayoutVideo failed -> some attrs of (x, y) is invalid: ${o}, ${n}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.FAILED,code:"",msg:`params error -> x: ${o}, y: ${n}`},{logSource:e.LogSource.RTC}),this;if([a,c].some((t=>!e.isNumber(t)||t<0)))return r.error(`addCustomizeLayoutVideo failed -> some attrs of (width, height) is invalid: ${a}, ${c}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.FAILED,code:"",msg:`params error -> width: ${a}, height: ${c}`},{logSource:e.LogSource.RTC}),this;const{userId:d,tag:_,mediaType:u}=We(t);if(u!==exports.RCMediaType.VIDEO_ONLY)return r.error(`addCustomizeLayoutVideo failed -> kind of trackId is not 'video': ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.FAILED,code:"",msg:`params error -> trackId: ${t}的资源不是视频`},{logSource:e.LogSource.RTC}),this;const l=ze(d,_),R=this._values.input||(this._values.input={}),C=R.video||(R.video=[]);return C.some((e=>e.height===c&&e.width===a&&e.stream_id===l&&e.user_id===d&&e.x===o&&e.y===n))?(e.logger.warn(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.FAILED,code:"",msg:"Duplicate configuration item ignored"},{logSource:e.LogSource.RTC}),this):(C.push({user_id:d,stream_id:l,x:o,y:n,width:a,height:c}),e.logger.info(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.SUCCESSED,trackId:t,x:o,y:n,width:a,height:c},{logSource:e.LogSource.RTC}),this)}removeCustomizeLayoutVideo(t){if(r.info(`clearCustomizeInputAudio -> trackId: ${t}`),!this._isValidTrackId(t))return r.error(`clearCustomizeInputAudio failed -> trackId is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.FAILED,code:"",msg:`params error -> trackId: ${t}`},{logSource:e.LogSource.RTC}),this;const{userId:o,tag:n,mediaType:a}=We(t);if(a!==exports.RCMediaType.VIDEO_ONLY)return r.error(`clearCustomizeInputAudio failed -> kind of trackId is not 'video': ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.FAILED,code:"",msg:`params error -> trackId: ${t}的资源不是视频`},{logSource:e.LogSource.RTC}),this;const c=ze(o,n),d=this._values.input;return(null==d?void 0:d.video)&&d.video.length>0&&(d.video=d.video.filter((e=>e.stream_id===c))),e.logger.info(i.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.SUCCESSED,trackId:t},{logSource:e.LogSource.RTC}),this}clearCustomizeLayoutVideo(){r.info("clearCustomizeLayoutVideo ->");const t=this._values.input;return null==t||delete t.video,e.logger.info(i.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this}setCustomizeInputAudio(t){if(r.info(`setCustomizeInputAudio -> trackIds: ${t.join(",")}`),t.some((e=>this._isValidTrackId(e))))return r.warn(`setCustomizeInputAudio failed -> trackIds contain invalid items: $${t.join(",")}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:s.FAILED,code:"",msg:`params error -> trackIds: ${t.join(",")}`},{logSource:e.LogSource.RTC}),this;return(this._values.input||(this._values.input={})).audio=t.map((e=>{const{userId:t,tag:r}=We(e);return{stream_id:ze(t,r),user_id:t}})),this._values.inputFilterMode=Cr.AUDIO_INPUT_VIDEO_ALL,e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:s.SUCCESSED,trackIds:t},{logSource:e.LogSource.RTC}),this}addCustomizeInputAudio(t){if(r.info(`addCustomizeInputAudio -> trackId: ${t}`),!this._isValidTrackId(t))return r.warn(`addCustomizeInputAudio failed -> trackId is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:s.FAILED,code:"",msg:`params error -> trackId: ${t}`},{logSource:e.LogSource.RTC}),this;const o=this._values.input||(this._values.input={}),n=o.audio||(o.audio=[]),{userId:a,tag:c}=We(t),d=ze(a,c);return n.some((e=>e.stream_id===d&&e.user_id===a))?(e.logger.warn(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:s.FAILED,code:"",msg:`trackId:${t} is exist`},{logSource:e.LogSource.RTC}),this):(n.push({user_id:a,stream_id:d}),this._values.inputFilterMode=Cr.AUDIO_INPUT_VIDEO_ALL,e.logger.info(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:s.SUCCESSED,trackId:t},{logSource:e.LogSource.RTC}),this)}removeCustomizeInputAudio(t){if(r.info(`removeCustomizeInputAudio -> trackId: ${t}`),!this._isValidTrackId(t))return r.error(`removeCustomizeInputAudio failed -> trackId is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:s.FAILED,code:"",msg:`params error -> trackId: ${t}`},{logSource:e.LogSource.RTC}),this;const o=this._values.input;if(!(null==o?void 0:o.audio)||0===o.audio.length)return e.logger.error(i.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:s.FAILED,code:"",msg:"not audio"},{logSource:e.LogSource.RTC}),this;const{userId:n,tag:a}=We(t),c=ze(n,a);return o.audio=o.audio.filter((e=>n!==e.user_id||c!==e.stream_id)),e.logger.info(i.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:s.SUCCESSED,trackId:t},{logSource:e.LogSource.RTC}),this}clearCustomizeInputAudio(){r.info("clearCustomizeInputAudio ->");const t=this._values.input;return(null==t?void 0:t.audio)&&delete t.audio,this._values.inputFilterMode=Cr.AUDIO_VIDEO_ALL,e.logger.info(i.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_INPUT_AUDIO_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this}reset(){return r.info("MCUConfigBuilder.reset ->"),this._values=pr(),e.logger.info(i.L_MCU_CONFIG_BUILDER_RESET_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this}flush(r=!0){return t(this,void 0,void 0,(function*(){const t=JSON.parse(JSON.stringify(this._values)),{code:o}=yield this._invoker.push(new _r(t,this._values));return r&&(this._values=pr()),e.logger.info(i.L_MCU_CONFIG_BUILDER_FLUSH_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),{code:o}}))}__innerGetValues(){return JSON.parse(JSON.stringify(this._values))}}var Tr,gr,mr;exports.RCLivingType=void 0,(Tr=exports.RCLivingType||(exports.RCLivingType={}))[Tr.VIDEO=0]="VIDEO",Tr[Tr.AUDIO=1]="AUDIO",function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(gr||(gr={}));class Er extends $t{constructor(e,t,r){super(),this.roomId=e,this.hooks=t,this.roomPKHandler=r}_exchangeWithPushOtherRoom(e,o){return t(this,void 0,void 0,(function*(){if(!e.getLocalTracks().length)return;const t=Object.values(e.peerMgr.getMutilPeerCData()),i=Object.keys(e.peerMgr.getMutilPeerCData());for(let s=0;s<t.length;s++){const{pc:n,isPub:a}=t[s],c=a&&e.useMutilPeerC?[]:e.getSubscribedList(),d=yield Jt(c,!1,n,e),{pushOtherRooms:_,headers:u}=this.hooks(i[s]);d.pushOtherRooms=_;const l=yield new zt(u,d).execute(e,o);if(l.code!==exports.RCRTCCode.SUCCESS)return void r.error(`exchange with pushOtherRoom failed: ${l.code}`);const{sdp:R,resultCode:C}=l.data;if(C!==exports.RCRTCCode.SUCCESS)return void r.error(`exchange with pushOtherRoom failed: ${C}`);n.setRemoteAnswer(R.sdp)}}))}execute(o,n){return t(this,void 0,void 0,(function*(){const{roomId:t}=this;if(e.logger.info(i.L_LIVING_ROOM_JOINED_PK_ROOM_T,{roomId:t,userId:o.crtUserId},{logSource:e.LogSource.RTC}),!this.roomPKHandler)return void e.logger.error(i.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:s.FAILED,code:"",msg:"_roomPKHandler not exist"},{logSource:e.LogSource.RTC});const a=this.roomPKHandler.getPKInfo(t);if(!a)return r.warn(`exchange to update pushOtherRoom cancel, pkInfo lost -> roomId: ${t}`),void e.logger.error(i.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:s.FAILED,code:"",msg:"PKInfo not exist"},{logSource:e.LogSource.RTC});yield this._exchangeWithPushOtherRoom(o,n),e.logger.info(i.L_LIVING_ROOM_JOINED_PK_ROOM_T,{status:s.SUCCESSED,roomId:t,userId:o.crtUserId,PKInfo:a},{logSource:e.LogSource.RTC})}))}}class Sr extends $t{constructor(e,t,r,o,i,s){super(),this.pkHandler=e,this.room=t,this._PKInfo=r,this.hooks=o,this._joinedPKRooms=i,this.isQuitPK=s}quitRoomPK(o,i){return t(this,void 0,void 0,(function*(){if(!this._PKInfo[o])return;const{inviterRoomId:t,inviteeRoomId:s,inviterUserId:n,inviteSessionId:a}=this._PKInfo[o],c={inviteeRoomId:s,inviterRoomId:t,userId:i.crtUserId},d={roomId:i.roomId,endRoomId:o,sessionId:a,content:JSON.stringify(c),keys:[`${t}|${n}`]};r.info(`quitRoomPK -> params: ${JSON.stringify(d)}`);const _=yield i.context.endRoomPK(d);return _!==e.ErrorCode.SUCCESS?(r.error(`quitRoomPK failed: ${_}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):(r.info("quitRoomPK success"),delete this._PKInfo[o],{code:exports.RCRTCCode.SUCCESS})}))}execute(o,n){return t(this,void 0,void 0,(function*(){const{room:t,isQuitPK:a}=this,c=t.getRoomId();return r.info(`leavePKRoom -> userId: ${o.crtUserId} , roomId: ${c}`),e.logger.info(i.L_LIVING_ROOM_LEAVE_PK_ROOM_T,{roomId:c,userId:o.crtUserId,isQuitPK:a},{logSource:e.LogSource.RTC}),yield t.__destroy(!0),delete this._joinedPKRooms[c],yield new Er(c,this.hooks,this.pkHandler).execute(o,n),a&&this.quitRoomPK(c,o),e.logger.info(i.L_LIVING_ROOM_LEAVE_PK_ROOM_R,{status:s.SUCCESSED,roomId:c,userId:o.crtUserId,isQuitPK:a},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS}}))}}class Ir{constructor(e,t,r,o,i,s,n,a,c,d,_){this._invoker=e,this._PKInfo=t,this._hooks=r,this._context=o,this._runtime=i,this._service=s,this._initOptions=n,this._mainLivingRoom=a,this._registerPKMsgListener=c,this._onJoinedPKRoom=d,this._clientSessionId=_,this._inviteTimeout=30,this._appListener=null,this._joinedPKRooms={},this._registerPKMsgListener(this._onRecvPKMsg.bind(this)),this._mainRoomId=this._mainLivingRoom.getRoomId()}_callAppListener(e,...t){var o;r.info(`${e} callback ->`,...t);const i=null===(o=this._appListener)||void 0===o?void 0:o[e];if(i)try{i(...t)}catch(e){r.error(e)}}_onInvite(e){const t=e.inviteInfo||{},{inviterRoomId:r,inviterUserId:o,extra:i}=t,s={inviterRoomId:r,inviterUserId:o,extra:i};this._PKInfo[r]=t,this._callAppListener("onRequestJoinOtherRoom",s)}_onCancelInvite(e){const{inviterRoomId:t,inviterUserId:r,extra:o}=e.inviteInfo||{},i={inviterRoomId:t,inviterUserId:r,extra:o};delete this._PKInfo[t],this._callAppListener("onCancelRequestOtherRoom",i)}_onInviteTimeout(e){}_onInviteAnswer(e){const{answerCode:t,inviteContent:r}=e,{inviteSessionId:o,inviterUserId:i,inviterRoomId:s,inviteeUserId:n,inviterUserAutoMix:a,inviteeUserAutoMix:c,inviteeRoomId:d,extra:_}=r,u={agree:1===t,inviterRoomId:s,inviterUserId:i,inviteeRoomId:d,inviteeUserId:n,extra:_};this._PKInfo[d]=this._PKInfo[d]||{inviteSessionId:o,inviterRoomId:s,inviterUserId:i,inviterUserAutoMix:a,inviteeRoomId:d},this._PKInfo[d].inviteeUserAutoMix=c,this._callAppListener("onResponseJoinOtherRoom",u)}createLeaveOtherRoomCommand(e,t){return new Sr(this,e,this._PKInfo,this._hooks,this._joinedPKRooms,t)}_onPKEnd(e){return t(this,void 0,void 0,(function*(){const{inviteeRoomId:t,inviterRoomId:r,userId:o}=e.inviteInfo,i=r===this._mainRoomId?t:r,s={endRoomId:i,endUserId:o},n=this._joinedPKRooms[i];n&&(yield this._invoker.push(this.createLeaveOtherRoomCommand(n))),delete this._PKInfo[i],this._callAppListener("onFinishOtherRoom",s)}))}_onRecvPKMsg(e){const{targetId:t,content:r,messageType:o}=e;switch(o){case ut.PK_INVITE:this._onInvite(r);break;case ut.PK_CANCEL_INVITE:this._onCancelInvite(r);break;case ut.PK_INVITE_TIMEOUT:this._onInviteTimeout(r);break;case ut.PK_INVITE_ANSWER:this._onInviteAnswer(r);break;case ut.PK_END:this._onPKEnd(r)}}registerRoomPKEventListener(t){e.logger.info(i.L_LIVING_PK_HANDLER_REGISTER_ROOM_PK_EVENT_LISTENER_O,{status:s.SUCCESSED,listener:t&&Object.keys(t)},{logSource:e.LogSource.RTC}),this._appListener=t}requestJoinOtherRoom(o,n,a){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:o,inviteeUserId:n,options:a},{logSource:e.LogSource.RTC}),!e.validate("inviteeRoomId",o,e.notEmptyString,!0)||!e.validate("inviteeUserId",n,e.notEmptyString,!0))return e.logger.error(i.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> inviteeRoomId 或 inviteeUserId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`requestRoomPK -> inviteeRoomId: ${o}; inviteeUserId: ${n}; options: ${JSON.stringify(a||{})}`);const t=Ct(),c=!e.isBoolean(null==a?void 0:a.autoMix)||(null==a?void 0:a.autoMix),d={inviteSessionId:t,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:c,inviteeRoomId:o,inviteeUserId:n,inviteeTimeoutTime:this._inviteTimeout,extra:(null==a?void 0:a.extra)||""},_={roomId:this._mainRoomId,invitedRoomId:o,invitedUserId:n,inviteTimeout:this._inviteTimeout,inviteInfo:JSON.stringify(d),inviteSessionId:t};r.info(`requestRoomPK -> params: ${JSON.stringify(_)}`);const u=yield this._context.requestRoomPK(_);return u!==e.ErrorCode.SUCCESS?(r.error(`requestRoomPK failed: ${u}`),e.logger.error(i.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:u,msg:""},{logSource:e.LogSource.RTC}),{code:u}):(r.info("requestRoomPK success"),this._PKInfo[o]={inviteSessionId:t,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:c,inviteeRoomId:o},e.logger.info(i.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{inviteeRoomId:o,inviteeUserId:n,options:a},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}cancelRequestJoinOtherRoom(o,n,a){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:o,inviteeUserId:n,extra:a,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:e.LogSource.RTC}),!e.validate("inviteeRoomId",o,e.notEmptyString,!0)||!e.validate("inviteeUserId",n,e.notEmptyString,!0))return e.logger.error(i.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> inviteeRoomId or inviteeUserId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(!this._PKInfo[o])return r.error(`The request to connect with ${n} user in room ${o} is not initiated`),e.logger.error(i.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:`The request to connect with ${n} user in room ${o} is not initiated`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`canceRequestJoinPK -> inviteeRoomId: ${o}; inviteeUserId: ${n}; extra: ${a}`);const t={inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviteeRoomId:o,inviteeUserId:n,extra:a||""},c={roomId:this._mainRoomId,invitedRoomId:o,invitedUserId:n,inviteSessionId:this._PKInfo[o].inviteSessionId,inviteInfo:JSON.stringify(t)};r.info(`canceRequestJoinPK -> params: ${JSON.stringify(c)}`);const d=yield this._context.cancelRoomPK(c);return d!==e.ErrorCode.SUCCESS?(r.error(`canceRequestJoinPK failed: ${d}`),e.logger.error(i.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:d,msg:`The request to connect with ${n} user in room ${o} is not initiated`},{logSource:e.LogSource.RTC}),{code:d}):(r.info("canceRequestJoinPK success"),e.logger.info(i.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:s.SUCCESSED,inviteeRoomId:o,inviteeUserId:n,extra:a},{logSource:e.LogSource.RTC}),delete this._PKInfo[o],{code:exports.RCRTCCode.SUCCESS})}))}responseJoinOtherRoom(o,n,a,c){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_T,{inviterRoomId:o,inviterUserId:n,agree:a,options:c,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:e.LogSource.RTC}),!e.validate("inviterRoomId",o,e.notEmptyString,!0)||!e.validate("inviterUserId",n,e.notEmptyString,!0))return e.logger.error(i.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> inviterRoomId or inviterUserId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(!this._PKInfo[o])return r.error(`User ${n} in room ${o} did not send a request for connection`),e.logger.error(i.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:`User ${n} in room ${o} did not send a request for connection`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`responseRoomPK -> inviterRoomId: ${o}; inviterUserId: ${n}; agree: ${a}; options: ${JSON.stringify(c||{})}`);const{inviteSessionId:t,inviterUserAutoMix:d}=this._PKInfo[o],_=!e.isBoolean(null==c?void 0:c.autoMix)||(null==c?void 0:c.autoMix),u={inviteSessionId:t,inviterRoomId:o,inviterUserId:n,inviterUserAutoMix:d,inviteeRoomId:this._mainRoomId,inviteeUserId:this._context.getCurrentId(),inviteeUserAutoMix:_},l=Object.assign(u,{inviterUserAutoMix:d}),R=a?Object.assign(u,{MultiRoomKey:`${o}|${this._mainRoomId}`,MultiRoomValue:JSON.stringify(l)}):u;!e.isUndefined(null==c?void 0:c.extra)&&Object.assign(R,{extra:c.extra});const C={agree:a,roomId:this._mainRoomId,inviteSessionId:t,inviteRoomId:o,inviteUserId:n,content:JSON.stringify(R),key:`${o}|${this._mainRoomId}`,value:JSON.stringify(u)};r.info(`responseRoomPK -> params: ${JSON.stringify(C)}`);const p=yield this._context.responseRoomPK(C);return p!==e.ErrorCode.SUCCESS?(r.error(`responseRoomPK failed: ${p}`),e.logger.error(i.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:p,msg:""},{logSource:e.LogSource.RTC}),{code:p}):(r.info("responseRoomPK success"),e.logger.info(i.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:s.SUCCESSED,inviterRoomId:o,inviterUserId:n,agree:a,options:c,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:e.LogSource.RTC}),this._PKInfo[o].inviteeUserAutoMix=_,{code:exports.RCRTCCode.SUCCESS})}))}joinOtherRoom(o){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_T,{roomId:o,userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),!e.validate("roomId",o,e.notEmptyString,!0))return e.logger.error(i.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(this._context.getConnectionStatus()!==e.ConnectionStatus.CONNECTED)return e.logger.error(i.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.SIGNAL_DISCONNECTED,msg:"IM disconnected"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_DISCONNECTED};if(r.info(`JoinPKRoom, roomId: ${o}`),this._joinedPKRooms[o])return e.logger.warn(i.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const t=exports.RCLivingType.VIDEO,n={extra:`{"roomId": "${this._mainRoomId}"}`},a=new Or(this._context,this._runtime,o,this._service,this._initOptions,t,!1,!1,!1,this._clientSessionId),{code:c,data:d}=yield a.__innerInit(e.RTCMode.LIVE,void 0,t,n);return c!==exports.RCRTCCode.SUCCESS?(r.error(`JoinPKRoom failed -> code: ${c}`),e.logger.error(i.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:c,msg:""},{logSource:e.LogSource.RTC}),{code:c}):(r.info(`JoinPKRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${o}, data: ${JSON.stringify(d)}`),this._joinedPKRooms[o]=a,yield this._onJoinedPKRoom(o,a),e.logger.info(i.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:s.SUCCESSED,roomId:o,userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),{room:a,code:exports.RCRTCCode.SUCCESS,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()})}))}leaveOtherRoom(e,r){return t(this,void 0,void 0,(function*(){return this._invoker.push(this.createLeaveOtherRoomCommand(e,r))}))}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"}(mr||(mr={}));class fr extends $t{constructor(e,t){super(),this.cdnValues=e,this.enable=t}execute(o,n){return t(this,void 0,void 0,(function*(){const{enable:t}=this;if(e.logger.info(i.L_LIVING_ROOM_ENABLE_INNER_CDN_T,{roomId:o.roomId,enable:t},{logSource:e.LogSource.RTC}),!o.isMainRoom)return r.error("the `enableInnerCDN` is disabled in PK room"),e.logger.error(i.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:s.FAILED,code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!e.isBoolean(t))return r.error("`enable` is invalid"),e.logger.error(i.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> enable"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};o.setCDNEnabel(t);const a={version:2,output:{inCDNModel:t?mr.OPEN:mr.STOP}},{code:c}=yield new _r(a,this.cdnValues).execute(o,n);if(c!==exports.RCRTCCode.SUCCESS)return r.error(`enableInnerCDN failed -> code: ${c}`),e.logger.error(i.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:s.FAILED,code:c,msg:"signal error"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_ERROR};const d=o.getCDNUris();if(d&&d.broadcast!==Bt.SPREAD)return r.info("enableInnerCDN succeed"),e.logger.info(i.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:s.SUCCESSED,enable:t},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS};const{code:_}=yield Wt(o);return _===exports.RCRTCCode.SUCCESS?(r.info("enableInnerCDN succeed"),e.logger.info(i.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:s.SUCCESSED,enable:t},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS}):(r.error(`enableInnerCDN failed -> code: ${_}`),e.logger.error(i.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:s.FAILED,code:_,msg:""},{logSource:e.LogSource.RTC}),{code:_})}))}}class Lr extends $t{constructor(e){super(),this.livingType=e}execute(r,o){var i;return t(this,void 0,void 0,(function*(){const{code:t,data:s}=yield r.context.rtcIdentityChange(r.roomId,e.RTCIdentityChangeType.ViewerToAnchor,this.livingType);if(t!==e.ErrorCode.SUCCESS||!s)return{code:t};r.initWithRoomData(s);r.getResourcesByUserId(r.crtUserId).length>0&&o.push(new Ht);const n=null===(i=s.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===i?void 0:i.value;return n&&r.setCDNUris(JSON.parse(n)[0]),{code:t,data:s}}))}}class Or extends dr{constructor(t,r,o,i,s,n,a,c,d,_){super(t,r,o,e.RTCMode.LIVE,i,s,a,c,d,_),this._livingType=n,this._mcuConfigBuilder=new hr(this._invoker,this._isValidResourceId.bind(this))}_initAfterCatchRoomData(e){if(this._store.isUpgrade&&this._afterChangedRole(e),this._store.isMainRoom){const t=((e,t)=>{const r={};return t.forEach((t=>{const o=JSON.parse(t.value),{inviterRoomId:i,inviteeRoomId:s}=o;r[e===i?s:i]=JSON.parse(t.value)})),r})(this._roomId,e.roomInfo);this._roomPKHandler=new Ir(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(r,o,n,a,c){const d=Object.create(null,{__innerInit:{get:()=>super.__innerInit}});return t(this,void 0,void 0,(function*(){if(!e.validate("livingType",n,(e=>e===exports.RCLivingType.AUDIO||e===exports.RCLivingType.VIDEO)))return e.logger.error(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> livingType"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};const{code:t,data:_}=yield d.__innerInit.call(this,r,o,n,a,c);return t===exports.RCRTCCode.SUCCESS&&_&&this._initAfterCatchRoomData(_),{code:t,data:_}}))}__innerInitByIdentityChange(){return t(this,void 0,void 0,(function*(){const{code:t,data:r}=yield this._invoker.push(new Lr(this._livingType));return t===e.ErrorCode.SUCCESS&&r&&(this._initAfterCatchRoomData(r),this._initWithRoomData(r.offlineKickTime),e.logger.info(i.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:s.SUCCESSED,roomData:r},{logSource:e.LogSource.RTC})),t}))}publish(o){const n=Object.create(null,{publish:{get:()=>super.publish}});return t(this,void 0,void 0,(function*(){return this._store.isMainRoom?n.publish.call(this,o):(r.warn("the `publish` is disabled in PK room "),e.logger.error(i.L_ABSTRACT_ROOM_PUBLISH_R,{status:s.FAILED,code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}unpublish(o){const n=Object.create(null,{unpublish:{get:()=>super.unpublish}});return t(this,void 0,void 0,(function*(){return this._store.isMainRoom?n.unpublish.call(this,o):(r.warn("the `unpublish` is disabled in PK room "),e.logger.error(i.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:s.FAILED,code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}_isValidResourceId(e){var t;const{userId:r}=We(e),o=!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>qe(t)===e)));let i=!1;const{code:s,roomPKHandler:n}=this.getRoomPKHandler();if(s!==exports.RCRTCCode.SUCCESS||!n)return o;const a=n.getJoinedPKRooms(),c=[];return Object.values(a).map((e=>{c.push(...e.getRemoteTracks())})),i=c.some((t=>e===t.getTrackId())),o||i}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._store.isMainRoom?this._mcuConfigBuilder:(r.error("the `getMCUConfigBuilder` is disabled in PK room"),{code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}enableInnerCDN(e){return t(this,void 0,void 0,(function*(){return this._invoker.push(new fr(this._mcuConfigBuilder.__innerGetValues(),e))}))}_resourceHandle(e,r,o){const i=Object.create(null,{_resourceHandle:{get:()=>super._resourceHandle}});return t(this,void 0,void 0,(function*(){i._resourceHandle.call(this,e,r,o)}))}_afterChangedRole(e){const t=dt(e,this._roomId),r=this._context.getCurrentId(),o=Object.keys(t);setTimeout((()=>{var i;const s=o.filter((e=>e!==r));s.length>0&&this._callAppListener("onUserJoin",s);for(const e in t)e!==r&&this._resourceHandle({uris:t[e]},ut.TOTAL_CONTENT_RESOURCE,e);if(!(null===(i=e.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===i?void 0:i.value))return;const n=this._store.getCDNUris();(null==n?void 0:n.push_mode)===gr.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,r){return t(this,void 0,void 0,(function*(){this._invoker.push(new Er(e,(e=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(e)})),this._roomPKHandler))}))}_getPushOtherRoomsParams(){const e=[];if(!this.isMainRoom()||!this._roomPKHandler)return e;const t=this._roomPKHandler.getJoinedPKRooms();for(const r in t){const o=t[r].getSessionId(),i=this._roomPKHandler.getPKInfo(r);if(!i)continue;const{inviterUserAutoMix:s,inviteeUserAutoMix:n,inviterUserId:a}=i,c=this._context.getCurrentId()===a;e.push({roomId:r,sessionId:o,autoMix:c?!!s:!!n})}return e}getRoomPKHandler(){return this._store.isMainRoom?(e.logger.info(i.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:s.SUCCESSED,handler:this._roomPKHandler},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,roomPKHandler:this._roomPKHandler}):(r.error("the `getRoomPKHandler` is disabled in PK room"),e.logger.error(i.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:s.SUCCESSED,code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}_quitAllPKRoom(){return t(this,void 0,void 0,(function*(){const t=this._roomPKHandler.getJoinedPKRooms();for(const e in t)this._roomPKHandler.leaveOtherRoom(t[e]);e.logger.info(i.L_LIVING_ROOM_QUIT_ALL_PK_ROOM_O,{status:s.SUCCESSED,roomIds:Object.keys(t)},{logSource:e.LogSource.RTC})}))}isMainRoom(){return this._store.isMainRoom}}class vr extends dr{constructor(t,r,o,i,s,n,a,c,d){super(t,r,o,e.RTCMode.RTC,i,s,n,a,c,d)}}const Ar=new class{constructor(){this.queue=[],this.locked=!1}checkToStart(){return t(this,void 0,void 0,(function*(){if(0===this.queue.length||this.locked)return;this.locked=!0;const{resolve:e,task:t,reject:r}=this.queue.shift();let o;try{o=yield t(),e(o)}catch(e){r(e)}this.locked=!1,this.checkToStart()}))}push(e){const t=new Promise(((t,r)=>{this.queue.push({resolve:t,task:e,reject:r})}));return this.checkToStart(),t}},Nr=e=>Ar.push(e);class Dr{constructor(e,t,r,o){this._context=e,this._useMutilPeerC=o,this._rtcToken="",this._liveUrl="",this._subTracks=[],this._clientSessionId=Ct(),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 Ft(this._useMutilPeerC,this._context.getCurrentId(),this._reTryExchange.bind(this),this._context.getCurrentId())}_getReqHeaders(o){return t(this,void 0,void 0,(function*(){const t=this._context.getCurrentId(),i=t;if(!this._rtcToken){const{code:t,data:s}=yield this._context.getRTCToken(i,e.RTCMode.LIVE,o);if(t!==e.ErrorCode.SUCCESS)return r.error(`getRTCToken failed: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR};this._rtcToken=s.rtcToken}return{code:exports.RCRTCCode.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:t,RoomId:i,RoomType:e.RTCMode.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 t(this,void 0,void 0,(function*(){this._fromRetry=!0;const{code:t}=yield this.subscribe(this._liveUrl,this._livingType,this._mediaType,this._subTiny);t===exports.RCRTCCode.SUCCESS&&(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer())}))}subscribe(e,r,o,i=!1){return t(this,void 0,void 0,(function*(){return Nr((()=>this.__subscribe(e,r,o,i)))}))}__subscribe(o,n,a,c=!1){var d;return t(this,void 0,void 0,(function*(){e.logger.info(i.L_AUDIENCE_CLIENT_SUBSCRIBE_T,{liveUrl:o,livingType:n,mediaType:a,subTiny:c},{logSource:e.LogSource.RTC});const t=[];if(ct(this._context.getNaviInfo()))return e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,tracks:t};if(!this._fromRetry&&(null===(d=this._pc)||void 0===d||d.clearReTryExchangeTimer()),this._fromRetry=!1,!e.isString(o))return r.error(`liveUrl is invalid: ${o}`),e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:`params error -> liveUrl: ${o}`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};if(![exports.RCLivingType.AUDIO,exports.RCLivingType.VIDEO].includes(n))return r.error(`livingType is invalid: ${n}`),e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:`params error -> livingType: ${n}`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};if(![exports.RCMediaType.AUDIO_ONLY,exports.RCMediaType.VIDEO_ONLY,exports.RCMediaType.AUDIO_VIDEO].includes(a))return r.error(`mediaType is invalid: ${a}`),e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:`params error -> -> mediaType: ${a}`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};if(this._liveUrl&&this._liveUrl!==o)return e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.BROADCAST_SUB_LIST_NOT_EMPTY,msg:"repeat subscribe"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.BROADCAST_SUB_LIST_NOT_EMPTY,tracks:t};if(!this._pc){const{pcName:e,pc:r}=this._peerCManager.createPeerCList(t)[0];this._pc=r,this._pcName=e,this._pc.on(yt.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this._pc.registerReportListener(this._reportListener),this._pc.__reportR3R4ToPolaris()}this._liveUrl=o;const{code:_,headers:u}=yield this._getReqHeaders(n);if(_!==exports.RCRTCCode.SUCCESS)return e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:_,msg:""},{logSource:e.LogSource.RTC}),{code:_,tracks:t};const l=`rc_mcu_${Date.now()}`,R="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new Ve(R,l),new Fe(R,l)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const C={sdp:yield this._pc.createOffer(!0),liveUrl:o,mediaType:a,simulcast:c?Tt.TINY:Tt.NORMAL,switchstream:!1},p=yield this._service.broadcastSubscribe(u,C);if(p.code!==exports.RCRTCCode.SUCCESS)return r.error(`andience subscribe failed: ${p.code}`),e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:p.code,msg:""},{logSource:e.LogSource.RTC}),{code:p.code,tracks:t};const h=p.data;if(h.resultCode!==exports.RCRTCCode.SUCCESS)return r.error(`andience subscribe failed! code: ${h.resultCode}; message: ${h.message}`),e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:h.resultCode,msg:""},{logSource:e.LogSource.RTC}),{code:h.resultCode,tracks:t};r.debug(`andience subscribe success: ${o}`),this._livingType=n,this._mediaType=a,this._subTiny=c;const{sdp:T,subscribedList:g}=h,m=[];return g.forEach((e=>{const{mediaType:t}=e,r=this._subTracks[t];m.push(r),r.__innerSetRemoteMuted(!0)})),this._pc.setRemoteAnswer(T.sdp),e.logger.info(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.SUCCESSED,liveUrl:o},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,tracks:m}}))}unsubscribe(){return t(this,void 0,void 0,(function*(){return Nr((()=>this.__unsubscribe()))}))}__unsubscribe(){var o;return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_AUDIENCE_CLIENT_UNSUBSCRIBE_T,{liveUrl:this._liveUrl},{logSource:e.LogSource.RTC}),null===(o=this._pc)||void 0===o||o.clearReTryExchangeTimer(),!this._rtcToken||!this._liveUrl)return e.logger.warn(i.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:s.FAILED,code:"",msg:"Address does not exist, without unsubscribe"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS};const{headers:t}=yield this._getReqHeaders(),{code:n}=yield this._service.broadcastExit(t);return n!==exports.RCRTCCode.SUCCESS?(r.error(`broadcast unsubscribe failed: ${n}`),e.logger.error(i.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:s.FAILED,code:n,msg:""},{logSource:e.LogSource.RTC})):(r.debug("broadcast unsubscribe success"),e.logger.info(i.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:s.SUCCESSED,liveUrl:this._liveUrl},{logSource:e.LogSource.RTC})),this._clearSubscribeInfo(),{code:n}}))}registerReportListener(e){this._reportListener=e}registerTrackEventListener(e){this._appListener=e}_onTrackReady(e){var t,o;const i=e.receiver.track,s="audio"===i.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY,n=this._subTracks[s];n.__innerSetMediaStreamTrack(i);try{null===(o=null===(t=this._appListener)||void 0===t?void 0:t.onTrackReady)||void 0===o||o.call(t,n)}catch(e){r.error(e)}}}var yr,Pr;exports.RCInnerCDNPullKind=void 0,(yr=exports.RCInnerCDNPullKind||(exports.RCInnerCDNPullKind={})).RTMP="rtmp",yr.FLV="flv",yr.HLS="hls",exports.RCInnerCDNPullIsHttps=void 0,(Pr=exports.RCInnerCDNPullIsHttps||(exports.RCInnerCDNPullIsHttps={}))[Pr.NOT_HTTPS=0]="NOT_HTTPS",Pr[Pr.HTTPS=1]="HTTPS";const kr=Object.assign(Object.assign({},et(exports.RCResolution.W176_H144)),{frameRate:ot(exports.RCFrameRate.FPS_15)});class Ur{constructor(e,t,r,o,i,s,n,a=Ct()){this._context=e,this._runtime=t,this._initOptions=r,this._roomId=o,this._joinResData=i,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 wt(this._context,this._runtime,this._roomId,this,kt.Audience),this._polarisReport.sendR1(),this._peerCManager=new Ft(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:o,remoteTracks:i,CDNUris:s}=((e,t)=>{const r=t.filter((e=>"RC_RTC_SESSIONID"===e.key))[0],o=r?r.value:"",i=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:o}=t,i=r===exports.RCMediaType.AUDIO_ONLY?new Ve(o,"",e):new Fe(o,"",e);a.push(i)}));const c=[],d=[];s.forEach((e=>{const t=JSON.parse(e.uris||"[]");c.push(...t),t.forEach((e=>{const{mediaType:t,tag:r,msid:o}=e,i=o.split("_")[0],s=t===exports.RCMediaType.AUDIO_ONLY?new Ve(r,i):new Fe(r,i);d.push(s)}))}));const _=t.filter((e=>"RC_CDN"===e.key)).map((e=>{const t=JSON.parse(e.value||"[]");return JSON.parse(t.cdn_uris)[0]}))[0];return{sessionId:o,remoteUserIds:i||[],remoteRTCUris:c,remoteMUCUris:n,remoteRTCTracks:d,remoteMCUTracks:a,remoteTracks:[...d,...a],CDNUris:_||{}}})(this._roomId,this._joinResData.kvEntries);this._sessionId=e,this._roomAnchorList=t,i.forEach((e=>{this._remoteTracks[e.getTrackId()]=e})),this._CDNUris=s,r.forEach((e=>{const t=e.msid.split("_")[0];this._roomAnchorRes[t]?this._roomAnchorRes[t].push(e):this._roomAnchorRes[t]=[e]})),o.forEach((e=>{const{mediaType:t,tag:r}=e,o=[this._roomId,r,t].join("_");this._roomRes[o]=e})),r.forEach((e=>{const t=qe(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 r.warn(e),exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(t,o){var n;if(e.logger.info(i.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_T,{singalData:t,roomId:o,userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),o!==this._roomId)return r.warn(`singalDataChange -> not the current room data: data roomId: ${o}, current roomId: ${this._roomId}`),void e.logger.error(i.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:s.FAILED,code:"",msg:`id inconsistency -> params id:${o},current id:${this._roomId}`},{logSource:e.LogSource.RTC});r.debug("singalDataChange -> singalData:",JSON.stringify(t||{}));const a=[],c=null===(n=t.filter((e=>"RC_CDN"===e.key))[0])||void 0===n?void 0:n.value;c&&this._diffCDNUris(JSON.parse(JSON.parse(c).cdn_uris)[0]),t.forEach((e=>{const{key:t,value:r,timestamp:o,uid:i}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),o=JSON.parse(e.uris||"[]");return a.push(...t),void this._diffAnchorResource(o,i)}if("RC_ANCHOR_LIST"===t){const e=JSON.parse(r||"[]"),{joinUserIds:t,leftUserIds:o}=this._diffAnchorList(e);t.length>0&&this._handleNewJoinedAnchor(t),o.length>0&&this._handleLeftedAnchor(o)}})),this._diffRoomResource(a),e.logger.info(i.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:s.SUCCESSED,singalData:t,roomId:o,userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC})}_diffAnchorList(e){const t=e.filter((e=>this._roomAnchorList.indexOf(e)<0));return{leftUserIds:this._roomAnchorList.filter((t=>e.indexOf(t)<0)),joinUserIds:t}}_handleNewJoinedAnchor(e){this._roomAnchorList.push(...e),this._callAppListener("onAnchorJoin",e)}_handleLeftedAnchor(e){return t(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 t(this,void 0,void 0,(function*(){const t=[],r=[],o=[];e.forEach((e=>{const r=qe(e),{userId:i,tag:s,mediaType:n}=We(r),a=[this._roomId,s,n].join("_");if(!this._remoteTracks[a]){const r=n===exports.RCMediaType.AUDIO_ONLY?new Ve(s,"",this._roomId):new Fe(s,"",this._roomId);t.push(r),this._remoteTracks[a]=r,this._roomRes[r.getTrackId()]=e}o.push(a)})),Object.keys(this._remoteTracks).forEach((e=>{o.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,o){return t(this,void 0,void 0,(function*(){const t=this._roomAnchorRes[o]||(this._roomAnchorRes[o]=[]),{publishedList:i,unpublishedList:s,modifiedList:n}=Ze(t,e);if(i.length){const e=t.map(qe),o=[],s=[];if(i.forEach((r=>{const i=qe(r),n=e.indexOf(i),{userId:a,tag:c,mediaType:d}=We(i);n>-1?t[n]=r:t.push(r);let _=this._remoteTracks[i];this._roomRes[i]=r,_?_.isSubscribed()&&o.push(_):(_=d===exports.RCMediaType.AUDIO_ONLY?new Ve(c,a):new Fe(c,a),this._remoteTracks[i]=_,s.push(_)),_.__innerSetRemoteMuted(0===r.state)})),o.length){const e=o.map((e=>e.getTrackId()));r.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:t}=yield Nr((()=>this._subscribeHandle(o,!0)));t!==exports.RCRTCCode.SUCCESS&&r.error(`resub tracks failed -> code: ${t}, ids: ${JSON.stringify(e)}`)}this._callAppListener("onAnchorTrackPublish",s)}if(s.length){const e=s.map(qe);for(let r=t.length-1;r>=0;r-=1){const o=t[r];e.includes(qe(o))&&t.splice(r,1)}const r=s.map((e=>{const t=qe(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(r,"onAnchorTrackUnpublish")}if(n.length){const e=t.map(qe);for(let r=0;r<n.length;r++){const o=n[r],i=qe(o),s=e.indexOf(i);t[s].state=o.state;const a=this._remoteTracks[i];a.__innerSetRemoteMuted(0===o.state),a.isAudioTrack()?this._callAppListener("onAudioMuteChange",a):this._callAppListener("onVideoMuteChange",a)}}}))}_onUserUnpublish(e,r){return t(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(r,e)}))}_callAppListener(e,...t){var o;r.info(`${e} callback ->`,...t);const i=null===(o=this._appListener)||void 0===o?void 0:o[e];if(i)try{i(...t)}catch(e){r.error(e)}}_reTryExchange(){return t(this,void 0,void 0,(function*(){Nr((()=>t(this,void 0,void 0,(function*(){var e;const{reqBody:t}=yield this._createSubscribeParams(this._subscribedList,{},!0),o=yield this._exchangeHandle(t);if(o.code!==exports.RCRTCCode.SUCCESS)return r.error(`reTryExchange failed: ${o.code}`),{code:o.code};const{sdp:i,resultCode:s}=o.data;if(s!==exports.RCRTCCode.SUCCESS)return r.error(`reTryExchange failed: ${s}`),{code:s};this._pc.clearReTryExchangeTimer();const n=this._subscribedList.filter((e=>e.track.isMCUTrack()));if(n.length>0){const t=n[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 a=yield this._pc.setRemoteAnswer(i.sdp);return a!==exports.RCRTCCode.SUCCESS?{code:a}:void 0}))))}))}_createSubscribeParams(e,r,o){return t(this,void 0,void 0,(function*(){const t=yield this._pc.createOffer(o),i={resolutionInfo:[]},s={min:0,max:0};Object.keys(r).forEach((e=>{const{mediaStream:o,tinyStream:n}=r[e];[o,n].forEach(((r,o)=>{var n;const a=1===o?[e,"tiny"].join("_"):e;t.sdp=null===(n=t.sdp)||void 0===n?void 0:n.replace(new RegExp(r.id,"g"),a);const c=r.getVideoTracks()[0];if(!c)return;const d=0===o,{width:_,height:u,frameRate:l}=d?Je(c):kr;i.resolutionInfo.push({trackId:c.id,simulcast:d?Tt.NORMAL:Tt.TINY,resolution:`${_}x${u}`});const R=Le(_,u),C=ve(l);s.min+=R.minBitrate*C,s.max+=R.maxBitrate*C}))}));return{reqBody:{sdp:t,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?Tt.TINY:Tt.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:s,offer:t}}))}_subscribeHandle(r,o=!1){var n;return t(this,void 0,void 0,(function*(){e.logger.info(i.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_T,{trackIds:r.map(_t),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:o},{logSource:e.LogSource.RTC});if(this._assertRoomDestroyed())return e.logger.error(i.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED,msg:"room destroyed"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!e.validate("tracks",r,(()=>e.isArray(r)&&r.length>0&&r.every((e=>e instanceof we||e.track instanceof we))),!0))return e.logger.error(i.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};const{pc:t,pcName:a}=this._peerCManager.createPeerCList(r)[0];this._pc=t,this._pc.__reportR3R4ToPolaris(),this._pcName=a,this._pc.registerReportListener(this._reportListener),this._addPeerCEvent();const c=this._subscribedList.map((e=>Object.assign({},e))),d=r.map((e=>e instanceof we?{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)})),_||o?(null===(n=this._polarisReport)||void 0===n||n.sendR2(bt.SUBSCRIBE,xt.BEGIN,u),e.logger.info(i.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:s.SUCCESSED,trackIds:r.map(_t),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:o},{logSource:e.LogSource.RTC}),this._updateSubListHandle(c,!0)):(e.logger.warn(i.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:s.FAILED,code:"",msg:"repeat subscribe"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}_addPeerCEvent(){this._pc.on(yt.__INNER_EVENT_TRACK_READY__,(e=>{const t=e.streams[0].id,o=e.receiver.track,i=[t,"audio"===o.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY].join("_"),s=this._remoteTracks[i];s?(s.__innerSetMediaStreamTrack(o),this._callAppListener("onTrackReady",s)):r.warn("cannot found RCRemoteTrack:",o.id)}))}_getReqHeaders(){const t=this._context.getCurrentId();return{"App-Key":this._context.getAppkey(),RoomId:t,Token:this._joinResData.token,RoomType:e.RTCMode.LIVE,UserId:t,"Session-Id":this._sessionId,"Peer-Connection-Id":this._pcName,"Client-Session-Id":this._clientSessionId}}_exchangeHandle(e){return this._service.broadcastSubscribe(this._getReqHeaders(),e)}_updateSubListHandle(o,i=!1){var s;return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!e.validate("resources",o,(()=>e.isArray(o)&&o.every((e=>e instanceof we||e.track instanceof we))),!0))return{code:exports.RCRTCCode.PARAMS_ERROR};let t=o.map((e=>e instanceof we?{track:e}:Object.assign({},e)));const n={};t=t.filter((e=>{const t=e.track.getTrackId();return!n[t]&&(n[t]=!0)})).map((e=>Object.assign({},e)));const a=this._subscribedList.map((e=>Object.assign({},e)));if(!i){let e=!1;if(t.forEach((t=>{const r=a.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);a.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),a.length&&(e=!0),!e)return{code:exports.RCRTCCode.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(t.map((e=>e.track)));const{reqBody:c}=yield this._createSubscribeParams(t,{},!1),d=yield this._exchangeHandle(c);if(a.length){const e=[];a.forEach((t=>{e.push(t.track.getTrackId())})),null===(s=this._pc.reportParser)||void 0===s||s.clearLatestPacketsRecv(e)}if(d.code!==exports.RCRTCCode.SUCCESS)return{code:d.code};const{sdp:_,resultCode:u,message:l,subscribedList:R}=d.data;if(u!==exports.RCRTCCode.SUCCESS)return r.error("change subscribe list failed:",l,u),{code:u};t.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:o}=We(t.getTrackId()),i=[o,r].join("_");_.sdp=_.sdp.replace(new RegExp(e,"g"),i)}}));const C=yield this._pc.setRemoteAnswer(_.sdp);if(C!==exports.RCRTCCode.SUCCESS)return{code:C};const p=null==R?void 0:R.map((e=>`${e.msid}_${e.mediaType}`)),h=t.filter((e=>{if(e.track.isMCUTrack()){const t=this._roomRes[e.track.getTrackId()],r=`${t.msid}_${t.mediaType}`;return p.includes(r)}return null==p?void 0:p.includes(e.track.getTrackId())})),T=null==h?void 0:h.map((e=>`${e.track.getTrackId()}`)),g=t.filter((e=>!(null==T?void 0:T.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=h.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...h),g.length?{code:exports.RCRTCCode.SUCCESS,failedList:g}:{code:exports.RCRTCCode.SUCCESS}}))}_diffCDNUris(e){return t(this,void 0,void 0,(function*(){if(this._CDNUris.url&&!e.url)return this._callAppListener("onCDNInfoDisable"),void(this._CDNUris=e);(!this._CDNUris||!this._CDNUris.url&&e.url)&&this._callAppListener("onCDNInfoEnable",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`});const t=this._CDNUris.w&&e.w&&this._CDNUris.w!==e.w,r=this._CDNUris.h&&e.h&&this._CDNUris.h!==e.h,o=this._CDNUris.fps&&e.fps&&this._CDNUris.fps!==e.fps;(t||r||o)&&this._callAppListener("onCDNInfoChange",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`}),this._CDNUris=e}))}_getCDNPlayUrl(e){return t(this,void 0,void 0,(function*(){const{w:t,h:o,fps:i}=e,s=this._initOptions.pullInnerCDNProtocol||exports.RCInnerCDNPullKind.FLV,n=this._initOptions.pullInnerCDNUseHttps===exports.RCInnerCDNPullIsHttps.NOT_HTTPS?exports.RCInnerCDNPullIsHttps.NOT_HTTPS:exports.RCInnerCDNPullIsHttps.HTTPS;if(!this._CDNUris.url)return r.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${exports.RCRTCCode.CDN_RESOURCE_IS_EMPTY}`),{code:exports.RCRTCCode.CDN_RESOURCE_IS_EMPTY};const a={"App-Key":this._context.getAppkey(),Token:this._joinResData.token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},c=[];t&&c.push(`w=${t}`),o&&c.push(`h=${o}`),i&&c.push(`fps=${i}`),c.push(`kind=${s}`),c.push(`is_https=${n}`);const d=c.join("&");let _=`${this._CDNUris.url}?`;d&&(_+=d);const{code:u,res:l}=yield this._service.getCDNResourceInfo(a,_);return u!==exports.RCRTCCode.SUCCESS?(r.error(`getCDNPlayUrl failed: ${u}`),{code:u}):(r.info(`getCDNPlayUrl success: ${null==l?void 0:l.data.pull_url}`),{code:u,CDNPlayUrl:null==l?void 0:l.data.pull_url})}))}getCDNPlayUrl(o,n){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_T,{resolution:o,fps:n},{logSource:e.LogSource.RTC}),o&&!tt(o))return r.error("`resolution` is invalid"),e.logger.error(i.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> resolution"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(n&&!rt(n))return r.error("`fps` is invalid"),e.logger.error(i.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> fps"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};const{width:t,height:a}=o?et(o):{width:null,height:null},c=n?ot(n):null,d={};return t&&(d.w=t),a&&(d.h=a),c&&(d.fps=c),e.logger.info(i.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:s.SUCCESSED,resolution:o,fps:n},{logSource:e.LogSource.RTC}),this._getCDNPlayUrl(d)}))}subscribe(e){return t(this,void 0,void 0,(function*(){return Nr((()=>this._subscribeHandle(e,!1)))}))}__unsubscribe(o){var n;return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_T,{trackIds:o.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),!e.validate("tracks",o,(()=>e.isArray(o)&&o.length>0&&o.every((e=>e instanceof we))),!0))return r.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),e.logger.error(i.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};const t=this._subscribedList.map((e=>Object.assign({},e))).filter((e=>!o.includes(e.track)));return null===(n=this._polarisReport)||void 0===n||n.sendR2(bt.SUBSCRIBE,xt.END,o.map((e=>e.getTrackId()))),e.logger.info(i.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:s.SUCCESSED,trackIds:o.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),this._updateSubListHandle(t,!1)}))}unsubscribe(e){return t(this,void 0,void 0,(function*(){return Nr((()=>this.__unsubscribe(e)))}))}__destroy(e){var r,o;return t(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),e&&(yield this._context.quitLivingRoomAsAudience(this._roomId)),yield this._service.broadcastExit(this._getReqHeaders()),null===(o=this._pc)||void 0===o||o.destroy(),this._polarisReport=null,this._context.onrtcdatachange=()=>{})}))}getRemoteTrack(e){return this._remoteTracks[e]}__getPC(){return this._peerCManager.getPCList()}getLocalTrack(e){return{}}__onReconnected(){return t(this,void 0,void 0,(function*(){const{code:t}=yield this._context.joinLivingRoomAsAudience(this._roomId,e.RTCMode.LIVE);t!==e.ErrorCode.SUCCESS&&r.error("join living room error when on reconnected")}))}registerRoomEventListener(e){this._appListener=e}onAudioLevelChange(t,r){var o;null===(o=this._audioLevelReport)||void 0===o||o.clearAudioLevelReportTimer(),this._audioLevelReport=new Vt(this),this._audioLevelReport.onAudioLevelChange(t,r||1e3),e.logger.info(i.L_AUDIENCE_LIVING_ROOM_AUDIO_LEVEL_CHANGE_O,{status:s.SUCCESSED,handler:null==t?void 0:t.name,gap:r},{logSource:e.LogSource.RTC})}registerReportListener(e){this._reportListener=e}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}getSessionId(){return this._sessionId}getRemoteUserIds(){return this._roomAnchorList}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const o=this._remoteTracks[r];o.getUserId()===e&&t.push(o)}return t}getRemoteTracks(){const e=[],t=[];for(const e in this._remoteTracks){if(2===t.length)break;const r=this._remoteTracks[e];r.isMCUTrack()&&t.push(r)}return this._roomAnchorList.forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),[...t,...e]}getRemoteRTCTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()||e.push(r)}return e}getRemoteMCUTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()&&e.push(r)}return e}getCDNInfo(){return this._CDNUris.w?{resolution:`W${this._CDNUris.w}_H${this._CDNUris.h}`,fps:`FPS_${this._CDNUris.fps}`,CDNEnable:this._CDNUris.enableInnerCDN}:{CDNEnable:!1}}getClientSessionId(){return this._clientSessionId}}const Mr=(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 br{constructor(e,t,r){this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,At.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(t){var r;if(t.conversationType!==e.ConversationType.RTC_ROOM)return!1;if(this._crtRoom instanceof Or){this._getJoinedPKRoomList().forEach((e=>{e.__parseInnerMessage(t)}))}return null===(r=this._crtRoom)||void 0===r||r.__parseInnerMessage(t),e.logger.info(i.L_RTC_CLIENT_MESSAGE_O,{status:s.SUCCESSED,message:Object.assign(t,{content:"内容涉及隐私不予显示"})},{logSource:e.LogSource.RTC}),!0}_getJoinedPKRoomList(){const{code:e,roomPKHandler:t}=this._crtRoom.getRoomPKHandler();if(e===exports.RCRTCCode.SUCCESS&&t){const e=t.getJoinedPKRooms()||{};return Object.values(e)}return[]}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(r,o,n,a){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_RTC_CLIENT_JOIN_RTC_ROOM_T,{roomId:r,joinType:o,outerUserDatas:n,useMutilPeerC:a},{logSource:e.LogSource.RTC}),this._crtRoom)return e.logger.error(i.L_RTC_CLIENT_JOIN_RTC_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const t=this._crtRoom=new vr(this._context,this._runtime,r,this._service,this._options,!1,!1,a,Ct()),{code:c}=yield t.__innerInit(e.RTCMode.RTC,o,void 0,void 0,n);return c!==exports.RCRTCCode.SUCCESS?(this._crtRoom=null,{code:c}):(t.once(cr,(()=>{this._crtRoom=null})),{code:c,room:t,userIds:t.getRemoteUserIds(),tracks:t.getRemoteTracks()})}))}joinLivingRoom(r,o,n,a,c){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_T,{roomId:r,livingType:o,joinType:n,outerUserDatas:a,useMutilPeerC:c},{logSource:e.LogSource.RTC}),this._crtRoom)return e.logger.error(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.REPERT_JOIN_ROOM,msg:`Join the room repeatedly -> roomId: ${r}`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const t=this._crtRoom=new Or(this._context,this._runtime,r,this._service,this._options,o,!1,!0,c),{code:d}=yield t.__innerInit(e.RTCMode.LIVE,n,o,void 0,a);if(d!==exports.RCRTCCode.SUCCESS)return this._crtRoom=null,{code:d};t.once(cr,(()=>{this._crtRoom=null}));const _={code:d,room:t,userIds:t.getRemoteUserIds(),tracks:t.getRemoteTracks()};return t.__getCDNPushMode()===gr.MANUAL&&Object.assign(_,{CDNEnable:t.__getCDNEnable()}),_}))}getAudienceClient(t){return this._audience||(this._audience=new Dr(this._context,this._runtime,this._options,t)),e.logger.info(i.L_RTC_CLIENT_GET_AUDIENCE_CLIENT_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this._audience}_onIMStatusChange(t){if(r.debug(`signal server connection state change: ${t}`),e.logger.info(i.L_RTC_CLIENT_CONNECTION_STATE_S,{status:s.SUCCESSED,data:t},{logSource:e.LogSource.RTC}),t===e.ConnectionStatus.CONNECTED){if(this._crtRoom instanceof Or){this._getJoinedPKRoomList().forEach((e=>{e.__onReconnected()}))}this._crtRoom&&this._crtRoom.__onReconnected()}}_onIMDisconnect(){e.logger.info(i.L_RTC_CLIENT_DISCONNECT_S,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),r.debug("TODO -> on IM disconnect")}_onIMUninit(){e.logger.info(i.L_RTC_CLIENT_DESTROY_S,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),r.debug("TODO -> on IM client ondestroy")}leaveRoom(o){var n,a;return t(this,void 0,void 0,(function*(){return e.logger.info(i.L_RTC_CLIENT_LEAVE_ROOM_T,{userId:this._context.getCurrentId(),roomId:null===(n=this._crtRoom)||void 0===n?void 0:n.getRoomId()},{logSource:e.LogSource.RTC}),this._crtRoom?(yield this._crtRoom.__destroy(!0),r.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),e.logger.info(i.L_RTC_CLIENT_LEAVE_ROOM_R,{status:s.SUCCESSED,userId:this._context.getCurrentId(),roomId:null===(a=this._crtRoom)||void 0===a?void 0:a.getRoomId()},{logSource:e.LogSource.RTC}),this._crtRoom=null,{code:exports.RCRTCCode.SUCCESS}):(e.logger.warn(i.L_RTC_CLIENT_LEAVE_ROOM_R,{status:s.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}_getMediaStream(e,o="getUserMedia"){return t(this,void 0,void 0,(function*(){try{const t=yield navigator.mediaDevices[o](e);return{code:exports.RCRTCCode.SUCCESS,stream:t}}catch(e){if("Permission denied"===e.message)return{code:exports.RCRTCCode.PERMISSION_DENIED};r.error(`get user media failed -> ${e.message}`)}return{code:"getUserMedia"===o?exports.RCRTCCode.GET_USER_MEDIA_FAILED:exports.RCRTCCode.GET_DISPLAY_MEDIA_FAILED}}))}createMicrophoneAudioTrack(r="RongCloudRTC",o){return t(this,void 0,void 0,(function*(){if(!Ke(r))return e.logger.error(i.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS};const t=this._context.getCurrentId();if(!t)return e.logger.error(i.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID};const{stream:n,code:a}=yield this._getMediaStream({audio:{deviceId:null==o?void 0:o.micphoneId,sampleRate:null==o?void 0:o.sampleRate}});if(a!==exports.RCRTCCode.SUCCESS)return e.logger.error(i.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:s.FAILED,code:a,msg:"Failed to get microphone audio stream"},{logSource:e.LogSource.RTC}),{code:a};const c=n.getAudioTracks()[0],d=new be(r,t,c);return e.logger.info(i.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:s.SUCCESSED,trackId:d.getTrackId()},{logSource:e.LogSource.RTC}),{code:a,track:d}}))}createCameraVideoTrack(r="RongCloudRTC",o){return t(this,void 0,void 0,(function*(){if(!Ke(r))return e.logger.error(i.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS};const t=this._context.getCurrentId();if(!t)return e.logger.error(i.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID};const n=tt(null==o?void 0:o.resolution)?o.resolution:exports.RCResolution.W640_H480,{width:a,height:c}=et(n),{stream:d,code:_}=yield this._getMediaStream({video:{deviceId:null==o?void 0:o.cameraId,frameRate:ot((null==o?void 0:o.frameRate)||exports.RCFrameRate.FPS_15),width:a,height:c,facingMode:null==o?void 0:o.faceMode}});if(_!==exports.RCRTCCode.SUCCESS)return e.logger.error(i.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"Failed to get camera video stream"},{logSource:e.LogSource.RTC}),{code:_};const u=d.getVideoTracks()[0],l=new xe(r,t,u);return e.logger.info(i.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:s.SUCCESSED,trackId:l.getTrackId()},{logSource:e.LogSource.RTC}),{code:_,track:l}}))}createMicrophoneAndCameraTracks(r="RongCloudRTC",o){var n,a,c,d,_,u;return t(this,void 0,void 0,(function*(){const t=[];if(!Ke(r))return e.logger.error(i.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS,tracks:t};const l=this._context.getCurrentId();if(!l)return e.logger.error(i.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID,tracks:t};const R=tt(null===(n=null==o?void 0:o.video)||void 0===n?void 0:n.resolution)?o.video.resolution:exports.RCResolution.W640_H480,{width:C,height:p}=et(R),{stream:h,code:T}=yield this._getMediaStream({video:{deviceId:null===(a=null==o?void 0:o.video)||void 0===a?void 0:a.cameraId,frameRate:ot((null===(c=null==o?void 0:o.video)||void 0===c?void 0:c.frameRate)||exports.RCFrameRate.FPS_15),width:C,height:p,facingMode:null===(d=null==o?void 0:o.video)||void 0===d?void 0:d.faceMode},audio:{deviceId:null===(_=null==o?void 0:o.audio)||void 0===_?void 0:_.micphoneId,sampleRate:null===(u=null==o?void 0:o.audio)||void 0===u?void 0:u.sampleRate}});return T!==exports.RCRTCCode.SUCCESS?(e.logger.error(i.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:s.FAILED,code:T,msg:"Failed to get audio and video stream of camera and microphone"},{logSource:e.LogSource.RTC}),{code:T,tracks:t}):(h.getTracks().forEach((e=>{"video"===e.kind?t.push(new xe(r,l,e)):t.unshift(new be(r,l,e))})),e.logger.info(i.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:s.SUCCESSED,trackIds:t.map((e=>e.getTrackId()))},{logSource:e.LogSource.RTC}),{code:T,tracks:t})}))}createScreenVideoTrack(r="screenshare",o){return t(this,void 0,void 0,(function*(){if(!Ke(r))return e.logger.error(i.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS};const t=this._context.getCurrentId();if(!t)return e.logger.error(i.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID};if(!nt())return e.logger.error(i.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.BROWSER_NOT_SUPPORT};const n=/Electron/.test(navigator.userAgent);if(n&&!(null==o?void 0:o.chromeMediaSourceId))return e.logger.error(i.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> options.chromeMediaSourceId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};const a=tt(null==o?void 0:o.resolution)?o.resolution:exports.RCResolution.W1280_H720,{width:c,height:d}=et(a),_=n?{mandatory:{chromeMediaSourceId:o.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:c,maxWidth:c,minHeight:d,maxHeight:d}}:{frameRate:ot((null==o?void 0:o.frameRate)||exports.RCFrameRate.FPS_15),width:c,height:d},{stream:u,code:l}=yield this._getMediaStream({video:_,audio:!1},n?"getUserMedia":"getDisplayMedia");if(l!==exports.RCRTCCode.SUCCESS)return e.logger.error(i.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:s.FAILED,code:l,msg:"Failed to get shared screen video stream"},{logSource:e.LogSource.RTC}),{code:l};const R=u.getVideoTracks()[0],C=new Be(r,t,R);return e.logger.info(i.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:s.SUCCESSED,trackId:C.getTrackId()},{logSource:e.LogSource.RTC}),{code:l,track:C}}))}createLocalAudioTrack(r,o){return t(this,void 0,void 0,(function*(){if(!Ke(r))return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS};if(!o||"[object MediaStreamTrack]"!==o.toString()||"audio"!==o.kind)return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"Failed to create custom stream"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED};const t=this._context.getCurrentId();if(!t)return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID};const n=new ye(r,t,o);return e.logger.info(i.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:s.SUCCESSED,trackId:n.getTrackId()},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,track:n}}))}createLocalVideoTrack(r,o){return t(this,void 0,void 0,(function*(){if(!Ke(r))return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS};if(!o||"[object MediaStreamTrack]"!==o.toString()||"video"!==o.kind)return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED,msg:"Failed to create custom stream"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED};const t=this._context.getCurrentId();if(!t)return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID};const n=new Pe(r,t,o);return e.logger.info(i.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:s.SUCCESSED,trackId:n.getTrackId()},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,track:n}}))}createLocalFileTracks(o,n,a){return t(this,void 0,void 0,(function*(){if(!Ke(o))return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS,tracks:[]};if(!st())return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.BROWSER_NOT_SUPPORT,tracks:[]};const t=n instanceof File?URL.createObjectURL(n):n;if(!e.isHttpUrl(t)&&!/^blob:/.test(t))return r.warn(`createLocalFileTracks failed: params error -> url: ${t}`),e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> file"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:[]};const c=this._context.getCurrentId();return c?new Promise((n=>{const d=document.createElement("video");(null==a?void 0:a.withoutAudio)&&(d.muted=!0),d.onloadedmetadata=()=>{const _=[];let u;try{const e=d.mozCaptureStream?"mozCaptureStream":"captureStream";u=d[e]()}catch(o){r.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${t}`),r.error(o),e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:e.LogSource.RTC}),n({code:exports.RCRTCCode.CREATE_FILE_TRACK_FAILED,tracks:_})}const[l,R]=Mr(u,a);l&&_.push(new Me(o,c,l,d)),R&&_.push(new Ue(o,c,R,d)),0===_.length&&(d.pause(),d.src=""),d.onerror=null,e.logger.info(i.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:s.SUCCESSED,trackIds:_.map((e=>e.getTrackId()))},{logSource:e.LogSource.RTC}),n({code:exports.RCRTCCode.SUCCESS,tracks:_})},d.onerror=()=>{r.error(`create RCLocalFileTrack failed -> url: ${t}`),e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:e.LogSource.RTC}),n({code:exports.RCRTCCode.CREATE_FILE_TRACK_FAILED,tracks:[]})},d.src=t,d.loop=!0,d.play()})):(e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID,tracks:[]})}))}createLocalTracks(r,o,n){return t(this,void 0,void 0,(function*(){const t=[];if(!Ke(r))return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS,tracks:t};if(!(o instanceof MediaStream))return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> stream"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};const a=this._context.getCurrentId();if(!a)return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID,tracks:t};const[c,d]=Mr(o,n);return c&&t.push(new ye(r,a,c)),d&&t.push(new Pe(r,a,d)),e.logger.info(i.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:s.SUCCESSED,trackIds:t.map((e=>e.getTrackId()))},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,tracks:t}}))}joinLivingRoomAsAudience(o,n,a){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_T,{roomId:o,livingType:n,useMutilPeerC:a},{logSource:e.LogSource.RTC}),ct(this._context.getNaviInfo()))return e.logger.error(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:s.FAILED,code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR};if(!e.validate("roomId",o,e.notEmptyString,!0)||!e.validate("livingType",n,(e=>e===exports.RCLivingType.AUDIO||e===exports.RCLivingType.VIDEO)))return e.logger.error(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:s.FAILED,code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"params error -> roomId or livingType"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return e.logger.error(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:s.FAILED,code:exports.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REPERT_JOIN_ROOM};if(!this._service.getNaviMS().length)return e.logger.error(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:s.FAILED,code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:t,data:c}=yield this._context.joinLivingRoomAsAudience(o,e.RTCMode.LIVE,n);if(t!==e.ErrorCode.SUCCESS)return r.error("audienceJoinLivingRoomError:",t),e.logger.error(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:s.FAILED,code:exports.RCRTCCode.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED,msg:"signal error -> audience join room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};r.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(c)}`);const d=Ct(),_=new Ur(this._context,this._runtime,this._options,o,c,n,a,d);return this._crtAudienceLivingRoom=_,e.logger.info(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:s.SUCCESSED,roomData:c},{logSource:e.LogSource.RTC}),{room:_,code:exports.RCRTCCode.SUCCESS,userIds:_.getRemoteUserIds(),RTCTracks:_.getRemoteRTCTracks(),MCUTracks:_.getRemoteMCUTracks(),CDNUris:_.getCDNInfo()}}))}leaveLivingRoomAsAudience(r){return t(this,void 0,void 0,(function*(){return e.logger.info(i.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_T,{roomId:r.getRoomId(),userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),this._crtAudienceLivingRoom?this._crtAudienceLivingRoom!==r?(e.logger.error(i.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR}):(yield this._crtAudienceLivingRoom.__destroy(!0),this._crtAudienceLivingRoom=null,e.logger.info(i.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:s.SUCCESSED,roomId:r.getRoomId(),userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS}):(e.logger.warn(i.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:s.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}upgradeToAnchorRoom(o){return t(this,void 0,void 0,(function*(){if(!e.validate("room",o,(()=>o instanceof Ur),!0))return e.logger.error(i.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(e.logger.info(i.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_T,{roomId:o.getRoomId(),userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),this._crtRoom)return e.logger.error(i.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const t=o.getRoomId(),n=this._crtRoom=new Or(this._context,this._runtime,t,this._service,this._options,o.livingType,!0,!0,!1,o.getClientSessionId()),a=yield n.__innerInitByIdentityChange();return a!==e.ErrorCode.SUCCESS?(r.warn(`change room identity failed -> code: ${a}`),this._crtRoom=null,e.logger.error(i.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):(n.once(cr,(()=>{this._crtRoom=null})),yield this._crtAudienceLivingRoom.__destroy(!1),this._crtAudienceLivingRoom=null,{room:n,code:exports.RCRTCCode.SUCCESS,userIds:n.getRemoteUserIds(),tracks:n.getRemoteTracks()})}))}downgradeToAudienceRoom(o){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_T,{roomId:o._roomId,userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),!o.isMainRoom())return r.error("the `downgradeToAudienceRoom` is disabled in PK room"),e.logger.error(i.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!e.validate("room._roomId",o._roomId,e.notEmptyString,!0))return e.logger.error(i.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> room._roomId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return e.logger.error(i.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const{code:t,data:n}=yield this._context.rtcIdentityChange(o._roomId,e.RTCIdentityChangeType.AnchorToViewer,o.getLivingType());if(t!==e.ErrorCode.SUCCESS)return r.error("change room identity error",t),e.logger.error(i.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};r.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(n)}`),e.logger.info(i.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:s.SUCCESSED,roomData:n},{logSource:e.LogSource.RTC});const a=o.getClientSessionId(),c=new Ur(this._context,this._runtime,this._options,o._roomId,n,o.getLivingType(),!1,a);return this._crtAudienceLivingRoom=c,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:c,code:exports.RCRTCCode.SUCCESS,userIds:c.getRemoteUserIds(),RTCTracks:c.getRemoteRTCTracks(),MCUTracks:c.getRemoteMCUTracks(),CDNUris:c.getCDNInfo()}}))}getJoinedRoomInfo(){return t(this,void 0,void 0,(function*(){const{code:t,data:o}=yield this._context.getRTCJoinedUserInfo(this._context.getCurrentId());return t!==e.ErrorCode.SUCCESS?(r.error("getJoinedUserInfo error",t),e.logger.error(i.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:s.FAILED,code:t,msg:"Switch identity error"},{logSource:e.LogSource.RTC}),{code:t}):(e.logger.info(i.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:s.SUCCESSED,roomInfo:o},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,data:o})}))}}var xr;exports.RCKickReason=void 0,(xr=exports.RCKickReason||(exports.RCKickReason={}))[xr.SERVER_KICK=1]="SERVER_KICK",xr[xr.OTHER_KICK=2]="OTHER_KICK";const Br={tag:"RCRTC",verify:t=>"browser"!==t.tag?(r.error(`RCRTC Plugin is not support the runtime '${t.tag}'`),!1):He?(e.VersionManage.add("plugin-rtc","5.4.2"),!!e.VersionManage.validEngine(">=5.3.4")||(r.error(`The current engine version '${e.VersionManage.getInfo().engine}' error, plugin-rtc required engine version at least '>=5.3.4'.`),!1)):(r.error("Please use the https protocol or use `http://localhost` to open the page!"),!1),setup:(t,o,i={})=>(r.setLogLevel(i.logLevel),r.setLogStdout(i.logStdout),r.warn("RCRTC Version: 5.4.2, Commit: 70db3a426400ee9ed6b37015c553787be663f508"),r.warn(`browserInfo.browser -> ${it.browser}`),r.warn(`browserInfo.supportsUnifiedPlan -> ${it.supportsUnifiedPlan}`),r.warn(`browserInfo.version -> ${it.version}`),e.assert("options.mediaServer",i.mediaServer,(t=>!(!e.isHttpUrl(t)||"https:"===location.protocol&&!/^https/.test(t)))),e.assert("options.timeout",i.timeout,(t=>e.isNumber(t)&&t>=5e3&&t<=3e4)),e.assert("options.pingGap",i.pingGap,(t=>e.isNumber(t)&&t>=3e3&&t<=1e4)),new br(t,o,i))},wr={transResolution:et,transFrameRate:ot,parseTrackId:We,ifSupportLocalFileTrack:st,ifSupportScreenShare:nt};Object.defineProperty(exports,"RTCJoinType",{enumerable:!0,get:function(){return e.RTCJoinType}}),exports.RCAbstractRoom=dr,exports.RCAudienceClient=Dr,exports.RCAudienceLivingRoom=Ur,exports.RCCameraVideoTrack=xe,exports.RCLivingRoom=Or,exports.RCLocalAudioTrack=ye,exports.RCLocalFileAudioTrack=Me,exports.RCLocalFileTrack=ke,exports.RCLocalFileVideoTrack=Ue,exports.RCLocalTrack=De,exports.RCLocalVideoTrack=Pe,exports.RCMCUConfigBuilder=hr,exports.RCMicphoneAudioTrack=be,exports.RCRTCClient=br,exports.RCRTCRoom=vr,exports.RCRemoteAudioTrack=Ve,exports.RCRemoteTrack=we,exports.RCRemoteVideoTrack=Fe,exports.RCScreenVideoTrack=Be,exports.RCTag={DEFAULT:"RongCloudRTC"},exports.RCTrack=Ne,exports.device=Ae,exports.helper=wr,exports.installer=Br;
15
+ ***************************************************************************** */function t(e,t,r,o){return new(r||(r=Promise))((function(i,s){function n(e){try{c(o.next(e))}catch(e){s(e)}}function a(e){try{c(o.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,a)}c((o=o.apply(e,t||[])).next())}))}const r=new e.Logger("RCRTC");var o,i,s;exports.RCRTCCode=void 0,(o=exports.RCRTCCode||(exports.RCRTCCode={}))[o.SUCCESS=1e4]="SUCCESS",o[o.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",o[o.PARAMS_ERROR=50001]="PARAMS_ERROR",o[o.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",o[o.NOT_IN_ROOM=50003]="NOT_IN_ROOM",o[o.SERVICE_INVALID=50004]="SERVICE_INVALID",o[o.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",o[o.SIGNAL_ERROR=53001]="SIGNAL_ERROR",o[o.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",o[o.REQUEST_FAILED=53004]="REQUEST_FAILED",o[o.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",o[o.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",o[o.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",o[o.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",o[o.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",o[o.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",o[o.PERMISSION_DENIED=53012]="PERMISSION_DENIED",o[o.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",o[o.INVALID_TAGS=53014]="INVALID_TAGS",o[o.INVALID_USER_ID=53015]="INVALID_USER_ID",o[o.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",o[o.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",o[o.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",o[o.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",o[o.TRACK_NOT_READY=53020]="TRACK_NOT_READY",o[o.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",o[o.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",o[o.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",o[o.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",o[o.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",o[o.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",o[o.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",o[o.SIGNAL_JOIN_RTC_ROOM_REFUSED=53028]="SIGNAL_JOIN_RTC_ROOM_REFUSED",o[o.NO_PERMISSION_TO_USE_REQUESTED_DEVICE=53029]="NO_PERMISSION_TO_USE_REQUESTED_DEVICE",o[o.THE_FUNCTION_IS_DISABLED_IN_PKROOM=53030]="THE_FUNCTION_IS_DISABLED_IN_PKROOM",o[o.SOME_TRACKS_PUBLISH_FAILED=53031]="SOME_TRACKS_PUBLISH_FAILED",o[o.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO=53032]="MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO",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"}(i||(i={})),function(e){e.FAILED="fail",e.SUCCESSED="success",e.TIMEOUT="timeout",e.INFO="info"}(s||(s={}));let n=!0,a=!0;function c(e,t,r){const o=e.match(t);return o&&o.length>=r&&parseInt(o[r],10)}function d(e,t,r){if(!e.RTCPeerConnection)return;const o=e.RTCPeerConnection.prototype,i=o.addEventListener;o.addEventListener=function(e,o){if(e!==t)return i.apply(this,arguments);const s=e=>{const t=r(e);t&&(o.handleEvent?o.handleEvent(t):o(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(o,s),i.apply(this,[e,s])};const s=o.removeEventListener;o.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const o=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,o])},Object.defineProperty(o,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function _(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(n=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function u(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(a=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function l(){if("object"==typeof window){if(n)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function R(e,t){a&&console.warn(e+" is deprecated, please use "+t+" instead.")}function C(e){return"[object Object]"===Object.prototype.toString.call(e)}function p(e){return C(e)?Object.keys(e).reduce((function(t,r){const o=C(e[r]),i=o?p(e[r]):e[r],s=o&&!Object.keys(i).length;return void 0===i||s?t:Object.assign(t,{[r]:i})}),{}):e}function h(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((o=>{o.endsWith("Id")?h(e,e.get(t[o]),r):o.endsWith("Ids")&&t[o].forEach((t=>{h(e,e.get(t),r)}))})))}function T(e,t,r){const o=r?"outbound-rtp":"inbound-rtp",i=new Map;if(null===t)return i;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===o&&r.trackId===t.id&&h(e,r,i)}))})),i}const g=l;function m(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const o=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const o="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==o.exact&&"number"==typeof o.exact&&(o.min=o.max=o.exact);const i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==o.ideal){t.optional=t.optional||[];let e={};"number"==typeof o.ideal?(e[i("min",r)]=o.ideal,t.optional.push(e),e={},e[i("max",r)]=o.ideal,t.optional.push(e)):(e[i("",r)]=o.ideal,t.optional.push(e))}void 0!==o.exact&&"number"!=typeof o.exact?(t.mandatory=t.mandatory||{},t.mandatory[i("",r)]=o.exact):["min","max"].forEach((e=>{void 0!==o[e]&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,r)]=o[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=o(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const n=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||n)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{let n=(r=r.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!n&&r.length&&t.includes("back")&&(n=r[r.length-1]),n&&(e.video.deviceId=s.exact?{exact:n.deviceId}:{ideal:n.deviceId}),e.video=o(e.video),g("chrome: "+JSON.stringify(e)),i(e)}))}e.video=o(e.video)}return g("chrome: "+JSON.stringify(e)),i(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,o){i(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{o&&o(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return i(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function S(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function E(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(r=>{let o;o=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const i=new Event("track");i.track=r.track,i.receiver=o,i.transceiver={receiver:o},i.streams=[t.stream],this.dispatchEvent(i)})),t.stream.getTracks().forEach((r=>{let o;o=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const i=new Event("track");i.track=r,i.receiver=o,i.transceiver={receiver:o},i.streams=[t.stream],this.dispatchEvent(i)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else d(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function I(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,o){let i=r.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};const o=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){o.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const o=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],o.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function f(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,o]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const i=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const o=function(e){r(s(i(e)))};return t.apply(this,[o,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(s(i(t)))},r])})).then(r,o)}}function L(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>T(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}),d(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>T(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,o;return this.getSenders().forEach((r=>{r.track===e&&(t?o=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?o=!0:r=t),t.track===e))),o||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function O(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const o=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(o)&&this._shimmedLocalStreams[r.id].push(o):this._shimmedLocalStreams[r.id]=[r,o],o};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();r.apply(this,arguments);const o=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(o)};const o=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],o.apply(this,arguments)};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),i.apply(this,arguments)}}function v(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return O(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const o=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}o.apply(this,[t])};const i=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const o=e._reverseStreams[t],i=e._streams[o.id];r=r.replace(new RegExp(i.id,"g"),o.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function n(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const o=e._reverseStreams[t],i=e._streams[o.id];r=r.replace(new RegExp(o.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const o=[].slice.call(arguments,1);if(1!==o.length||!o[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const i=this.getSenders().find((e=>e.track===t));if(i)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[r.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const o=new e.MediaStream([t]);this._streams[r.id]=o,this._reverseStreams[o.id]=r,this.addStream(o)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],o={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=o[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=n(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=c.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function A(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],o={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=o[t]}))}function N(e,t){d(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var D=Object.freeze({__proto__:null,shimMediaStream:S,shimOnTrack:E,shimGetSendersWithDtmf:I,shimGetStats:f,shimSenderReceiverGetStats:L,shimAddTrackRemoveTrackWithNative:O,shimAddTrackRemoveTrack:v,shimPeerConnection:A,fixNegotiationNeeded:N,shimGetUserMedia:m,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const o=r.video&&r.video.width,i=r.video&&r.video.height,s=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},o&&(r.video.mandatory.maxWidth=o),i&&(r.video.mandatory.maxHeight=i),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});var k,P,y=(k=function(e){var t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},t.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},t.getDescription=function(e){var r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){var r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((function(e){return 0===e.indexOf(r)}))},t.parseCandidate=function(e){for(var t,r={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},o=8;o<t.length;o+=2)switch(t[o]){case"raddr":r.relatedAddress=t[o+1];break;case"rport":r.relatedPort=parseInt(t[o+1],10);break;case"tcptype":r.tcpType=t[o+1];break;case"ufrag":r.ufrag=t[o+1],r.usernameFragment=t[o+1];break;default:r[t[o]]=t[o+1]}return r},t.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substr(14).split(" ")},t.parseRtpMap=function(e){var t=e.substr(9).split(" "),r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){for(var t,r={},o=e.substr(e.indexOf(" ")+1).split(";"),i=0;i<o.length;i++)r[(t=o[i].trim().split("="))[0].trim()]=t[1];return r},t.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var o=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?o.push(t+"="+e.parameters[t]):o.push(t)})),t+="a=fmtp:"+r+" "+o.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){var t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},o=e.indexOf(":",t);return o>-1?(r.attribute=e.substr(t+1,o-t-1),r.value=e.substr(o+1)):r.attribute=e.substr(t+1),r},t.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},t.getMid=function(e){var r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substr(6)},t.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){var r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){var t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;var t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){var o=t.matchPrefix(e+r,"a=ice-ufrag:")[0],i=t.matchPrefix(e+r,"a=ice-pwd:")[0];return o&&i?{usernameFragment:o.substr(12),password:i.substr(10)}:null},t.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},t.parseRtpParameters=function(e){for(var r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},o=t.splitLines(e)[0].split(" "),i=3;i<o.length;i++){var s=o[i],n=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(n){var a=t.parseRtpMap(n),c=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(a.parameters=c.length?t.parseFmtp(c[0]):{},a.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(a.name.toUpperCase())}}}return t.matchPrefix(e,"a=extmap:").forEach((function(e){r.headerExtensions.push(t.parseExtmap(e))})),r},t.writeRtpDescription=function(e,r){var o="";o+="m="+e+" ",o+=r.codecs.length>0?"9":"0",o+=" UDP/TLS/RTP/SAVPF ",o+=r.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",o+="c=IN IP4 0.0.0.0\r\n",o+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((function(e){o+=t.writeRtpMap(e),o+=t.writeFmtp(e),o+=t.writeRtcpFb(e)}));var i=0;return r.codecs.forEach((function(e){e.maxptime>i&&(i=e.maxptime)})),i>0&&(o+="a=maxptime:"+i+"\r\n"),o+="a=rtcp-mux\r\n",r.headerExtensions&&r.headerExtensions.forEach((function(e){o+=t.writeExtmap(e)})),o},t.parseRtpEncodingParameters=function(e){var r,o=[],i=t.parseRtpParameters(e),s=-1!==i.fecMechanisms.indexOf("RED"),n=-1!==i.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute})),c=a.length>0&&a[0].ssrc,d=t.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));d.length>0&&d[0].length>1&&d[0][0]===c&&(r=d[0][1]),i.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&r&&(t.rtx={ssrc:r}),o.push(t),s&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:n?"red+ulpfec":"red"},o.push(t))}})),0===o.length&&c&&o.push({ssrc:c});var _=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,o.forEach((function(e){e.maxBitrate=_}))),o},t.parseRtcpParameters=function(e){var r={},o=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];o&&(r.cname=o.value,r.ssrc=o.ssrc);var i=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=i.length>0,r.compound=0===i.length;var s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.parseMsid=function(e){var r,o=t.matchPrefix(e,"a=msid:");if(1===o.length)return{stream:(r=o[0].substr(7).split(" "))[0],track:r[1]};var i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return i.length>0?{stream:(r=i[0].value.split(" "))[0],track:r[1]}:void 0},t.parseSctpDescription=function(e){var r,o=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");i.length>0&&(r=parseInt(i[0].substr(19),10)),isNaN(r)&&(r=65536);var s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substr(12),10),protocol:o.fmt,maxMessageSize:r};if(t.matchPrefix(e,"a=sctpmap:").length>0){var n=t.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(n[0],10),protocol:n[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){var r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,r,o){var i=void 0!==r?r:2;return"v=0\r\no="+(o||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+i+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,r,o,i){var s=t.writeRtpDescription(e.kind,r);if(s+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===o?"actpass":"active"),s+="a=mid:"+e.mid+"\r\n",e.direction?s+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var n="msid:"+i.id+" "+e.rtpSender.track.id+"\r\n";s+="a="+n,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+n,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+n,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+t.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+t.localCName+"\r\n"),s},t.getDirection=function(e,r){for(var o=t.splitLines(e),i=0;i<o.length;i++)switch(o[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return o[i].substr(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substr(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){var r=t.splitLines(e)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){var r=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var r=t.splitLines(e),o=0;o<r.length;o++)if(r[o].length<2||"="!==r[o].charAt(1))return!1;return!0},e.exports=t},k(P={exports:{}},P.exports),P.exports);function U(e,t,r,o,i){var s=y.writeRtpDescription(e.kind,t);if(s+=y.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=y.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":i||"active"),s+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var n=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=n;var a="msid:"+(o?o.id:"-")+" "+n+"\r\n";s+="a="+a,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+y.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+y.localCName+"\r\n"),s}function M(e,t){var r={codecs:[],headerExtensions:[],fecMechanisms:[]},o=function(e,t){e=parseInt(e,10);for(var r=0;r<t.length;r++)if(t[r].payloadType===e||t[r].preferredPayloadType===e)return t[r]},i=function(e,t,r,i){var s=o(e.parameters.apt,r),n=o(t.parameters.apt,i);return s&&n&&s.name.toLowerCase()===n.name.toLowerCase()};return e.codecs.forEach((function(o){for(var s=0;s<t.codecs.length;s++){var n=t.codecs[s];if(o.name.toLowerCase()===n.name.toLowerCase()&&o.clockRate===n.clockRate){if("rtx"===o.name.toLowerCase()&&o.parameters&&n.parameters.apt&&!i(o,n,e.codecs,t.codecs))continue;(n=JSON.parse(JSON.stringify(n))).numChannels=Math.min(o.numChannels,n.numChannels),r.codecs.push(n),n.rtcpFeedback=n.rtcpFeedback.filter((function(e){for(var t=0;t<o.rtcpFeedback.length;t++)if(o.rtcpFeedback[t].type===e.type&&o.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var o=0;o<t.headerExtensions.length;o++){var i=t.headerExtensions[o];if(e.uri===i.uri){r.headerExtensions.push(i);break}}})),r}function b(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 x(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 B(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 V=function(e,t){function r(t,r){r.addTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function o(t,r,o,i){var s=new Event("track");s.track=r,s.receiver=o,s.transceiver={receiver:o},s.streams=i,e.setTimeout((function(){t._dispatchEvent("track",s)}))}var i=function(r){var o=this,i=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){o[e]=i[e].bind(i)})),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",r=JSON.parse(JSON.stringify(r||{})),this.usingBundle="max-bundle"===r.bundlePolicy,"negotiate"===r.rtcpMuxPolicy)throw B("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var o=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var i="string"==typeof o;return i&&(o=[o]),o=o.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||r?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(r=!0,!0)})),delete e.url,e.urls=i?o[0]:o,!!o.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var s=r.iceCandidatePoolSize;s>0;s--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=y.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(i.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(i.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),i.prototype.onicecandidate=null,i.prototype.onaddstream=null,i.prototype.ontrack=null,i.prototype.onremovestream=null,i.prototype.onsignalingstatechange=null,i.prototype.oniceconnectionstatechange=null,i.prototype.onconnectionstatechange=null,i.prototype.onicegatheringstatechange=null,i.prototype.onnegotiationneeded=null,i.prototype.ondatachannel=null,i.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},i.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},i.prototype.getConfiguration=function(){return this._config},i.prototype.getLocalStreams=function(){return this.localStreams},i.prototype.getRemoteStreams=function(){return this.remoteStreams},i.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,o={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&r)o.iceTransport=this.transceivers[0].iceTransport,o.dtlsTransport=this.transceivers[0].dtlsTransport;else{var i=this._createIceAndDtlsTransports();o.iceTransport=i.iceTransport,o.dtlsTransport=i.dtlsTransport}return t||this.transceivers.push(o),o},i.prototype.addTrack=function(t,r){if(this._isClosed)throw B("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var o;if(this.transceivers.find((function(e){return e.track===t})))throw B("InvalidAccessError","Track already exists.");for(var i=0;i<this.transceivers.length;i++)this.transceivers[i].track||this.transceivers[i].kind!==t.kind||(o=this.transceivers[i]);return o||(o=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),o.track=t,o.stream=r,o.rtpSender=new e.RTCRtpSender(t,o.dtlsTransport),o.rtpSender},i.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var o=e.clone();e.getTracks().forEach((function(e,t){var r=o.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),o.getTracks().forEach((function(e){r.addTrack(e,o)}))}},i.prototype.removeTrack=function(t){if(this._isClosed)throw B("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 B("InvalidAccessError","Sender was not created by this connection.");var o=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(o)&&this.localStreams.indexOf(o)>-1&&this.localStreams.splice(this.localStreams.indexOf(o),1),this._maybeFireNegotiationNeeded()},i.prototype.removeStream=function(e){var t=this;e.getTracks().forEach((function(e){var r=t.getSenders().find((function(t){return t.track===e}));r&&t.removeTrack(r)}))},i.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},i.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},i.prototype._createIceGatherer=function(t,r){var o=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var i=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(i,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(e){var r=!e.candidate||0===Object.keys(e.candidate).length;i.state=r?"completed":"gathering",null!==o.transceivers[t].bufferedCandidateEvents&&o.transceivers[t].bufferedCandidateEvents.push(e)},i.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),i},i.prototype._gather=function(t,r){var o=this,i=this.transceivers[r].iceGatherer;if(!i.onlocalcandidate){var s=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,i.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),i.onlocalcandidate=function(e){if(!(o.usingBundle&&r>0)){var s=new Event("icecandidate");s.candidate={sdpMid:t,sdpMLineIndex:r};var n=e.candidate,a=!n||0===Object.keys(n).length;if(a)"new"!==i.state&&"gathering"!==i.state||(i.state="completed");else{"new"===i.state&&(i.state="gathering"),n.component=1,n.ufrag=i.getLocalParameters().usernameFragment;var c=y.writeCandidate(n);s.candidate=Object.assign(s.candidate,y.parseCandidate(c)),s.candidate.candidate=c,s.candidate.toJSON=function(){return{candidate:s.candidate.candidate,sdpMid:s.candidate.sdpMid,sdpMLineIndex:s.candidate.sdpMLineIndex,usernameFragment:s.candidate.usernameFragment}}}var d=y.getMediaSections(o._localDescription.sdp);d[s.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",o._localDescription.sdp=y.getDescription(o._localDescription.sdp)+d.join("");var _=o.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==o.iceGatheringState&&(o.iceGatheringState="gathering",o._emitGatheringStateChange()),a||o._dispatchEvent("icecandidate",s),_&&(o._dispatchEvent("icecandidate",new Event("icecandidate")),o.iceGatheringState="complete",o._emitGatheringStateChange())}},e.setTimeout((function(){s.forEach((function(e){i.onlocalcandidate(e)}))}),0)}},i.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var o=new e.RTCDtlsTransport(r);return o.ondtlsstatechange=function(){t._updateConnectionState()},o.onerror=function(){Object.defineProperty(o,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:o}},i.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var r=this.transceivers[e].iceTransport;r&&(delete r.onicestatechange,delete this.transceivers[e].iceTransport);var o=this.transceivers[e].dtlsTransport;o&&(delete o.ondtlsstatechange,delete o.onerror,delete this.transceivers[e].dtlsTransport)},i.prototype._transceive=function(e,r,o){var i=M(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(i.encodings=e.sendEncodingParameters,i.rtcp={cname:y.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(i.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(i)),o&&e.rtpReceiver&&i.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?i.encodings=e.recvEncodingParameters:i.encodings=[{}],i.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(i.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(i.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(i))},i.prototype.setLocalDescription=function(e){var t,r,o=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(B("TypeError",'Unsupported type "'+e.type+'"'));if(!b("setLocalDescription",e.type,o.signalingState)||o._isClosed)return Promise.reject(B("InvalidStateError","Can not set local "+e.type+" in state "+o.signalingState));if("offer"===e.type)t=y.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=y.parseRtpParameters(e);o.transceivers[t].localCapabilities=r})),o.transceivers.forEach((function(e,t){o._gather(e.mid,t)}));else if("answer"===e.type){t=y.splitSections(o._remoteDescription.sdp),r=t.shift();var i=y.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var s=o.transceivers[t],n=s.iceGatherer,a=s.iceTransport,c=s.dtlsTransport,d=s.localCapabilities,_=s.remoteCapabilities;if(!(y.isRejected(e)&&0===y.matchPrefix(e,"a=bundle-only").length)&&!s.rejected){var u=y.getIceParameters(e,r),l=y.getDtlsParameters(e,r);i&&(l.role="server"),o.usingBundle&&0!==t||(o._gather(s.mid,t),"new"===a.state&&a.start(n,u,i?"controlling":"controlled"),"new"===c.state&&c.start(l));var R=M(d,_);o._transceive(s,R.codecs.length>0,!1)}}))}return o._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?o._updateSignalingState("have-local-offer"):o._updateSignalingState("stable"),Promise.resolve()},i.prototype.setRemoteDescription=function(i){var s=this;if(-1===["offer","answer"].indexOf(i.type))return Promise.reject(B("TypeError",'Unsupported type "'+i.type+'"'));if(!b("setRemoteDescription",i.type,s.signalingState)||s._isClosed)return Promise.reject(B("InvalidStateError","Can not set remote "+i.type+" in state "+s.signalingState));var n={};s.remoteStreams.forEach((function(e){n[e.id]=e}));var a=[],c=y.splitSections(i.sdp),d=c.shift(),_=y.matchPrefix(d,"a=ice-lite").length>0,u=y.matchPrefix(d,"a=group:BUNDLE ").length>0;s.usingBundle=u;var l=y.matchPrefix(d,"a=ice-options:")[0];return s.canTrickleIceCandidates=!!l&&l.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(o,c){var l=y.splitLines(o),R=y.getKind(o),C=y.isRejected(o)&&0===y.matchPrefix(o,"a=bundle-only").length,p=l[0].substr(2).split(" ")[2],h=y.getDirection(o,d),T=y.parseMsid(o),g=y.getMid(o)||y.generateIdentifier();if(C||"application"===R&&("DTLS/SCTP"===p||"UDP/DTLS/SCTP"===p))s.transceivers[c]={mid:g,kind:R,protocol:p,rejected:!0};else{var m,S,E,I,f,L,O,v,A;!C&&s.transceivers[c]&&s.transceivers[c].rejected&&(s.transceivers[c]=s._createTransceiver(R,!0));var N,D,k=y.parseRtpParameters(o);C||(N=y.getIceParameters(o,d),(D=y.getDtlsParameters(o,d)).role="client"),O=y.parseRtpEncodingParameters(o);var P=y.parseRtcpParameters(o),U=y.matchPrefix(o,"a=end-of-candidates",d).length>0,b=y.matchPrefix(o,"a=candidate:").map((function(e){return y.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===i.type||"answer"===i.type)&&!C&&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"!==i.type||C){if("answer"===i.type&&!C){S=(m=s.transceivers[c]).iceGatherer,E=m.iceTransport,I=m.dtlsTransport,f=m.rtpReceiver,L=m.sendEncodingParameters,v=m.localCapabilities,s.transceivers[c].recvEncodingParameters=O,s.transceivers[c].remoteCapabilities=k,s.transceivers[c].rtcpParameters=P,b.length&&"new"===E.state&&(!_&&!U||u&&0!==c?b.forEach((function(e){x(m.iceTransport,e)})):E.setRemoteCandidates(b)),u&&0!==c||("new"===E.state&&E.start(S,N,"controlling"),"new"===I.state&&I.start(D)),!M(m.localCapabilities,m.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&m.sendEncodingParameters[0].rtx&&delete m.sendEncodingParameters[0].rtx,s._transceive(m,"sendrecv"===h||"recvonly"===h,"sendrecv"===h||"sendonly"===h),!f||"sendrecv"!==h&&"sendonly"!==h?delete m.rtpReceiver:(A=f.track,T?(n[T.stream]||(n[T.stream]=new e.MediaStream),r(A,n[T.stream]),a.push([A,f,n[T.stream]])):(n.default||(n.default=new e.MediaStream),r(A,n.default),a.push([A,f,n.default])))}}else{(m=s.transceivers[c]||s._createTransceiver(R)).mid=g,m.iceGatherer||(m.iceGatherer=s._createIceGatherer(c,u)),b.length&&"new"===m.iceTransport.state&&(!U||u&&0!==c?b.forEach((function(e){x(m.iceTransport,e)})):m.iceTransport.setRemoteCandidates(b)),v=e.RTCRtpReceiver.getCapabilities(R),t<15019&&(v.codecs=v.codecs.filter((function(e){return"rtx"!==e.name}))),L=m.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var B,V=!1;if("sendrecv"===h||"sendonly"===h){if(V=!m.rtpReceiver,f=m.rtpReceiver||new e.RTCRtpReceiver(m.dtlsTransport,R),V)A=f.track,T&&"-"===T.stream||(T?(n[T.stream]||(n[T.stream]=new e.MediaStream,Object.defineProperty(n[T.stream],"id",{get:function(){return T.stream}})),Object.defineProperty(A,"id",{get:function(){return T.track}}),B=n[T.stream]):(n.default||(n.default=new e.MediaStream),B=n.default)),B&&(r(A,B),m.associatedRemoteMediaStreams.push(B)),a.push([A,f,B])}else m.rtpReceiver&&m.rtpReceiver.track&&(m.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===m.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),m.associatedRemoteMediaStreams=[]);m.localCapabilities=v,m.remoteCapabilities=k,m.rtpReceiver=f,m.rtcpParameters=P,m.sendEncodingParameters=L,m.recvEncodingParameters=O,s._transceive(s.transceivers[c],!1,V)}}})),void 0===s._dtlsRole&&(s._dtlsRole="offer"===i.type?"active":"passive"),s._remoteDescription={type:i.type,sdp:i.sdp},"offer"===i.type?s._updateSignalingState("have-remote-offer"):s._updateSignalingState("stable"),Object.keys(n).forEach((function(t){var r=n[t];if(r.getTracks().length){if(-1===s.remoteStreams.indexOf(r)){s.remoteStreams.push(r);var i=new Event("addstream");i.stream=r,e.setTimeout((function(){s._dispatchEvent("addstream",i)}))}a.forEach((function(e){var t=e[0],i=e[1];r.id===e[2].id&&o(s,t,i,[r])}))}})),a.forEach((function(e){e[2]||o(s,e[0],e[1],[])})),e.setTimeout((function(){s&&s.transceivers&&s.transceivers.forEach((function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},i.prototype.close=function(){this.transceivers.forEach((function(e){e.iceTransport&&e.iceTransport.stop(),e.dtlsTransport&&e.dtlsTransport.stop(),e.rtpSender&&e.rtpSender.stop(),e.rtpReceiver&&e.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},i.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},i.prototype._maybeFireNegotiationNeeded=function(){var t=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,e.setTimeout((function(){if(t.needNegotiation){t.needNegotiation=!1;var e=new Event("negotiationneeded");t._dispatchEvent("negotiationneeded",e)}}),0))},i.prototype._updateIceConnectionState=function(){var e,t={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&!e.rejected&&t[e.iceTransport.state]++})),e="new",t.failed>0?e="failed":t.checking>0?e="checking":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0?e="connected":t.completed>0&&(e="completed"),e!==this.iceConnectionState){this.iceConnectionState=e;var r=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",r)}},i.prototype._updateConnectionState=function(){var e,t={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&e.dtlsTransport&&!e.rejected&&(t[e.iceTransport.state]++,t[e.dtlsTransport.state]++)})),t.connected+=t.completed,e="new",t.failed>0?e="failed":t.connecting>0?e="connecting":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0&&(e="connected"),e!==this.connectionState){this.connectionState=e;var r=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",r)}},i.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(B("InvalidStateError","Can not call createOffer after close"));var o=r.transceivers.filter((function(e){return"audio"===e.kind})).length,i=r.transceivers.filter((function(e){return"video"===e.kind})).length,s=arguments[0];if(s){if(s.mandatory||s.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==s.offerToReceiveAudio&&(o=!0===s.offerToReceiveAudio?1:!1===s.offerToReceiveAudio?0:s.offerToReceiveAudio),void 0!==s.offerToReceiveVideo&&(i=!0===s.offerToReceiveVideo?1:!1===s.offerToReceiveVideo?0:s.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--o<0&&(e.wantReceive=!1):"video"===e.kind&&--i<0&&(e.wantReceive=!1)}));o>0||i>0;)o>0&&(r._createTransceiver("audio"),o--),i>0&&(r._createTransceiver("video"),i--);var n=y.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(o,i){var s=o.track,n=o.kind,a=o.mid||y.generateIdentifier();o.mid=a,o.iceGatherer||(o.iceGatherer=r._createIceGatherer(i,r.usingBundle));var c=e.RTCRtpSender.getCapabilities(n);t<15019&&(c.codecs=c.codecs.filter((function(e){return"rtx"!==e.name}))),c.codecs.forEach((function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1"),o.remoteCapabilities&&o.remoteCapabilities.codecs&&o.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(o.remoteCapabilities&&o.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=o.sendEncodingParameters||[{ssrc:1001*(2*i+1)}];s&&t>=15019&&"video"===n&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),o.wantReceive&&(o.rtpReceiver=new e.RTCRtpReceiver(o.dtlsTransport,n)),o.localCapabilities=c,o.sendEncodingParameters=d})),"max-compat"!==r._config.bundlePolicy&&(n+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),n+="a=ice-options:trickle\r\n",r.transceivers.forEach((function(e,t){n+=U(e,e.localCapabilities,"offer",e.stream,r._dtlsRole),n+="a=rtcp-rsize\r\n",!e.iceGatherer||"new"===r.iceGatheringState||0!==t&&r.usingBundle||(e.iceGatherer.getLocalCandidates().forEach((function(e){e.component=1,n+="a="+y.writeCandidate(e)+"\r\n"})),"completed"===e.iceGatherer.state&&(n+="a=end-of-candidates\r\n"))}));var a=new e.RTCSessionDescription({type:"offer",sdp:n});return Promise.resolve(a)},i.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(B("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(B("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var o=y.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.usingBundle&&(o+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),o+="a=ice-options:trickle\r\n";var i=y.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,s){if(!(s+1>i)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?o+="m=application 0 DTLS/SCTP 5000\r\n":o+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?o+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(o+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(o+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var n;if(e.stream)"audio"===e.kind?n=e.stream.getAudioTracks()[0]:"video"===e.kind&&(n=e.stream.getVideoTracks()[0]),n&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1});var a=M(e.localCapabilities,e.remoteCapabilities);!a.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,o+=U(e,a,"answer",e.stream,r._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(o+="a=rtcp-rsize\r\n")}}));var s=new e.RTCSessionDescription({type:"answer",sdp:o});return Promise.resolve(s)},i.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(o,i){if(!r._remoteDescription)return i(B("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var s=e.sdpMLineIndex;if(e.sdpMid)for(var n=0;n<r.transceivers.length;n++)if(r.transceivers[n].mid===e.sdpMid){s=n;break}var a=r.transceivers[s];if(!a)return i(B("OperationError","Can not add ICE candidate"));if(a.rejected)return o();var c=Object.keys(e.candidate).length>0?y.parseCandidate(e.candidate):{};if("tcp"===c.protocol&&(0===c.port||9===c.port))return o();if(c.component&&1!==c.component)return o();if((0===s||s>0&&a.iceTransport!==r.transceivers[0].iceTransport)&&!x(a.iceTransport,c))return i(B("OperationError","Can not add ICE candidate"));var d=e.candidate.trim();0===d.indexOf("a=")&&(d=d.substr(2)),(t=y.getMediaSections(r._remoteDescription.sdp))[s]+="a="+(c.type?d:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=y.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var _=0;_<r.transceivers.length&&(r.transceivers[_].rejected||(r.transceivers[_].iceTransport.addRemoteCandidate({}),(t=y.getMediaSections(r._remoteDescription.sdp))[_]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=y.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));_++);o()}))},i.prototype.getStats=function(t){if(t&&t instanceof e.MediaStreamTrack){var r=null;if(this.transceivers.forEach((function(e){e.rtpSender&&e.rtpSender.track===t?r=e.rtpSender:e.rtpReceiver&&e.rtpReceiver.track===t&&(r=e.rtpReceiver)})),!r)throw B("InvalidAccessError","Invalid selector.");return r.getStats()}var o=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&o.push(e[t].getStats())}))})),Promise.all(o).then((function(e){var t=new Map;return e.forEach((function(e){e.forEach((function(e){t.set(e.id,e)}))})),t}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(t){var r=e[t];if(r&&r.prototype&&r.prototype.getStats){var o=r.prototype.getStats;r.prototype.getStats=function(){return o.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var o;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(o=e[r]).type]||o.type,t.set(r,e[r])})),t}))}}}));var s=["createOffer","createAnswer"];return s.forEach((function(e){var t=i.prototype[e];i.prototype[e]=function(){var e=arguments;return"function"==typeof e[0]||"function"==typeof e[1]?t.apply(this,[arguments[2]]).then((function(t){"function"==typeof e[0]&&e[0].apply(null,[t])}),(function(t){"function"==typeof e[1]&&e[1].apply(null,[t])})):t.apply(this,arguments)}})),(s=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=i.prototype[e];i.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]||"function"==typeof e[2]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)}),(function(t){"function"==typeof e[2]&&e[2].apply(null,[t])})):t.apply(this,arguments)}})),["getStats"].forEach((function(e){var t=i.prototype[e];i.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)})):t.apply(this,arguments)}})),i};function w(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 F(e){"getDisplayMedia"in e.navigator&&e.navigator.mediaDevices&&(e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=e.navigator.getDisplayMedia.bind(e.navigator)))}function $(e,t){if(e.RTCIceGatherer&&(e.RTCIceCandidate||(e.RTCIceCandidate=function(e){return e}),e.RTCSessionDescription||(e.RTCSessionDescription=function(e){return e}),t.version<15025)){const t=Object.getOwnPropertyDescriptor(e.MediaStreamTrack.prototype,"enabled");Object.defineProperty(e.MediaStreamTrack.prototype,"enabled",{set(e){t.set.call(this,e);const r=new Event("enabled");r.enabled=e,this.dispatchEvent(r)}})}e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)&&Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new e.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),e.RTCDtmfSender&&!e.RTCDTMFSender&&(e.RTCDTMFSender=e.RTCDtmfSender);const r=V(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&&R("RTCIceServer.url","RTCIceServer.urls");const o="string"==typeof t;return o&&(t=[t]),t=t.filter((e=>{if(0===e.indexOf("stun:"))return!1;const t=e.startsWith("turn")&&!e.startsWith("turn:[")&&e.includes("transport=udp");return t&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=o?t[0]:t,!!t.length}}))}(e.iceServers,t.version),l("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype}function G(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var K=Object.freeze({__proto__:null,shimPeerConnection:$,shimReplaceTrack:G,shimGetUserMedia:w,shimGetDisplayMedia:F});function H(e,t){const r=e&&e.navigator,o=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,o){R("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,o)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},o&&o.prototype.getSettings){const t=o.prototype.getSettings;o.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(o&&o.prototype.applyConstraints){const t=o.prototype.applyConstraints;o.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function j(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function J(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],o={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=o[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},o=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,s]=arguments;return o.apply(this,[e||null]).then((e=>{if(t.version<53&&!i)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,o)=>{e.set(o,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(i,s)}}function W(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 Y(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}),d(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function q(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){R("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function z(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Q(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],r=e&&"sendEncodings"in e;r&&e.sendEncodings.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const o=t.apply(this,arguments);if(r){const{sender:t}=o,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return o})}function Z(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function X(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 ee(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 te=Object.freeze({__proto__:null,shimOnTrack:j,shimPeerConnection:J,shimSenderGetStats:W,shimReceiverGetStats:Y,shimRemoveStream:q,shimRTCDataChannel:z,shimAddTransceiver:Q,shimGetParameters:Z,shimCreateOffer:X,shimCreateAnswer:ee,shimGetUserMedia:H,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 re(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function oe(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function ie(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,o=t.createAnswer,i=t.setLocalDescription,s=t.setRemoteDescription,n=t.addIceCandidate;t.createOffer=function(e,t){const o=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[o]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],i=o.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i};let a=function(e,t,r){const o=i.apply(this,[e]);return r?(o.then(t,r),Promise.resolve()):o};t.setLocalDescription=a,a=function(e,t,r){const o=s.apply(this,[e]);return r?(o.then(t,r),Promise.resolve()):o},t.setRemoteDescription=a,a=function(e,t,r){const o=n.apply(this,[e]);return r?(o.then(t,r),Promise.resolve()):o},t.addIceCandidate=a}function se(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,o){t.mediaDevices.getUserMedia(e).then(r,o)}.bind(t))}function ne(e){return e&&void 0!==e.video?Object.assign({},e,{video:p(e.video)}):e}function ae(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let o=e.iceServers[r];!o.hasOwnProperty("urls")&&o.hasOwnProperty("url")?(R("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,t.push(o)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function ce(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 de(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 _e(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ue=Object.freeze({__proto__:null,shimLocalStreamsAPI:re,shimRemoteStreamsAPI:oe,shimCallbacksAPI:ie,shimGetUserMedia:se,shimConstraints:ne,shimRTCIceServerUrls:ae,shimTrackEventTransceiver:ce,shimCreateOfferLegacy:de,shimAudioContext:_e});function le(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const r=new t(e),o=y.parseCandidate(e.candidate),i=Object.assign(r,o);return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,d(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Re(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=function(e){if(!e||!e.sdp)return!1;const t=y.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=y.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},o=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r},i=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r},s=function(e,r){let o=65536;"firefox"===t.browser&&57===t.version&&(o=65535);const i=y.matchPrefix(e.sdp,"a=max-message-size:");return i.length>0?o=parseInt(i[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(o=2147483637),o},n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){const e=o(arguments[0]),t=i(e),r=s(arguments[0],e);let n;n=0===t&&0===r?Number.POSITIVE_INFINITY:0===t||0===r?Math.max(t,r):Math.min(t,r);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>n}),this._sctp=a}return n.apply(this,arguments)}}function Ce(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const o=arguments[0],i=o.length||o.size||o.byteLength;if("open"===e.readyState&&t.sctp&&i>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},d(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function pe(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function he(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function Te(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 ge=Object.freeze({__proto__:null,shimRTCIceCandidate:le,shimMaxMessageSize:Re,shimSendThrowTypeError:Ce,shimConnectionState:pe,removeExtmapAllowMixed:he,shimAddIceCandidateNullOrEmpty:Te});const me=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=l,o=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=c(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=c(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=c(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=c(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),i={browserDetails:o,commonShim:ge,extractVersion:c,disableLog:_,disableWarnings:u};switch(o.browser){case"chrome":if(!D||!A||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),i;if(null===o.version)return r("Chrome shim can not determine version, not shimming."),i;r("adapter.js shimming chrome."),i.browserShim=D,Te(e,o),m(e,o),S(e),A(e,o),E(e),v(e,o),I(e),f(e),L(e),N(e,o),le(e),pe(e),Re(e,o),Ce(e),he(e,o);break;case"firefox":if(!te||!J||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=te,Te(e,o),H(e,o),J(e,o),j(e),q(e),W(e),Y(e),z(e),Q(e),Z(e),X(e),ee(e),le(e),pe(e),Re(e,o),Ce(e);break;case"edge":if(!K||!$||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),i;r("adapter.js shimming edge."),i.browserShim=K,w(e),F(e),$(e,o),G(e),Re(e,o),Ce(e);break;case"safari":if(!ue||!t.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=ue,Te(e,o),ae(e),de(e),ie(e),re(e),oe(e),ce(e),se(e),_e(e),le(e),Re(e,o),Ce(e),he(e,o);break;default:r("Unsupported browser!")}return i}({window:"undefined"==typeof window?void 0:window});var Se,Ee,Ie;exports.RCFrameRate=void 0,(Se=exports.RCFrameRate||(exports.RCFrameRate={})).FPS_10="FPS_10",Se.FPS_15="FPS_15",Se.FPS_24="FPS_24",Se.FPS_30="FPS_30",exports.RCResolution=void 0,(Ee=exports.RCResolution||(exports.RCResolution={})).W176_H132="W176_H132",Ee.W176_H144="W176_H144",Ee.W256_H144="W256_H144",Ee.W320_H180="W320_H180",Ee.W240_H240="W240_H240",Ee.W320_H240="W320_H240",Ee.W480_H360="W480_H360",Ee.W640_H360="W640_H360",Ee.W480_H480="W480_H480",Ee.W640_H480="W640_H480",Ee.W720_H480="W720_H480",Ee.W1280_H720="W1280_H720",Ee.W1920_H1080="W1920_H1080",exports.RCMediaType=void 0,(Ie=exports.RCMediaType||(exports.RCMediaType={}))[Ie.AUDIO_ONLY=0]="AUDIO_ONLY",Ie[Ie.VIDEO_ONLY=1]="VIDEO_ONLY",Ie[Ie.AUDIO_VIDEO=2]="AUDIO_VIDEO";const fe={[exports.RCResolution.W176_H132]:{width:176,height:132,maxBitrate:150,minBitrate:80},[exports.RCResolution.W176_H144]:{width:176,height:144,maxBitrate:160,minBitrate:80},[exports.RCResolution.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[exports.RCResolution.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[exports.RCResolution.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[exports.RCResolution.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[exports.RCResolution.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[exports.RCResolution.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[exports.RCResolution.W480_H480]:{width:480,height:480,maxBitrate:800,minBitrate:180},[exports.RCResolution.W640_H480]:{width:640,height:480,maxBitrate:900,minBitrate:200},[exports.RCResolution.W720_H480]:{width:720,height:480,maxBitrate:1e3,minBitrate:200},[exports.RCResolution.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[exports.RCResolution.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},Le=(e,t)=>{const r=fe[`W${e}_H${t}`];if(r)return r;const o=e*t;return Object.keys(fe).map((e=>fe[e])).sort(((e,t)=>e.height*e.width-t.width*t.height)).filter((e=>e.height*e.width>=o))[0]||fe.W1920_H1080},Oe={10:1,15:1,24:1.5,30:1.5},ve=e=>{let t=Number.MAX_VALUE,r=1;for(const o in Oe){const i=Math.abs(e-parseInt(o));i<t&&(t=i,r=Oe[o])}return r},Ae={getCameras:()=>t(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))})),getMicrophones:()=>t(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))})),getSpeakers:()=>t(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audiooutput"===e.kind))}))};var Ne,De;!function(e){e.AUDIO="audio",e.VIDEO="video"}(Ne||(Ne={}));class ke extends e.EventEmitter{constructor(e,t,r,o,i){super(),this._tag=e,this._userId=t,this._kind=r,this._isLocalTrack=o,this._roomId=i,this._localMuted=!1,this._remoteMuted=!1,this._streamId=[this._userId||this._roomId,this._tag].join("_"),this._id=[this._streamId,this.isAudioTrack()?0:1].join("_")}getStreamId(){return this._streamId}getTrackId(){return this._id}getUserId(){return this._userId}__innerGetMediaStreamTrack(){return this._msTrack}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(){r.info(`set ${this._id} enabled: false`),e.logger.info(i.L_TRACK_MUTE_O,{status:s.SUCCESSED,id:this._id},{logSource:e.LogSource.RTC}),this._setLocalMuted(!0)}unmute(){r.info(`set ${this._id} enabled: true`),e.logger.info(i.L_TRACK_UNMUTE_O,{status:s.SUCCESSED,id:this._id},{logSource:e.LogSource.RTC}),this._setLocalMuted(!1)}isLocalMuted(){return this._localMuted}isMCUTrack(){return Boolean(this._roomId)}isOwnerMuted(){return this._remoteMuted}play(o,n={autoplay:!0}){var a,c;return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_TRACK_PLAY_T,{element:o,options:n},{logSource:e.LogSource.RTC}),!this._msTrack)return r.warn(`the track is not ready to play -> id: ${this._id}`),e.logger.error(i.L_TRACK_PLAY_R,{status:s.FAILED,code:exports.RCRTCCode.TRACK_NOT_READY,msg:`play error -> id: ${this._id}`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&(r.warn(`the track's readyState is 'ended' -> id: ${this._id}`),e.logger.error(i.L_TRACK_PLAY_R,{status:s.FAILED,code:"",msg:`the track's readyState is ended -> id: ${this._id}`},{logSource:e.LogSource.RTC})),null==n?void 0:n.volume){if(!e.isNumber(null==n?void 0:n.volume))return r.error(`${null==n?void 0:n.volume} is not a number, the valid range of options.volume is 0-100`),e.logger.error(i.L_TRACK_PLAY_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> options.volume不是数字"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};(null==n?void 0:n.volume)<0&&(n.volume=0,r.warn("the valid range of options.volume is 0-100, the value of volume has been set 0"),e.logger.warn(i.L_TRACK_PLAY_R,{status:s.FAILED,code:"",msg:"params error -> options.volume < 0"},{logSource:e.LogSource.RTC})),(null==n?void 0:n.volume)>100&&(n.volume=100,r.warn("the valid range of options.volume is 0-100, the value of volume has been set 100"),e.logger.warn(i.L_TRACK_PLAY_R,{status:s.FAILED,code:"",msg:"params error -> options.volume > 100"},{logSource:e.LogSource.RTC}))}if(null==n?void 0:n.audioDeviceId){if(!(yield Ae.getSpeakers()).map((e=>e.deviceId)).includes(n.audioDeviceId))return r.error(`the options.audioDeviceId is invalid --\x3e ${n.audioDeviceId}`),e.logger.error(i.L_TRACK_PLAY_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> options.audioDeviceId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR}}const d=this.isVideoTrack();if(d&&(!o||!(o instanceof HTMLVideoElement||this.__validateVideoNodeName(o))))return r.error(`the video track need an <video> to play -> id: ${this._id}`),e.logger.error(i.L_TRACK_PLAY_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> element不是一个video标签"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.VIDEO_TRACK_MISS_MEDIA_ELEMENT};this._element=d?o:this._element||new Audio,this._localMuted&&this._setLocalMuted(!1),this._element.srcObject&&this._element.srcObject===this._msStream||this._element.pause(),this._element.onloadstart=t=>{var o,n;r.debug(`HTMLMediaElement onloadstart -> id: ${null===(o=t.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`),e.logger.info(i.L_TRACK_PLAY_R,{status:s.INFO,msg:`HTMLMediaElement onloadstart -> id: ${null===(n=t.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:e.LogSource.RTC})},this._element.ondurationchange=t=>{var o,n;r.debug(`HTMLMediaElement ondurationchange -> id: ${null===(o=t.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`),e.logger.info(i.L_TRACK_PLAY_R,{status:s.INFO,msg:`HTMLMediaElement ondurationchange -> id: ${null===(n=t.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:e.LogSource.RTC})},this._element.onloadedmetadata=t=>{var o,n;r.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(o=t.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`),e.logger.info(i.L_TRACK_PLAY_R,{status:s.INFO,msg:`HTMLMediaElement onloadedmetadata -> id: ${null===(n=t.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:e.LogSource.RTC})},this._element.onloadeddata=t=>{var o,n;r.debug(`HTMLMediaElement onloadeddata -> id: ${null===(o=t.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`),e.logger.info(i.L_TRACK_PLAY_R,{status:s.INFO,msg:`HTMLMediaElement onloadeddata -> id: ${null===(n=t.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:e.LogSource.RTC})},this._element.onabort=t=>{var o,n;r.info(`HTMLMediaElement onabort -> id: ${null===(o=t.target)||void 0===o?void 0:o.id}, trackId: ${this._id}`),e.logger.info(i.L_TRACK_PLAY_R,{status:s.INFO,msg:`HTMLMediaElement onabort -> id: ${null===(n=t.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:e.LogSource.RTC})};const _=null===(null===(a=this._element)||void 0===a?void 0:a.getAttribute("autoplay"))?n.autoplay:null===(c=this._element)||void 0===c?void 0:c.autoplay;return this._element.oncanplay=o=>t(this,void 0,void 0,(function*(){var t,n,a;if(r.info(`HTMLMediaElement oncanplay -> id: ${null===(t=o.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`),e.logger.info(i.L_TRACK_PLAY_R,{status:s.INFO,msg:`HTMLMediaElement oncanplay -> id: ${null===(n=o.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:e.LogSource.RTC}),_)try{null===(a=this._element)||void 0===a||a.play()}catch(t){if("No permission to use requested device"===t.message)return r.error(`setSinkId failed -> ${t.message}`),void e.logger.error(i.L_TRACK_PLAY_R,{status:s.FAILED,code:exports.RCRTCCode.NO_PERMISSION_TO_USE_REQUESTED_DEVICE,msg:"No permission"},{logSource:e.LogSource.RTC});r.error(t),e.logger.error(i.L_TRACK_PLAY_R,{status:s.FAILED,code:exports.RCRTCCode.TRACK_PLAY_ERROR,msg:"play error"},{logSource:e.LogSource.RTC})}})),this._element.onvolumechange=t=>{var o,n;const a=Math.floor(100*(null===(o=t.target)||void 0===o?void 0:o.volume));r.info(`HTMLMediaElement onvolumechange -> volume: ${a}, trackId: ${this._id}`),e.logger.info(i.L_TRACK_PLAY_R,{status:s.INFO,msg:`HTMLMediaElement onvolumechange -> id: ${null===(n=t.target)||void 0===n?void 0:n.id}, trackId: ${this._id}`},{logSource:e.LogSource.RTC})},this._element.srcObject=this._msStream,this._element.autoplay=_,d&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),(null==n?void 0:n.audioDeviceId)&&!d&&(yield this._element.setSinkId(n.audioDeviceId)),d||!(null==n?void 0:n.volume)&&0!==(null==n?void 0:n.volume)||(this._element.volume=(null==n?void 0:n.volume)/100),e.logger.info(i.L_TRACK_PLAY_R,{status:s.SUCCESSED,element:o,options:n},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.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()}}exports.RCAudioBitrate=void 0,(De=exports.RCAudioBitrate||(exports.RCAudioBitrate={})).Speech="Speech",De.Music="Music",De.MusicHigh="MusicHigh";const Pe={[exports.RCAudioBitrate.Music]:{max:64e3,min:64e3},[exports.RCAudioBitrate.MusicHigh]:{max:128e3,min:128e3},[exports.RCAudioBitrate.Speech]:{max:32e3,min:32e3}};var ye;exports.RCVideoBitrate=void 0,(ye=exports.RCVideoBitrate||(exports.RCVideoBitrate={})).LEVEL0="LEVEL0",ye.LEVEL1="LEVEL1",ye.LEVEL2="LEVEL2",ye.LEVEL3="LEVEL3",ye.LEVEL4="LEVEL4",ye.LEVEL5="LEVEL5";const Ue={[exports.RCVideoBitrate.LEVEL0]:{max:150,min:80},[exports.RCVideoBitrate.LEVEL1]:{max:280,min:120},[exports.RCVideoBitrate.LEVEL2]:{max:650,min:150},[exports.RCVideoBitrate.LEVEL3]:{max:1e3,min:200},[exports.RCVideoBitrate.LEVEL4]:{max:2200,min:250},[exports.RCVideoBitrate.LEVEL5]:{max:4e3,min:400}};class Me extends ke{constructor(e,t,r,o){super(e,t,r,!0),this._isPublished=!1,this.__innerSetMediaStreamTrack(o),o.onended=()=>{o.onended=null,this.emit(Me.EVENT_LOCAL_TRACK_END,this),this.removeAll(Me.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(t){const r=this._localMuted!==t;super._setLocalMuted(t),this._remoteMuted=this._localMuted,r&&this.emit(Me.__INNER_EVENT_MUTED_CHANGE__,this),e.logger.info(i.L_LOCAL_TRACK_SET_LOCAL_MUTED_O,{status:s.SUCCESSED,bool:t},{logSource:e.LogSource.RTC})}__innerSetPublished(t){e.logger.info(i.L_LOCAL_TRACK_INNER_SET_PUBLISHED_O,{status:s.SUCCESSED,bool:t},{logSource:e.LogSource.RTC}),this._isPublished=t}isPublished(){return this._isPublished}destroy(){var t;r.info(`track is destroyed -> trackId: ${this.getTrackId()}`),null===(t=this._msTrack)||void 0===t||t.stop(),super.__innerDestroy(),this.isAudioTrack()&&super.__releaseMediaElement(),this.emit(Me.__INNER_EVENT_DESTROY__,this),e.logger.info(i.L_LOCAL_TRACK_DESTROY_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC})}setBitrate(t=0,o=0,n=0){if(!e.isNumber(t)||!e.isNumber(o)||!e.isNumber(n)||t<=0||o<=0||t<o)return r.error("setBitrate params error ->"),void e.logger.error(i.L_LOCAL_TRACK_SET_BITRATE_O,{status:s.FAILED,code:"",msg:`params error -> max: ${t},min: ${o}, start: ${n}`},{logSource:e.LogSource.RTC});e.logger.info(i.L_LOCAL_TRACK_SET_BITRATE_O,{status:s.SUCCESSED,max:t,min:o,start:n},{logSource:e.LogSource.RTC}),this._bitrateInfo={max:t,min:o,start:n}}getBitrate(){var e,t,r,o,i,s,n;let{min:a,max:c,start:d}={min:0,max:0,start:0};return(null===(e=this._msTrack)||void 0===e?void 0:e.kind)===Ne.VIDEO?({min:a,max:c}=Xe(this._msTrack)):(null===(t=this._msTrack)||void 0===t?void 0:t.kind)===Ne.AUDIO&&({min:a,max:c}={min:32e3,max:32e3}),(null===(r=this._bitrateInfo)||void 0===r?void 0:r.max)&&(d=.7*(null===(o=this._bitrateInfo)||void 0===o?void 0:o.max)),{min:(null===(i=this._bitrateInfo)||void 0===i?void 0:i.min)||a,max:(null===(s=this._bitrateInfo)||void 0===s?void 0:s.max)||c,start:(null===(n=this._bitrateInfo)||void 0===n?void 0:n.start)||d}}}Me.EVENT_LOCAL_TRACK_END="local-track-end",Me.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",Me.__INNER_EVENT_DESTROY__="inner-destroy";class be extends Me{constructor(e,t,r){super(e,t,"audio",r)}setRecommendBitrate(t){if(!e.validate("livingType",t,(e=>e in exports.RCAudioBitrate)))return void e.logger.warn(i.L_RTC_SET_RECOMMEND_BITRATE_O,{status:s.FAILED,msg:"params error -> setRecommendBitrate Audio"},{logSource:e.LogSource.RTC});const r=Pe[t];this.setBitrate(r.max,r.min,r.start||.7*r.max)}setBitrate(e,...t){const[r=1,o=.7*e||1]=t;super.setBitrate(e,r,o)}}class xe extends Me{constructor(e,t,r,o=!1){super(e,t,"video",r),this._isTiny=o}__isTiny(){return this._isTiny}getStreamId(){const e=super.getStreamId();return this._isTiny?`${e}_tiny`:e}getTrackId(){const e=super.getTrackId();return this._isTiny?`${e}_tiny`:e}setRecommendBitrate(t){if(!e.validate("livingType",t,(e=>e in exports.RCVideoBitrate)))return void e.logger.warn(i.L_RTC_SET_RECOMMEND_BITRATE_O,{status:s.FAILED,msg:"params error -> setRecommendBitrate Video"},{logSource:e.LogSource.RTC});const r=Ue[t];this.setBitrate(r.max,r.min,r.start||.7*r.max)}setBitrate(e,...t){const[r=1,o=.7*e||1]=t;super.setBitrate(e,r,o)}}class Be extends Me{constructor(e,t,r,o,i){super(e,t,r,o),this._resource=i,Be.__innerSetMapping(this.getTrackId(),i)}static __innerSetMapping(e,t){const r=this._mapping.get(t)||[];r.push(e),this._mapping.set(t,r)}static __innerRemoveMapping(e,t){var r,o;const i=null===(r=this._mapping.get(t))||void 0===r?void 0:r.filter((t=>t!==e));i&&i.length>0?this._mapping.set(t,i):(this._mapping.delete(t),t.pause(),t.src="",null===(o=t.parentNode)||void 0===o||o.removeChild(t))}destroy(){this.isAudioTrack()&&this.mute(),Be.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}Be._mapping=new Map;class Ve extends Be{constructor(e,t,r,o){super(e,t,"video",r,o)}}class we extends Be{constructor(e,t,r,o){super(e,t,"audio",r,o)}_setLocalMuted(e){this._resource&&(this._resource.muted=e),super._setLocalMuted(e)}play(){return this._setLocalMuted(!1),Promise.resolve({code:exports.RCRTCCode.SUCCESS})}}class Fe extends be{}class $e extends xe{}class Ge extends xe{}class Ke extends be{}class He extends ke{constructor(e,t,r,o){super(e,t,r,!1,o),this._isSubscribed=!1}__innerSetRemoteMuted(e){this._remoteMuted=e}__innerSetSubscribed(t){this._isSubscribed=t,e.logger.info(i.L_REMOTE_TRACK_INNER_SET_SUBSCRIBED_O,{status:s.SUCCESSED,bool:t},{logSource:e.LogSource.RTC})}isSubscribed(){return this._isSubscribed}}class je extends He{constructor(e,t,r){super(e,t,"audio",r)}}class Je extends He{constructor(e,t,r){super(e,t,"video",r)}}const We=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),Ye=e=>JSON.stringify(e),qe=e=>/^[a-zA-Z\d-=]+$/g.test(e),ze="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),Qe=t=>{if(void 0===t)return 0;if(e.isNumber(t))return t;const r=t;return r.exact||r.ideal||r.max||0},Ze=e=>{const t=e.getSettings(),r=e.getConstraints();return{width:t.width||Qe(r.width),height:t.height||Qe(r.height),frameRate:t.frameRate||Qe(r.frameRate)}},Xe=e=>{const{width:t,height:r,frameRate:o}=Ze(e),i=Le(t||1920,r||1080),s=ve(o);return{min:i.minBitrate*s,max:i.maxBitrate*s}},et=e=>[e.msid,e.mediaType].join("_"),tt=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},rt=(e,t)=>[e,t].join("_"),ot=e=>e.map((e=>Object.assign({},e))),it=(e,t,r=!1)=>{e=e.slice();const o=[],i=[],s=[];return t.forEach((t=>{const i=et(t);let n=e.findIndex((e=>et(e)===i));if(r&&(n=e.findIndex((e=>e.uri===t.uri))),-1===n)return void o.push(t);const a=e[n];a.uri!==t.uri?o.push(t):a.state!==t.state&&s.push(t),e.splice(n,1)})),i.push(...e),{publishedList:o,unpublishedList:i,modifiedList:s}},st=()=>{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 o=+e;const i=[];do{const e=o%r;o=(o-e)/r,i.unshift(t[e])}while(o);return i.join("")})(e),e.length>22&&(e=e.slice(0,22)),e},nt=e=>{const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},at=e=>!!exports.RCResolution[e],ct=e=>!!exports.RCFrameRate[e],dt=e=>parseInt(e.replace("FPS_","")),_t=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=me.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function ut(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function lt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const Rt=e=>"[object Null]"===Object.prototype.toString.call(e),Ct=e=>1===e.type,pt=(e,t)=>{const o={},i=Object.keys(e.users);return i.length&&i.forEach((i=>{const s=[],n=e.users[i];if(n.extra){const e=JSON.parse(n.extra).roomId;if(t!==e)return}if(n.uris)try{s.push(...JSON.parse(n.uris))}catch(e){r.warn(`invalid user data -> userId: ${i}, userData: ${n}`)}o[i]=s})),o},ht=e=>e instanceof ke?e.getTrackId():e.track.getTrackId();var Tt,gt;!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"}(Tt||(Tt={})),exports.RCRTCPingResult=void 0,(gt=exports.RCRTCPingResult||(exports.RCRTCPingResult={})).SUCCESS="Success",gt.FAIL="Fail";class mt{constructor(e,t,r,o=5e3,i=6e4){this._roomId=e,this._roomMode=t,this._context=r,this._gap=o,this._offlineKickTime=i,this._latestTimestamp=Date.now(),this._started=!1,this._timer=null}start(){this._started||(r.info("rtcping start ->"),e.logger.info(i.L_PINGER_START_O,{status:s.SUCCESSED,interval:this._gap},{logSource:e.LogSource.RTC}),this._started=!0,this._checkAlive())}_sendPing(){return new Promise((t=>{this._context.rtcPing(this._roomId,this._roomMode).then(t).catch((o=>{r.error(`rtcping receive unknown error -> ${o}`),t(e.ErrorCode.UNKNOWN)})),setTimeout(t,5e3,e.ErrorCode.TIMEOUT)}))}_checkAlive(){var o,n,a;return t(this,void 0,void 0,(function*(){r.info("rtcping ->");const t=yield this._sendPing(),c=Date.now();return t===e.ErrorCode.SUCCESS?(r.info("rtcping success ->"),this._latestTimestamp=c,null===(o=this.onPingResult)||void 0===o||o.call(this,exports.RCRTCPingResult.SUCCESS),void(this._timer=setTimeout((()=>this._checkAlive()),this._gap))):(t===e.ErrorCode.TIMEOUT&&e.logger.error(i.L_PINGER_TIMEOUT_O,{status:s.TIMEOUT},{logSource:e.LogSource.RTC}),r.warn(`rtcping failed -> code: ${t}`),null===(n=this.onPingResult)||void 0===n||n.call(this,exports.RCRTCPingResult.FAIL),40003===t||c-this._latestTimestamp>this._offlineKickTime?(this.stop(),void(null===(a=this.onFailed)||void 0===a||a.call(this,40003===t))):void(this._timer=setTimeout((()=>this._checkAlive()),500)))}))}stop(){this._started&&(r.info("rtcping stop ->"),e.logger.info(i.L_PINGER_STOP_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this._started=!1,this._timer&&(clearTimeout(this._timer),this._timer=null))}}const St=()=>"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)})),Et=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${_t.browser}|${_t.version}`,ClientVersion:"5.4.3","Client-Session-Id":St(),"Request-Id":Date.now().toString()});class It{constructor(e,t,r,o=5e3){this._runtime=e,this._context=t,this._msUrl=r,this._timeout=o,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 o;try{o=JSON.parse(e.voipCallInfo||'{ "strategy": 0 }')}catch(t){return r.warn("parse `voipCallInfo` of navi failed: "+e.voipCallInfo),[]}if(0===o.strategy)return[];const i=null===(t=o.callEngine)||void 0===t?void 0:t.filter((e=>4===e.engineType));if(!i||0===i.length)return[];const s=i[0],n=[];return s.mediaServer&&n.push(s.mediaServer.replace(/^(https?:\/\/)?/,"https://")),s.backupMediaServer&&s.backupMediaServer.forEach((e=>{n.push(e.replace(/^(https?:\/\/)?/,"https://"))})),n})(this._context.getNaviInfo())):(this._msInNavi.push(...this._failedMs),this._failedMs.length=0)),this._msInNavi.map((e=>e.trim())))}_request(o,n,a){return t(this,void 0,void 0,(function*(){const t=this.getNaviMS();if(0===t.length)return r.warn(`request '${o}' failed -> have no valid service address.`),e.logger.error(i.L_MEDIA_SERVICE_REQUEST_R,{status:s.FAILED,code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"invalid navi_url"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(a.rtcFinger=this._rtcFinger);for(let c=0;c<t.length;c+=1){const d=`${t[c]}${o}`,_=Et(),u=Object.assign(Object.assign({},_),n),l=JSON.stringify(a),R=_["Request-Id"];e.logger.info(i.L_MEDIA_SERVICE_REQUEST_T,{path:o,headers:n,body:a,reqId:R},{logSource:e.LogSource.RTC}),r.info(`request -> Request-Id: ${R}, url: ${d}, headers: ${JSON.stringify(u)}, body: ${l}`);const{status:C,data:p}=yield this._runtime.httpReq({url:d,body:l,headers:u,method:e.HttpMethod.POST,timeout:this._timeout});if(200===C){const t=JSON.parse(p);return t.rtcFinger&&(this._rtcFinger=t.rtcFinger),t.clusterId&&(this._clusterId=t.clusterId),r.info(`request success -> Request-Id: ${R}`),e.logger.info(i.L_MEDIA_SERVICE_REQUEST_R,{status:s.SUCCESSED,reqId:R},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,data:t}}r.warn(`request failed -> Request-Id: ${R}, status: ${C}, url: ${d}`),this._failedMs.push(...this._msInNavi.splice(c,1)),e.logger.error(i.L_MEDIA_SERVICE_REQUEST_R,{status:s.FAILED,code:"",reqId:R,msg:`request error -> Request-Id: ${R}, status: ${C}, url: ${d}`},{logSource:e.LogSource.RTC})}return{code:exports.RCRTCCode.REQUEST_FAILED}}))}exchange(e,r){var o;return t(this,void 0,void 0,(function*(){const t=yield this._request("/exchange",e,r);if(t.code===exports.RCRTCCode.SUCCESS&&(null===(o=t.data)||void 0===o?void 0:o.resultCode)===exports.RCRTCCode.SUCCESS){const e=t.data.urls;e&&(this._configUrl=e.configUrl)}return t}))}exit(e){return t(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 t(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/broadcast/exit",e,{});return{code:t}}))}setMcuConfig(o,n){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_MEDIA_SERVICE_SET_MCU_CONFIG_T,{headers:o,body:n},{logSource:e.LogSource.RTC}),!this._configUrl)return r.warn("RCMediaService.setMcuConfig failed -> RCRTCCode.MCU_SERVER_NOT_FOUND"),e.logger.error(i.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:s.FAILED,code:exports.RCRTCCode.MCU_SERVER_NOT_FOUND,msg:"MCU not found"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.MCU_SERVER_NOT_FOUND};const t=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,a=Et(),c=Object.assign(Object.assign({},a),o),d=JSON.stringify(n),_=a["Request-Id"];r.info(`request -> Request-Id: ${_}, url: ${t}, headers: ${JSON.stringify(c)}, body: ${d}`);const{status:u,data:l}=yield this._runtime.httpReq({url:t,headers:c,body:d,method:e.HttpMethod.POST});if(200===u){r.info(`request success -> Request-Id: ${_}`);const t=JSON.parse(l);return e.logger.info(i.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:s.SUCCESSED,reqId:_},{logSource:e.LogSource.RTC}),{code:t.resultCode,res:t}}return r.warn(`request failed -> Request-Id: ${_}, status: ${u}, url: ${t}`),e.logger.error(i.L_MEDIA_SERVICE_SET_MCU_CONFIG_R,{status:s.FAILED,code:exports.RCRTCCode.REQUEST_FAILED,msg:`request error -> Request-Id: ${_}, status: ${u}, url: ${t}`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REQUEST_FAILED}}))}getCDNResourceInfo(o,n){return t(this,void 0,void 0,(function*(){e.logger.info(i.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_T,{headers:o,url:n},{logSource:e.LogSource.RTC});const t=Et(),a=Object.assign(Object.assign({},t),o),c=t["Request-Id"];r.info(`request -> Request-Id: ${c}, url: ${n}, headers: ${JSON.stringify(a)}`);const{status:d,data:_}=yield this._runtime.httpReq({url:n,headers:a,method:e.HttpMethod.GET});if(200===d){r.info(`request success -> Request-Id: ${t["Request-Id"]}`);const o=JSON.parse(_);return e.logger.info(i.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:s.SUCCESSED,reqId:t["Request-Id"]},{logSource:e.LogSource.RTC}),{code:o.resultCode,res:o}}return r.warn(`request failed -> Request-Id: ${t["Request-Id"]}, status: ${d}, url: ${n}`),e.logger.info(i.L_MEDIA_SERVICE_GET_CDN_RESOURCE_INFO_R,{status:s.FAILED,code:exports.RCRTCCode.REQUEST_FAILED,msg:`request error -> Request-Id: ${t["Request-Id"]}, status: ${d}, url: ${n}`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REQUEST_FAILED}}))}}var ft;!function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(ft||(ft={}));const Lt=(e,t)=>Math.round(8*t/e),Ot=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},vt=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.ceil(e*r)},At=(e,t,r,o)=>{if(0===t)return 0;if(!r||!o)return Ot(e/t,3);const i=t-o;if(0===i)return 0;const s=e-r;return s<0||i<0?0:Ot(s/i,3)},Nt=e=>{const{jitter:t,rtt:r,packetsLostRate:o}=e;return!Rt(t)||!Rt(r)||0!==o};class Dt{constructor(e,t,r){this._rtcPeerConn=e,this._sdpSemantics=t,this._currentUserId=r,this._latestPacketsSent={},this._latestBytesSent={},this._latestBytesRecv={},this._latestPacketsRecv={}}updateBytesSent(e,t,r){let o,i;if(this._latestBytesSent[e]&&t<this._latestBytesSent[e].bytesSent&&this.clearLatestpacketsSent([e]),this._latestBytesSent[e]){const{bytesSent:s,timestamp:n}=this._latestBytesSent[e];o=t-s,i=r-n,this._latestBytesSent[e]={bytesSent:t,timestamp:r}}else o=t,i=1e3,this._latestBytesSent[e]={bytesSent:t,timestamp:r};return Lt(i,o)}updateBytesRecv(e,t,r){let o,i;if(this._latestBytesRecv[e]&&t<this._latestBytesRecv[e].bytesRecv&&this.clearLatestPacketsRecv([e]),this._latestBytesRecv[e]){const{bytesRecv:s,timestamp:n}=this._latestBytesRecv[e];o=t-s,i=r-n,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r}}else o=t,i=1e3,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r};return Lt(i,o)}updateSenderPacketsLost(e,t,r){let o;if(Object.prototype.hasOwnProperty.call(this._latestPacketsSent[e],"packetsSent")){const{packetsLost:i,packetsSent:s}=this._latestPacketsSent[e];o=At(t,r,i,s),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=i===t?s:r}else o=At(t,r),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=r;return o}updateReceiverPacketsLost(e,t,r){let o;if(this._latestPacketsRecv[e]){const{packetsLost:i,packetsRecv:s}=this._latestPacketsRecv[e];o=At(t,r+t,i,s+i)}else o=At(t,r);return this._latestPacketsRecv[e]={packetsLost:t,packetsRecv:r},o}clearLatestpacketsSent(e){e.forEach((e=>{if(parseInt(e.split("_").pop())===exports.RCMediaType.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 o=t.next();for(;!o.done;){const i=o.value,s=e.get(i);/^RTCCodec_/.test(i)||(r[i]=s),o=t.next()}return r}formatRCRTCStateReport(t){const r={senders:[],receivers:[]};return e.logger.info(i.L_ABSTRACT_STAT_PARSER_FORMAT_RTC_STATE_REPORT_O,{status:s.SUCCESSED,stats:t,reports:r},{logSource:e.LogSource.RTC}),r}getAudioLevelList(e){return[]}getResourceIdByParseSdp(e){var t,r;const o=e.ssrc,i=e.kind||e.mediaType,s=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,n=null===(r=this._rtcPeerConn.currentRemoteDescription)||void 0===r?void 0:r.sdp;let a;a="unified-plan"===this._sdpSemantics?new RegExp("a=msid:(.*?) "):new RegExp(`a=ssrc:${o} msid:(.*?) `);const c=null==s?void 0:s.split("\r\nm="),d=null==c?void 0:c.filter((e=>e.includes(`a=ssrc:${o}`)))[0],_=null==d?void 0:d.match(a);let u=_?_[1]:"";if(u){if("audio"===i)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="),R=null==l?void 0:l.filter((e=>e.includes(`a=ssrc:${o}`)))[0],C=null==R?void 0:R.match(a);return u=C?C[1]:"",u?`${u}_${"video"===i?1:0}`:""}isValidSender(e){var t;const r=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,{ssrc:o}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(o)&&e.includes("a=inactive"))))}isValidReceiver(e){var t;const r=null===(t=this._rtcPeerConn.currentRemoteDescription)||void 0===t?void 0:t.sdp,{ssrc:o}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(o)&&e.includes("a=inactive"))))}}class kt extends Dt{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const o=Object.keys(e);let i=0,s=0;o.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const n=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const{id:a,kind:c,transportId:d,mediaSourceId:_,remoteId:u,packetsSent:l,bytesSent:R,trackId:C,encoderImplementation:p,pliCount:h,nackCount:T,firCount:g}=n;if(!C)return;let{framesPerSecond:m,frameWidth:S,frameHeight:E}=n;"video"!==c||S||E||m||(S=e[C].frameWidth,E=e[C].frameHeight,m=_?e[_].framesPerSecond:null);const I=e[u];let f=null,L=null,O=0;I&&(f=I.jitter,L=I.roundTripTime,O=I.packetsLost),i+=O;const v=this.getResourceIdByParseSdp(n);if(!v)return;const A=_?e[_].audioLevel:e[C].audioLevel;let N=null;!this._latestPacketsSent[v]&&(this._latestPacketsSent[v]={}),I?N=this.updateSenderPacketsLost(v,O,l):this._latestPacketsSent[v].crtPacketsSent=l;let D=this.updateBytesSent(v,R,r);D<0&&(D=0),s+=D,t.senders.push({id:a,trackId:v,kind:c,packetsLostRate:N,remoteResource:!1,audioLevel:A||0===A?vt(A):null,frameWidth:S,frameHeight:E,frameRate:m,bitrate:D,jitter:f?Math.round(1e3*f):f,rtt:L,encoderImplementation:p,pliCount:h,nackCount:T,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));o.filter((e=>/RTCRemoteInboundRtp(Video|Audio)Stream_/.test(e))).forEach((r=>{const{localId:o,jitter:i,roundTripTime:s,packetsLost:n}=e[r],a=t.senders.filter((e=>e.id===o))[0];if(a&&!Nt(a)){const t=this.getResourceIdByParseSdp(e[a.id]);a.jitter=Math.round(1e3*i),a.rtt=s;const r=this._latestPacketsSent[t].crtPacketsSent;a.packetsLostRate=this.updateSenderPacketsLost(t,n,r)}}));let n=0;o.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const s=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:_,bytesReceived:u,framesPerSecond:l,kind:R,codecImplementationName:C,nackCount:p,pliCount:h}=s;if(!a)return;let{frameWidth:T,frameHeight:g,audioLevel:m}=s;"video"===R?T||g||(T=e[a].frameWidth,g=e[a].frameHeight):m||(m=e[a].audioLevel),i+=c;const S=this.getResourceIdByParseSdp(s),E=this.updateReceiverPacketsLost(S,c,d);let I=this.updateBytesRecv(S,u,r);I<0&&(I=0),n+=I,t.receivers.push({trackId:S,kind:R,packetsLostRate:E,remoteResource:!0,audioLevel:m||0===m?vt(m):null,frameWidth:T,frameHeight:g,frameRate:l,bitrate:I,jitter:_?Math.round(1e3*_):0,codecImplementationName:C,nackCount:p,pliCount:h,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=o.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:o}=r;if(o){const r=e[o],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:_,remoteCandidateId:u}=r,l=e[_],{ip:R,port:C,networkType:p}=l,h=e[u],{ip:T,port:g,protocol:m}=h;t.iceCandidatePair={IP:R,port:C,networkType:p,remoteIP:T,remotePort:g,protocol:m,bitrateRecv:n,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:i},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTPAudioStream_/.test(e))).forEach((r=>{var o;const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const{mediaSourceId:s,trackId:n}=i,a=this.getResourceIdByParseSdp(i),c=s&&e[s]?e[s].audioLevel:(null===(o=e[n])||void 0===o?void 0:o.audioLevel)||null;t.push({trackId:a,audioLevel:c||0===c?vt(c):null})}));return r.filter((e=>/^RTCInboundRTPAudioStream_/.test(e))).forEach((r=>{const o=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:i}=o,s=o.audioLevel||e[i].audioLevel,n=this.getResourceIdByParseSdp(o);t.push({trackId:n,audioLevel:s||0===s?vt(s):null})})),t}}class Pt extends Dt{formatRCRTCStateReport(e){const t=+new Date,r={senders:[],receivers:[],timestamp:t};let o=0,i=0,s=0;for(const n in e){const a=e[n],c=a.type;if("outbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(a))continue;const{id:s,kind:n,bytesSent:c,packetsSent:d,bitrateMean:_,framerateMean:u,nackCount:l,pliCount:R,remoteId:C}=a,{jitter:p,roundTripTime:h,packetsLost:T}=C?e[C]:{jitter:null,roundTripTime:null,packetsLost:0},g=this.getResourceIdByParseSdp(a);o+=T;let m=null;!this._latestPacketsSent[g]&&(this._latestPacketsSent[g]={}),C?m=this.updateSenderPacketsLost(g,T,d):this._latestPacketsSent[g].crtPacketsSent=d;let S=0;"video"===n?_&&(S=Math.floor(_/1e3)):S=this.updateBytesSent(g,c,t),S<0&&(S=0),i+=S,r.senders.push({trackId:g,kind:n,packetsLostRate:m,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:S,jitter:p?Math.round(1e3*p):null,rtt:h,encoderImplementation:null,pliCount:R,nackCount:l,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}if("remote-inbound-rtp"===c){const{localId:t}=a,o=this.getResourceIdByParseSdp(e[t]),i=r.senders.filter((e=>e.trackId===o))[0];i&&Nt(i)&&(i.jitter=Math.round(1e3*a.jitter),i.rtt=a.rtt,i.packetsLostRate=this.updateSenderPacketsLost(o,a.packetsLost,this._latestPacketsSent[o].crtPacketsSent))}if("inbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(a))continue;const{id:e,packetsLost:i,bytesReceived:n,packetsReceived:c,jitter:d,framerateMean:_,kind:u,bitrateMean:l,nackCount:R,pliCount:C}=a,p=this.getResourceIdByParseSdp(a);o+=i;const h=this.updateReceiverPacketsLost(p,i,c);let T=0;"video"===u?l&&(T=Math.floor(l/1e3)):T=this.updateBytesRecv(p,n,t),T<0&&(T=0),s+=T,r.receivers.push({trackId:p,kind:u,packetsLostRate:h,remoteResource:!0,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(_),bitrate:T,jitter:d?Math.round(1e3*d):null,codecImplementationName:null,nackCount:R,pliCount:C,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}if("candidate-pair"===c&&"succeeded"===a.state){const t=e[a.localCandidateId],{address:n,port:c}=t,d=e[a.remoteCandidateId],{address:_,port:u,protocol:l}=d;r.iceCandidatePair={IP:n,port:c,networkType:null,remoteIP:_,remotePort:u,protocol:l,bitrateRecv:s,bitrateSend:i,rtt:null,availableOutgoingBitrate:null,availableIncomingBitrate:null,totalPacketsLost:o}}}return r.iceCandidatePair&&(r.iceCandidatePair.bitrateSend=i),r.iceCandidatePair&&(r.iceCandidatePair.bitrateRecv=s),r}getAudioLevelList(e){const t=[];for(const r in e){const o=e[r],i=o.type;if("outbound-rtp"===i){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))continue;const{kind:e}=o;if("video"===e)continue;const r=this.getResourceIdByParseSdp(o);t.push({trackId:r,audioLevel:null})}if("inbound-rtp"===i){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))continue;const{kind:e}=o;if("video"===e)continue;const r=this.getResourceIdByParseSdp(o);t.push({trackId:r,audioLevel:null})}}return t}}class yt extends Dt{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const o=Object.keys(e);let i=0,s=0;o.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const i=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const n=this.getResourceIdByParseSdp(i),{mediaType:a,transportId:c,remoteId:d,packetsSent:_,bytesSent:u,trackId:l,encoderImplementation:R,pliCount:C,nackCount:p,firCount:h}=i;if(!l)return;const{audioLevel:T,frameHeight:g,frameWidth:m}=e[l];let S=this.updateBytesSent(n,u,r);S<0&&(S=0),s+=S,t.senders.push({trackId:n,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:T||0===T?vt(T):null,frameWidth:m,frameHeight:g,frameRate:null,bitrate:S,jitter:null,rtt:null,encoderImplementation:R,pliCount:C,nackCount:p,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));let n=0;o.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((o=>{const s=e[o];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:_,bytesReceived:u,mediaType:l,nackCount:R,pliCount:C}=s,p=this.getResourceIdByParseSdp(s);if(!a)return;const{frameHeight:h,frameWidth:T,audioLevel:g}=e[a];i+=c;const m=this.updateReceiverPacketsLost(p,c,d);let S=this.updateBytesRecv(p,u,r);S<0&&(S=0),n+=S,t.receivers.push({trackId:p,kind:l,packetsLostRate:m,remoteResource:!0,audioLevel:g||0===g?vt(g):null,frameWidth:T,frameHeight:h,frameRate:null,bitrate:S,jitter:_,codecImplementationName:null,nackCount:R,pliCount:C,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=o.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:o}=r;if(o){const r=e[o],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:_,remoteCandidateId:u}=r,l=e[_],{address:R,port:C}=l,p=e[u],{address:h,port:T,protocol:g}=p;t.iceCandidatePair={IP:R||null,port:C,networkType:null,remoteIP:h,remotePort:T,protocol:g,bitrateRecv:n,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:i},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const o=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))return;const{trackId:i,mediaType:s}=o;if("video"===s)return;const n=this.getResourceIdByParseSdp(o),a=e[i];t.push({trackId:n,audioLevel:a||0===a?vt(a):null})}));return r.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const o=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:i,mediaType:s}=o;if(!i||"video"===s)return;const{audioLevel:n}=e[i],a=this.getResourceIdByParseSdp(o);t.push({trackId:a,audioLevel:n||0===n?vt(n):null})})),t}}class Ut{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(t){return r.info(i.L_RTC_SDP_BITRATE_O,{bitrate:t,msg:"SDP setAudiosBitrate"},{logSource:e.LogSource.RTC}),this.audioStreams=this.audioStreams.map((e=>this.setAudioItemBitrate(e,t))),this}setAudioBitrateWithStreamId(t,o){return r.info(i.L_RTC_SDP_BITRATE_O,{bitrate:t,streamId:o,msg:"SDP setAudioBitrateWithStreamId"},{logSource:e.LogSource.RTC}),this.audioStreams=this.audioStreams.map((e=>new RegExp(`\\bmsid:${o}\\b`,"ig").test(e)?this.setAudioItemBitrate(e,t):e)),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(t){return r.info(i.L_RTC_SDP_BITRATE_O,{bitrate:t,msg:"SDP setVideosBitrate"},{logSource:e.LogSource.RTC}),this.videoStreams=this.videoStreams.map((e=>this.setVideoItemBitrate(e,t))),this}setVideoBitrateWithStreamId(t,o){return r.info(i.L_RTC_SDP_BITRATE_O,{bitrate:t,streamId:o,msg:"SDP setVideoBitrateWithStreamId"},{logSource:e.LogSource.RTC}),this.videoStreams=this.videoStreams.map((e=>new RegExp(`\\bmsid:${o}\\b`,"ig").test(e)?this.setVideoItemBitrate(e,t):e)),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 Mt,bt,xt,Bt,Vt,wt,Ft,$t;!function(e){e.PLANB="plan-b",e.UNIFIEDPLAN="unified-plan"}(Mt||(Mt={}));class Gt{constructor(e){this._peer=e,this._outboundStreams={}}static setSdpSemantics(t){e.logger.info(i.L_A_SDP_STRATEGY_SET_SDP_SEMANTICS_O,{status:s.SUCCESSED,sdpSemantics:t},{logSource:e.LogSource.RTC});const{browser:r,version:o,supportsUnifiedPlan:n}=_t;e.logger.debug(`sdpSemantics, browser: ${r}, version: ${o}, supportsUnifiedPlan: ${n}`),n?/chrome/i.test(r)?this._sdpSemantics=o>92?"unified-plan":o<72?"plan-b":t:/firefox/i.test(r)?this._sdpSemantics="unified-plan":/safari/i.test(r)?this._sdpSemantics=o<12?"plan-b":"unified-plan":this._sdpSemantics="unified-plan":this._sdpSemantics="plan-b"}static getSdpSemantics(){return Gt._sdpSemantics}getOutboundVideoInfo(){const e=[];for(const t in this._outboundStreams){const r=this._outboundStreams[t].getVideoTracks()[0];if(!r)continue;const o=/_tiny$/.test(t),{width:i,height:s}=Ze(r);e.push({trackId:r.id,simulcast:o?ft.TINY:ft.NORMAL,resolution:`${i}x${s}`})}return e}setRemoteAnswer(o){return t(this,void 0,void 0,(function*(){o=Ut.trimBlankLine(o),e.logger.info(`set remote answer -> ${o}`);try{yield this._peer.setRemoteDescription({type:"answer",sdp:o})}catch(t){return r.error(t),e.logger.info(i.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:s.FAILED,code:"",msg:t},{logSource:e.LogSource.RTC}),exports.RCRTCCode.SET_REMOTE_DESCRIPTION_FAILED}return e.logger.info(i.L_A_SDP_STRATEGY_SET_REMOTE_ANSWER_O,{status:s.SUCCESSED,sdp:o},{logSource:e.LogSource.RTC}),exports.RCRTCCode.SUCCESS}))}getStatParsr(e,t,r){return/chrome/i.test(_t.browser)?new kt(e,t,r):/Firefox/i.test(_t.browser)?new Pt(e,t,r):/Safari/i.test(_t.browser)?new yt(e,t,r):null}resetSdp(e){return Ut.trimBlankLine(e)}}class Kt extends Ut{constructor(e){super(e,Mt.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]===Ne.AUDIO&&(e[1]=t),r&&r[1]===Ne.VIDEO&&(e[2]=t)}));const t=e.join("");return Ut.trimBlankLine(t)}setAudioBitrateWithStreamId(e,t){return r.warn("plan-b not support set Audio Bitrate With Stream Id"),this}setVideoBitrateWithStreamId(e,t){return r.warn("plan-b not support set Video Bitrate With Stream Id"),this}}class Ht extends Gt{constructor(){super(...arguments),this.senders={},this._localTracks=[]}addLocalTrack(e){this._localTracks.includes(e)||this._localTracks.push(e);const t=e.getStreamId(),r=e.__innerGetMediaStreamTrack(),o=this._outboundStreams[t]||(this._outboundStreams[t]=new MediaStream);o.getTracks().forEach((e=>{e.kind===r.kind&&o.removeTrack(e)})),o.addTrack(r);const i=e.getTrackId(),s=this.senders[i];s?s.replaceTrack(r):this.senders[i]=this._peer.addTrack(r,o)}removeLocalTrack(e){const t=this._localTracks.findIndex((t=>t===e));t>=0&&this._localTracks.splice(t,1);const r=e.getTrackId(),o=this.senders[r];o&&(o.replaceTrack(null),this._peer.removeTrack(o),delete this.senders[r])}updateSubRemoteTracks(e){}updateRecvTransceiverMap(e,t){}setBitrate(e,t,r){this._maxBitrate=e,this._minBitrate=t,this._startBitrate=r||.7*e}createOffer(e){return t(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 Kt(e),r={max:0,min:0},o={max:0,min:0};return this._localTracks.forEach((e=>{const{min:t,max:i,start:s}=e.getBitrate();e.isAudioTrack()&&(o.max=o.max<i?i:o.max,o.min=o.min>t?t:o.min,o.max===i?o.start=s:o.start=.7*o.max),e.isVideoTrack()&&(r.max=r.max<i?i:r.max,r.min=r.min>t?t:r.min,r.max===i?r.start=s:r.start=.7*r.max)})),t.setAudiosBitrate(o),t.setVideosBitrate(r),t.stringify()}}class jt extends Ut{constructor(e){super(e,Mt.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 Ut.trimBlankLine(t)}}class Jt extends Gt{constructor(){super(...arguments),this._sendTransceiver={},this._localTracks={},this._recvAudio=[],this._recvVideo=[],this._recvTransceiver={},this._subedTracks=[]}setBitrate(e,t,o){r.warn("the interface named `setBitrate` is invalid while sdpSemantics value is `unified-plan`")}addLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId(),o=e.__innerGetMediaStreamTrack();this._localTracks[t]=e;const i=this._outboundStreams[r]||(this._outboundStreams[r]=new MediaStream);i.getTracks().forEach((e=>{e.kind===o.kind&&i.removeTrack(e)})),i.addTrack(o);const s=this._sendTransceiver[t];s?(s.sender.replaceTrack(o),s.direction="sendonly"):this._sendTransceiver[t]=this._peer.addTransceiver(o,{direction:"sendonly",streams:[i]})}removeLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId();e.__innerGetMediaStreamTrack(),delete this._localTracks[t];const o=this._sendTransceiver[t];if(!o)return;o.direction="inactive",this._peer.removeTrack(o.sender),o.sender.replaceTrack(null);const i=this._outboundStreams[r];(e.isAudioTrack()?i.getAudioTracks():i.getVideoTracks()).forEach((e=>i.removeTrack(e)));const s=this._sendTransceiver[`${t}_tiny`];if(!s||"inactive"===s.direction)return;s.direction="inactive";const 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}=tt(e);this._recvTransceiver[e]=t;const o=r===exports.RCMediaType.AUDIO_ONLY?this._recvAudio:this._recvVideo,i=o.findIndex((e=>e===t));i>=0&&o.splice(i,1)}updateSubRemoteTracks(e){const t=e.slice(),r=this._subedTracks.slice();this._subedTracks=e.slice();for(let e=t.length-1;e>=0;e-=1){const o=t[e],i=r.findIndex((e=>e===o));i>=0&&(t.splice(e,1),r.splice(i,1))}r.length&&r.forEach((e=>{const t=e.getTrackId();e.__innerSetMediaStreamTrack(void 0);const r=this._recvTransceiver[t];r&&(r.direction="inactive")}));const o={audio:0,video:0};t.length&&t.forEach((e=>{const t=e.isAudioTrack()?"audio":"video",r=this._recvTransceiver[e.getTrackId()];r?r.direction="recvonly":o[t]+=1}));for(let e=this._recvAudio.length;e<o.audio;e+=1)this._recvAudio.push(this._peer.addTransceiver("audio",{direction:"recvonly"}));for(let e=this._recvVideo.length;e<o.video;e+=1)this._recvVideo.push(this._peer.addTransceiver("video",{direction:"recvonly"}))}createOffer(e){return t(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)&&(r.warn(`answer sdp invalid -> ${JSON.stringify(e)}`),e=e.replace(t,"\r\n")),super.setRemoteAnswer(e)}resetSdp(e){const t=new jt(e);for(const e in this._sendTransceiver){const r=this._localTracks[e],o=null==r?void 0:r.getBitrate(),i=null==r?void 0:r.getStreamId();o&&i&&(r.isVideoTrack()&&t.setVideoBitrateWithStreamId(o,i),r.isAudioTrack()&&t.setAudioBitrateWithStreamId(o,i))}return t.stringify()}}class Wt extends e.EventEmitter{constructor(e,t,r,o){super(),this._pcName=e,this._reTryExchange=t,this._currentUserId=r,this._polarisReport=o,this.pubLocalTracks={},this._reTryExchangeTimer=null,this._reportStatsTimer=null,this._reportR3R4ToPolarisTimer=null,this._reportListener=null;const i=Gt.getSdpSemantics(),s=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:i});this._sdpStrategy="plan-b"===i?new Ht(s):new Jt(s),this._rtcPeerConn.oniceconnectionstatechange=this._onICEConnectionStateChange.bind(this),this._rtcPeerConn.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._rtcPeerConn.ontrack=this._onTrackReady.bind(this),this.reportParser=this._sdpStrategy.getStatParsr(this._rtcPeerConn,i,this._currentUserId)}getName(){return this._pcName}getLocalTracks(){return e.logger.info(i.L_RTC_PEER_CONNECTION_GET_LOCAL_TRACKS_O,{status:s.SUCCESSED,trackIds:Object.keys(this.pubLocalTracks)},{logSource:e.LogSource.RTC}),Object.values(this.pubLocalTracks)}_onConnectionStateChange(){r.info(`onconnectionstatechange -> ${this._rtcPeerConn.connectionState}, ${this._pcName}`),e.logger.info(i.L_RTC_PEER_CONNECTION_CONNECTION_STATE_S,{status:s.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:e.LogSource.RTC})}_onICEConnectionStateChange(){var t,o;r.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||(r.warn(`${this._pcName} iceconenction state is failed, exchange SDP to try again.`),e.logger.error(i.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:s.FAILED,code:"",msg:`${this._pcName} iceconenction state is failed, exchange SDP to try again.`},{logSource:e.LogSource.RTC}),this._reTryExchange(),this._reTryExchangeTimer=setInterval(this._reTryExchange,15e3));try{null===(o=null===(t=this._reportListener)||void 0===t?void 0:t.onICEConnectionStateChange)||void 0===o||o.call(t,this._rtcPeerConn.iceConnectionState,this._pcName)}catch(t){r.error("onICEConnectionStateChange error",t,this._pcName),e.logger.error(i.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:s.FAILED,code:"",msg:`${this._pcName}, ${t}`},{logSource:e.LogSource.RTC})}e.logger.info(i.L_RTC_PEER_CONNECTION_ICE_CONNECTION_STATE_S,{status:s.SUCCESSED,connectionState:this._rtcPeerConn.connectionState,pcName:this._pcName},{logSource:e.LogSource.RTC})}_onTrackReady(e){if(!e.streams.length)return;const t=[e.streams[0].id,"audio"===e.receiver.track.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY].join("_");this._updateRecvTransceiverMap(t,e.transceiver),this.emit(Wt.__INNER_EVENT_TRACK_READY__,e)}setBitrate(r,o,n){return t(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(r,o,n),e.logger.info(i.L_RTC_PEER_CONNECTION_SET_BITRATE_O,{status:s.SUCCESSED,max:r,min:o,start:n},{logSource:e.LogSource.RTC})}))}createOffer(o){return t(this,void 0,void 0,(function*(){const t=yield this._sdpStrategy.createOffer(o);return r.debug(`offer -> ${JSON.stringify(t.sdp)}`),e.logger.info(i.L_RTC_PEER_CONNECTION_CREATE_OFFER_O,{status:s.SUCCESSED,offerSDP:t.sdp},{logSource:e.LogSource.RTC}),t}))}setRemoteAnswer(o){return t(this,void 0,void 0,(function*(){return r.debug(`answer -> ${JSON.stringify(o)}`),e.logger.info(i.L_RTC_PEER_CONNECTION_SET_REMOTE_ANSWER_O,{status:s.SUCCESSED,answer:o},{logSource:e.LogSource.RTC}),this._sdpStrategy.setRemoteAnswer(o)}))}getLocalTrack(e){return this.pubLocalTracks[e]||null}addLocalTrack(t){this.pubLocalTracks[t.getTrackId()]=t,this._sdpStrategy.addLocalTrack(t),t.off(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.off(Me.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),t.on(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.on(Me.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.logger.info(i.L_RTC_PEER_CONNECTION_ADD_LOCAL_TRACK_O,{status:s.SUCCESSED,trackId:t.getTrackId()},{logSource:e.LogSource.RTC})}removeLocalTrackById(t){const r=this.getLocalTrack(t);r?(e.logger.info(i.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:s.SUCCESSED,trackId:t},{logSource:e.LogSource.RTC}),this.removeLocalTrack(r)):e.logger.warn(i.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_BY_ID_O,{status:s.FAILED,code:"",msg:"track not found"},{logSource:e.LogSource.RTC})}removeAllLocalTrack(){Object.keys(this.pubLocalTracks).forEach((e=>{/_tiny$/.test(e)||this.removeLocalTrackById(e)})),e.logger.info(i.L_RTC_PEER_CONNECTION_REMOVE_ALL_LOCAL_TRACK_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC})}removeLocalTrack(t){const r=t.getTrackId();delete this.pubLocalTracks[r],this._sdpStrategy.removeLocalTrack(t),t.__innerSetPublished(!1),t.off(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.off(Me.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this);const o=`${r}_tiny`,n=this.getLocalTrack(o);n&&(this._sdpStrategy.removeLocalTrack(n),delete this.pubLocalTracks[o],n.destroy()),e.logger.info(i.L_RTC_PEER_CONNECTION_REMOVE_LOCAL_TRACK_O,{status:s.SUCCESSED,trackId:r},{logSource:e.LogSource.RTC})}_updateRecvTransceiverMap(e,t){this._sdpStrategy.updateRecvTransceiverMap(e,t)}updateSubRemoteTracks(t){this._sdpStrategy.updateSubRemoteTracks(t),e.logger.info(i.L_RTC_PEER_CONNECTION_UPDATE_SUB_REMOTE_TRACKS_O,{status:s.SUCCESSED,trackIds:t.map((e=>e.getTrackId()))},{logSource:e.LogSource.RTC})}getOutboundVideoInfo(){return this._sdpStrategy.getOutboundVideoInfo()}_onLocalTrackMuted(t){const r=this.getLocalTrack(`${t.getTrackId()}_tiny`);r&&(r.__innerGetMediaStreamTrack().enabled=!t.isLocalMuted()),this.emit(Me.__INNER_EVENT_MUTED_CHANGE__,t),e.logger.info(i.L_RTC_PEER_CONNECTION_LOCAL_TRACK_MUTED_O,{status:s.SUCCESSED,trackId:t.getTrackId()},{logSource:e.LogSource.RTC})}_onLocalTrackDestroied(e){this.emit(Me.__INNER_EVENT_DESTROY__,e)}registerReportListener(e){this._reportListener=e}_createRCRTCStateReport(e){const{timestamp:t,iceCandidatePair:r,senders:o,receivers:i}=JSON.parse(JSON.stringify(e));null==r||delete r.totalPacketsLost;for(const e in r)Rt(r[e])&&delete r[e];return{timestamp:t,iceCandidatePair:r,senders:o.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),receivers:i.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),pcName:this._pcName}}_getStatsData(){var r,o;return t(this,void 0,void 0,(function*(){const t=yield this._rtcPeerConn.getStats(),n=null===(r=this.reportParser)||void 0===r?void 0:r.parseRTCStatsReport(t),a=null===(o=this.reportParser)||void 0===o?void 0:o.formatRCRTCStateReport(n);return e.logger.info(i.L_RTC_PEER_CONNECTION_GET_STATS_DATA_O,{status:s.SUCCESSED,formatData:a},{logSource:e.LogSource.RTC}),a}))}getAudioLevelReportData(){var e,r;return t(this,void 0,void 0,(function*(){const t=yield this._rtcPeerConn.getStats(),o=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(t);if(!o)return[];return null===(r=this.reportParser)||void 0===r?void 0:r.getAudioLevelList(o)}))}_reportHandle(){var e,r;return t(this,void 0,void 0,(function*(){const t=yield this._getStatsData();if(!t)return;const o=this._createRCRTCStateReport(t);null===(r=null===(e=this._reportListener)||void 0===e?void 0:e.onStateReport)||void 0===r||r.call(e,o)}))}_sendR3R4Data(){var e;return t(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 t(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,e.logger.info(i.L_RTC_PEER_CONNECTION_DESTROY_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC})}clearReTryExchangeTimer(){clearInterval(this._reTryExchangeTimer),this._reTryExchangeTimer=null}}Wt.__INNER_EVENT_TRACK_READY__="inner-track-ready",function(e){e[e.DISABLE=0]="DISABLE",e[e.ENABLE=1]="ENABLE"}(bt||(bt={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(xt||(xt={}));class Yt{constructor(e,t,r,o,i=xt.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=o,this._userRole=i}_send(r){return t(this,void 0,void 0,(function*(){let t=!1;if(this._context.getConnectionStatus()!==e.ConnectionStatus.CONNECTED)return t;return t=(yield this._context.setRTCState(this._roomId,r))===e.ErrorCode.SUCCESS,t}))}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=st(),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(),o=parseInt(r.pop())===exports.RCMediaType.AUDIO_ONLY?"audio":"video",i=r.pop();t=[r.join("_"),i,e,o].join("_")}else{const e=parseInt(r.pop())===exports.RCMediaType.AUDIO_ONLY?"audio":"video",o=r.pop();t=[r.join("_"),o,e].join("_")}return t}sendR3R4Data(e){return t(this,void 0,void 0,(function*(){const{iceCandidatePair:t,senders:r,receivers:o}=e,i=(null==t?void 0:t.bitrateSend)||-1,s=(null==t?void 0:t.bitrateRecv)||-1,n=(null==t?void 0:t.networkType)||"unknown",a=(null==t?void 0:t.rtt)||-1,c=`${(null==t?void 0:t.IP)||-1}:${null==t?void 0:t.port}`,d=(null==t||t.remoteIP,null==t||t.remotePort,(null==t?void 0:t.availableIncomingBitrate)||-1),_=(null==t?void 0:t.availableOutgoingBitrate)||-1,u=(null==t?void 0:t.totalPacketsLost)||-1,l=this._context.getCurrentId();let R=`R3\t${i}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${_}\t${u}\t${l}\r`,C=`R4\t${s}\t-1\t-1\t-1\t${n}\t${a}\t${c}\t${d}\t${_}\t${u}\t${l}\r`;const p=r.map((e=>{var t;const{trackId:r,audioLevel:o,samplingRate:i,bitrate:s,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:_,jitter:u,nackCount:l,pliCount:R,rtt:C,googFirsSent:p,encoderImplementation:h}=e,T=this._getPolarisTrackId(r),g=this._getRealResourceId(r);return{trackId:T,googCodecName:h||String(-1),audioLevel:o||0===o?o:-1,bitrate:s||0===s?s:-1,packetsLostRate:n||0===n?n:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:R||0===R?R:-1,rtt:C||-1,googFirsSent:p,samplingRate:i,googRenderDelayMs:_,encoderImplementation:h||String(-1),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(g))||void 0===t?void 0:t.isLocalMuted())?bt.DISABLE:bt.ENABLE}})),h=o.filter((e=>!!e.trackId)).map((e=>{var t;const{trackId:r,audioLevel:o,samplingRate:i,bitrate:s,packetsLostRate:n,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:_,jitter:u,nackCount:l,pliCount:R,rtt:C,googFirsReceived:p,codecImplementationName:h}=e,T=this._getPolarisTrackId(r),g=this._getRealResourceId(r);return{trackId:T,googCodecName:h||String(-1),audioLevel:o||0===o?o:-1,bitrate:s||0===s?s:-1,packetsLostRate:n||0===n?n:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:u||-1,nackCount:l||0===l?l:-1,pliCount:R||0===R?R:-1,rtt:C||-1,googFirsReceived:p,samplingRate:i,googRenderDelayMs:_,codecImplementationName:h||String(-1),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(g))||void 0===t?void 0:t.isLocalMuted())?bt.DISABLE:bt.ENABLE}}));let T=!1;R+=p.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsSent}\t${e.encoderImplementation}\t${e.trackState}`)).join("\n"),e.senders.length&&(T=yield this._send(R+`\r${this._userRole}`));let g=!1;return C+=h.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsReceived}\t${e.codecImplementationName}\t${e.trackState}`)).join("\n"),e.receivers.length&&(g=yield this._send(C+`\r${this._userRole}`)),!(!T&&!g)}))}sendR1(){const e=`R1\t5.4.3\t${this._context.getCoreVersion()}\tweb\t${navigator.platform}\t-1\t${_t.browser}\t${_t.version}\t${this._getClientID()}\t${this._userRole}`;this._send(e)}sendR2(e,t,r){const o=`R2\t${e}\t${t}\t${this._getClientID()}\r${r.join("\t")}\r${this._userRole}`;this._send(o)}}class qt{constructor(e){this._room=e,this._audioLevelChangeHandler=null,this._timer=null}_audioLevelReport(){return t(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 o=t[r];if("new"===o.getRTCPeerConn().iceConnectionState)return;const i=(yield o.getAudioLevelReportData()).map((e=>{const{userId:t}=tt(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(...i)}this._audioLevelChangeHandler(e)}))}onAudioLevelChange(e,t){t<300||t>1e3?r.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)}}exports.RCRTCLiveRole=void 0,(Bt=exports.RCRTCLiveRole||(exports.RCRTCLiveRole={}))[Bt.ANCHOR=1]="ANCHOR",Bt[Bt.AUDIENCE=2]="AUDIENCE";class zt{constructor(e=!1,t,r,o,i){this._useMutilPeerC=e,this._roomId=t,this._reTryExchange=r,this._currentUserId=o,this._polarisReport=i,this._mutilPeerC={}}get useMutilPeerC(){return this._useMutilPeerC}_isPub(e){if(!e.length)return!1;const{track:t}=e[0]instanceof Me||e[0]instanceof He?{track:e[0]}:e[0];return t.isLocalTrack()}_groupTracksByTag(e){const t={};return e.map((e=>{const{track:r}=e instanceof Me?{track:e}:e,o=r.getTag();t[o]?t[o].push(e):t[o]=[e]})),t}_genPCName(e,t){let r=null;return r=e?this._useMutilPeerC?`${this._roomId}_${t}`:`${this._roomId}_pub`:`${this._roomId}_sub`,r}_createOnePeerCItem(e,t){if(this._mutilPeerC[e]&&(this._mutilPeerC[e].tracks=t),!this._mutilPeerC[e]){const r=this._isPub(t),o=new Wt(e,(()=>this._reTryExchange(e,r)),this._currentUserId,this._polarisReport);this._mutilPeerC[e]={pc:o,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 o=this._groupTracksByTag(e);for(const e in o){const i=this._genPCName(r,e),s=o[e];t.push(this._createOnePeerCItem(i,s))}return t}_removeAllLocalTrack(){this.getPCList().forEach((e=>e.removeAllLocalTrack()))}destroyPeerC(e){this._mutilPeerC[e].pc.destroy()}_destroyAllPeerC(){this.getPCList().forEach((e=>e.destroy()))}getPCItemByPCName(e){return this._mutilPeerC[e]}getPCByTrackId(e,t=!0){const{tag:r}=tt(e),o=this._genPCName(t,r);return this._mutilPeerC[o].pc}getPCList(){const e=[];for(const t in this._mutilPeerC)e.push(this._mutilPeerC[t].pc);return e}getMutilPeerCData(){return this._mutilPeerC}setPeerCData(e,t,r){}clear(){this._removeAllLocalTrack(),this._destroyAllPeerC()}}!function(e){e[e.LOW=0]="LOW",e[e.NORMAL=1]="NORMAL",e[e.HIGH=2]="HIGH"}(Vt||(Vt={}));class Qt{get priority(){return Vt.LOW}}class Zt extends class{constructor(e,t,r,o,i,s,n,a,c){this.context=e,this.service=t,this.peerMgr=r,this.roomId=o,this.crtUserId=i,this.roomMode=s,this.polarisReport=n,this.isUpgrade=a,this.isMainRoom=c,this._remoteTracks={},this._subscribedList=[],this._CDNUris=null,this._CDNEnable=!1,this._destroyed=!1}get useMutilPeerC(){return this.peerMgr.useMutilPeerC}getResourcesByUserId(e){return this._roomResources[e]}getRemoteTrack(e){return this._remoteTracks[e]}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const o=this._remoteTracks[r];o.getUserId()===e&&t.push(o)}return t}getRemoteTracks(){return this._remoteTracks}getSessionId(){return this._sessionId}getAllUserIds(){return Object.keys(this._roomResources)}getRemoteUserIds(){return this.getAllUserIds().filter((e=>e!==this.crtUserId))}getSubscribedList(){return this._subscribedList}getPublishedResourceByTrackId(e){const{userId:t}=tt(e);return this._roomResources[t].find((t=>et(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=et(e),{tag:r,userId:o,mediaType:i}=tt(t),s=i===exports.RCMediaType.AUDIO_ONLY?new je(r,o):new Je(r,o);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=pt(e,this.roomId),this._initRemoteTracks(),this.setResourcesByUserId(this.crtUserId,this.getResourcesByUserId(this.crtUserId)||[]),r.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 Xt 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 t(this,void 0,void 0,(function*(){if(this._isDestroyed||this._busy||0===this._queue.length)return;this._busy=!0;const{command:e,resolve:t,reject:r}=this._queue.shift();let o;try{o=yield e.execute(this._store,this)}catch(e){return r(e),void this._next()}t(o),this._next()}))}push(e){return new Promise(((t,r)=>{if(this._isDestroyed)return;const o=e.priority;if(o===Vt.LOW)this._queue.push({command:e,resolve:t,reject:r});else{const i=this._queue.findIndex((e=>e.command.priority<o)),s=-1===i?this._queue.length-1:i;this._queue.splice(s,0,{command:e,resolve:t,reject:r})}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,o,i,s,n,a,c){super(new Zt(e,t,r,o,i,s,n,a,c),exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED)}get store(){return this._store}destroy(){super.destroy(),this._store.removeRemoteTracks()}}class er extends Qt{execute(o){return t(this,void 0,void 0,(function*(){const t=o.getResourcesByUserId(o.crtUserId),i=t.slice();t.length=0,r.info(`unpublish uris before rejoin -> ${JSON.stringify(i)}`);const s=yield o.context.setRTCTotalRes(o.roomId,We(Tt.UNPUBLISH,i),Ye([]),Tt.TOTAL_CONTENT_RESOURCE,Ye([]));s!==e.ErrorCode.SUCCESS?r.error(`unpublish uris before rejoin failed -> code: ${s}`):r.info("unpublish uris before rejoin success")}))}}class tr extends Qt{constructor(e,t,r,o,i,s){super(),this.roomId=e,this.roomType=t,this.joinType=r,this.livingType=o,this.innerUserDatas=i,this.outerUserDatas=s}execute(o,n){var a;return t(this,void 0,void 0,(function*(){const{context:t,service:c}=o,d=this.roomType===e.RTCMode.LIVE?i.L_RTC_CLIENT_JOIN_LIVING_ROOM_R:i.L_RTC_CLIENT_JOIN_RTC_ROOM_R;if(t.getConnectionStatus()!==e.ConnectionStatus.CONNECTED)return e.logger.error(d,{status:s.FAILED,code:exports.RCRTCCode.SIGNAL_DISCONNECTED,msg:"im not connected"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_DISCONNECTED};if(Ct(t.getNaviInfo()))return e.logger.error(d,{status:s.FAILED,code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_usl error"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR};if(!e.validate("roomId",this.roomId,e.notEmptyString,!0))return e.logger.error(d,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(!e.validate("roomType",this.roomType,(t=>void 0!==e.RTCMode[t])))return e.logger.error(d,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> roomType"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(!e.validate("outerUserDatas",this.outerUserDatas,e.isObject,!1))return e.logger.error(d,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(this.outerUserDatas){if(!Object.keys(this.outerUserDatas).every((t=>e.validate(`outerUserDatas.${t}`,this.outerUserDatas[t],e.isString,!0))))return e.logger.error(d,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> outerUserDatas"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR}}if(!c.getNaviMS().length)return e.logger.error(d,{status:s.FAILED,code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};r.info(`joinRoom -> roomId: ${this.roomId}; joinType: ${this.joinType||e.RTCJoinType.KICK}`);const{code:_,data:u}=yield t.joinRTCRoom(this.roomId,this.roomType,this.livingType,this.joinType,this.innerUserDatas,this.outerUserDatas);if(_!==e.ErrorCode.SUCCESS||!u){r.warn(`joinRoom failed -> code: ${_}`);const t=40032===_?exports.RCRTCCode.SIGNAL_JOIN_RTC_ROOM_REFUSED:_;return e.logger.error(d,{status:s.FAILED,code:t,msg:`joinRoom failed -> code: ${_}`},{logSource:e.LogSource.RTC}),{code:t}}r.info(`joinRoom success -> userId: ${t.getCurrentId()}, roomId: ${this.roomId}, data: ${JSON.stringify(u)}`),o.initWithRoomData(u);o.getResourcesByUserId(o.crtUserId).length>0&&n.push(new er);const l=null===(a=u.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===a?void 0:a.value;return l&&o.setCDNUris(JSON.parse(l)[0]),e.logger.info(d,{status:s.SUCCESSED,userId:o.crtUserId,roomId:this.roomId,data:u},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,data:u}}))}}function rr(e,r,o,i){return t(this,void 0,void 0,(function*(){return{sdp:yield o.createOffer(r),extend:JSON.stringify({resolutionInfo:o.getOutboundVideoInfo()}),subscribeList:e.filter((e=>{const t=e.track.getTrackId(),{userId:r}=tt(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?ft.TINY:ft.NORMAL,resolution:"",uri:i.getPublishedResourceByTrackId(e.track.getTrackId()).uri}))),switchstream:!1}}))}function or(o,i,s){return t(this,void 0,void 0,(function*(){const t=yield o.setRTCCDNUris(i,Tt.TOTAL_CONTENT_RESOURCE,JSON.stringify([s]));return t!==e.ErrorCode.SUCCESS?(r.error(`spreadCDNInfo failed -> code: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):(r.info("spreadCDNInfo succeed"),{code:exports.RCRTCCode.SUCCESS})}))}function ir(o,i,s){return t(this,void 0,void 0,(function*(){const t=yield o.setRTCData(i,"cdn_uris",JSON.stringify([s]),!0,e.RTCApiType.ROOM);return t!==e.ErrorCode.SUCCESS?(r.error(`setRoomCDNInfo failed -> code: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):(r.info("setRoomCDNInfo succeed"),{code:exports.RCRTCCode.SUCCESS})}))}function sr(r){return t(this,void 0,void 0,(function*(){const t=r.context,o=r.roomId,n=Object.assign({},r.getCDNUris(),{enableInnerCDN:r.getCDNEnable()});e.logger.info(i.L_LIVING_ROOM_SPREAD_CDN_INFO_T,{roomId:o,CDNUris:n},{logSource:e.LogSource.RTC});const a=(yield Promise.all([or(t,o,n),ir(t,o,n)])).every((e=>e.code===exports.RCRTCCode.SUCCESS));return a?e.logger.info(i.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:s.SUCCESSED,CDNUris:n},{logSource:e.LogSource.RTC}):e.logger.error(i.L_LIVING_ROOM_SPREAD_CDN_INFO_R,{status:s.FAILED,code:exports.RCRTCCode.SIGNAL_ERROR,msg:"signal error"},{logSource:e.LogSource.RTC}),a?{code:exports.RCRTCCode.SUCCESS}:{code:exports.RCRTCCode.SIGNAL_ERROR}}))}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(wt||(wt={})),function(e){e.BEGIN="begin",e.END="end"}(Ft||(Ft={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}($t||($t={}));class nr extends Qt{constructor(e,t){super(),this.headers=e,this.reqBody=t}execute(r,o){var i,s;return t(this,void 0,void 0,(function*(){const t=yield r.service.exchange(this.headers,this.reqBody);if(r.roomMode!==e.RTCMode.LIVE)return t;const o=null===(s=null===(i=t.data)||void 0===i?void 0:i.urls)||void 0===s?void 0:s.pull_url;if(t.code!==exports.RCRTCCode.SUCCESS||!o)return t;const n=JSON.parse(o);return r.setCDNUris(n),(null==n?void 0:n.broadcast)===$t.SPREAD&&(r.setCDNEnabel(!0),sr(r)),t}))}}class ar extends Qt{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(o,i){return t(this,void 0,void 0,(function*(){const{tracks:t,forceReq:s}=this,n=o.roomId;if(!e.validate("tracks",t,(()=>e.isArray(t)&&t.every((e=>e instanceof He||e.track instanceof He))),!0))return r.warn(`update sublist failed, tracks is invalid -> roomId: ${n}`),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`update subscribe list -> roomId: ${n}, forceReq: ${s}, tracks: ${t.map(ht)}`);let a=t.map((e=>e instanceof He?{track:e}:Object.assign({},e)));const c={};a=a.filter((e=>{const t=e.track.getTrackId();return o.getRemoteTrack(t)?!c[t]&&(c[t]=!0):(r.warn(`track cannot found in room -> trackId: ${t}`),!1)})).map((e=>Object.assign({},e)));const d=o.getSubscribedList().map((e=>Object.assign({},e)));if(!s){let e=!1;if(a.forEach((t=>{const r=d.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);d.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),d.length&&(e=!0),!e)return{code:exports.RCRTCCode.SUCCESS}}const{pc:_,pushOtherRooms:u,headers:l}=this.subhook(t);_.updateSubRemoteTracks(a.map((e=>e.track)));const R=yield rr(a,!1,_,o);u&&(R.pushOtherRooms=u);const C=yield new nr(l,R).execute(o,i),p=a.map((e=>e.track.getTrackId()));if(C.code!==exports.RCRTCCode.SUCCESS)return{code:C.code};const{sdp:h,resultCode:T,message:g,subscribedList:m}=C.data;if(T!==exports.RCRTCCode.SUCCESS)return r.error(`change subscribe list failed: ${T}`),{code:T};r.debug(`subscribe success: ${p.join(",")}`);const S=yield _.setRemoteAnswer(h.sdp);if(S!==exports.RCRTCCode.SUCCESS)return{code:S};const E=null==m?void 0:m.map((e=>`${e.msid}_${e.mediaType}`)),I=a.filter((e=>null==E?void 0:E.includes(e.track.getTrackId()))),f=a.filter((e=>!(null==E?void 0:E.includes(e.track.getTrackId())))),L=o.getRemoteTracks();for(const e in L){const t=I.some((t=>t.track.getTrackId()===e));L[e].__innerSetSubscribed(t)}const O=o.getSubscribedList();return O.splice(0,O.length,...I),f.length?{code:exports.RCRTCCode.SUCCESS,failedList:f}:{code:exports.RCRTCCode.SUCCESS}}))}}class cr extends Qt{constructor(e,t){super(),this.tracks=e,this.subhook=t}execute(o,n){return t(this,void 0,void 0,(function*(){const t=this.tracks,a=o.roomId;if(e.logger.info(i.L_ABSTRACT_ROOM_UNSUBSCRIBE_T,{trackIds:t.map(ht)},{logSource:e.LogSource.RTC}),!e.validate("tracks",t,(()=>e.isArray(t)&&t.length>0&&t.every((e=>e instanceof He))),!0))return r.warn(`unsubscribe failed, tracks is invalid -> roomId: ${a}`),e.logger.warn(i.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`unsubscribe -> roomId: ${a}, tracks: ${t.map(ht)}`);const c=o.getSubscribedList().map((e=>Object.assign({},e))).filter((e=>!t.includes(e.track)));return o.polarisReport.sendR2(wt.SUBSCRIBE,Ft.END,t.map((e=>e.getTrackId()))),e.logger.info(i.L_ABSTRACT_ROOM_UNSUBSCRIBE_R,{trackIds:t.map(ht),roomId:a},{logSource:e.LogSource.RTC}),new ar(c,this.subhook,!1).execute(o,n)}))}}class dr extends Qt{constructor(e,t){super(),this.msgContent=e,this.subhook=t}get priority(){return Vt.NORMAL}execute(e,o){return t(this,void 0,void 0,(function*(){const t=[],i=[],s=[],n=[],a={joined:t,left:i,upgrade:s,downgrade:n},{users:c}=this.msgContent;if(0===c.length)return a;for(let t=0;t<c.length;t++){const r=c[t];if(r.extra&&r.extra.roomId!==e.roomId)return a;if(1==+r.state&&!e.getRemoteUserIds().includes(r.userId))return a}c.forEach((o=>{const a=o.userId;if(0==+o.state){r.debug(`user joined -> ${a}`);const i=e.getResourcesByUserId(a);i||(o.switchRoleType?s.push(a):t.push(a)),e.setResourcesByUserId(a,i||[])}else r.debug(`user left -> ${a}`),o.switchRoleType?n.push(a):i.push(a)}));const d=[...i,...n];if(d.length){const t=[],r=[];d.forEach((o=>{t.push(...e.getRemoteTracksByUserId(o)),r.push(o)})),t.length&&(yield new cr(t,this.subhook).execute(e,o),t.forEach((t=>e.removeRemoteTrack(t.getTrackId())))),r.length&&r.forEach((t=>e.removeResourcesByUserId(t)))}return a}))}}class _r extends Qt{constructor(e,t,r){super(),this.subhook=e,this.tracks=t,this.onTrackUnpublish=r}execute(e,r){return t(this,void 0,void 0,(function*(){const t=this.tracks;yield new cr(t,this.subhook).execute(e,r),t.forEach((t=>{t.__innerDestroy(),e.removeRemoteTrack(t.getTrackId())})),this.onTrackUnpublish(t)}))}}class ur extends Qt{constructor(e,t,r){super(),this.tracks=e,this.subhook=t,this.forceReq=r}execute(o,n){return t(this,void 0,void 0,(function*(){const{tracks:t,forceReq:a}=this,c=o.roomId;if(e.logger.info(i.L_ABSTRACT_ROOM_SUBSCRIBE_T,{trackIds:t.map(ht),forceReq:a},{logSource:e.LogSource.RTC}),!e.validate("tracks",t,(()=>e.isArray(t)&&t.length>0&&t.every((e=>e instanceof He||e.track instanceof He))),!0))return r.warn(`subscribe failed, tracks is invalid -> roomId: ${c}`),e.logger.error(i.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`subscribe -> roomId: ${c}, tracks: ${t.map(ht)}`);const d=o.getSubscribedList().map((e=>Object.assign({},e))),_=t.map((e=>e instanceof He?{track:e}:e));let u=!1;const l=[];return _.forEach((e=>{const t=e.track.getTrackId();l.push(t);const r=d.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:d.push(e),u=!0)})),u||a?(o.polarisReport.sendR2(wt.SUBSCRIBE,Ft.BEGIN,l),e.logger.info(i.L_ABSTRACT_ROOM_SUBSCRIBE_R,{trackIds:t.map(ht),roomId:c},{logSource:e.LogSource.RTC}),new ar(d,this.subhook,!0).execute(o,n)):(e.logger.warn(i.L_ABSTRACT_ROOM_SUBSCRIBE_R,{status:s.FAILED,code:"",msg:"repeat subscribe"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}}class lr extends Qt{constructor(e,t,r,o,i){super(),this.msgContent=e,this.messageType=t,this.senderId=r,this.subhook=o,this.callback=i}get priority(){return Vt.NORMAL}execute(o,i){var s,n;return t(this,void 0,void 0,(function*(){const{uris:t}=this.msgContent,a=[],c=[],d=[];let _;const u=this.senderId,l=this.messageType,R=o.getResourcesByUserId(u)||[];switch(o.setResourcesByUserId(u,R),l){case Tt.MODIFY:d.push(...t);break;case Tt.PUBLISH:a.push(...t);break;case Tt.UNPUBLISH:c.push(...t);break;case Tt.TOTAL_CONTENT_RESOURCE:_=it(R,t),a.push(..._.publishedList),c.push(..._.unpublishedList),d.push(..._.modifiedList)}if(a.length>0){const e=R.map(et),t=[],s=[];if(a.forEach((r=>{const i=et(r),n=e.indexOf(i),{userId:a,tag:c,mediaType:d}=tt(i);n>-1?R[n]=r:R.push(r);let _=o.getRemoteTrack(i);_?_.isSubscribed()&&t.push(_):(_=d===exports.RCMediaType.AUDIO_ONLY?new je(c,a):new Je(c,a),o.addRemoteTrack(_),s.push(_)),_.__innerSetRemoteMuted(0===r.state)})),t.length){const e=t.map((e=>e.getTrackId()));r.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:s}=yield new ur(t,this.subhook,!0).execute(o,i);s!==exports.RCRTCCode.SUCCESS&&r.error(`resub tracks failed -> code: ${s}, ids: ${JSON.stringify(e)}`)}this.callback.onTrackPublish(s)}if(c.length>0){const e=c.map(et);for(let t=R.length-1;t>=0;t-=1){const r=R[t];e.includes(et(r))&&R.splice(t,1)}const t=c.map((e=>{const t=et(e);return o.getRemoteTrack(t)}));yield new _r(this.subhook,t,this.callback.onTrackUnublish).execute(o,i)}if(d.length>0){const e=R.map(et);for(let t=0;t<d.length;t+=1){const r=d[t],i=et(r),s=e.indexOf(i);R[s].state=r.state;const n=o.getRemoteTrack(i);n.__innerSetRemoteMuted(0===r.state),n.isAudioTrack()?this.callback.onAudioMute(n):this.callback.onVideoMute(n)}}if(o.roomMode!==e.RTCMode.LIVE)return;const C=this.msgContent;if(!C.cdn_uris)return;const p=(null===(s=o.getCDNUris())||void 0===s?void 0:s.enableInnerCDN)!==C.cdn_uris[0].enableInnerCDN;o.setCDNUris(C.cdn_uris[0]),p&&this.callback.onCDNEnableChange(!!(null===(n=o.getCDNUris())||void 0===n?void 0:n.enableInnerCDN))}))}}class Rr extends Qt{constructor(e,t){super(),this.tracks=e,this.pubhook=t}_removePubFailedTracks(e,t){e.forEach((e=>{const o=e instanceof Me?e:e.track;r.debug(`remove pub failed track from peerconnection -> trackId: ${o.getTrackId()}`),t.removeLocalTrackById(o.getTrackId())}))}__publish(e,o,i,s,n){return t(this,void 0,void 0,(function*(){const{pcName:t,pc:a,headers:c}=o,d=e.roomId,_=[];i.forEach((e=>{const{track:t}=e instanceof Me?{track:e}:e;_.push(t)}));if(a.getLocalTracks().length+((e,t)=>{let r=0;return e.forEach((e=>{const o=e instanceof Me?e.getTrackId():e.track.getTrackId();t.getLocalTrack(o)||(e instanceof Me?r++:e.pubTiny&&e.track.isVideoTrack()&&(r+=2))})),r})(i,a)>10)return r.error(`publish failed, tracks limit exceeded -> roomId: ${d}`),{code:exports.RCRTCCode.PUBLISH_TRACK_LIMIT_EXCEEDED,tracks:_};r.debug(`publish tracks -> roomId: ${d}, tracks: ${i.map(ht)}`),i.forEach((e=>{const{track:t,pubTiny:o}=e instanceof Me?{pubTiny:!1,track:e}:e;if(a.addLocalTrack(t),t.isVideoTrack()&&o){let e;try{e=t.__innerGetMediaStreamTrack().clone();const r=o.frameRate||exports.RCFrameRate.FPS_15,i=o.resolution||exports.RCResolution.W176_H144,{width:s,height:n}=nt(i),a=dt(r);e.applyConstraints({width:s,height:n,frameRate:a})}catch(o){return null==e||e.stop(),void r.warn(`pubTiny failed -> id: ${t.getTrackId()}, msg: ${o.message}`)}a.addLocalTrack(new xe(t.getTag(),t.getUserId(),e,!0))}})),a.clearReTryExchangeTimer();const u=e.useMutilPeerC?[]:e.getSubscribedList(),l=yield rr(u,!1,a,e);s&&(l.pushOtherRooms=s);const R=yield new nr(c,l).execute(e,n);if(R.code!==exports.RCRTCCode.SUCCESS)return r.error(`publish failed -> roomId: ${d}, code: ${R.code}`),this._removePubFailedTracks(i,a),{code:R.code,tracks:_};const{sdp:C,resultCode:p,message:h}=R.data;if(p!==exports.RCRTCCode.SUCCESS)return r.error(`publish failed -> roomId: ${d}, code: ${p}, msg: ${h}`),this._removePubFailedTracks(i,a),{code:p,tracks:_};const T=yield a.setRemoteAnswer(C.sdp);return T!==exports.RCRTCCode.SUCCESS?{code:T,tracks:_}:Object.assign({},R,{tracks:_})}))}_mergePublishRes(o,i){return t(this,void 0,void 0,(function*(){const t=i.crtUserId,s=i.roomId;let n="";const a=[],c=i.getResourcesByUserId(t),d=[...c];let _=[];o.forEach((e=>{if(e.code!==exports.RCRTCCode.SUCCESS){const{tracks:t}=e;return void a.push({code:e.code,tracks:t})}const{publishList:t,urls:r,mcuPublishList:o}=e.data;n=null==r?void 0:r.liveUrl;t.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:i.getTrackState(et(e))},e))).forEach((e=>{const{isInclude:t,index:r}=((e,t)=>{let r=!1,o=0;for(let i=0;i<t.length;i++){const s=t[i];if(`${e.msid}_${e.mediaType}`==`${s.msid}_${s.mediaType}`){r=!0,o=i;break}}return{isInclude:r,index:o}})(e,d);t?d.splice(r,1,e):d.push(e)}));const s=(null==o?void 0:o.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))))||[];_=s}));const{publishedList:u}=it(c,d),l=yield i.context.setRTCTotalRes(s,We(Tt.PUBLISH,u),Ye(d),Tt.TOTAL_CONTENT_RESOURCE,Ye(_));if(l!==e.ErrorCode.SUCCESS)return r.error(`send publish streams notification failed: ${l}`),{code:exports.RCRTCCode.SIGNAL_ERROR};i.setResourcesByUserId(t,d);const R=u.map((e=>et(e)));i.polarisReport&&i.polarisReport.sendR2(wt.PUBLISH,Ft.BEGIN,R),u.forEach((e=>{const t=i.useMutilPeerC?`${s}_${e.msid.split("_")[1]}`:`${s}_pub`,{pc:r}=i.peerMgr.getPCItemByPCName(t);r.getLocalTrack(`${e.msid}_${e.mediaType}`).__innerSetPublished(!0)})),r.debug(`publish success: ${R.join(",")}`);const C={code:exports.RCRTCCode.SUCCESS};return n&&(C.liveUrl=n),a.length&&(C.failedTracks=a,C.code=exports.RCRTCCode.SOME_TRACKS_PUBLISH_FAILED),C}))}execute(o,n){return t(this,void 0,void 0,(function*(){const t=this.tracks,a=o.roomId;if(e.logger.info(i.L_ABSTRACT_ROOM_PUBLISH_T,{trackIds:t.map(ht)},{logSource:e.LogSource.RTC}),!e.validate("tracks",t,(()=>e.isArray(t)&&t.length>0&&t.every((e=>e instanceof Me||e.track instanceof Me))),!0))return r.warn(`publish failed, tracks is invalid -> roomId: ${a}`),e.logger.error(i.L_ABSTRACT_ROOM_PUBLISH_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};const c=[],{plist:d,pushOtherRooms:_}=this.pubhook(t);for(let e=0;e<d.length;e++){const t=d[e];c.push(this.__publish(o,t,t.tracks,_,n))}const u=yield Promise.all(c),l=yield this._mergePublishRes(u,o);return e.logger.info(i.L_ABSTRACT_ROOM_PUBLISH_R,{status:s.SUCCESSED,roomId:a,trackIds:t.map(ht)},{logSource:e.LogSource.RTC}),l}))}}class Cr extends Qt{constructor(e,t){super(),this.tracks=e,this.unpubhook=t}__unpublish(e,o,i,s){return t(this,void 0,void 0,(function*(){const{pcName:t,pc:n}=i;e.roomId;const a=s.map((e=>e.getTrackId()));if(0===a.map(e.getPublishedResourceByTrackId.bind(e)).filter((e=>!!e)).length)return{code:exports.RCRTCCode.SUCCESS,tracks:s};a.forEach((e=>n.removeLocalTrackById(e))),e.polarisReport.sendR2(wt.PUBLISH,Ft.END,a),n.clearReTryExchangeTimer();const c=e.useMutilPeerC?[]:e.getSubscribedList(),d=yield rr(c,!1,n,e),{pushOtherRooms:_,headers:u}=this.unpubhook(s,t);_&&(d.pushOtherRooms=_);const l=yield new nr(u,d).execute(e,o);return l.code!==exports.RCRTCCode.SUCCESS?(r.error(`exchange failed -> code: ${l.code}`),{code:l.code,tracks:s}):Object.assign({},l,{tracks:s})}))}_mergeUnpublishRes(o,i){return t(this,void 0,void 0,(function*(){const s=o.context.getCurrentId(),n=o.roomId,a=[],c=[],d=[],_=[];let u=[];for(let e=0;e<i.length;e++){const t=i[e];if(t.code!==exports.RCRTCCode.SUCCESS){const{tracks:e}=t;c.push({code:t.code,tracks:e});continue}const{resultCode:s,message:n,mcuPublishList:l}=t.data;s!==exports.RCRTCCode.SUCCESS&&r.error(`unpublish streams failed -> code: ${s}, msg: ${n}`);const R=t.tracks.map((e=>e.getTrackId()));_.push(...R);const C=R.map(o.getPublishedResourceByTrackId.bind(o)).filter((e=>!!e));d.push(...C),a.push(t);const p=l?l.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[];u=p}const l=o.getResourcesByUserId(s).filter((e=>!d.includes(e))),R=yield o.context.setRTCTotalRes(n,We(Tt.UNPUBLISH,d),Ye(l),Tt.TOTAL_CONTENT_RESOURCE,Ye(u));if(R!==e.ErrorCode.SUCCESS)return r.error("send unpublish notification failed:",R),{code:exports.RCRTCCode.SIGNAL_ERROR};r.debug(`unpublish success -> tracks: ${_.join(",")}`),a.forEach((e=>t(this,void 0,void 0,(function*(){const{sdp:t}=e.data,{tracks:r}=e,i=o.peerMgr.getPCByTrackId(r[0].getTrackId());yield i.setRemoteAnswer(t.sdp)})))),o.setResourcesByUserId(s,l);const C={code:exports.RCRTCCode.SUCCESS};return c.length&&(C.failedTracks=c,C.code=exports.RCRTCCode.SOME_TRACKS_PUBLISH_FAILED),C}))}execute(o,n){return t(this,void 0,void 0,(function*(){const{crtUserId:t,roomId:a}=o,c=this.tracks;e.logger.info(i.L_ABSTRACT_ROOM_UNPUBLISH_T,{trackIds:c.map(ht)},{logSource:e.LogSource.RTC});if(!e.validate("tracks",c,(()=>c.every((e=>e.getUserId()===t&&e instanceof Me))),!0))return r.warn(`unpublish failed, tracks is invalid -> roomId: ${a}, tracks: ${c.map(ht)}`),e.logger.error(i.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};const d=o.peerMgr.createPeerCList(c),_=[];for(let e=0;e<d.length;e++){const{tracks:t}=d[e];_.push(this.__unpublish(o,n,d[e],t))}const u=yield Promise.all(_),l=yield this._mergeUnpublishRes(o,u);return e.logger.info(i.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:s.SUCCESSED,roomId:a,trackIds:c.map(ht)},{logSource:e.LogSource.RTC}),l}))}}class pr extends Qt{constructor(e){super(),this.localTrack=e}execute(o,i){return t(this,void 0,void 0,(function*(){const{localTrack:t}=this,i=t.getTrackId(),{crtUserId:s,roomId:n}=o,a=[{resourceId:i,enabled:!t.isLocalMuted()}],c=o.getResourcesByUserId(s),d=[];for(let e=0;e<c.length;e+=1){const t=c[e],r=et(t),o=a.findIndex((e=>e.resourceId===r));if(o>=0){const{enabled:e}=a[o];t.state=e?1:0,d.push(t);break}}const _=yield o.context.setRTCTotalRes(n,We(Tt.MODIFY,d),Ye(c),Tt.TOTAL_CONTENT_RESOURCE);_!==e.ErrorCode.SUCCESS&&r.error("notice `track.enabled` change failed -> code: "+_)}))}}class hr extends Qt{constructor(e,t,r){super(),this.pcName=e,this.isPub=t,this.retryHook=r}get priority(){return Vt.HIGH}execute(e,o){return t(this,void 0,void 0,(function*(){const{pcName:t,isPub:i}=this,{useMutilPeerC:s}=e,{pc:n}=e.peerMgr.getPCItemByPCName(t),a=i&&s?[]:e.getSubscribedList(),c=yield rr(a,!0,n,e),{pushOtherRooms:d,headers:_}=this.retryHook(t);d&&(c.pushOtherRooms=d);const u=yield new nr(_,c).execute(e,o);if(u.code!==exports.RCRTCCode.SUCCESS)return void r.error(`reTryExchange failed: ${u.code}, pcName: ${t}`);const{sdp:l,resultCode:R}=u.data;R===exports.RCRTCCode.SUCCESS?(n.clearReTryExchangeTimer(),yield n.setRemoteAnswer(l.sdp)):r.error(`reTryExchange failed: ${R}, pcName: ${t}`)}))}}class Tr extends Qt{constructor(e,t,r){super(),this.subhook=e,this.callbacks=t,this.livingType=r}get priority(){return Vt.HIGH}execute(o,n){return t(this,void 0,void 0,(function*(){const{livingType:t}=this,{roomId:a,crtUserId:c,roomMode:d}=o;e.logger.info(i.L_ABSTRACT_ROOM_RECONNECTED_T,{livingType:t},{logSource:e.LogSource.RTC});if(o.peerMgr.getPCList().some((e=>"closed"===e.getRTCPeerConn().connectionState)))return r.warn("RTCPeerConnection closed. Please rejoin room to restore services."),e.logger.error(i.L_ABSTRACT_ROOM_RECONNECTED_R,{status:s.FAILED,code:"",msg:"RTCPeerConnection disconnected"},{logSource:e.LogSource.RTC}),void this.callbacks.onPeerClosed();const{code:_,data:u}=yield o.context.joinRTCRoom(a,d,t);if(_!==e.ErrorCode.SUCCESS)return r.error(`RTC __onReconnected getRTCRoomInfo failed: ${_}`),void e.logger.error(i.L_ABSTRACT_ROOM_RECONNECTED_R,{status:s.FAILED,code:_,msg:""},{logSource:e.LogSource.RTC});r.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(u)}`);const l=[],R={},C={},p={},h=pt(u,a),T=Object.keys(h),g=o.getAllUserIds();for(let e=T.length-1;e>=0;e-=1){const t=T[e],r=g.indexOf(t);if(-1===r){l.push(t),R[t]=ot(h[t]);continue}const i=o.getResourcesByUserId(t),s=h[t],{publishedList:n,modifiedList:a,unpublishedList:c}=it(i,s,!0);R[t]=ot(n),C[t]=ot(c),p[t]=ot(a),g.splice(r,1)}g.length&&g.forEach((e=>{o.removeResourcesByUserId(e)})),o.assignRoomData(h),g.length&&this.callbacks.onUserLeave(g),l.length&&this.callbacks.onUserJoin(l);for(const e in C){if(e===c)continue;const t=C[e];if(t.length){const e=t.map((e=>o.getRemoteTrack(et(e))));yield new _r(this.subhook,e,this.callbacks.onTrackUnpublish).execute(o,n)}}return Object.keys(R).forEach((e=>{const t=R[e];if(0===t.length)return;const r=t.map((e=>{const t=et(e),{userId:r,tag:i,mediaType:s}=tt(t),n=s===exports.RCMediaType.AUDIO_ONLY?new je(i,r):new Je(i,r);return o.addRemoteTrack(n),n.__innerSetRemoteMuted(0===e.state),n}));this.callbacks.onTrackPublish(r)})),Object.keys(p).forEach((e=>{p[e].forEach((e=>{const t=et(e),r=o.getRemoteTrack(t);r.__innerSetRemoteMuted(0===e.state),r.isAudioTrack()?this.callbacks.onAudioMuteChange(r):this.callbacks.onVideoMuteChange(r)}))})),o.roomMode===e.RTCMode.LIVE&&this.executeInLivingRoom(o,u),e.logger.info(i.L_ABSTRACT_ROOM_RECONNECTED_R,{status:s.SUCCESSED,roomData:u},{logSource:e.LogSource.RTC}),{data:u}}))}executeInLivingRoom(t,r){var o,n;if(e.logger.error(i.L_LIVING_ROOM_RECONNECTED_T,{roomData:r},{logSource:e.LogSource.RTC}),!r)return void e.logger.info(i.L_LIVING_ROOM_RECONNECTED_R,{status:s.FAILED,code:"",msg:"room not fond"},{logSource:e.LogSource.RTC});const a=null===(o=r.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===o?void 0:o.value;if(!a)return void e.logger.error(i.L_LIVING_ROOM_RECONNECTED_R,{status:s.FAILED,code:"",msg:"cdn_uris not found"},{logSource:e.LogSource.RTC});const c=JSON.parse(a),d=(null===(n=t.getCDNUris())||void 0===n?void 0:n.enableInnerCDN)!==c.enableInnerCDN;t.setCDNUris(c),e.logger.info(i.L_LIVING_ROOM_RECONNECTED_R,{status:s.SUCCESSED,roomData:r},{logSource:e.LogSource.RTC}),d&&this.callbacks.onCDNEnableChange(c.enableInnerCDN)}}const gr="evt-leave";class mr extends e.EventEmitter{constructor(e,t,r,o,i,s,n,a,c,d=St()){super(),this._context=e,this._runtime=t,this._roomId=r,this._service=i,this._initOptions=s,this._useMutilPeerC=c,this._clientSessionId=d,this._appListener=null,this._reportListener=null,this._onRecvPKMsg=null,this._polarisReport=new Yt(this._context,this._runtime,this._roomId,this),this._peerCManager=new zt(this._useMutilPeerC,this._roomId,this._reTryExchange.bind(this),this._context.getCurrentId(),this._polarisReport),this._invoker=new Xt(this._context,this._service,this._peerCManager,r,this._context.getCurrentId(),o,this._polarisReport,n,a),this._store=this._invoker.store}__innerInit(e,r,o,i,s){return t(this,void 0,void 0,(function*(){const{code:t,data:n}=yield this._invoker.push(new tr(this._roomId,e,r,o,i,s));return t!==exports.RCRTCCode.SUCCESS?{code:t}:(this._initWithRoomData(n.offlineKickTime),{code:t,data:n})}))}_initWithRoomData(e){var t;this._pinger=new mt(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(t,o,i){if(this._useMutilPeerC)return void r.error("`RCAbstractRoom.setBitrate` is disabled, use `RCLocalTrack.setBitrate` instead.");r.warn("`RCAbstractRoom.setBitrate` will be deprecated, use `RCLocalTrack.setBitrate` instead."),e.assert("max",t,(t=>e.isNumber(t)&&t>Math.max(o||1,200)),!0),e.assert("min",o,(r=>e.isNumber(r)&&r>=1&&(!e.isNumber(t)||r<t)),!0),e.assert("start",i,(r=>e.isNumber(r)&&r>o&&r<=t));this._peerCManager.getPCList().forEach((e=>{e.setBitrate(t,o,i)}))}_onTrackReady(e){const t=e.streams[0].id,o=e.receiver.track,i=[t,"audio"===o.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY].join("_"),s=this._store.getRemoteTrack(i);s?(s.__innerSetMediaStreamTrack(o),this._callAppListener("onTrackReady",s)):r.warn(`cannot found remote track ${o.id}`)}_callAppListener(t,...o){var n;"onPing"!==t&&e.logger.info(i.L_ABSTRACT_ROOM_CALL_APP_LISTENER_O,{status:s.SUCCESSED,eventType:t,attrs:o},{logSource:e.LogSource.RTC}),"onPing"!==t&&r.info(`${t} callback ->`,...o);const a=null===(n=this._appListener)||void 0===n?void 0:n[t];if(a)try{a(...o)}catch(e){r.error(e)}}_onTrackUnpublish(e){this._callAppListener("onTrackUnpublish",e)}__parseInnerMessage(t){const{targetId:o,conversationType:i}=t;if(i!==e.ConversationType.RTC_ROOM)return!1;if(o!==this._roomId)return!0;r.info(`recv inner msg -> message: ${JSON.stringify(t)} | roomid: ${this._roomId}`);const s=t.content;switch(t.messageType){case Tt.KICK:this._kickoff(!0,s);break;case Tt.STATE:this._stateHandle(s);break;case Tt.MODIFY:case Tt.PUBLISH:case Tt.UNPUBLISH:case Tt.TOTAL_CONTENT_RESOURCE:this._resourceHandle(s,t.messageType,t.senderUserId);break;case Tt.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",t.messageType,t.content);break;case Tt.USER_NOTIFY:r.warn(`TODO: ${Tt.USER_NOTIFY}`);break;case Tt.PK_INVITE:case Tt.PK_CANCEL_INVITE:case Tt.PK_INVITE_TIMEOUT:case Tt.PK_INVITE_ANSWER:case Tt.PK_END:this._onRecvPKMsg&&this._onRecvPKMsg(t);break;case Tt.OTHER_ROOM_OFFLINE:break;default:this._callAppListener("onMessageReceive",t.messageType,t.content,t.senderUserId,t.messageUId)}return!0}_kickoff(e,o){return t(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;let t,i;r.warn(`onKickOff -> byServer: ${e}`),this.emit(gr),this._leaveHandle(!e),e&&((null==o?void 0:o.users)||[]).forEach((e=>{e.userId===this._context.getCurrentId()&&(i=e.type,t=e.kickExtra)})),this._callAppListener("onKickOff",e,i,t)}))}_rtcpeerClosed(){this.emit(gr),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,r,o){return t(this,void 0,void 0,(function*(){const{uris:t,ignore:i}=e;!i&&t&&this._invoker.push(new lr(e,r,o,this._subhook.bind(this),{onAudioMute:this._onAudioMuteChange.bind(this),onVideoMute:this._onVideoMuteChange.bind(this),onTrackPublish:this._onTrackPublish.bind(this),onTrackUnublish:this._onTrackUnpublish.bind(this),onCDNEnableChange:this._callAppListener.bind(this,"onCDNEnableChange")}))}))}_onTrackPublish(e){this._callAppListener("onTrackPublish",e)}_stateHandle(e){var r;return t(this,void 0,void 0,(function*(){const{left:t,joined:o,upgrade:i,downgrade:s}=yield this._invoker.push(new dr(e,this._subhook.bind(this)));if(null===(r=this._appListener)||void 0===r?void 0:r.onSwitchRole)return i.length&&i.forEach((e=>this._callAppListener("onSwitchRole",e,exports.RCRTCLiveRole.ANCHOR))),s.length&&s.forEach((e=>this._callAppListener("onSwitchRole",e,exports.RCRTCLiveRole.AUDIENCE))),o.length&&this._callAppListener("onUserJoin",o),void(t.length&&this._callAppListener("onUserLeave",t));const n=[...o,...i],a=[...t,...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(o,n){return t(this,void 0,void 0,(function*(){e.logger.info(i.L_ABSTRACT_ROOM_SEND_MESSAGE_T,{name:o,content:n},{logSource:e.LogSource.RTC});const{code:t}=yield this._context.sendMessage(e.ConversationType.RTC_ROOM,this._roomId,{messageType:o,content:n,isStatusMessage:!0});return t!==e.ErrorCode.SUCCESS?(r.error(`send message failed -> code: ${t}`),e.logger.error(i.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:s.FAILED,code:t,msg:""},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_ERROR}):(e.logger.info(i.L_ABSTRACT_ROOM_SEND_MESSAGE_R,{status:s.SUCCESSED,name:o,content:n},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}setRoomAttribute(o,n,a,c=!1){return t(this,void 0,void 0,(function*(){e.logger.info(i.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_T,{roomId:this._roomId,key:o,value:n,message:a,isInner:c},{logSource:e.LogSource.RTC});const t=yield this._context.setRTCData(this._roomId,o,n,c,e.RTCApiType.ROOM,a);return t!==e.ErrorCode.SUCCESS?(r.error(`SetRoomAttributeValue Failed: ${t}`),e.logger.error(i.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:s.FAILED,code:t,msg:""},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_ERROR}):(e.logger.info(i.L_ABSTRACT_ROOM_SET_ROOM_ATTRIBUTE_R,{status:s.SUCCESSED,roomId:this._roomId,key:o,value:n,message:a,isInner:c},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}deleteRoomAttributes(o,n,a=!1){return t(this,void 0,void 0,(function*(){e.logger.info(i.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_T,{roomId:this._roomId,keys:o,message:n,isInner:a},{logSource:e.LogSource.RTC});const t=yield this._context.removeRTCData(this._roomId,o,a,e.RTCApiType.ROOM,n);return t!==e.ErrorCode.SUCCESS?(r.error(`DeleteRoomAttribute Failed: ${t}`),e.logger.error(i.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:s.FAILED,code:t,msg:""},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_ERROR}):(e.logger.info(i.L_ABSTRACT_ROOM_DELETE_ROOM_ATTRIBUTE_R,{status:s.SUCCESSED,roomId:this._roomId,keys:o,message:n,isInner:a},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}getRoomAttributes(o=[],i=!1){return t(this,void 0,void 0,(function*(){const{code:t,data:s}=yield this._context.getRTCData(this._roomId,o,i,e.RTCApiType.ROOM);return t!==e.ErrorCode.SUCCESS?(r.error(`GetRoomAttributes Failed: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):{code:exports.RCRTCCode.SUCCESS,data:s}}))}_setUserAttributeValue(t,r,o){return this._context.setRTCData(this._roomId,t,r,!1,e.RTCApiType.PERSON,o)}_deleteUserAttributes(t,r){return this._context.removeRTCData(this._roomId,t,!1,e.RTCApiType.PERSON,r)}_getUserAttributes(t){return this._context.getRTCData(this._roomId,t,!1,e.RTCApiType.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 r;return t(this,void 0,void 0,(function*(){if(this._invoker.isDestroyed())return;this._invoker.destroy(),this._muteRemoteTracksBeforeQuit(),this._muteRemoteTracksBeforeQuit(),null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),e&&(yield this._context.quitRTCRoom(this._roomId)),this._store.isMainRoom&&(yield this._quitAllPKRoom()),this._pinger.stop();const t=[];Object.keys(this._peerCManager.getMutilPeerCData()).forEach((e=>{t.push(this._service.exit(this._getRTCReqestHeaders(e)))})),yield Promise.all(t),this._releasePCManager(),this._polarisReport=null}))}_releasePCManager(){const e=this._peerCManager.getPCList();null==e||e.forEach((e=>{e.off(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Me.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)})),this._peerCManager.clear(),this._peerCManager=null}_onLocalTrackDestroied(e){e instanceof xe&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(e){return t(this,void 0,void 0,(function*(){this._invoker.push(new pr(e))}))}publish(e){return t(this,void 0,void 0,(function*(){return this._invoker.push(new Rr(e,this._pubhook.bind(this)))}))}_getPushOtherRoomsParams(){return[]}_reTryExchange(e,r){return t(this,void 0,void 0,(function*(){this._invoker.push(new hr(e,r,(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 t(this,void 0,void 0,(function*(){return this._invoker.push(new Cr(e,((e,t)=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(t)}))))}))}_getResourceById(e){return this._store.getPublishedResourceByTrackId(e)}_isValidResourceId(e){var t;const{userId:r}=tt(e);return!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>et(t)===e)))}_subhook(e){const{pc:t,pcName:r}=this._peerCManager.createPeerCList(e)[0];return t.on(Wt.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),t.__reportR3R4ToPolaris(),t.registerReportListener(this._reportListener),t.clearReTryExchangeTimer(),{pc:t,pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(r)}}_pubhook(e){return{plist:this._peerCManager.createPeerCList(e).map((e=>{const{pc:t,pcName:r}=e;return t.on(Me.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),t.on(Me.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),t.registerReportListener(this._reportListener),t.__reportR3R4ToPolaris(),Object.assign(Object.assign({},e),{headers:this._getRTCReqestHeaders(r)})})),pushOtherRooms:this._getPushOtherRoomsParams()}}subscribe(e){return t(this,void 0,void 0,(function*(){return this._invoker.push(new ur(e,this._subhook.bind(this),!1))}))}unsubscribe(e){return t(this,void 0,void 0,(function*(){return this._invoker.push(new cr(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 t(this,void 0,void 0,(function*(){return this._invoker.push(new ar(e,this._subhook.bind(this),!1))}))}registerRoomEventListener(t){e.logger.info(i.L_ABSTRACT_ROOM_REGISTER_ROOM_EVENT_LISTENER_O,{status:s.SUCCESSED,listener:t&&Object.keys(t)},{logSource:e.LogSource.RTC}),this._appListener=t}registerReportListener(t){e.logger.info(i.L_ABSTRACT_ROOM_REGISTER_REPORT_LISTENER_O,{status:s.SUCCESSED,listener:t&&Object.keys(t)},{logSource:e.LogSource.RTC}),this._reportListener=t}onAudioLevelChange(t,r){var o;e.logger.info(i.L_ABSTRACT_ROOM_AUDIO_LEVEL_O,{status:s.SUCCESSED,handler:null==t?void 0:t.name,gap:r},{logSource:e.LogSource.RTC}),null===(o=this._audioLevelReport)||void 0===o||o.clearAudioLevelReportTimer(),this._audioLevelReport=new qt(this),this._audioLevelReport.onAudioLevelChange(t,r||1e3)}__onReconnected(e){return t(this,void 0,void 0,(function*(){return this._invoker.push(new Tr(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 Sr extends Qt{constructor(e,t){super(),this.data=e,this.cdnValues=t}execute(e,o){var i,s,n,a;return t(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:o,res:c}=yield e.service.setMcuConfig(t,this.data);if(o!==exports.RCRTCCode.SUCCESS)return r.error(`set MCU config failed: ${o}`),{code:o};r.info("set MCU config success"),c.pull_url&&e.setCDNUris(JSON.parse(c.pull_url));const d=this.cdnValues;return o===exports.RCRTCCode.SUCCESS&&((null===(s=null===(i=d.output)||void 0===i?void 0:i.video.normal)||void 0===s?void 0:s.width)||(null===(a=null===(n=d.output)||void 0===n?void 0:n.video.normal)||void 0===a?void 0:a.fps))&&sr(e),{code:o,res:c}}))}}var Er,Ir,fr,Lr;exports.BackgroundPictureFillMode=void 0,(Er=exports.BackgroundPictureFillMode||(exports.BackgroundPictureFillMode={}))[Er.CROP=1]="CROP",Er[Er.WHOLE=2]="WHOLE",exports.MixLayoutMode=void 0,(Ir=exports.MixLayoutMode||(exports.MixLayoutMode={}))[Ir.CUSTOMIZE=1]="CUSTOMIZE",Ir[Ir.SUSPENSION=2]="SUSPENSION",Ir[Ir.ADAPTATION=3]="ADAPTATION",exports.MixVideoRenderMode=void 0,(fr=exports.MixVideoRenderMode||(exports.MixVideoRenderMode={}))[fr.CROP=1]="CROP",fr[fr.WHOLE=2]="WHOLE",function(e){e[e.AUDIO_VIDEO_ALL=0]="AUDIO_VIDEO_ALL",e[e.AUDIO_VIDEO_NO=1]="AUDIO_VIDEO_NO",e[e.AUDIO_ALL_VIDEO_NO=2]="AUDIO_ALL_VIDEO_NO",e[e.AUDIO_NO_VIDEO_ALL=3]="AUDIO_NO_VIDEO_ALL",e[e.AUDIO_VIDEO_INPUT=4]="AUDIO_VIDEO_INPUT",e[e.AUDIO_ALL_VIDEO_INPUT=5]="AUDIO_ALL_VIDEO_INPUT",e[e.AUDIO_NO_VIDEO_INPUT=6]="AUDIO_NO_VIDEO_INPUT",e[e.AUDIO_INPUT_VIDEO_ALL=7]="AUDIO_INPUT_VIDEO_ALL",e[e.AUDIO_INPUT_VIDEO_NO=8]="AUDIO_INPUT_VIDEO_NO",e[e.ROOM_AUDIO_VIDEO_APPEND=9]="ROOM_AUDIO_VIDEO_APPEND",e[e.ROOM_AUDIO_VIDEO_NOT_APPEND=10]="ROOM_AUDIO_VIDEO_NOT_APPEND",e[e.ROOM_AUDIO_APPEND=11]="ROOM_AUDIO_APPEND",e[e.ROOM_AUDIO_NOT_APPEND=12]="ROOM_AUDIO_NOT_APPEND",e[e.ROOM_VIDEO_APPEND=13]="ROOM_VIDEO_APPEND",e[e.ROOM_VIDEO_NOT_APPEND=14]="ROOM_VIDEO_NOT_APPEND"}(Lr||(Lr={}));const Or=()=>({version:2,mode:exports.MixLayoutMode.SUSPENSION});class vr{constructor(e,t){this._invoker=e,this._isValidTrackId=t,this._values=Or()}setHostVideoTrack(t){if(r.info(`setHostVideoTrack -> videoTrackId: ${t}`),!this._isValidTrackId(t))return r.error(`setHostVideoTrack failed -> videoTrackId is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:s.FAILED,code:"",msg:"params error -> videoTrackId"},{logSource:e.LogSource.RTC}),this;const{mediaType:o,tag:n,userId:a}=tt(t);return o!==exports.RCMediaType.VIDEO_ONLY?(r.error(`setHostVideoTrack failed -> kind of resource is not 'video' -> ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:s.FAILED,code:"",msg:"not video"},{logSource:e.LogSource.RTC}),this):(this._values.host_stream_id=rt(a,n),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_HOST_VIDEO_TRACK_O,{status:s.SUCCESSED,videoTrackId:t},{logSource:e.LogSource.RTC}),this)}setMixLayoutMode(t){r.info(`setMixLayoutMode -> mode: ${t}`);return[exports.MixLayoutMode.CUSTOMIZE,exports.MixLayoutMode.SUSPENSION,exports.MixLayoutMode.ADAPTATION].includes(t)?(this._values.mode=t,e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:s.SUCCESSED,mode:t},{logSource:e.LogSource.RTC}),this):(r.error(`setMixLayoutMode failed -> mode is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_MIX_LAYOUT_MODE_O,{status:s.SUCCESSED,code:"",msg:`params error -> mode: ${t}`},{logSource:e.LogSource.RTC}),this)}_addOutputValue(e,t,r="normal"){const o=this._values.output||(this._values.output={video:{normal:{width:640,height:480}}});if("cdn"===e)return void(o.cdn=t);if("audio"===e)return void(o.audio={bitrate:t});const i=o.video;if("normal"!==r&&"tiny"!==r)if("backgroundColor"!==r)if("exparams"!==r){if("backgroundPicture"===r){const e=i.backgroundPicture||(i.backgroundPicture={fillMode:exports.BackgroundPictureFillMode.CROP,picture:[]});Object.assign(e,t)}}else i.exparams={renderMode:t};else i.backgroundColor=t;else{const e=i[r]||(i[r]={});Object.assign(e,t)}}setOutputVideoResolution(t){if(r.info(`setOutputVideoResolution -> resolution: ${t}`),!at(t))return r.error(`setOutputVideoResolution failed -> resolution is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:s.FAILED,code:"",msg:`params error -> resolution: ${t}`},{logSource:e.LogSource.RTC}),this;const{width:o,height:n}=nt(t);return this._addOutputValue("video",{width:o,height:n},"normal"),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RESOLUTION_O,{status:s.SUCCESSED,resolution:t},{logSource:e.LogSource.RTC}),this}setOutputVideoFPS(t){if(r.info(`setOutputVideoFPS -> fps: ${t}`),!ct(t))return r.error(`setOutputVideoFPS failed -> fps is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:s.FAILED,code:"",msg:`params error -> fps: ${t}`},{logSource:e.LogSource.RTC}),this;const o=dt(t);return this._addOutputValue("video",{fps:o},"normal"),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_FPS_O,{status:s.SUCCESSED,fps:t},{logSource:e.LogSource.RTC}),this}setOutputVideoBitrate(t){return r.info(`setOutputVideoBitrate -> bitrate: ${t}`),!e.isNumber(t)||t<=0?(r.error(`setOutputVideoBitrate failed -> bitrate is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:s.FAILED,code:"",msg:`params error -> bitrate: ${t}`},{logSource:e.LogSource.RTC})):this._addOutputValue("video",{bitrate:t},"normal"),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_BITRATE_O,{status:s.SUCCESSED,bitrate:t},{logSource:e.LogSource.RTC}),this}setOutputTinyVideoResolution(t){if(r.info(`setOutputTinyVideoResolution -> resolution: ${t}`),!at(t))return r.error(`setOutputTinyVideoResolution failed -> resolution is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:s.FAILED,code:"",msg:`params error -> resolution: ${t}`},{logSource:e.LogSource.RTC}),this;const{width:o,height:n}=nt(t);return this._addOutputValue("video",{width:o,height:n},"tiny"),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_RESOLUTION_O,{status:s.SUCCESSED,resolution:t},{logSource:e.LogSource.RTC}),this}setOutputTinyVideoFPS(t){if(r.info(`setOutputTinyVideoFPS -> fps: ${t}`),!ct(t))return r.error(`setOutputTinyVideoFPS failed -> fps is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:s.FAILED,code:"",msg:`params error -> fps: ${t}`},{logSource:e.LogSource.RTC}),this;const o=dt(t);return this._addOutputValue("video",{fps:o},"tiny"),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_FPS_O,{status:s.SUCCESSED,fps:t},{logSource:e.LogSource.RTC}),this}setOutputTinyVideoBitrate(t){return r.info(`setOutputTinyVideoBitrate -> bitrate: ${t}`),!e.isNumber(t)||t<=0?(r.error(`setOutputTinyVideoBitrate failed -> bitrate is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:s.FAILED,code:"",msg:`params error -> bitrate: ${t}`},{logSource:e.LogSource.RTC})):this._addOutputValue("video",{bitrate:t},"tiny"),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_TINY_VIDEO_BITRATE_O,{status:s.SUCCESSED,bitrate:t},{logSource:e.LogSource.RTC}),this}setOutputVideoRenderMode(t){return r.info(`setOutputVideoRenderMode -> renderMode: ${t}`),[exports.MixVideoRenderMode.CROP,exports.MixVideoRenderMode.WHOLE].includes(t)?this._addOutputValue("video",t,"exparams"):(r.error(`setOutputVideoRenderMode failed -> renderMode is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:s.FAILED,code:"",msg:`params error -> renderMode: ${t}`},{logSource:e.LogSource.RTC})),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_VIDEO_RENDER_MODE_O,{status:s.SUCCESSED,renderMode:t},{logSource:e.LogSource.RTC}),this}setOutputAudioBitrate(t){return r.info(`setOutputAudioBitrate -> bitrate: ${t}`),e.isNumber(t)&&t>0?this._addOutputValue("audio",t):(r.error(`setOutputAudioBitrate failed -> bitrate is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:s.FAILED,code:"",msg:`params error -> bitrate: ${t}`},{logSource:e.LogSource.RTC})),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_AUDIO_BITRATE_O,{status:s.SUCCESSED,bitrate:t},{logSource:e.LogSource.RTC}),this}setOutputBackgroundColor(t){return r.info(`setOutputBackgroundColor -> color: ${t}`),/^0x[a-fA-F0-9]{6}$/.test(t)?this._addOutputValue("video",t,"backgroundColor"):(r.error(`setOutputBackgroundColor failed -> color is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:s.FAILED,code:"",msg:`params error -> color: ${t}`},{logSource:e.LogSource.RTC})),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_COLOR_O,{status:s.SUCCESSED,color:t},{logSource:e.LogSource.RTC}),this}addOutputBackgroundPicture(t,o,n,a,c){var d,_,u;if(r.info(`addOutputBackgroundPicture -> uri: ${t}, x: ${o}, y: ${n}, w: ${a}, h: ${c}`),!e.isHttpUrl(t))return r.error(`addOutputBackgroundPicture failed -> uri is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:s.FAILED,code:"",msg:`params error -> uri: ${t}`},{logSource:e.LogSource.RTC}),this;if([o,n,a,c].some((t=>!e.isNumber(t)||t<0||t>1)))return r.error(`addOutputBackgroundPicture failed -> some attrs of (x, y, w, h) is invalid: ${o}, ${n}, ${a}, ${c}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:s.FAILED,code:"",msg:`params error -> x: ${o}, y: ${n}, w: ${a}, h: ${c}`},{logSource:e.LogSource.RTC}),this;const l=(null===(u=null===(_=null===(d=this._values.output)||void 0===d?void 0:d.video)||void 0===_?void 0:_.backgroundPicture)||void 0===u?void 0:u.picture)||[];return l.push({uri:t,w:a,h:c,x:o,y:n}),this._addOutputValue("video",{picture:l},"backgroundPicture"),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:s.SUCCESSED,uri:t,x:o,y:n,w:a,h:c},{logSource:e.LogSource.RTC}),this}removeOutputBackgroundPicture(t){var o,n,a;if(r.info(`removeOutputBackgroundPicture -> uri: ${t}`),!e.isHttpUrl(t))return r.error(`removeOutputBackgroundPicture failed -> uri is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:s.FAILED,code:"",msg:`params error -> uri: ${t}`},{logSource:e.LogSource.RTC}),this;let c=null===(a=null===(n=null===(o=this._values.output)||void 0===o?void 0:o.video)||void 0===n?void 0:n.backgroundPicture)||void 0===a?void 0:a.picture;return c&&(c=c.filter((e=>e.uri!==t)),this._addOutputValue("video",{pictures:c},"backgroundPicture")),e.logger.info(i.L_MCU_CONFIG_BUILDER_REMOVE_OUTPUT_BACKGROUND_PICTURE_O,{status:s.SUCCESSED,uri:t},{logSource:e.LogSource.RTC}),this}clearOutputBackgroundPicture(){return r.info("clearOutputBackgroundPicture ->"),this._addOutputValue("video",{pictures:[]},"backgroundPicture"),e.logger.info(i.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this}setOutputBackgroundPictureFillMode(t){return r.info(`setOutputBackgroundPictureFillMode -> fillMode: ${t}`),[exports.BackgroundPictureFillMode.CROP,exports.BackgroundPictureFillMode.WHOLE].includes(t)?this._addOutputValue("video",{fillMode:t},"backgroundPicture"):(r.error(`setOutputBackgroundPictureFillMode failed -> fillMode is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:s.FAILED,code:"",msg:`params error -> fillMode: ${t}`},{logSource:e.LogSource.RTC})),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:s.SUCCESSED,fillMode:t},{logSource:e.LogSource.RTC}),this}addPublishStreamUrls(t){var o,n;r.info(`addPublishStreamUrls -> urls: ${t.join(",")}`);const a=/^rtmp:\/\/.+/;if(!e.isArray(t)||0===t.length||t.some((e=>!a.test(e))))return r.error(`addPublishStreamUrls failed -> urls is invalid: ${t.join(",")}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:s.FAILED,code:"",msg:`params error -> urls: ${t.join(",")}`},{logSource:e.LogSource.RTC}),this;const c=(null===(n=null===(o=this._values.output)||void 0===o?void 0:o.cdn)||void 0===n?void 0:n.concat())||[];let d=!1;return t.forEach((e=>{c.some((t=>t.pushurl===e))||(d=!0,c.push({pushurl:e}))})),c.length>5?(r.error("addPublishStreamUrls failed -> publish stream urls no more than 5!"),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_FILL_MODE_O,{status:s.FAILED,code:"",msg:`params error -> publish stream urls no more than 5, length: ${t.length}`},{logSource:e.LogSource.RTC}),this):(d&&this._addOutputValue("cdn",c),e.logger.info(i.L_MCU_CONFIG_BUILDER_ADD_PUBLISH_STREAM_URLS_O,{status:s.SUCCESSED,urls:t},{logSource:e.LogSource.RTC}),this)}removePublishStreamUrls(t){var o,n;r.info(`removePublishStreamUrls -> urls: ${t.join(",")}`);const a=/^rtmp:\/\/.+/;if(!e.isArray(t)||0===t.length||t.some((e=>!a.test(e))))return r.error(`removePublishStreamUrls failed -> urls contain invalid items: ${t.join(",")}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:s.FAILED,code:"",msg:`params error -> urls: ${t.join(",")}`},{logSource:e.LogSource.RTC}),this;const c=(null===(n=null===(o=this._values.output)||void 0===o?void 0:o.cdn)||void 0===n?void 0:n.concat())||[];for(let e=c.length-1;e>=0;e-=1){const{pushurl:r}=c[e],o=t.indexOf(r);o>=0&&(t.splice(o,1),c.splice(e,1))}return this._addOutputValue("cdn",c),e.logger.info(i.L_MCU_CONFIG_BUILDER_REMOVE_PUBLISH_STREAM_URLS_O,{status:s.SUCCESSED,urls:t},{logSource:e.LogSource.RTC}),this}clearPublishStreamUrls(){return r.info("clearPublishStreamUrls ->"),this._addOutputValue("cdn",[]),e.logger.info(i.L_MCU_CONFIG_BUILDER_CLEAR_PUBLISH_STREAM_URLS_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this}addCustomizeLayoutVideo(t,o,n,a,c){if(r.info(`addCustomizeLayoutVideo -> trackId: ${t}, x: ${o}, y: ${n}, width: ${a}, height: ${c}`),!e.notEmptyString(t)||!this._isValidTrackId(t))return r.error(`addCustomizeLayoutVideo failed -> trackId is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.FAILED,code:"",msg:`params error -> trackId: ${t}`},{logSource:e.LogSource.RTC}),this;if(!e.isNumber(o)||!e.isNumber(n))return r.error(`addCustomizeLayoutVideo failed -> some attrs of (x, y) is invalid: ${o}, ${n}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.FAILED,code:"",msg:`params error -> x: ${o}, y: ${n}`},{logSource:e.LogSource.RTC}),this;if([a,c].some((t=>!e.isNumber(t)||t<0)))return r.error(`addCustomizeLayoutVideo failed -> some attrs of (width, height) is invalid: ${a}, ${c}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.FAILED,code:"",msg:`params error -> width: ${a}, height: ${c}`},{logSource:e.LogSource.RTC}),this;const{userId:d,tag:_,mediaType:u}=tt(t);if(u!==exports.RCMediaType.VIDEO_ONLY)return r.error(`addCustomizeLayoutVideo failed -> kind of trackId is not 'video': ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.FAILED,code:"",msg:`params error -> trackId: ${t}的资源不是视频`},{logSource:e.LogSource.RTC}),this;const l=rt(d,_),R=this._values.input||(this._values.input={}),C=R.video||(R.video=[]);return C.some((e=>e.height===c&&e.width===a&&e.stream_id===l&&e.user_id===d&&e.x===o&&e.y===n))?(e.logger.warn(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.FAILED,code:"",msg:"Duplicate configuration item ignored"},{logSource:e.LogSource.RTC}),this):(C.push({user_id:d,stream_id:l,x:o,y:n,width:a,height:c}),e.logger.info(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.SUCCESSED,trackId:t,x:o,y:n,width:a,height:c},{logSource:e.LogSource.RTC}),this)}removeCustomizeLayoutVideo(t){if(r.info(`clearCustomizeInputAudio -> trackId: ${t}`),!this._isValidTrackId(t))return r.error(`clearCustomizeInputAudio failed -> trackId is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.FAILED,code:"",msg:`params error -> trackId: ${t}`},{logSource:e.LogSource.RTC}),this;const{userId:o,tag:n,mediaType:a}=tt(t);if(a!==exports.RCMediaType.VIDEO_ONLY)return r.error(`clearCustomizeInputAudio failed -> kind of trackId is not 'video': ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.FAILED,code:"",msg:`params error -> trackId: ${t}的资源不是视频`},{logSource:e.LogSource.RTC}),this;const c=rt(o,n),d=this._values.input;return(null==d?void 0:d.video)&&d.video.length>0&&(d.video=d.video.filter((e=>e.stream_id===c))),e.logger.info(i.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.SUCCESSED,trackId:t},{logSource:e.LogSource.RTC}),this}clearCustomizeLayoutVideo(){r.info("clearCustomizeLayoutVideo ->");const t=this._values.input;return null==t||delete t.video,e.logger.info(i.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_LAYOUT_VIDEO_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this}setCustomizeInputAudio(t){if(r.info(`setCustomizeInputAudio -> trackIds: ${t.join(",")}`),t.some((e=>this._isValidTrackId(e))))return r.warn(`setCustomizeInputAudio failed -> trackIds contain invalid items: $${t.join(",")}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:s.FAILED,code:"",msg:`params error -> trackIds: ${t.join(",")}`},{logSource:e.LogSource.RTC}),this;return(this._values.input||(this._values.input={})).audio=t.map((e=>{const{userId:t,tag:r}=tt(e);return{stream_id:rt(t,r),user_id:t}})),this._values.inputFilterMode=Lr.AUDIO_INPUT_VIDEO_ALL,e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_CUSTOMIZE_INPUT_AUDIO_O,{status:s.SUCCESSED,trackIds:t},{logSource:e.LogSource.RTC}),this}addCustomizeInputAudio(t){if(r.info(`addCustomizeInputAudio -> trackId: ${t}`),!this._isValidTrackId(t))return r.warn(`addCustomizeInputAudio failed -> trackId is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:s.FAILED,code:"",msg:`params error -> trackId: ${t}`},{logSource:e.LogSource.RTC}),this;const o=this._values.input||(this._values.input={}),n=o.audio||(o.audio=[]),{userId:a,tag:c}=tt(t),d=rt(a,c);return n.some((e=>e.stream_id===d&&e.user_id===a))?(e.logger.warn(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:s.FAILED,code:"",msg:`trackId:${t} is exist`},{logSource:e.LogSource.RTC}),this):(n.push({user_id:a,stream_id:d}),this._values.inputFilterMode=Lr.AUDIO_INPUT_VIDEO_ALL,e.logger.info(i.L_MCU_CONFIG_BUILDER_ADD_CUSTOMIZE_INPUT_AUDIO_O,{status:s.SUCCESSED,trackId:t},{logSource:e.LogSource.RTC}),this)}removeCustomizeInputAudio(t){if(r.info(`removeCustomizeInputAudio -> trackId: ${t}`),!this._isValidTrackId(t))return r.error(`removeCustomizeInputAudio failed -> trackId is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:s.FAILED,code:"",msg:`params error -> trackId: ${t}`},{logSource:e.LogSource.RTC}),this;const o=this._values.input;if(!(null==o?void 0:o.audio)||0===o.audio.length)return e.logger.error(i.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:s.FAILED,code:"",msg:"not audio"},{logSource:e.LogSource.RTC}),this;const{userId:n,tag:a}=tt(t),c=rt(n,a);return o.audio=o.audio.filter((e=>n!==e.user_id||c!==e.stream_id)),e.logger.info(i.L_MCU_CONFIG_BUILDER_REMOVE_CUSTOMIZE_INPUT_AUDIO_O,{status:s.SUCCESSED,trackId:t},{logSource:e.LogSource.RTC}),this}clearCustomizeInputAudio(){r.info("clearCustomizeInputAudio ->");const t=this._values.input;return(null==t?void 0:t.audio)&&delete t.audio,this._values.inputFilterMode=Lr.AUDIO_VIDEO_ALL,e.logger.info(i.L_MCU_CONFIG_BUILDER_CLEAR_CUSTOMIZE_INPUT_AUDIO_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this}addPictureWaterMark(t,o,n,a,c,d){if(r.info(`addPictureWaterMark -> trackId: ${t} uri: ${o}, x: ${n}, y: ${a}, w: ${c}, h: ${d}`),!this._isValidTrackId(t))return r.warn(`addPictureWaterMark failed -> trackId is invalid: ${t}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:s.FAILED,code:"",msg:`params error -> trackId: ${t}`},{logSource:e.LogSource.RTC}),this;if(!e.isHttpUrl(o))return r.error(`addPictureWaterMark failed -> uri is invalid: ${o}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:s.FAILED,code:"",msg:`params error -> uri: ${o}`},{logSource:e.LogSource.RTC}),this;if([n,a,c,d].some((t=>!e.isNumber(t)||t<0||t>1)))return r.error(`addPictureWaterMark failed -> some attrs of (x, y, w, h) is invalid: ${n}, ${a}, ${c}, ${d}`),e.logger.error(i.L_MCU_CONFIG_BUILDER_ADD_SINGLE_WATER_MARK_O,{status:s.FAILED,code:"",msg:`params error -> x: ${n}, y: ${a}, w: ${c}, h: ${d}`},{logSource:e.LogSource.RTC}),this;const{userId:_,tag:u}=tt(t),l=rt(_,u),R=(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen;r.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(R)}`);const C=R.filter((e=>e.streamId===l))[0];return r.info(`addPictureWaterMark target-> : ${C}`),C?C.picture.push({uri:o,w:c,h:d,x:n,y:a}):R.push({streamId:l,picture:[{uri:o,w:c,h:d,x:n,y:a}]}),r.info(`addPictureWaterMark singleScreen-> : ${JSON.stringify(R)}`),this._values.waterMark.singleScreen=R,r.info(`addPictureWaterMark this._values.waterMark.singleScreen-> : ${JSON.stringify(this._values.waterMark.singleScreen)}`),e.logger.info(i.L_MCU_CONFIG_BUILDER_SET_OUTPUT_BACKGROUND_PICTURE_O,{status:s.SUCCESSED,trackId:t,uri:o,x:n,y:a,w:c,h:d},{logSource:e.LogSource.RTC}),this}clearPictureWaterMark(){r.info("clearOutputBackgroundPicture ->");return(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen=[],e.logger.info(i.L_MCU_CONFIG_BUILDER_CLEAR_OUTPUT_BACKGROUND_PICTURE_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this}removePictureWaterMark(t,r){if(!e.notEmptyString(t)||!this._isValidTrackId(t))return e.logger.error(i.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O,{status:s.FAILED,code:"",msg:`params error -> trackId: ${t}`},{logSource:e.LogSource.RTC}),this;const{userId:o,tag:n}=tt(t),a=rt(o,n);return(this._values.waterMark||(this._values.waterMark={enable:"on",singleScreen:[]})).singleScreen.forEach((e=>{e.streamId===a&&(e.picture=e.picture.filter((e=>e.uri!==r)))})),e.logger.info(i.L_MCU_CONFIG_BUILDER_REMOVE_SINGLE_WATER_MARK_O,{status:s.SUCCESSED,trackId:t,uri:r},{logSource:e.LogSource.RTC}),this}reset(){return r.info("MCUConfigBuilder.reset ->"),this._values=Or(),e.logger.info(i.L_MCU_CONFIG_BUILDER_RESET_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this}flush(r=!0){return t(this,void 0,void 0,(function*(){const t=JSON.parse(JSON.stringify(this._values)),{code:o}=yield this._invoker.push(new Sr(t,this._values));return r&&(this._values=Or()),e.logger.info(i.L_MCU_CONFIG_BUILDER_FLUSH_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),{code:o}}))}__innerGetValues(){return JSON.parse(JSON.stringify(this._values))}}var Ar,Nr,Dr;exports.RCLivingType=void 0,(Ar=exports.RCLivingType||(exports.RCLivingType={}))[Ar.VIDEO=0]="VIDEO",Ar[Ar.AUDIO=1]="AUDIO",function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(Nr||(Nr={}));class kr extends Qt{constructor(e,t,r){super(),this.roomId=e,this.hooks=t,this.roomPKHandler=r}_exchangeWithPushOtherRoom(e,o){return t(this,void 0,void 0,(function*(){if(!e.getLocalTracks().length)return;const t=Object.values(e.peerMgr.getMutilPeerCData()),i=Object.keys(e.peerMgr.getMutilPeerCData());for(let s=0;s<t.length;s++){const{pc:n,isPub:a}=t[s],c=a&&e.useMutilPeerC?[]:e.getSubscribedList(),d=yield rr(c,!1,n,e),{pushOtherRooms:_,headers:u}=this.hooks(i[s]);d.pushOtherRooms=_;const l=yield new nr(u,d).execute(e,o);if(l.code!==exports.RCRTCCode.SUCCESS)return void r.error(`exchange with pushOtherRoom failed: ${l.code}`);const{sdp:R,resultCode:C}=l.data;if(C!==exports.RCRTCCode.SUCCESS)return void r.error(`exchange with pushOtherRoom failed: ${C}`);n.setRemoteAnswer(R.sdp)}}))}execute(o,n){return t(this,void 0,void 0,(function*(){const{roomId:t}=this;if(e.logger.info(i.L_LIVING_ROOM_JOINED_PK_ROOM_T,{roomId:t,userId:o.crtUserId},{logSource:e.LogSource.RTC}),!this.roomPKHandler)return void e.logger.error(i.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:s.FAILED,code:"",msg:"_roomPKHandler not exist"},{logSource:e.LogSource.RTC});const a=this.roomPKHandler.getPKInfo(t);if(!a)return r.warn(`exchange to update pushOtherRoom cancel, pkInfo lost -> roomId: ${t}`),void e.logger.error(i.L_LIVING_ROOM_JOINED_PK_ROOM_R,{status:s.FAILED,code:"",msg:"PKInfo not exist"},{logSource:e.LogSource.RTC});yield this._exchangeWithPushOtherRoom(o,n),e.logger.info(i.L_LIVING_ROOM_JOINED_PK_ROOM_T,{status:s.SUCCESSED,roomId:t,userId:o.crtUserId,PKInfo:a},{logSource:e.LogSource.RTC})}))}}class Pr extends Qt{constructor(e,t,r,o,i,s){super(),this.pkHandler=e,this.room=t,this._PKInfo=r,this.hooks=o,this._joinedPKRooms=i,this.isQuitPK=s}quitRoomPK(o,i){return t(this,void 0,void 0,(function*(){if(!this._PKInfo[o])return;const{inviterRoomId:t,inviteeRoomId:s,inviterUserId:n,inviteSessionId:a}=this._PKInfo[o],c={inviteeRoomId:s,inviterRoomId:t,userId:i.crtUserId},d={roomId:i.roomId,endRoomId:o,sessionId:a,content:JSON.stringify(c),keys:[`${t}|${n}`]};r.info(`quitRoomPK -> params: ${JSON.stringify(d)}`);const _=yield i.context.endRoomPK(d);return _!==e.ErrorCode.SUCCESS?(r.error(`quitRoomPK failed: ${_}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):(r.info("quitRoomPK success"),delete this._PKInfo[o],{code:exports.RCRTCCode.SUCCESS})}))}execute(o,n){return t(this,void 0,void 0,(function*(){const{room:t,isQuitPK:a}=this,c=t.getRoomId();return r.info(`leavePKRoom -> userId: ${o.crtUserId} , roomId: ${c}`),e.logger.info(i.L_LIVING_ROOM_LEAVE_PK_ROOM_T,{roomId:c,userId:o.crtUserId,isQuitPK:a},{logSource:e.LogSource.RTC}),yield t.__destroy(!0),delete this._joinedPKRooms[c],yield new kr(c,this.hooks,this.pkHandler).execute(o,n),a&&this.quitRoomPK(c,o),e.logger.info(i.L_LIVING_ROOM_LEAVE_PK_ROOM_R,{status:s.SUCCESSED,roomId:c,userId:o.crtUserId,isQuitPK:a},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS}}))}}class yr{constructor(e,t,r,o,i,s,n,a,c,d,_){this._invoker=e,this._PKInfo=t,this._hooks=r,this._context=o,this._runtime=i,this._service=s,this._initOptions=n,this._mainLivingRoom=a,this._registerPKMsgListener=c,this._onJoinedPKRoom=d,this._clientSessionId=_,this._inviteTimeout=30,this._appListener=null,this._joinedPKRooms={},this._registerPKMsgListener(this._onRecvPKMsg.bind(this)),this._mainRoomId=this._mainLivingRoom.getRoomId()}_callAppListener(e,...t){var o;r.info(`${e} callback ->`,...t);const i=null===(o=this._appListener)||void 0===o?void 0:o[e];if(i)try{i(...t)}catch(e){r.error(e)}}_onInvite(e){const t=e.inviteInfo||{},{inviterRoomId:r,inviterUserId:o,extra:i}=t,s={inviterRoomId:r,inviterUserId:o,extra:i};this._PKInfo[r]=t,this._callAppListener("onRequestJoinOtherRoom",s)}_onCancelInvite(e){const{inviterRoomId:t,inviterUserId:r,extra:o}=e.inviteInfo||{},i={inviterRoomId:t,inviterUserId:r,extra:o};delete this._PKInfo[t],this._callAppListener("onCancelRequestOtherRoom",i)}_onInviteTimeout(e){}_onInviteAnswer(e){const{answerCode:t,inviteContent:r}=e,{inviteSessionId:o,inviterUserId:i,inviterRoomId:s,inviteeUserId:n,inviterUserAutoMix:a,inviteeUserAutoMix:c,inviteeRoomId:d,extra:_}=r,u={agree:1===t,inviterRoomId:s,inviterUserId:i,inviteeRoomId:d,inviteeUserId:n,extra:_};this._PKInfo[d]=this._PKInfo[d]||{inviteSessionId:o,inviterRoomId:s,inviterUserId:i,inviterUserAutoMix:a,inviteeRoomId:d},this._PKInfo[d].inviteeUserAutoMix=c,this._callAppListener("onResponseJoinOtherRoom",u)}createLeaveOtherRoomCommand(e,t){return new Pr(this,e,this._PKInfo,this._hooks,this._joinedPKRooms,t)}_onPKEnd(e){return t(this,void 0,void 0,(function*(){const{inviteeRoomId:t,inviterRoomId:r,userId:o}=e.inviteInfo,i=r===this._mainRoomId?t:r,s={endRoomId:i,endUserId:o},n=this._joinedPKRooms[i];n&&(yield this._invoker.push(this.createLeaveOtherRoomCommand(n))),delete this._PKInfo[i],this._callAppListener("onFinishOtherRoom",s)}))}_onRecvPKMsg(e){const{targetId:t,content:r,messageType:o}=e;switch(o){case Tt.PK_INVITE:this._onInvite(r);break;case Tt.PK_CANCEL_INVITE:this._onCancelInvite(r);break;case Tt.PK_INVITE_TIMEOUT:this._onInviteTimeout(r);break;case Tt.PK_INVITE_ANSWER:this._onInviteAnswer(r);break;case Tt.PK_END:this._onPKEnd(r)}}registerRoomPKEventListener(t){e.logger.info(i.L_LIVING_PK_HANDLER_REGISTER_ROOM_PK_EVENT_LISTENER_O,{status:s.SUCCESSED,listener:t&&Object.keys(t)},{logSource:e.LogSource.RTC}),this._appListener=t}requestJoinOtherRoom(o,n,a){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:o,inviteeUserId:n,options:a},{logSource:e.LogSource.RTC}),!e.validate("inviteeRoomId",o,e.notEmptyString,!0)||!e.validate("inviteeUserId",n,e.notEmptyString,!0))return e.logger.error(i.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> inviteeRoomId 或 inviteeUserId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`requestRoomPK -> inviteeRoomId: ${o}; inviteeUserId: ${n}; options: ${JSON.stringify(a||{})}`);const t=St(),c=!e.isBoolean(null==a?void 0:a.autoMix)||(null==a?void 0:a.autoMix),d={inviteSessionId:t,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:c,inviteeRoomId:o,inviteeUserId:n,inviteeTimeoutTime:this._inviteTimeout,extra:(null==a?void 0:a.extra)||""},_={roomId:this._mainRoomId,invitedRoomId:o,invitedUserId:n,inviteTimeout:this._inviteTimeout,inviteInfo:JSON.stringify(d),inviteSessionId:t};r.info(`requestRoomPK -> params: ${JSON.stringify(_)}`);const u=yield this._context.requestRoomPK(_);return u!==e.ErrorCode.SUCCESS?(r.error(`requestRoomPK failed: ${u}`),e.logger.error(i.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:u,msg:""},{logSource:e.LogSource.RTC}),{code:u}):(r.info("requestRoomPK success"),this._PKInfo[o]={inviteSessionId:t,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:c,inviteeRoomId:o},e.logger.info(i.L_LIVING_PK_HANDLER_REQUEST_JOIN_OTHER_ROOM_R,{inviteeRoomId:o,inviteeUserId:n,options:a},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}cancelRequestJoinOtherRoom(o,n,a){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_T,{inviteeRoomId:o,inviteeUserId:n,extra:a,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:e.LogSource.RTC}),!e.validate("inviteeRoomId",o,e.notEmptyString,!0)||!e.validate("inviteeUserId",n,e.notEmptyString,!0))return e.logger.error(i.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> inviteeRoomId or inviteeUserId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(!this._PKInfo[o])return r.error(`The request to connect with ${n} user in room ${o} is not initiated`),e.logger.error(i.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:`The request to connect with ${n} user in room ${o} is not initiated`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`canceRequestJoinPK -> inviteeRoomId: ${o}; inviteeUserId: ${n}; extra: ${a}`);const t={inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviteeRoomId:o,inviteeUserId:n,extra:a||""},c={roomId:this._mainRoomId,invitedRoomId:o,invitedUserId:n,inviteSessionId:this._PKInfo[o].inviteSessionId,inviteInfo:JSON.stringify(t)};r.info(`canceRequestJoinPK -> params: ${JSON.stringify(c)}`);const d=yield this._context.cancelRoomPK(c);return d!==e.ErrorCode.SUCCESS?(r.error(`canceRequestJoinPK failed: ${d}`),e.logger.error(i.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:d,msg:`The request to connect with ${n} user in room ${o} is not initiated`},{logSource:e.LogSource.RTC}),{code:d}):(r.info("canceRequestJoinPK success"),e.logger.info(i.L_LIVING_PK_HANDLER_CANCEL_REQUEST_JOIN_OTHER_ROOM_R,{status:s.SUCCESSED,inviteeRoomId:o,inviteeUserId:n,extra:a},{logSource:e.LogSource.RTC}),delete this._PKInfo[o],{code:exports.RCRTCCode.SUCCESS})}))}responseJoinOtherRoom(o,n,a,c){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_T,{inviterRoomId:o,inviterUserId:n,agree:a,options:c,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:e.LogSource.RTC}),!e.validate("inviterRoomId",o,e.notEmptyString,!0)||!e.validate("inviterUserId",n,e.notEmptyString,!0))return e.logger.error(i.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> inviterRoomId or inviterUserId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(!this._PKInfo[o])return r.error(`User ${n} in room ${o} did not send a request for connection`),e.logger.error(i.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:`User ${n} in room ${o} did not send a request for connection`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`responseRoomPK -> inviterRoomId: ${o}; inviterUserId: ${n}; agree: ${a}; options: ${JSON.stringify(c||{})}`);const{inviteSessionId:t,inviterUserAutoMix:d}=this._PKInfo[o],_=!e.isBoolean(null==c?void 0:c.autoMix)||(null==c?void 0:c.autoMix),u={inviteSessionId:t,inviterRoomId:o,inviterUserId:n,inviterUserAutoMix:d,inviteeRoomId:this._mainRoomId,inviteeUserId:this._context.getCurrentId(),inviteeUserAutoMix:_},l=Object.assign(u,{inviterUserAutoMix:d}),R=a?Object.assign(u,{MultiRoomKey:`${o}|${this._mainRoomId}`,MultiRoomValue:JSON.stringify(l)}):u;!e.isUndefined(null==c?void 0:c.extra)&&Object.assign(R,{extra:c.extra});const C={agree:a,roomId:this._mainRoomId,inviteSessionId:t,inviteRoomId:o,inviteUserId:n,content:JSON.stringify(R),key:`${o}|${this._mainRoomId}`,value:JSON.stringify(u)};r.info(`responseRoomPK -> params: ${JSON.stringify(C)}`);const p=yield this._context.responseRoomPK(C);return p!==e.ErrorCode.SUCCESS?(r.error(`responseRoomPK failed: ${p}`),e.logger.error(i.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:p,msg:""},{logSource:e.LogSource.RTC}),{code:p}):(r.info("responseRoomPK success"),e.logger.info(i.L_LIVING_PK_HANDLER_RESPONSE_JOIN_OTHER_ROOM_R,{status:s.SUCCESSED,inviterRoomId:o,inviterUserId:n,agree:a,options:c,userId:this._context.getCurrentId(),roomId:this._mainRoomId},{logSource:e.LogSource.RTC}),this._PKInfo[o].inviteeUserAutoMix=_,{code:exports.RCRTCCode.SUCCESS})}))}joinOtherRoom(o){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_T,{roomId:o,userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),!e.validate("roomId",o,e.notEmptyString,!0))return e.logger.error(i.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> roomId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(this._context.getConnectionStatus()!==e.ConnectionStatus.CONNECTED)return e.logger.error(i.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.SIGNAL_DISCONNECTED,msg:"IM disconnected"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_DISCONNECTED};if(r.info(`JoinPKRoom, roomId: ${o}`),this._joinedPKRooms[o])return e.logger.warn(i.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const t=exports.RCLivingType.VIDEO,n={extra:`{"roomId": "${this._mainRoomId}"}`},a=new br(this._context,this._runtime,o,this._service,this._initOptions,t,!1,!1,!1,this._clientSessionId),{code:c,data:d}=yield a.__innerInit(e.RTCMode.LIVE,void 0,t,n);return c!==exports.RCRTCCode.SUCCESS?(r.error(`JoinPKRoom failed -> code: ${c}`),e.logger.error(i.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:s.FAILED,code:c,msg:""},{logSource:e.LogSource.RTC}),{code:c}):(r.info(`JoinPKRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${o}, data: ${JSON.stringify(d)}`),this._joinedPKRooms[o]=a,yield this._onJoinedPKRoom(o,a),e.logger.info(i.L_LIVING_PK_HANDLER_JOIN_OTHER_ROOM_R,{status:s.SUCCESSED,roomId:o,userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),{room:a,code:exports.RCRTCCode.SUCCESS,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()})}))}leaveOtherRoom(e,r){return t(this,void 0,void 0,(function*(){return this._invoker.push(this.createLeaveOtherRoomCommand(e,r))}))}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"}(Dr||(Dr={}));class Ur extends Qt{constructor(e,t){super(),this.cdnValues=e,this.enable=t}execute(o,n){return t(this,void 0,void 0,(function*(){const{enable:t}=this;if(e.logger.info(i.L_LIVING_ROOM_ENABLE_INNER_CDN_T,{roomId:o.roomId,enable:t},{logSource:e.LogSource.RTC}),!o.isMainRoom)return r.error("the `enableInnerCDN` is disabled in PK room"),e.logger.error(i.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:s.FAILED,code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!e.isBoolean(t))return r.error("`enable` is invalid"),e.logger.error(i.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> enable"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};o.setCDNEnabel(t);const a={version:2,output:{inCDNModel:t?Dr.OPEN:Dr.STOP}},{code:c}=yield new Sr(a,this.cdnValues).execute(o,n);if(c!==exports.RCRTCCode.SUCCESS)return r.error(`enableInnerCDN failed -> code: ${c}`),e.logger.error(i.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:s.FAILED,code:c,msg:"signal error"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_ERROR};const d=o.getCDNUris();if(d&&d.broadcast!==$t.SPREAD)return r.info("enableInnerCDN succeed"),e.logger.info(i.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:s.SUCCESSED,enable:t},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS};const{code:_}=yield sr(o);return _===exports.RCRTCCode.SUCCESS?(r.info("enableInnerCDN succeed"),e.logger.info(i.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:s.SUCCESSED,enable:t},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS}):(r.error(`enableInnerCDN failed -> code: ${_}`),e.logger.error(i.L_LIVING_ROOM_ENABLE_INNER_CDN_R,{status:s.FAILED,code:_,msg:""},{logSource:e.LogSource.RTC}),{code:_})}))}}class Mr extends Qt{constructor(e){super(),this.livingType=e}execute(r,o){var i;return t(this,void 0,void 0,(function*(){const{code:t,data:s}=yield r.context.rtcIdentityChange(r.roomId,e.RTCIdentityChangeType.ViewerToAnchor,this.livingType);if(t!==e.ErrorCode.SUCCESS||!s)return{code:t};r.initWithRoomData(s);r.getResourcesByUserId(r.crtUserId).length>0&&o.push(new er);const n=null===(i=s.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===i?void 0:i.value;return n&&r.setCDNUris(JSON.parse(n)[0]),{code:t,data:s}}))}}class br extends mr{constructor(t,r,o,i,s,n,a,c,d,_){super(t,r,o,e.RTCMode.LIVE,i,s,a,c,d,_),this._livingType=n,this._mcuConfigBuilder=new vr(this._invoker,this._isValidResourceId.bind(this))}_initAfterCatchRoomData(e){if(this._store.isUpgrade&&this._afterChangedRole(e),this._store.isMainRoom){const t=((e,t)=>{const r={};return t.forEach((t=>{const o=JSON.parse(t.value),{inviterRoomId:i,inviteeRoomId:s}=o;r[e===i?s:i]=JSON.parse(t.value)})),r})(this._roomId,e.roomInfo);this._roomPKHandler=new yr(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(r,o,n,a,c){const d=Object.create(null,{__innerInit:{get:()=>super.__innerInit}});return t(this,void 0,void 0,(function*(){if(!e.validate("livingType",n,(e=>e===exports.RCLivingType.AUDIO||e===exports.RCLivingType.VIDEO)))return e.logger.error(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> livingType"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};const{code:t,data:_}=yield d.__innerInit.call(this,r,o,n,a,c);return t===exports.RCRTCCode.SUCCESS&&_&&this._initAfterCatchRoomData(_),{code:t,data:_}}))}__innerInitByIdentityChange(){return t(this,void 0,void 0,(function*(){const{code:t,data:r}=yield this._invoker.push(new Mr(this._livingType));return t===e.ErrorCode.SUCCESS&&r&&(this._initAfterCatchRoomData(r),this._initWithRoomData(r.offlineKickTime),e.logger.info(i.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:s.SUCCESSED,roomData:r},{logSource:e.LogSource.RTC})),t}))}publish(o){const n=Object.create(null,{publish:{get:()=>super.publish}});return t(this,void 0,void 0,(function*(){return this._store.isMainRoom?n.publish.call(this,o):(r.warn("the `publish` is disabled in PK room "),e.logger.error(i.L_ABSTRACT_ROOM_PUBLISH_R,{status:s.FAILED,code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}unpublish(o){const n=Object.create(null,{unpublish:{get:()=>super.unpublish}});return t(this,void 0,void 0,(function*(){return this._store.isMainRoom?n.unpublish.call(this,o):(r.warn("the `unpublish` is disabled in PK room "),e.logger.error(i.L_ABSTRACT_ROOM_UNPUBLISH_R,{status:s.FAILED,code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}))}_isValidResourceId(e){var t;const{userId:r}=tt(e),o=!!(null===(t=this._store.getResourcesByUserId(r))||void 0===t?void 0:t.find((t=>et(t)===e)));let i=!1;const{code:s,roomPKHandler:n}=this.getRoomPKHandler();if(s!==exports.RCRTCCode.SUCCESS||!n)return o;const a=n.getJoinedPKRooms(),c=[];return Object.values(a).map((e=>{c.push(...e.getRemoteTracks())})),i=c.some((t=>e===t.getTrackId())),o||i}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._store.isMainRoom?this._mcuConfigBuilder:(r.error("the `getMCUConfigBuilder` is disabled in PK room"),{code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}enableInnerCDN(e){return t(this,void 0,void 0,(function*(){return this._invoker.push(new Ur(this._mcuConfigBuilder.__innerGetValues(),e))}))}_resourceHandle(e,r,o){const i=Object.create(null,{_resourceHandle:{get:()=>super._resourceHandle}});return t(this,void 0,void 0,(function*(){i._resourceHandle.call(this,e,r,o)}))}_afterChangedRole(e){const t=pt(e,this._roomId),r=this._context.getCurrentId(),o=Object.keys(t);setTimeout((()=>{var i;const s=o.filter((e=>e!==r));s.length>0&&this._callAppListener("onUserJoin",s);for(const e in t)e!==r&&this._resourceHandle({uris:t[e]},Tt.TOTAL_CONTENT_RESOURCE,e);if(!(null===(i=e.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===i?void 0:i.value))return;const n=this._store.getCDNUris();(null==n?void 0:n.push_mode)===Nr.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,r){return t(this,void 0,void 0,(function*(){this._invoker.push(new kr(e,(e=>({pushOtherRooms:this._getPushOtherRoomsParams(),headers:this._getRTCReqestHeaders(e)})),this._roomPKHandler))}))}_getPushOtherRoomsParams(){const e=[];if(!this.isMainRoom()||!this._roomPKHandler)return e;const t=this._roomPKHandler.getJoinedPKRooms();for(const r in t){const o=t[r].getSessionId(),i=this._roomPKHandler.getPKInfo(r);if(!i)continue;const{inviterUserAutoMix:s,inviteeUserAutoMix:n,inviterUserId:a}=i,c=this._context.getCurrentId()===a;e.push({roomId:r,sessionId:o,autoMix:c?!!s:!!n})}return e}getRoomPKHandler(){return this._store.isMainRoom?(e.logger.info(i.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,roomPKHandler:this._roomPKHandler}):(r.error("the `getRoomPKHandler` is disabled in PK room"),e.logger.error(i.L_LIVING_ROOM_GET_ROOM_PK_HANDLER_O,{status:s.SUCCESSED,code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}_quitAllPKRoom(){return t(this,void 0,void 0,(function*(){const t=this._roomPKHandler.getJoinedPKRooms();for(const e in t)this._roomPKHandler.leaveOtherRoom(t[e]);e.logger.info(i.L_LIVING_ROOM_QUIT_ALL_PK_ROOM_O,{status:s.SUCCESSED,roomIds:Object.keys(t)},{logSource:e.LogSource.RTC})}))}isMainRoom(){return this._store.isMainRoom}}class xr extends mr{constructor(t,r,o,i,s,n,a,c,d){super(t,r,o,e.RTCMode.RTC,i,s,n,a,c,d)}}const Br=new class{constructor(){this.queue=[],this.locked=!1,this.taskCount=0}checkToStart(){return t(this,void 0,void 0,(function*(){if(0===this.queue.length||this.locked)return;this.locked=!0;const{resolve:e,task:t,reject:r}=this.queue.shift();let o;try{o=yield t(),e(o)}catch(e){r(e)}this.locked=!1,this.checkToStart()}))}push(e,t=""){const r=new Promise(((t,r)=>{this.queue.push({resolve:t,task:e,reject:r})}));return this.checkToStart(),r}},Vr=(e,t="")=>Br.push(e,t);class wr{constructor(e,t,r,o){this._context=e,this._useMutilPeerC=o,this._rtcToken="",this._liveUrl="",this._subTracks=[],this._clientSessionId=St(),this._livingType=null,this._mediaType=null,this._subTiny=!1,this._fromRetry=!1,this._appListener=null,this._service=new It(t,e,r.mediaServer),this._peerCManager=new zt(this._useMutilPeerC,this._context.getCurrentId(),this._reTryExchange.bind(this),this._context.getCurrentId())}_getReqHeaders(o){return t(this,void 0,void 0,(function*(){const t=this._context.getCurrentId(),i=t;if(!this._rtcToken){const{code:t,data:s}=yield this._context.getRTCToken(i,e.RTCMode.LIVE,o);if(t!==e.ErrorCode.SUCCESS)return r.error(`getRTCToken failed: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR};this._rtcToken=s.rtcToken}return{code:exports.RCRTCCode.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:t,RoomId:i,RoomType:e.RTCMode.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 t(this,void 0,void 0,(function*(){this._fromRetry=!0;const{code:t}=yield this.subscribe(this._liveUrl,this._livingType,this._mediaType,this._subTiny);t===exports.RCRTCCode.SUCCESS&&(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer())}))}subscribe(e,r,o,i=!1){return t(this,void 0,void 0,(function*(){return Vr((()=>this.__subscribe(e,r,o,i)),"audience-client-sub")}))}__subscribe(o,n,a,c=!1){var d;return t(this,void 0,void 0,(function*(){e.logger.info(i.L_AUDIENCE_CLIENT_SUBSCRIBE_T,{liveUrl:o,livingType:n,mediaType:a,subTiny:c},{logSource:e.LogSource.RTC});const t=[];if(Ct(this._context.getNaviInfo()))return e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,tracks:t};if(!this._fromRetry&&(null===(d=this._pc)||void 0===d||d.clearReTryExchangeTimer()),this._fromRetry=!1,!e.isString(o))return r.error(`liveUrl is invalid: ${o}`),e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:`params error -> liveUrl: ${o}`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};if(![exports.RCLivingType.AUDIO,exports.RCLivingType.VIDEO].includes(n))return r.error(`livingType is invalid: ${n}`),e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:`params error -> livingType: ${n}`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};if(![exports.RCMediaType.AUDIO_ONLY,exports.RCMediaType.VIDEO_ONLY,exports.RCMediaType.AUDIO_VIDEO].includes(a))return r.error(`mediaType is invalid: ${a}`),e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:`params error -> -> mediaType: ${a}`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};if(this._liveUrl&&this._liveUrl!==o)return e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.BROADCAST_SUB_LIST_NOT_EMPTY,msg:"repeat subscribe"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.BROADCAST_SUB_LIST_NOT_EMPTY,tracks:t};if(!this._pc){const{pcName:e,pc:r}=this._peerCManager.createPeerCList(t)[0];this._pc=r,this._pcName=e,this._pc.on(Wt.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this._pc.registerReportListener(this._reportListener),this._pc.__reportR3R4ToPolaris()}this._liveUrl=o;const{code:_,headers:u}=yield this._getReqHeaders(n);if(_!==exports.RCRTCCode.SUCCESS)return e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:_,msg:""},{logSource:e.LogSource.RTC}),{code:_,tracks:t};const l=`rc_mcu_${Date.now()}`,R="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new je(R,l),new Je(R,l)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const C={sdp:yield this._pc.createOffer(!0),liveUrl:o,mediaType:a,simulcast:c?ft.TINY:ft.NORMAL,switchstream:!1},p=yield this._service.broadcastSubscribe(u,C);if(p.code!==exports.RCRTCCode.SUCCESS)return r.error(`andience subscribe failed: ${p.code}`),e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:p.code,msg:""},{logSource:e.LogSource.RTC}),{code:p.code,tracks:t};const h=p.data;if(h.resultCode!==exports.RCRTCCode.SUCCESS)return r.error(`andience subscribe failed! code: ${h.resultCode}; message: ${h.message}`),e.logger.error(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.FAILED,code:h.resultCode,msg:""},{logSource:e.LogSource.RTC}),{code:h.resultCode,tracks:t};r.debug(`andience subscribe success: ${o}`),this._livingType=n,this._mediaType=a,this._subTiny=c;const{sdp:T,subscribedList:g}=h,m=[];return g.forEach((e=>{const{mediaType:t}=e,r=this._subTracks[t];m.push(r),r.__innerSetRemoteMuted(!0)})),this._pc.setRemoteAnswer(T.sdp),e.logger.info(i.L_AUDIENCE_CLIENT_SUBSCRIBE_R,{status:s.SUCCESSED,liveUrl:o},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,tracks:m}}))}unsubscribe(){return t(this,void 0,void 0,(function*(){return Vr((()=>this.__unsubscribe()),"audience-client-unsub")}))}__unsubscribe(){var o;return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_AUDIENCE_CLIENT_UNSUBSCRIBE_T,{liveUrl:this._liveUrl},{logSource:e.LogSource.RTC}),null===(o=this._pc)||void 0===o||o.clearReTryExchangeTimer(),!this._rtcToken||!this._liveUrl)return e.logger.warn(i.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:s.FAILED,code:"",msg:"Address does not exist, without unsubscribe"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS};const{headers:t}=yield this._getReqHeaders(),{code:n}=yield this._service.broadcastExit(t);return n!==exports.RCRTCCode.SUCCESS?(r.error(`broadcast unsubscribe failed: ${n}`),e.logger.error(i.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:s.FAILED,code:n,msg:""},{logSource:e.LogSource.RTC})):(r.debug("broadcast unsubscribe success"),e.logger.info(i.L_AUDIENCE_CLIENT_UNSUBSCRIBE_R,{status:s.SUCCESSED,liveUrl:this._liveUrl},{logSource:e.LogSource.RTC})),this._clearSubscribeInfo(),{code:n}}))}registerReportListener(e){this._reportListener=e}registerTrackEventListener(e){this._appListener=e}_onTrackReady(e){var t,o;const i=e.receiver.track,s="audio"===i.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY,n=this._subTracks[s];n.__innerSetMediaStreamTrack(i);try{null===(o=null===(t=this._appListener)||void 0===t?void 0:t.onTrackReady)||void 0===o||o.call(t,n)}catch(e){r.error(e)}}}var Fr,$r;exports.RCInnerCDNPullKind=void 0,(Fr=exports.RCInnerCDNPullKind||(exports.RCInnerCDNPullKind={})).RTMP="rtmp",Fr.FLV="flv",Fr.HLS="hls",exports.RCInnerCDNPullIsHttps=void 0,($r=exports.RCInnerCDNPullIsHttps||(exports.RCInnerCDNPullIsHttps={}))[$r.NOT_HTTPS=0]="NOT_HTTPS",$r[$r.HTTPS=1]="HTTPS";const Gr=Object.assign(Object.assign({},nt(exports.RCResolution.W176_H144)),{frameRate:dt(exports.RCFrameRate.FPS_15)});class Kr{constructor(e,t,r,o,i,s,n,a=St()){this._context=e,this._runtime=t,this._initOptions=r,this._roomId=o,this._joinResData=i,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 It(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new Yt(this._context,this._runtime,this._roomId,this,xt.Audience),this._polarisReport.sendR1(),this._peerCManager=new zt(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:o,remoteTracks:i,CDNUris:s}=((e,t)=>{const r=t.filter((e=>"RC_RTC_SESSIONID"===e.key))[0],o=r?r.value:"",i=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:o}=t,i=r===exports.RCMediaType.AUDIO_ONLY?new je(o,"",e):new Je(o,"",e);a.push(i)}));const c=[],d=[];s.forEach((e=>{const t=JSON.parse(e.uris||"[]");c.push(...t),t.forEach((e=>{const{mediaType:t,tag:r,msid:o}=e,i=o.split("_")[0],s=t===exports.RCMediaType.AUDIO_ONLY?new je(r,i):new Je(r,i);d.push(s)}))}));const _=t.filter((e=>"RC_CDN"===e.key)).map((e=>{const t=JSON.parse(e.value||"[]");return JSON.parse(t.cdn_uris)[0]}))[0];return{sessionId:o,remoteUserIds:i||[],remoteRTCUris:c,remoteMUCUris:n,remoteRTCTracks:d,remoteMCUTracks:a,remoteTracks:[...d,...a],CDNUris:_||{}}})(this._roomId,this._joinResData.kvEntries);this._sessionId=e,this._roomAnchorList=t,i.forEach((e=>{this._remoteTracks[e.getTrackId()]=e})),this._CDNUris=s,r.forEach((e=>{const t=e.msid.split("_")[0];this._roomAnchorRes[t]?this._roomAnchorRes[t].push(e):this._roomAnchorRes[t]=[e]})),o.forEach((e=>{const{mediaType:t,tag:r}=e,o=[this._roomId,r,t].join("_");this._roomRes[o]=e})),r.forEach((e=>{const t=et(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 r.warn(e),exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(t,o){var n;if(e.logger.info(i.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_T,{singalData:t,roomId:o,userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),o!==this._roomId)return r.warn(`singalDataChange -> not the current room data: data roomId: ${o}, current roomId: ${this._roomId}`),void e.logger.error(i.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:s.FAILED,code:"",msg:`id inconsistency -> params id:${o},current id:${this._roomId}`},{logSource:e.LogSource.RTC});r.debug("singalDataChange -> singalData:",JSON.stringify(t||{}));const a=[],c=null===(n=t.filter((e=>"RC_CDN"===e.key))[0])||void 0===n?void 0:n.value;c&&this._diffCDNUris(JSON.parse(JSON.parse(c).cdn_uris)[0]),t.forEach((e=>{const{key:t,value:r,timestamp:o,uid:i}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),o=JSON.parse(e.uris||"[]");return a.push(...t),void this._diffAnchorResource(o,i)}if("RC_ANCHOR_LIST"===t){const e=JSON.parse(r||"[]"),{joinUserIds:t,leftUserIds:o}=this._diffAnchorList(e);t.length>0&&this._handleNewJoinedAnchor(t),o.length>0&&this._handleLeftedAnchor(o)}})),this._diffRoomResource(a),e.logger.info(i.L_AUDIENCE_LIVING_ROOM_SINGAL_DATA_CHANGE_R,{status:s.SUCCESSED,singalData:t,roomId:o,userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC})}_diffAnchorList(e){const t=e.filter((e=>this._roomAnchorList.indexOf(e)<0));return{leftUserIds:this._roomAnchorList.filter((t=>e.indexOf(t)<0)),joinUserIds:t}}_handleNewJoinedAnchor(e){this._roomAnchorList.push(...e),this._callAppListener("onAnchorJoin",e)}_handleLeftedAnchor(e){return t(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 t(this,void 0,void 0,(function*(){const t=[],r=[],o=[];e.forEach((e=>{const r=et(e),{userId:i,tag:s,mediaType:n}=tt(r),a=[this._roomId,s,n].join("_");if(!this._remoteTracks[a]){const r=n===exports.RCMediaType.AUDIO_ONLY?new je(s,"",this._roomId):new Je(s,"",this._roomId);t.push(r),this._remoteTracks[a]=r,this._roomRes[r.getTrackId()]=e}o.push(a)})),Object.keys(this._remoteTracks).forEach((e=>{o.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,o){return t(this,void 0,void 0,(function*(){const t=this._roomAnchorRes[o]||(this._roomAnchorRes[o]=[]),{publishedList:i,unpublishedList:s,modifiedList:n}=it(t,e);if(i.length){const e=t.map(et),o=[],s=[];if(i.forEach((r=>{const i=et(r),n=e.indexOf(i),{userId:a,tag:c,mediaType:d}=tt(i);n>-1?t[n]=r:t.push(r);let _=this._remoteTracks[i];this._roomRes[i]=r,_?_.isSubscribed()&&o.push(_):(_=d===exports.RCMediaType.AUDIO_ONLY?new je(c,a):new Je(c,a),this._remoteTracks[i]=_,s.push(_)),_.__innerSetRemoteMuted(0===r.state)})),o.length){const e=o.map((e=>e.getTrackId()));r.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:t}=yield Vr((()=>this._subscribeHandle(o,!0)));t!==exports.RCRTCCode.SUCCESS&&r.error(`resub tracks failed -> code: ${t}, ids: ${JSON.stringify(e)}`)}this._callAppListener("onAnchorTrackPublish",s)}if(s.length){const e=s.map(et);for(let r=t.length-1;r>=0;r-=1){const o=t[r];e.includes(et(o))&&t.splice(r,1)}const r=s.map((e=>{const t=et(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(r,"onAnchorTrackUnpublish")}if(n.length){const e=t.map(et);for(let r=0;r<n.length;r++){const o=n[r],i=et(o),s=e.indexOf(i);t[s].state=o.state;const a=this._remoteTracks[i];a.__innerSetRemoteMuted(0===o.state),a.isAudioTrack()?this._callAppListener("onAudioMuteChange",a):this._callAppListener("onVideoMuteChange",a)}}}))}_onUserUnpublish(e,r){return t(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(r,e)}))}_callAppListener(e,...t){var o;r.info(`${e} callback ->`,...t);const i=null===(o=this._appListener)||void 0===o?void 0:o[e];if(i)try{i(...t)}catch(e){r.error(e)}}_reTryExchange(){return t(this,void 0,void 0,(function*(){Vr((()=>t(this,void 0,void 0,(function*(){var e;const{reqBody:t}=yield this._createSubscribeParams(this._subscribedList,{},!0),o=yield this._exchangeHandle(t);if(o.code!==exports.RCRTCCode.SUCCESS)return r.error(`reTryExchange failed: ${o.code}`),{code:o.code};const{sdp:i,resultCode:s}=o.data;if(s!==exports.RCRTCCode.SUCCESS)return r.error(`reTryExchange failed: ${s}`),{code:s};this._pc.clearReTryExchangeTimer();const n=this._subscribedList.filter((e=>e.track.isMCUTrack()));if(n.length>0){const t=n[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 a=yield this._pc.setRemoteAnswer(i.sdp);return a!==exports.RCRTCCode.SUCCESS?{code:a}:void 0}))),"audience-retry-exchange")}))}_createSubscribeParams(e,r,o){return t(this,void 0,void 0,(function*(){const t=yield this._pc.createOffer(o),i={resolutionInfo:[]},s={min:0,max:0};Object.keys(r).forEach((e=>{const{mediaStream:o,tinyStream:n}=r[e];[o,n].forEach(((r,o)=>{var n;const a=1===o?[e,"tiny"].join("_"):e;t.sdp=null===(n=t.sdp)||void 0===n?void 0:n.replace(new RegExp(r.id,"g"),a);const c=r.getVideoTracks()[0];if(!c)return;const d=0===o,{width:_,height:u,frameRate:l}=d?Ze(c):Gr;i.resolutionInfo.push({trackId:c.id,simulcast:d?ft.NORMAL:ft.TINY,resolution:`${_}x${u}`});const R=Le(_,u),C=ve(l);s.min+=R.minBitrate*C,s.max+=R.maxBitrate*C}))}));return{reqBody:{sdp:t,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?ft.TINY:ft.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:s,offer:t}}))}_subscribeHandle(r,o=!1){var n;return t(this,void 0,void 0,(function*(){e.logger.info(i.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_T,{trackIds:r.map(ht),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:o},{logSource:e.LogSource.RTC});if(this._assertRoomDestroyed())return e.logger.error(i.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED,msg:"room destroyed"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!e.validate("tracks",r,(()=>e.isArray(r)&&r.length>0&&r.every((e=>e instanceof He||e.track instanceof He))),!0))return e.logger.error(i.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};const{pc:t,pcName:a}=this._peerCManager.createPeerCList(r)[0];this._pc=t,this._pc.__reportR3R4ToPolaris(),this._pcName=a,this._pc.registerReportListener(this._reportListener),this._addPeerCEvent();const c=this._subscribedList.map((e=>Object.assign({},e))),d=r.map((e=>e instanceof He?{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)})),_||o?(null===(n=this._polarisReport)||void 0===n||n.sendR2(wt.SUBSCRIBE,Ft.BEGIN,u),e.logger.info(i.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:s.SUCCESSED,trackIds:r.map(ht),roomId:this._roomId,userId:this._context.getCurrentId(),forceReq:o},{logSource:e.LogSource.RTC}),this._updateSubListHandle(c,!0)):(e.logger.warn(i.L_AUDIENCE_LIVING_ROOM_SUBSCRIBE_R,{status:s.FAILED,code:"",msg:"repeat subscribe"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}_addPeerCEvent(){this._pc.on(Wt.__INNER_EVENT_TRACK_READY__,(e=>{const t=e.streams[0].id,o=e.receiver.track,i=[t,"audio"===o.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY].join("_"),s=this._remoteTracks[i];s?(s.__innerSetMediaStreamTrack(o),this._callAppListener("onTrackReady",s)):r.warn("cannot found RCRemoteTrack:",o.id)}))}_getReqHeaders(){const t=this._context.getCurrentId();return{"App-Key":this._context.getAppkey(),RoomId:t,Token:this._joinResData.token,RoomType:e.RTCMode.LIVE,UserId:t,"Session-Id":this._sessionId,"Peer-Connection-Id":this._pcName,"Client-Session-Id":this._clientSessionId}}_exchangeHandle(e){return this._service.broadcastSubscribe(this._getReqHeaders(),e)}_updateSubListHandle(o,i=!1){var s;return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!e.validate("resources",o,(()=>e.isArray(o)&&o.every((e=>e instanceof He||e.track instanceof He))),!0))return{code:exports.RCRTCCode.PARAMS_ERROR};let t=o.map((e=>e instanceof He?{track:e}:Object.assign({},e)));const n={};t=t.filter((e=>{const t=e.track.getTrackId();return!n[t]&&(n[t]=!0)})).map((e=>Object.assign({},e)));const a=this._subscribedList.map((e=>Object.assign({},e)));if(!i){let e=!1;if(t.forEach((t=>{const r=a.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);a.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),a.length&&(e=!0),!e)return{code:exports.RCRTCCode.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(t.map((e=>e.track)));const{reqBody:c}=yield this._createSubscribeParams(t,{},!1),d=yield this._exchangeHandle(c);if(a.length){const e=[];a.forEach((t=>{e.push(t.track.getTrackId())})),null===(s=this._pc.reportParser)||void 0===s||s.clearLatestPacketsRecv(e)}if(d.code!==exports.RCRTCCode.SUCCESS)return{code:d.code};const{sdp:_,resultCode:u,message:l,subscribedList:R}=d.data;if(u!==exports.RCRTCCode.SUCCESS)return r.error("change subscribe list failed:",l,u),{code:u};t.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:o}=tt(t.getTrackId()),i=[o,r].join("_");_.sdp=_.sdp.replace(new RegExp(e,"g"),i)}}));const C=yield this._pc.setRemoteAnswer(_.sdp);if(C!==exports.RCRTCCode.SUCCESS)return{code:C};const p=null==R?void 0:R.map((e=>`${e.msid}_${e.mediaType}`)),h=t.filter((e=>{if(e.track.isMCUTrack()){const t=this._roomRes[e.track.getTrackId()],r=`${t.msid}_${t.mediaType}`;return p.includes(r)}return null==p?void 0:p.includes(e.track.getTrackId())})),T=null==h?void 0:h.map((e=>`${e.track.getTrackId()}`)),g=t.filter((e=>!(null==T?void 0:T.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=h.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...h),g.length?{code:exports.RCRTCCode.SUCCESS,failedList:g}:{code:exports.RCRTCCode.SUCCESS}}))}_diffCDNUris(e){return t(this,void 0,void 0,(function*(){if(this._CDNUris.url&&!e.url)return this._callAppListener("onCDNInfoDisable"),void(this._CDNUris=e);(!this._CDNUris||!this._CDNUris.url&&e.url)&&this._callAppListener("onCDNInfoEnable",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`});const t=this._CDNUris.w&&e.w&&this._CDNUris.w!==e.w,r=this._CDNUris.h&&e.h&&this._CDNUris.h!==e.h,o=this._CDNUris.fps&&e.fps&&this._CDNUris.fps!==e.fps;(t||r||o)&&this._callAppListener("onCDNInfoChange",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`}),this._CDNUris=e}))}_getCDNPlayUrl(e){return t(this,void 0,void 0,(function*(){const{w:t,h:o,fps:i}=e,s=this._initOptions.pullInnerCDNProtocol||exports.RCInnerCDNPullKind.FLV,n=this._initOptions.pullInnerCDNUseHttps===exports.RCInnerCDNPullIsHttps.NOT_HTTPS?exports.RCInnerCDNPullIsHttps.NOT_HTTPS:exports.RCInnerCDNPullIsHttps.HTTPS;if(!this._CDNUris.url)return r.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${exports.RCRTCCode.CDN_RESOURCE_IS_EMPTY}`),{code:exports.RCRTCCode.CDN_RESOURCE_IS_EMPTY};const a={"App-Key":this._context.getAppkey(),Token:this._joinResData.token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},c=[];t&&c.push(`w=${t}`),o&&c.push(`h=${o}`),i&&c.push(`fps=${i}`),c.push(`kind=${s}`),c.push(`is_https=${n}`);const d=c.join("&");let _=`${this._CDNUris.url}?`;d&&(_+=d);const{code:u,res:l}=yield this._service.getCDNResourceInfo(a,_);return u!==exports.RCRTCCode.SUCCESS?(r.error(`getCDNPlayUrl failed: ${u}`),{code:u}):(r.info(`getCDNPlayUrl success: ${null==l?void 0:l.data.pull_url}`),{code:u,CDNPlayUrl:null==l?void 0:l.data.pull_url})}))}getCDNPlayUrl(o,n){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_T,{resolution:o,fps:n},{logSource:e.LogSource.RTC}),o&&!at(o))return r.error("`resolution` is invalid"),e.logger.error(i.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> resolution"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(n&&!ct(n))return r.error("`fps` is invalid"),e.logger.error(i.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> fps"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};const{width:t,height:a}=o?nt(o):{width:null,height:null},c=n?dt(n):null,d={};return t&&(d.w=t),a&&(d.h=a),c&&(d.fps=c),e.logger.info(i.L_AUDIENCE_LIVING_ROOM_GET_CDN_PLAY_URL_R,{status:s.SUCCESSED,resolution:o,fps:n},{logSource:e.LogSource.RTC}),this._getCDNPlayUrl(d)}))}subscribe(e){return t(this,void 0,void 0,(function*(){return Vr((()=>this._subscribeHandle(e,!1)),"audience-sub")}))}__unsubscribe(o){var n;return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_T,{trackIds:o.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),!e.validate("tracks",o,(()=>e.isArray(o)&&o.length>0&&o.every((e=>e instanceof He))),!0))return r.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),e.logger.error(i.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> tracks"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};const t=this._subscribedList.map((e=>Object.assign({},e))).filter((e=>!o.includes(e.track)));return null===(n=this._polarisReport)||void 0===n||n.sendR2(wt.SUBSCRIBE,Ft.END,o.map((e=>e.getTrackId()))),e.logger.info(i.L_AUDIENCE_LIVING_ROOM_UNSUBSCRIBE_R,{status:s.SUCCESSED,trackIds:o.map((e=>e.getTrackId())),roomId:this._roomId,userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),this._updateSubListHandle(t,!1)}))}unsubscribe(e){return t(this,void 0,void 0,(function*(){return Vr((()=>this.__unsubscribe(e)),"audience-unsub")}))}__destroy(e){var r,o;return t(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),e&&(yield this._context.quitLivingRoomAsAudience(this._roomId)),yield this._service.broadcastExit(this._getReqHeaders()),null===(o=this._pc)||void 0===o||o.destroy(),this._polarisReport=null,this._context.onrtcdatachange=()=>{})}))}getRemoteTrack(e){return this._remoteTracks[e]}__getPC(){return this._peerCManager.getPCList()}getLocalTrack(e){return{}}__onReconnected(){return t(this,void 0,void 0,(function*(){const{code:t}=yield this._context.joinLivingRoomAsAudience(this._roomId,e.RTCMode.LIVE);t!==e.ErrorCode.SUCCESS&&r.error("join living room error when on reconnected")}))}registerRoomEventListener(e){this._appListener=e}onAudioLevelChange(t,r){var o;null===(o=this._audioLevelReport)||void 0===o||o.clearAudioLevelReportTimer(),this._audioLevelReport=new qt(this),this._audioLevelReport.onAudioLevelChange(t,r||1e3),e.logger.info(i.L_AUDIENCE_LIVING_ROOM_AUDIO_LEVEL_CHANGE_O,{status:s.SUCCESSED,handler:null==t?void 0:t.name,gap:r},{logSource:e.LogSource.RTC})}registerReportListener(e){this._reportListener=e}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}getSessionId(){return this._sessionId}getRemoteUserIds(){return this._roomAnchorList}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const o=this._remoteTracks[r];o.getUserId()===e&&t.push(o)}return t}getRemoteTracks(){const e=[],t=[];for(const e in this._remoteTracks){if(2===t.length)break;const r=this._remoteTracks[e];r.isMCUTrack()&&t.push(r)}return this._roomAnchorList.forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),[...t,...e]}getRemoteRTCTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()||e.push(r)}return e}getRemoteMCUTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()&&e.push(r)}return e}getCDNInfo(){return this._CDNUris.w?{resolution:`W${this._CDNUris.w}_H${this._CDNUris.h}`,fps:`FPS_${this._CDNUris.fps}`,CDNEnable:this._CDNUris.enableInnerCDN}:{CDNEnable:!1}}getClientSessionId(){return this._clientSessionId}}class Hr{constructor(e){this._context=e,this._isElectron=/Electron/.test(navigator.userAgent)}_getMediaStream(e,o="getUserMedia"){return t(this,void 0,void 0,(function*(){try{const t=this.setConstraintsConfig(e),r=yield navigator.mediaDevices[o](t);return{code:exports.RCRTCCode.SUCCESS,stream:r}}catch(e){if("Permission denied"===e.message)return{code:exports.RCRTCCode.PERMISSION_DENIED};r.error(`get user media failed -> ${e.message}`)}return{code:"getUserMedia"===o?exports.RCRTCCode.GET_USER_MEDIA_FAILED:exports.RCRTCCode.GET_DISPLAY_MEDIA_FAILED}}))}setConstraintsConfig(e){if((null==e?void 0:e.audio)&&!this._isElectron){"boolean"==typeof e.audio&&(e.audio={});const t=navigator.mediaDevices.getSupportedConstraints();t.noiseSuppression&&(e.audio.noiseSuppression=!!t.noiseSuppression),t.autoGainControl&&(e.audio.autoGainControl=!!t.autoGainControl),t.echoCancellation&&(e.audio.echoCancellation=!!t.echoCancellation),r.info(`browser supported -> ${JSON.stringify(t)}`)}return e}createMicrophoneAudioTrack(r="RongCloudRTC",o){return t(this,void 0,void 0,(function*(){if(!qe(r))return e.logger.error(i.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS};const t=this._context.getCurrentId();if(!t)return e.logger.error(i.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID};const{stream:n,code:a}=yield this._getMediaStream({audio:{deviceId:null==o?void 0:o.micphoneId,sampleRate:null==o?void 0:o.sampleRate}});if(a!==exports.RCRTCCode.SUCCESS)return e.logger.error(i.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:s.FAILED,code:a,msg:"Failed to get microphone audio stream"},{logSource:e.LogSource.RTC}),{code:a};const c=n.getAudioTracks()[0],d=new Fe(r,t,c);return e.logger.info(i.L_RTC_CLIENT_CREATE_MICROPHONE_AUDIO_TRACK_O,{status:s.SUCCESSED,trackId:d.getTrackId()},{logSource:e.LogSource.RTC}),{code:a,track:d}}))}createCameraVideoTrack(r="RongCloudRTC",o){return t(this,void 0,void 0,(function*(){if(!qe(r))return e.logger.error(i.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS};const t=this._context.getCurrentId();if(!t)return e.logger.error(i.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID};const n=at(null==o?void 0:o.resolution)?o.resolution:exports.RCResolution.W640_H480,{width:a,height:c}=nt(n),{stream:d,code:_}=yield this._getMediaStream({video:{deviceId:null==o?void 0:o.cameraId,frameRate:dt((null==o?void 0:o.frameRate)||exports.RCFrameRate.FPS_15),width:a,height:c,facingMode:null==o?void 0:o.faceMode}});if(_!==exports.RCRTCCode.SUCCESS)return e.logger.error(i.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"Failed to get camera video stream"},{logSource:e.LogSource.RTC}),{code:_};const u=d.getVideoTracks()[0],l=new $e(r,t,u);return e.logger.info(i.L_RTC_CLIENT_CREATE_CAMERA_VIDEO_TRACK_O,{status:s.SUCCESSED,trackId:l.getTrackId()},{logSource:e.LogSource.RTC}),{code:_,track:l}}))}createMicrophoneAndCameraTracks(r="RongCloudRTC",o){var n,a,c,d,_,u;return t(this,void 0,void 0,(function*(){const t=[];if(!qe(r))return e.logger.error(i.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS,tracks:t};const l=this._context.getCurrentId();if(!l)return e.logger.error(i.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID,tracks:t};const R=at(null===(n=null==o?void 0:o.video)||void 0===n?void 0:n.resolution)?o.video.resolution:exports.RCResolution.W640_H480,{width:C,height:p}=nt(R),{stream:h,code:T}=yield this._getMediaStream({video:{deviceId:null===(a=null==o?void 0:o.video)||void 0===a?void 0:a.cameraId,frameRate:dt((null===(c=null==o?void 0:o.video)||void 0===c?void 0:c.frameRate)||exports.RCFrameRate.FPS_15),width:C,height:p,facingMode:null===(d=null==o?void 0:o.video)||void 0===d?void 0:d.faceMode},audio:{deviceId:null===(_=null==o?void 0:o.audio)||void 0===_?void 0:_.micphoneId,sampleRate:null===(u=null==o?void 0:o.audio)||void 0===u?void 0:u.sampleRate}});return T!==exports.RCRTCCode.SUCCESS?(e.logger.error(i.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:s.FAILED,code:T,msg:"Failed to get audio and video stream of camera and microphone"},{logSource:e.LogSource.RTC}),{code:T,tracks:t}):(h.getTracks().forEach((e=>{"video"===e.kind?t.push(new $e(r,l,e)):t.unshift(new Fe(r,l,e))})),e.logger.info(i.L_RTC_CLIENT_CREATE_MICROPHONE_AND_CAMERA_TRACKS_O,{status:s.SUCCESSED,trackIds:t.map((e=>e.getTrackId()))},{logSource:e.LogSource.RTC}),{code:T,tracks:t})}))}createScreenVideoTrack(e="screenshare",r){return t(this,void 0,void 0,(function*(){const t=yield this._createScreenTracks(e,!1,i.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,r);return t.code===exports.RCRTCCode.SUCCESS?{code:t.code,track:t.tracks[0]}:t}))}createScreenWithAudioTracks(e="screenshare",r){return t(this,void 0,void 0,(function*(){return this._createScreenTracks(e,!0,i.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_AND_AUDIO_TRACKS_O,r)}))}_createScreenTracks(r,o,n,a){var c,d;return t(this,void 0,void 0,(function*(){if(!qe(r))return e.logger.error(n,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS};const t=this._context.getCurrentId();if(!t)return e.logger.error(n,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID};if(!lt())return e.logger.error(i.L_RTC_CLIENT_CREATE_SCREEN_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.BROWSER_NOT_SUPPORT};const _=/macintosh|mac os x/i.test(navigator.userAgent);this._isElectron&&_&&o&&e.logger.warn(n,{status:s.INFO,code:exports.RCRTCCode.MAC_IN_ELECTRON_NOT_SUPPORT_SCREEN_SHARE_WITH_AUDIO,msg:"mac in electron not support screen share with audio"});const u=(!this._isElectron||!_)&&o;if(this._isElectron&&!e.isUndefined(null==a?void 0:a.chromeMediaSourceId)&&!e.isString(null==a?void 0:a.chromeMediaSourceId))return e.logger.error(n,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> options.chromeMediaSourceId type is string"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};const l=at(null==a?void 0:a.resolution)?a.resolution:exports.RCResolution.W1280_H720,{width:R,height:C}=nt(l),p=this._isElectron?{mandatory:{chromeMediaSourceId:null==a?void 0:a.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:R,maxWidth:R,minHeight:C,maxHeight:C}}:{frameRate:dt((null==a?void 0:a.frameRate)||exports.RCFrameRate.FPS_15),width:R,height:C};!(null==a?void 0:a.chromeMediaSourceId)&&this._isElectron&&(null===(c=p.mandatory)||void 0===c||delete c.chromeMediaSourceId);let h=null;u&&this._isElectron&&(null===(d=p.mandatory)||void 0===d||delete d.chromeMediaSourceId,h={mandatory:{chromeMediaSource:"desktop"}});const{stream:T,code:g}=yield this._getMediaStream({video:p,audio:h||u},this._isElectron?"getUserMedia":"getDisplayMedia");if(g!==exports.RCRTCCode.SUCCESS)return e.logger.error(n,{status:s.FAILED,code:g,msg:"Failed to get shared screen video stream"},{logSource:e.LogSource.RTC}),{code:g};const m=T.getVideoTracks()[0],S=[new Ge(r,t,m)];if(u){const e=T.getAudioTracks()[0];e&&S.push(new Ke(r,t,e))}return e.logger.info(n,{status:s.SUCCESSED,trackIds:S.map((e=>e.getTrackId()))},{logSource:e.LogSource.RTC}),{code:g,tracks:S}}))}createLocalAudioTrack(r,o){return t(this,void 0,void 0,(function*(){if(!qe(r))return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS};if(!o||"[object MediaStreamTrack]"!==o.toString()||"audio"!==o.kind)return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"Failed to create custom stream"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED};const t=this._context.getCurrentId();if(!t)return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID};const n=new be(r,t,o);return e.logger.info(i.L_RTC_CLIENT_CREATE_LOCAL_AUDIO_TRACK_O,{status:s.SUCCESSED,trackId:n.getTrackId()},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,track:n}}))}createLocalVideoTrack(r,o){return t(this,void 0,void 0,(function*(){if(!qe(r))return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS};if(!o||"[object MediaStreamTrack]"!==o.toString()||"video"!==o.kind)return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED,msg:"Failed to create custom stream"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED};const t=this._context.getCurrentId();if(!t)return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID};const n=new xe(r,t,o);return e.logger.info(i.L_RTC_CLIENT_CREATE_LOCAL_VIDEO_TRACK_O,{status:s.SUCCESSED,trackId:n.getTrackId()},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,track:n}}))}createLocalFileTracks(o,n,a){return t(this,void 0,void 0,(function*(){if(!qe(o))return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS,tracks:[]};if(!ut())return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.BROWSER_NOT_SUPPORT,msg:"browser not support"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.BROWSER_NOT_SUPPORT,tracks:[]};const t=n instanceof File?URL.createObjectURL(n):n;if(!e.isHttpUrl(t)&&!/^blob:/.test(t))return r.warn(`createLocalFileTracks failed: params error -> url: ${t}`),e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> file"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:[]};const c=this._context.getCurrentId();return c?new Promise((n=>{const d=document.createElement("video");(null==a?void 0:a.withoutAudio)&&(d.muted=!0),d.onloadedmetadata=()=>{const _=[];let u;try{const e=d.mozCaptureStream?"mozCaptureStream":"captureStream";u=d[e]()}catch(o){r.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${t}`),r.error(o),e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:e.LogSource.RTC}),n({code:exports.RCRTCCode.CREATE_FILE_TRACK_FAILED,tracks:_})}const[l,R]=Hr.getTracksWithOptions(u,a);l&&_.push(new we(o,c,l,d)),R&&_.push(new Ve(o,c,R,d)),0===_.length&&(d.pause(),d.src=""),d.onerror=null,e.logger.info(i.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:s.SUCCESSED,trackIds:_.map((e=>e.getTrackId()))},{logSource:e.LogSource.RTC}),n({code:exports.RCRTCCode.SUCCESS,tracks:_})},d.onerror=()=>{r.error(`create RCLocalFileTrack failed -> url: ${t}`),e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.CREATE_FILE_TRACK_FAILED,msg:"Failed to create file stream"},{logSource:e.LogSource.RTC}),n({code:exports.RCRTCCode.CREATE_FILE_TRACK_FAILED,tracks:[]})},d.src=t,d.loop=!0,d.play()})):(e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_FILE_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID,tracks:[]})}))}createLocalTracks(r,o,n){return t(this,void 0,void 0,(function*(){const t=[];if(!qe(r))return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_TAGS,msg:"invalid tag"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_TAGS,tracks:t};if(!(o instanceof MediaStream))return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> stream"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};const a=this._context.getCurrentId();if(!a)return e.logger.error(i.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:s.FAILED,code:exports.RCRTCCode.INVALID_USER_ID,msg:"invalid IM connection,invalid userId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.INVALID_USER_ID,tracks:t};const[c,d]=Hr.getTracksWithOptions(o,n);return c&&t.push(new be(r,a,c)),d&&t.push(new xe(r,a,d)),e.logger.info(i.L_RTC_CLIENT_CREATE_LOCAL_TRACKS_O,{status:s.SUCCESSED,trackIds:t.map((e=>e.getTrackId()))},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,tracks:t}}))}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 jr extends Hr{constructor(e,t,r){super(e),this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,Gt.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new It(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(t){var r;if(t.conversationType!==e.ConversationType.RTC_ROOM)return!1;if(this._crtRoom instanceof br){this._getJoinedPKRoomList().forEach((e=>{e.__parseInnerMessage(t)}))}return null===(r=this._crtRoom)||void 0===r||r.__parseInnerMessage(t),e.logger.info(i.L_RTC_CLIENT_MESSAGE_O,{status:s.SUCCESSED,message:Object.assign(t,{content:"内容涉及隐私不予显示"})},{logSource:e.LogSource.RTC}),!0}_getJoinedPKRoomList(){const{code:e,roomPKHandler:t}=this._crtRoom.getRoomPKHandler();if(e===exports.RCRTCCode.SUCCESS&&t){const e=t.getJoinedPKRooms()||{};return Object.values(e)}return[]}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(r,o,n,a,c=e.RTCMode.RTC){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_RTC_CLIENT_JOIN_RTC_ROOM_T,{roomId:r,joinType:o,outerUserDatas:n,useMutilPeerC:a,roomType:c},{logSource:e.LogSource.RTC}),this._crtRoom)return e.logger.error(i.L_RTC_CLIENT_JOIN_RTC_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const t=this._crtRoom=new xr(this._context,this._runtime,r,this._service,this._options,!1,!1,a,St()),{code:d}=yield t.__innerInit(c,o,void 0,void 0,n);return d!==exports.RCRTCCode.SUCCESS?(this._crtRoom=null,{code:d}):(t.once(gr,(()=>{this._crtRoom=null})),{code:d,room:t,userIds:t.getRemoteUserIds(),tracks:t.getRemoteTracks()})}))}joinLivingRoom(r,o,n,a,c){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_T,{roomId:r,livingType:o,joinType:n,outerUserDatas:a,useMutilPeerC:c},{logSource:e.LogSource.RTC}),this._crtRoom)return e.logger.error(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.REPERT_JOIN_ROOM,msg:`Join the room repeatedly -> roomId: ${r}`},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const t=this._crtRoom=new br(this._context,this._runtime,r,this._service,this._options,o,!1,!0,c),{code:d}=yield t.__innerInit(e.RTCMode.LIVE,n,o,void 0,a);if(d!==exports.RCRTCCode.SUCCESS)return this._crtRoom=null,{code:d};t.once(gr,(()=>{this._crtRoom=null}));const _={code:d,room:t,userIds:t.getRemoteUserIds(),tracks:t.getRemoteTracks()};return t.__getCDNPushMode()===Nr.MANUAL&&Object.assign(_,{CDNEnable:t.__getCDNEnable()}),_}))}getAudienceClient(t){return this._audience||(this._audience=new wr(this._context,this._runtime,this._options,t)),e.logger.info(i.L_RTC_CLIENT_GET_AUDIENCE_CLIENT_O,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),this._audience}_onIMStatusChange(t){if(r.debug(`signal server connection state change: ${t}`),e.logger.info(i.L_RTC_CLIENT_CONNECTION_STATE_S,{status:s.SUCCESSED,data:t},{logSource:e.LogSource.RTC}),t===e.ConnectionStatus.CONNECTED){if(this._crtRoom instanceof br){this._getJoinedPKRoomList().forEach((e=>{e.__onReconnected()}))}this._crtRoom&&this._crtRoom.__onReconnected()}}_onIMDisconnect(){e.logger.info(i.L_RTC_CLIENT_DISCONNECT_S,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),r.debug("TODO -> on IM disconnect")}_onIMUninit(){e.logger.info(i.L_RTC_CLIENT_DESTROY_S,{status:s.SUCCESSED},{logSource:e.LogSource.RTC}),r.debug("TODO -> on IM client ondestroy")}leaveRoom(o){var n,a;return t(this,void 0,void 0,(function*(){return e.logger.info(i.L_RTC_CLIENT_LEAVE_ROOM_T,{userId:this._context.getCurrentId(),roomId:null===(n=this._crtRoom)||void 0===n?void 0:n.getRoomId()},{logSource:e.LogSource.RTC}),this._crtRoom?(yield this._crtRoom.__destroy(!0),r.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),e.logger.info(i.L_RTC_CLIENT_LEAVE_ROOM_R,{status:s.SUCCESSED,userId:this._context.getCurrentId(),roomId:null===(a=this._crtRoom)||void 0===a?void 0:a.getRoomId()},{logSource:e.LogSource.RTC}),this._crtRoom=null,{code:exports.RCRTCCode.SUCCESS}):(e.logger.warn(i.L_RTC_CLIENT_LEAVE_ROOM_R,{status:s.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}joinLivingRoomAsAudience(o,n,a){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_T,{roomId:o,livingType:n,useMutilPeerC:a},{logSource:e.LogSource.RTC}),Ct(this._context.getNaviInfo()))return e.logger.error(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:s.FAILED,code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"navi_url error"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR};if(!e.validate("roomId",o,e.notEmptyString,!0)||!e.validate("livingType",n,(e=>e===exports.RCLivingType.AUDIO||e===exports.RCLivingType.VIDEO)))return e.logger.error(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:s.FAILED,code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,msg:"params error -> roomId or livingType"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return e.logger.error(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:s.FAILED,code:exports.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REPERT_JOIN_ROOM};if(!this._service.getNaviMS().length)return e.logger.error(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:s.FAILED,code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER,msg:"No audio / video server address available"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:t,data:c}=yield this._context.joinLivingRoomAsAudience(o,e.RTCMode.LIVE,n);if(t!==e.ErrorCode.SUCCESS)return r.error("audienceJoinLivingRoomError:",t),e.logger.error(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:s.FAILED,code:exports.RCRTCCode.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED,msg:"signal error -> audience join room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};r.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(c)}`);const d=St(),_=new Kr(this._context,this._runtime,this._options,o,c,n,a,d);return this._crtAudienceLivingRoom=_,e.logger.info(i.L_RTC_CLIENT_JOIN_LIVING_ROOM_AS_AUDIENCE_R,{status:s.SUCCESSED,roomData:c},{logSource:e.LogSource.RTC}),{room:_,code:exports.RCRTCCode.SUCCESS,userIds:_.getRemoteUserIds(),RTCTracks:_.getRemoteRTCTracks(),MCUTracks:_.getRemoteMCUTracks(),CDNUris:_.getCDNInfo()}}))}leaveLivingRoomAsAudience(r){return t(this,void 0,void 0,(function*(){return e.logger.info(i.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_T,{roomId:r.getRoomId(),userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),this._crtAudienceLivingRoom?this._crtAudienceLivingRoom!==r?(e.logger.error(i.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR}):(yield this._crtAudienceLivingRoom.__destroy(!0),this._crtAudienceLivingRoom=null,e.logger.info(i.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:s.SUCCESSED,roomId:r.getRoomId(),userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS}):(e.logger.warn(i.L_RTC_CLIENT_LEAVE_LIVING_ROOM_AS_AUDIENCE_R,{status:s.FAILED,code:"",msg:"Room does not exist, whiout leave"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS})}))}upgradeToAnchorRoom(o){return t(this,void 0,void 0,(function*(){if(!e.validate("room",o,(()=>o instanceof Kr),!0))return e.logger.error(i.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(e.logger.info(i.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_T,{roomId:o.getRoomId(),userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),this._crtRoom)return e.logger.error(i.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const t=o.getRoomId(),n=this._crtRoom=new br(this._context,this._runtime,t,this._service,this._options,o.livingType,!0,!0,!1,o.getClientSessionId()),a=yield n.__innerInitByIdentityChange();return a!==e.ErrorCode.SUCCESS?(r.warn(`change room identity failed -> code: ${a}`),this._crtRoom=null,e.logger.error(i.L_RTC_CLIENT_UPGRADE_TO_ANCHOR_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):(n.once(gr,(()=>{this._crtRoom=null})),yield this._crtAudienceLivingRoom.__destroy(!1),this._crtAudienceLivingRoom=null,{room:n,code:exports.RCRTCCode.SUCCESS,userIds:n.getRemoteUserIds(),tracks:n.getRemoteTracks()})}))}downgradeToAudienceRoom(o){return t(this,void 0,void 0,(function*(){if(e.logger.info(i.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_T,{roomId:o._roomId,userId:this._context.getCurrentId()},{logSource:e.LogSource.RTC}),!o.isMainRoom())return r.error("the `downgradeToAudienceRoom` is disabled in PK room"),e.logger.error(i.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM,msg:"method not available in room"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!e.validate("room._roomId",o._roomId,e.notEmptyString,!0))return e.logger.error(i.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.PARAMS_ERROR,msg:"params error -> room._roomId"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return e.logger.error(i.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.REPERT_JOIN_ROOM,msg:"Join the room repeatedly"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const{code:t,data:n}=yield this._context.rtcIdentityChange(o._roomId,e.RTCIdentityChangeType.AnchorToViewer,o.getLivingType());if(t!==e.ErrorCode.SUCCESS)return r.error("change room identity error",t),e.logger.error(i.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:s.FAILED,code:exports.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED,msg:"Switch identity error"},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};r.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(n)}`),e.logger.info(i.L_RTC_CLIENT_DOWNGRADE_TO_AUDIENCE_ROOM_R,{status:s.SUCCESSED,roomData:n},{logSource:e.LogSource.RTC});const a=o.getClientSessionId(),c=new Kr(this._context,this._runtime,this._options,o._roomId,n,o.getLivingType(),!1,a);return this._crtAudienceLivingRoom=c,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:c,code:exports.RCRTCCode.SUCCESS,userIds:c.getRemoteUserIds(),RTCTracks:c.getRemoteRTCTracks(),MCUTracks:c.getRemoteMCUTracks(),CDNUris:c.getCDNInfo()}}))}getJoinedRoomInfo(){return t(this,void 0,void 0,(function*(){const{code:t,data:o}=yield this._context.getRTCJoinedUserInfo(this._context.getCurrentId());return t!==e.ErrorCode.SUCCESS?(r.error("getJoinedUserInfo error",t),e.logger.error(i.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:s.FAILED,code:t,msg:"Switch identity error"},{logSource:e.LogSource.RTC}),{code:t}):(e.logger.info(i.L_RTC_CLIENT_GET_JOINED_ROOM_INFO_O,{status:s.SUCCESSED,roomInfo:o},{logSource:e.LogSource.RTC}),{code:exports.RCRTCCode.SUCCESS,data:o})}))}}var Jr;exports.RCKickReason=void 0,(Jr=exports.RCKickReason||(exports.RCKickReason={}))[Jr.SERVER_KICK=1]="SERVER_KICK",Jr[Jr.OTHER_KICK=2]="OTHER_KICK";const Wr={tag:"RCRTC",verify:t=>"browser"!==t.tag?(r.error(`RCRTC Plugin is not support the runtime '${t.tag}'`),!1):ze?(e.VersionManage.add("plugin-rtc","5.4.3"),!!e.VersionManage.validEngine(">=5.3.3-beem-alpha.2 || >=5.3.4")||(r.error(`The current engine version '${e.VersionManage.getInfo().engine}' error, plugin-rtc required engine version at least '>=5.3.3-beem-alpha.2 || >=5.3.4'.`),!1)):(r.error("Please use the https protocol or use `http://localhost` to open the page!"),!1),setup:(t,o,i={})=>(r.setLogLevel(i.logLevel),r.setLogStdout(i.logStdout),r.warn("RCRTC Version: 5.4.3, Commit: 14f0acc9bca79c93547703c573d297dbd301594c"),r.warn(`browserInfo.browser -> ${_t.browser}`),r.warn(`browserInfo.supportsUnifiedPlan -> ${_t.supportsUnifiedPlan}`),r.warn(`browserInfo.version -> ${_t.version}`),e.assert("options.mediaServer",i.mediaServer,(t=>!(!e.isHttpUrl(t)||"https:"===location.protocol&&!/^https/.test(t)))),e.assert("options.timeout",i.timeout,(t=>e.isNumber(t)&&t>=5e3&&t<=3e4)),e.assert("options.pingGap",i.pingGap,(t=>e.isNumber(t)&&t>=3e3&&t<=1e4)),new jr(t,o,i))},Yr={transResolution:nt,transFrameRate:dt,parseTrackId:tt,ifSupportLocalFileTrack:ut,ifSupportScreenShare:lt};Object.defineProperty(exports,"RTCJoinType",{enumerable:!0,get:function(){return e.RTCJoinType}}),exports.RCAbstractRoom=mr,exports.RCAudienceClient=wr,exports.RCAudienceLivingRoom=Kr,exports.RCCameraVideoTrack=$e,exports.RCLivingRoom=br,exports.RCLocalAudioTrack=be,exports.RCLocalFileAudioTrack=we,exports.RCLocalFileTrack=Be,exports.RCLocalFileVideoTrack=Ve,exports.RCLocalTrack=Me,exports.RCLocalVideoTrack=xe,exports.RCMCUConfigBuilder=vr,exports.RCMediaStreamCapture=Hr,exports.RCMicphoneAudioTrack=Fe,exports.RCRTCClient=jr,exports.RCRTCRoom=xr,exports.RCRemoteAudioTrack=je,exports.RCRemoteTrack=He,exports.RCRemoteVideoTrack=Je,exports.RCScreenAudioTrack=Ke,exports.RCScreenVideoTrack=Ge,exports.RCTag={DEFAULT:"RongCloudRTC"},exports.RCTrack=ke,exports.device=Ae,exports.helper=Yr,exports.installer=Wr;