channel.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /**
  2. * Copyright (c) 2019-2021 Paul-Louis Ageneau
  3. *
  4. * This Source Code Form is subject to the terms of the Mozilla Public
  5. * License, v. 2.0. If a copy of the MPL was not distributed with this
  6. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  7. */
  8. #include "channel.hpp"
  9. #include "internals.hpp"
  10. namespace rtc::impl {
  11. void Channel::triggerOpen() {
  12. mOpenTriggered = true;
  13. try {
  14. openCallback();
  15. } catch (const std::exception &e) {
  16. PLOG_WARNING << "Uncaught exception in callback: " << e.what();
  17. }
  18. flushPendingMessages();
  19. }
  20. void Channel::triggerClosed() {
  21. try {
  22. closedCallback();
  23. } catch (const std::exception &e) {
  24. PLOG_WARNING << "Uncaught exception in callback: " << e.what();
  25. }
  26. }
  27. void Channel::triggerError(string error) {
  28. try {
  29. errorCallback(std::move(error));
  30. } catch (const std::exception &e) {
  31. PLOG_WARNING << "Uncaught exception in callback: " << e.what();
  32. }
  33. }
  34. void Channel::triggerAvailable(size_t count) {
  35. if (count == 1) {
  36. try {
  37. availableCallback();
  38. } catch (const std::exception &e) {
  39. PLOG_WARNING << "Uncaught exception in callback: " << e.what();
  40. }
  41. }
  42. flushPendingMessages();
  43. }
  44. void Channel::triggerBufferedAmount(size_t amount) {
  45. size_t previous = bufferedAmount.exchange(amount);
  46. size_t threshold = bufferedAmountLowThreshold.load();
  47. if (previous > threshold && amount <= threshold) {
  48. try {
  49. bufferedAmountLowCallback();
  50. } catch (const std::exception &e) {
  51. PLOG_WARNING << "Uncaught exception in callback: " << e.what();
  52. }
  53. }
  54. }
  55. void Channel::flushPendingMessages() {
  56. if (!mOpenTriggered)
  57. return;
  58. while (messageCallback) {
  59. auto next = receive();
  60. if (!next)
  61. break;
  62. try {
  63. messageCallback(*next);
  64. } catch (const std::exception &e) {
  65. PLOG_WARNING << "Uncaught exception in callback: " << e.what();
  66. }
  67. }
  68. }
  69. void Channel::resetOpenCallback() {
  70. mOpenTriggered = false;
  71. openCallback = nullptr;
  72. }
  73. void Channel::resetCallbacks() {
  74. mOpenTriggered = false;
  75. openCallback = nullptr;
  76. closedCallback = nullptr;
  77. errorCallback = nullptr;
  78. availableCallback = nullptr;
  79. bufferedAmountLowCallback = nullptr;
  80. messageCallback = nullptr;
  81. }
  82. } // namespace rtc::impl