blob: 7ec7ab3cbce2bb5fe8f198a37849c914bc293969 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
stefan@webrtc.org07b45a52012-02-02 08:37:48 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "video/video_stream_encoder.h"
mflodman@webrtc.org84d17832011-12-01 17:02:23 +000012
stefan@webrtc.orgc3cc3752013-06-04 09:36:56 +000013#include <algorithm>
perkj57c21f92016-06-17 07:27:16 -070014#include <limits>
sprangc5d62e22017-04-02 23:53:04 -070015#include <numeric>
Per512ecb32016-09-23 15:52:06 +020016#include <utility>
niklase@google.com470e71d2011-07-07 08:21:25 +000017
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "api/video/i420_buffer.h"
19#include "common_video/include/video_bitrate_allocator.h"
20#include "common_video/include/video_frame.h"
21#include "modules/pacing/paced_sender.h"
22#include "modules/video_coding/codecs/vp8/temporal_layers.h"
23#include "modules/video_coding/include/video_codec_initializer.h"
24#include "modules/video_coding/include/video_coding.h"
25#include "modules/video_coding/include/video_coding_defines.h"
26#include "rtc_base/arraysize.h"
27#include "rtc_base/checks.h"
28#include "rtc_base/location.h"
29#include "rtc_base/logging.h"
30#include "rtc_base/timeutils.h"
31#include "rtc_base/trace_event.h"
32#include "video/overuse_frame_detector.h"
33#include "video/send_statistics_proxy.h"
nisseea3a7982017-05-15 02:42:11 -070034
niklase@google.com470e71d2011-07-07 08:21:25 +000035namespace webrtc {
36
perkj26091b12016-09-01 01:17:40 -070037namespace {
sprangb1ca0732017-02-01 08:38:12 -080038
asapersson6ffb67d2016-09-12 00:10:45 -070039// Time interval for logging frame counts.
40const int64_t kFrameLogIntervalMs = 60000;
sprangc5d62e22017-04-02 23:53:04 -070041const int kMinFramerateFps = 2;
sprangfda496a2017-06-15 04:21:07 -070042const int kMaxFramerateFps = 120;
perkj26091b12016-09-01 01:17:40 -070043
kthelgason2bc68642017-02-07 07:02:22 -080044// The maximum number of frames to drop at beginning of stream
45// to try and achieve desired bitrate.
46const int kMaxInitialFramedrop = 4;
47
kthelgason2bc68642017-02-07 07:02:22 -080048uint32_t MaximumFrameSizeForBitrate(uint32_t kbps) {
49 if (kbps > 0) {
50 if (kbps < 300 /* qvga */) {
51 return 320 * 240;
52 } else if (kbps < 500 /* vga */) {
53 return 640 * 480;
54 }
55 }
56 return std::numeric_limits<uint32_t>::max();
57}
58
asaperssonf7e294d2017-06-13 23:25:22 -070059// Initial limits for kBalanced degradation preference.
60int MinFps(int pixels) {
61 if (pixels <= 320 * 240) {
62 return 7;
63 } else if (pixels <= 480 * 270) {
64 return 10;
65 } else if (pixels <= 640 * 480) {
66 return 15;
67 } else {
68 return std::numeric_limits<int>::max();
69 }
70}
71
72int MaxFps(int pixels) {
73 if (pixels <= 320 * 240) {
74 return 10;
75 } else if (pixels <= 480 * 270) {
76 return 15;
77 } else {
78 return std::numeric_limits<int>::max();
79 }
80}
81
asapersson09f05612017-05-15 23:40:18 -070082bool IsResolutionScalingEnabled(
83 VideoSendStream::DegradationPreference degradation_preference) {
84 return degradation_preference ==
85 VideoSendStream::DegradationPreference::kMaintainFramerate ||
86 degradation_preference ==
87 VideoSendStream::DegradationPreference::kBalanced;
88}
89
90bool IsFramerateScalingEnabled(
91 VideoSendStream::DegradationPreference degradation_preference) {
92 return degradation_preference ==
93 VideoSendStream::DegradationPreference::kMaintainResolution ||
94 degradation_preference ==
95 VideoSendStream::DegradationPreference::kBalanced;
96}
97
perkj26091b12016-09-01 01:17:40 -070098} // namespace
99
mflodmancc3d4422017-08-03 08:27:51 -0700100class VideoStreamEncoder::ConfigureEncoderTask : public rtc::QueuedTask {
Pera48ddb72016-09-29 11:48:50 +0200101 public:
mflodmancc3d4422017-08-03 08:27:51 -0700102 ConfigureEncoderTask(VideoStreamEncoder* video_stream_encoder,
Pera48ddb72016-09-29 11:48:50 +0200103 VideoEncoderConfig config,
asapersson5f7226f2016-11-25 04:37:00 -0800104 size_t max_data_payload_length,
105 bool nack_enabled)
mflodmancc3d4422017-08-03 08:27:51 -0700106 : video_stream_encoder_(video_stream_encoder),
Pera48ddb72016-09-29 11:48:50 +0200107 config_(std::move(config)),
asapersson5f7226f2016-11-25 04:37:00 -0800108 max_data_payload_length_(max_data_payload_length),
109 nack_enabled_(nack_enabled) {}
Pera48ddb72016-09-29 11:48:50 +0200110
111 private:
112 bool Run() override {
mflodmancc3d4422017-08-03 08:27:51 -0700113 video_stream_encoder_->ConfigureEncoderOnTaskQueue(
asapersson5f7226f2016-11-25 04:37:00 -0800114 std::move(config_), max_data_payload_length_, nack_enabled_);
Pera48ddb72016-09-29 11:48:50 +0200115 return true;
116 }
117
mflodmancc3d4422017-08-03 08:27:51 -0700118 VideoStreamEncoder* const video_stream_encoder_;
Pera48ddb72016-09-29 11:48:50 +0200119 VideoEncoderConfig config_;
120 size_t max_data_payload_length_;
asapersson5f7226f2016-11-25 04:37:00 -0800121 bool nack_enabled_;
Pera48ddb72016-09-29 11:48:50 +0200122};
123
mflodmancc3d4422017-08-03 08:27:51 -0700124class VideoStreamEncoder::EncodeTask : public rtc::QueuedTask {
perkj26091b12016-09-01 01:17:40 -0700125 public:
perkjd52063f2016-09-07 06:32:18 -0700126 EncodeTask(const VideoFrame& frame,
mflodmancc3d4422017-08-03 08:27:51 -0700127 VideoStreamEncoder* video_stream_encoder,
nissee0e3bdf2017-01-18 02:16:20 -0800128 int64_t time_when_posted_us,
asapersson6ffb67d2016-09-12 00:10:45 -0700129 bool log_stats)
nissedf2ceb82016-12-15 06:29:53 -0800130 : frame_(frame),
mflodmancc3d4422017-08-03 08:27:51 -0700131 video_stream_encoder_(video_stream_encoder),
nissee0e3bdf2017-01-18 02:16:20 -0800132 time_when_posted_us_(time_when_posted_us),
asapersson6ffb67d2016-09-12 00:10:45 -0700133 log_stats_(log_stats) {
mflodmancc3d4422017-08-03 08:27:51 -0700134 ++video_stream_encoder_->posted_frames_waiting_for_encode_;
perkj26091b12016-09-01 01:17:40 -0700135 }
136
137 private:
138 bool Run() override {
mflodmancc3d4422017-08-03 08:27:51 -0700139 RTC_DCHECK_RUN_ON(&video_stream_encoder_->encoder_queue_);
mflodmancc3d4422017-08-03 08:27:51 -0700140 video_stream_encoder_->stats_proxy_->OnIncomingFrame(frame_.width(),
141 frame_.height());
142 ++video_stream_encoder_->captured_frame_count_;
Yuwei Huangd9f99c12017-10-24 15:40:52 -0700143 const int posted_frames_waiting_for_encode =
144 video_stream_encoder_->posted_frames_waiting_for_encode_.fetch_sub(1);
145 RTC_DCHECK_GT(posted_frames_waiting_for_encode, 0);
146 if (posted_frames_waiting_for_encode == 1) {
mflodmancc3d4422017-08-03 08:27:51 -0700147 video_stream_encoder_->EncodeVideoFrame(frame_, time_when_posted_us_);
perkj26091b12016-09-01 01:17:40 -0700148 } else {
149 // There is a newer frame in flight. Do not encode this frame.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100150 RTC_LOG(LS_VERBOSE)
perkj26091b12016-09-01 01:17:40 -0700151 << "Incoming frame dropped due to that the encoder is blocked.";
mflodmancc3d4422017-08-03 08:27:51 -0700152 ++video_stream_encoder_->dropped_frame_count_;
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200153 video_stream_encoder_->stats_proxy_->OnFrameDroppedInEncoderQueue();
asapersson6ffb67d2016-09-12 00:10:45 -0700154 }
155 if (log_stats_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100156 RTC_LOG(LS_INFO) << "Number of frames: captured "
157 << video_stream_encoder_->captured_frame_count_
158 << ", dropped (due to encoder blocked) "
159 << video_stream_encoder_->dropped_frame_count_
160 << ", interval_ms " << kFrameLogIntervalMs;
mflodmancc3d4422017-08-03 08:27:51 -0700161 video_stream_encoder_->captured_frame_count_ = 0;
162 video_stream_encoder_->dropped_frame_count_ = 0;
perkj26091b12016-09-01 01:17:40 -0700163 }
164 return true;
165 }
166 VideoFrame frame_;
mflodmancc3d4422017-08-03 08:27:51 -0700167 VideoStreamEncoder* const video_stream_encoder_;
nissee0e3bdf2017-01-18 02:16:20 -0800168 const int64_t time_when_posted_us_;
asapersson6ffb67d2016-09-12 00:10:45 -0700169 const bool log_stats_;
perkj26091b12016-09-01 01:17:40 -0700170};
171
perkja49cbd32016-09-16 07:53:41 -0700172// VideoSourceProxy is responsible ensuring thread safety between calls to
mflodmancc3d4422017-08-03 08:27:51 -0700173// VideoStreamEncoder::SetSource that will happen on libjingle's worker thread
174// when a video capturer is connected to the encoder and the encoder task queue
perkja49cbd32016-09-16 07:53:41 -0700175// (encoder_queue_) where the encoder reports its VideoSinkWants.
mflodmancc3d4422017-08-03 08:27:51 -0700176class VideoStreamEncoder::VideoSourceProxy {
perkja49cbd32016-09-16 07:53:41 -0700177 public:
mflodmancc3d4422017-08-03 08:27:51 -0700178 explicit VideoSourceProxy(VideoStreamEncoder* video_stream_encoder)
179 : video_stream_encoder_(video_stream_encoder),
hbos8d609f62017-04-10 07:39:05 -0700180 degradation_preference_(
181 VideoSendStream::DegradationPreference::kDegradationDisabled),
perkj803d97f2016-11-01 11:45:46 -0700182 source_(nullptr) {}
perkja49cbd32016-09-16 07:53:41 -0700183
hbos8d609f62017-04-10 07:39:05 -0700184 void SetSource(
185 rtc::VideoSourceInterface<VideoFrame>* source,
186 const VideoSendStream::DegradationPreference& degradation_preference) {
perkj803d97f2016-11-01 11:45:46 -0700187 // Called on libjingle's worker thread.
perkja49cbd32016-09-16 07:53:41 -0700188 RTC_DCHECK_CALLED_SEQUENTIALLY(&main_checker_);
189 rtc::VideoSourceInterface<VideoFrame>* old_source = nullptr;
perkj803d97f2016-11-01 11:45:46 -0700190 rtc::VideoSinkWants wants;
perkja49cbd32016-09-16 07:53:41 -0700191 {
192 rtc::CritScope lock(&crit_);
sprangc5d62e22017-04-02 23:53:04 -0700193 degradation_preference_ = degradation_preference;
perkja49cbd32016-09-16 07:53:41 -0700194 old_source = source_;
195 source_ = source;
sprangfda496a2017-06-15 04:21:07 -0700196 wants = GetActiveSinkWantsInternal();
perkja49cbd32016-09-16 07:53:41 -0700197 }
198
199 if (old_source != source && old_source != nullptr) {
mflodmancc3d4422017-08-03 08:27:51 -0700200 old_source->RemoveSink(video_stream_encoder_);
perkja49cbd32016-09-16 07:53:41 -0700201 }
202
203 if (!source) {
204 return;
205 }
206
mflodmancc3d4422017-08-03 08:27:51 -0700207 source->AddOrUpdateSink(video_stream_encoder_, wants);
perkja49cbd32016-09-16 07:53:41 -0700208 }
209
perkj803d97f2016-11-01 11:45:46 -0700210 void SetWantsRotationApplied(bool rotation_applied) {
211 rtc::CritScope lock(&crit_);
212 sink_wants_.rotation_applied = rotation_applied;
sprangc5d62e22017-04-02 23:53:04 -0700213 if (source_)
mflodmancc3d4422017-08-03 08:27:51 -0700214 source_->AddOrUpdateSink(video_stream_encoder_, sink_wants_);
sprangc5d62e22017-04-02 23:53:04 -0700215 }
216
sprangfda496a2017-06-15 04:21:07 -0700217 rtc::VideoSinkWants GetActiveSinkWants() {
218 rtc::CritScope lock(&crit_);
219 return GetActiveSinkWantsInternal();
perkj803d97f2016-11-01 11:45:46 -0700220 }
221
asaperssonf7e294d2017-06-13 23:25:22 -0700222 void ResetPixelFpsCount() {
223 rtc::CritScope lock(&crit_);
224 sink_wants_.max_pixel_count = std::numeric_limits<int>::max();
225 sink_wants_.target_pixel_count.reset();
226 sink_wants_.max_framerate_fps = std::numeric_limits<int>::max();
227 if (source_)
mflodmancc3d4422017-08-03 08:27:51 -0700228 source_->AddOrUpdateSink(video_stream_encoder_, sink_wants_);
asaperssonf7e294d2017-06-13 23:25:22 -0700229 }
230
Ã…sa Perssonc3ed6302017-11-16 14:04:52 +0100231 bool RequestResolutionLowerThan(int pixel_count,
232 int min_pixels_per_frame,
233 bool* min_pixels_reached) {
perkj803d97f2016-11-01 11:45:46 -0700234 // Called on the encoder task queue.
235 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700236 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700237 // This can happen since |degradation_preference_| is set on libjingle's
238 // worker thread but the adaptation is done on the encoder task queue.
asaperssond0de2952017-04-21 01:47:31 -0700239 return false;
perkj803d97f2016-11-01 11:45:46 -0700240 }
asapersson13874762017-06-07 00:01:02 -0700241 // The input video frame size will have a resolution less than or equal to
242 // |max_pixel_count| depending on how the source can scale the frame size.
kthelgason5e13d412016-12-01 03:59:51 -0800243 const int pixels_wanted = (pixel_count * 3) / 5;
Ã…sa Perssonc3ed6302017-11-16 14:04:52 +0100244 if (pixels_wanted >= sink_wants_.max_pixel_count) {
245 return false;
246 }
247 if (pixels_wanted < min_pixels_per_frame) {
248 *min_pixels_reached = true;
asaperssond0de2952017-04-21 01:47:31 -0700249 return false;
asapersson13874762017-06-07 00:01:02 -0700250 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100251 RTC_LOG(LS_INFO) << "Scaling down resolution, max pixels: "
252 << pixels_wanted;
sprangc5d62e22017-04-02 23:53:04 -0700253 sink_wants_.max_pixel_count = pixels_wanted;
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100254 sink_wants_.target_pixel_count = rtc::nullopt;
mflodmancc3d4422017-08-03 08:27:51 -0700255 source_->AddOrUpdateSink(video_stream_encoder_,
256 GetActiveSinkWantsInternal());
asaperssond0de2952017-04-21 01:47:31 -0700257 return true;
sprangc5d62e22017-04-02 23:53:04 -0700258 }
259
sprangfda496a2017-06-15 04:21:07 -0700260 int RequestFramerateLowerThan(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700261 // Called on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700262 // The input video frame rate will be scaled down to 2/3, rounding down.
sprangfda496a2017-06-15 04:21:07 -0700263 int framerate_wanted = (fps * 2) / 3;
264 return RestrictFramerate(framerate_wanted) ? framerate_wanted : -1;
perkj803d97f2016-11-01 11:45:46 -0700265 }
266
asapersson13874762017-06-07 00:01:02 -0700267 bool RequestHigherResolutionThan(int pixel_count) {
268 // Called on the encoder task queue.
perkj803d97f2016-11-01 11:45:46 -0700269 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700270 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700271 // This can happen since |degradation_preference_| is set on libjingle's
272 // worker thread but the adaptation is done on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700273 return false;
perkj803d97f2016-11-01 11:45:46 -0700274 }
asapersson13874762017-06-07 00:01:02 -0700275 int max_pixels_wanted = pixel_count;
276 if (max_pixels_wanted != std::numeric_limits<int>::max())
277 max_pixels_wanted = pixel_count * 4;
sprangc5d62e22017-04-02 23:53:04 -0700278
asapersson13874762017-06-07 00:01:02 -0700279 if (max_pixels_wanted <= sink_wants_.max_pixel_count)
280 return false;
281
282 sink_wants_.max_pixel_count = max_pixels_wanted;
283 if (max_pixels_wanted == std::numeric_limits<int>::max()) {
sprangc5d62e22017-04-02 23:53:04 -0700284 // Remove any constraints.
285 sink_wants_.target_pixel_count.reset();
sprangc5d62e22017-04-02 23:53:04 -0700286 } else {
287 // On step down we request at most 3/5 the pixel count of the previous
288 // resolution, so in order to take "one step up" we request a resolution
289 // as close as possible to 5/3 of the current resolution. The actual pixel
290 // count selected depends on the capabilities of the source. In order to
291 // not take a too large step up, we cap the requested pixel count to be at
292 // most four time the current number of pixels.
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100293 sink_wants_.target_pixel_count = (pixel_count * 5) / 3;
sprangc5d62e22017-04-02 23:53:04 -0700294 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100295 RTC_LOG(LS_INFO) << "Scaling up resolution, max pixels: "
296 << max_pixels_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700297 source_->AddOrUpdateSink(video_stream_encoder_,
298 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700299 return true;
sprangc5d62e22017-04-02 23:53:04 -0700300 }
301
sprangfda496a2017-06-15 04:21:07 -0700302 // Request upgrade in framerate. Returns the new requested frame, or -1 if
303 // no change requested. Note that maxint may be returned if limits due to
304 // adaptation requests are removed completely. In that case, consider
305 // |max_framerate_| to be the current limit (assuming the capturer complies).
306 int RequestHigherFramerateThan(int fps) {
asapersson13874762017-06-07 00:01:02 -0700307 // Called on the encoder task queue.
308 // The input frame rate will be scaled up to the last step, with rounding.
309 int framerate_wanted = fps;
310 if (fps != std::numeric_limits<int>::max())
311 framerate_wanted = (fps * 3) / 2;
312
sprangfda496a2017-06-15 04:21:07 -0700313 return IncreaseFramerate(framerate_wanted) ? framerate_wanted : -1;
asapersson13874762017-06-07 00:01:02 -0700314 }
315
316 bool RestrictFramerate(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700317 // Called on the encoder task queue.
318 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700319 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
320 return false;
321
322 const int fps_wanted = std::max(kMinFramerateFps, fps);
323 if (fps_wanted >= sink_wants_.max_framerate_fps)
324 return false;
325
Mirko Bonadei675513b2017-11-09 11:09:25 +0100326 RTC_LOG(LS_INFO) << "Scaling down framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700327 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700328 source_->AddOrUpdateSink(video_stream_encoder_,
329 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700330 return true;
331 }
332
333 bool IncreaseFramerate(int fps) {
334 // Called on the encoder task queue.
335 rtc::CritScope lock(&crit_);
336 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
337 return false;
338
339 const int fps_wanted = std::max(kMinFramerateFps, fps);
340 if (fps_wanted <= sink_wants_.max_framerate_fps)
341 return false;
342
Mirko Bonadei675513b2017-11-09 11:09:25 +0100343 RTC_LOG(LS_INFO) << "Scaling up framerate: " << fps_wanted;
asapersson13874762017-06-07 00:01:02 -0700344 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700345 source_->AddOrUpdateSink(video_stream_encoder_,
346 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700347 return true;
perkj803d97f2016-11-01 11:45:46 -0700348 }
349
perkja49cbd32016-09-16 07:53:41 -0700350 private:
sprangfda496a2017-06-15 04:21:07 -0700351 rtc::VideoSinkWants GetActiveSinkWantsInternal()
danilchapa37de392017-09-09 04:17:22 -0700352 RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
sprangfda496a2017-06-15 04:21:07 -0700353 rtc::VideoSinkWants wants = sink_wants_;
354 // Clear any constraints from the current sink wants that don't apply to
355 // the used degradation_preference.
356 switch (degradation_preference_) {
357 case VideoSendStream::DegradationPreference::kBalanced:
358 break;
359 case VideoSendStream::DegradationPreference::kMaintainFramerate:
360 wants.max_framerate_fps = std::numeric_limits<int>::max();
361 break;
362 case VideoSendStream::DegradationPreference::kMaintainResolution:
363 wants.max_pixel_count = std::numeric_limits<int>::max();
364 wants.target_pixel_count.reset();
365 break;
366 case VideoSendStream::DegradationPreference::kDegradationDisabled:
367 wants.max_pixel_count = std::numeric_limits<int>::max();
368 wants.target_pixel_count.reset();
369 wants.max_framerate_fps = std::numeric_limits<int>::max();
370 }
371 return wants;
372 }
373
perkja49cbd32016-09-16 07:53:41 -0700374 rtc::CriticalSection crit_;
375 rtc::SequencedTaskChecker main_checker_;
mflodmancc3d4422017-08-03 08:27:51 -0700376 VideoStreamEncoder* const video_stream_encoder_;
danilchapa37de392017-09-09 04:17:22 -0700377 rtc::VideoSinkWants sink_wants_ RTC_GUARDED_BY(&crit_);
hbos8d609f62017-04-10 07:39:05 -0700378 VideoSendStream::DegradationPreference degradation_preference_
danilchapa37de392017-09-09 04:17:22 -0700379 RTC_GUARDED_BY(&crit_);
380 rtc::VideoSourceInterface<VideoFrame>* source_ RTC_GUARDED_BY(&crit_);
perkja49cbd32016-09-16 07:53:41 -0700381
382 RTC_DISALLOW_COPY_AND_ASSIGN(VideoSourceProxy);
383};
384
Ã…sa Persson0122e842017-10-16 12:19:23 +0200385VideoStreamEncoder::VideoStreamEncoder(
386 uint32_t number_of_cores,
387 SendStatisticsProxy* stats_proxy,
388 const VideoSendStream::Config::EncoderSettings& settings,
389 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback,
Ã…sa Persson0122e842017-10-16 12:19:23 +0200390 std::unique_ptr<OveruseFrameDetector> overuse_detector)
perkj26091b12016-09-01 01:17:40 -0700391 : shutdown_event_(true /* manual_reset */, false),
392 number_of_cores_(number_of_cores),
kthelgason2bc68642017-02-07 07:02:22 -0800393 initial_rampup_(0),
perkja49cbd32016-09-16 07:53:41 -0700394 source_proxy_(new VideoSourceProxy(this)),
Pera48ddb72016-09-29 11:48:50 +0200395 sink_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700396 settings_(settings),
kthelgason1cdddc92017-08-24 03:52:48 -0700397 codec_type_(PayloadStringToCodecType(settings.payload_name)),
Niels Möllera0565992017-10-24 11:37:08 +0200398 video_sender_(Clock::GetRealTimeClock(), this),
sprangfda496a2017-06-15 04:21:07 -0700399 overuse_detector_(
400 overuse_detector.get()
401 ? overuse_detector.release()
402 : new OveruseFrameDetector(
403 GetCpuOveruseOptions(settings.full_overuse_time),
404 this,
sprangfda496a2017-06-15 04:21:07 -0700405 stats_proxy)),
Peter Boström7083e112015-09-22 16:28:51 +0200406 stats_proxy_(stats_proxy),
perkj26091b12016-09-01 01:17:40 -0700407 pre_encode_callback_(pre_encode_callback),
sprangfda496a2017-06-15 04:21:07 -0700408 max_framerate_(-1),
perkjfa10b552016-10-02 23:45:26 -0700409 pending_encoder_reconfiguration_(false),
perkj26091b12016-09-01 01:17:40 -0700410 encoder_start_bitrate_bps_(0),
Pera48ddb72016-09-29 11:48:50 +0200411 max_data_payload_length_(0),
asapersson5f7226f2016-11-25 04:37:00 -0800412 nack_enabled_(false),
pbos@webrtc.org143451d2015-03-18 14:40:03 +0000413 last_observed_bitrate_bps_(0),
stefan@webrtc.org792f1a12015-03-04 12:24:26 +0000414 encoder_paused_and_dropped_frame_(false),
perkj26091b12016-09-01 01:17:40 -0700415 clock_(Clock::GetRealTimeClock()),
hbos8d609f62017-04-10 07:39:05 -0700416 degradation_preference_(
417 VideoSendStream::DegradationPreference::kDegradationDisabled),
Yuwei Huangd9f99c12017-10-24 15:40:52 -0700418 posted_frames_waiting_for_encode_(0),
perkj26091b12016-09-01 01:17:40 -0700419 last_captured_timestamp_(0),
420 delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
421 clock_->TimeInMilliseconds()),
asapersson6ffb67d2016-09-12 00:10:45 -0700422 last_frame_log_ms_(clock_->TimeInMilliseconds()),
423 captured_frame_count_(0),
424 dropped_frame_count_(0),
sprang1a646ee2016-12-01 06:34:11 -0800425 bitrate_observer_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700426 encoder_queue_("EncoderQueue") {
sprang552c7c72017-02-13 04:41:45 -0800427 RTC_DCHECK(stats_proxy);
perkj803d97f2016-11-01 11:45:46 -0700428 encoder_queue_.PostTask([this] {
perkj26091b12016-09-01 01:17:40 -0700429 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700430 overuse_detector_->StartCheckForOveruse();
perkj26091b12016-09-01 01:17:40 -0700431 video_sender_.RegisterExternalEncoder(
432 settings_.encoder, settings_.payload_type, settings_.internal_source);
433 });
mflodman@webrtc.org02270cd2015-02-06 13:10:19 +0000434}
435
mflodmancc3d4422017-08-03 08:27:51 -0700436VideoStreamEncoder::~VideoStreamEncoder() {
perkja49cbd32016-09-16 07:53:41 -0700437 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 01:17:40 -0700438 RTC_DCHECK(shutdown_event_.Wait(0))
439 << "Must call ::Stop() before destruction.";
440}
441
sprangfda496a2017-06-15 04:21:07 -0700442// TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
443// pipelining encoders better (multiple input frames before something comes
444// out). This should effectively turn off CPU adaptations for systems that
445// remotely cope with the load right now.
mflodmancc3d4422017-08-03 08:27:51 -0700446CpuOveruseOptions VideoStreamEncoder::GetCpuOveruseOptions(
447 bool full_overuse_time) {
sprangfda496a2017-06-15 04:21:07 -0700448 CpuOveruseOptions options;
449 if (full_overuse_time) {
450 options.low_encode_usage_threshold_percent = 150;
451 options.high_encode_usage_threshold_percent = 200;
452 }
453 return options;
454}
455
mflodmancc3d4422017-08-03 08:27:51 -0700456void VideoStreamEncoder::Stop() {
perkja49cbd32016-09-16 07:53:41 -0700457 RTC_DCHECK_RUN_ON(&thread_checker_);
hbos8d609f62017-04-10 07:39:05 -0700458 source_proxy_->SetSource(nullptr, VideoSendStream::DegradationPreference());
perkja49cbd32016-09-16 07:53:41 -0700459 encoder_queue_.PostTask([this] {
460 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700461 overuse_detector_->StopCheckForOveruse();
Erik Språng08127a92016-11-16 16:41:30 +0100462 rate_allocator_.reset();
sprang1a646ee2016-12-01 06:34:11 -0800463 bitrate_observer_ = nullptr;
perkja49cbd32016-09-16 07:53:41 -0700464 video_sender_.RegisterExternalEncoder(nullptr, settings_.payload_type,
465 false);
kthelgason876222f2016-11-29 01:44:11 -0800466 quality_scaler_ = nullptr;
perkja49cbd32016-09-16 07:53:41 -0700467 shutdown_event_.Set();
468 });
469
470 shutdown_event_.Wait(rtc::Event::kForever);
perkj26091b12016-09-01 01:17:40 -0700471}
472
mflodmancc3d4422017-08-03 08:27:51 -0700473void VideoStreamEncoder::SetBitrateObserver(
sprang1a646ee2016-12-01 06:34:11 -0800474 VideoBitrateAllocationObserver* bitrate_observer) {
475 RTC_DCHECK_RUN_ON(&thread_checker_);
476 encoder_queue_.PostTask([this, bitrate_observer] {
477 RTC_DCHECK_RUN_ON(&encoder_queue_);
478 RTC_DCHECK(!bitrate_observer_);
479 bitrate_observer_ = bitrate_observer;
480 });
481}
482
mflodmancc3d4422017-08-03 08:27:51 -0700483void VideoStreamEncoder::SetSource(
perkj803d97f2016-11-01 11:45:46 -0700484 rtc::VideoSourceInterface<VideoFrame>* source,
asapersson09f05612017-05-15 23:40:18 -0700485 const VideoSendStream::DegradationPreference& degradation_preference) {
perkja49cbd32016-09-16 07:53:41 -0700486 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj803d97f2016-11-01 11:45:46 -0700487 source_proxy_->SetSource(source, degradation_preference);
488 encoder_queue_.PostTask([this, degradation_preference] {
489 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700490 if (degradation_preference_ != degradation_preference) {
491 // Reset adaptation state, so that we're not tricked into thinking there's
492 // an already pending request of the same type.
493 last_adaptation_request_.reset();
asaperssonf7e294d2017-06-13 23:25:22 -0700494 if (degradation_preference ==
495 VideoSendStream::DegradationPreference::kBalanced ||
496 degradation_preference_ ==
497 VideoSendStream::DegradationPreference::kBalanced) {
498 // TODO(asapersson): Consider removing |adapt_counters_| map and use one
499 // AdaptCounter for all modes.
500 source_proxy_->ResetPixelFpsCount();
501 adapt_counters_.clear();
502 }
sprangc5d62e22017-04-02 23:53:04 -0700503 }
sprangb1ca0732017-02-01 08:38:12 -0800504 degradation_preference_ = degradation_preference;
asapersson91914e22017-06-01 00:34:08 -0700505 bool allow_scaling = IsResolutionScalingEnabled(degradation_preference_);
sprangc5d62e22017-04-02 23:53:04 -0700506 initial_rampup_ = allow_scaling ? 0 : kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 07:02:22 -0800507 ConfigureQualityScaler();
Niels Möller7dc26b72017-12-06 10:27:48 +0100508 if (!IsFramerateScalingEnabled(degradation_preference) &&
509 max_framerate_ != -1) {
510 // If frame rate scaling is no longer allowed, remove any potential
511 // allowance for longer frame intervals.
512 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
513 }
perkj803d97f2016-11-01 11:45:46 -0700514 });
perkja49cbd32016-09-16 07:53:41 -0700515}
516
mflodmancc3d4422017-08-03 08:27:51 -0700517void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
perkj803d97f2016-11-01 11:45:46 -0700518 source_proxy_->SetWantsRotationApplied(rotation_applied);
perkj26091b12016-09-01 01:17:40 -0700519 encoder_queue_.PostTask([this, sink] {
520 RTC_DCHECK_RUN_ON(&encoder_queue_);
521 sink_ = sink;
522 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000523}
524
mflodmancc3d4422017-08-03 08:27:51 -0700525void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
perkj26091b12016-09-01 01:17:40 -0700526 encoder_queue_.PostTask([this, start_bitrate_bps] {
527 RTC_DCHECK_RUN_ON(&encoder_queue_);
528 encoder_start_bitrate_bps_ = start_bitrate_bps;
529 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000530}
Peter Boström00b9d212016-05-19 16:59:03 +0200531
mflodmancc3d4422017-08-03 08:27:51 -0700532void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
533 size_t max_data_payload_length,
534 bool nack_enabled) {
Pera48ddb72016-09-29 11:48:50 +0200535 encoder_queue_.PostTask(
536 std::unique_ptr<rtc::QueuedTask>(new ConfigureEncoderTask(
asapersson5f7226f2016-11-25 04:37:00 -0800537 this, std::move(config), max_data_payload_length, nack_enabled)));
perkj26091b12016-09-01 01:17:40 -0700538}
539
mflodmancc3d4422017-08-03 08:27:51 -0700540void VideoStreamEncoder::ConfigureEncoderOnTaskQueue(
541 VideoEncoderConfig config,
542 size_t max_data_payload_length,
543 bool nack_enabled) {
perkj26091b12016-09-01 01:17:40 -0700544 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -0700545 RTC_DCHECK(sink_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100546 RTC_LOG(LS_INFO) << "ConfigureEncoder requested.";
Pera48ddb72016-09-29 11:48:50 +0200547
548 max_data_payload_length_ = max_data_payload_length;
asapersson5f7226f2016-11-25 04:37:00 -0800549 nack_enabled_ = nack_enabled;
Pera48ddb72016-09-29 11:48:50 +0200550 encoder_config_ = std::move(config);
perkjfa10b552016-10-02 23:45:26 -0700551 pending_encoder_reconfiguration_ = true;
Pera48ddb72016-09-29 11:48:50 +0200552
perkjfa10b552016-10-02 23:45:26 -0700553 // Reconfigure the encoder now if the encoder has an internal source or
Per21d45d22016-10-30 21:37:57 +0100554 // if the frame resolution is known. Otherwise, the reconfiguration is
555 // deferred until the next frame to minimize the number of reconfigurations.
556 // The codec configuration depends on incoming video frame size.
557 if (last_frame_info_) {
558 ReconfigureEncoder();
559 } else if (settings_.internal_source) {
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100560 last_frame_info_ = VideoFrameInfo(176, 144, false);
perkjfa10b552016-10-02 23:45:26 -0700561 ReconfigureEncoder();
562 }
563}
perkj26091b12016-09-01 01:17:40 -0700564
mflodmancc3d4422017-08-03 08:27:51 -0700565void VideoStreamEncoder::ReconfigureEncoder() {
perkjfa10b552016-10-02 23:45:26 -0700566 RTC_DCHECK_RUN_ON(&encoder_queue_);
567 RTC_DCHECK(pending_encoder_reconfiguration_);
568 std::vector<VideoStream> streams =
569 encoder_config_.video_stream_factory->CreateEncoderStreams(
570 last_frame_info_->width, last_frame_info_->height, encoder_config_);
perkj26091b12016-09-01 01:17:40 -0700571
ilnik6b826ef2017-06-16 06:53:48 -0700572 // TODO(ilnik): If configured resolution is significantly less than provided,
573 // e.g. because there are not enough SSRCs for all simulcast streams,
574 // signal new resolutions via SinkWants to video source.
575
576 // Stream dimensions may be not equal to given because of a simulcast
577 // restrictions.
578 int highest_stream_width = static_cast<int>(streams.back().width);
579 int highest_stream_height = static_cast<int>(streams.back().height);
580 // Dimension may be reduced to be, e.g. divisible by 4.
581 RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
582 RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
583 crop_width_ = last_frame_info_->width - highest_stream_width;
584 crop_height_ = last_frame_info_->height - highest_stream_height;
585
Erik Språng08127a92016-11-16 16:41:30 +0100586 VideoCodec codec;
587 if (!VideoCodecInitializer::SetupCodec(encoder_config_, settings_, streams,
asapersson5f7226f2016-11-25 04:37:00 -0800588 nack_enabled_, &codec,
589 &rate_allocator_)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100590 RTC_LOG(LS_ERROR) << "Failed to create encoder configuration.";
Erik Språng08127a92016-11-16 16:41:30 +0100591 }
perkjfa10b552016-10-02 23:45:26 -0700592
593 codec.startBitrate =
594 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
595 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
596 codec.expect_encode_from_texture = last_frame_info_->is_texture;
sprangfda496a2017-06-15 04:21:07 -0700597 max_framerate_ = codec.maxFramerate;
598 RTC_DCHECK_LE(max_framerate_, kMaxFramerateFps);
Stefan Holmere5904162015-03-26 11:11:06 +0100599
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200600 bool success = video_sender_.RegisterSendCodec(
perkjfa10b552016-10-02 23:45:26 -0700601 &codec, number_of_cores_,
602 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK;
Peter Boström905f8e72016-03-02 16:59:56 +0100603 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100604 RTC_LOG(LS_ERROR) << "Failed to configure encoder.";
sprangfe627f32017-03-29 08:24:59 -0700605 rate_allocator_.reset();
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000606 }
Peter Boström905f8e72016-03-02 16:59:56 +0100607
ilnik35b7de42017-03-15 04:24:21 -0700608 video_sender_.UpdateChannelParemeters(rate_allocator_.get(),
609 bitrate_observer_);
610
sprangfda496a2017-06-15 04:21:07 -0700611 // Get the current actual framerate, as measured by the stats proxy. This is
612 // used to get the correct bitrate layer allocation.
613 int current_framerate = stats_proxy_->GetSendFrameRate();
614 if (current_framerate == 0)
615 current_framerate = codec.maxFramerate;
sprang552c7c72017-02-13 04:41:45 -0800616 stats_proxy_->OnEncoderReconfigured(
Ã…sa Perssonaa329e72017-12-15 15:54:44 +0100617 encoder_config_, streams,
sprangfda496a2017-06-15 04:21:07 -0700618 rate_allocator_.get()
619 ? rate_allocator_->GetPreferredBitrateBps(current_framerate)
620 : codec.maxBitrate);
Per512ecb32016-09-23 15:52:06 +0200621
perkjfa10b552016-10-02 23:45:26 -0700622 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 16:41:30 +0100623
Pera48ddb72016-09-29 11:48:50 +0200624 sink_->OnEncoderConfigurationChanged(
perkjfa10b552016-10-02 23:45:26 -0700625 std::move(streams), encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 01:44:11 -0800626
Niels Möller7dc26b72017-12-06 10:27:48 +0100627 // Get the current target framerate, ie the maximum framerate as specified by
628 // the current codec configuration, or any limit imposed by cpu adaption in
629 // maintain-resolution or balanced mode. This is used to make sure overuse
630 // detection doesn't needlessly trigger in low and/or variable framerate
631 // scenarios.
632 int target_framerate = std::min(
633 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
634 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
635
kthelgason2bc68642017-02-07 07:02:22 -0800636 ConfigureQualityScaler();
637}
638
mflodmancc3d4422017-08-03 08:27:51 -0700639void VideoStreamEncoder::ConfigureQualityScaler() {
kthelgason2bc68642017-02-07 07:02:22 -0800640 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -0800641 const auto scaling_settings = settings_.encoder->GetScalingSettings();
asapersson36e9eb42017-03-31 05:29:12 -0700642 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 00:34:08 -0700643 IsResolutionScalingEnabled(degradation_preference_) &&
644 scaling_settings.enabled;
kthelgason3af6cc02017-03-22 00:25:28 -0700645
asapersson36e9eb42017-03-31 05:29:12 -0700646 if (quality_scaling_allowed) {
asapersson09f05612017-05-15 23:40:18 -0700647 if (quality_scaler_.get() == nullptr) {
648 // Quality scaler has not already been configured.
649 // Drop frames and scale down until desired quality is achieved.
650 if (scaling_settings.thresholds) {
651 quality_scaler_.reset(
652 new QualityScaler(this, *(scaling_settings.thresholds)));
653 } else {
654 quality_scaler_.reset(new QualityScaler(this, codec_type_));
655 }
kthelgason876222f2016-11-29 01:44:11 -0800656 }
657 } else {
658 quality_scaler_.reset(nullptr);
kthelgasonad9010c2017-02-14 00:46:51 -0800659 initial_rampup_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 01:44:11 -0800660 }
asapersson09f05612017-05-15 23:40:18 -0700661
662 stats_proxy_->SetAdaptationStats(GetActiveCounts(kCpu),
663 GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000664}
665
mflodmancc3d4422017-08-03 08:27:51 -0700666void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 01:17:40 -0700667 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 01:17:40 -0700668 VideoFrame incoming_frame = video_frame;
669
670 // Local time in webrtc time base.
ilnik04f4d122017-06-19 07:18:55 -0700671 int64_t current_time_us = clock_->TimeInMicroseconds();
672 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
673 // In some cases, e.g., when the frame from decoder is fed to encoder,
674 // the timestamp may be set to the future. As the encoding pipeline assumes
675 // capture time to be less than present time, we should reset the capture
676 // timestamps here. Otherwise there may be issues with RTP send stream.
677 if (incoming_frame.timestamp_us() > current_time_us)
678 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 01:17:40 -0700679
680 // Capture time may come from clock with an offset and drift from clock_.
681 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 10:02:22 -0800682 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 01:17:40 -0700683 capture_ntp_time_ms = video_frame.ntp_time_ms();
684 } else if (video_frame.render_time_ms() != 0) {
685 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
686 } else {
nisse1c0dea82017-01-30 02:43:18 -0800687 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 01:17:40 -0700688 }
689 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
690
691 // Convert NTP time, in ms, to RTP timestamp.
692 const int kMsToRtpTimestamp = 90;
693 incoming_frame.set_timestamp(
694 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
695
696 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
697 // We don't allow the same capture time for two frames, drop this one.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100698 RTC_LOG(LS_WARNING) << "Same/old NTP timestamp ("
699 << incoming_frame.ntp_time_ms()
700 << " <= " << last_captured_timestamp_
701 << ") for incoming frame. Dropping.";
perkj26091b12016-09-01 01:17:40 -0700702 return;
703 }
704
asapersson6ffb67d2016-09-12 00:10:45 -0700705 bool log_stats = false;
nisse1c0dea82017-01-30 02:43:18 -0800706 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
707 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 00:10:45 -0700708 log_stats = true;
709 }
710
perkj26091b12016-09-01 01:17:40 -0700711 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
asapersson6ffb67d2016-09-12 00:10:45 -0700712 encoder_queue_.PostTask(std::unique_ptr<rtc::QueuedTask>(new EncodeTask(
nissee0e3bdf2017-01-18 02:16:20 -0800713 incoming_frame, this, rtc::TimeMicros(), log_stats)));
perkj26091b12016-09-01 01:17:40 -0700714}
715
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200716void VideoStreamEncoder::OnDiscardedFrame() {
717 stats_proxy_->OnFrameDroppedBySource();
718}
719
mflodmancc3d4422017-08-03 08:27:51 -0700720bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 01:17:40 -0700721 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08 +0000722 // Pause video if paused by caller or as long as the network is down or the
723 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 07:27:16 -0700724 // If the pacer queue has grown too large or the network is down,
perkjfea93092016-05-14 00:58:48 -0700725 // last_observed_bitrate_bps_ will be 0.
perkj26091b12016-09-01 01:17:40 -0700726 return last_observed_bitrate_bps_ == 0;
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +0000727}
728
mflodmancc3d4422017-08-03 08:27:51 -0700729void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 01:17:40 -0700730 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000731 // Start trace event only on the first frame after encoder is paused.
732 if (!encoder_paused_and_dropped_frame_) {
733 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
734 }
735 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000736}
737
mflodmancc3d4422017-08-03 08:27:51 -0700738void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 01:17:40 -0700739 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000740 // End trace event on first frame after encoder resumes, if frame was dropped.
741 if (encoder_paused_and_dropped_frame_) {
742 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
743 }
744 encoder_paused_and_dropped_frame_ = false;
745}
746
mflodmancc3d4422017-08-03 08:27:51 -0700747void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
748 int64_t time_when_posted_us) {
perkj26091b12016-09-01 01:17:40 -0700749 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -0800750
perkj26091b12016-09-01 01:17:40 -0700751 if (pre_encode_callback_)
752 pre_encode_callback_->OnFrame(video_frame);
753
Per21d45d22016-10-30 21:37:57 +0100754 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-02 23:45:26 -0700755 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-02 23:45:26 -0700756 video_frame.is_texture() != last_frame_info_->is_texture) {
757 pending_encoder_reconfiguration_ = true;
Oskar Sundbom8e07c132018-01-08 16:45:42 +0100758 last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(),
759 video_frame.is_texture());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100760 RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions="
761 << last_frame_info_->width << "x"
762 << last_frame_info_->height
763 << ", texture=" << last_frame_info_->is_texture << ".";
perkjfa10b552016-10-02 23:45:26 -0700764 }
765
kthelgason2bc68642017-02-07 07:02:22 -0800766 if (initial_rampup_ < kMaxInitialFramedrop &&
767 video_frame.size() >
768 MaximumFrameSizeForBitrate(encoder_start_bitrate_bps_ / 1000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100769 RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
Ã…sa Persson875841d2018-01-08 08:49:53 +0100770 int count = GetConstAdaptCounter().ResolutionCount(kQuality);
kthelgason2bc68642017-02-07 07:02:22 -0800771 AdaptDown(kQuality);
Ã…sa Persson875841d2018-01-08 08:49:53 +0100772 if (GetConstAdaptCounter().ResolutionCount(kQuality) > count) {
773 stats_proxy_->OnInitialQualityResolutionAdaptDown();
774 }
kthelgason2bc68642017-02-07 07:02:22 -0800775 ++initial_rampup_;
776 return;
777 }
778 initial_rampup_ = kMaxInitialFramedrop;
779
sprang57c2fff2017-01-16 06:24:02 -0800780 int64_t now_ms = clock_->TimeInMilliseconds();
perkjfa10b552016-10-02 23:45:26 -0700781 if (pending_encoder_reconfiguration_) {
782 ReconfigureEncoder();
sprang4847ae62017-06-27 07:06:52 -0700783 last_parameters_update_ms_.emplace(now_ms);
sprang57c2fff2017-01-16 06:24:02 -0800784 } else if (!last_parameters_update_ms_ ||
785 now_ms - *last_parameters_update_ms_ >=
786 vcm::VCMProcessTimer::kDefaultProcessIntervalMs) {
787 video_sender_.UpdateChannelParemeters(rate_allocator_.get(),
788 bitrate_observer_);
sprang4847ae62017-06-27 07:06:52 -0700789 last_parameters_update_ms_.emplace(now_ms);
perkjfa10b552016-10-02 23:45:26 -0700790 }
791
perkj26091b12016-09-01 01:17:40 -0700792 if (EncoderPaused()) {
793 TraceFrameDropStart();
794 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000795 }
perkj26091b12016-09-01 01:17:40 -0700796 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25 +0000797
ilnik6b826ef2017-06-16 06:53:48 -0700798 VideoFrame out_frame(video_frame);
799 // Crop frame if needed.
800 if (crop_width_ > 0 || crop_height_ > 0) {
801 int cropped_width = video_frame.width() - crop_width_;
802 int cropped_height = video_frame.height() - crop_height_;
803 rtc::scoped_refptr<I420Buffer> cropped_buffer =
804 I420Buffer::Create(cropped_width, cropped_height);
805 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
806 // happen after SinkWants signaled correctly from ReconfigureEncoder.
807 if (crop_width_ < 4 && crop_height_ < 4) {
808 cropped_buffer->CropAndScaleFrom(
809 *video_frame.video_frame_buffer()->ToI420(), crop_width_ / 2,
810 crop_height_ / 2, cropped_width, cropped_height);
811 } else {
812 cropped_buffer->ScaleFrom(
813 *video_frame.video_frame_buffer()->ToI420().get());
814 }
815 out_frame =
816 VideoFrame(cropped_buffer, video_frame.timestamp(),
817 video_frame.render_time_ms(), video_frame.rotation());
818 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
819 }
820
Magnus Jedvert26679d62015-04-07 14:07:41 +0200821 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18 +0000822 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43 +0000823
Niels Möller7dc26b72017-12-06 10:27:48 +0100824 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 06:32:18 -0700825
ilnik6b826ef2017-06-16 06:53:48 -0700826 video_sender_.AddVideoFrame(out_frame, nullptr);
niklase@google.com470e71d2011-07-07 08:21:25 +0000827}
niklase@google.com470e71d2011-07-07 08:21:25 +0000828
mflodmancc3d4422017-08-03 08:27:51 -0700829void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 01:17:40 -0700830 if (!encoder_queue_.IsCurrent()) {
831 encoder_queue_.PostTask([this] { SendKeyFrame(); });
832 return;
833 }
834 RTC_DCHECK_RUN_ON(&encoder_queue_);
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200835 video_sender_.IntraFrameRequest(0);
stefan@webrtc.org07b45a52012-02-02 08:37:48 +0000836}
837
mflodmancc3d4422017-08-03 08:27:51 -0700838EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700839 const EncodedImage& encoded_image,
840 const CodecSpecificInfo* codec_specific_info,
841 const RTPFragmentationHeader* fragmentation) {
perkj26091b12016-09-01 01:17:40 -0700842 // Encoded is called on whatever thread the real encoder implementation run
843 // on. In the case of hardware encoders, there might be several encoders
844 // running in parallel on different threads.
sprang552c7c72017-02-13 04:41:45 -0800845 stats_proxy_->OnSendEncodedImage(encoded_image, codec_specific_info);
sprang3911c262016-04-15 01:24:14 -0700846
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700847 EncodedImageCallback::Result result =
848 sink_->OnEncodedImage(encoded_image, codec_specific_info, fragmentation);
perkjbc75d972016-05-02 06:31:25 -0700849
Niels Möller7dc26b72017-12-06 10:27:48 +0100850 int64_t time_sent_us = rtc::TimeMicros();
851 uint32_t timestamp = encoded_image._timeStamp;
kthelgason876222f2016-11-29 01:44:11 -0800852 const int qp = encoded_image.qp_;
Niels Möller83dbeac2017-12-14 16:39:44 +0100853 int64_t capture_time_us =
854 encoded_image.capture_time_ms_ * rtc::kNumMicrosecsPerMillisec;
855
856 rtc::Optional<int> encode_duration_us;
857 if (encoded_image.timing_.flags != TimingFrameFlags::kInvalid) {
858 encode_duration_us.emplace(
859 // TODO(nisse): Maybe use capture_time_ms_ rather than encode_start_ms_?
860 rtc::kNumMicrosecsPerMillisec *
861 (encoded_image.timing_.encode_finish_ms -
862 encoded_image.timing_.encode_start_ms));
863 }
864
865 encoder_queue_.PostTask(
866 [this, timestamp, time_sent_us, qp, capture_time_us, encode_duration_us] {
867 RTC_DCHECK_RUN_ON(&encoder_queue_);
868 overuse_detector_->FrameSent(timestamp, time_sent_us, capture_time_us,
869 encode_duration_us);
870 if (quality_scaler_ && qp >= 0)
871 quality_scaler_->ReportQP(qp);
872 });
perkj803d97f2016-11-01 11:45:46 -0700873
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700874 return result;
Peter Boströmb7d9a972015-12-18 16:01:11 +0100875}
876
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +0200877void VideoStreamEncoder::OnDroppedFrame(DropReason reason) {
878 switch (reason) {
879 case DropReason::kDroppedByMediaOptimizations:
880 stats_proxy_->OnFrameDroppedByMediaOptimizations();
881 encoder_queue_.PostTask([this] {
882 RTC_DCHECK_RUN_ON(&encoder_queue_);
883 if (quality_scaler_)
884 quality_scaler_->ReportDroppedFrame();
885 });
886 break;
887 case DropReason::kDroppedByEncoder:
888 stats_proxy_->OnFrameDroppedByEncoder();
889 break;
890 }
kthelgason876222f2016-11-29 01:44:11 -0800891}
892
mflodmancc3d4422017-08-03 08:27:51 -0700893void VideoStreamEncoder::OnReceivedIntraFrameRequest(size_t stream_index) {
perkj26091b12016-09-01 01:17:40 -0700894 if (!encoder_queue_.IsCurrent()) {
895 encoder_queue_.PostTask(
896 [this, stream_index] { OnReceivedIntraFrameRequest(stream_index); });
897 return;
898 }
899 RTC_DCHECK_RUN_ON(&encoder_queue_);
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000900 // Key frame request from remote side, signal to VCM.
justinlin@chromium.org7bfb3a32013-05-13 22:59:00 +0000901 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
perkj600246e2016-05-04 11:26:51 -0700902 video_sender_.IntraFrameRequest(stream_index);
mflodman@webrtc.orgaca26292012-10-05 16:17:41 +0000903}
904
mflodmancc3d4422017-08-03 08:27:51 -0700905void VideoStreamEncoder::OnBitrateUpdated(uint32_t bitrate_bps,
906 uint8_t fraction_lost,
907 int64_t round_trip_time_ms) {
perkj26091b12016-09-01 01:17:40 -0700908 if (!encoder_queue_.IsCurrent()) {
909 encoder_queue_.PostTask(
910 [this, bitrate_bps, fraction_lost, round_trip_time_ms] {
911 OnBitrateUpdated(bitrate_bps, fraction_lost, round_trip_time_ms);
912 });
913 return;
914 }
915 RTC_DCHECK_RUN_ON(&encoder_queue_);
916 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
917
Mirko Bonadei675513b2017-11-09 11:09:25 +0100918 RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
919 << " packet loss " << static_cast<int>(fraction_lost)
920 << " rtt " << round_trip_time_ms;
perkj26091b12016-09-01 01:17:40 -0700921
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200922 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost,
sprang1a646ee2016-12-01 06:34:11 -0800923 round_trip_time_ms, rate_allocator_.get(),
924 bitrate_observer_);
perkj26091b12016-09-01 01:17:40 -0700925
926 encoder_start_bitrate_bps_ =
927 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
mflodman101f2502016-06-09 17:21:19 +0200928 bool video_is_suspended = bitrate_bps == 0;
Erik Språng08127a92016-11-16 16:41:30 +0100929 bool video_suspension_changed = video_is_suspended != EncoderPaused();
perkj26091b12016-09-01 01:17:40 -0700930 last_observed_bitrate_bps_ = bitrate_bps;
Peter Boströmd153a372015-11-10 15:27:12 +0000931
sprang552c7c72017-02-13 04:41:45 -0800932 if (video_suspension_changed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100933 RTC_LOG(LS_INFO) << "Video suspend state changed to: "
934 << (video_is_suspended ? "suspended" : "not suspended");
Peter Boström7083e112015-09-22 16:28:51 +0200935 stats_proxy_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 17:21:19 +0200936 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000937}
938
mflodmancc3d4422017-08-03 08:27:51 -0700939void VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -0700940 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700941 AdaptationRequest adaptation_request = {
942 last_frame_info_->pixel_count(),
943 stats_proxy_->GetStats().input_frame_rate,
944 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-15 23:40:18 -0700945
sprangc5d62e22017-04-02 23:53:04 -0700946 bool downgrade_requested =
947 last_adaptation_request_ &&
948 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
949
sprangc5d62e22017-04-02 23:53:04 -0700950 switch (degradation_preference_) {
hbos8d609f62017-04-10 07:39:05 -0700951 case VideoSendStream::DegradationPreference::kBalanced:
asaperssonf7e294d2017-06-13 23:25:22 -0700952 break;
hbos8d609f62017-04-10 07:39:05 -0700953 case VideoSendStream::DegradationPreference::kMaintainFramerate:
sprangc5d62e22017-04-02 23:53:04 -0700954 if (downgrade_requested &&
955 adaptation_request.input_pixel_count_ >=
956 last_adaptation_request_->input_pixel_count_) {
957 // Don't request lower resolution if the current resolution is not
958 // lower than the last time we asked for the resolution to be lowered.
959 return;
960 }
961 break;
hbos8d609f62017-04-10 07:39:05 -0700962 case VideoSendStream::DegradationPreference::kMaintainResolution:
sprangc5d62e22017-04-02 23:53:04 -0700963 if (adaptation_request.framerate_fps_ <= 0 ||
964 (downgrade_requested &&
965 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
966 // If no input fps estimate available, can't determine how to scale down
967 // framerate. Otherwise, don't request lower framerate if we don't have
968 // a valid frame rate. Since framerate, unlike resolution, is a measure
969 // we have to estimate, and can fluctuate naturally over time, don't
970 // make the same kind of limitations as for resolution, but trust the
971 // overuse detector to not trigger too often.
972 return;
973 }
974 break;
hbos8d609f62017-04-10 07:39:05 -0700975 case VideoSendStream::DegradationPreference::kDegradationDisabled:
sprangc5d62e22017-04-02 23:53:04 -0700976 return;
sprang84a37592017-02-10 07:04:27 -0800977 }
sprangc5d62e22017-04-02 23:53:04 -0700978
sprangc5d62e22017-04-02 23:53:04 -0700979 switch (degradation_preference_) {
asaperssonf7e294d2017-06-13 23:25:22 -0700980 case VideoSendStream::DegradationPreference::kBalanced: {
981 // Try scale down framerate, if lower.
982 int fps = MinFps(last_frame_info_->pixel_count());
983 if (source_proxy_->RestrictFramerate(fps)) {
984 GetAdaptCounter().IncrementFramerate(reason);
985 break;
986 }
987 // Scale down resolution.
kjellanderbdf30722017-09-08 11:00:21 -0700988 FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -0700989 }
Ã…sa Perssonc3ed6302017-11-16 14:04:52 +0100990 case VideoSendStream::DegradationPreference::kMaintainFramerate: {
asapersson13874762017-06-07 00:01:02 -0700991 // Scale down resolution.
Ã…sa Perssonc3ed6302017-11-16 14:04:52 +0100992 bool min_pixels_reached = false;
asaperssond0de2952017-04-21 01:47:31 -0700993 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 08:58:54 -0700994 adaptation_request.input_pixel_count_,
Ã…sa Perssonc3ed6302017-11-16 14:04:52 +0100995 settings_.encoder->GetScalingSettings().min_pixels_per_frame,
996 &min_pixels_reached)) {
997 if (min_pixels_reached)
998 stats_proxy_->OnMinPixelLimitReached();
asaperssond0de2952017-04-21 01:47:31 -0700999 return;
1000 }
asaperssonf7e294d2017-06-13 23:25:22 -07001001 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001002 break;
Ã…sa Perssonc3ed6302017-11-16 14:04:52 +01001003 }
sprangfda496a2017-06-15 04:21:07 -07001004 case VideoSendStream::DegradationPreference::kMaintainResolution: {
asapersson13874762017-06-07 00:01:02 -07001005 // Scale down framerate.
sprangfda496a2017-06-15 04:21:07 -07001006 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
1007 adaptation_request.framerate_fps_);
1008 if (requested_framerate == -1)
asapersson13874762017-06-07 00:01:02 -07001009 return;
sprangfda496a2017-06-15 04:21:07 -07001010 RTC_DCHECK_NE(max_framerate_, -1);
Niels Möller7dc26b72017-12-06 10:27:48 +01001011 overuse_detector_->OnTargetFramerateUpdated(
1012 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001013 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001014 break;
sprangfda496a2017-06-15 04:21:07 -07001015 }
hbos8d609f62017-04-10 07:39:05 -07001016 case VideoSendStream::DegradationPreference::kDegradationDisabled:
sprangc5d62e22017-04-02 23:53:04 -07001017 RTC_NOTREACHED();
1018 }
1019
asaperssond0de2952017-04-21 01:47:31 -07001020 last_adaptation_request_.emplace(adaptation_request);
1021
asapersson09f05612017-05-15 23:40:18 -07001022 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 01:47:31 -07001023
Mirko Bonadei675513b2017-11-09 11:09:25 +01001024 RTC_LOG(LS_INFO) << GetConstAdaptCounter().ToString();
perkj26091b12016-09-01 01:17:40 -07001025}
1026
mflodmancc3d4422017-08-03 08:27:51 -07001027void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001028 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-15 23:40:18 -07001029
1030 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
1031 int num_downgrades = adapt_counter.TotalCount(reason);
1032 if (num_downgrades == 0)
perkj803d97f2016-11-01 11:45:46 -07001033 return;
asapersson09f05612017-05-15 23:40:18 -07001034 RTC_DCHECK_GT(num_downgrades, 0);
1035
sprangc5d62e22017-04-02 23:53:04 -07001036 AdaptationRequest adaptation_request = {
1037 last_frame_info_->pixel_count(),
1038 stats_proxy_->GetStats().input_frame_rate,
1039 AdaptationRequest::Mode::kAdaptUp};
1040
1041 bool adapt_up_requested =
1042 last_adaptation_request_ &&
1043 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-15 23:40:18 -07001044
asaperssonf7e294d2017-06-13 23:25:22 -07001045 if (degradation_preference_ ==
1046 VideoSendStream::DegradationPreference::kMaintainFramerate) {
1047 if (adapt_up_requested &&
1048 adaptation_request.input_pixel_count_ <=
1049 last_adaptation_request_->input_pixel_count_) {
1050 // Don't request higher resolution if the current resolution is not
1051 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-02 23:53:04 -07001052 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001053 }
sprangb1ca0732017-02-01 08:38:12 -08001054 }
sprangc5d62e22017-04-02 23:53:04 -07001055
sprangc5d62e22017-04-02 23:53:04 -07001056 switch (degradation_preference_) {
asaperssonf7e294d2017-06-13 23:25:22 -07001057 case VideoSendStream::DegradationPreference::kBalanced: {
1058 // Try scale up framerate, if higher.
1059 int fps = MaxFps(last_frame_info_->pixel_count());
1060 if (source_proxy_->IncreaseFramerate(fps)) {
1061 GetAdaptCounter().DecrementFramerate(reason, fps);
1062 // Reset framerate in case of fewer fps steps down than up.
1063 if (adapt_counter.FramerateCount() == 0 &&
1064 fps != std::numeric_limits<int>::max()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001065 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asaperssonf7e294d2017-06-13 23:25:22 -07001066 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
1067 }
1068 break;
1069 }
1070 // Scale up resolution.
kjellanderbdf30722017-09-08 11:00:21 -07001071 FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001072 }
asapersson13874762017-06-07 00:01:02 -07001073 case VideoSendStream::DegradationPreference::kMaintainFramerate: {
1074 // Scale up resolution.
1075 int pixel_count = adaptation_request.input_pixel_count_;
1076 if (adapt_counter.ResolutionCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001077 RTC_LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001078 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001079 }
asapersson13874762017-06-07 00:01:02 -07001080 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
1081 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001082 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001083 break;
asapersson13874762017-06-07 00:01:02 -07001084 }
1085 case VideoSendStream::DegradationPreference::kMaintainResolution: {
1086 // Scale up framerate.
1087 int fps = adaptation_request.framerate_fps_;
1088 if (adapt_counter.FramerateCount() == 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001089 RTC_LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001090 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001091 }
sprangfda496a2017-06-15 04:21:07 -07001092
1093 const int requested_framerate =
1094 source_proxy_->RequestHigherFramerateThan(fps);
1095 if (requested_framerate == -1) {
Niels Möller7dc26b72017-12-06 10:27:48 +01001096 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 00:01:02 -07001097 return;
sprangfda496a2017-06-15 04:21:07 -07001098 }
Niels Möller7dc26b72017-12-06 10:27:48 +01001099 overuse_detector_->OnTargetFramerateUpdated(
1100 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001101 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001102 break;
asapersson13874762017-06-07 00:01:02 -07001103 }
hbos8d609f62017-04-10 07:39:05 -07001104 case VideoSendStream::DegradationPreference::kDegradationDisabled:
asaperssonf7e294d2017-06-13 23:25:22 -07001105 return;
sprangc5d62e22017-04-02 23:53:04 -07001106 }
1107
asaperssond0de2952017-04-21 01:47:31 -07001108 last_adaptation_request_.emplace(adaptation_request);
1109
asapersson09f05612017-05-15 23:40:18 -07001110 UpdateAdaptationStats(reason);
1111
Mirko Bonadei675513b2017-11-09 11:09:25 +01001112 RTC_LOG(LS_INFO) << adapt_counter.ToString();
asapersson09f05612017-05-15 23:40:18 -07001113}
1114
mflodmancc3d4422017-08-03 08:27:51 -07001115void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 01:47:31 -07001116 switch (reason) {
asaperssond0de2952017-04-21 01:47:31 -07001117 case kCpu:
asapersson09f05612017-05-15 23:40:18 -07001118 stats_proxy_->OnCpuAdaptationChanged(GetActiveCounts(kCpu),
1119 GetActiveCounts(kQuality));
1120 break;
1121 case kQuality:
1122 stats_proxy_->OnQualityAdaptationChanged(GetActiveCounts(kCpu),
1123 GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 01:47:31 -07001124 break;
1125 }
perkj26091b12016-09-01 01:17:40 -07001126}
1127
mflodmancc3d4422017-08-03 08:27:51 -07001128VideoStreamEncoder::AdaptCounts VideoStreamEncoder::GetActiveCounts(
1129 AdaptReason reason) {
1130 VideoStreamEncoder::AdaptCounts counts =
1131 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-15 23:40:18 -07001132 switch (reason) {
1133 case kCpu:
1134 if (!IsFramerateScalingEnabled(degradation_preference_))
1135 counts.fps = -1;
1136 if (!IsResolutionScalingEnabled(degradation_preference_))
1137 counts.resolution = -1;
1138 break;
1139 case kQuality:
1140 if (!IsFramerateScalingEnabled(degradation_preference_) ||
1141 !quality_scaler_) {
1142 counts.fps = -1;
1143 }
1144 if (!IsResolutionScalingEnabled(degradation_preference_) ||
1145 !quality_scaler_) {
1146 counts.resolution = -1;
1147 }
1148 break;
sprangc5d62e22017-04-02 23:53:04 -07001149 }
asapersson09f05612017-05-15 23:40:18 -07001150 return counts;
sprangc5d62e22017-04-02 23:53:04 -07001151}
1152
mflodmancc3d4422017-08-03 08:27:51 -07001153VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001154 return adapt_counters_[degradation_preference_];
1155}
1156
mflodmancc3d4422017-08-03 08:27:51 -07001157const VideoStreamEncoder::AdaptCounter&
1158VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001159 return adapt_counters_[degradation_preference_];
1160}
1161
1162// Class holding adaptation information.
mflodmancc3d4422017-08-03 08:27:51 -07001163VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001164 fps_counters_.resize(kScaleReasonSize);
1165 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-13 23:25:22 -07001166 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-15 23:40:18 -07001167}
1168
mflodmancc3d4422017-08-03 08:27:51 -07001169VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-15 23:40:18 -07001170
mflodmancc3d4422017-08-03 08:27:51 -07001171std::string VideoStreamEncoder::AdaptCounter::ToString() const {
asapersson09f05612017-05-15 23:40:18 -07001172 std::stringstream ss;
1173 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
1174 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
1175 return ss.str();
1176}
1177
mflodmancc3d4422017-08-03 08:27:51 -07001178VideoStreamEncoder::AdaptCounts VideoStreamEncoder::AdaptCounter::Counts(
1179 int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001180 AdaptCounts counts;
1181 counts.fps = fps_counters_[reason];
1182 counts.resolution = resolution_counters_[reason];
1183 return counts;
1184}
1185
mflodmancc3d4422017-08-03 08:27:51 -07001186void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001187 ++(fps_counters_[reason]);
asapersson09f05612017-05-15 23:40:18 -07001188}
1189
mflodmancc3d4422017-08-03 08:27:51 -07001190void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001191 ++(resolution_counters_[reason]);
1192}
1193
mflodmancc3d4422017-08-03 08:27:51 -07001194void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001195 if (fps_counters_[reason] == 0) {
1196 // Balanced mode: Adapt up is in a different order, switch reason.
1197 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
1198 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
1199 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
1200 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
1201 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
1202 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1203 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
1204 MoveCount(&resolution_counters_, reason);
1205 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
1206 }
1207 --(fps_counters_[reason]);
1208 RTC_DCHECK_GE(fps_counters_[reason], 0);
1209}
1210
mflodmancc3d4422017-08-03 08:27:51 -07001211void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001212 if (resolution_counters_[reason] == 0) {
1213 // Balanced mode: Adapt up is in a different order, switch reason.
1214 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1215 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
1216 MoveCount(&fps_counters_, reason);
1217 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
1218 }
1219 --(resolution_counters_[reason]);
1220 RTC_DCHECK_GE(resolution_counters_[reason], 0);
1221}
1222
mflodmancc3d4422017-08-03 08:27:51 -07001223void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
1224 int cur_fps) {
asaperssonf7e294d2017-06-13 23:25:22 -07001225 DecrementFramerate(reason);
1226 // Reset if at max fps (i.e. in case of fewer steps up than down).
1227 if (cur_fps == std::numeric_limits<int>::max())
1228 std::fill(fps_counters_.begin(), fps_counters_.end(), 0);
asapersson09f05612017-05-15 23:40:18 -07001229}
1230
mflodmancc3d4422017-08-03 08:27:51 -07001231int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-15 23:40:18 -07001232 return Count(fps_counters_);
1233}
1234
mflodmancc3d4422017-08-03 08:27:51 -07001235int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-15 23:40:18 -07001236 return Count(resolution_counters_);
1237}
1238
mflodmancc3d4422017-08-03 08:27:51 -07001239int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001240 return fps_counters_[reason];
1241}
1242
mflodmancc3d4422017-08-03 08:27:51 -07001243int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001244 return resolution_counters_[reason];
1245}
1246
mflodmancc3d4422017-08-03 08:27:51 -07001247int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001248 return FramerateCount(reason) + ResolutionCount(reason);
1249}
1250
mflodmancc3d4422017-08-03 08:27:51 -07001251int VideoStreamEncoder::AdaptCounter::Count(
1252 const std::vector<int>& counters) const {
asapersson09f05612017-05-15 23:40:18 -07001253 return std::accumulate(counters.begin(), counters.end(), 0);
1254}
1255
mflodmancc3d4422017-08-03 08:27:51 -07001256void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
1257 int from_reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001258 int to_reason = (from_reason + 1) % kScaleReasonSize;
1259 ++((*counters)[to_reason]);
1260 --((*counters)[from_reason]);
1261}
1262
mflodmancc3d4422017-08-03 08:27:51 -07001263std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-15 23:40:18 -07001264 const std::vector<int>& counters) const {
1265 std::stringstream ss;
1266 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
1267 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-02 23:53:04 -07001268 }
asapersson09f05612017-05-15 23:40:18 -07001269 return ss.str();
sprangc5d62e22017-04-02 23:53:04 -07001270}
1271
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001272} // namespace webrtc