You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2446 lines
95 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include "video/video_stream_encoder.h"
  11. #include <algorithm>
  12. #include <array>
  13. #include <limits>
  14. #include <memory>
  15. #include <numeric>
  16. #include <utility>
  17. #include "absl/algorithm/container.h"
  18. #include "api/video/encoded_image.h"
  19. #include "api/video/i420_buffer.h"
  20. #include "api/video/video_bitrate_allocator_factory.h"
  21. #include "api/video/video_codec_constants.h"
  22. #include "api/video_codecs/video_encoder.h"
  23. #include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
  24. #include "modules/video_coding/include/video_codec_initializer.h"
  25. #include "modules/video_coding/utility/default_video_bitrate_allocator.h"
  26. #include "rtc_base/arraysize.h"
  27. #include "rtc_base/checks.h"
  28. #include "rtc_base/experiments/alr_experiment.h"
  29. #include "rtc_base/experiments/quality_scaling_experiment.h"
  30. #include "rtc_base/experiments/rate_control_settings.h"
  31. #include "rtc_base/location.h"
  32. #include "rtc_base/logging.h"
  33. #include "rtc_base/strings/string_builder.h"
  34. #include "rtc_base/system/fallthrough.h"
  35. #include "rtc_base/time_utils.h"
  36. #include "rtc_base/trace_event.h"
  37. #include "system_wrappers/include/field_trial.h"
  38. namespace webrtc {
  39. namespace {
  40. // Time interval for logging frame counts.
  41. const int64_t kFrameLogIntervalMs = 60000;
  42. const int kMinFramerateFps = 2;
  43. // Time to keep a single cached pending frame in paused state.
  44. const int64_t kPendingFrameTimeoutMs = 1000;
  45. const char kInitialFramedropFieldTrial[] = "WebRTC-InitialFramedrop";
  46. constexpr char kFrameDropperFieldTrial[] = "WebRTC-FrameDropper";
  47. // The maximum number of frames to drop at beginning of stream
  48. // to try and achieve desired bitrate.
  49. const int kMaxInitialFramedrop = 4;
  50. // When the first change in BWE above this threshold occurs,
  51. // enable DropFrameDueToSize logic.
  52. const float kFramedropThreshold = 0.3;
  53. // Averaging window spanning 90 frames at default 30fps, matching old media
  54. // optimization module defaults.
  55. const int64_t kFrameRateAvergingWindowSizeMs = (1000 / 30) * 90;
  56. const size_t kDefaultPayloadSize = 1440;
  57. const int64_t kParameterUpdateIntervalMs = 1000;
  58. uint32_t abs_diff(uint32_t a, uint32_t b) {
  59. return (a < b) ? b - a : a - b;
  60. }
  61. bool IsResolutionScalingEnabled(DegradationPreference degradation_preference) {
  62. return degradation_preference == DegradationPreference::MAINTAIN_FRAMERATE ||
  63. degradation_preference == DegradationPreference::BALANCED;
  64. }
  65. bool IsFramerateScalingEnabled(DegradationPreference degradation_preference) {
  66. return degradation_preference == DegradationPreference::MAINTAIN_RESOLUTION ||
  67. degradation_preference == DegradationPreference::BALANCED;
  68. }
  69. // TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
  70. // pipelining encoders better (multiple input frames before something comes
  71. // out). This should effectively turn off CPU adaptations for systems that
  72. // remotely cope with the load right now.
  73. CpuOveruseOptions GetCpuOveruseOptions(
  74. const VideoStreamEncoderSettings& settings,
  75. bool full_overuse_time) {
  76. CpuOveruseOptions options;
  77. if (full_overuse_time) {
  78. options.low_encode_usage_threshold_percent = 150;
  79. options.high_encode_usage_threshold_percent = 200;
  80. }
  81. if (settings.experiment_cpu_load_estimator) {
  82. options.filter_time_ms = 5 * rtc::kNumMillisecsPerSec;
  83. }
  84. return options;
  85. }
  86. bool RequiresEncoderReset(const VideoCodec& prev_send_codec,
  87. const VideoCodec& new_send_codec,
  88. bool was_encode_called_since_last_initialization) {
  89. // Does not check max/minBitrate or maxFramerate.
  90. if (new_send_codec.codecType != prev_send_codec.codecType ||
  91. new_send_codec.width != prev_send_codec.width ||
  92. new_send_codec.height != prev_send_codec.height ||
  93. new_send_codec.qpMax != prev_send_codec.qpMax ||
  94. new_send_codec.numberOfSimulcastStreams !=
  95. prev_send_codec.numberOfSimulcastStreams ||
  96. new_send_codec.mode != prev_send_codec.mode) {
  97. return true;
  98. }
  99. if (!was_encode_called_since_last_initialization &&
  100. (new_send_codec.startBitrate != prev_send_codec.startBitrate)) {
  101. // If start bitrate has changed reconfigure encoder only if encoding had not
  102. // yet started.
  103. return true;
  104. }
  105. switch (new_send_codec.codecType) {
  106. case kVideoCodecVP8:
  107. if (new_send_codec.VP8() != prev_send_codec.VP8()) {
  108. return true;
  109. }
  110. break;
  111. case kVideoCodecVP9:
  112. if (new_send_codec.VP9() != prev_send_codec.VP9()) {
  113. return true;
  114. }
  115. break;
  116. case kVideoCodecH264:
  117. if (new_send_codec.H264() != prev_send_codec.H264()) {
  118. return true;
  119. }
  120. break;
  121. default:
  122. break;
  123. }
  124. for (unsigned char i = 0; i < new_send_codec.numberOfSimulcastStreams; ++i) {
  125. if (new_send_codec.simulcastStream[i].width !=
  126. prev_send_codec.simulcastStream[i].width ||
  127. new_send_codec.simulcastStream[i].height !=
  128. prev_send_codec.simulcastStream[i].height ||
  129. new_send_codec.simulcastStream[i].numberOfTemporalLayers !=
  130. prev_send_codec.simulcastStream[i].numberOfTemporalLayers ||
  131. new_send_codec.simulcastStream[i].qpMax !=
  132. prev_send_codec.simulcastStream[i].qpMax ||
  133. new_send_codec.simulcastStream[i].active !=
  134. prev_send_codec.simulcastStream[i].active) {
  135. return true;
  136. }
  137. }
  138. return false;
  139. }
  140. std::array<uint8_t, 2> GetExperimentGroups() {
  141. std::array<uint8_t, 2> experiment_groups;
  142. absl::optional<AlrExperimentSettings> experiment_settings =
  143. AlrExperimentSettings::CreateFromFieldTrial(
  144. AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
  145. if (experiment_settings) {
  146. experiment_groups[0] = experiment_settings->group_id + 1;
  147. } else {
  148. experiment_groups[0] = 0;
  149. }
  150. experiment_settings = AlrExperimentSettings::CreateFromFieldTrial(
  151. AlrExperimentSettings::kScreenshareProbingBweExperimentName);
  152. if (experiment_settings) {
  153. experiment_groups[1] = experiment_settings->group_id + 1;
  154. } else {
  155. experiment_groups[1] = 0;
  156. }
  157. return experiment_groups;
  158. }
  159. // Limit allocation across TLs in bitrate allocation according to number of TLs
  160. // in EncoderInfo.
  161. VideoBitrateAllocation UpdateAllocationFromEncoderInfo(
  162. const VideoBitrateAllocation& allocation,
  163. const VideoEncoder::EncoderInfo& encoder_info) {
  164. if (allocation.get_sum_bps() == 0) {
  165. return allocation;
  166. }
  167. VideoBitrateAllocation new_allocation;
  168. for (int si = 0; si < kMaxSpatialLayers; ++si) {
  169. if (encoder_info.fps_allocation[si].size() == 1 &&
  170. allocation.IsSpatialLayerUsed(si)) {
  171. // One TL is signalled to be used by the encoder. Do not distribute
  172. // bitrate allocation across TLs (use sum at ti:0).
  173. new_allocation.SetBitrate(si, 0, allocation.GetSpatialLayerSum(si));
  174. } else {
  175. for (int ti = 0; ti < kMaxTemporalStreams; ++ti) {
  176. if (allocation.HasBitrate(si, ti))
  177. new_allocation.SetBitrate(si, ti, allocation.GetBitrate(si, ti));
  178. }
  179. }
  180. }
  181. return new_allocation;
  182. }
  183. } // namespace
  184. // VideoSourceProxy is responsible ensuring thread safety between calls to
  185. // VideoStreamEncoder::SetSource that will happen on libjingle's worker thread
  186. // when a video capturer is connected to the encoder and the encoder task queue
  187. // (encoder_queue_) where the encoder reports its VideoSinkWants.
  188. class VideoStreamEncoder::VideoSourceProxy {
  189. public:
  190. explicit VideoSourceProxy(VideoStreamEncoder* video_stream_encoder)
  191. : video_stream_encoder_(video_stream_encoder),
  192. degradation_preference_(DegradationPreference::DISABLED),
  193. source_(nullptr),
  194. max_framerate_(std::numeric_limits<int>::max()) {}
  195. void SetSource(rtc::VideoSourceInterface<VideoFrame>* source,
  196. const DegradationPreference& degradation_preference) {
  197. // Called on libjingle's worker thread.
  198. RTC_DCHECK_RUN_ON(&main_checker_);
  199. rtc::VideoSourceInterface<VideoFrame>* old_source = nullptr;
  200. rtc::VideoSinkWants wants;
  201. {
  202. rtc::CritScope lock(&crit_);
  203. degradation_preference_ = degradation_preference;
  204. old_source = source_;
  205. source_ = source;
  206. wants = GetActiveSinkWantsInternal();
  207. }
  208. if (old_source != source && old_source != nullptr) {
  209. old_source->RemoveSink(video_stream_encoder_);
  210. }
  211. if (!source) {
  212. return;
  213. }
  214. source->AddOrUpdateSink(video_stream_encoder_, wants);
  215. }
  216. void SetMaxFramerate(int max_framerate) {
  217. RTC_DCHECK_GT(max_framerate, 0);
  218. rtc::CritScope lock(&crit_);
  219. if (max_framerate == max_framerate_)
  220. return;
  221. RTC_LOG(LS_INFO) << "Set max framerate: " << max_framerate;
  222. max_framerate_ = max_framerate;
  223. if (source_) {
  224. source_->AddOrUpdateSink(video_stream_encoder_,
  225. GetActiveSinkWantsInternal());
  226. }
  227. }
  228. void SetWantsRotationApplied(bool rotation_applied) {
  229. rtc::CritScope lock(&crit_);
  230. sink_wants_.rotation_applied = rotation_applied;
  231. if (source_) {
  232. source_->AddOrUpdateSink(video_stream_encoder_,
  233. GetActiveSinkWantsInternal());
  234. }
  235. }
  236. rtc::VideoSinkWants GetActiveSinkWants() {
  237. rtc::CritScope lock(&crit_);
  238. return GetActiveSinkWantsInternal();
  239. }
  240. void ResetPixelFpsCount() {
  241. rtc::CritScope lock(&crit_);
  242. sink_wants_.max_pixel_count = std::numeric_limits<int>::max();
  243. sink_wants_.target_pixel_count.reset();
  244. sink_wants_.max_framerate_fps = std::numeric_limits<int>::max();
  245. if (source_)
  246. source_->AddOrUpdateSink(video_stream_encoder_,
  247. GetActiveSinkWantsInternal());
  248. }
  249. bool RequestResolutionLowerThan(int pixel_count,
  250. int min_pixels_per_frame,
  251. bool* min_pixels_reached) {
  252. // Called on the encoder task queue.
  253. rtc::CritScope lock(&crit_);
  254. if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
  255. // This can happen since |degradation_preference_| is set on libjingle's
  256. // worker thread but the adaptation is done on the encoder task queue.
  257. return false;
  258. }
  259. // The input video frame size will have a resolution less than or equal to
  260. // |max_pixel_count| depending on how the source can scale the frame size.
  261. const int pixels_wanted = (pixel_count * 3) / 5;
  262. if (pixels_wanted >= sink_wants_.max_pixel_count) {
  263. return false;
  264. }
  265. if (pixels_wanted < min_pixels_per_frame) {
  266. *min_pixels_reached = true;
  267. return false;
  268. }
  269. RTC_LOG(LS_INFO) << "Scaling down resolution, max pixels: "
  270. << pixels_wanted;
  271. sink_wants_.max_pixel_count = pixels_wanted;
  272. sink_wants_.target_pixel_count = absl::nullopt;
  273. source_->AddOrUpdateSink(video_stream_encoder_,
  274. GetActiveSinkWantsInternal());
  275. return true;
  276. }
  277. int RequestFramerateLowerThan(int fps) {
  278. // Called on the encoder task queue.
  279. // The input video frame rate will be scaled down to 2/3, rounding down.
  280. int framerate_wanted = (fps * 2) / 3;
  281. return RestrictFramerate(framerate_wanted) ? framerate_wanted : -1;
  282. }
  283. int GetHigherResolutionThan(int pixel_count) const {
  284. // On step down we request at most 3/5 the pixel count of the previous
  285. // resolution, so in order to take "one step up" we request a resolution
  286. // as close as possible to 5/3 of the current resolution. The actual pixel
  287. // count selected depends on the capabilities of the source. In order to
  288. // not take a too large step up, we cap the requested pixel count to be at
  289. // most four time the current number of pixels.
  290. return (pixel_count * 5) / 3;
  291. }
  292. bool RequestHigherResolutionThan(int pixel_count) {
  293. // Called on the encoder task queue.
  294. rtc::CritScope lock(&crit_);
  295. if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
  296. // This can happen since |degradation_preference_| is set on libjingle's
  297. // worker thread but the adaptation is done on the encoder task queue.
  298. return false;
  299. }
  300. int max_pixels_wanted = pixel_count;
  301. if (max_pixels_wanted != std::numeric_limits<int>::max())
  302. max_pixels_wanted = pixel_count * 4;
  303. if (max_pixels_wanted <= sink_wants_.max_pixel_count)
  304. return false;
  305. sink_wants_.max_pixel_count = max_pixels_wanted;
  306. if (max_pixels_wanted == std::numeric_limits<int>::max()) {
  307. // Remove any constraints.
  308. sink_wants_.target_pixel_count.reset();
  309. } else {
  310. sink_wants_.target_pixel_count = GetHigherResolutionThan(pixel_count);
  311. }
  312. RTC_LOG(LS_INFO) << "Scaling up resolution, max pixels: "
  313. << max_pixels_wanted;
  314. source_->AddOrUpdateSink(video_stream_encoder_,
  315. GetActiveSinkWantsInternal());
  316. return true;
  317. }
  318. // Request upgrade in framerate. Returns the new requested frame, or -1 if
  319. // no change requested. Note that maxint may be returned if limits due to
  320. // adaptation requests are removed completely. In that case, consider
  321. // |max_framerate_| to be the current limit (assuming the capturer complies).
  322. int RequestHigherFramerateThan(int fps) {
  323. // Called on the encoder task queue.
  324. // The input frame rate will be scaled up to the last step, with rounding.
  325. int framerate_wanted = fps;
  326. if (fps != std::numeric_limits<int>::max())
  327. framerate_wanted = (fps * 3) / 2;
  328. return IncreaseFramerate(framerate_wanted) ? framerate_wanted : -1;
  329. }
  330. bool RestrictFramerate(int fps) {
  331. // Called on the encoder task queue.
  332. rtc::CritScope lock(&crit_);
  333. if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
  334. return false;
  335. const int fps_wanted = std::max(kMinFramerateFps, fps);
  336. if (fps_wanted >= sink_wants_.max_framerate_fps)
  337. return false;
  338. RTC_LOG(LS_INFO) << "Scaling down framerate: " << fps_wanted;
  339. sink_wants_.max_framerate_fps = fps_wanted;
  340. source_->AddOrUpdateSink(video_stream_encoder_,
  341. GetActiveSinkWantsInternal());
  342. return true;
  343. }
  344. bool IncreaseFramerate(int fps) {
  345. // Called on the encoder task queue.
  346. rtc::CritScope lock(&crit_);
  347. if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
  348. return false;
  349. const int fps_wanted = std::max(kMinFramerateFps, fps);
  350. if (fps_wanted <= sink_wants_.max_framerate_fps)
  351. return false;
  352. RTC_LOG(LS_INFO) << "Scaling up framerate: " << fps_wanted;
  353. sink_wants_.max_framerate_fps = fps_wanted;
  354. source_->AddOrUpdateSink(video_stream_encoder_,
  355. GetActiveSinkWantsInternal());
  356. return true;
  357. }
  358. private:
  359. rtc::VideoSinkWants GetActiveSinkWantsInternal()
  360. RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
  361. rtc::VideoSinkWants wants = sink_wants_;
  362. // Clear any constraints from the current sink wants that don't apply to
  363. // the used degradation_preference.
  364. switch (degradation_preference_) {
  365. case DegradationPreference::BALANCED:
  366. break;
  367. case DegradationPreference::MAINTAIN_FRAMERATE:
  368. wants.max_framerate_fps = std::numeric_limits<int>::max();
  369. break;
  370. case DegradationPreference::MAINTAIN_RESOLUTION:
  371. wants.max_pixel_count = std::numeric_limits<int>::max();
  372. wants.target_pixel_count.reset();
  373. break;
  374. case DegradationPreference::DISABLED:
  375. wants.max_pixel_count = std::numeric_limits<int>::max();
  376. wants.target_pixel_count.reset();
  377. wants.max_framerate_fps = std::numeric_limits<int>::max();
  378. }
  379. // Limit to configured max framerate.
  380. wants.max_framerate_fps = std::min(max_framerate_, wants.max_framerate_fps);
  381. return wants;
  382. }
  383. rtc::CriticalSection crit_;
  384. SequenceChecker main_checker_;
  385. VideoStreamEncoder* const video_stream_encoder_;
  386. rtc::VideoSinkWants sink_wants_ RTC_GUARDED_BY(&crit_);
  387. DegradationPreference degradation_preference_ RTC_GUARDED_BY(&crit_);
  388. rtc::VideoSourceInterface<VideoFrame>* source_ RTC_GUARDED_BY(&crit_);
  389. int max_framerate_ RTC_GUARDED_BY(&crit_);
  390. RTC_DISALLOW_COPY_AND_ASSIGN(VideoSourceProxy);
  391. };
  392. VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings()
  393. : rate_control(),
  394. encoder_target(DataRate::Zero()),
  395. stable_encoder_target(DataRate::Zero()) {}
  396. VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings(
  397. const VideoBitrateAllocation& bitrate,
  398. double framerate_fps,
  399. DataRate bandwidth_allocation,
  400. DataRate encoder_target,
  401. DataRate stable_encoder_target)
  402. : rate_control(bitrate, framerate_fps, bandwidth_allocation),
  403. encoder_target(encoder_target),
  404. stable_encoder_target(stable_encoder_target) {}
  405. bool VideoStreamEncoder::EncoderRateSettings::operator==(
  406. const EncoderRateSettings& rhs) const {
  407. return rate_control == rhs.rate_control &&
  408. encoder_target == rhs.encoder_target &&
  409. stable_encoder_target == rhs.stable_encoder_target;
  410. }
  411. bool VideoStreamEncoder::EncoderRateSettings::operator!=(
  412. const EncoderRateSettings& rhs) const {
  413. return !(*this == rhs);
  414. }
  415. VideoStreamEncoder::VideoStreamEncoder(
  416. Clock* clock,
  417. uint32_t number_of_cores,
  418. VideoStreamEncoderObserver* encoder_stats_observer,
  419. const VideoStreamEncoderSettings& settings,
  420. std::unique_ptr<OveruseFrameDetector> overuse_detector,
  421. TaskQueueFactory* task_queue_factory)
  422. : shutdown_event_(true /* manual_reset */, false),
  423. number_of_cores_(number_of_cores),
  424. initial_framedrop_(0),
  425. initial_framedrop_on_bwe_enabled_(
  426. webrtc::field_trial::IsEnabled(kInitialFramedropFieldTrial)),
  427. quality_scaling_experiment_enabled_(QualityScalingExperiment::Enabled()),
  428. source_proxy_(new VideoSourceProxy(this)),
  429. sink_(nullptr),
  430. settings_(settings),
  431. rate_control_settings_(RateControlSettings::ParseFromFieldTrials()),
  432. quality_scaler_settings_(QualityScalerSettings::ParseFromFieldTrials()),
  433. overuse_detector_(std::move(overuse_detector)),
  434. encoder_stats_observer_(encoder_stats_observer),
  435. encoder_initialized_(false),
  436. max_framerate_(-1),
  437. pending_encoder_reconfiguration_(false),
  438. pending_encoder_creation_(false),
  439. crop_width_(0),
  440. crop_height_(0),
  441. encoder_start_bitrate_bps_(0),
  442. set_start_bitrate_bps_(0),
  443. set_start_bitrate_time_ms_(0),
  444. has_seen_first_bwe_drop_(false),
  445. max_data_payload_length_(0),
  446. encoder_paused_and_dropped_frame_(false),
  447. was_encode_called_since_last_initialization_(false),
  448. encoder_failed_(false),
  449. clock_(clock),
  450. degradation_preference_(DegradationPreference::DISABLED),
  451. posted_frames_waiting_for_encode_(0),
  452. last_captured_timestamp_(0),
  453. delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
  454. clock_->TimeInMilliseconds()),
  455. last_frame_log_ms_(clock_->TimeInMilliseconds()),
  456. captured_frame_count_(0),
  457. dropped_frame_count_(0),
  458. pending_frame_post_time_us_(0),
  459. accumulated_update_rect_{0, 0, 0, 0},
  460. bitrate_observer_(nullptr),
  461. fec_controller_override_(nullptr),
  462. force_disable_frame_dropper_(false),
  463. input_framerate_(kFrameRateAvergingWindowSizeMs, 1000),
  464. pending_frame_drops_(0),
  465. next_frame_types_(1, VideoFrameType::kVideoFrameDelta),
  466. frame_encode_metadata_writer_(this),
  467. experiment_groups_(GetExperimentGroups()),
  468. next_frame_id_(0),
  469. encoder_switch_experiment_(ParseEncoderSwitchFieldTrial()),
  470. encoder_switch_requested_(false),
  471. encoder_queue_(task_queue_factory->CreateTaskQueue(
  472. "EncoderQueue",
  473. TaskQueueFactory::Priority::NORMAL)) {
  474. RTC_DCHECK(encoder_stats_observer);
  475. RTC_DCHECK(overuse_detector_);
  476. RTC_DCHECK_GE(number_of_cores, 1);
  477. for (auto& state : encoder_buffer_state_)
  478. state.fill(std::numeric_limits<int64_t>::max());
  479. }
  480. VideoStreamEncoder::~VideoStreamEncoder() {
  481. RTC_DCHECK_RUN_ON(&thread_checker_);
  482. RTC_DCHECK(shutdown_event_.Wait(0))
  483. << "Must call ::Stop() before destruction.";
  484. }
  485. void VideoStreamEncoder::Stop() {
  486. RTC_DCHECK_RUN_ON(&thread_checker_);
  487. source_proxy_->SetSource(nullptr, DegradationPreference());
  488. encoder_queue_.PostTask([this] {
  489. RTC_DCHECK_RUN_ON(&encoder_queue_);
  490. overuse_detector_->StopCheckForOveruse();
  491. rate_allocator_ = nullptr;
  492. bitrate_observer_ = nullptr;
  493. ReleaseEncoder();
  494. quality_scaler_ = nullptr;
  495. shutdown_event_.Set();
  496. });
  497. shutdown_event_.Wait(rtc::Event::kForever);
  498. }
  499. void VideoStreamEncoder::SetBitrateAllocationObserver(
  500. VideoBitrateAllocationObserver* bitrate_observer) {
  501. RTC_DCHECK_RUN_ON(&thread_checker_);
  502. encoder_queue_.PostTask([this, bitrate_observer] {
  503. RTC_DCHECK_RUN_ON(&encoder_queue_);
  504. RTC_DCHECK(!bitrate_observer_);
  505. bitrate_observer_ = bitrate_observer;
  506. });
  507. }
  508. void VideoStreamEncoder::SetFecControllerOverride(
  509. FecControllerOverride* fec_controller_override) {
  510. encoder_queue_.PostTask([this, fec_controller_override] {
  511. RTC_DCHECK_RUN_ON(&encoder_queue_);
  512. RTC_DCHECK(!fec_controller_override_);
  513. fec_controller_override_ = fec_controller_override;
  514. if (encoder_) {
  515. encoder_->SetFecControllerOverride(fec_controller_override_);
  516. }
  517. });
  518. }
  519. void VideoStreamEncoder::SetSource(
  520. rtc::VideoSourceInterface<VideoFrame>* source,
  521. const DegradationPreference& degradation_preference) {
  522. RTC_DCHECK_RUN_ON(&thread_checker_);
  523. source_proxy_->SetSource(source, degradation_preference);
  524. encoder_queue_.PostTask([this, degradation_preference] {
  525. RTC_DCHECK_RUN_ON(&encoder_queue_);
  526. if (degradation_preference_ != degradation_preference) {
  527. // Reset adaptation state, so that we're not tricked into thinking there's
  528. // an already pending request of the same type.
  529. last_adaptation_request_.reset();
  530. if (degradation_preference == DegradationPreference::BALANCED ||
  531. degradation_preference_ == DegradationPreference::BALANCED) {
  532. // TODO(asapersson): Consider removing |adapt_counters_| map and use one
  533. // AdaptCounter for all modes.
  534. source_proxy_->ResetPixelFpsCount();
  535. adapt_counters_.clear();
  536. }
  537. }
  538. degradation_preference_ = degradation_preference;
  539. if (encoder_)
  540. ConfigureQualityScaler(encoder_->GetEncoderInfo());
  541. if (!IsFramerateScalingEnabled(degradation_preference) &&
  542. max_framerate_ != -1) {
  543. // If frame rate scaling is no longer allowed, remove any potential
  544. // allowance for longer frame intervals.
  545. overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
  546. }
  547. });
  548. }
  549. void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
  550. source_proxy_->SetWantsRotationApplied(rotation_applied);
  551. encoder_queue_.PostTask([this, sink] {
  552. RTC_DCHECK_RUN_ON(&encoder_queue_);
  553. sink_ = sink;
  554. });
  555. }
  556. void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
  557. encoder_queue_.PostTask([this, start_bitrate_bps] {
  558. RTC_DCHECK_RUN_ON(&encoder_queue_);
  559. encoder_start_bitrate_bps_ = start_bitrate_bps;
  560. set_start_bitrate_bps_ = start_bitrate_bps;
  561. set_start_bitrate_time_ms_ = clock_->TimeInMilliseconds();
  562. });
  563. }
  564. void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
  565. size_t max_data_payload_length) {
  566. encoder_queue_.PostTask(
  567. [this, config = std::move(config), max_data_payload_length]() mutable {
  568. RTC_DCHECK_RUN_ON(&encoder_queue_);
  569. RTC_DCHECK(sink_);
  570. RTC_LOG(LS_INFO) << "ConfigureEncoder requested.";
  571. pending_encoder_creation_ =
  572. (!encoder_ || encoder_config_.video_format != config.video_format ||
  573. max_data_payload_length_ != max_data_payload_length);
  574. encoder_config_ = std::move(config);
  575. max_data_payload_length_ = max_data_payload_length;
  576. pending_encoder_reconfiguration_ = true;
  577. // Reconfigure the encoder now if the encoder has an internal source or
  578. // if the frame resolution is known. Otherwise, the reconfiguration is
  579. // deferred until the next frame to minimize the number of
  580. // reconfigurations. The codec configuration depends on incoming video
  581. // frame size.
  582. if (last_frame_info_) {
  583. ReconfigureEncoder();
  584. } else {
  585. codec_info_ = settings_.encoder_factory->QueryVideoEncoder(
  586. encoder_config_.video_format);
  587. if (HasInternalSource()) {
  588. last_frame_info_ = VideoFrameInfo(176, 144, false);
  589. ReconfigureEncoder();
  590. }
  591. }
  592. });
  593. }
  594. static absl::optional<VideoEncoder::ResolutionBitrateLimits>
  595. GetEncoderBitrateLimits(const VideoEncoder::EncoderInfo& encoder_info,
  596. int frame_size_pixels) {
  597. std::vector<VideoEncoder::ResolutionBitrateLimits> bitrate_limits =
  598. encoder_info.resolution_bitrate_limits;
  599. // Sort the list of bitrate limits by resolution.
  600. sort(bitrate_limits.begin(), bitrate_limits.end(),
  601. [](const VideoEncoder::ResolutionBitrateLimits& lhs,
  602. const VideoEncoder::ResolutionBitrateLimits& rhs) {
  603. return lhs.frame_size_pixels < rhs.frame_size_pixels;
  604. });
  605. for (size_t i = 0; i < bitrate_limits.size(); ++i) {
  606. RTC_DCHECK_GT(bitrate_limits[i].min_bitrate_bps, 0);
  607. RTC_DCHECK_GE(bitrate_limits[i].min_start_bitrate_bps,
  608. bitrate_limits[i].min_bitrate_bps);
  609. RTC_DCHECK_GT(bitrate_limits[i].max_bitrate_bps,
  610. bitrate_limits[i].min_start_bitrate_bps);
  611. if (i > 0) {
  612. // The bitrate limits aren't expected to decrease with resolution.
  613. RTC_DCHECK_GE(bitrate_limits[i].min_bitrate_bps,
  614. bitrate_limits[i - 1].min_bitrate_bps);
  615. RTC_DCHECK_GE(bitrate_limits[i].min_start_bitrate_bps,
  616. bitrate_limits[i - 1].min_start_bitrate_bps);
  617. RTC_DCHECK_GE(bitrate_limits[i].max_bitrate_bps,
  618. bitrate_limits[i - 1].max_bitrate_bps);
  619. }
  620. if (bitrate_limits[i].frame_size_pixels >= frame_size_pixels) {
  621. return absl::optional<VideoEncoder::ResolutionBitrateLimits>(
  622. bitrate_limits[i]);
  623. }
  624. }
  625. return absl::nullopt;
  626. }
  627. // TODO(bugs.webrtc.org/8807): Currently this always does a hard
  628. // reconfiguration, but this isn't always necessary. Add in logic to only update
  629. // the VideoBitrateAllocator and call OnEncoderConfigurationChanged with a
  630. // "soft" reconfiguration.
  631. void VideoStreamEncoder::ReconfigureEncoder() {
  632. RTC_DCHECK(pending_encoder_reconfiguration_);
  633. if (encoder_switch_experiment_.IsPixelCountBelowThreshold(
  634. last_frame_info_->width * last_frame_info_->height) &&
  635. !encoder_switch_requested_ && settings_.encoder_switch_request_callback) {
  636. EncoderSwitchRequestCallback::Config conf;
  637. conf.codec_name = encoder_switch_experiment_.to_codec;
  638. conf.param = encoder_switch_experiment_.to_param;
  639. conf.value = encoder_switch_experiment_.to_value;
  640. settings_.encoder_switch_request_callback->RequestEncoderSwitch(conf);
  641. encoder_switch_requested_ = true;
  642. }
  643. std::vector<VideoStream> streams =
  644. encoder_config_.video_stream_factory->CreateEncoderStreams(
  645. last_frame_info_->width, last_frame_info_->height, encoder_config_);
  646. // TODO(ilnik): If configured resolution is significantly less than provided,
  647. // e.g. because there are not enough SSRCs for all simulcast streams,
  648. // signal new resolutions via SinkWants to video source.
  649. // Stream dimensions may be not equal to given because of a simulcast
  650. // restrictions.
  651. auto highest_stream = absl::c_max_element(
  652. streams, [](const webrtc::VideoStream& a, const webrtc::VideoStream& b) {
  653. return std::tie(a.width, a.height) < std::tie(b.width, b.height);
  654. });
  655. int highest_stream_width = static_cast<int>(highest_stream->width);
  656. int highest_stream_height = static_cast<int>(highest_stream->height);
  657. // Dimension may be reduced to be, e.g. divisible by 4.
  658. RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
  659. RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
  660. crop_width_ = last_frame_info_->width - highest_stream_width;
  661. crop_height_ = last_frame_info_->height - highest_stream_height;
  662. bool encoder_reset_required = false;
  663. if (pending_encoder_creation_) {
  664. // Destroy existing encoder instance before creating a new one. Otherwise
  665. // attempt to create another instance will fail if encoder factory
  666. // supports only single instance of encoder of given type.
  667. encoder_.reset();
  668. encoder_ = settings_.encoder_factory->CreateVideoEncoder(
  669. encoder_config_.video_format);
  670. // TODO(nisse): What to do if creating the encoder fails? Crash,
  671. // or just discard incoming frames?
  672. RTC_CHECK(encoder_);
  673. encoder_->SetFecControllerOverride(fec_controller_override_);
  674. codec_info_ = settings_.encoder_factory->QueryVideoEncoder(
  675. encoder_config_.video_format);
  676. encoder_reset_required = true;
  677. }
  678. encoder_bitrate_limits_ = GetEncoderBitrateLimits(
  679. encoder_->GetEncoderInfo(),
  680. last_frame_info_->width * last_frame_info_->height);
  681. if (streams.size() == 1 && encoder_bitrate_limits_) {
  682. // Use bitrate limits recommended by encoder only if app didn't set any of
  683. // them.
  684. if (encoder_config_.max_bitrate_bps <= 0 &&
  685. (encoder_config_.simulcast_layers.empty() ||
  686. encoder_config_.simulcast_layers[0].min_bitrate_bps <= 0)) {
  687. streams.back().min_bitrate_bps = encoder_bitrate_limits_->min_bitrate_bps;
  688. streams.back().max_bitrate_bps = encoder_bitrate_limits_->max_bitrate_bps;
  689. streams.back().target_bitrate_bps =
  690. std::min(streams.back().target_bitrate_bps,
  691. encoder_bitrate_limits_->max_bitrate_bps);
  692. }
  693. }
  694. VideoCodec codec;
  695. if (!VideoCodecInitializer::SetupCodec(encoder_config_, streams, &codec)) {
  696. RTC_LOG(LS_ERROR) << "Failed to create encoder configuration.";
  697. }
  698. // Set min_bitrate_bps, max_bitrate_bps, and max padding bit rate for VP9.
  699. if (encoder_config_.codec_type == kVideoCodecVP9) {
  700. // Lower max bitrate to the level codec actually can produce.
  701. streams[0].max_bitrate_bps =
  702. std::min(streams[0].max_bitrate_bps,
  703. SvcRateAllocator::GetMaxBitrate(codec).bps<int>());
  704. streams[0].min_bitrate_bps = codec.spatialLayers[0].minBitrate * 1000;
  705. // target_bitrate_bps specifies the maximum padding bitrate.
  706. streams[0].target_bitrate_bps =
  707. SvcRateAllocator::GetPaddingBitrate(codec).bps<int>();
  708. }
  709. char log_stream_buf[4 * 1024];
  710. rtc::SimpleStringBuilder log_stream(log_stream_buf);
  711. log_stream << "ReconfigureEncoder:\n";
  712. log_stream << "Simulcast streams:\n";
  713. for (size_t i = 0; i < codec.numberOfSimulcastStreams; ++i) {
  714. log_stream << i << ": " << codec.simulcastStream[i].width << "x"
  715. << codec.simulcastStream[i].height
  716. << " fps: " << codec.simulcastStream[i].maxFramerate
  717. << " min_bps: " << codec.simulcastStream[i].minBitrate
  718. << " target_bps: " << codec.simulcastStream[i].targetBitrate
  719. << " max_bps: " << codec.simulcastStream[i].maxBitrate
  720. << " max_qp: " << codec.simulcastStream[i].qpMax
  721. << " num_tl: " << codec.simulcastStream[i].numberOfTemporalLayers
  722. << " active: "
  723. << (codec.simulcastStream[i].active ? "true" : "false") << "\n";
  724. }
  725. if (encoder_config_.codec_type == kVideoCodecVP9) {
  726. size_t num_spatial_layers = codec.VP9()->numberOfSpatialLayers;
  727. log_stream << "Spatial layers:\n";
  728. for (size_t i = 0; i < num_spatial_layers; ++i) {
  729. log_stream << i << ": " << codec.spatialLayers[i].width << "x"
  730. << codec.spatialLayers[i].height
  731. << " fps: " << codec.spatialLayers[i].maxFramerate
  732. << " min_bps: " << codec.spatialLayers[i].minBitrate
  733. << " target_bps: " << codec.spatialLayers[i].targetBitrate
  734. << " max_bps: " << codec.spatialLayers[i].maxBitrate
  735. << " max_qp: " << codec.spatialLayers[i].qpMax
  736. << " num_tl: " << codec.spatialLayers[i].numberOfTemporalLayers
  737. << " active: "
  738. << (codec.spatialLayers[i].active ? "true" : "false") << "\n";
  739. }
  740. }
  741. RTC_LOG(LS_INFO) << log_stream.str();
  742. codec.startBitrate =
  743. std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
  744. codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
  745. codec.expect_encode_from_texture = last_frame_info_->is_texture;
  746. // Make sure the start bit rate is sane...
  747. RTC_DCHECK_LE(codec.startBitrate, 1000000);
  748. max_framerate_ = codec.maxFramerate;
  749. // Inform source about max configured framerate.
  750. int max_framerate = 0;
  751. for (const auto& stream : streams) {
  752. max_framerate = std::max(stream.max_framerate, max_framerate);
  753. }
  754. source_proxy_->SetMaxFramerate(max_framerate);
  755. if (codec.maxBitrate == 0) {
  756. // max is one bit per pixel
  757. codec.maxBitrate =
  758. (static_cast<int>(codec.height) * static_cast<int>(codec.width) *
  759. static_cast<int>(codec.maxFramerate)) /
  760. 1000;
  761. if (codec.startBitrate > codec.maxBitrate) {
  762. // But if the user tries to set a higher start bit rate we will
  763. // increase the max accordingly.
  764. codec.maxBitrate = codec.startBitrate;
  765. }
  766. }
  767. if (codec.startBitrate > codec.maxBitrate) {
  768. codec.startBitrate = codec.maxBitrate;
  769. }
  770. rate_allocator_ =
  771. settings_.bitrate_allocator_factory->CreateVideoBitrateAllocator(codec);
  772. // Reset (release existing encoder) if one exists and anything except
  773. // start bitrate or max framerate has changed.
  774. if (!encoder_reset_required) {
  775. encoder_reset_required = RequiresEncoderReset(
  776. codec, send_codec_, was_encode_called_since_last_initialization_);
  777. }
  778. send_codec_ = codec;
  779. encoder_switch_experiment_.SetCodec(send_codec_.codecType);
  780. // Keep the same encoder, as long as the video_format is unchanged.
  781. // Encoder creation block is split in two since EncoderInfo needed to start
  782. // CPU adaptation with the correct settings should be polled after
  783. // encoder_->InitEncode().
  784. bool success = true;
  785. if (encoder_reset_required) {
  786. ReleaseEncoder();
  787. const size_t max_data_payload_length = max_data_payload_length_ > 0
  788. ? max_data_payload_length_
  789. : kDefaultPayloadSize;
  790. if (encoder_->InitEncode(
  791. &send_codec_,
  792. VideoEncoder::Settings(settings_.capabilities, number_of_cores_,
  793. max_data_payload_length)) != 0) {
  794. RTC_LOG(LS_ERROR) << "Failed to initialize the encoder associated with "
  795. "codec type: "
  796. << CodecTypeToPayloadString(send_codec_.codecType)
  797. << " (" << send_codec_.codecType << ")";
  798. ReleaseEncoder();
  799. success = false;
  800. } else {
  801. encoder_initialized_ = true;
  802. encoder_->RegisterEncodeCompleteCallback(this);
  803. frame_encode_metadata_writer_.OnEncoderInit(send_codec_,
  804. HasInternalSource());
  805. }
  806. frame_encode_metadata_writer_.Reset();
  807. last_encode_info_ms_ = absl::nullopt;
  808. was_encode_called_since_last_initialization_ = false;
  809. }
  810. if (success) {
  811. next_frame_types_.clear();
  812. next_frame_types_.resize(
  813. std::max(static_cast<int>(codec.numberOfSimulcastStreams), 1),
  814. VideoFrameType::kVideoFrameKey);
  815. RTC_LOG(LS_VERBOSE) << " max bitrate " << codec.maxBitrate
  816. << " start bitrate " << codec.startBitrate
  817. << " max frame rate " << codec.maxFramerate
  818. << " max payload size " << max_data_payload_length_;
  819. } else {
  820. RTC_LOG(LS_ERROR) << "Failed to configure encoder.";
  821. rate_allocator_ = nullptr;
  822. }
  823. if (pending_encoder_creation_) {
  824. overuse_detector_->StopCheckForOveruse();
  825. overuse_detector_->StartCheckForOveruse(
  826. &encoder_queue_,
  827. GetCpuOveruseOptions(
  828. settings_, encoder_->GetEncoderInfo().is_hardware_accelerated),
  829. this);
  830. pending_encoder_creation_ = false;
  831. }
  832. int num_layers;
  833. if (codec.codecType == kVideoCodecVP8) {
  834. num_layers = codec.VP8()->numberOfTemporalLayers;
  835. } else if (codec.codecType == kVideoCodecVP9) {
  836. num_layers = codec.VP9()->numberOfTemporalLayers;
  837. } else if (codec.codecType == kVideoCodecH264) {
  838. num_layers = codec.H264()->numberOfTemporalLayers;
  839. } else if (codec.codecType == kVideoCodecGeneric &&
  840. codec.numberOfSimulcastStreams > 0) {
  841. // This is mainly for unit testing, disabling frame dropping.
  842. // TODO(sprang): Add a better way to disable frame dropping.
  843. num_layers = codec.simulcastStream[0].numberOfTemporalLayers;
  844. } else {
  845. num_layers = 1;
  846. }
  847. frame_dropper_.Reset();
  848. frame_dropper_.SetRates(codec.startBitrate, max_framerate_);
  849. // Force-disable frame dropper if either:
  850. // * We have screensharing with layers.
  851. // * "WebRTC-FrameDropper" field trial is "Disabled".
  852. force_disable_frame_dropper_ =
  853. field_trial::IsDisabled(kFrameDropperFieldTrial) ||
  854. (num_layers > 1 && codec.mode == VideoCodecMode::kScreensharing);
  855. VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
  856. if (rate_control_settings_.UseEncoderBitrateAdjuster()) {
  857. bitrate_adjuster_ = std::make_unique<EncoderBitrateAdjuster>(codec);
  858. bitrate_adjuster_->OnEncoderInfo(info);
  859. }
  860. if (rate_allocator_ && last_encoder_rate_settings_) {
  861. // We have a new rate allocator instance and already configured target
  862. // bitrate. Update the rate allocation and notify observers.
  863. // We must invalidate the last_encoder_rate_settings_ to ensure
  864. // the changes get propagated to all listeners.
  865. EncoderRateSettings rate_settings = *last_encoder_rate_settings_;
  866. last_encoder_rate_settings_.reset();
  867. rate_settings.rate_control.framerate_fps = GetInputFramerateFps();
  868. SetEncoderRates(UpdateBitrateAllocationAndNotifyObserver(rate_settings));
  869. }
  870. encoder_stats_observer_->OnEncoderReconfigured(encoder_config_, streams);
  871. pending_encoder_reconfiguration_ = false;
  872. sink_->OnEncoderConfigurationChanged(
  873. std::move(streams), encoder_config_.content_type,
  874. encoder_config_.min_transmit_bitrate_bps);
  875. // Get the current target framerate, ie the maximum framerate as specified by
  876. // the current codec configuration, or any limit imposed by cpu adaption in
  877. // maintain-resolution or balanced mode. This is used to make sure overuse
  878. // detection doesn't needlessly trigger in low and/or variable framerate
  879. // scenarios.
  880. int target_framerate = std::min(
  881. max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
  882. overuse_detector_->OnTargetFramerateUpdated(target_framerate);
  883. ConfigureQualityScaler(info);
  884. }
  885. void VideoStreamEncoder::ConfigureQualityScaler(
  886. const VideoEncoder::EncoderInfo& encoder_info) {
  887. RTC_DCHECK_RUN_ON(&encoder_queue_);
  888. const auto scaling_settings = encoder_info.scaling_settings;
  889. const bool quality_scaling_allowed =
  890. IsResolutionScalingEnabled(degradation_preference_) &&
  891. scaling_settings.thresholds;
  892. if (quality_scaling_allowed) {
  893. if (quality_scaler_ == nullptr) {
  894. // Quality scaler has not already been configured.
  895. // Use experimental thresholds if available.
  896. absl::optional<VideoEncoder::QpThresholds> experimental_thresholds;
  897. if (quality_scaling_experiment_enabled_) {
  898. experimental_thresholds = QualityScalingExperiment::GetQpThresholds(
  899. encoder_config_.codec_type);
  900. }
  901. // Since the interface is non-public, std::make_unique can't do this
  902. // upcast.
  903. AdaptationObserverInterface* observer = this;
  904. quality_scaler_ = std::make_unique<QualityScaler>(
  905. &encoder_queue_, observer,
  906. experimental_thresholds ? *experimental_thresholds
  907. : *(scaling_settings.thresholds));
  908. has_seen_first_significant_bwe_change_ = false;
  909. initial_framedrop_ = 0;
  910. }
  911. } else {
  912. quality_scaler_.reset(nullptr);
  913. initial_framedrop_ = kMaxInitialFramedrop;
  914. }
  915. if (degradation_preference_ == DegradationPreference::BALANCED &&
  916. quality_scaler_ && last_frame_info_) {
  917. absl::optional<VideoEncoder::QpThresholds> thresholds =
  918. balanced_settings_.GetQpThresholds(encoder_config_.codec_type,
  919. last_frame_info_->pixel_count());
  920. if (thresholds) {
  921. quality_scaler_->SetQpThresholds(*thresholds);
  922. }
  923. }
  924. encoder_stats_observer_->OnAdaptationChanged(
  925. VideoStreamEncoderObserver::AdaptationReason::kNone,
  926. GetActiveCounts(kCpu), GetActiveCounts(kQuality));
  927. }
  928. void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
  929. RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
  930. VideoFrame incoming_frame = video_frame;
  931. // Local time in webrtc time base.
  932. int64_t current_time_us = clock_->TimeInMicroseconds();
  933. int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
  934. // In some cases, e.g., when the frame from decoder is fed to encoder,
  935. // the timestamp may be set to the future. As the encoding pipeline assumes
  936. // capture time to be less than present time, we should reset the capture
  937. // timestamps here. Otherwise there may be issues with RTP send stream.
  938. if (incoming_frame.timestamp_us() > current_time_us)
  939. incoming_frame.set_timestamp_us(current_time_us);
  940. // Capture time may come from clock with an offset and drift from clock_.
  941. int64_t capture_ntp_time_ms;
  942. if (video_frame.ntp_time_ms() > 0) {
  943. capture_ntp_time_ms = video_frame.ntp_time_ms();
  944. } else if (video_frame.render_time_ms() != 0) {
  945. capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
  946. } else {
  947. capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
  948. }
  949. incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
  950. // Convert NTP time, in ms, to RTP timestamp.
  951. const int kMsToRtpTimestamp = 90;
  952. incoming_frame.set_timestamp(
  953. kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
  954. if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
  955. // We don't allow the same capture time for two frames, drop this one.
  956. RTC_LOG(LS_WARNING) << "Same/old NTP timestamp ("
  957. << incoming_frame.ntp_time_ms()
  958. << " <= " << last_captured_timestamp_
  959. << ") for incoming frame. Dropping.";
  960. encoder_queue_.PostTask([this, incoming_frame]() {
  961. RTC_DCHECK_RUN_ON(&encoder_queue_);
  962. accumulated_update_rect_.Union(incoming_frame.update_rect());
  963. });
  964. return;
  965. }
  966. bool log_stats = false;
  967. if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
  968. last_frame_log_ms_ = current_time_ms;
  969. log_stats = true;
  970. }
  971. last_captured_timestamp_ = incoming_frame.ntp_time_ms();
  972. int64_t post_time_us = rtc::TimeMicros();
  973. ++posted_frames_waiting_for_encode_;
  974. encoder_queue_.PostTask(
  975. [this, incoming_frame, post_time_us, log_stats]() {
  976. RTC_DCHECK_RUN_ON(&encoder_queue_);
  977. encoder_stats_observer_->OnIncomingFrame(incoming_frame.width(),
  978. incoming_frame.height());
  979. ++captured_frame_count_;
  980. const int posted_frames_waiting_for_encode =
  981. posted_frames_waiting_for_encode_.fetch_sub(1);
  982. RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
  983. if (posted_frames_waiting_for_encode == 1) {
  984. MaybeEncodeVideoFrame(incoming_frame, post_time_us);
  985. } else {
  986. // There is a newer frame in flight. Do not encode this frame.
  987. RTC_LOG(LS_VERBOSE)
  988. << "Incoming frame dropped due to that the encoder is blocked.";
  989. ++dropped_frame_count_;
  990. encoder_stats_observer_->OnFrameDropped(
  991. VideoStreamEncoderObserver::DropReason::kEncoderQueue);
  992. accumulated_update_rect_.Union(incoming_frame.update_rect());
  993. }
  994. if (log_stats) {
  995. RTC_LOG(LS_INFO) << "Number of frames: captured "
  996. << captured_frame_count_
  997. << ", dropped (due to encoder blocked) "
  998. << dropped_frame_count_ << ", interval_ms "
  999. << kFrameLogIntervalMs;
  1000. captured_frame_count_ = 0;
  1001. dropped_frame_count_ = 0;
  1002. }
  1003. });
  1004. }
  1005. void VideoStreamEncoder::OnDiscardedFrame() {
  1006. encoder_stats_observer_->OnFrameDropped(
  1007. VideoStreamEncoderObserver::DropReason::kSource);
  1008. }
  1009. bool VideoStreamEncoder::EncoderPaused() const {
  1010. RTC_DCHECK_RUN_ON(&encoder_queue_);
  1011. // Pause video if paused by caller or as long as the network is down or the
  1012. // pacer queue has grown too large in buffered mode.
  1013. // If the pacer queue has grown too large or the network is down,
  1014. // |last_encoder_rate_settings_->encoder_target| will be 0.
  1015. return !last_encoder_rate_settings_ ||
  1016. last_encoder_rate_settings_->encoder_target == DataRate::Zero();
  1017. }
  1018. void VideoStreamEncoder::TraceFrameDropStart() {
  1019. RTC_DCHECK_RUN_ON(&encoder_queue_);
  1020. // Start trace event only on the first frame after encoder is paused.
  1021. if (!encoder_paused_and_dropped_frame_) {
  1022. TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
  1023. }
  1024. encoder_paused_and_dropped_frame_ = true;
  1025. }
  1026. void VideoStreamEncoder::TraceFrameDropEnd() {
  1027. RTC_DCHECK_RUN_ON(&encoder_queue_);
  1028. // End trace event on first frame after encoder resumes, if frame was dropped.
  1029. if (encoder_paused_and_dropped_frame_) {
  1030. TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
  1031. }
  1032. encoder_paused_and_dropped_frame_ = false;
  1033. }
  1034. VideoStreamEncoder::EncoderRateSettings
  1035. VideoStreamEncoder::UpdateBitrateAllocationAndNotifyObserver(
  1036. const EncoderRateSettings& rate_settings) {
  1037. VideoBitrateAllocation new_allocation;
  1038. // Only call allocators if bitrate > 0 (ie, not suspended), otherwise they
  1039. // might cap the bitrate to the min bitrate configured.
  1040. if (rate_allocator_ && rate_settings.encoder_target > DataRate::Zero()) {
  1041. new_allocation = rate_allocator_->Allocate(VideoBitrateAllocationParameters(
  1042. rate_settings.encoder_target, rate_settings.stable_encoder_target,
  1043. rate_settings.rate_control.framerate_fps));
  1044. }
  1045. if (bitrate_observer_ && new_allocation.get_sum_bps() > 0) {
  1046. if (encoder_ && encoder_initialized_) {
  1047. // Avoid too old encoder_info_.
  1048. const int64_t kMaxDiffMs = 100;
  1049. const bool updated_recently =
  1050. (last_encode_info_ms_ && ((clock_->TimeInMilliseconds() -
  1051. *last_encode_info_ms_) < kMaxDiffMs));
  1052. // Update allocation according to info from encoder.
  1053. bitrate_observer_->OnBitrateAllocationUpdated(
  1054. UpdateAllocationFromEncoderInfo(
  1055. new_allocation,
  1056. updated_recently ? encoder_info_ : encoder_->GetEncoderInfo()));
  1057. } else {
  1058. bitrate_observer_->OnBitrateAllocationUpdated(new_allocation);
  1059. }
  1060. }
  1061. EncoderRateSettings new_rate_settings = rate_settings;
  1062. new_rate_settings.rate_control.bitrate = new_allocation;
  1063. // VideoBitrateAllocator subclasses may allocate a bitrate higher than the
  1064. // target in order to sustain the min bitrate of the video codec. In this
  1065. // case, make sure the bandwidth allocation is at least equal the allocation
  1066. // as that is part of the document contract for that field.
  1067. new_rate_settings.rate_control.bandwidth_allocation = std::max(
  1068. new_rate_settings.rate_control.bandwidth_allocation,
  1069. DataRate::bps(new_rate_settings.rate_control.bitrate.get_sum_bps()));
  1070. if (bitrate_adjuster_) {
  1071. VideoBitrateAllocation adjusted_allocation =
  1072. bitrate_adjuster_->AdjustRateAllocation(new_rate_settings.rate_control);
  1073. RTC_LOG(LS_VERBOSE) << "Adjusting allocation, fps = "
  1074. << rate_settings.rate_control.framerate_fps << ", from "
  1075. << new_allocation.ToString() << ", to "
  1076. << adjusted_allocation.ToString();
  1077. new_rate_settings.rate_control.bitrate = adjusted_allocation;
  1078. }
  1079. encoder_stats_observer_->OnBitrateAllocationUpdated(
  1080. send_codec_, new_rate_settings.rate_control.bitrate);
  1081. return new_rate_settings;
  1082. }
  1083. uint32_t VideoStreamEncoder::GetInputFramerateFps() {
  1084. const uint32_t default_fps = max_framerate_ != -1 ? max_framerate_ : 30;
  1085. absl::optional<uint32_t> input_fps =
  1086. input_framerate_.Rate(clock_->TimeInMilliseconds());
  1087. if (!input_fps || *input_fps == 0) {
  1088. return default_fps;
  1089. }
  1090. return *input_fps;
  1091. }
  1092. void VideoStreamEncoder::SetEncoderRates(
  1093. const EncoderRateSettings& rate_settings) {
  1094. RTC_DCHECK_GT(rate_settings.rate_control.framerate_fps, 0.0);
  1095. bool rate_control_changed =
  1096. (!last_encoder_rate_settings_.has_value() ||
  1097. last_encoder_rate_settings_->rate_control != rate_settings.rate_control);
  1098. if (last_encoder_rate_settings_ != rate_settings) {
  1099. last_encoder_rate_settings_ = rate_settings;
  1100. }
  1101. if (!encoder_) {
  1102. return;
  1103. }
  1104. // |bitrate_allocation| is 0 it means that the network is down or the send
  1105. // pacer is full. We currently only report this if the encoder has an internal
  1106. // source. If the encoder does not have an internal source, higher levels
  1107. // are expected to not call AddVideoFrame. We do this since its unclear
  1108. // how current encoder implementations behave when given a zero target
  1109. // bitrate.
  1110. // TODO(perkj): Make sure all known encoder implementations handle zero
  1111. // target bitrate and remove this check.
  1112. if (!HasInternalSource() &&
  1113. rate_settings.rate_control.bitrate.get_sum_bps() == 0) {
  1114. return;
  1115. }
  1116. if (rate_control_changed) {
  1117. encoder_->SetRates(rate_settings.rate_control);
  1118. frame_encode_metadata_writer_.OnSetRates(
  1119. rate_settings.rate_control.bitrate,
  1120. static_cast<uint32_t>(rate_settings.rate_control.framerate_fps + 0.5));
  1121. }
  1122. }
  1123. void VideoStreamEncoder::MaybeEncodeVideoFrame(const VideoFrame& video_frame,
  1124. int64_t time_when_posted_us) {
  1125. RTC_DCHECK_RUN_ON(&encoder_queue_);
  1126. if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
  1127. video_frame.height() != last_frame_info_->height ||
  1128. video_frame.is_texture() != last_frame_info_->is_texture) {
  1129. pending_encoder_reconfiguration_ = true;
  1130. last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(),
  1131. video_frame.is_texture());
  1132. RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions="
  1133. << last_frame_info_->width << "x"
  1134. << last_frame_info_->height
  1135. << ", texture=" << last_frame_info_->is_texture << ".";
  1136. // Force full frame update, since resolution has changed.
  1137. accumulated_update_rect_ =
  1138. VideoFrame::UpdateRect{0, 0, video_frame.width(), video_frame.height()};
  1139. }
  1140. // We have to create then encoder before the frame drop logic,
  1141. // because the latter depends on encoder_->GetScalingSettings.
  1142. // According to the testcase
  1143. // InitialFrameDropOffWhenEncoderDisabledScaling, the return value
  1144. // from GetScalingSettings should enable or disable the frame drop.
  1145. // Update input frame rate before we start using it. If we update it after
  1146. // any potential frame drop we are going to artificially increase frame sizes.
  1147. // Poll the rate before updating, otherwise we risk the rate being estimated
  1148. // a little too high at the start of the call when then window is small.
  1149. uint32_t framerate_fps = GetInputFramerateFps();
  1150. input_framerate_.Update(1u, clock_->TimeInMilliseconds());
  1151. int64_t now_ms = clock_->TimeInMilliseconds();
  1152. if (pending_encoder_reconfiguration_) {
  1153. ReconfigureEncoder();
  1154. last_parameters_update_ms_.emplace(now_ms);
  1155. } else if (!last_parameters_update_ms_ ||
  1156. now_ms - *last_parameters_update_ms_ >=
  1157. kParameterUpdateIntervalMs) {
  1158. if (last_encoder_rate_settings_) {
  1159. // Clone rate settings before update, so that SetEncoderRates() will
  1160. // actually detect the change between the input and
  1161. // |last_encoder_rate_setings_|, triggering the call to SetRate() on the
  1162. // encoder.
  1163. EncoderRateSettings new_rate_settings = *last_encoder_rate_settings_;
  1164. new_rate_settings.rate_control.framerate_fps =
  1165. static_cast<double>(framerate_fps);
  1166. SetEncoderRates(
  1167. UpdateBitrateAllocationAndNotifyObserver(new_rate_settings));
  1168. }
  1169. last_parameters_update_ms_.emplace(now_ms);
  1170. }
  1171. // Because pending frame will be dropped in any case, we need to
  1172. // remember its updated region.
  1173. if (pending_frame_) {
  1174. encoder_stats_observer_->OnFrameDropped(
  1175. VideoStreamEncoderObserver::DropReason::kEncoderQueue);
  1176. accumulated_update_rect_.Union(pending_frame_->update_rect());
  1177. }
  1178. if (DropDueToSize(video_frame.size())) {
  1179. RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
  1180. int fps_count = GetConstAdaptCounter().FramerateCount(kQuality);
  1181. int res_count = GetConstAdaptCounter().ResolutionCount(kQuality);
  1182. AdaptDown(kQuality);
  1183. if (degradation_preference_ == DegradationPreference::BALANCED &&
  1184. GetConstAdaptCounter().FramerateCount(kQuality) > fps_count) {
  1185. // Adapt framerate in same step as resolution.
  1186. AdaptDown(kQuality);
  1187. }
  1188. if (GetConstAdaptCounter().ResolutionCount(kQuality) > res_count) {
  1189. encoder_stats_observer_->OnInitialQualityResolutionAdaptDown();
  1190. }
  1191. ++initial_framedrop_;
  1192. // Storing references to a native buffer risks blocking frame capture.
  1193. if (video_frame.video_frame_buffer()->type() !=
  1194. VideoFrameBuffer::Type::kNative) {
  1195. pending_frame_ = video_frame;
  1196. pending_frame_post_time_us_ = time_when_posted_us;
  1197. } else {
  1198. // Ensure that any previously stored frame is dropped.
  1199. pending_frame_.reset();
  1200. accumulated_update_rect_.Union(video_frame.update_rect());
  1201. }
  1202. return;
  1203. }
  1204. initial_framedrop_ = kMaxInitialFramedrop;
  1205. if (EncoderPaused()) {
  1206. // Storing references to a native buffer risks blocking frame capture.
  1207. if (video_frame.video_frame_buffer()->type() !=
  1208. VideoFrameBuffer::Type::kNative) {
  1209. if (pending_frame_)
  1210. TraceFrameDropStart();
  1211. pending_frame_ = video_frame;
  1212. pending_frame_post_time_us_ = time_when_posted_us;
  1213. } else {
  1214. // Ensure that any previously stored frame is dropped.
  1215. pending_frame_.reset();
  1216. TraceFrameDropStart();
  1217. accumulated_update_rect_.Union(video_frame.update_rect());
  1218. }
  1219. return;
  1220. }
  1221. pending_frame_.reset();
  1222. frame_dropper_.Leak(framerate_fps);
  1223. // Frame dropping is enabled iff frame dropping is not force-disabled, and
  1224. // rate controller is not trusted.
  1225. const bool frame_dropping_enabled =
  1226. !force_disable_frame_dropper_ &&
  1227. !encoder_info_.has_trusted_rate_controller;
  1228. frame_dropper_.Enable(frame_dropping_enabled);
  1229. if (frame_dropping_enabled && frame_dropper_.DropFrame()) {
  1230. RTC_LOG(LS_VERBOSE)
  1231. << "Drop Frame: "
  1232. << "target bitrate "
  1233. << (last_encoder_rate_settings_
  1234. ? last_encoder_rate_settings_->encoder_target.bps()
  1235. : 0)
  1236. << ", input frame rate " << framerate_fps;
  1237. OnDroppedFrame(
  1238. EncodedImageCallback::DropReason::kDroppedByMediaOptimizations);
  1239. accumulated_update_rect_.Union(video_frame.update_rect());
  1240. return;
  1241. }
  1242. EncodeVideoFrame(video_frame, time_when_posted_us);
  1243. }
  1244. void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
  1245. int64_t time_when_posted_us) {
  1246. RTC_DCHECK_RUN_ON(&encoder_queue_);
  1247. // If the encoder fail we can't continue to encode frames. When this happens
  1248. // the WebrtcVideoSender is notified and the whole VideoSendStream is
  1249. // recreated.
  1250. if (encoder_failed_)
  1251. return;
  1252. TraceFrameDropEnd();
  1253. // Encoder metadata needs to be updated before encode complete callback.
  1254. VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo();
  1255. if (info.implementation_name != encoder_info_.implementation_name) {
  1256. encoder_stats_observer_->OnEncoderImplementationChanged(
  1257. info.implementation_name);
  1258. if (bitrate_adjuster_) {
  1259. // Encoder implementation changed, reset overshoot detector states.
  1260. bitrate_adjuster_->Reset();
  1261. }
  1262. }
  1263. if (bitrate_adjuster_) {
  1264. for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
  1265. if (info.fps_allocation[si] != encoder_info_.fps_allocation[si]) {
  1266. bitrate_adjuster_->OnEncoderInfo(info);
  1267. break;
  1268. }
  1269. }
  1270. }
  1271. encoder_info_ = info;
  1272. last_encode_info_ms_ = clock_->TimeInMilliseconds();
  1273. VideoFrame out_frame(video_frame);
  1274. const VideoFrameBuffer::Type buffer_type =
  1275. out_frame.video_frame_buffer()->type();
  1276. const bool is_buffer_type_supported =
  1277. buffer_type == VideoFrameBuffer::Type::kI420 ||
  1278. (buffer_type == VideoFrameBuffer::Type::kNative &&
  1279. info.supports_native_handle);
  1280. if (!is_buffer_type_supported) {
  1281. // This module only supports software encoding.
  1282. rtc::scoped_refptr<I420BufferInterface> converted_buffer(
  1283. out_frame.video_frame_buffer()->ToI420());
  1284. if (!converted_buffer) {
  1285. RTC_LOG(LS_ERROR) << "Frame conversion failed, dropping frame.";
  1286. return;
  1287. }
  1288. VideoFrame::UpdateRect update_rect = out_frame.update_rect();
  1289. if (!update_rect.IsEmpty() &&
  1290. out_frame.video_frame_buffer()->GetI420() == nullptr) {
  1291. // UpdatedRect is reset to full update if it's not empty, and buffer was
  1292. // converted, therefore we can't guarantee that pixels outside of
  1293. // UpdateRect didn't change comparing to the previous frame.
  1294. update_rect =
  1295. VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()};
  1296. }
  1297. out_frame.set_video_frame_buffer(converted_buffer);
  1298. out_frame.set_update_rect(update_rect);
  1299. }
  1300. // Crop frame if needed.
  1301. if ((crop_width_ > 0 || crop_height_ > 0) &&
  1302. out_frame.video_frame_buffer()->type() !=
  1303. VideoFrameBuffer::Type::kNative) {
  1304. // If the frame can't be converted to I420, drop it.
  1305. auto i420_buffer = video_frame.video_frame_buffer()->ToI420();
  1306. if (!i420_buffer) {
  1307. RTC_LOG(LS_ERROR) << "Frame conversion for crop failed, dropping frame.";
  1308. return;
  1309. }
  1310. int cropped_width = video_frame.width() - crop_width_;
  1311. int cropped_height = video_frame.height() - crop_height_;
  1312. rtc::scoped_refptr<I420Buffer> cropped_buffer =
  1313. I420Buffer::Create(cropped_width, cropped_height);
  1314. // TODO(ilnik): Remove scaling if cropping is too big, as it should never
  1315. // happen after SinkWants signaled correctly from ReconfigureEncoder.
  1316. VideoFrame::UpdateRect update_rect = video_frame.update_rect();
  1317. if (crop_width_ < 4 && crop_height_ < 4) {
  1318. cropped_buffer->CropAndScaleFrom(*i420_buffer, crop_width_ / 2,
  1319. crop_height_ / 2, cropped_width,
  1320. cropped_height);
  1321. update_rect.offset_x -= crop_width_ / 2;
  1322. update_rect.offset_y -= crop_height_ / 2;
  1323. update_rect.Intersect(
  1324. VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height});
  1325. } else {
  1326. cropped_buffer->ScaleFrom(*i420_buffer);
  1327. if (!update_rect.IsEmpty()) {
  1328. // Since we can't reason about pixels after scaling, we invalidate whole
  1329. // picture, if anything changed.
  1330. update_rect =
  1331. VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height};
  1332. }
  1333. }
  1334. out_frame.set_video_frame_buffer(cropped_buffer);
  1335. out_frame.set_update_rect(update_rect);
  1336. out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
  1337. // Since accumulated_update_rect_ is constructed before cropping,
  1338. // we can't trust it. If any changes were pending, we invalidate whole
  1339. // frame here.
  1340. if (!accumulated_update_rect_.IsEmpty()) {
  1341. accumulated_update_rect_ =
  1342. VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()};
  1343. }
  1344. }
  1345. if (!accumulated_update_rect_.IsEmpty()) {
  1346. accumulated_update_rect_.Union(out_frame.update_rect());
  1347. accumulated_update_rect_.Intersect(
  1348. VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()});
  1349. out_frame.set_update_rect(accumulated_update_rect_);
  1350. accumulated_update_rect_.MakeEmptyUpdate();
  1351. }
  1352. TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
  1353. "Encode");
  1354. overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
  1355. RTC_DCHECK_LE(send_codec_.width, out_frame.width());
  1356. RTC_DCHECK_LE(send_codec_.height, out_frame.height());
  1357. // Native frames should be scaled by the client.
  1358. // For internal encoders we scale everything in one place here.
  1359. RTC_DCHECK((out_frame.video_frame_buffer()->type() ==
  1360. VideoFrameBuffer::Type::kNative) ||
  1361. (send_codec_.width == out_frame.width() &&
  1362. send_codec_.height == out_frame.height()));
  1363. TRACE_EVENT1("webrtc", "VCMGenericEncoder::Encode", "timestamp",
  1364. out_frame.timestamp());
  1365. frame_encode_metadata_writer_.OnEncodeStarted(out_frame);
  1366. const int32_t encode_status = encoder_->Encode(out_frame, &next_frame_types_);
  1367. was_encode_called_since_last_initialization_ = true;
  1368. if (encode_status < 0) {
  1369. if (encode_status == WEBRTC_VIDEO_CODEC_ENCODER_FAILURE) {
  1370. RTC_LOG(LS_ERROR) << "Encoder failed, failing encoder format: "
  1371. << encoder_config_.video_format.ToString();
  1372. if (settings_.encoder_switch_request_callback) {
  1373. encoder_failed_ = true;
  1374. settings_.encoder_switch_request_callback->RequestEncoderFallback();
  1375. } else {
  1376. RTC_LOG(LS_ERROR)
  1377. << "Encoder failed but no encoder fallback callback is registered";
  1378. }
  1379. } else {
  1380. RTC_LOG(LS_ERROR) << "Failed to encode frame. Error code: "
  1381. << encode_status;
  1382. }
  1383. return;
  1384. }
  1385. for (auto& it : next_frame_types_) {
  1386. it = VideoFrameType::kVideoFrameDelta;
  1387. }
  1388. }
  1389. void VideoStreamEncoder::SendKeyFrame() {
  1390. if (!encoder_queue_.IsCurrent()) {
  1391. encoder_queue_.PostTask([this] { SendKeyFrame(); });
  1392. return;
  1393. }
  1394. RTC_DCHECK_RUN_ON(&encoder_queue_);
  1395. TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
  1396. RTC_DCHECK(!next_frame_types_.empty());
  1397. // TODO(webrtc:10615): Map keyframe request to spatial layer.
  1398. std::fill(next_frame_types_.begin(), next_frame_types_.end(),
  1399. VideoFrameType::kVideoFrameKey);
  1400. if (HasInternalSource()) {
  1401. // Try to request the frame if we have an external encoder with
  1402. // internal source since AddVideoFrame never will be called.
  1403. // TODO(nisse): Used only with internal source. Delete as soon as
  1404. // that feature is removed. The only implementation I've been able
  1405. // to find ignores what's in the frame. With one exception: It seems
  1406. // a few test cases, e.g.,
  1407. // VideoSendStreamTest.VideoSendStreamStopSetEncoderRateToZero, set
  1408. // internal_source to true and use FakeEncoder. And the latter will
  1409. // happily encode this 1x1 frame and pass it on down the pipeline.
  1410. if (encoder_->Encode(VideoFrame::Builder()
  1411. .set_video_frame_buffer(I420Buffer::Create(1, 1))
  1412. .set_rotation(kVideoRotation_0)
  1413. .set_timestamp_us(0)
  1414. .build(),
  1415. &next_frame_types_) == WEBRTC_VIDEO_CODEC_OK) {
  1416. // Try to remove just-performed keyframe request, if stream still exists.
  1417. std::fill(next_frame_types_.begin(), next_frame_types_.end(),
  1418. VideoFrameType::kVideoFrameDelta);
  1419. }
  1420. }
  1421. }
  1422. void VideoStreamEncoder::OnLossNotification(
  1423. const VideoEncoder::LossNotification& loss_notification) {
  1424. if (!encoder_queue_.IsCurrent()) {
  1425. encoder_queue_.PostTask(
  1426. [this, loss_notification] { OnLossNotification(loss_notification); });
  1427. return;
  1428. }
  1429. RTC_DCHECK_RUN_ON(&encoder_queue_);
  1430. if (encoder_) {
  1431. encoder_->OnLossNotification(loss_notification);
  1432. }
  1433. }
  1434. EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
  1435. const EncodedImage& encoded_image,
  1436. const CodecSpecificInfo* codec_specific_info,
  1437. const RTPFragmentationHeader* fragmentation) {
  1438. TRACE_EVENT_INSTANT1("webrtc", "VCMEncodedFrameCallback::Encoded",
  1439. "timestamp", encoded_image.Timestamp());
  1440. const size_t spatial_idx = encoded_image.SpatialIndex().value_or(0);
  1441. EncodedImage image_copy(encoded_image);
  1442. frame_encode_metadata_writer_.FillTimingInfo(spatial_idx, &image_copy);
  1443. std::unique_ptr<RTPFragmentationHeader> fragmentation_copy =
  1444. frame_encode_metadata_writer_.UpdateBitstream(codec_specific_info,
  1445. fragmentation, &image_copy);
  1446. // Piggyback ALR experiment group id and simulcast id into the content type.
  1447. const uint8_t experiment_id =
  1448. experiment_groups_[videocontenttypehelpers::IsScreenshare(
  1449. image_copy.content_type_)];
  1450. // TODO(ilnik): This will force content type extension to be present even
  1451. // for realtime video. At the expense of miniscule overhead we will get
  1452. // sliced receive statistics.
  1453. RTC_CHECK(videocontenttypehelpers::SetExperimentId(&image_copy.content_type_,
  1454. experiment_id));
  1455. // We count simulcast streams from 1 on the wire. That's why we set simulcast
  1456. // id in content type to +1 of that is actual simulcast index. This is because
  1457. // value 0 on the wire is reserved for 'no simulcast stream specified'.
  1458. RTC_CHECK(videocontenttypehelpers::SetSimulcastId(
  1459. &image_copy.content_type_, static_cast<uint8_t>(spatial_idx + 1)));
  1460. // Encoded is called on whatever thread the real encoder implementation run
  1461. // on. In the case of hardware encoders, there might be several encoders
  1462. // running in parallel on different threads.
  1463. encoder_stats_observer_->OnSendEncodedImage(image_copy, codec_specific_info);
  1464. // The simulcast id is signaled in the SpatialIndex. This makes it impossible
  1465. // to do simulcast for codecs that actually support spatial layers since we
  1466. // can't distinguish between an actual spatial layer and a simulcast stream.
  1467. // TODO(bugs.webrtc.org/10520): Signal the simulcast id explicitly.
  1468. int simulcast_id = 0;
  1469. if (codec_specific_info &&
  1470. (codec_specific_info->codecType == kVideoCodecVP8 ||
  1471. codec_specific_info->codecType == kVideoCodecH264 ||
  1472. codec_specific_info->codecType == kVideoCodecGeneric)) {
  1473. simulcast_id = encoded_image.SpatialIndex().value_or(0);
  1474. }
  1475. std::unique_ptr<CodecSpecificInfo> codec_info_copy;
  1476. {
  1477. rtc::CritScope cs(&encoded_image_lock_);
  1478. if (codec_specific_info && codec_specific_info->generic_frame_info) {
  1479. codec_info_copy =
  1480. std::make_unique<CodecSpecificInfo>(*codec_specific_info);
  1481. GenericFrameInfo& generic_info = *codec_info_copy->generic_frame_info;
  1482. generic_info.frame_id = next_frame_id_++;
  1483. if (encoder_buffer_state_.size() <= static_cast<size_t>(simulcast_id)) {
  1484. RTC_LOG(LS_ERROR) << "At most " << encoder_buffer_state_.size()
  1485. << " simulcast streams supported.";
  1486. } else {
  1487. std::array<int64_t, kMaxEncoderBuffers>& state =
  1488. encoder_buffer_state_[simulcast_id];
  1489. for (const CodecBufferUsage& buffer : generic_info.encoder_buffers) {
  1490. if (state.size() <= static_cast<size_t>(buffer.id)) {
  1491. RTC_LOG(LS_ERROR)
  1492. << "At most " << state.size() << " encoder buffers supported.";
  1493. break;
  1494. }
  1495. if (buffer.referenced) {
  1496. int64_t diff = generic_info.frame_id - state[buffer.id];
  1497. if (diff <= 0) {
  1498. RTC_LOG(LS_ERROR) << "Invalid frame diff: " << diff << ".";
  1499. } else if (absl::c_find(generic_info.frame_diffs, diff) ==
  1500. generic_info.frame_diffs.end()) {
  1501. generic_info.frame_diffs.push_back(diff);
  1502. }
  1503. }
  1504. if (buffer.updated)
  1505. state[buffer.id] = generic_info.frame_id;
  1506. }
  1507. }
  1508. }
  1509. }
  1510. EncodedImageCallback::Result result = sink_->OnEncodedImage(
  1511. image_copy, codec_info_copy ? codec_info_copy.get() : codec_specific_info,
  1512. fragmentation_copy ? fragmentation_copy.get() : fragmentation);
  1513. // We are only interested in propagating the meta-data about the image, not
  1514. // encoded data itself, to the post encode function. Since we cannot be sure
  1515. // the pointer will still be valid when run on the task queue, set it to null.
  1516. image_copy.set_buffer(nullptr, 0);
  1517. int temporal_index = 0;
  1518. if (codec_specific_info) {
  1519. if (codec_specific_info->codecType == kVideoCodecVP9) {
  1520. temporal_index = codec_specific_info->codecSpecific.VP9.temporal_idx;
  1521. } else if (codec_specific_info->codecType == kVideoCodecVP8) {
  1522. temporal_index = codec_specific_info->codecSpecific.VP8.temporalIdx;
  1523. }
  1524. }
  1525. if (temporal_index == kNoTemporalIdx) {
  1526. temporal_index = 0;
  1527. }
  1528. RunPostEncode(image_copy, rtc::TimeMicros(), temporal_index);
  1529. if (result.error == Result::OK) {
  1530. // In case of an internal encoder running on a separate thread, the
  1531. // decision to drop a frame might be a frame late and signaled via
  1532. // atomic flag. This is because we can't easily wait for the worker thread
  1533. // without risking deadlocks, eg during shutdown when the worker thread
  1534. // might be waiting for the internal encoder threads to stop.
  1535. if (pending_frame_drops_.load() > 0) {
  1536. int pending_drops = pending_frame_drops_.fetch_sub(1);
  1537. RTC_DCHECK_GT(pending_drops, 0);
  1538. result.drop_next_frame = true;
  1539. }
  1540. }
  1541. return result;
  1542. }
  1543. void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
  1544. switch (reason) {
  1545. case DropReason::kDroppedByMediaOptimizations:
  1546. encoder_stats_observer_->OnFrameDropped(
  1547. VideoStreamEncoderObserver::DropReason::kMediaOptimization);
  1548. encoder_queue_.PostTask([this] {
  1549. RTC_DCHECK_RUN_ON(&encoder_queue_);
  1550. if (quality_scaler_)
  1551. quality_scaler_->ReportDroppedFrameByMediaOpt();
  1552. });
  1553. break;
  1554. case DropReason::kDroppedByEncoder:
  1555. encoder_stats_observer_->OnFrameDropped(
  1556. VideoStreamEncoderObserver::DropReason::kEncoder);
  1557. encoder_queue_.PostTask([this] {
  1558. RTC_DCHECK_RUN_ON(&encoder_queue_);
  1559. if (quality_scaler_)
  1560. quality_scaler_->ReportDroppedFrameByEncoder();
  1561. });
  1562. break;
  1563. }
  1564. }
  1565. void VideoStreamEncoder::OnBitrateUpdated(DataRate target_bitrate,
  1566. DataRate stable_target_bitrate,
  1567. DataRate link_allocation,
  1568. uint8_t fraction_lost,
  1569. int64_t round_trip_time_ms) {
  1570. RTC_DCHECK_GE(link_allocation, target_bitrate);
  1571. if (!encoder_queue_.IsCurrent()) {
  1572. encoder_queue_.PostTask([this, target_bitrate, stable_target_bitrate,
  1573. link_allocation, fraction_lost,
  1574. round_trip_time_ms] {
  1575. OnBitrateUpdated(target_bitrate, stable_target_bitrate, link_allocation,
  1576. fraction_lost, round_trip_time_ms);
  1577. });
  1578. return;
  1579. }
  1580. RTC_DCHECK_RUN_ON(&encoder_queue_);
  1581. if (encoder_switch_experiment_.IsBitrateBelowThreshold(target_bitrate) &&
  1582. settings_.encoder_switch_request_callback && !encoder_switch_requested_) {
  1583. EncoderSwitchRequestCallback::Config conf;
  1584. conf.codec_name = encoder_switch_experiment_.to_codec;
  1585. conf.param = encoder_switch_experiment_.to_param;
  1586. conf.value = encoder_switch_experiment_.to_value;
  1587. settings_.encoder_switch_request_callback->RequestEncoderSwitch(conf);
  1588. encoder_switch_requested_ = true;
  1589. }
  1590. RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
  1591. RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << target_bitrate.bps()
  1592. << " stable bitrate = " << stable_target_bitrate.bps()
  1593. << " link allocation bitrate = " << link_allocation.bps()
  1594. << " packet loss " << static_cast<int>(fraction_lost)
  1595. << " rtt " << round_trip_time_ms;
  1596. // On significant changes to BWE at the start of the call,
  1597. // enable frame drops to quickly react to jumps in available bandwidth.
  1598. if (encoder_start_bitrate_bps_ != 0 &&
  1599. !has_seen_first_significant_bwe_change_ && quality_scaler_ &&
  1600. initial_framedrop_on_bwe_enabled_ &&
  1601. abs_diff(target_bitrate.bps(), encoder_start_bitrate_bps_) >=
  1602. kFramedropThreshold * encoder_start_bitrate_bps_) {
  1603. // Reset initial framedrop feature when first real BW estimate arrives.
  1604. // TODO(kthelgason): Update BitrateAllocator to not call OnBitrateUpdated
  1605. // without an actual BW estimate.
  1606. initial_framedrop_ = 0;
  1607. has_seen_first_significant_bwe_change_ = true;
  1608. }
  1609. if (set_start_bitrate_bps_ > 0 && !has_seen_first_bwe_drop_ &&
  1610. quality_scaler_ && quality_scaler_settings_.InitialBitrateIntervalMs() &&
  1611. quality_scaler_settings_.InitialBitrateFactor()) {
  1612. int64_t diff_ms = clock_->TimeInMilliseconds() - set_start_bitrate_time_ms_;
  1613. if (diff_ms < quality_scaler_settings_.InitialBitrateIntervalMs().value() &&
  1614. (target_bitrate.bps() <
  1615. (set_start_bitrate_bps_ *
  1616. quality_scaler_settings_.InitialBitrateFactor().value()))) {
  1617. RTC_LOG(LS_INFO) << "Reset initial_framedrop_. Start bitrate: "
  1618. << set_start_bitrate_bps_
  1619. << ", target bitrate: " << target_bitrate.bps();
  1620. initial_framedrop_ = 0;
  1621. has_seen_first_bwe_drop_ = true;
  1622. }
  1623. }
  1624. if (encoder_) {
  1625. encoder_->OnPacketLossRateUpdate(static_cast<float>(fraction_lost) / 256.f);
  1626. encoder_->OnRttUpdate(round_trip_time_ms);
  1627. }
  1628. uint32_t framerate_fps = GetInputFramerateFps();
  1629. frame_dropper_.SetRates((target_bitrate.bps() + 500) / 1000, framerate_fps);
  1630. const bool video_is_suspended = target_bitrate == DataRate::Zero();
  1631. const bool video_suspension_changed = video_is_suspended != EncoderPaused();
  1632. EncoderRateSettings new_rate_settings{
  1633. VideoBitrateAllocation(), static_cast<double>(framerate_fps),
  1634. link_allocation, target_bitrate, stable_target_bitrate};
  1635. SetEncoderRates(UpdateBitrateAllocationAndNotifyObserver(new_rate_settings));
  1636. encoder_start_bitrate_bps_ = target_bitrate.bps() != 0
  1637. ? target_bitrate.bps()
  1638. : encoder_start_bitrate_bps_;
  1639. if (video_suspension_changed) {
  1640. RTC_LOG(LS_INFO) << "Video suspend state changed to: "
  1641. << (video_is_suspended ? "suspended" : "not suspended");
  1642. encoder_stats_observer_->OnSuspendChange(video_is_suspended);
  1643. }
  1644. if (video_suspension_changed && !video_is_suspended && pending_frame_ &&
  1645. !DropDueToSize(pending_frame_->size())) {
  1646. int64_t pending_time_us = rtc::TimeMicros() - pending_frame_post_time_us_;
  1647. if (pending_time_us < kPendingFrameTimeoutMs * 1000)
  1648. EncodeVideoFrame(*pending_frame_, pending_frame_post_time_us_);
  1649. pending_frame_.reset();
  1650. }
  1651. }
  1652. bool VideoStreamEncoder::DropDueToSize(uint32_t pixel_count) const {
  1653. if (initial_framedrop_ >= kMaxInitialFramedrop ||
  1654. encoder_start_bitrate_bps_ == 0) {
  1655. return false;
  1656. }
  1657. absl::optional<VideoEncoder::ResolutionBitrateLimits> encoder_bitrate_limits =
  1658. GetEncoderBitrateLimits(encoder_->GetEncoderInfo(), pixel_count);
  1659. if (encoder_bitrate_limits.has_value()) {
  1660. // Use bitrate limits provided by encoder.
  1661. return encoder_start_bitrate_bps_ <
  1662. static_cast<uint32_t>(encoder_bitrate_limits->min_start_bitrate_bps);
  1663. }
  1664. if (encoder_start_bitrate_bps_ < 300000 /* qvga */) {
  1665. return pixel_count > 320 * 240;
  1666. } else if (encoder_start_bitrate_bps_ < 500000 /* vga */) {
  1667. return pixel_count > 640 * 480;
  1668. }
  1669. return false;
  1670. }
  1671. bool VideoStreamEncoder::AdaptDown(AdaptReason reason) {
  1672. RTC_DCHECK_RUN_ON(&encoder_queue_);
  1673. AdaptationRequest adaptation_request = {
  1674. last_frame_info_->pixel_count(),
  1675. encoder_stats_observer_->GetInputFrameRate(),
  1676. AdaptationRequest::Mode::kAdaptDown};
  1677. bool downgrade_requested =
  1678. last_adaptation_request_ &&
  1679. last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
  1680. bool did_adapt = true;
  1681. switch (degradation_preference_) {
  1682. case DegradationPreference::BALANCED:
  1683. break;
  1684. case DegradationPreference::MAINTAIN_FRAMERATE:
  1685. if (downgrade_requested &&
  1686. adaptation_request.input_pixel_count_ >=
  1687. last_adaptation_request_->input_pixel_count_) {
  1688. // Don't request lower resolution if the current resolution is not
  1689. // lower than the last time we asked for the resolution to be lowered.
  1690. return true;
  1691. }
  1692. break;
  1693. case DegradationPreference::MAINTAIN_RESOLUTION:
  1694. if (adaptation_request.framerate_fps_ <= 0 ||
  1695. (downgrade_requested &&
  1696. adaptation_request.framerate_fps_ < kMinFramerateFps)) {
  1697. // If no input fps estimate available, can't determine how to scale down
  1698. // framerate. Otherwise, don't request lower framerate if we don't have
  1699. // a valid frame rate. Since framerate, unlike resolution, is a measure
  1700. // we have to estimate, and can fluctuate naturally over time, don't
  1701. // make the same kind of limitations as for resolution, but trust the
  1702. // overuse detector to not trigger too often.
  1703. return true;
  1704. }
  1705. break;
  1706. case DegradationPreference::DISABLED:
  1707. return true;
  1708. }
  1709. switch (degradation_preference_) {
  1710. case DegradationPreference::BALANCED: {
  1711. // Try scale down framerate, if lower.
  1712. int fps = balanced_settings_.MinFps(encoder_config_.codec_type,
  1713. last_frame_info_->pixel_count());
  1714. if (source_proxy_->RestrictFramerate(fps)) {
  1715. GetAdaptCounter().IncrementFramerate(reason);
  1716. // Check if requested fps is higher (or close to) input fps.
  1717. absl::optional<int> min_diff =
  1718. balanced_settings_.MinFpsDiff(last_frame_info_->pixel_count());
  1719. if (min_diff && adaptation_request.framerate_fps_ > 0) {
  1720. int fps_diff = adaptation_request.framerate_fps_ - fps;
  1721. if (fps_diff < min_diff.value()) {
  1722. did_adapt = false;
  1723. }
  1724. }
  1725. break;
  1726. }
  1727. // Scale down resolution.
  1728. RTC_FALLTHROUGH();
  1729. }
  1730. case DegradationPreference::MAINTAIN_FRAMERATE: {
  1731. // Scale down resolution.
  1732. bool min_pixels_reached = false;
  1733. if (!source_proxy_->RequestResolutionLowerThan(
  1734. adaptation_request.input_pixel_count_,
  1735. encoder_->GetEncoderInfo().scaling_settings.min_pixels_per_frame,
  1736. &min_pixels_reached)) {
  1737. if (min_pixels_reached)
  1738. encoder_stats_observer_->OnMinPixelLimitReached();
  1739. return true;
  1740. }
  1741. GetAdaptCounter().IncrementResolution(reason);
  1742. break;
  1743. }
  1744. case DegradationPreference::MAINTAIN_RESOLUTION: {
  1745. // Scale down framerate.
  1746. const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
  1747. adaptation_request.framerate_fps_);
  1748. if (requested_framerate == -1)
  1749. return true;
  1750. RTC_DCHECK_NE(max_framerate_, -1);
  1751. overuse_detector_->OnTargetFramerateUpdated(
  1752. std::min(max_framerate_, requested_framerate));
  1753. GetAdaptCounter().IncrementFramerate(reason);
  1754. break;
  1755. }
  1756. case DegradationPreference::DISABLED:
  1757. RTC_NOTREACHED();
  1758. }
  1759. last_adaptation_request_.emplace(adaptation_request);
  1760. UpdateAdaptationStats(reason);
  1761. RTC_LOG(LS_INFO) << GetConstAdaptCounter().ToString();
  1762. return did_adapt;
  1763. }
  1764. void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
  1765. RTC_DCHECK_RUN_ON(&encoder_queue_);
  1766. const AdaptCounter& adapt_counter = GetConstAdaptCounter();
  1767. int num_downgrades = adapt_counter.TotalCount(reason);
  1768. if (num_downgrades == 0)
  1769. return;
  1770. RTC_DCHECK_GT(num_downgrades, 0);
  1771. AdaptationRequest adaptation_request = {
  1772. last_frame_info_->pixel_count(),
  1773. encoder_stats_observer_->GetInputFrameRate(),
  1774. AdaptationRequest::Mode::kAdaptUp};
  1775. bool adapt_up_requested =
  1776. last_adaptation_request_ &&
  1777. last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
  1778. if (degradation_preference_ == DegradationPreference::MAINTAIN_FRAMERATE) {
  1779. if (adapt_up_requested &&
  1780. adaptation_request.input_pixel_count_ <=
  1781. last_adaptation_request_->input_pixel_count_) {
  1782. // Don't request higher resolution if the current resolution is not
  1783. // higher than the last time we asked for the resolution to be higher.
  1784. return;
  1785. }
  1786. }
  1787. switch (degradation_preference_) {
  1788. case DegradationPreference::BALANCED: {
  1789. // Check if quality should be increased based on bitrate.
  1790. if (reason == kQuality &&
  1791. !balanced_settings_.CanAdaptUp(last_frame_info_->pixel_count(),
  1792. encoder_start_bitrate_bps_)) {
  1793. return;
  1794. }
  1795. // Try scale up framerate, if higher.
  1796. int fps = balanced_settings_.MaxFps(encoder_config_.codec_type,
  1797. last_frame_info_->pixel_count());
  1798. if (source_proxy_->IncreaseFramerate(fps)) {
  1799. GetAdaptCounter().DecrementFramerate(reason, fps);
  1800. // Reset framerate in case of fewer fps steps down than up.
  1801. if (adapt_counter.FramerateCount() == 0 &&
  1802. fps != std::numeric_limits<int>::max()) {
  1803. RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
  1804. source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
  1805. }
  1806. break;
  1807. }
  1808. // Check if resolution should be increased based on bitrate.
  1809. if (reason == kQuality &&
  1810. !balanced_settings_.CanAdaptUpResolution(
  1811. last_frame_info_->pixel_count(), encoder_start_bitrate_bps_)) {
  1812. return;
  1813. }
  1814. // Scale up resolution.
  1815. RTC_FALLTHROUGH();
  1816. }
  1817. case DegradationPreference::MAINTAIN_FRAMERATE: {
  1818. // Check if resolution should be increased based on bitrate and
  1819. // limits specified by encoder capabilities.
  1820. if (reason == kQuality &&
  1821. !CanAdaptUpResolution(last_frame_info_->pixel_count(),
  1822. encoder_start_bitrate_bps_)) {
  1823. return;
  1824. }
  1825. // Scale up resolution.
  1826. int pixel_count = adaptation_request.input_pixel_count_;
  1827. if (adapt_counter.ResolutionCount() == 1) {
  1828. RTC_LOG(LS_INFO) << "Removing resolution down-scaling setting.";
  1829. pixel_count = std::numeric_limits<int>::max();
  1830. }
  1831. if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
  1832. return;
  1833. GetAdaptCounter().DecrementResolution(reason);
  1834. break;
  1835. }
  1836. case DegradationPreference::MAINTAIN_RESOLUTION: {
  1837. // Scale up framerate.
  1838. int fps = adaptation_request.framerate_fps_;
  1839. if (adapt_counter.FramerateCount() == 1) {
  1840. RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
  1841. fps = std::numeric_limits<int>::max();
  1842. }
  1843. const int requested_framerate =
  1844. source_proxy_->RequestHigherFramerateThan(fps);
  1845. if (requested_framerate == -1) {
  1846. overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
  1847. return;
  1848. }
  1849. overuse_detector_->OnTargetFramerateUpdated(
  1850. std::min(max_framerate_, requested_framerate));
  1851. GetAdaptCounter().DecrementFramerate(reason);
  1852. break;
  1853. }
  1854. case DegradationPreference::DISABLED:
  1855. return;
  1856. }
  1857. last_adaptation_request_.emplace(adaptation_request);
  1858. UpdateAdaptationStats(reason);
  1859. RTC_LOG(LS_INFO) << adapt_counter.ToString();
  1860. }
  1861. bool VideoStreamEncoder::CanAdaptUpResolution(int pixels,
  1862. uint32_t bitrate_bps) const {
  1863. absl::optional<VideoEncoder::ResolutionBitrateLimits> bitrate_limits =
  1864. GetEncoderBitrateLimits(encoder_info_,
  1865. source_proxy_->GetHigherResolutionThan(pixels));
  1866. if (!bitrate_limits.has_value() || bitrate_bps == 0) {
  1867. return true; // No limit configured or bitrate provided.
  1868. }
  1869. RTC_DCHECK_GE(bitrate_limits->frame_size_pixels, pixels);
  1870. return bitrate_bps >=
  1871. static_cast<uint32_t>(bitrate_limits->min_start_bitrate_bps);
  1872. }
  1873. // TODO(nisse): Delete, once AdaptReason and AdaptationReason are merged.
  1874. void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
  1875. switch (reason) {
  1876. case kCpu:
  1877. encoder_stats_observer_->OnAdaptationChanged(
  1878. VideoStreamEncoderObserver::AdaptationReason::kCpu,
  1879. GetActiveCounts(kCpu), GetActiveCounts(kQuality));
  1880. break;
  1881. case kQuality:
  1882. encoder_stats_observer_->OnAdaptationChanged(
  1883. VideoStreamEncoderObserver::AdaptationReason::kQuality,
  1884. GetActiveCounts(kCpu), GetActiveCounts(kQuality));
  1885. break;
  1886. }
  1887. }
  1888. VideoStreamEncoderObserver::AdaptationSteps VideoStreamEncoder::GetActiveCounts(
  1889. AdaptReason reason) {
  1890. VideoStreamEncoderObserver::AdaptationSteps counts =
  1891. GetConstAdaptCounter().Counts(reason);
  1892. switch (reason) {
  1893. case kCpu:
  1894. if (!IsFramerateScalingEnabled(degradation_preference_))
  1895. counts.num_framerate_reductions = absl::nullopt;
  1896. if (!IsResolutionScalingEnabled(degradation_preference_))
  1897. counts.num_resolution_reductions = absl::nullopt;
  1898. break;
  1899. case kQuality:
  1900. if (!IsFramerateScalingEnabled(degradation_preference_) ||
  1901. !quality_scaler_) {
  1902. counts.num_framerate_reductions = absl::nullopt;
  1903. }
  1904. if (!IsResolutionScalingEnabled(degradation_preference_) ||
  1905. !quality_scaler_) {
  1906. counts.num_resolution_reductions = absl::nullopt;
  1907. }
  1908. break;
  1909. }
  1910. return counts;
  1911. }
  1912. VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
  1913. return adapt_counters_[degradation_preference_];
  1914. }
  1915. const VideoStreamEncoder::AdaptCounter&
  1916. VideoStreamEncoder::GetConstAdaptCounter() {
  1917. return adapt_counters_[degradation_preference_];
  1918. }
  1919. void VideoStreamEncoder::RunPostEncode(EncodedImage encoded_image,
  1920. int64_t time_sent_us,
  1921. int temporal_index) {
  1922. if (!encoder_queue_.IsCurrent()) {
  1923. encoder_queue_.PostTask(
  1924. [this, encoded_image, time_sent_us, temporal_index] {
  1925. RunPostEncode(encoded_image, time_sent_us, temporal_index);
  1926. });
  1927. return;
  1928. }
  1929. RTC_DCHECK_RUN_ON(&encoder_queue_);
  1930. absl::optional<int> encode_duration_us;
  1931. if (encoded_image.timing_.flags != VideoSendTiming::kInvalid) {
  1932. encode_duration_us =
  1933. // TODO(nisse): Maybe use capture_time_ms_ rather than encode_start_ms_?
  1934. rtc::kNumMicrosecsPerMillisec *
  1935. (encoded_image.timing_.encode_finish_ms -
  1936. encoded_image.timing_.encode_start_ms);
  1937. }
  1938. // Run post encode tasks, such as overuse detection and frame rate/drop
  1939. // stats for internal encoders.
  1940. const size_t frame_size = encoded_image.size();
  1941. const bool keyframe =
  1942. encoded_image._frameType == VideoFrameType::kVideoFrameKey;
  1943. if (frame_size > 0) {
  1944. frame_dropper_.Fill(frame_size, !keyframe);
  1945. }
  1946. if (HasInternalSource()) {
  1947. // Update frame dropper after the fact for internal sources.
  1948. input_framerate_.Update(1u, clock_->TimeInMilliseconds());
  1949. frame_dropper_.Leak(GetInputFramerateFps());
  1950. // Signal to encoder to drop next frame.
  1951. if (frame_dropper_.DropFrame()) {
  1952. pending_frame_drops_.fetch_add(1);
  1953. }
  1954. }
  1955. overuse_detector_->FrameSent(
  1956. encoded_image.Timestamp(), time_sent_us,
  1957. encoded_image.capture_time_ms_ * rtc::kNumMicrosecsPerMillisec,
  1958. encode_duration_us);
  1959. if (quality_scaler_ && encoded_image.qp_ >= 0)
  1960. quality_scaler_->ReportQp(encoded_image.qp_, time_sent_us);
  1961. if (bitrate_adjuster_) {
  1962. bitrate_adjuster_->OnEncodedFrame(encoded_image, temporal_index);
  1963. }
  1964. }
  1965. bool VideoStreamEncoder::HasInternalSource() const {
  1966. // TODO(sprang): Checking both info from encoder and from encoder factory
  1967. // until we have deprecated and removed the encoder factory info.
  1968. return codec_info_.has_internal_source || encoder_info_.has_internal_source;
  1969. }
  1970. void VideoStreamEncoder::ReleaseEncoder() {
  1971. if (!encoder_ || !encoder_initialized_) {
  1972. return;
  1973. }
  1974. encoder_->Release();
  1975. encoder_initialized_ = false;
  1976. TRACE_EVENT0("webrtc", "VCMGenericEncoder::Release");
  1977. }
  1978. // Class holding adaptation information.
  1979. VideoStreamEncoder::AdaptCounter::AdaptCounter() {
  1980. fps_counters_.resize(kScaleReasonSize);
  1981. resolution_counters_.resize(kScaleReasonSize);
  1982. static_assert(kScaleReasonSize == 2, "Update MoveCount.");
  1983. }
  1984. VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
  1985. std::string VideoStreamEncoder::AdaptCounter::ToString() const {
  1986. rtc::StringBuilder ss;
  1987. ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
  1988. ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
  1989. return ss.Release();
  1990. }
  1991. VideoStreamEncoderObserver::AdaptationSteps
  1992. VideoStreamEncoder::AdaptCounter::Counts(int reason) const {
  1993. VideoStreamEncoderObserver::AdaptationSteps counts;
  1994. counts.num_framerate_reductions = fps_counters_[reason];
  1995. counts.num_resolution_reductions = resolution_counters_[reason];
  1996. return counts;
  1997. }
  1998. void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
  1999. ++(fps_counters_[reason]);
  2000. }
  2001. void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
  2002. ++(resolution_counters_[reason]);
  2003. }
  2004. void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
  2005. if (fps_counters_[reason] == 0) {
  2006. // Balanced mode: Adapt up is in a different order, switch reason.
  2007. // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
  2008. // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
  2009. // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
  2010. // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
  2011. // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
  2012. RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
  2013. RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
  2014. MoveCount(&resolution_counters_, reason);
  2015. MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
  2016. }
  2017. --(fps_counters_[reason]);
  2018. RTC_DCHECK_GE(fps_counters_[reason], 0);
  2019. }
  2020. void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
  2021. if (resolution_counters_[reason] == 0) {
  2022. // Balanced mode: Adapt up is in a different order, switch reason.
  2023. RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
  2024. RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
  2025. MoveCount(&fps_counters_, reason);
  2026. MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
  2027. }
  2028. --(resolution_counters_[reason]);
  2029. RTC_DCHECK_GE(resolution_counters_[reason], 0);
  2030. }
  2031. void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
  2032. int cur_fps) {
  2033. DecrementFramerate(reason);
  2034. // Reset if at max fps (i.e. in case of fewer steps up than down).
  2035. if (cur_fps == std::numeric_limits<int>::max())
  2036. absl::c_fill(fps_counters_, 0);
  2037. }
  2038. int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
  2039. return Count(fps_counters_);
  2040. }
  2041. int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
  2042. return Count(resolution_counters_);
  2043. }
  2044. int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
  2045. return fps_counters_[reason];
  2046. }
  2047. int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
  2048. return resolution_counters_[reason];
  2049. }
  2050. int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
  2051. return FramerateCount(reason) + ResolutionCount(reason);
  2052. }
  2053. int VideoStreamEncoder::AdaptCounter::Count(
  2054. const std::vector<int>& counters) const {
  2055. return absl::c_accumulate(counters, 0);
  2056. }
  2057. void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
  2058. int from_reason) {
  2059. int to_reason = (from_reason + 1) % kScaleReasonSize;
  2060. ++((*counters)[to_reason]);
  2061. --((*counters)[from_reason]);
  2062. }
  2063. std::string VideoStreamEncoder::AdaptCounter::ToString(
  2064. const std::vector<int>& counters) const {
  2065. rtc::StringBuilder ss;
  2066. for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
  2067. ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
  2068. }
  2069. return ss.Release();
  2070. }
  2071. bool VideoStreamEncoder::EncoderSwitchExperiment::IsBitrateBelowThreshold(
  2072. const DataRate& target_bitrate) {
  2073. DataRate rate =
  2074. DataRate::kbps(bitrate_filter.Apply(1.0, target_bitrate.kbps()));
  2075. return current_thresholds.bitrate && rate < *current_thresholds.bitrate;
  2076. }
  2077. bool VideoStreamEncoder::EncoderSwitchExperiment::IsPixelCountBelowThreshold(
  2078. int pixel_count) const {
  2079. return current_thresholds.pixel_count &&
  2080. pixel_count < *current_thresholds.pixel_count;
  2081. }
  2082. void VideoStreamEncoder::EncoderSwitchExperiment::SetCodec(
  2083. VideoCodecType codec) {
  2084. auto it = codec_thresholds.find(codec);
  2085. if (it == codec_thresholds.end()) {
  2086. current_thresholds = {};
  2087. } else {
  2088. current_thresholds = it->second;
  2089. }
  2090. }
  2091. VideoStreamEncoder::EncoderSwitchExperiment
  2092. VideoStreamEncoder::ParseEncoderSwitchFieldTrial() const {
  2093. EncoderSwitchExperiment result;
  2094. // Each "codec threshold" have the format
  2095. // "<codec name>;<bitrate kbps>;<pixel count>", and are separated by the "|"
  2096. // character.
  2097. webrtc::FieldTrialOptional<std::string> codec_thresholds_string{
  2098. "codec_thresholds"};
  2099. webrtc::FieldTrialOptional<std::string> to_codec{"to_codec"};
  2100. webrtc::FieldTrialOptional<std::string> to_param{"to_param"};
  2101. webrtc::FieldTrialOptional<std::string> to_value{"to_value"};
  2102. webrtc::FieldTrialOptional<double> window{"window"};
  2103. webrtc::ParseFieldTrial(
  2104. {&codec_thresholds_string, &to_codec, &to_param, &to_value, &window},
  2105. webrtc::field_trial::FindFullName(
  2106. "WebRTC-NetworkCondition-EncoderSwitch"));
  2107. if (!codec_thresholds_string || !to_codec || !window) {
  2108. return {};
  2109. }
  2110. result.bitrate_filter.Reset(1.0 - 1.0 / *window);
  2111. result.to_codec = *to_codec;
  2112. result.to_param = to_param.GetOptional();
  2113. result.to_value = to_value.GetOptional();
  2114. std::vector<std::string> codecs_thresholds;
  2115. if (rtc::split(*codec_thresholds_string, '|', &codecs_thresholds) == 0) {
  2116. return {};
  2117. }
  2118. for (const std::string& codec_threshold : codecs_thresholds) {
  2119. std::vector<std::string> thresholds_split;
  2120. if (rtc::split(codec_threshold, ';', &thresholds_split) != 3) {
  2121. return {};
  2122. }
  2123. VideoCodecType codec = PayloadStringToCodecType(thresholds_split[0]);
  2124. int bitrate_kbps;
  2125. rtc::FromString(thresholds_split[1], &bitrate_kbps);
  2126. int pixel_count;
  2127. rtc::FromString(thresholds_split[2], &pixel_count);
  2128. if (bitrate_kbps > 0) {
  2129. result.codec_thresholds[codec].bitrate = DataRate::kbps(bitrate_kbps);
  2130. }
  2131. if (pixel_count > 0) {
  2132. result.codec_thresholds[codec].pixel_count = pixel_count;
  2133. }
  2134. if (!result.codec_thresholds[codec].bitrate &&
  2135. !result.codec_thresholds[codec].pixel_count) {
  2136. return {};
  2137. }
  2138. }
  2139. rtc::StringBuilder ss;
  2140. ss << "Successfully parsed WebRTC-NetworkCondition-EncoderSwitch field "
  2141. "trial."
  2142. << " to_codec:" << result.to_codec
  2143. << " to_param:" << result.to_param.value_or("<none>")
  2144. << " to_value:" << result.to_value.value_or("<none>")
  2145. << " codec_thresholds:";
  2146. for (auto kv : result.codec_thresholds) {
  2147. std::string codec_name = CodecTypeToPayloadString(kv.first);
  2148. std::string bitrate = kv.second.bitrate
  2149. ? std::to_string(kv.second.bitrate->kbps())
  2150. : "<none>";
  2151. std::string pixels = kv.second.pixel_count
  2152. ? std::to_string(*kv.second.pixel_count)
  2153. : "<none>";
  2154. ss << " (" << codec_name << ":" << bitrate << ":" << pixels << ")";
  2155. }
  2156. RTC_LOG(LS_INFO) << ss.str();
  2157. return result;
  2158. }
  2159. } // namespace webrtc