blob: ccd28544e858f6a3312624258d6fca4353804546 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:251/*
stefan@webrtc.org07b45a52012-02-02 08:37:482 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:253 *
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 15:27:5111#include "webrtc/video/video_stream_encoder.h"
mflodman@webrtc.org84d17832011-12-01 17:02:2312
stefan@webrtc.orgc3cc3752013-06-04 09:36:5613#include <algorithm>
perkj57c21f92016-06-17 14:27:1614#include <limits>
sprangc5d62e22017-04-03 06:53:0415#include <numeric>
Per512ecb32016-09-23 13:52:0616#include <utility>
niklase@google.com470e71d2011-07-07 08:21:2517
ilnik6b826ef2017-06-16 13:53:4818#include "webrtc/api/video/i420_buffer.h"
sprang1a646ee2016-12-01 14:34:1119#include "webrtc/common_video/include/video_bitrate_allocator.h"
nisseea3a7982017-05-15 09:42:1120#include "webrtc/common_video/include/video_frame.h"
Henrik Kjellander0b9e29c2015-11-16 10:12:2421#include "webrtc/modules/pacing/paced_sender.h"
Erik Språng08127a92016-11-16 15:41:3022#include "webrtc/modules/video_coding/codecs/vp8/temporal_layers.h"
sprangb1ca0732017-02-01 16:38:1223#include "webrtc/modules/video_coding/include/video_codec_initializer.h"
Henrik Kjellander2557b862015-11-18 21:00:2124#include "webrtc/modules/video_coding/include/video_coding.h"
25#include "webrtc/modules/video_coding/include/video_coding_defines.h"
Edward Lemurc20978e2017-07-06 17:44:3426#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 10:13:2832#include "webrtc/video/overuse_frame_detector.h"
pbos@webrtc.org273a4142014-12-01 15:23:2133#include "webrtc/video/send_statistics_proxy.h"
nisseea3a7982017-05-15 09:42:1134
niklase@google.com470e71d2011-07-07 08:21:2535namespace webrtc {
36
perkj26091b12016-09-01 08:17:4037namespace {
sprangb1ca0732017-02-01 16:38:1238
asapersson6ffb67d2016-09-12 07:10:4539// Time interval for logging frame counts.
40const int64_t kFrameLogIntervalMs = 60000;
sprangc5d62e22017-04-03 06:53:0441const int kMinFramerateFps = 2;
sprangfda496a2017-06-15 11:21:0742const int kMaxFramerateFps = 120;
perkj26091b12016-09-01 08:17:4043
kthelgason2bc68642017-02-07 15:02:2244// 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 15:02:2248uint32_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-14 06:25:2259// 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-16 06:40:1882bool 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 08:17:4098} // namespace
99
mflodmancc3d4422017-08-03 15:27:51100class VideoStreamEncoder::ConfigureEncoderTask : public rtc::QueuedTask {
Pera48ddb72016-09-29 09:48:50101 public:
mflodmancc3d4422017-08-03 15:27:51102 ConfigureEncoderTask(VideoStreamEncoder* video_stream_encoder,
Pera48ddb72016-09-29 09:48:50103 VideoEncoderConfig config,
asapersson5f7226f2016-11-25 12:37:00104 size_t max_data_payload_length,
105 bool nack_enabled)
mflodmancc3d4422017-08-03 15:27:51106 : video_stream_encoder_(video_stream_encoder),
Pera48ddb72016-09-29 09:48:50107 config_(std::move(config)),
asapersson5f7226f2016-11-25 12:37:00108 max_data_payload_length_(max_data_payload_length),
109 nack_enabled_(nack_enabled) {}
Pera48ddb72016-09-29 09:48:50110
111 private:
112 bool Run() override {
mflodmancc3d4422017-08-03 15:27:51113 video_stream_encoder_->ConfigureEncoderOnTaskQueue(
asapersson5f7226f2016-11-25 12:37:00114 std::move(config_), max_data_payload_length_, nack_enabled_);
Pera48ddb72016-09-29 09:48:50115 return true;
116 }
117
mflodmancc3d4422017-08-03 15:27:51118 VideoStreamEncoder* const video_stream_encoder_;
Pera48ddb72016-09-29 09:48:50119 VideoEncoderConfig config_;
120 size_t max_data_payload_length_;
asapersson5f7226f2016-11-25 12:37:00121 bool nack_enabled_;
Pera48ddb72016-09-29 09:48:50122};
123
mflodmancc3d4422017-08-03 15:27:51124class VideoStreamEncoder::EncodeTask : public rtc::QueuedTask {
perkj26091b12016-09-01 08:17:40125 public:
perkjd52063f2016-09-07 13:32:18126 EncodeTask(const VideoFrame& frame,
mflodmancc3d4422017-08-03 15:27:51127 VideoStreamEncoder* video_stream_encoder,
nissee0e3bdf2017-01-18 10:16:20128 int64_t time_when_posted_us,
asapersson6ffb67d2016-09-12 07:10:45129 bool log_stats)
nissedf2ceb82016-12-15 14:29:53130 : frame_(frame),
mflodmancc3d4422017-08-03 15:27:51131 video_stream_encoder_(video_stream_encoder),
nissee0e3bdf2017-01-18 10:16:20132 time_when_posted_us_(time_when_posted_us),
asapersson6ffb67d2016-09-12 07:10:45133 log_stats_(log_stats) {
mflodmancc3d4422017-08-03 15:27:51134 ++video_stream_encoder_->posted_frames_waiting_for_encode_;
perkj26091b12016-09-01 08:17:40135 }
136
137 private:
138 bool Run() override {
mflodmancc3d4422017-08-03 15:27:51139 RTC_DCHECK_RUN_ON(&video_stream_encoder_->encoder_queue_);
140 RTC_DCHECK_GT(
141 video_stream_encoder_->posted_frames_waiting_for_encode_.Value(), 0);
142 video_stream_encoder_->stats_proxy_->OnIncomingFrame(frame_.width(),
143 frame_.height());
144 ++video_stream_encoder_->captured_frame_count_;
145 if (--video_stream_encoder_->posted_frames_waiting_for_encode_ == 0) {
146 video_stream_encoder_->EncodeVideoFrame(frame_, time_when_posted_us_);
perkj26091b12016-09-01 08:17:40147 } else {
148 // There is a newer frame in flight. Do not encode this frame.
149 LOG(LS_VERBOSE)
150 << "Incoming frame dropped due to that the encoder is blocked.";
mflodmancc3d4422017-08-03 15:27:51151 ++video_stream_encoder_->dropped_frame_count_;
asapersson6ffb67d2016-09-12 07:10:45152 }
153 if (log_stats_) {
154 LOG(LS_INFO) << "Number of frames: captured "
mflodmancc3d4422017-08-03 15:27:51155 << video_stream_encoder_->captured_frame_count_
asapersson6ffb67d2016-09-12 07:10:45156 << ", dropped (due to encoder blocked) "
mflodmancc3d4422017-08-03 15:27:51157 << video_stream_encoder_->dropped_frame_count_
158 << ", interval_ms "
asapersson6ffb67d2016-09-12 07:10:45159 << kFrameLogIntervalMs;
mflodmancc3d4422017-08-03 15:27:51160 video_stream_encoder_->captured_frame_count_ = 0;
161 video_stream_encoder_->dropped_frame_count_ = 0;
perkj26091b12016-09-01 08:17:40162 }
163 return true;
164 }
165 VideoFrame frame_;
mflodmancc3d4422017-08-03 15:27:51166 VideoStreamEncoder* const video_stream_encoder_;
nissee0e3bdf2017-01-18 10:16:20167 const int64_t time_when_posted_us_;
asapersson6ffb67d2016-09-12 07:10:45168 const bool log_stats_;
perkj26091b12016-09-01 08:17:40169};
170
perkja49cbd32016-09-16 14:53:41171// VideoSourceProxy is responsible ensuring thread safety between calls to
mflodmancc3d4422017-08-03 15:27:51172// VideoStreamEncoder::SetSource that will happen on libjingle's worker thread
173// when a video capturer is connected to the encoder and the encoder task queue
perkja49cbd32016-09-16 14:53:41174// (encoder_queue_) where the encoder reports its VideoSinkWants.
mflodmancc3d4422017-08-03 15:27:51175class VideoStreamEncoder::VideoSourceProxy {
perkja49cbd32016-09-16 14:53:41176 public:
mflodmancc3d4422017-08-03 15:27:51177 explicit VideoSourceProxy(VideoStreamEncoder* video_stream_encoder)
178 : video_stream_encoder_(video_stream_encoder),
hbos8d609f62017-04-10 14:39:05179 degradation_preference_(
180 VideoSendStream::DegradationPreference::kDegradationDisabled),
perkj803d97f2016-11-01 18:45:46181 source_(nullptr) {}
perkja49cbd32016-09-16 14:53:41182
hbos8d609f62017-04-10 14:39:05183 void SetSource(
184 rtc::VideoSourceInterface<VideoFrame>* source,
185 const VideoSendStream::DegradationPreference& degradation_preference) {
perkj803d97f2016-11-01 18:45:46186 // Called on libjingle's worker thread.
perkja49cbd32016-09-16 14:53:41187 RTC_DCHECK_CALLED_SEQUENTIALLY(&main_checker_);
188 rtc::VideoSourceInterface<VideoFrame>* old_source = nullptr;
perkj803d97f2016-11-01 18:45:46189 rtc::VideoSinkWants wants;
perkja49cbd32016-09-16 14:53:41190 {
191 rtc::CritScope lock(&crit_);
sprangc5d62e22017-04-03 06:53:04192 degradation_preference_ = degradation_preference;
perkja49cbd32016-09-16 14:53:41193 old_source = source_;
194 source_ = source;
sprangfda496a2017-06-15 11:21:07195 wants = GetActiveSinkWantsInternal();
perkja49cbd32016-09-16 14:53:41196 }
197
198 if (old_source != source && old_source != nullptr) {
mflodmancc3d4422017-08-03 15:27:51199 old_source->RemoveSink(video_stream_encoder_);
perkja49cbd32016-09-16 14:53:41200 }
201
202 if (!source) {
203 return;
204 }
205
mflodmancc3d4422017-08-03 15:27:51206 source->AddOrUpdateSink(video_stream_encoder_, wants);
perkja49cbd32016-09-16 14:53:41207 }
208
perkj803d97f2016-11-01 18:45:46209 void SetWantsRotationApplied(bool rotation_applied) {
210 rtc::CritScope lock(&crit_);
211 sink_wants_.rotation_applied = rotation_applied;
sprangc5d62e22017-04-03 06:53:04212 if (source_)
mflodmancc3d4422017-08-03 15:27:51213 source_->AddOrUpdateSink(video_stream_encoder_, sink_wants_);
sprangc5d62e22017-04-03 06:53:04214 }
215
sprangfda496a2017-06-15 11:21:07216 rtc::VideoSinkWants GetActiveSinkWants() {
217 rtc::CritScope lock(&crit_);
218 return GetActiveSinkWantsInternal();
perkj803d97f2016-11-01 18:45:46219 }
220
asaperssonf7e294d2017-06-14 06:25:22221 void ResetPixelFpsCount() {
222 rtc::CritScope lock(&crit_);
223 sink_wants_.max_pixel_count = std::numeric_limits<int>::max();
224 sink_wants_.target_pixel_count.reset();
225 sink_wants_.max_framerate_fps = std::numeric_limits<int>::max();
226 if (source_)
mflodmancc3d4422017-08-03 15:27:51227 source_->AddOrUpdateSink(video_stream_encoder_, sink_wants_);
asaperssonf7e294d2017-06-14 06:25:22228 }
229
asapersson142fcc92017-08-17 15:58:54230 bool RequestResolutionLowerThan(int pixel_count, int min_pixels_per_frame) {
perkj803d97f2016-11-01 18:45:46231 // Called on the encoder task queue.
232 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 07:01:02233 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 08:12:52234 // This can happen since |degradation_preference_| is set on libjingle's
235 // worker thread but the adaptation is done on the encoder task queue.
asaperssond0de2952017-04-21 08:47:31236 return false;
perkj803d97f2016-11-01 18:45:46237 }
asapersson13874762017-06-07 07:01:02238 // The input video frame size will have a resolution less than or equal to
239 // |max_pixel_count| depending on how the source can scale the frame size.
kthelgason5e13d412016-12-01 11:59:51240 const int pixels_wanted = (pixel_count * 3) / 5;
asapersson142fcc92017-08-17 15:58:54241 if (pixels_wanted < min_pixels_per_frame ||
asapersson13874762017-06-07 07:01:02242 pixels_wanted >= sink_wants_.max_pixel_count) {
asaperssond0de2952017-04-21 08:47:31243 return false;
asapersson13874762017-06-07 07:01:02244 }
245 LOG(LS_INFO) << "Scaling down resolution, max pixels: " << pixels_wanted;
sprangc5d62e22017-04-03 06:53:04246 sink_wants_.max_pixel_count = pixels_wanted;
sprang84a37592017-02-10 15:04:27247 sink_wants_.target_pixel_count = rtc::Optional<int>();
mflodmancc3d4422017-08-03 15:27:51248 source_->AddOrUpdateSink(video_stream_encoder_,
249 GetActiveSinkWantsInternal());
asaperssond0de2952017-04-21 08:47:31250 return true;
sprangc5d62e22017-04-03 06:53:04251 }
252
sprangfda496a2017-06-15 11:21:07253 int RequestFramerateLowerThan(int fps) {
sprangc5d62e22017-04-03 06:53:04254 // Called on the encoder task queue.
asapersson13874762017-06-07 07:01:02255 // The input video frame rate will be scaled down to 2/3, rounding down.
sprangfda496a2017-06-15 11:21:07256 int framerate_wanted = (fps * 2) / 3;
257 return RestrictFramerate(framerate_wanted) ? framerate_wanted : -1;
perkj803d97f2016-11-01 18:45:46258 }
259
asapersson13874762017-06-07 07:01:02260 bool RequestHigherResolutionThan(int pixel_count) {
261 // Called on the encoder task queue.
perkj803d97f2016-11-01 18:45:46262 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 07:01:02263 if (!source_ || !IsResolutionScalingEnabled(degradation_preference_)) {
asapersson02465b82017-04-10 08:12:52264 // This can happen since |degradation_preference_| is set on libjingle's
265 // worker thread but the adaptation is done on the encoder task queue.
asapersson13874762017-06-07 07:01:02266 return false;
perkj803d97f2016-11-01 18:45:46267 }
asapersson13874762017-06-07 07:01:02268 int max_pixels_wanted = pixel_count;
269 if (max_pixels_wanted != std::numeric_limits<int>::max())
270 max_pixels_wanted = pixel_count * 4;
sprangc5d62e22017-04-03 06:53:04271
asapersson13874762017-06-07 07:01:02272 if (max_pixels_wanted <= sink_wants_.max_pixel_count)
273 return false;
274
275 sink_wants_.max_pixel_count = max_pixels_wanted;
276 if (max_pixels_wanted == std::numeric_limits<int>::max()) {
sprangc5d62e22017-04-03 06:53:04277 // Remove any constraints.
278 sink_wants_.target_pixel_count.reset();
sprangc5d62e22017-04-03 06:53:04279 } else {
280 // On step down we request at most 3/5 the pixel count of the previous
281 // resolution, so in order to take "one step up" we request a resolution
282 // as close as possible to 5/3 of the current resolution. The actual pixel
283 // count selected depends on the capabilities of the source. In order to
284 // not take a too large step up, we cap the requested pixel count to be at
285 // most four time the current number of pixels.
286 sink_wants_.target_pixel_count =
287 rtc::Optional<int>((pixel_count * 5) / 3);
sprangc5d62e22017-04-03 06:53:04288 }
asapersson13874762017-06-07 07:01:02289 LOG(LS_INFO) << "Scaling up resolution, max pixels: " << max_pixels_wanted;
mflodmancc3d4422017-08-03 15:27:51290 source_->AddOrUpdateSink(video_stream_encoder_,
291 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 07:01:02292 return true;
sprangc5d62e22017-04-03 06:53:04293 }
294
sprangfda496a2017-06-15 11:21:07295 // Request upgrade in framerate. Returns the new requested frame, or -1 if
296 // no change requested. Note that maxint may be returned if limits due to
297 // adaptation requests are removed completely. In that case, consider
298 // |max_framerate_| to be the current limit (assuming the capturer complies).
299 int RequestHigherFramerateThan(int fps) {
asapersson13874762017-06-07 07:01:02300 // Called on the encoder task queue.
301 // The input frame rate will be scaled up to the last step, with rounding.
302 int framerate_wanted = fps;
303 if (fps != std::numeric_limits<int>::max())
304 framerate_wanted = (fps * 3) / 2;
305
sprangfda496a2017-06-15 11:21:07306 return IncreaseFramerate(framerate_wanted) ? framerate_wanted : -1;
asapersson13874762017-06-07 07:01:02307 }
308
309 bool RestrictFramerate(int fps) {
sprangc5d62e22017-04-03 06:53:04310 // Called on the encoder task queue.
311 rtc::CritScope lock(&crit_);
asapersson13874762017-06-07 07:01:02312 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
313 return false;
314
315 const int fps_wanted = std::max(kMinFramerateFps, fps);
316 if (fps_wanted >= sink_wants_.max_framerate_fps)
317 return false;
318
319 LOG(LS_INFO) << "Scaling down framerate: " << fps_wanted;
320 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 15:27:51321 source_->AddOrUpdateSink(video_stream_encoder_,
322 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 07:01:02323 return true;
324 }
325
326 bool IncreaseFramerate(int fps) {
327 // Called on the encoder task queue.
328 rtc::CritScope lock(&crit_);
329 if (!source_ || !IsFramerateScalingEnabled(degradation_preference_))
330 return false;
331
332 const int fps_wanted = std::max(kMinFramerateFps, fps);
333 if (fps_wanted <= sink_wants_.max_framerate_fps)
334 return false;
335
336 LOG(LS_INFO) << "Scaling up framerate: " << fps_wanted;
337 sink_wants_.max_framerate_fps = fps_wanted;
mflodmancc3d4422017-08-03 15:27:51338 source_->AddOrUpdateSink(video_stream_encoder_,
339 GetActiveSinkWantsInternal());
asapersson13874762017-06-07 07:01:02340 return true;
perkj803d97f2016-11-01 18:45:46341 }
342
perkja49cbd32016-09-16 14:53:41343 private:
sprangfda496a2017-06-15 11:21:07344 rtc::VideoSinkWants GetActiveSinkWantsInternal()
danilchapa37de392017-09-09 11:17:22345 RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_) {
sprangfda496a2017-06-15 11:21:07346 rtc::VideoSinkWants wants = sink_wants_;
347 // Clear any constraints from the current sink wants that don't apply to
348 // the used degradation_preference.
349 switch (degradation_preference_) {
350 case VideoSendStream::DegradationPreference::kBalanced:
351 break;
352 case VideoSendStream::DegradationPreference::kMaintainFramerate:
353 wants.max_framerate_fps = std::numeric_limits<int>::max();
354 break;
355 case VideoSendStream::DegradationPreference::kMaintainResolution:
356 wants.max_pixel_count = std::numeric_limits<int>::max();
357 wants.target_pixel_count.reset();
358 break;
359 case VideoSendStream::DegradationPreference::kDegradationDisabled:
360 wants.max_pixel_count = std::numeric_limits<int>::max();
361 wants.target_pixel_count.reset();
362 wants.max_framerate_fps = std::numeric_limits<int>::max();
363 }
364 return wants;
365 }
366
perkja49cbd32016-09-16 14:53:41367 rtc::CriticalSection crit_;
368 rtc::SequencedTaskChecker main_checker_;
mflodmancc3d4422017-08-03 15:27:51369 VideoStreamEncoder* const video_stream_encoder_;
danilchapa37de392017-09-09 11:17:22370 rtc::VideoSinkWants sink_wants_ RTC_GUARDED_BY(&crit_);
hbos8d609f62017-04-10 14:39:05371 VideoSendStream::DegradationPreference degradation_preference_
danilchapa37de392017-09-09 11:17:22372 RTC_GUARDED_BY(&crit_);
373 rtc::VideoSourceInterface<VideoFrame>* source_ RTC_GUARDED_BY(&crit_);
perkja49cbd32016-09-16 14:53:41374
375 RTC_DISALLOW_COPY_AND_ASSIGN(VideoSourceProxy);
376};
377
mflodmancc3d4422017-08-03 15:27:51378VideoStreamEncoder::VideoStreamEncoder(uint32_t number_of_cores,
Peter Boström7083e112015-09-22 14:28:51379 SendStatisticsProxy* stats_proxy,
perkj26091b12016-09-01 08:17:40380 const VideoSendStream::Config::EncoderSettings& settings,
381 rtc::VideoSinkInterface<VideoFrame>* pre_encode_callback,
sprangfda496a2017-06-15 11:21:07382 EncodedFrameObserver* encoder_timing,
383 std::unique_ptr<OveruseFrameDetector> overuse_detector)
perkj26091b12016-09-01 08:17:40384 : shutdown_event_(true /* manual_reset */, false),
385 number_of_cores_(number_of_cores),
kthelgason2bc68642017-02-07 15:02:22386 initial_rampup_(0),
perkja49cbd32016-09-16 14:53:41387 source_proxy_(new VideoSourceProxy(this)),
Pera48ddb72016-09-29 09:48:50388 sink_(nullptr),
perkj26091b12016-09-01 08:17:40389 settings_(settings),
kthelgason1cdddc92017-08-24 10:52:48390 codec_type_(PayloadStringToCodecType(settings.payload_name)),
perkjf5b2e512016-07-05 15:34:04391 video_sender_(Clock::GetRealTimeClock(), this, this),
sprangfda496a2017-06-15 11:21:07392 overuse_detector_(
393 overuse_detector.get()
394 ? overuse_detector.release()
395 : new OveruseFrameDetector(
396 GetCpuOveruseOptions(settings.full_overuse_time),
397 this,
398 encoder_timing,
399 stats_proxy)),
Peter Boström7083e112015-09-22 14:28:51400 stats_proxy_(stats_proxy),
perkj26091b12016-09-01 08:17:40401 pre_encode_callback_(pre_encode_callback),
402 module_process_thread_(nullptr),
sprangfda496a2017-06-15 11:21:07403 max_framerate_(-1),
perkjfa10b552016-10-03 06:45:26404 pending_encoder_reconfiguration_(false),
perkj26091b12016-09-01 08:17:40405 encoder_start_bitrate_bps_(0),
Pera48ddb72016-09-29 09:48:50406 max_data_payload_length_(0),
asapersson5f7226f2016-11-25 12:37:00407 nack_enabled_(false),
pbos@webrtc.org143451d2015-03-18 14:40:03408 last_observed_bitrate_bps_(0),
stefan@webrtc.org792f1a12015-03-04 12:24:26409 encoder_paused_and_dropped_frame_(false),
perkj26091b12016-09-01 08:17:40410 clock_(Clock::GetRealTimeClock()),
hbos8d609f62017-04-10 14:39:05411 degradation_preference_(
412 VideoSendStream::DegradationPreference::kDegradationDisabled),
perkj26091b12016-09-01 08:17:40413 last_captured_timestamp_(0),
414 delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() -
415 clock_->TimeInMilliseconds()),
asapersson6ffb67d2016-09-12 07:10:45416 last_frame_log_ms_(clock_->TimeInMilliseconds()),
417 captured_frame_count_(0),
418 dropped_frame_count_(0),
sprang1a646ee2016-12-01 14:34:11419 bitrate_observer_(nullptr),
perkj26091b12016-09-01 08:17:40420 encoder_queue_("EncoderQueue") {
sprang552c7c72017-02-13 12:41:45421 RTC_DCHECK(stats_proxy);
perkj803d97f2016-11-01 18:45:46422 encoder_queue_.PostTask([this] {
perkj26091b12016-09-01 08:17:40423 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 11:21:07424 overuse_detector_->StartCheckForOveruse();
perkj26091b12016-09-01 08:17:40425 video_sender_.RegisterExternalEncoder(
426 settings_.encoder, settings_.payload_type, settings_.internal_source);
427 });
mflodman@webrtc.org02270cd2015-02-06 13:10:19428}
429
mflodmancc3d4422017-08-03 15:27:51430VideoStreamEncoder::~VideoStreamEncoder() {
perkja49cbd32016-09-16 14:53:41431 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 08:17:40432 RTC_DCHECK(shutdown_event_.Wait(0))
433 << "Must call ::Stop() before destruction.";
434}
435
sprangfda496a2017-06-15 11:21:07436// TODO(pbos): Lower these thresholds (to closer to 100%) when we handle
437// pipelining encoders better (multiple input frames before something comes
438// out). This should effectively turn off CPU adaptations for systems that
439// remotely cope with the load right now.
mflodmancc3d4422017-08-03 15:27:51440CpuOveruseOptions VideoStreamEncoder::GetCpuOveruseOptions(
441 bool full_overuse_time) {
sprangfda496a2017-06-15 11:21:07442 CpuOveruseOptions options;
443 if (full_overuse_time) {
444 options.low_encode_usage_threshold_percent = 150;
445 options.high_encode_usage_threshold_percent = 200;
446 }
447 return options;
448}
449
mflodmancc3d4422017-08-03 15:27:51450void VideoStreamEncoder::Stop() {
perkja49cbd32016-09-16 14:53:41451 RTC_DCHECK_RUN_ON(&thread_checker_);
hbos8d609f62017-04-10 14:39:05452 source_proxy_->SetSource(nullptr, VideoSendStream::DegradationPreference());
perkja49cbd32016-09-16 14:53:41453 encoder_queue_.PostTask([this] {
454 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 11:21:07455 overuse_detector_->StopCheckForOveruse();
Erik Språng08127a92016-11-16 15:41:30456 rate_allocator_.reset();
sprang1a646ee2016-12-01 14:34:11457 bitrate_observer_ = nullptr;
perkja49cbd32016-09-16 14:53:41458 video_sender_.RegisterExternalEncoder(nullptr, settings_.payload_type,
459 false);
kthelgason876222f2016-11-29 09:44:11460 quality_scaler_ = nullptr;
perkja49cbd32016-09-16 14:53:41461 shutdown_event_.Set();
462 });
463
464 shutdown_event_.Wait(rtc::Event::kForever);
perkj26091b12016-09-01 08:17:40465}
466
mflodmancc3d4422017-08-03 15:27:51467void VideoStreamEncoder::RegisterProcessThread(
468 ProcessThread* module_process_thread) {
perkja49cbd32016-09-16 14:53:41469 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj26091b12016-09-01 08:17:40470 RTC_DCHECK(!module_process_thread_);
471 module_process_thread_ = module_process_thread;
tommidea489f2017-03-03 11:20:24472 module_process_thread_->RegisterModule(&video_sender_, RTC_FROM_HERE);
perkj26091b12016-09-01 08:17:40473 module_process_thread_checker_.DetachFromThread();
474}
475
mflodmancc3d4422017-08-03 15:27:51476void VideoStreamEncoder::DeRegisterProcessThread() {
perkja49cbd32016-09-16 14:53:41477 RTC_DCHECK_RUN_ON(&thread_checker_);
Peter Boströmcd5c25c2016-04-21 14:48:08478 module_process_thread_->DeRegisterModule(&video_sender_);
asapersson@webrtc.org96dc6852014-11-03 14:40:38479}
480
mflodmancc3d4422017-08-03 15:27:51481void VideoStreamEncoder::SetBitrateObserver(
sprang1a646ee2016-12-01 14:34:11482 VideoBitrateAllocationObserver* bitrate_observer) {
483 RTC_DCHECK_RUN_ON(&thread_checker_);
484 encoder_queue_.PostTask([this, bitrate_observer] {
485 RTC_DCHECK_RUN_ON(&encoder_queue_);
486 RTC_DCHECK(!bitrate_observer_);
487 bitrate_observer_ = bitrate_observer;
488 });
489}
490
mflodmancc3d4422017-08-03 15:27:51491void VideoStreamEncoder::SetSource(
perkj803d97f2016-11-01 18:45:46492 rtc::VideoSourceInterface<VideoFrame>* source,
asapersson09f05612017-05-16 06:40:18493 const VideoSendStream::DegradationPreference& degradation_preference) {
perkja49cbd32016-09-16 14:53:41494 RTC_DCHECK_RUN_ON(&thread_checker_);
perkj803d97f2016-11-01 18:45:46495 source_proxy_->SetSource(source, degradation_preference);
496 encoder_queue_.PostTask([this, degradation_preference] {
497 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-03 06:53:04498 if (degradation_preference_ != degradation_preference) {
499 // Reset adaptation state, so that we're not tricked into thinking there's
500 // an already pending request of the same type.
501 last_adaptation_request_.reset();
asaperssonf7e294d2017-06-14 06:25:22502 if (degradation_preference ==
503 VideoSendStream::DegradationPreference::kBalanced ||
504 degradation_preference_ ==
505 VideoSendStream::DegradationPreference::kBalanced) {
506 // TODO(asapersson): Consider removing |adapt_counters_| map and use one
507 // AdaptCounter for all modes.
508 source_proxy_->ResetPixelFpsCount();
509 adapt_counters_.clear();
510 }
sprangc5d62e22017-04-03 06:53:04511 }
sprangb1ca0732017-02-01 16:38:12512 degradation_preference_ = degradation_preference;
asapersson91914e22017-06-01 07:34:08513 bool allow_scaling = IsResolutionScalingEnabled(degradation_preference_);
sprangc5d62e22017-04-03 06:53:04514 initial_rampup_ = allow_scaling ? 0 : kMaxInitialFramedrop;
kthelgason2bc68642017-02-07 15:02:22515 ConfigureQualityScaler();
sprangfda496a2017-06-15 11:21:07516 if (!IsFramerateScalingEnabled(degradation_preference) &&
517 max_framerate_ != -1) {
518 // If frame rate scaling is no longer allowed, remove any potential
519 // allowance for longer frame intervals.
520 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
521 }
perkj803d97f2016-11-01 18:45:46522 });
perkja49cbd32016-09-16 14:53:41523}
524
mflodmancc3d4422017-08-03 15:27:51525void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) {
perkj803d97f2016-11-01 18:45:46526 source_proxy_->SetWantsRotationApplied(rotation_applied);
perkj26091b12016-09-01 08:17:40527 encoder_queue_.PostTask([this, sink] {
528 RTC_DCHECK_RUN_ON(&encoder_queue_);
529 sink_ = sink;
530 });
mflodman@webrtc.org84d17832011-12-01 17:02:23531}
532
mflodmancc3d4422017-08-03 15:27:51533void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) {
perkj26091b12016-09-01 08:17:40534 encoder_queue_.PostTask([this, start_bitrate_bps] {
535 RTC_DCHECK_RUN_ON(&encoder_queue_);
536 encoder_start_bitrate_bps_ = start_bitrate_bps;
537 });
mflodman@webrtc.org84d17832011-12-01 17:02:23538}
Peter Boström00b9d212016-05-19 14:59:03539
mflodmancc3d4422017-08-03 15:27:51540void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config,
541 size_t max_data_payload_length,
542 bool nack_enabled) {
Pera48ddb72016-09-29 09:48:50543 encoder_queue_.PostTask(
544 std::unique_ptr<rtc::QueuedTask>(new ConfigureEncoderTask(
asapersson5f7226f2016-11-25 12:37:00545 this, std::move(config), max_data_payload_length, nack_enabled)));
perkj26091b12016-09-01 08:17:40546}
547
mflodmancc3d4422017-08-03 15:27:51548void VideoStreamEncoder::ConfigureEncoderOnTaskQueue(
549 VideoEncoderConfig config,
550 size_t max_data_payload_length,
551 bool nack_enabled) {
perkj26091b12016-09-01 08:17:40552 RTC_DCHECK_RUN_ON(&encoder_queue_);
perkj26091b12016-09-01 08:17:40553 RTC_DCHECK(sink_);
perkjfa10b552016-10-03 06:45:26554 LOG(LS_INFO) << "ConfigureEncoder requested.";
Pera48ddb72016-09-29 09:48:50555
556 max_data_payload_length_ = max_data_payload_length;
asapersson5f7226f2016-11-25 12:37:00557 nack_enabled_ = nack_enabled;
Pera48ddb72016-09-29 09:48:50558 encoder_config_ = std::move(config);
perkjfa10b552016-10-03 06:45:26559 pending_encoder_reconfiguration_ = true;
Pera48ddb72016-09-29 09:48:50560
perkjfa10b552016-10-03 06:45:26561 // Reconfigure the encoder now if the encoder has an internal source or
Per21d45d22016-10-30 20:37:57562 // if the frame resolution is known. Otherwise, the reconfiguration is
563 // deferred until the next frame to minimize the number of reconfigurations.
564 // The codec configuration depends on incoming video frame size.
565 if (last_frame_info_) {
566 ReconfigureEncoder();
567 } else if (settings_.internal_source) {
brandtra3241662017-05-03 11:55:51568 last_frame_info_ =
569 rtc::Optional<VideoFrameInfo>(VideoFrameInfo(176, 144, false));
perkjfa10b552016-10-03 06:45:26570 ReconfigureEncoder();
571 }
572}
perkj26091b12016-09-01 08:17:40573
mflodmancc3d4422017-08-03 15:27:51574void VideoStreamEncoder::ReconfigureEncoder() {
perkjfa10b552016-10-03 06:45:26575 RTC_DCHECK_RUN_ON(&encoder_queue_);
576 RTC_DCHECK(pending_encoder_reconfiguration_);
577 std::vector<VideoStream> streams =
578 encoder_config_.video_stream_factory->CreateEncoderStreams(
579 last_frame_info_->width, last_frame_info_->height, encoder_config_);
perkj26091b12016-09-01 08:17:40580
ilnik6b826ef2017-06-16 13:53:48581 // TODO(ilnik): If configured resolution is significantly less than provided,
582 // e.g. because there are not enough SSRCs for all simulcast streams,
583 // signal new resolutions via SinkWants to video source.
584
585 // Stream dimensions may be not equal to given because of a simulcast
586 // restrictions.
587 int highest_stream_width = static_cast<int>(streams.back().width);
588 int highest_stream_height = static_cast<int>(streams.back().height);
589 // Dimension may be reduced to be, e.g. divisible by 4.
590 RTC_CHECK_GE(last_frame_info_->width, highest_stream_width);
591 RTC_CHECK_GE(last_frame_info_->height, highest_stream_height);
592 crop_width_ = last_frame_info_->width - highest_stream_width;
593 crop_height_ = last_frame_info_->height - highest_stream_height;
594
Erik Språng08127a92016-11-16 15:41:30595 VideoCodec codec;
596 if (!VideoCodecInitializer::SetupCodec(encoder_config_, settings_, streams,
asapersson5f7226f2016-11-25 12:37:00597 nack_enabled_, &codec,
598 &rate_allocator_)) {
Erik Språng08127a92016-11-16 15:41:30599 LOG(LS_ERROR) << "Failed to create encoder configuration.";
600 }
perkjfa10b552016-10-03 06:45:26601
602 codec.startBitrate =
603 std::max(encoder_start_bitrate_bps_ / 1000, codec.minBitrate);
604 codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate);
605 codec.expect_encode_from_texture = last_frame_info_->is_texture;
sprangfda496a2017-06-15 11:21:07606 max_framerate_ = codec.maxFramerate;
607 RTC_DCHECK_LE(max_framerate_, kMaxFramerateFps);
Stefan Holmere5904162015-03-26 10:11:06608
Peter Boströmcd5c25c2016-04-21 14:48:08609 bool success = video_sender_.RegisterSendCodec(
perkjfa10b552016-10-03 06:45:26610 &codec, number_of_cores_,
611 static_cast<uint32_t>(max_data_payload_length_)) == VCM_OK;
Peter Boström905f8e72016-03-02 15:59:56612 if (!success) {
613 LOG(LS_ERROR) << "Failed to configure encoder.";
sprangfe627f32017-03-29 15:24:59614 rate_allocator_.reset();
mflodman@webrtc.org84d17832011-12-01 17:02:23615 }
Peter Boström905f8e72016-03-02 15:59:56616
ilnik35b7de42017-03-15 11:24:21617 video_sender_.UpdateChannelParemeters(rate_allocator_.get(),
618 bitrate_observer_);
619
sprangfda496a2017-06-15 11:21:07620 // Get the current actual framerate, as measured by the stats proxy. This is
621 // used to get the correct bitrate layer allocation.
622 int current_framerate = stats_proxy_->GetSendFrameRate();
623 if (current_framerate == 0)
624 current_framerate = codec.maxFramerate;
sprang552c7c72017-02-13 12:41:45625 stats_proxy_->OnEncoderReconfigured(
sprangfda496a2017-06-15 11:21:07626 encoder_config_,
627 rate_allocator_.get()
628 ? rate_allocator_->GetPreferredBitrateBps(current_framerate)
629 : codec.maxBitrate);
Per512ecb32016-09-23 13:52:06630
perkjfa10b552016-10-03 06:45:26631 pending_encoder_reconfiguration_ = false;
Erik Språng08127a92016-11-16 15:41:30632
Pera48ddb72016-09-29 09:48:50633 sink_->OnEncoderConfigurationChanged(
perkjfa10b552016-10-03 06:45:26634 std::move(streams), encoder_config_.min_transmit_bitrate_bps);
kthelgason876222f2016-11-29 09:44:11635
sprangfda496a2017-06-15 11:21:07636 // Get the current target framerate, ie the maximum framerate as specified by
637 // the current codec configuration, or any limit imposed by cpu adaption in
638 // maintain-resolution or balanced mode. This is used to make sure overuse
639 // detection doesn't needlessly trigger in low and/or variable framerate
640 // scenarios.
641 int target_framerate = std::min(
642 max_framerate_, source_proxy_->GetActiveSinkWants().max_framerate_fps);
643 overuse_detector_->OnTargetFramerateUpdated(target_framerate);
644
kthelgason2bc68642017-02-07 15:02:22645 ConfigureQualityScaler();
646}
647
mflodmancc3d4422017-08-03 15:27:51648void VideoStreamEncoder::ConfigureQualityScaler() {
kthelgason2bc68642017-02-07 15:02:22649 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 09:44:11650 const auto scaling_settings = settings_.encoder->GetScalingSettings();
asapersson36e9eb42017-03-31 12:29:12651 const bool quality_scaling_allowed =
asapersson91914e22017-06-01 07:34:08652 IsResolutionScalingEnabled(degradation_preference_) &&
653 scaling_settings.enabled;
kthelgason3af6cc02017-03-22 07:25:28654
asapersson36e9eb42017-03-31 12:29:12655 if (quality_scaling_allowed) {
asapersson09f05612017-05-16 06:40:18656 if (quality_scaler_.get() == nullptr) {
657 // Quality scaler has not already been configured.
658 // Drop frames and scale down until desired quality is achieved.
659 if (scaling_settings.thresholds) {
660 quality_scaler_.reset(
661 new QualityScaler(this, *(scaling_settings.thresholds)));
662 } else {
663 quality_scaler_.reset(new QualityScaler(this, codec_type_));
664 }
kthelgason876222f2016-11-29 09:44:11665 }
666 } else {
667 quality_scaler_.reset(nullptr);
kthelgasonad9010c2017-02-14 08:46:51668 initial_rampup_ = kMaxInitialFramedrop;
kthelgason876222f2016-11-29 09:44:11669 }
asapersson09f05612017-05-16 06:40:18670
671 stats_proxy_->SetAdaptationStats(GetActiveCounts(kCpu),
672 GetActiveCounts(kQuality));
mflodman@webrtc.org84d17832011-12-01 17:02:23673}
674
mflodmancc3d4422017-08-03 15:27:51675void VideoStreamEncoder::OnFrame(const VideoFrame& video_frame) {
perkj26091b12016-09-01 08:17:40676 RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_);
perkj26091b12016-09-01 08:17:40677 VideoFrame incoming_frame = video_frame;
678
679 // Local time in webrtc time base.
ilnik04f4d122017-06-19 14:18:55680 int64_t current_time_us = clock_->TimeInMicroseconds();
681 int64_t current_time_ms = current_time_us / rtc::kNumMicrosecsPerMillisec;
682 // In some cases, e.g., when the frame from decoder is fed to encoder,
683 // the timestamp may be set to the future. As the encoding pipeline assumes
684 // capture time to be less than present time, we should reset the capture
685 // timestamps here. Otherwise there may be issues with RTP send stream.
686 if (incoming_frame.timestamp_us() > current_time_us)
687 incoming_frame.set_timestamp_us(current_time_us);
perkj26091b12016-09-01 08:17:40688
689 // Capture time may come from clock with an offset and drift from clock_.
690 int64_t capture_ntp_time_ms;
nisse891419f2017-01-12 18:02:22691 if (video_frame.ntp_time_ms() > 0) {
perkj26091b12016-09-01 08:17:40692 capture_ntp_time_ms = video_frame.ntp_time_ms();
693 } else if (video_frame.render_time_ms() != 0) {
694 capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_;
695 } else {
nisse1c0dea82017-01-30 10:43:18696 capture_ntp_time_ms = current_time_ms + delta_ntp_internal_ms_;
perkj26091b12016-09-01 08:17:40697 }
698 incoming_frame.set_ntp_time_ms(capture_ntp_time_ms);
699
700 // Convert NTP time, in ms, to RTP timestamp.
701 const int kMsToRtpTimestamp = 90;
702 incoming_frame.set_timestamp(
703 kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms()));
704
705 if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) {
706 // We don't allow the same capture time for two frames, drop this one.
707 LOG(LS_WARNING) << "Same/old NTP timestamp ("
708 << incoming_frame.ntp_time_ms()
709 << " <= " << last_captured_timestamp_
710 << ") for incoming frame. Dropping.";
711 return;
712 }
713
asapersson6ffb67d2016-09-12 07:10:45714 bool log_stats = false;
nisse1c0dea82017-01-30 10:43:18715 if (current_time_ms - last_frame_log_ms_ > kFrameLogIntervalMs) {
716 last_frame_log_ms_ = current_time_ms;
asapersson6ffb67d2016-09-12 07:10:45717 log_stats = true;
718 }
719
perkj26091b12016-09-01 08:17:40720 last_captured_timestamp_ = incoming_frame.ntp_time_ms();
asapersson6ffb67d2016-09-12 07:10:45721 encoder_queue_.PostTask(std::unique_ptr<rtc::QueuedTask>(new EncodeTask(
nissee0e3bdf2017-01-18 10:16:20722 incoming_frame, this, rtc::TimeMicros(), log_stats)));
perkj26091b12016-09-01 08:17:40723}
724
mflodmancc3d4422017-08-03 15:27:51725bool VideoStreamEncoder::EncoderPaused() const {
perkj26091b12016-09-01 08:17:40726 RTC_DCHECK_RUN_ON(&encoder_queue_);
pwestin@webrtc.org91563e42013-04-25 22:20:08727 // Pause video if paused by caller or as long as the network is down or the
728 // pacer queue has grown too large in buffered mode.
perkj57c21f92016-06-17 14:27:16729 // If the pacer queue has grown too large or the network is down,
perkjfea93092016-05-14 07:58:48730 // last_observed_bitrate_bps_ will be 0.
perkj26091b12016-09-01 08:17:40731 return last_observed_bitrate_bps_ == 0;
stefan@webrtc.orgbfacda62013-03-27 16:36:01732}
733
mflodmancc3d4422017-08-03 15:27:51734void VideoStreamEncoder::TraceFrameDropStart() {
perkj26091b12016-09-01 08:17:40735 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16736 // Start trace event only on the first frame after encoder is paused.
737 if (!encoder_paused_and_dropped_frame_) {
738 TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this);
739 }
740 encoder_paused_and_dropped_frame_ = true;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16741}
742
mflodmancc3d4422017-08-03 15:27:51743void VideoStreamEncoder::TraceFrameDropEnd() {
perkj26091b12016-09-01 08:17:40744 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16745 // End trace event on first frame after encoder resumes, if frame was dropped.
746 if (encoder_paused_and_dropped_frame_) {
747 TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this);
748 }
749 encoder_paused_and_dropped_frame_ = false;
750}
751
mflodmancc3d4422017-08-03 15:27:51752void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame,
753 int64_t time_when_posted_us) {
perkj26091b12016-09-01 08:17:40754 RTC_DCHECK_RUN_ON(&encoder_queue_);
kthelgason876222f2016-11-29 09:44:11755
perkj26091b12016-09-01 08:17:40756 if (pre_encode_callback_)
757 pre_encode_callback_->OnFrame(video_frame);
758
Per21d45d22016-10-30 20:37:57759 if (!last_frame_info_ || video_frame.width() != last_frame_info_->width ||
perkjfa10b552016-10-03 06:45:26760 video_frame.height() != last_frame_info_->height ||
perkjfa10b552016-10-03 06:45:26761 video_frame.is_texture() != last_frame_info_->is_texture) {
762 pending_encoder_reconfiguration_ = true;
brandtra3241662017-05-03 11:55:51763 last_frame_info_ = rtc::Optional<VideoFrameInfo>(VideoFrameInfo(
764 video_frame.width(), video_frame.height(), video_frame.is_texture()));
perkjfa10b552016-10-03 06:45:26765 LOG(LS_INFO) << "Video frame parameters changed: dimensions="
766 << last_frame_info_->width << "x" << last_frame_info_->height
brandtra3241662017-05-03 11:55:51767 << ", texture=" << last_frame_info_->is_texture << ".";
perkjfa10b552016-10-03 06:45:26768 }
769
kthelgason2bc68642017-02-07 15:02:22770 if (initial_rampup_ < kMaxInitialFramedrop &&
771 video_frame.size() >
772 MaximumFrameSizeForBitrate(encoder_start_bitrate_bps_ / 1000)) {
773 LOG(LS_INFO) << "Dropping frame. Too large for target bitrate.";
774 AdaptDown(kQuality);
775 ++initial_rampup_;
776 return;
777 }
778 initial_rampup_ = kMaxInitialFramedrop;
779
sprang57c2fff2017-01-16 14:24:02780 int64_t now_ms = clock_->TimeInMilliseconds();
perkjfa10b552016-10-03 06:45:26781 if (pending_encoder_reconfiguration_) {
782 ReconfigureEncoder();
sprang4847ae62017-06-27 14:06:52783 last_parameters_update_ms_.emplace(now_ms);
sprang57c2fff2017-01-16 14:24:02784 } 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 14:06:52789 last_parameters_update_ms_.emplace(now_ms);
perkjfa10b552016-10-03 06:45:26790 }
791
perkj26091b12016-09-01 08:17:40792 if (EncoderPaused()) {
793 TraceFrameDropStart();
794 return;
mflodman@webrtc.org84d17832011-12-01 17:02:23795 }
perkj26091b12016-09-01 08:17:40796 TraceFrameDropEnd();
niklase@google.com470e71d2011-07-07 08:21:25797
ilnik6b826ef2017-06-16 13:53:48798 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 12:07:41821 TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(),
hclam@chromium.org1a7b9b92013-07-08 21:31:18822 "Encode");
pbos@webrtc.orgfe1ef932013-10-21 10:34:43823
ilnik6b826ef2017-06-16 13:53:48824 overuse_detector_->FrameCaptured(out_frame, time_when_posted_us);
perkjd52063f2016-09-07 13:32:18825
ilnik6b826ef2017-06-16 13:53:48826 video_sender_.AddVideoFrame(out_frame, nullptr);
niklase@google.com470e71d2011-07-07 08:21:25827}
niklase@google.com470e71d2011-07-07 08:21:25828
mflodmancc3d4422017-08-03 15:27:51829void VideoStreamEncoder::SendKeyFrame() {
perkj26091b12016-09-01 08:17:40830 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 14:48:08835 video_sender_.IntraFrameRequest(0);
stefan@webrtc.org07b45a52012-02-02 08:37:48836}
837
mflodmancc3d4422017-08-03 15:27:51838EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage(
Sergey Ulanov525df3f2016-08-03 00:46:41839 const EncodedImage& encoded_image,
840 const CodecSpecificInfo* codec_specific_info,
841 const RTPFragmentationHeader* fragmentation) {
perkj26091b12016-09-01 08:17:40842 // 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 12:41:45845 stats_proxy_->OnSendEncodedImage(encoded_image, codec_specific_info);
sprang3911c262016-04-15 08:24:14846
Sergey Ulanov525df3f2016-08-03 00:46:41847 EncodedImageCallback::Result result =
848 sink_->OnEncodedImage(encoded_image, codec_specific_info, fragmentation);
perkjbc75d972016-05-02 13:31:25849
nissee0e3bdf2017-01-18 10:16:20850 int64_t time_sent_us = rtc::TimeMicros();
perkjd52063f2016-09-07 13:32:18851 uint32_t timestamp = encoded_image._timeStamp;
kthelgason876222f2016-11-29 09:44:11852 const int qp = encoded_image.qp_;
nissee0e3bdf2017-01-18 10:16:20853 encoder_queue_.PostTask([this, timestamp, time_sent_us, qp] {
perkjd52063f2016-09-07 13:32:18854 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangfda496a2017-06-15 11:21:07855 overuse_detector_->FrameSent(timestamp, time_sent_us);
sprang84a37592017-02-10 15:04:27856 if (quality_scaler_ && qp >= 0)
kthelgason876222f2016-11-29 09:44:11857 quality_scaler_->ReportQP(qp);
perkjd52063f2016-09-07 13:32:18858 });
perkj803d97f2016-11-01 18:45:46859
Sergey Ulanov525df3f2016-08-03 00:46:41860 return result;
Peter Boströmb7d9a972015-12-18 15:01:11861}
862
mflodmancc3d4422017-08-03 15:27:51863void VideoStreamEncoder::OnDroppedFrame() {
kthelgason876222f2016-11-29 09:44:11864 encoder_queue_.PostTask([this] {
865 RTC_DCHECK_RUN_ON(&encoder_queue_);
866 if (quality_scaler_)
867 quality_scaler_->ReportDroppedFrame();
868 });
869}
870
mflodmancc3d4422017-08-03 15:27:51871void VideoStreamEncoder::SendStatistics(uint32_t bit_rate,
872 uint32_t frame_rate) {
perkj26091b12016-09-01 08:17:40873 RTC_DCHECK(module_process_thread_checker_.CalledOnValidThread());
sprang552c7c72017-02-13 12:41:45874 stats_proxy_->OnEncoderStatsUpdate(frame_rate, bit_rate);
niklase@google.com470e71d2011-07-07 08:21:25875}
876
mflodmancc3d4422017-08-03 15:27:51877void VideoStreamEncoder::OnReceivedIntraFrameRequest(size_t stream_index) {
perkj26091b12016-09-01 08:17:40878 if (!encoder_queue_.IsCurrent()) {
879 encoder_queue_.PostTask(
880 [this, stream_index] { OnReceivedIntraFrameRequest(stream_index); });
881 return;
882 }
883 RTC_DCHECK_RUN_ON(&encoder_queue_);
mflodman@webrtc.org84d17832011-12-01 17:02:23884 // Key frame request from remote side, signal to VCM.
justinlin@chromium.org7bfb3a32013-05-13 22:59:00885 TRACE_EVENT0("webrtc", "OnKeyFrameRequest");
perkj600246e2016-05-04 18:26:51886 video_sender_.IntraFrameRequest(stream_index);
mflodman@webrtc.orgaca26292012-10-05 16:17:41887}
888
mflodmancc3d4422017-08-03 15:27:51889void VideoStreamEncoder::OnBitrateUpdated(uint32_t bitrate_bps,
890 uint8_t fraction_lost,
891 int64_t round_trip_time_ms) {
perkj26091b12016-09-01 08:17:40892 if (!encoder_queue_.IsCurrent()) {
893 encoder_queue_.PostTask(
894 [this, bitrate_bps, fraction_lost, round_trip_time_ms] {
895 OnBitrateUpdated(bitrate_bps, fraction_lost, round_trip_time_ms);
896 });
897 return;
898 }
899 RTC_DCHECK_RUN_ON(&encoder_queue_);
900 RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active.";
901
perkjec81bcd2016-05-11 13:01:13902 LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << bitrate_bps
mflodman8602a3d2015-05-20 22:54:42903 << " packet loss " << static_cast<int>(fraction_lost)
mflodman@webrtc.org5574dac2014-04-07 10:56:31904 << " rtt " << round_trip_time_ms;
perkj26091b12016-09-01 08:17:40905
Peter Boströmcd5c25c2016-04-21 14:48:08906 video_sender_.SetChannelParameters(bitrate_bps, fraction_lost,
sprang1a646ee2016-12-01 14:34:11907 round_trip_time_ms, rate_allocator_.get(),
908 bitrate_observer_);
perkj26091b12016-09-01 08:17:40909
910 encoder_start_bitrate_bps_ =
911 bitrate_bps != 0 ? bitrate_bps : encoder_start_bitrate_bps_;
mflodman101f2502016-06-09 15:21:19912 bool video_is_suspended = bitrate_bps == 0;
Erik Språng08127a92016-11-16 15:41:30913 bool video_suspension_changed = video_is_suspended != EncoderPaused();
perkj26091b12016-09-01 08:17:40914 last_observed_bitrate_bps_ = bitrate_bps;
Peter Boströmd153a372015-11-10 15:27:12915
sprang552c7c72017-02-13 12:41:45916 if (video_suspension_changed) {
mflodman522739c2016-06-22 15:42:30917 LOG(LS_INFO) << "Video suspend state changed to: "
918 << (video_is_suspended ? "suspended" : "not suspended");
Peter Boström7083e112015-09-22 14:28:51919 stats_proxy_->OnSuspendChange(video_is_suspended);
mflodman101f2502016-06-09 15:21:19920 }
niklase@google.com470e71d2011-07-07 08:21:25921}
922
mflodmancc3d4422017-08-03 15:27:51923void VideoStreamEncoder::AdaptDown(AdaptReason reason) {
perkjd52063f2016-09-07 13:32:18924 RTC_DCHECK_RUN_ON(&encoder_queue_);
sprangc5d62e22017-04-03 06:53:04925 AdaptationRequest adaptation_request = {
926 last_frame_info_->pixel_count(),
927 stats_proxy_->GetStats().input_frame_rate,
928 AdaptationRequest::Mode::kAdaptDown};
asapersson09f05612017-05-16 06:40:18929
sprangc5d62e22017-04-03 06:53:04930 bool downgrade_requested =
931 last_adaptation_request_ &&
932 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptDown;
933
sprangc5d62e22017-04-03 06:53:04934 switch (degradation_preference_) {
hbos8d609f62017-04-10 14:39:05935 case VideoSendStream::DegradationPreference::kBalanced:
asaperssonf7e294d2017-06-14 06:25:22936 break;
hbos8d609f62017-04-10 14:39:05937 case VideoSendStream::DegradationPreference::kMaintainFramerate:
sprangc5d62e22017-04-03 06:53:04938 if (downgrade_requested &&
939 adaptation_request.input_pixel_count_ >=
940 last_adaptation_request_->input_pixel_count_) {
941 // Don't request lower resolution if the current resolution is not
942 // lower than the last time we asked for the resolution to be lowered.
943 return;
944 }
945 break;
hbos8d609f62017-04-10 14:39:05946 case VideoSendStream::DegradationPreference::kMaintainResolution:
sprangc5d62e22017-04-03 06:53:04947 if (adaptation_request.framerate_fps_ <= 0 ||
948 (downgrade_requested &&
949 adaptation_request.framerate_fps_ < kMinFramerateFps)) {
950 // If no input fps estimate available, can't determine how to scale down
951 // framerate. Otherwise, don't request lower framerate if we don't have
952 // a valid frame rate. Since framerate, unlike resolution, is a measure
953 // we have to estimate, and can fluctuate naturally over time, don't
954 // make the same kind of limitations as for resolution, but trust the
955 // overuse detector to not trigger too often.
956 return;
957 }
958 break;
hbos8d609f62017-04-10 14:39:05959 case VideoSendStream::DegradationPreference::kDegradationDisabled:
sprangc5d62e22017-04-03 06:53:04960 return;
sprang84a37592017-02-10 15:04:27961 }
sprangc5d62e22017-04-03 06:53:04962
asaperssond0de2952017-04-21 08:47:31963 if (reason == kCpu) {
asaperssonf7e294d2017-06-14 06:25:22964 if (GetConstAdaptCounter().ResolutionCount(kCpu) >=
965 kMaxCpuResolutionDowngrades ||
966 GetConstAdaptCounter().FramerateCount(kCpu) >=
967 kMaxCpuFramerateDowngrades) {
asaperssond0de2952017-04-21 08:47:31968 return;
asaperssonf7e294d2017-06-14 06:25:22969 }
kthelgason876222f2016-11-29 09:44:11970 }
sprangc5d62e22017-04-03 06:53:04971
sprangc5d62e22017-04-03 06:53:04972 switch (degradation_preference_) {
asaperssonf7e294d2017-06-14 06:25:22973 case VideoSendStream::DegradationPreference::kBalanced: {
974 // Try scale down framerate, if lower.
975 int fps = MinFps(last_frame_info_->pixel_count());
976 if (source_proxy_->RestrictFramerate(fps)) {
977 GetAdaptCounter().IncrementFramerate(reason);
978 break;
979 }
980 // Scale down resolution.
kjellanderbdf30722017-09-08 18:00:21981 FALLTHROUGH();
asaperssonf7e294d2017-06-14 06:25:22982 }
hbos8d609f62017-04-10 14:39:05983 case VideoSendStream::DegradationPreference::kMaintainFramerate:
asapersson13874762017-06-07 07:01:02984 // Scale down resolution.
asaperssond0de2952017-04-21 08:47:31985 if (!source_proxy_->RequestResolutionLowerThan(
asapersson142fcc92017-08-17 15:58:54986 adaptation_request.input_pixel_count_,
987 settings_.encoder->GetScalingSettings().min_pixels_per_frame)) {
asaperssond0de2952017-04-21 08:47:31988 return;
989 }
asaperssonf7e294d2017-06-14 06:25:22990 GetAdaptCounter().IncrementResolution(reason);
sprangc5d62e22017-04-03 06:53:04991 break;
sprangfda496a2017-06-15 11:21:07992 case VideoSendStream::DegradationPreference::kMaintainResolution: {
asapersson13874762017-06-07 07:01:02993 // Scale down framerate.
sprangfda496a2017-06-15 11:21:07994 const int requested_framerate = source_proxy_->RequestFramerateLowerThan(
995 adaptation_request.framerate_fps_);
996 if (requested_framerate == -1)
asapersson13874762017-06-07 07:01:02997 return;
sprangfda496a2017-06-15 11:21:07998 RTC_DCHECK_NE(max_framerate_, -1);
999 overuse_detector_->OnTargetFramerateUpdated(
1000 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-14 06:25:221001 GetAdaptCounter().IncrementFramerate(reason);
sprangc5d62e22017-04-03 06:53:041002 break;
sprangfda496a2017-06-15 11:21:071003 }
hbos8d609f62017-04-10 14:39:051004 case VideoSendStream::DegradationPreference::kDegradationDisabled:
sprangc5d62e22017-04-03 06:53:041005 RTC_NOTREACHED();
1006 }
1007
asaperssond0de2952017-04-21 08:47:311008 last_adaptation_request_.emplace(adaptation_request);
1009
asapersson09f05612017-05-16 06:40:181010 UpdateAdaptationStats(reason);
asaperssond0de2952017-04-21 08:47:311011
asapersson09f05612017-05-16 06:40:181012 LOG(LS_INFO) << GetConstAdaptCounter().ToString();
perkj26091b12016-09-01 08:17:401013}
1014
mflodmancc3d4422017-08-03 15:27:511015void VideoStreamEncoder::AdaptUp(AdaptReason reason) {
perkjd52063f2016-09-07 13:32:181016 RTC_DCHECK_RUN_ON(&encoder_queue_);
asapersson09f05612017-05-16 06:40:181017
1018 const AdaptCounter& adapt_counter = GetConstAdaptCounter();
1019 int num_downgrades = adapt_counter.TotalCount(reason);
1020 if (num_downgrades == 0)
perkj803d97f2016-11-01 18:45:461021 return;
asapersson09f05612017-05-16 06:40:181022 RTC_DCHECK_GT(num_downgrades, 0);
1023
sprangc5d62e22017-04-03 06:53:041024 AdaptationRequest adaptation_request = {
1025 last_frame_info_->pixel_count(),
1026 stats_proxy_->GetStats().input_frame_rate,
1027 AdaptationRequest::Mode::kAdaptUp};
1028
1029 bool adapt_up_requested =
1030 last_adaptation_request_ &&
1031 last_adaptation_request_->mode_ == AdaptationRequest::Mode::kAdaptUp;
asapersson09f05612017-05-16 06:40:181032
asaperssonf7e294d2017-06-14 06:25:221033 if (degradation_preference_ ==
1034 VideoSendStream::DegradationPreference::kMaintainFramerate) {
1035 if (adapt_up_requested &&
1036 adaptation_request.input_pixel_count_ <=
1037 last_adaptation_request_->input_pixel_count_) {
1038 // Don't request higher resolution if the current resolution is not
1039 // higher than the last time we asked for the resolution to be higher.
sprangc5d62e22017-04-03 06:53:041040 return;
asaperssonf7e294d2017-06-14 06:25:221041 }
sprangb1ca0732017-02-01 16:38:121042 }
sprangc5d62e22017-04-03 06:53:041043
sprangc5d62e22017-04-03 06:53:041044 switch (degradation_preference_) {
asaperssonf7e294d2017-06-14 06:25:221045 case VideoSendStream::DegradationPreference::kBalanced: {
1046 // Try scale up framerate, if higher.
1047 int fps = MaxFps(last_frame_info_->pixel_count());
1048 if (source_proxy_->IncreaseFramerate(fps)) {
1049 GetAdaptCounter().DecrementFramerate(reason, fps);
1050 // Reset framerate in case of fewer fps steps down than up.
1051 if (adapt_counter.FramerateCount() == 0 &&
1052 fps != std::numeric_limits<int>::max()) {
1053 LOG(LS_INFO) << "Removing framerate down-scaling setting.";
1054 source_proxy_->IncreaseFramerate(std::numeric_limits<int>::max());
1055 }
1056 break;
1057 }
1058 // Scale up resolution.
kjellanderbdf30722017-09-08 18:00:211059 FALLTHROUGH();
asaperssonf7e294d2017-06-14 06:25:221060 }
asapersson13874762017-06-07 07:01:021061 case VideoSendStream::DegradationPreference::kMaintainFramerate: {
1062 // Scale up resolution.
1063 int pixel_count = adaptation_request.input_pixel_count_;
1064 if (adapt_counter.ResolutionCount() == 1) {
sprangc5d62e22017-04-03 06:53:041065 LOG(LS_INFO) << "Removing resolution down-scaling setting.";
asapersson13874762017-06-07 07:01:021066 pixel_count = std::numeric_limits<int>::max();
sprangc5d62e22017-04-03 06:53:041067 }
asapersson13874762017-06-07 07:01:021068 if (!source_proxy_->RequestHigherResolutionThan(pixel_count))
1069 return;
asaperssonf7e294d2017-06-14 06:25:221070 GetAdaptCounter().DecrementResolution(reason);
sprangc5d62e22017-04-03 06:53:041071 break;
asapersson13874762017-06-07 07:01:021072 }
1073 case VideoSendStream::DegradationPreference::kMaintainResolution: {
1074 // Scale up framerate.
1075 int fps = adaptation_request.framerate_fps_;
1076 if (adapt_counter.FramerateCount() == 1) {
sprangc5d62e22017-04-03 06:53:041077 LOG(LS_INFO) << "Removing framerate down-scaling setting.";
asapersson13874762017-06-07 07:01:021078 fps = std::numeric_limits<int>::max();
sprangc5d62e22017-04-03 06:53:041079 }
sprangfda496a2017-06-15 11:21:071080
1081 const int requested_framerate =
1082 source_proxy_->RequestHigherFramerateThan(fps);
1083 if (requested_framerate == -1) {
1084 overuse_detector_->OnTargetFramerateUpdated(max_framerate_);
asapersson13874762017-06-07 07:01:021085 return;
sprangfda496a2017-06-15 11:21:071086 }
1087 overuse_detector_->OnTargetFramerateUpdated(
1088 std::min(max_framerate_, requested_framerate));
asaperssonf7e294d2017-06-14 06:25:221089 GetAdaptCounter().DecrementFramerate(reason);
sprangc5d62e22017-04-03 06:53:041090 break;
asapersson13874762017-06-07 07:01:021091 }
hbos8d609f62017-04-10 14:39:051092 case VideoSendStream::DegradationPreference::kDegradationDisabled:
asaperssonf7e294d2017-06-14 06:25:221093 return;
sprangc5d62e22017-04-03 06:53:041094 }
1095
asaperssond0de2952017-04-21 08:47:311096 last_adaptation_request_.emplace(adaptation_request);
1097
asapersson09f05612017-05-16 06:40:181098 UpdateAdaptationStats(reason);
1099
1100 LOG(LS_INFO) << adapt_counter.ToString();
1101}
1102
mflodmancc3d4422017-08-03 15:27:511103void VideoStreamEncoder::UpdateAdaptationStats(AdaptReason reason) {
asaperssond0de2952017-04-21 08:47:311104 switch (reason) {
asaperssond0de2952017-04-21 08:47:311105 case kCpu:
asapersson09f05612017-05-16 06:40:181106 stats_proxy_->OnCpuAdaptationChanged(GetActiveCounts(kCpu),
1107 GetActiveCounts(kQuality));
1108 break;
1109 case kQuality:
1110 stats_proxy_->OnQualityAdaptationChanged(GetActiveCounts(kCpu),
1111 GetActiveCounts(kQuality));
asaperssond0de2952017-04-21 08:47:311112 break;
1113 }
perkj26091b12016-09-01 08:17:401114}
1115
mflodmancc3d4422017-08-03 15:27:511116VideoStreamEncoder::AdaptCounts VideoStreamEncoder::GetActiveCounts(
1117 AdaptReason reason) {
1118 VideoStreamEncoder::AdaptCounts counts =
1119 GetConstAdaptCounter().Counts(reason);
asapersson09f05612017-05-16 06:40:181120 switch (reason) {
1121 case kCpu:
1122 if (!IsFramerateScalingEnabled(degradation_preference_))
1123 counts.fps = -1;
1124 if (!IsResolutionScalingEnabled(degradation_preference_))
1125 counts.resolution = -1;
1126 break;
1127 case kQuality:
1128 if (!IsFramerateScalingEnabled(degradation_preference_) ||
1129 !quality_scaler_) {
1130 counts.fps = -1;
1131 }
1132 if (!IsResolutionScalingEnabled(degradation_preference_) ||
1133 !quality_scaler_) {
1134 counts.resolution = -1;
1135 }
1136 break;
sprangc5d62e22017-04-03 06:53:041137 }
asapersson09f05612017-05-16 06:40:181138 return counts;
sprangc5d62e22017-04-03 06:53:041139}
1140
mflodmancc3d4422017-08-03 15:27:511141VideoStreamEncoder::AdaptCounter& VideoStreamEncoder::GetAdaptCounter() {
asapersson09f05612017-05-16 06:40:181142 return adapt_counters_[degradation_preference_];
1143}
1144
mflodmancc3d4422017-08-03 15:27:511145const VideoStreamEncoder::AdaptCounter&
1146VideoStreamEncoder::GetConstAdaptCounter() {
asapersson09f05612017-05-16 06:40:181147 return adapt_counters_[degradation_preference_];
1148}
1149
1150// Class holding adaptation information.
mflodmancc3d4422017-08-03 15:27:511151VideoStreamEncoder::AdaptCounter::AdaptCounter() {
asapersson09f05612017-05-16 06:40:181152 fps_counters_.resize(kScaleReasonSize);
1153 resolution_counters_.resize(kScaleReasonSize);
asaperssonf7e294d2017-06-14 06:25:221154 static_assert(kScaleReasonSize == 2, "Update MoveCount.");
asapersson09f05612017-05-16 06:40:181155}
1156
mflodmancc3d4422017-08-03 15:27:511157VideoStreamEncoder::AdaptCounter::~AdaptCounter() {}
asapersson09f05612017-05-16 06:40:181158
mflodmancc3d4422017-08-03 15:27:511159std::string VideoStreamEncoder::AdaptCounter::ToString() const {
asapersson09f05612017-05-16 06:40:181160 std::stringstream ss;
1161 ss << "Downgrade counts: fps: {" << ToString(fps_counters_);
1162 ss << "}, resolution: {" << ToString(resolution_counters_) << "}";
1163 return ss.str();
1164}
1165
mflodmancc3d4422017-08-03 15:27:511166VideoStreamEncoder::AdaptCounts VideoStreamEncoder::AdaptCounter::Counts(
1167 int reason) const {
asapersson09f05612017-05-16 06:40:181168 AdaptCounts counts;
1169 counts.fps = fps_counters_[reason];
1170 counts.resolution = resolution_counters_[reason];
1171 return counts;
1172}
1173
mflodmancc3d4422017-08-03 15:27:511174void VideoStreamEncoder::AdaptCounter::IncrementFramerate(int reason) {
asaperssonf7e294d2017-06-14 06:25:221175 ++(fps_counters_[reason]);
asapersson09f05612017-05-16 06:40:181176}
1177
mflodmancc3d4422017-08-03 15:27:511178void VideoStreamEncoder::AdaptCounter::IncrementResolution(int reason) {
asaperssonf7e294d2017-06-14 06:25:221179 ++(resolution_counters_[reason]);
1180}
1181
mflodmancc3d4422017-08-03 15:27:511182void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason) {
asaperssonf7e294d2017-06-14 06:25:221183 if (fps_counters_[reason] == 0) {
1184 // Balanced mode: Adapt up is in a different order, switch reason.
1185 // E.g. framerate adapt down: quality (2), framerate adapt up: cpu (3).
1186 // 1. Down resolution (cpu): res={quality:0,cpu:1}, fps={quality:0,cpu:0}
1187 // 2. Down fps (quality): res={quality:0,cpu:1}, fps={quality:1,cpu:0}
1188 // 3. Up fps (cpu): res={quality:1,cpu:0}, fps={quality:0,cpu:0}
1189 // 4. Up resolution (quality): res={quality:0,cpu:0}, fps={quality:0,cpu:0}
1190 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1191 RTC_DCHECK_GT(FramerateCount(), 0) << "Framerate not downgraded.";
1192 MoveCount(&resolution_counters_, reason);
1193 MoveCount(&fps_counters_, (reason + 1) % kScaleReasonSize);
1194 }
1195 --(fps_counters_[reason]);
1196 RTC_DCHECK_GE(fps_counters_[reason], 0);
1197}
1198
mflodmancc3d4422017-08-03 15:27:511199void VideoStreamEncoder::AdaptCounter::DecrementResolution(int reason) {
asaperssonf7e294d2017-06-14 06:25:221200 if (resolution_counters_[reason] == 0) {
1201 // Balanced mode: Adapt up is in a different order, switch reason.
1202 RTC_DCHECK_GT(TotalCount(reason), 0) << "No downgrade for reason.";
1203 RTC_DCHECK_GT(ResolutionCount(), 0) << "Resolution not downgraded.";
1204 MoveCount(&fps_counters_, reason);
1205 MoveCount(&resolution_counters_, (reason + 1) % kScaleReasonSize);
1206 }
1207 --(resolution_counters_[reason]);
1208 RTC_DCHECK_GE(resolution_counters_[reason], 0);
1209}
1210
mflodmancc3d4422017-08-03 15:27:511211void VideoStreamEncoder::AdaptCounter::DecrementFramerate(int reason,
1212 int cur_fps) {
asaperssonf7e294d2017-06-14 06:25:221213 DecrementFramerate(reason);
1214 // Reset if at max fps (i.e. in case of fewer steps up than down).
1215 if (cur_fps == std::numeric_limits<int>::max())
1216 std::fill(fps_counters_.begin(), fps_counters_.end(), 0);
asapersson09f05612017-05-16 06:40:181217}
1218
mflodmancc3d4422017-08-03 15:27:511219int VideoStreamEncoder::AdaptCounter::FramerateCount() const {
asapersson09f05612017-05-16 06:40:181220 return Count(fps_counters_);
1221}
1222
mflodmancc3d4422017-08-03 15:27:511223int VideoStreamEncoder::AdaptCounter::ResolutionCount() const {
asapersson09f05612017-05-16 06:40:181224 return Count(resolution_counters_);
1225}
1226
mflodmancc3d4422017-08-03 15:27:511227int VideoStreamEncoder::AdaptCounter::FramerateCount(int reason) const {
asapersson09f05612017-05-16 06:40:181228 return fps_counters_[reason];
1229}
1230
mflodmancc3d4422017-08-03 15:27:511231int VideoStreamEncoder::AdaptCounter::ResolutionCount(int reason) const {
asapersson09f05612017-05-16 06:40:181232 return resolution_counters_[reason];
1233}
1234
mflodmancc3d4422017-08-03 15:27:511235int VideoStreamEncoder::AdaptCounter::TotalCount(int reason) const {
asapersson09f05612017-05-16 06:40:181236 return FramerateCount(reason) + ResolutionCount(reason);
1237}
1238
mflodmancc3d4422017-08-03 15:27:511239int VideoStreamEncoder::AdaptCounter::Count(
1240 const std::vector<int>& counters) const {
asapersson09f05612017-05-16 06:40:181241 return std::accumulate(counters.begin(), counters.end(), 0);
1242}
1243
mflodmancc3d4422017-08-03 15:27:511244void VideoStreamEncoder::AdaptCounter::MoveCount(std::vector<int>* counters,
1245 int from_reason) {
asaperssonf7e294d2017-06-14 06:25:221246 int to_reason = (from_reason + 1) % kScaleReasonSize;
1247 ++((*counters)[to_reason]);
1248 --((*counters)[from_reason]);
1249}
1250
mflodmancc3d4422017-08-03 15:27:511251std::string VideoStreamEncoder::AdaptCounter::ToString(
asapersson09f05612017-05-16 06:40:181252 const std::vector<int>& counters) const {
1253 std::stringstream ss;
1254 for (size_t reason = 0; reason < kScaleReasonSize; ++reason) {
1255 ss << (reason ? " cpu" : "quality") << ":" << counters[reason];
sprangc5d62e22017-04-03 06:53:041256 }
asapersson09f05612017-05-16 06:40:181257 return ss.str();
sprangc5d62e22017-04-03 06:53:041258}
1259
mflodman@webrtc.org84d17832011-12-01 17:02:231260} // namespace webrtc