data_channel_observer.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include "pch.h"
  2. #include "../common/comm.h"
  3. #include "data_channel_observer.h"
  4. using RtcDataState = webrtc::DataChannelInterface::DataState;
  5. using ApiDataState = DataChannelState;
  6. inline ApiDataState apiStateFromRtcState(RtcDataState rtcState) {
  7. // API values have been chosen to match the current WebRTC values. If the
  8. // later change, this helper must be updated, as API values cannot change.
  9. assert((int)RtcDataState::kOpen == (int)ApiDataState::kOpen);
  10. assert((int)RtcDataState::kConnecting ==
  11. (int)ApiDataState::kConnecting);
  12. assert((int)RtcDataState::kClosing == (int)ApiDataState::kClosing);
  13. assert((int)RtcDataState::kClosed == (int)ApiDataState::kClosed);
  14. return (ApiDataState)rtcState;
  15. }
  16. DataChannelObserver::DataChannelObserver(
  17. rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel)
  18. : data_channel_(std::move(data_channel)) {}
  19. void DataChannelObserver::OnStateChange() {
  20. std::lock_guard<std::mutex> lock{ mutex_ };
  21. if (!state_callback_)
  22. return;
  23. auto apiState = apiStateFromRtcState(data_channel_->state());
  24. state_callback_((int)apiState, data_channel_->id());
  25. }
  26. void DataChannelObserver::OnMessage(const webrtc::DataBuffer& buffer) {
  27. std::lock_guard<std::mutex> lock{ mutex_ };
  28. if (!message_callback_)
  29. return;
  30. message_callback_(buffer.data.data(), buffer.data.size());
  31. }
  32. void DataChannelObserver::OnBufferedAmountChange(
  33. uint64_t previous_amount) {
  34. std::lock_guard<std::mutex> lock{ mutex_ };
  35. if (!buffering_callback_)
  36. return;
  37. uint64_t current_amount = data_channel_->buffered_amount();
  38. constexpr uint64_t max_capacity =
  39. 0x1000000; // 16MB, see DataChannelInterface
  40. buffering_callback_(previous_amount, current_amount, max_capacity);
  41. }