blob: 51fb1d43d61de933dc0ec35b7d43ee1379daebbf [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
mflodmancc3d4422017-08-03 08:27:51 -070011#include "webrtc/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
ilnik6b826ef2017-06-16 06:53:48 -070018#include "webrtc/api/video/i420_buffer.h"
sprang1a646ee2016-12-01 06:34:11 -080019#include "webrtc/common_video/include/video_bitrate_allocator.h"
nisseea3a7982017-05-15 02:42:11 -070020#include "webrtc/common_video/include/video_frame.h"
Henrik Kjellander0b9e29c2015-11-16 11:12:24 +010021#include "webrtc/modules/pacing/paced_sender.h"
Erik Språng08127a92016-11-16 16:41:30 +010022#include "webrtc/modules/video_coding/codecs/vp8/temporal_layers.h"
sprangb1ca0732017-02-01 08:38:12 -080023#include "webrtc/modules/video_coding/include/video_codec_initializer.h"
Henrik Kjellander2557b862015-11-18 22:00:21 +010024#include "webrtc/modules/video_coding/include/video_coding.h"
25#include "webrtc/modules/video_coding/include/video_coding_defines.h"
Edward Lemurc20978e2017-07-06 19:44:34 +020026#include "webrtc/rtc_base/arraysize.h"
27#include "webrtc/rtc_base/checks.h"
28#include "webrtc/rtc_base/location.h"
29#include "webrtc/rtc_base/logging.h"
30#include "webrtc/rtc_base/timeutils.h"
31#include "webrtc/rtc_base/trace_event.h"
Peter Boströme4499152016-02-05 11:13:28 +010032#include "webrtc/video/overuse_frame_detector.h"
pbos@webrtc.org273a4142014-12-01 15:23:21 +000033#include "webrtc/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;
kthelgasonfa5fdce2017-02-27 00:15:31 -080041
kthelgason5e13d412016-12-01 03:59:51 -080042// We will never ask for a resolution lower than this.
kthelgason33ce8892016-12-09 03:53:59 -080043// TODO(kthelgason): Lower this limit when better testing
44// on MediaCodec and fallback implementations are in place.
kthelgasonfa5fdce2017-02-27 00:15:31 -080045// See https://bugs.chromium.org/p/webrtc/issues/detail?id=7206
kthelgason33ce8892016-12-09 03:53:59 -080046const int kMinPixelsPerFrame = 320 * 180;
sprangc5d62e22017-04-02 23:53:04 -070047const int kMinFramerateFps = 2;
sprangfda496a2017-06-15 04:21:07 -070048const int kMaxFramerateFps = 120;
perkj26091b12016-09-01 01:17:40 -070049
kthelgason2bc68642017-02-07 07:02:22 -080050// The maximum number of frames to drop at beginning of stream
51// to try and achieve desired bitrate.
52const int kMaxInitialFramedrop = 4;
53
kthelgason2bc68642017-02-07 07:02:22 -080054uint32_t MaximumFrameSizeForBitrate(uint32_t kbps) {
55 if (kbps > 0) {
56 if (kbps < 300 /* qvga */) {
57 return 320 * 240;
58 } else if (kbps < 500 /* vga */) {
59 return 640 * 480;
60 }
61 }
62 return std::numeric_limits<uint32_t>::max();
63}
64
asaperssonf7e294d2017-06-13 23:25:22 -070065// Initial limits for kBalanced degradation preference.
66int MinFps(int pixels) {
67 if (pixels <= 320 * 240) {
68 return 7;
69 } else if (pixels <= 480 * 270) {
70 return 10;
71 } else if (pixels <= 640 * 480) {
72 return 15;
73 } else {
74 return std::numeric_limits<int>::max();
75 }
76}
77
78int MaxFps(int pixels) {
79 if (pixels <= 320 * 240) {
80 return 10;
81 } else if (pixels <= 480 * 270) {
82 return 15;
83 } else {
84 return std::numeric_limits<int>::max();
85 }
86}
87
asapersson09f05612017-05-15 23:40:18 -070088bool IsResolutionScalingEnabled(
89 VideoSendStream::DegradationPreference degradation_preference) {
90 return degradation_preference ==
91 VideoSendStream::DegradationPreference::kMaintainFramerate ||
92 degradation_preference ==
93 VideoSendStream::DegradationPreference::kBalanced;
94}
95
96bool IsFramerateScalingEnabled(
97 VideoSendStream::DegradationPreference degradation_preference) {
98 return degradation_preference ==
99 VideoSendStream::DegradationPreference::kMaintainResolution ||
100 degradation_preference ==
101 VideoSendStream::DegradationPreference::kBalanced;
102}
103
perkj26091b12016-09-01 01:17:40 -0700104} // namespace
105
mflodmancc3d4422017-08-03 08:27:51 -0700106class VideoStreamEncoder::ConfigureEncoderTask : public rtc::QueuedTask {
Pera48ddb72016-09-29 11:48:50 +0200107 public:
mflodmancc3d4422017-08-03 08:27:51 -0700108 ConfigureEncoderTask(VideoStreamEncoder* video_stream_encoder,
Pera48ddb72016-09-29 11:48:50 +0200109 VideoEncoderConfig config,
asapersson5f7226f2016-11-25 04:37:00 -0800110 size_t max_data_payload_length,
111 bool nack_enabled)
mflodmancc3d4422017-08-03 08:27:51 -0700112 : video_stream_encoder_(video_stream_encoder),
Pera48ddb72016-09-29 11:48:50 +0200113 config_(std::move(config)),
asapersson5f7226f2016-11-25 04:37:00 -0800114 max_data_payload_length_(max_data_payload_length),
115 nack_enabled_(nack_enabled) {}
Pera48ddb72016-09-29 11:48:50 +0200116
117 private:
118 bool Run() override {
mflodmancc3d4422017-08-03 08:27:51 -0700119 video_stream_encoder_->ConfigureEncoderOnTaskQueue(
asapersson5f7226f2016-11-25 04:37:00 -0800120 std::move(config_), max_data_payload_length_, nack_enabled_);
Pera48ddb72016-09-29 11:48:50 +0200121 return true;
122 }
123
mflodmancc3d4422017-08-03 08:27:51 -0700124 VideoStreamEncoder* const video_stream_encoder_;
Pera48ddb72016-09-29 11:48:50 +0200125 VideoEncoderConfig config_;
126 size_t max_data_payload_length_;
asapersson5f7226f2016-11-25 04:37:00 -0800127 bool nack_enabled_;
Pera48ddb72016-09-29 11:48:50 +0200128};
129
mflodmancc3d4422017-08-03 08:27:51 -0700130class VideoStreamEncoder::EncodeTask : public rtc::QueuedTask {
perkj26091b12016-09-01 01:17:40 -0700131 public:
perkjd52063f2016-09-07 06:32:18 -0700132 EncodeTask(const VideoFrame& frame,
mflodmancc3d4422017-08-03 08:27:51 -0700133 VideoStreamEncoder* video_stream_encoder,
nissee0e3bdf2017-01-18 02:16:20 -0800134 int64_t time_when_posted_us,
asapersson6ffb67d2016-09-12 00:10:45 -0700135 bool log_stats)
nissedf2ceb82016-12-15 06:29:53 -0800136 : frame_(frame),
mflodmancc3d4422017-08-03 08:27:51 -0700137 video_stream_encoder_(video_stream_encoder),
nissee0e3bdf2017-01-18 02:16:20 -0800138 time_when_posted_us_(time_when_posted_us),
asapersson6ffb67d2016-09-12 00:10:45 -0700139 log_stats_(log_stats) {
mflodmancc3d4422017-08-03 08:27:51 -0700140 ++video_stream_encoder_->posted_frames_waiting_for_encode_;
perkj26091b12016-09-01 01:17:40 -0700141 }
142
143 private:
144 bool Run() override {
mflodmancc3d4422017-08-03 08:27:51 -0700145 RTC_DCHECK_RUN_ON(&video_stream_encoder_->encoder_queue_);
146 RTC_DCHECK_GT(
147 video_stream_encoder_->posted_frames_waiting_for_encode_.Value(), 0);
148 video_stream_encoder_->stats_proxy_->OnIncomingFrame(frame_.width(),
149 frame_.height());
150 ++video_stream_encoder_->captured_frame_count_;
151 if (--video_stream_encoder_->posted_frames_waiting_for_encode_ == 0) {
152 video_stream_encoder_->EncodeVideoFrame(frame_, time_when_posted_us_);
perkj26091b12016-09-01 01:17:40 -0700153 } else {
154 // There is a newer frame in flight. Do not encode this frame.
155 LOG(LS_VERBOSE)
156 << "Incoming frame dropped due to that the encoder is blocked.";
mflodmancc3d4422017-08-03 08:27:51 -0700157 ++video_stream_encoder_->dropped_frame_count_;
asapersson6ffb67d2016-09-12 00:10:45 -0700158 }
159 if (log_stats_) {
160 LOG(LS_INFO) << "Number of frames: captured "
mflodmancc3d4422017-08-03 08:27:51 -0700161 << video_stream_encoder_->captured_frame_count_
asapersson6ffb67d2016-09-12 00:10:45 -0700162 << ", dropped (due to encoder blocked) "
mflodmancc3d4422017-08-03 08:27:51 -0700163 << video_stream_encoder_->dropped_frame_count_
164 << ", interval_ms "
asapersson6ffb67d2016-09-12 00:10:45 -0700165 << kFrameLogIntervalMs;
mflodmancc3d4422017-08-03 08:27:51 -0700166 video_stream_encoder_->captured_frame_count_ = 0;
167 video_stream_encoder_->dropped_frame_count_ = 0;
perkj26091b12016-09-01 01:17:40 -0700168 }
169 return true;
170 }
171 VideoFrame frame_;
mflodmancc3d4422017-08-03 08:27:51 -0700172 VideoStreamEncoder* const video_stream_encoder_;
nissee0e3bdf2017-01-18 02:16:20 -0800173 const int64_t time_when_posted_us_;
asapersson6ffb67d2016-09-12 00:10:45 -0700174 const bool log_stats_;
perkj26091b12016-09-01 01:17:40 -0700175};
176
perkja49cbd32016-09-16 07:53:41 -0700177// VideoSourceProxy is responsible ensuring thread safety between calls to
mflodmancc3d4422017-08-03 08:27:51 -0700178// VideoStreamEncoder::SetSource that will happen on libjingle's worker thread
179// when a video capturer is connected to the encoder and the encoder task queue
perkja49cbd32016-09-16 07:53:41 -0700180// (encoder_queue_) where the encoder reports its VideoSinkWants.
mflodmancc3d4422017-08-03 08:27:51 -0700181class VideoStreamEncoder::VideoSourceProxy {
perkja49cbd32016-09-16 07:53:41 -0700182 public:
mflodmancc3d4422017-08-03 08:27:51 -0700183 explicit VideoSourceProxy(VideoStreamEncoder* video_stream_encoder)
184 : video_stream_encoder_(video_stream_encoder),
hbos8d609f62017-04-10 07:39:05 -0700185 degradation_preference_(
186 VideoSendStream::DegradationPreference::kDegradationDisabled),
perkj803d97f2016-11-01 11:45:46 -0700187 source_(nullptr) {}
perkja49cbd32016-09-16 07:53:41 -0700188
hbos8d609f62017-04-10 07:39:05 -0700189 void SetSource(
190 rtc::VideoSourceInterface<VideoFrame>* source,
191 const VideoSendStream::DegradationPreference& degradation_preference) {
perkj803d97f2016-11-01 11:45:46 -0700192 // Called on libjingle's worker thread.
perkja49cbd32016-09-16 07:53:41 -0700193 RTC_DCHECK_CALLED_SEQUENTIALLY(&main_checker_);
194 rtc::VideoSourceInterface<VideoFrame>* old_source = nullptr;
perkj803d97f2016-11-01 11:45:46 -0700195 rtc::VideoSinkWants wants;
perkja49cbd32016-09-16 07:53:41 -0700196 {
197 rtc::CritScope lock(&crit_);
sprangc5d62e22017-04-02 23:53:04 -0700198 degradation_preference_ = degradation_preference;
perkja49cbd32016-09-16 07:53:41 -0700199 old_source = source_;
200 source_ = source;
sprangfda496a2017-06-15 04:21:07 -0700201 wants = GetActiveSinkWantsInternal();
perkja49cbd32016-09-16 07:53:41 -0700202 }
203
204 if (old_source != source && old_source != nullptr) {
mflodmancc3d4422017-08-03 08:27:51 -0700205 old_source->RemoveSink(video_stream_encoder_);
perkja49cbd32016-09-16 07:53:41 -0700206 }
207
208 if (!source) {
209 return;
210 }
211
mflodmancc3d4422017-08-03 08:27:51 -0700212 source->AddOrUpdateSink(video_stream_encoder_, wants);
perkja49cbd32016-09-16 07:53:41 -0700213 }
214
perkj803d97f2016-11-01 11:45:46 -0700215 void SetWantsRotationApplied(bool rotation_applied) {
216 rtc::CritScope lock(&crit_);
217 sink_wants_.rotation_applied = rotation_applied;
sprangc5d62e22017-04-02 23:53:04 -0700218 if (source_)
mflodmancc3d4422017-08-03 08:27:51 -0700219 source_->AddOrUpdateSink(video_stream_encoder_, sink_wants_);
sprangc5d62e22017-04-02 23:53:04 -0700220 }
221
sprangfda496a2017-06-15 04:21:07 -0700222 rtc::VideoSinkWants GetActiveSinkWants() {
223 rtc::CritScope lock(&crit_);
224 return GetActiveSinkWantsInternal();
perkj803d97f2016-11-01 11:45:46 -0700225 }
226
asaperssonf7e294d2017-06-13 23:25:22 -0700227 void ResetPixelFpsCount() {
228 rtc::CritScope lock(&crit_);
229 sink_wants_.max_pixel_count = std::numeric_limits<int>::max();
230 sink_wants_.target_pixel_count.reset();
231 sink_wants_.max_framerate_fps = std::numeric_limits<int>::max();
232 if (source_)
mflodmancc3d4422017-08-03 08:27:51 -0700233 source_->AddOrUpdateSink(video_stream_encoder_, sink_wants_);
asaperssonf7e294d2017-06-13 23:25:22 -0700234 }
235
asaperssond0de2952017-04-21 01:47:31 -0700236 bool RequestResolutionLowerThan(int pixel_count) {
perkj803d97f2016-11-01 11:45:46 -0700237 // Called on the encoder task queue.
238 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700239 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700240 // This can happen since |degradation_preference_| is set on libjingle's
241 // worker thread but the adaptation is done on the encoder task queue.
asaperssond0de2952017-04-21 01:47:31 -0700242 return false;
perkj803d97f2016-11-01 11:45:46 -0700243 }
asapersson13874762017-06-07 00:01:02 -0700244 // The input video frame size will have a resolution less than or equal to
245 // |max_pixel_count| depending on how the source can scale the frame size.
kthelgason5e13d412016-12-01 03:59:51 -0800246 const int pixels_wanted = (pixel_count * 3) / 5;
asapersson13874762017-06-07 00:01:02 -0700247 if (pixels_wanted < kMinPixelsPerFrame ||
248 pixels_wanted >= sink_wants_.max_pixel_count) {
asaperssond0de2952017-04-21 01:47:31 -0700249 return false;
asapersson13874762017-06-07 00:01:02 -0700250 }
251 LOG(LS_INFO) << "Scaling down resolution, max pixels: " << pixels_wanted;
sprangc5d62e22017-04-02 23:53:04 -0700252 sink_wants_.max_pixel_count = pixels_wanted;
sprang84a37592017-02-10 07:04:27 -0800253 sink_wants_.target_pixel_count = rtc::Optional<int>();
mflodmancc3d4422017-08-03 08:27:51 -0700254 source_->AddOrUpdateSink(video_stream_encoder_,
255 GetActiveSinkWantsInternal());
asaperssond0de2952017-04-21 01:47:31 -0700256 return true;
sprangc5d62e22017-04-02 23:53:04 -0700257 }
258
sprangfda496a2017-06-15 04:21:07 -0700259 int RequestFramerateLowerThan(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700260 // Called on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700261 // The input video frame rate will be scaled down to 2/3, rounding down.
sprangfda496a2017-06-15 04:21:07 -0700262 int framerate_wanted = (fps * 2) / 3;
263 return RestrictFramerate(framerate_wanted) ? framerate_wanted : -1;
perkj803d97f2016-11-01 11:45:46 -0700264 }
265
asapersson13874762017-06-07 00:01:02 -0700266 bool RequestHigherResolutionThan(int pixel_count) {
267 // Called on the encoder task queue.
perkj803d97f2016-11-01 11:45:46 -0700268 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700269 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 01:12:52 -0700270 // This can happen since |degradation_preference_| is set on libjingle's
271 // worker thread but the adaptation is done on the encoder task queue.
asapersson13874762017-06-07 00:01:02 -0700272 return false;
perkj803d97f2016-11-01 11:45:46 -0700273 }
asapersson13874762017-06-07 00:01:02 -0700274 int max_pixels_wanted = pixel_count;
275 if (max_pixels_wanted != std::numeric_limits<int>::max())
276 max_pixels_wanted = pixel_count * 4;
sprangc5d62e22017-04-02 23:53:04 -0700277
asapersson13874762017-06-07 00:01:02 -0700278 if (max_pixels_wanted <= sink_wants_.max_pixel_count)
279 return false;
280
281 sink_wants_.max_pixel_count = max_pixels_wanted;
282 if (max_pixels_wanted == std::numeric_limits<int>::max()) {
sprangc5d62e22017-04-02 23:53:04 -0700283 // Remove any constraints.
284 sink_wants_.target_pixel_count.reset();
sprangc5d62e22017-04-02 23:53:04 -0700285 } else {
286 // On step down we request at most 3/5 the pixel count of the previous
287 // resolution, so in order to take "one step up" we request a resolution
288 // as close as possible to 5/3 of the current resolution. The actual pixel
289 // count selected depends on the capabilities of the source. In order to
290 // not take a too large step up, we cap the requested pixel count to be at
291 // most four time the current number of pixels.
292 sink_wants_.target_pixel_count =
293 rtc::Optional<int>((pixel_count * 5) / 3);
sprangc5d62e22017-04-02 23:53:04 -0700294 }
asapersson13874762017-06-07 00:01:02 -0700295 LOG(LS_INFO) << "Scaling up resolution, max pixels: " << max_pixels_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700296 source_->AddOrUpdateSink(video_stream_encoder_,
297 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700298 return true;
sprangc5d62e22017-04-02 23:53:04 -0700299 }
300
sprangfda496a2017-06-15 04:21:07 -0700301 // Request upgrade in framerate. Returns the new requested frame, or -1 if
302 // no change requested. Note that maxint may be returned if limits due to
303 // adaptation requests are removed completely. In that case, consider
304 // |max_framerate_| to be the current limit (assuming the capturer complies).
305 int RequestHigherFramerateThan(int fps) {
asapersson13874762017-06-07 00:01:02 -0700306 // Called on the encoder task queue.
307 // The input frame rate will be scaled up to the last step, with rounding.
308 int framerate_wanted = fps;
309 if (fps != std::numeric_limits<int>::max())
310 framerate_wanted = (fps * 3) / 2;
311
sprangfda496a2017-06-15 04:21:07 -0700312 return IncreaseFramerate(framerate_wanted) ? framerate_wanted : -1;
asapersson13874762017-06-07 00:01:02 -0700313 }
314
315 bool RestrictFramerate(int fps) {
sprangc5d62e22017-04-02 23:53:04 -0700316 // Called on the encoder task queue.
317 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 00:01:02 -0700318 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
319 return false;
320
321 const int fps_wanted = std::max(kMinFramerateFps, fps);
322 if (fps_wanted >= sink_wants_.max_framerate_fps)
323 return false;
324
325 LOG(LS_INFO) << "Scaling down framerate: " << fps_wanted;
326 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700327 source_->AddOrUpdateSink(video_stream_encoder_,
328 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700329 return true;
330 }
331
332 bool IncreaseFramerate(int fps) {
333 // Called on the encoder task queue.
334 rtc::CritScope lock(&crit_);
335 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
336 return false;
337
338 const int fps_wanted = std::max(kMinFramerateFps, fps);
339 if (fps_wanted <= sink_wants_.max_framerate_fps)
340 return false;
341
342 LOG(LS_INFO) << "Scaling up framerate: " << fps_wanted;
343 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 08:27:51 -0700344 source_->AddOrUpdateSink(video_stream_encoder_,
345 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 00:01:02 -0700346 return true;
perkj803d97f2016-11-01 11:45:46 -0700347 }
348
perkja49cbd32016-09-16 07:53:41 -0700349 private:
sprangfda496a2017-06-15 04:21:07 -0700350 rtc::VideoSinkWants GetActiveSinkWantsInternal()
351 EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
352 rtc::VideoSinkWants wants = sink_wants_;
353 // Clear any constraints from the current sink wants that don't apply to
354 // the used degradation_preference.
355 switch (degradation_preference_) {
356 case VideoSendStream::DegradationPreference::kBalanced:
357 break;
358 case VideoSendStream::DegradationPreference::kMaintainFramerate:
359 wants.max_framerate_fps = std::numeric_limits<int>::max();
360 break;
361 case VideoSendStream::DegradationPreference::kMaintainResolution:
362 wants.max_pixel_count = std::numeric_limits<int>::max();
363 wants.target_pixel_count.reset();
364 break;
365 case VideoSendStream::DegradationPreference::kDegradationDisabled:
366 wants.max_pixel_count = std::numeric_limits<int>::max();
367 wants.target_pixel_count.reset();
368 wants.max_framerate_fps = std::numeric_limits<int>::max();
369 }
370 return wants;
371 }
372
perkja49cbd32016-09-16 07:53:41 -0700373 rtc::CriticalSection crit_;
374 rtc::SequencedTaskChecker main_checker_;
mflodmancc3d4422017-08-03 08:27:51 -0700375 VideoStreamEncoder* const video_stream_encoder_;
perkj803d97f2016-11-01 11:45:46 -0700376 rtc::VideoSinkWants sink_wants_ GUARDED_BY(&crit_);
hbos8d609f62017-04-10 07:39:05 -0700377 VideoSendStream::DegradationPreference degradation_preference_
378 GUARDED_BY(&crit_);
perkja49cbd32016-09-16 07:53:41 -0700379 rtc::VideoSourceInterface<VideoFrame>* source_ GUARDED_BY(&crit_);
380
381 RTC_DISALLOW_COPY_AND_ASSIGN(VideoSourceProxy);
382};
383
mflodmancc3d4422017-08-03 08:27:51 -0700384VideoStreamEncoder::VideoStreamEncoder(uint32_t number_of_cores,
Peter Boström7083e112015-09-22 16:28:51 +0200385 SendStatisticsProxy* stats_proxy,
perkj26091b12016-09-01 01:17:40 -0700386 const VideoSendStream::Config::EncoderSettings& settings,
387 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback,
sprangfda496a2017-06-15 04:21:07 -0700388 EncodedFrameObserver* encoder_timing,
389 std::unique_ptr<OveruseFrameDetector> overuse_detector)
perkj26091b12016-09-01 01:17:40 -0700390 : shutdown_event_(true /* manual_reset */, false),
391 number_of_cores_(number_of_cores),
kthelgason2bc68642017-02-07 07:02:22 -0800392 initial_rampup_(0),
perkja49cbd32016-09-16 07:53:41 -0700393 source_proxy_(new VideoSourceProxy(this)),
Pera48ddb72016-09-29 11:48:50 +0200394 sink_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700395 settings_(settings),
Erik Språng08127a92016-11-16 16:41:30 +0100396 codec_type_(PayloadNameToCodecType(settings.payload_name)
397 .value_or(VideoCodecType::kVideoCodecUnknown)),
perkjf5b2e512016-07-05 08:34:04 -0700398 video_sender_(Clock::GetRealTimeClock(), this, 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,
405 encoder_timing,
406 stats_proxy)),
Peter Boström7083e112015-09-22 16:28:51 +0200407 stats_proxy_(stats_proxy),
perkj26091b12016-09-01 01:17:40 -0700408 pre_encode_callback_(pre_encode_callback),
409 module_process_thread_(nullptr),
sprangfda496a2017-06-15 04:21:07 -0700410 max_framerate_(-1),
perkjfa10b552016-10-02 23:45:26 -0700411 pending_encoder_reconfiguration_(false),
perkj26091b12016-09-01 01:17:40 -0700412 encoder_start_bitrate_bps_(0),
Pera48ddb72016-09-29 11:48:50 +0200413 max_data_payload_length_(0),
asapersson5f7226f2016-11-25 04:37:00 -0800414 nack_enabled_(false),
pbos@webrtc.org143451d2015-03-18 14:40:03 +0000415 last_observed_bitrate_bps_(0),
stefan@webrtc.org792f1a12015-03-04 12:24:26 +0000416 encoder_paused_and_dropped_frame_(false),
perkj26091b12016-09-01 01:17:40 -0700417 clock_(Clock::GetRealTimeClock()),
hbos8d609f62017-04-10 07:39:05 -0700418 degradation_preference_(
419 VideoSendStream::DegradationPreference::kDegradationDisabled),
perkj26091b12016-09-01 01:17:40 -0700420 last_captured_timestamp_(0),
421 delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
422 clock_->TimeInMilliseconds()),
asapersson6ffb67d2016-09-12 00:10:45 -0700423 last_frame_log_ms_(clock_->TimeInMilliseconds()),
424 captured_frame_count_(0),
425 dropped_frame_count_(0),
sprang1a646ee2016-12-01 06:34:11 -0800426 bitrate_observer_(nullptr),
perkj26091b12016-09-01 01:17:40 -0700427 encoder_queue_("EncoderQueue") {
sprang552c7c72017-02-13 04:41:45 -0800428 RTC_DCHECK(stats_proxy);
perkj803d97f2016-11-01 11:45:46 -0700429 encoder_queue_.PostTask([this] {
perkj26091b12016-09-01 01:17:40 -0700430 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700431 overuse_detector_->StartCheckForOveruse();
perkj26091b12016-09-01 01:17:40 -0700432 video_sender_.RegisterExternalEncoder(
433 settings_.encoder, settings_.payload_type, settings_.internal_source);
434 });
mflodman@webrtc.org02270cd2015-02-06 13:10:19 +0000435}
436
mflodmancc3d4422017-08-03 08:27:51 -0700437VideoStreamEncoder::~VideoStreamEncoder() {
perkja49cbd32016-09-16 07:53:41 -0700438 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 01:17:40 -0700439 RTC_DCHECK(shutdown_event_.Wait(0))
440 << "Must call ::Stop() before destruction.";
441}
442
sprangfda496a2017-06-15 04:21:07 -0700443// TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
444// pipelining encoders better (multiple input frames before something comes
445// out). This should effectively turn off CPU adaptations for systems that
446// remotely cope with the load right now.
mflodmancc3d4422017-08-03 08:27:51 -0700447CpuOveruseOptions VideoStreamEncoder::GetCpuOveruseOptions(
448 bool full_overuse_time) {
sprangfda496a2017-06-15 04:21:07 -0700449 CpuOveruseOptions options;
450 if (full_overuse_time) {
451 options.low_encode_usage_threshold_percent = 150;
452 options.high_encode_usage_threshold_percent = 200;
453 }
454 return options;
455}
456
mflodmancc3d4422017-08-03 08:27:51 -0700457void VideoStreamEncoder::Stop() {
perkja49cbd32016-09-16 07:53:41 -0700458 RTC_DCHECK_RUN_ON(&thread_checker_);
hbos8d609f62017-04-10 07:39:05 -0700459 source_proxy_->SetSource(nullptr, VideoSendStream::DegradationPreference());
perkja49cbd32016-09-16 07:53:41 -0700460 encoder_queue_.PostTask([this] {
461 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700462 overuse_detector_->StopCheckForOveruse();
Erik Språng08127a92016-11-16 16:41:30 +0100463 rate_allocator_.reset();
sprang1a646ee2016-12-01 06:34:11 -0800464 bitrate_observer_ = nullptr;
perkja49cbd32016-09-16 07:53:41 -0700465 video_sender_.RegisterExternalEncoder(nullptr, settings_.payload_type,
466 false);
kthelgason876222f2016-11-29 01:44:11 -0800467 quality_scaler_ = nullptr;
perkja49cbd32016-09-16 07:53:41 -0700468 shutdown_event_.Set();
469 });
470
471 shutdown_event_.Wait(rtc::Event::kForever);
perkj26091b12016-09-01 01:17:40 -0700472}
473
mflodmancc3d4422017-08-03 08:27:51 -0700474void VideoStreamEncoder::RegisterProcessThread(
475 ProcessThread* module_process_thread) {
perkja49cbd32016-09-16 07:53:41 -0700476 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 01:17:40 -0700477 RTC_DCHECK(!module_process_thread_);
478 module_process_thread_ = module_process_thread;
tommidea489f2017-03-03 03:20:24 -0800479 module_process_thread_->RegisterModule(&video_sender_, RTC_FROM_HERE);
perkj26091b12016-09-01 01:17:40 -0700480 module_process_thread_checker_.DetachFromThread();
481}
482
mflodmancc3d4422017-08-03 08:27:51 -0700483void VideoStreamEncoder::DeRegisterProcessThread() {
perkja49cbd32016-09-16 07:53:41 -0700484 RTC_DCHECK_RUN_ON(&thread_checker_);
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200485 module_process_thread_->DeRegisterModule(&video_sender_);
asapersson@webrtc.org96dc6852014-11-03 14:40:38 +0000486}
487
mflodmancc3d4422017-08-03 08:27:51 -0700488void VideoStreamEncoder::SetBitrateObserver(
sprang1a646ee2016-12-01 06:34:11 -0800489 VideoBitrateAllocationObserver* bitrate_observer) {
490 RTC_DCHECK_RUN_ON(&thread_checker_);
491 encoder_queue_.PostTask([this, bitrate_observer] {
492 RTC_DCHECK_RUN_ON(&encoder_queue_);
493 RTC_DCHECK(!bitrate_observer_);
494 bitrate_observer_ = bitrate_observer;
495 });
496}
497
mflodmancc3d4422017-08-03 08:27:51 -0700498void VideoStreamEncoder::SetSource(
perkj803d97f2016-11-01 11:45:46 -0700499 rtc::VideoSourceInterface<VideoFrame>* source,
asapersson09f05612017-05-15 23:40:18 -0700500 const VideoSendStream::DegradationPreference& degradation_preference) {
perkja49cbd32016-09-16 07:53:41 -0700501 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj803d97f2016-11-01 11:45:46 -0700502 source_proxy_->SetSource(source, degradation_preference);
503 encoder_queue_.PostTask([this, degradation_preference] {
504 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700505 if (degradation_preference_ != degradation_preference) {
506 // Reset adaptation state, so that we're not tricked into thinking there's
507 // an already pending request of the same type.
508 last_adaptation_request_.reset();
asaperssonf7e294d2017-06-13 23:25:22 -0700509 if (degradation_preference ==
510 VideoSendStream::DegradationPreference::kBalanced ||
511 degradation_preference_ ==
512 VideoSendStream::DegradationPreference::kBalanced) {
513 // TODO(asapersson): Consider removing |adapt_counters_| map and use one
514 // AdaptCounter for all modes.
515 source_proxy_->ResetPixelFpsCount();
516 adapt_counters_.clear();
517 }
sprangc5d62e22017-04-02 23:53:04 -0700518 }
sprangb1ca0732017-02-01 08:38:12 -0800519 degradation_preference_ = degradation_preference;
asapersson91914e22017-06-01 00:34:08 -0700520 bool allow_scaling = IsResolutionScalingEnabled(degradation_preference_);
sprangc5d62e22017-04-02 23:53:04 -0700521 initial_rampup_ = allow_scaling ? 0 : kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 07:02:22 -0800522 ConfigureQualityScaler();
sprangfda496a2017-06-15 04:21:07 -0700523 if (!IsFramerateScalingEnabled(degradation_preference) &&
524 max_framerate_ != -1) {
525 // If frame rate scaling is no longer allowed, remove any potential
526 // allowance for longer frame intervals.
527 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
528 }
perkj803d97f2016-11-01 11:45:46 -0700529 });
perkja49cbd32016-09-16 07:53:41 -0700530}
531
mflodmancc3d4422017-08-03 08:27:51 -0700532void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
perkj803d97f2016-11-01 11:45:46 -0700533 source_proxy_->SetWantsRotationApplied(rotation_applied);
perkj26091b12016-09-01 01:17:40 -0700534 encoder_queue_.PostTask([this, sink] {
535 RTC_DCHECK_RUN_ON(&encoder_queue_);
536 sink_ = sink;
537 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000538}
539
mflodmancc3d4422017-08-03 08:27:51 -0700540void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
perkj26091b12016-09-01 01:17:40 -0700541 encoder_queue_.PostTask([this, start_bitrate_bps] {
542 RTC_DCHECK_RUN_ON(&encoder_queue_);
543 encoder_start_bitrate_bps_ = start_bitrate_bps;
544 });
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000545}
Peter Boström00b9d212016-05-19 16:59:03 +0200546
mflodmancc3d4422017-08-03 08:27:51 -0700547void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
548 size_t max_data_payload_length,
549 bool nack_enabled) {
Pera48ddb72016-09-29 11:48:50 +0200550 encoder_queue_.PostTask(
551 std::unique_ptr<rtc::QueuedTask>(new ConfigureEncoderTask(
asapersson5f7226f2016-11-25 04:37:00 -0800552 this, std::move(config), max_data_payload_length, nack_enabled)));
perkj26091b12016-09-01 01:17:40 -0700553}
554
mflodmancc3d4422017-08-03 08:27:51 -0700555void VideoStreamEncoder::ConfigureEncoderOnTaskQueue(
556 VideoEncoderConfig config,
557 size_t max_data_payload_length,
558 bool nack_enabled) {
perkj26091b12016-09-01 01:17:40 -0700559 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 01:17:40 -0700560 RTC_DCHECK(sink_);
perkjfa10b552016-10-02 23:45:26 -0700561 LOG(LS_INFO) << "ConfigureEncoder requested.";
Pera48ddb72016-09-29 11:48:50 +0200562
563 max_data_payload_length_ = max_data_payload_length;
asapersson5f7226f2016-11-25 04:37:00 -0800564 nack_enabled_ = nack_enabled;
Pera48ddb72016-09-29 11:48:50 +0200565 encoder_config_ = std::move(config);
perkjfa10b552016-10-02 23:45:26 -0700566 pending_encoder_reconfiguration_ = true;
Pera48ddb72016-09-29 11:48:50 +0200567
perkjfa10b552016-10-02 23:45:26 -0700568 // Reconfigure the encoder now if the encoder has an internal source or
Per21d45d22016-10-30 21:37:57 +0100569 // if the frame resolution is known. Otherwise, the reconfiguration is
570 // deferred until the next frame to minimize the number of reconfigurations.
571 // The codec configuration depends on incoming video frame size.
572 if (last_frame_info_) {
573 ReconfigureEncoder();
574 } else if (settings_.internal_source) {
brandtra3241662017-05-03 04:55:51 -0700575 last_frame_info_ =
576 rtc::Optional<VideoFrameInfo>(VideoFrameInfo(176, 144, false));
perkjfa10b552016-10-02 23:45:26 -0700577 ReconfigureEncoder();
578 }
579}
perkj26091b12016-09-01 01:17:40 -0700580
mflodmancc3d4422017-08-03 08:27:51 -0700581void VideoStreamEncoder::ReconfigureEncoder() {
perkjfa10b552016-10-02 23:45:26 -0700582 RTC_DCHECK_RUN_ON(&encoder_queue_);
583 RTC_DCHECK(pending_encoder_reconfiguration_);
584 std::vector<VideoStream> streams =
585 encoder_config_.video_stream_factory->CreateEncoderStreams(
586 last_frame_info_->width, last_frame_info_->height, encoder_config_);
perkj26091b12016-09-01 01:17:40 -0700587
ilnik6b826ef2017-06-16 06:53:48 -0700588 // TODO(ilnik): If configured resolution is significantly less than provided,
589 // e.g. because there are not enough SSRCs for all simulcast streams,
590 // signal new resolutions via SinkWants to video source.
591
592 // Stream dimensions may be not equal to given because of a simulcast
593 // restrictions.
594 int highest_stream_width = static_cast<int>(streams.back().width);
595 int highest_stream_height = static_cast<int>(streams.back().height);
596 // Dimension may be reduced to be, e.g. divisible by 4.
597 RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
598 RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
599 crop_width_ = last_frame_info_->width - highest_stream_width;
600 crop_height_ = last_frame_info_->height - highest_stream_height;
601
Erik Språng08127a92016-11-16 16:41:30 +0100602 VideoCodec codec;
603 if (!VideoCodecInitializer::SetupCodec(encoder_config_, settings_, streams,
asapersson5f7226f2016-11-25 04:37:00 -0800604 nack_enabled_, &codec,
605 &rate_allocator_)) {
Erik Språng08127a92016-11-16 16:41:30 +0100606 LOG(LS_ERROR) << "Failed to create encoder configuration.";
607 }
perkjfa10b552016-10-02 23:45:26 -0700608
609 codec.startBitrate =
610 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
611 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
612 codec.expect_encode_from_texture = last_frame_info_->is_texture;
sprangfda496a2017-06-15 04:21:07 -0700613 max_framerate_ = codec.maxFramerate;
614 RTC_DCHECK_LE(max_framerate_, kMaxFramerateFps);
Stefan Holmere5904162015-03-26 11:11:06 +0100615
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200616 bool success = video_sender_.RegisterSendCodec(
perkjfa10b552016-10-02 23:45:26 -0700617 &codec, number_of_cores_,
618 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK;
Peter Boström905f8e72016-03-02 16:59:56 +0100619 if (!success) {
620 LOG(LS_ERROR) << "Failed to configure encoder.";
sprangfe627f32017-03-29 08:24:59 -0700621 rate_allocator_.reset();
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000622 }
Peter Boström905f8e72016-03-02 16:59:56 +0100623
ilnik35b7de42017-03-15 04:24:21 -0700624 video_sender_.UpdateChannelParemeters(rate_allocator_.get(),
625 bitrate_observer_);
626
sprangfda496a2017-06-15 04:21:07 -0700627 // Get the current actual framerate, as measured by the stats proxy. This is
628 // used to get the correct bitrate layer allocation.
629 int current_framerate = stats_proxy_->GetSendFrameRate();
630 if (current_framerate == 0)
631 current_framerate = codec.maxFramerate;
sprang552c7c72017-02-13 04:41:45 -0800632 stats_proxy_->OnEncoderReconfigured(
sprangfda496a2017-06-15 04:21:07 -0700633 encoder_config_,
634 rate_allocator_.get()
635 ? rate_allocator_->GetPreferredBitrateBps(current_framerate)
636 : codec.maxBitrate);
Per512ecb32016-09-23 15:52:06 +0200637
perkjfa10b552016-10-02 23:45:26 -0700638 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 16:41:30 +0100639
Pera48ddb72016-09-29 11:48:50 +0200640 sink_->OnEncoderConfigurationChanged(
perkjfa10b552016-10-02 23:45:26 -0700641 std::move(streams), encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 01:44:11 -0800642
sprangfda496a2017-06-15 04:21:07 -0700643 // Get the current target framerate, ie the maximum framerate as specified by
644 // the current codec configuration, or any limit imposed by cpu adaption in
645 // maintain-resolution or balanced mode. This is used to make sure overuse
646 // detection doesn't needlessly trigger in low and/or variable framerate
647 // scenarios.
648 int target_framerate = std::min(
649 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
650 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
651
kthelgason2bc68642017-02-07 07:02:22 -0800652 ConfigureQualityScaler();
653}
654
mflodmancc3d4422017-08-03 08:27:51 -0700655void VideoStreamEncoder::ConfigureQualityScaler() {
kthelgason2bc68642017-02-07 07:02:22 -0800656 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -0800657 const auto scaling_settings = settings_.encoder->GetScalingSettings();
asapersson36e9eb42017-03-31 05:29:12 -0700658 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 00:34:08 -0700659 IsResolutionScalingEnabled(degradation_preference_) &&
660 scaling_settings.enabled;
kthelgason3af6cc02017-03-22 00:25:28 -0700661
asapersson36e9eb42017-03-31 05:29:12 -0700662 if (quality_scaling_allowed) {
asapersson09f05612017-05-15 23:40:18 -0700663 if (quality_scaler_.get() == nullptr) {
664 // Quality scaler has not already been configured.
665 // Drop frames and scale down until desired quality is achieved.
666 if (scaling_settings.thresholds) {
667 quality_scaler_.reset(
668 new QualityScaler(this, *(scaling_settings.thresholds)));
669 } else {
670 quality_scaler_.reset(new QualityScaler(this, codec_type_));
671 }
kthelgason876222f2016-11-29 01:44:11 -0800672 }
673 } else {
674 quality_scaler_.reset(nullptr);
kthelgasonad9010c2017-02-14 00:46:51 -0800675 initial_rampup_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 01:44:11 -0800676 }
asapersson09f05612017-05-15 23:40:18 -0700677
678 stats_proxy_->SetAdaptationStats(GetActiveCounts(kCpu),
679 GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000680}
681
mflodmancc3d4422017-08-03 08:27:51 -0700682void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 01:17:40 -0700683 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 01:17:40 -0700684 VideoFrame incoming_frame = video_frame;
685
686 // Local time in webrtc time base.
ilnik04f4d122017-06-19 07:18:55 -0700687 int64_t current_time_us = clock_->TimeInMicroseconds();
688 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
689 // In some cases, e.g., when the frame from decoder is fed to encoder,
690 // the timestamp may be set to the future. As the encoding pipeline assumes
691 // capture time to be less than present time, we should reset the capture
692 // timestamps here. Otherwise there may be issues with RTP send stream.
693 if (incoming_frame.timestamp_us() > current_time_us)
694 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 01:17:40 -0700695
696 // Capture time may come from clock with an offset and drift from clock_.
697 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 10:02:22 -0800698 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 01:17:40 -0700699 capture_ntp_time_ms = video_frame.ntp_time_ms();
700 } else if (video_frame.render_time_ms() != 0) {
701 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
702 } else {
nisse1c0dea82017-01-30 02:43:18 -0800703 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 01:17:40 -0700704 }
705 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
706
707 // Convert NTP time, in ms, to RTP timestamp.
708 const int kMsToRtpTimestamp = 90;
709 incoming_frame.set_timestamp(
710 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
711
712 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
713 // We don't allow the same capture time for two frames, drop this one.
714 LOG(LS_WARNING) << "Same/old NTP timestamp ("
715 << incoming_frame.ntp_time_ms()
716 << " <= " << last_captured_timestamp_
717 << ") for incoming frame. Dropping.";
718 return;
719 }
720
asapersson6ffb67d2016-09-12 00:10:45 -0700721 bool log_stats = false;
nisse1c0dea82017-01-30 02:43:18 -0800722 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
723 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 00:10:45 -0700724 log_stats = true;
725 }
726
perkj26091b12016-09-01 01:17:40 -0700727 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
asapersson6ffb67d2016-09-12 00:10:45 -0700728 encoder_queue_.PostTask(std::unique_ptr<rtc::QueuedTask>(new EncodeTask(
nissee0e3bdf2017-01-18 02:16:20 -0800729 incoming_frame, this, rtc::TimeMicros(), log_stats)));
perkj26091b12016-09-01 01:17:40 -0700730}
731
mflodmancc3d4422017-08-03 08:27:51 -0700732bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 01:17:40 -0700733 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08 +0000734 // Pause video if paused by caller or as long as the network is down or the
735 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 07:27:16 -0700736 // If the pacer queue has grown too large or the network is down,
perkjfea93092016-05-14 00:58:48 -0700737 // last_observed_bitrate_bps_ will be 0.
perkj26091b12016-09-01 01:17:40 -0700738 return last_observed_bitrate_bps_ == 0;
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +0000739}
740
mflodmancc3d4422017-08-03 08:27:51 -0700741void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 01:17:40 -0700742 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000743 // Start trace event only on the first frame after encoder is paused.
744 if (!encoder_paused_and_dropped_frame_) {
745 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
746 }
747 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000748}
749
mflodmancc3d4422017-08-03 08:27:51 -0700750void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 01:17:40 -0700751 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000752 // End trace event on first frame after encoder resumes, if frame was dropped.
753 if (encoder_paused_and_dropped_frame_) {
754 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
755 }
756 encoder_paused_and_dropped_frame_ = false;
757}
758
mflodmancc3d4422017-08-03 08:27:51 -0700759void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
760 int64_t time_when_posted_us) {
perkj26091b12016-09-01 01:17:40 -0700761 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 01:44:11 -0800762
perkj26091b12016-09-01 01:17:40 -0700763 if (pre_encode_callback_)
764 pre_encode_callback_->OnFrame(video_frame);
765
Per21d45d22016-10-30 21:37:57 +0100766 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-02 23:45:26 -0700767 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-02 23:45:26 -0700768 video_frame.is_texture() != last_frame_info_->is_texture) {
769 pending_encoder_reconfiguration_ = true;
brandtra3241662017-05-03 04:55:51 -0700770 last_frame_info_ = rtc::Optional<VideoFrameInfo>(VideoFrameInfo(
771 video_frame.width(), video_frame.height(), video_frame.is_texture()));
perkjfa10b552016-10-02 23:45:26 -0700772 LOG(LS_INFO) << "Video frame parameters changed: dimensions="
773 << last_frame_info_->width << "x" << last_frame_info_->height
brandtra3241662017-05-03 04:55:51 -0700774 << ", texture=" << last_frame_info_->is_texture << ".";
perkjfa10b552016-10-02 23:45:26 -0700775 }
776
kthelgason2bc68642017-02-07 07:02:22 -0800777 if (initial_rampup_ < kMaxInitialFramedrop &&
778 video_frame.size() >
779 MaximumFrameSizeForBitrate(encoder_start_bitrate_bps_ / 1000)) {
780 LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
781 AdaptDown(kQuality);
782 ++initial_rampup_;
783 return;
784 }
785 initial_rampup_ = kMaxInitialFramedrop;
786
sprang57c2fff2017-01-16 06:24:02 -0800787 int64_t now_ms = clock_->TimeInMilliseconds();
perkjfa10b552016-10-02 23:45:26 -0700788 if (pending_encoder_reconfiguration_) {
789 ReconfigureEncoder();
sprang4847ae62017-06-27 07:06:52 -0700790 last_parameters_update_ms_.emplace(now_ms);
sprang57c2fff2017-01-16 06:24:02 -0800791 } else if (!last_parameters_update_ms_ ||
792 now_ms - *last_parameters_update_ms_ >=
793 vcm::VCMProcessTimer::kDefaultProcessIntervalMs) {
794 video_sender_.UpdateChannelParemeters(rate_allocator_.get(),
795 bitrate_observer_);
sprang4847ae62017-06-27 07:06:52 -0700796 last_parameters_update_ms_.emplace(now_ms);
perkjfa10b552016-10-02 23:45:26 -0700797 }
798
perkj26091b12016-09-01 01:17:40 -0700799 if (EncoderPaused()) {
800 TraceFrameDropStart();
801 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000802 }
perkj26091b12016-09-01 01:17:40 -0700803 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25 +0000804
ilnik6b826ef2017-06-16 06:53:48 -0700805 VideoFrame out_frame(video_frame);
806 // Crop frame if needed.
807 if (crop_width_ > 0 || crop_height_ > 0) {
808 int cropped_width = video_frame.width() - crop_width_;
809 int cropped_height = video_frame.height() - crop_height_;
810 rtc::scoped_refptr<I420Buffer> cropped_buffer =
811 I420Buffer::Create(cropped_width, cropped_height);
812 // TODO(ilnik): Remove scaling if cropping is too big, as it should never
813 // happen after SinkWants signaled correctly from ReconfigureEncoder.
814 if (crop_width_ < 4 && crop_height_ < 4) {
815 cropped_buffer->CropAndScaleFrom(
816 *video_frame.video_frame_buffer()->ToI420(), crop_width_ / 2,
817 crop_height_ / 2, cropped_width, cropped_height);
818 } else {
819 cropped_buffer->ScaleFrom(
820 *video_frame.video_frame_buffer()->ToI420().get());
821 }
822 out_frame =
823 VideoFrame(cropped_buffer, video_frame.timestamp(),
824 video_frame.render_time_ms(), video_frame.rotation());
825 out_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
826 }
827
Magnus Jedvert26679d62015-04-07 14:07:41 +0200828 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18 +0000829 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43 +0000830
ilnik6b826ef2017-06-16 06:53:48 -0700831 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 06:32:18 -0700832
ilnik6b826ef2017-06-16 06:53:48 -0700833 video_sender_.AddVideoFrame(out_frame, nullptr);
niklase@google.com470e71d2011-07-07 08:21:25 +0000834}
niklase@google.com470e71d2011-07-07 08:21:25 +0000835
mflodmancc3d4422017-08-03 08:27:51 -0700836void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 01:17:40 -0700837 if (!encoder_queue_.IsCurrent()) {
838 encoder_queue_.PostTask([this] { SendKeyFrame(); });
839 return;
840 }
841 RTC_DCHECK_RUN_ON(&encoder_queue_);
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200842 video_sender_.IntraFrameRequest(0);
stefan@webrtc.org07b45a52012-02-02 08:37:48 +0000843}
844
mflodmancc3d4422017-08-03 08:27:51 -0700845EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700846 const EncodedImage& encoded_image,
847 const CodecSpecificInfo* codec_specific_info,
848 const RTPFragmentationHeader* fragmentation) {
perkj26091b12016-09-01 01:17:40 -0700849 // Encoded is called on whatever thread the real encoder implementation run
850 // on. In the case of hardware encoders, there might be several encoders
851 // running in parallel on different threads.
sprang552c7c72017-02-13 04:41:45 -0800852 stats_proxy_->OnSendEncodedImage(encoded_image, codec_specific_info);
sprang3911c262016-04-15 01:24:14 -0700853
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700854 EncodedImageCallback::Result result =
855 sink_->OnEncodedImage(encoded_image, codec_specific_info, fragmentation);
perkjbc75d972016-05-02 06:31:25 -0700856
nissee0e3bdf2017-01-18 02:16:20 -0800857 int64_t time_sent_us = rtc::TimeMicros();
perkjd52063f2016-09-07 06:32:18 -0700858 uint32_t timestamp = encoded_image._timeStamp;
kthelgason876222f2016-11-29 01:44:11 -0800859 const int qp = encoded_image.qp_;
nissee0e3bdf2017-01-18 02:16:20 -0800860 encoder_queue_.PostTask([this, timestamp, time_sent_us, qp] {
perkjd52063f2016-09-07 06:32:18 -0700861 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 04:21:07 -0700862 overuse_detector_->FrameSent(timestamp, time_sent_us);
sprang84a37592017-02-10 07:04:27 -0800863 if (quality_scaler_ && qp >= 0)
kthelgason876222f2016-11-29 01:44:11 -0800864 quality_scaler_->ReportQP(qp);
perkjd52063f2016-09-07 06:32:18 -0700865 });
perkj803d97f2016-11-01 11:45:46 -0700866
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700867 return result;
Peter Boströmb7d9a972015-12-18 16:01:11 +0100868}
869
mflodmancc3d4422017-08-03 08:27:51 -0700870void VideoStreamEncoder::OnDroppedFrame() {
kthelgason876222f2016-11-29 01:44:11 -0800871 encoder_queue_.PostTask([this] {
872 RTC_DCHECK_RUN_ON(&encoder_queue_);
873 if (quality_scaler_)
874 quality_scaler_->ReportDroppedFrame();
875 });
876}
877
mflodmancc3d4422017-08-03 08:27:51 -0700878void VideoStreamEncoder::SendStatistics(uint32_t bit_rate,
879 uint32_t frame_rate) {
perkj26091b12016-09-01 01:17:40 -0700880 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
sprang552c7c72017-02-13 04:41:45 -0800881 stats_proxy_->OnEncoderStatsUpdate(frame_rate, bit_rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000882}
883
mflodmancc3d4422017-08-03 08:27:51 -0700884void VideoStreamEncoder::OnReceivedIntraFrameRequest(size_t stream_index) {
perkj26091b12016-09-01 01:17:40 -0700885 if (!encoder_queue_.IsCurrent()) {
886 encoder_queue_.PostTask(
887 [this, stream_index] { OnReceivedIntraFrameRequest(stream_index); });
888 return;
889 }
890 RTC_DCHECK_RUN_ON(&encoder_queue_);
mflodman@webrtc.org84d17832011-12-01 17:02:23 +0000891 // Key frame request from remote side, signal to VCM.
justinlin@chromium.org7bfb3a32013-05-13 22:59:00 +0000892 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
perkj600246e2016-05-04 11:26:51 -0700893 video_sender_.IntraFrameRequest(stream_index);
mflodman@webrtc.orgaca26292012-10-05 16:17:41 +0000894}
895
mflodmancc3d4422017-08-03 08:27:51 -0700896void VideoStreamEncoder::OnBitrateUpdated(uint32_t bitrate_bps,
897 uint8_t fraction_lost,
898 int64_t round_trip_time_ms) {
perkj26091b12016-09-01 01:17:40 -0700899 if (!encoder_queue_.IsCurrent()) {
900 encoder_queue_.PostTask(
901 [this, bitrate_bps, fraction_lost, round_trip_time_ms] {
902 OnBitrateUpdated(bitrate_bps, fraction_lost, round_trip_time_ms);
903 });
904 return;
905 }
906 RTC_DCHECK_RUN_ON(&encoder_queue_);
907 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
908
perkjec81bcd2016-05-11 06:01:13 -0700909 LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
mflodman8602a3d2015-05-20 15:54:42 -0700910 << " packet loss " << static_cast<int>(fraction_lost)
mflodman@webrtc.org5574dac2014-04-07 10:56:31 +0000911 << " rtt " << round_trip_time_ms;
perkj26091b12016-09-01 01:17:40 -0700912
Peter Boströmcd5c25c2016-04-21 16:48:08 +0200913 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost,
sprang1a646ee2016-12-01 06:34:11 -0800914 round_trip_time_ms, rate_allocator_.get(),
915 bitrate_observer_);
perkj26091b12016-09-01 01:17:40 -0700916
917 encoder_start_bitrate_bps_ =
918 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
mflodman101f2502016-06-09 17:21:19 +0200919 bool video_is_suspended = bitrate_bps == 0;
Erik Språng08127a92016-11-16 16:41:30 +0100920 bool video_suspension_changed = video_is_suspended != EncoderPaused();
perkj26091b12016-09-01 01:17:40 -0700921 last_observed_bitrate_bps_ = bitrate_bps;
Peter Boströmd153a372015-11-10 15:27:12 +0000922
sprang552c7c72017-02-13 04:41:45 -0800923 if (video_suspension_changed) {
mflodman522739c2016-06-22 17:42:30 +0200924 LOG(LS_INFO) << "Video suspend state changed to: "
925 << (video_is_suspended ? "suspended" : "not suspended");
Peter Boström7083e112015-09-22 16:28:51 +0200926 stats_proxy_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 17:21:19 +0200927 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000928}
929
mflodmancc3d4422017-08-03 08:27:51 -0700930void VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -0700931 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-02 23:53:04 -0700932 AdaptationRequest adaptation_request = {
933 last_frame_info_->pixel_count(),
934 stats_proxy_->GetStats().input_frame_rate,
935 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-15 23:40:18 -0700936
sprangc5d62e22017-04-02 23:53:04 -0700937 bool downgrade_requested =
938 last_adaptation_request_ &&
939 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
940
sprangc5d62e22017-04-02 23:53:04 -0700941 switch (degradation_preference_) {
hbos8d609f62017-04-10 07:39:05 -0700942 case VideoSendStream::DegradationPreference::kBalanced:
asaperssonf7e294d2017-06-13 23:25:22 -0700943 break;
hbos8d609f62017-04-10 07:39:05 -0700944 case VideoSendStream::DegradationPreference::kMaintainFramerate:
sprangc5d62e22017-04-02 23:53:04 -0700945 if (downgrade_requested &&
946 adaptation_request.input_pixel_count_ >=
947 last_adaptation_request_->input_pixel_count_) {
948 // Don't request lower resolution if the current resolution is not
949 // lower than the last time we asked for the resolution to be lowered.
950 return;
951 }
952 break;
hbos8d609f62017-04-10 07:39:05 -0700953 case VideoSendStream::DegradationPreference::kMaintainResolution:
sprangc5d62e22017-04-02 23:53:04 -0700954 if (adaptation_request.framerate_fps_ <= 0 ||
955 (downgrade_requested &&
956 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
957 // If no input fps estimate available, can't determine how to scale down
958 // framerate. Otherwise, don't request lower framerate if we don't have
959 // a valid frame rate. Since framerate, unlike resolution, is a measure
960 // we have to estimate, and can fluctuate naturally over time, don't
961 // make the same kind of limitations as for resolution, but trust the
962 // overuse detector to not trigger too often.
963 return;
964 }
965 break;
hbos8d609f62017-04-10 07:39:05 -0700966 case VideoSendStream::DegradationPreference::kDegradationDisabled:
sprangc5d62e22017-04-02 23:53:04 -0700967 return;
sprang84a37592017-02-10 07:04:27 -0800968 }
sprangc5d62e22017-04-02 23:53:04 -0700969
asaperssond0de2952017-04-21 01:47:31 -0700970 if (reason == kCpu) {
asaperssonf7e294d2017-06-13 23:25:22 -0700971 if (GetConstAdaptCounter().ResolutionCount(kCpu) >=
972 kMaxCpuResolutionDowngrades ||
973 GetConstAdaptCounter().FramerateCount(kCpu) >=
974 kMaxCpuFramerateDowngrades) {
asaperssond0de2952017-04-21 01:47:31 -0700975 return;
asaperssonf7e294d2017-06-13 23:25:22 -0700976 }
kthelgason876222f2016-11-29 01:44:11 -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.
sprang317005a2017-06-08 07:12:17 -0700988 FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -0700989 }
hbos8d609f62017-04-10 07:39:05 -0700990 case VideoSendStream::DegradationPreference::kMaintainFramerate:
asapersson13874762017-06-07 00:01:02 -0700991 // Scale down resolution.
asaperssond0de2952017-04-21 01:47:31 -0700992 if (!source_proxy_->RequestResolutionLowerThan(
993 adaptation_request.input_pixel_count_)) {
994 return;
995 }
asaperssonf7e294d2017-06-13 23:25:22 -0700996 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -0700997 break;
sprangfda496a2017-06-15 04:21:07 -0700998 case VideoSendStream::DegradationPreference::kMaintainResolution: {
asapersson13874762017-06-07 00:01:02 -0700999 // Scale down framerate.
sprangfda496a2017-06-15 04:21:07 -07001000 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
1001 adaptation_request.framerate_fps_);
1002 if (requested_framerate == -1)
asapersson13874762017-06-07 00:01:02 -07001003 return;
sprangfda496a2017-06-15 04:21:07 -07001004 RTC_DCHECK_NE(max_framerate_, -1);
1005 overuse_detector_->OnTargetFramerateUpdated(
1006 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001007 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001008 break;
sprangfda496a2017-06-15 04:21:07 -07001009 }
hbos8d609f62017-04-10 07:39:05 -07001010 case VideoSendStream::DegradationPreference::kDegradationDisabled:
sprangc5d62e22017-04-02 23:53:04 -07001011 RTC_NOTREACHED();
1012 }
1013
asaperssond0de2952017-04-21 01:47:31 -07001014 last_adaptation_request_.emplace(adaptation_request);
1015
asapersson09f05612017-05-15 23:40:18 -07001016 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 01:47:31 -07001017
asapersson09f05612017-05-15 23:40:18 -07001018 LOG(LS_INFO) << GetConstAdaptCounter().ToString();
perkj26091b12016-09-01 01:17:40 -07001019}
1020
mflodmancc3d4422017-08-03 08:27:51 -07001021void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 06:32:18 -07001022 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-15 23:40:18 -07001023
1024 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
1025 int num_downgrades = adapt_counter.TotalCount(reason);
1026 if (num_downgrades == 0)
perkj803d97f2016-11-01 11:45:46 -07001027 return;
asapersson09f05612017-05-15 23:40:18 -07001028 RTC_DCHECK_GT(num_downgrades, 0);
1029
sprangc5d62e22017-04-02 23:53:04 -07001030 AdaptationRequest adaptation_request = {
1031 last_frame_info_->pixel_count(),
1032 stats_proxy_->GetStats().input_frame_rate,
1033 AdaptationRequest::Mode::kAdaptUp};
1034
1035 bool adapt_up_requested =
1036 last_adaptation_request_ &&
1037 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-15 23:40:18 -07001038
asaperssonf7e294d2017-06-13 23:25:22 -07001039 if (degradation_preference_ ==
1040 VideoSendStream::DegradationPreference::kMaintainFramerate) {
1041 if (adapt_up_requested &&
1042 adaptation_request.input_pixel_count_ <=
1043 last_adaptation_request_->input_pixel_count_) {
1044 // Don't request higher resolution if the current resolution is not
1045 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-02 23:53:04 -07001046 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001047 }
sprangb1ca0732017-02-01 08:38:12 -08001048 }
sprangc5d62e22017-04-02 23:53:04 -07001049
sprangc5d62e22017-04-02 23:53:04 -07001050 switch (degradation_preference_) {
asaperssonf7e294d2017-06-13 23:25:22 -07001051 case VideoSendStream::DegradationPreference::kBalanced: {
1052 // Try scale up framerate, if higher.
1053 int fps = MaxFps(last_frame_info_->pixel_count());
1054 if (source_proxy_->IncreaseFramerate(fps)) {
1055 GetAdaptCounter().DecrementFramerate(reason, fps);
1056 // Reset framerate in case of fewer fps steps down than up.
1057 if (adapt_counter.FramerateCount() == 0 &&
1058 fps != std::numeric_limits<int>::max()) {
1059 LOG(LS_INFO) << "Removing framerate down-scaling setting.";
1060 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
1061 }
1062 break;
1063 }
1064 // Scale up resolution.
sprang317005a2017-06-08 07:12:17 -07001065 FALLTHROUGH();
asaperssonf7e294d2017-06-13 23:25:22 -07001066 }
asapersson13874762017-06-07 00:01:02 -07001067 case VideoSendStream::DegradationPreference::kMaintainFramerate: {
1068 // Scale up resolution.
1069 int pixel_count = adaptation_request.input_pixel_count_;
1070 if (adapt_counter.ResolutionCount() == 1) {
sprangc5d62e22017-04-02 23:53:04 -07001071 LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001072 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001073 }
asapersson13874762017-06-07 00:01:02 -07001074 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
1075 return;
asaperssonf7e294d2017-06-13 23:25:22 -07001076 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-02 23:53:04 -07001077 break;
asapersson13874762017-06-07 00:01:02 -07001078 }
1079 case VideoSendStream::DegradationPreference::kMaintainResolution: {
1080 // Scale up framerate.
1081 int fps = adaptation_request.framerate_fps_;
1082 if (adapt_counter.FramerateCount() == 1) {
sprangc5d62e22017-04-02 23:53:04 -07001083 LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 00:01:02 -07001084 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-02 23:53:04 -07001085 }
sprangfda496a2017-06-15 04:21:07 -07001086
1087 const int requested_framerate =
1088 source_proxy_->RequestHigherFramerateThan(fps);
1089 if (requested_framerate == -1) {
1090 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 00:01:02 -07001091 return;
sprangfda496a2017-06-15 04:21:07 -07001092 }
1093 overuse_detector_->OnTargetFramerateUpdated(
1094 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-13 23:25:22 -07001095 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-02 23:53:04 -07001096 break;
asapersson13874762017-06-07 00:01:02 -07001097 }
hbos8d609f62017-04-10 07:39:05 -07001098 case VideoSendStream::DegradationPreference::kDegradationDisabled:
asaperssonf7e294d2017-06-13 23:25:22 -07001099 return;
sprangc5d62e22017-04-02 23:53:04 -07001100 }
1101
asaperssond0de2952017-04-21 01:47:31 -07001102 last_adaptation_request_.emplace(adaptation_request);
1103
asapersson09f05612017-05-15 23:40:18 -07001104 UpdateAdaptationStats(reason);
1105
1106 LOG(LS_INFO) << adapt_counter.ToString();
1107}
1108
mflodmancc3d4422017-08-03 08:27:51 -07001109void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 01:47:31 -07001110 switch (reason) {
asaperssond0de2952017-04-21 01:47:31 -07001111 case kCpu:
asapersson09f05612017-05-15 23:40:18 -07001112 stats_proxy_->OnCpuAdaptationChanged(GetActiveCounts(kCpu),
1113 GetActiveCounts(kQuality));
1114 break;
1115 case kQuality:
1116 stats_proxy_->OnQualityAdaptationChanged(GetActiveCounts(kCpu),
1117 GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 01:47:31 -07001118 break;
1119 }
perkj26091b12016-09-01 01:17:40 -07001120}
1121
mflodmancc3d4422017-08-03 08:27:51 -07001122VideoStreamEncoder::AdaptCounts VideoStreamEncoder::GetActiveCounts(
1123 AdaptReason reason) {
1124 VideoStreamEncoder::AdaptCounts counts =
1125 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-15 23:40:18 -07001126 switch (reason) {
1127 case kCpu:
1128 if (!IsFramerateScalingEnabled(degradation_preference_))
1129 counts.fps = -1;
1130 if (!IsResolutionScalingEnabled(degradation_preference_))
1131 counts.resolution = -1;
1132 break;
1133 case kQuality:
1134 if (!IsFramerateScalingEnabled(degradation_preference_) ||
1135 !quality_scaler_) {
1136 counts.fps = -1;
1137 }
1138 if (!IsResolutionScalingEnabled(degradation_preference_) ||
1139 !quality_scaler_) {
1140 counts.resolution = -1;
1141 }
1142 break;
sprangc5d62e22017-04-02 23:53:04 -07001143 }
asapersson09f05612017-05-15 23:40:18 -07001144 return counts;
sprangc5d62e22017-04-02 23:53:04 -07001145}
1146
mflodmancc3d4422017-08-03 08:27:51 -07001147VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001148 return adapt_counters_[degradation_preference_];
1149}
1150
mflodmancc3d4422017-08-03 08:27:51 -07001151const VideoStreamEncoder::AdaptCounter&
1152VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001153 return adapt_counters_[degradation_preference_];
1154}
1155
1156// Class holding adaptation information.
mflodmancc3d4422017-08-03 08:27:51 -07001157VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-15 23:40:18 -07001158 fps_counters_.resize(kScaleReasonSize);
1159 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-13 23:25:22 -07001160 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-15 23:40:18 -07001161}
1162
mflodmancc3d4422017-08-03 08:27:51 -07001163VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-15 23:40:18 -07001164
mflodmancc3d4422017-08-03 08:27:51 -07001165std::string VideoStreamEncoder::AdaptCounter::ToString() const {
asapersson09f05612017-05-15 23:40:18 -07001166 std::stringstream ss;
1167 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
1168 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
1169 return ss.str();
1170}
1171
mflodmancc3d4422017-08-03 08:27:51 -07001172VideoStreamEncoder::AdaptCounts VideoStreamEncoder::AdaptCounter::Counts(
1173 int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001174 AdaptCounts counts;
1175 counts.fps = fps_counters_[reason];
1176 counts.resolution = resolution_counters_[reason];
1177 return counts;
1178}
1179
mflodmancc3d4422017-08-03 08:27:51 -07001180void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001181 ++(fps_counters_[reason]);
asapersson09f05612017-05-15 23:40:18 -07001182}
1183
mflodmancc3d4422017-08-03 08:27:51 -07001184void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001185 ++(resolution_counters_[reason]);
1186}
1187
mflodmancc3d4422017-08-03 08:27:51 -07001188void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001189 if (fps_counters_[reason] == 0) {
1190 // Balanced mode: Adapt up is in a different order, switch reason.
1191 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
1192 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
1193 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
1194 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
1195 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
1196 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1197 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
1198 MoveCount(&resolution_counters_, reason);
1199 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
1200 }
1201 --(fps_counters_[reason]);
1202 RTC_DCHECK_GE(fps_counters_[reason], 0);
1203}
1204
mflodmancc3d4422017-08-03 08:27:51 -07001205void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001206 if (resolution_counters_[reason] == 0) {
1207 // Balanced mode: Adapt up is in a different order, switch reason.
1208 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1209 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
1210 MoveCount(&fps_counters_, reason);
1211 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
1212 }
1213 --(resolution_counters_[reason]);
1214 RTC_DCHECK_GE(resolution_counters_[reason], 0);
1215}
1216
mflodmancc3d4422017-08-03 08:27:51 -07001217void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
1218 int cur_fps) {
asaperssonf7e294d2017-06-13 23:25:22 -07001219 DecrementFramerate(reason);
1220 // Reset if at max fps (i.e. in case of fewer steps up than down).
1221 if (cur_fps == std::numeric_limits<int>::max())
1222 std::fill(fps_counters_.begin(), fps_counters_.end(), 0);
asapersson09f05612017-05-15 23:40:18 -07001223}
1224
mflodmancc3d4422017-08-03 08:27:51 -07001225int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-15 23:40:18 -07001226 return Count(fps_counters_);
1227}
1228
mflodmancc3d4422017-08-03 08:27:51 -07001229int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-15 23:40:18 -07001230 return Count(resolution_counters_);
1231}
1232
mflodmancc3d4422017-08-03 08:27:51 -07001233int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001234 return fps_counters_[reason];
1235}
1236
mflodmancc3d4422017-08-03 08:27:51 -07001237int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001238 return resolution_counters_[reason];
1239}
1240
mflodmancc3d4422017-08-03 08:27:51 -07001241int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-15 23:40:18 -07001242 return FramerateCount(reason) + ResolutionCount(reason);
1243}
1244
mflodmancc3d4422017-08-03 08:27:51 -07001245int VideoStreamEncoder::AdaptCounter::Count(
1246 const std::vector<int>& counters) const {
asapersson09f05612017-05-15 23:40:18 -07001247 return std::accumulate(counters.begin(), counters.end(), 0);
1248}
1249
mflodmancc3d4422017-08-03 08:27:51 -07001250void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
1251 int from_reason) {
asaperssonf7e294d2017-06-13 23:25:22 -07001252 int to_reason = (from_reason + 1) % kScaleReasonSize;
1253 ++((*counters)[to_reason]);
1254 --((*counters)[from_reason]);
1255}
1256
mflodmancc3d4422017-08-03 08:27:51 -07001257std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-15 23:40:18 -07001258 const std::vector<int>& counters) const {
1259 std::stringstream ss;
1260 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
1261 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-02 23:53:04 -07001262 }
asapersson09f05612017-05-15 23:40:18 -07001263 return ss.str();
sprangc5d62e22017-04-02 23:53:04 -07001264}
1265
mflodman@webrtc.org84d17832011-12-01 17:02:23 +00001266} // namespace webrtc