blob: bcf89cbdbd8207b37054b3039967236e6cf8c095 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001// libjingle
2// Copyright 2010 Google Inc.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are met:
6//
7// 1. Redistributions of source code must retain the above copyright notice,
8// this list of conditions and the following disclaimer.
9// 2. Redistributions in binary form must reproduce the above copyright notice,
10// this list of conditions and the following disclaimer in the documentation
11// and/or other materials provided with the distribution.
12// 3. The name of the author may not be used to endorse or promote products
13// derived from this software without specific prior written permission.
14//
15// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
16// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
17// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
18// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
21// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
22// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
23// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
24// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25
26#include "talk/media/base/videoadapter.h"
27
28#include <limits.h> // For INT_MAX
29
henrike@webrtc.org28e20752013-07-10 00:45:36 +000030#include "talk/base/logging.h"
31#include "talk/base/timeutils.h"
henrike@webrtc.org28654cb2013-07-22 21:07:49 +000032#include "talk/media/base/constants.h"
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +000033#include "talk/media/base/videocommon.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000034#include "talk/media/base/videoframe.h"
35
36namespace cricket {
37
38// TODO(fbarchard): Make downgrades settable
39static const int kMaxCpuDowngrades = 2; // Downgrade at most 2 times for CPU.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +000040// The number of cpu samples to require before adapting. This value depends on
41// the cpu monitor sampling frequency being 2000ms.
42static const int kCpuLoadMinSamples = 3;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +000043// The amount of weight to give to each new cpu load sample. The lower the
44// value, the slower we'll adapt to changing cpu conditions.
45static const float kCpuLoadWeightCoefficient = 0.4f;
46// The seed value for the cpu load moving average.
47static const float kCpuLoadInitialAverage = 0.5f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000048
henrike@webrtc.org28e20752013-07-10 00:45:36 +000049// Desktop needs 1/8 scale for HD (1280 x 720) to QQVGA (160 x 90)
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000050static const float kScaleFactors[] = {
51 1.f / 1.f, // Full size.
52 3.f / 4.f, // 3/4 scale.
53 1.f / 2.f, // 1/2 scale.
54 3.f / 8.f, // 3/8 scale.
55 1.f / 4.f, // 1/4 scale.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056 3.f / 16.f, // 3/16 scale.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000057 1.f / 8.f, // 1/8 scale.
58 0.f // End of table.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000061// TODO(fbarchard): Use this table (optionally) for CPU and GD as well.
62static const float kViewScaleFactors[] = {
63 1.f / 1.f, // Full size.
64 3.f / 4.f, // 3/4 scale.
65 2.f / 3.f, // 2/3 scale. // Allow 1080p to 720p.
66 1.f / 2.f, // 1/2 scale.
67 3.f / 8.f, // 3/8 scale.
68 1.f / 3.f, // 1/3 scale. // Allow 1080p to 360p.
69 1.f / 4.f, // 1/4 scale.
70 3.f / 16.f, // 3/16 scale.
71 1.f / 8.f, // 1/8 scale.
72 0.f // End of table.
73};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000075const float* VideoAdapter::GetViewScaleFactors() const {
76 return scale_third_ ? kViewScaleFactors : kScaleFactors;
77}
78
79// For resolutions that would scale down a little instead of up a little,
80// bias toward scaling up a little. This will tend to choose 3/4 scale instead
81// of 2/3 scale, when the 2/3 is not an exact match.
82static const float kUpBias = -0.9f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000083// Find the scale factor that, when applied to width and height, is closest
84// to num_pixels.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000085float VideoAdapter::FindScale(const float* scale_factors,
86 const float upbias,
87 int width, int height,
88 int target_num_pixels) {
89 const float kMinNumPixels = 160 * 90;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000090 if (!target_num_pixels) {
91 return 0.f;
92 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000093 float best_distance = static_cast<float>(INT_MAX);
94 float best_scale = 1.f; // Default to unscaled if nothing matches.
95 float pixels = static_cast<float>(width * height);
96 for (int i = 0; ; ++i) {
97 float scale = scale_factors[i];
98 float test_num_pixels = pixels * scale * scale;
99 // Do not consider scale factors that produce too small images.
100 // Scale factor of 0 at end of table will also exit here.
101 if (test_num_pixels < kMinNumPixels) {
102 break;
103 }
104 float diff = target_num_pixels - test_num_pixels;
105 // If resolution is higher than desired, bias the difference based on
106 // preference for slightly larger for nearest, or avoid completely if
107 // looking for lower resolutions only.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108 if (diff < 0) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000109 diff = diff * kUpBias;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110 }
111 if (diff < best_distance) {
112 best_distance = diff;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000113 best_scale = scale;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000114 if (best_distance == 0) { // Found exact match.
115 break;
116 }
117 }
118 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000119 return best_scale;
120}
121
122// Find the closest scale factor.
123float VideoAdapter::FindClosestScale(int width, int height,
124 int target_num_pixels) {
125 return FindScale(kScaleFactors, kUpBias,
126 width, height, target_num_pixels);
127}
128
129// Find the closest view scale factor.
130float VideoAdapter::FindClosestViewScale(int width, int height,
131 int target_num_pixels) {
132 return FindScale(GetViewScaleFactors(), kUpBias,
133 width, height, target_num_pixels);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134}
135
136// Finds the scale factor that, when applied to width and height, produces
137// fewer than num_pixels.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000138static const float kUpAvoidBias = -1000000000.f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000139float VideoAdapter::FindLowerScale(int width, int height,
140 int target_num_pixels) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000141 return FindScale(GetViewScaleFactors(), kUpAvoidBias,
142 width, height, target_num_pixels);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000143}
144
145// There are several frame sizes used by Adapter. This explains them
146// input_format - set once by server to frame size expected from the camera.
147// output_format - size that output would like to be. Includes framerate.
148// output_num_pixels - size that output should be constrained to. Used to
149// compute output_format from in_frame.
150// in_frame - actual camera captured frame size, which is typically the same
151// as input_format. This can also be rotated or cropped for aspect ratio.
152// out_frame - actual frame output by adapter. Should be a direct scale of
153// in_frame maintaining rotation and aspect ratio.
154// OnOutputFormatRequest - server requests you send this resolution based on
155// view requests.
156// OnEncoderResolutionRequest - encoder requests you send this resolution based
157// on bandwidth
158// OnCpuLoadUpdated - cpu monitor requests you send this resolution based on
159// cpu load.
160
161///////////////////////////////////////////////////////////////////////
162// Implementation of VideoAdapter
163VideoAdapter::VideoAdapter()
164 : output_num_pixels_(INT_MAX),
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000165 scale_third_(false),
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000166 frames_in_(0),
167 frames_out_(0),
168 frames_scaled_(0),
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000169 adaption_changes_(0),
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000170 previous_width_(0),
171 previous_height_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000172 black_output_(false),
173 is_black_(false),
174 interval_next_frame_(0) {
175}
176
177VideoAdapter::~VideoAdapter() {
178}
179
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000180void VideoAdapter::SetInputFormat(const VideoFormat& format) {
181 talk_base::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000182 int64 old_input_interval = input_format_.interval;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000183 input_format_ = format;
184 output_format_.interval = talk_base::_max(
185 output_format_.interval, input_format_.interval);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000186 if (old_input_interval != input_format_.interval) {
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000187 LOG(LS_INFO) << "VAdapt input interval changed from "
188 << old_input_interval << " to " << input_format_.interval;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000189 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000190}
191
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000192void CoordinatedVideoAdapter::SetInputFormat(const VideoFormat& format) {
193 int previous_width = input_format().width;
194 int previous_height = input_format().height;
195 bool is_resolution_change = previous_width > 0 && format.width > 0 &&
196 (previous_width != format.width ||
197 previous_height != format.height);
198 VideoAdapter::SetInputFormat(format);
199 if (is_resolution_change) {
200 int width, height;
201 // Trigger the adaptation logic again, to potentially reset the adaptation
202 // state for things like view requests that may not longer be capping
203 // output (or may now cap output).
204 AdaptToMinimumFormat(&width, &height);
205 LOG(LS_INFO) << "VAdapt Input Resolution Change: "
206 << "Previous input resolution: "
207 << previous_width << "x" << previous_height
208 << " New input resolution: "
209 << format.width << "x" << format.height
210 << " New output resolution: "
211 << width << "x" << height;
212 }
213}
214
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000215void CoordinatedVideoAdapter::set_cpu_smoothing(bool enable) {
216 LOG(LS_INFO) << "CPU smoothing is now "
217 << (enable ? "enabled" : "disabled");
218 cpu_smoothing_ = enable;
219}
220
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000221void VideoAdapter::SetOutputFormat(const VideoFormat& format) {
222 talk_base::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000223 int64 old_output_interval = output_format_.interval;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000224 output_format_ = format;
225 output_num_pixels_ = output_format_.width * output_format_.height;
226 output_format_.interval = talk_base::_max(
227 output_format_.interval, input_format_.interval);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000228 if (old_output_interval != output_format_.interval) {
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000229 LOG(LS_INFO) << "VAdapt output interval changed from "
230 << old_output_interval << " to " << output_format_.interval;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000231 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000232}
233
234const VideoFormat& VideoAdapter::input_format() {
235 talk_base::CritScope cs(&critical_section_);
236 return input_format_;
237}
238
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000239bool VideoAdapter::drops_all_frames() const {
240 return output_num_pixels_ == 0;
241}
242
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000243const VideoFormat& VideoAdapter::output_format() {
244 talk_base::CritScope cs(&critical_section_);
245 return output_format_;
246}
247
248void VideoAdapter::SetBlackOutput(bool black) {
249 talk_base::CritScope cs(&critical_section_);
250 black_output_ = black;
251}
252
253// Constrain output resolution to this many pixels overall
254void VideoAdapter::SetOutputNumPixels(int num_pixels) {
255 output_num_pixels_ = num_pixels;
256}
257
258int VideoAdapter::GetOutputNumPixels() const {
259 return output_num_pixels_;
260}
261
262// TODO(fbarchard): Add AdaptFrameRate function that only drops frames but
263// not resolution.
264bool VideoAdapter::AdaptFrame(const VideoFrame* in_frame,
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000265 VideoFrame** out_frame) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000266 talk_base::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000267 if (!in_frame || !out_frame) {
268 return false;
269 }
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000270 ++frames_in_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000271
272 // Update input to actual frame dimensions.
mallinath@webrtc.orgab5a0912013-09-07 00:12:57 +0000273 VideoFormat format(static_cast<int>(in_frame->GetWidth()),
274 static_cast<int>(in_frame->GetHeight()),
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000275 input_format_.interval, input_format_.fourcc);
276 SetInputFormat(format);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000277
278 // Drop the input frame if necessary.
279 bool should_drop = false;
280 if (!output_num_pixels_) {
281 // Drop all frames as the output format is 0x0.
282 should_drop = true;
283 } else {
284 // Drop some frames based on input fps and output fps.
285 // Normally output fps is less than input fps.
286 // TODO(fbarchard): Consider adjusting interval to reflect the adjusted
287 // interval between frames after dropping some frames.
288 interval_next_frame_ += input_format_.interval;
289 if (output_format_.interval > 0) {
290 if (interval_next_frame_ >= output_format_.interval) {
291 interval_next_frame_ %= output_format_.interval;
292 } else {
293 should_drop = true;
294 }
295 }
296 }
297 if (should_drop) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000298 // Show VAdapt log every 90 frames dropped. (3 seconds)
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000299 if ((frames_in_ - frames_out_) % 90 == 0) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000300 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
301 // in default calls.
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000302 LOG(LS_INFO) << "VAdapt Drop Frame: scaled " << frames_scaled_
303 << " / out " << frames_out_
304 << " / in " << frames_in_
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000305 << " Changes: " << adaption_changes_
306 << " Input: " << in_frame->GetWidth()
307 << "x" << in_frame->GetHeight()
308 << " i" << input_format_.interval
309 << " Output: i" << output_format_.interval;
310 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000311 *out_frame = NULL;
312 return true;
313 }
314
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000315 float scale = 1.f;
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000316 if (output_num_pixels_ < input_format_.width * input_format_.height) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000317 scale = VideoAdapter::FindClosestViewScale(
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000318 static_cast<int>(in_frame->GetWidth()),
319 static_cast<int>(in_frame->GetHeight()),
320 output_num_pixels_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000321 output_format_.width = static_cast<int>(in_frame->GetWidth() * scale + .5f);
322 output_format_.height = static_cast<int>(in_frame->GetHeight() * scale +
323 .5f);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000324 } else {
325 output_format_.width = static_cast<int>(in_frame->GetWidth());
326 output_format_.height = static_cast<int>(in_frame->GetHeight());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000327 }
328
329 if (!StretchToOutputFrame(in_frame)) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000330 LOG(LS_VERBOSE) << "VAdapt Stretch Failed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000331 return false;
332 }
333
334 *out_frame = output_frame_.get();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000335
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000336 ++frames_out_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000337 if (in_frame->GetWidth() != (*out_frame)->GetWidth() ||
338 in_frame->GetHeight() != (*out_frame)->GetHeight()) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000339 ++frames_scaled_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000340 }
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000341 // Show VAdapt log every 90 frames output. (3 seconds)
342 // TODO(fbarchard): Consider GetLogSeverity() to change interval to less
343 // for LS_VERBOSE and more for LS_INFO.
344 bool show = (frames_out_) % 90 == 0;
345
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000346 // TODO(fbarchard): LOG the previous output resolution and track input
347 // resolution changes as well. Consider dropping the statistics into their
348 // own class which could be queried publically.
349 bool changed = false;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000350 if (previous_width_ && (previous_width_ != (*out_frame)->GetWidth() ||
351 previous_height_ != (*out_frame)->GetHeight())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000352 show = true;
353 ++adaption_changes_;
354 changed = true;
355 }
356 if (show) {
357 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
358 // in default calls.
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000359 LOG(LS_INFO) << "VAdapt Frame: scaled " << frames_scaled_
360 << " / out " << frames_out_
361 << " / in " << frames_in_
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000362 << " Changes: " << adaption_changes_
363 << " Input: " << in_frame->GetWidth()
364 << "x" << in_frame->GetHeight()
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000365 << " i" << input_format_.interval
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000366 << " Scale: " << scale
367 << " Output: " << (*out_frame)->GetWidth()
368 << "x" << (*out_frame)->GetHeight()
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000369 << " i" << output_format_.interval
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000370 << " Changed: " << (changed ? "true" : "false");
371 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000372 previous_width_ = (*out_frame)->GetWidth();
373 previous_height_ = (*out_frame)->GetHeight();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000374
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000375 return true;
376}
377
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000378void VideoAdapter::set_scale_third(bool enable) {
379 LOG(LS_INFO) << "Video Adapter third scaling is now "
380 << (enable ? "enabled" : "disabled");
381 scale_third_ = enable;
382}
383
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000384// Scale or Blacken the frame. Returns true if successful.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000385bool VideoAdapter::StretchToOutputFrame(const VideoFrame* in_frame) {
386 int output_width = output_format_.width;
387 int output_height = output_format_.height;
388
389 // Create and stretch the output frame if it has not been created yet or its
390 // size is not same as the expected.
391 bool stretched = false;
392 if (!output_frame_ ||
393 output_frame_->GetWidth() != static_cast<size_t>(output_width) ||
394 output_frame_->GetHeight() != static_cast<size_t>(output_height)) {
395 output_frame_.reset(
396 in_frame->Stretch(output_width, output_height, true, true));
397 if (!output_frame_) {
398 LOG(LS_WARNING) << "Adapter failed to stretch frame to "
399 << output_width << "x" << output_height;
400 return false;
401 }
402 stretched = true;
403 is_black_ = false;
404 }
405
406 if (!black_output_) {
407 if (!stretched) {
408 // The output frame does not need to be blacken and has not been stretched
409 // from the input frame yet, stretch the input frame. This is the most
410 // common case.
411 in_frame->StretchToFrame(output_frame_.get(), true, true);
412 }
413 is_black_ = false;
414 } else {
415 if (!is_black_) {
416 output_frame_->SetToBlack();
417 is_black_ = true;
418 }
419 output_frame_->SetElapsedTime(in_frame->GetElapsedTime());
420 output_frame_->SetTimeStamp(in_frame->GetTimeStamp());
421 }
422
423 return true;
424}
425
426///////////////////////////////////////////////////////////////////////
427// Implementation of CoordinatedVideoAdapter
428CoordinatedVideoAdapter::CoordinatedVideoAdapter()
wu@webrtc.org9caf2762013-12-11 18:25:07 +0000429 : cpu_adaptation_(true),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000430 cpu_smoothing_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000431 gd_adaptation_(true),
432 view_adaptation_(true),
433 view_switch_(false),
434 cpu_downgrade_count_(0),
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000435 cpu_load_min_samples_(kCpuLoadMinSamples),
436 cpu_load_num_samples_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000437 high_system_threshold_(kHighSystemCpuThreshold),
438 low_system_threshold_(kLowSystemCpuThreshold),
439 process_threshold_(kProcessCpuThreshold),
440 view_desired_num_pixels_(INT_MAX),
441 view_desired_interval_(0),
442 encoder_desired_num_pixels_(INT_MAX),
443 cpu_desired_num_pixels_(INT_MAX),
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000444 adapt_reason_(ADAPTREASON_NONE),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000445 system_load_average_(kCpuLoadInitialAverage) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000446}
447
448// Helper function to UPGRADE or DOWNGRADE a number of pixels
449void CoordinatedVideoAdapter::StepPixelCount(
450 CoordinatedVideoAdapter::AdaptRequest request,
451 int* num_pixels) {
452 switch (request) {
453 case CoordinatedVideoAdapter::DOWNGRADE:
454 *num_pixels /= 2;
455 break;
456
457 case CoordinatedVideoAdapter::UPGRADE:
458 *num_pixels *= 2;
459 break;
460
461 default: // No change in pixel count
462 break;
463 }
464 return;
465}
466
467// Find the adaptation request of the cpu based on the load. Return UPGRADE if
468// the load is low, DOWNGRADE if the load is high, and KEEP otherwise.
469CoordinatedVideoAdapter::AdaptRequest CoordinatedVideoAdapter::FindCpuRequest(
470 int current_cpus, int max_cpus,
471 float process_load, float system_load) {
472 // Downgrade if system is high and plugin is at least more than midrange.
473 if (system_load >= high_system_threshold_ * max_cpus &&
474 process_load >= process_threshold_ * current_cpus) {
475 return CoordinatedVideoAdapter::DOWNGRADE;
476 // Upgrade if system is low.
477 } else if (system_load < low_system_threshold_ * max_cpus) {
478 return CoordinatedVideoAdapter::UPGRADE;
479 }
480 return CoordinatedVideoAdapter::KEEP;
481}
482
483// A remote view request for a new resolution.
484void CoordinatedVideoAdapter::OnOutputFormatRequest(const VideoFormat& format) {
485 talk_base::CritScope cs(&request_critical_section_);
486 if (!view_adaptation_) {
487 return;
488 }
489 // Set output for initial aspect ratio in mediachannel unittests.
490 int old_num_pixels = GetOutputNumPixels();
491 SetOutputFormat(format);
492 SetOutputNumPixels(old_num_pixels);
493 view_desired_num_pixels_ = format.width * format.height;
494 view_desired_interval_ = format.interval;
495 int new_width, new_height;
496 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
497 LOG(LS_INFO) << "VAdapt View Request: "
498 << format.width << "x" << format.height
499 << " Pixels: " << view_desired_num_pixels_
500 << " Changed: " << (changed ? "true" : "false")
501 << " To: " << new_width << "x" << new_height;
502}
503
henrike@webrtc.orgd43aa9d2014-02-21 23:43:24 +0000504void CoordinatedVideoAdapter::set_cpu_load_min_samples(
505 int cpu_load_min_samples) {
506 if (cpu_load_min_samples_ != cpu_load_min_samples) {
507 LOG(LS_INFO) << "VAdapt Change Cpu Adapt Min Samples from: "
508 << cpu_load_min_samples_ << " to "
509 << cpu_load_min_samples;
510 cpu_load_min_samples_ = cpu_load_min_samples;
511 }
512}
513
514void CoordinatedVideoAdapter::set_high_system_threshold(
515 float high_system_threshold) {
516 ASSERT(high_system_threshold <= 1.0f);
517 ASSERT(high_system_threshold >= 0.0f);
518 if (high_system_threshold_ != high_system_threshold) {
519 LOG(LS_INFO) << "VAdapt Change High System Threshold from: "
520 << high_system_threshold_ << " to " << high_system_threshold;
521 high_system_threshold_ = high_system_threshold;
522 }
523}
524
525void CoordinatedVideoAdapter::set_low_system_threshold(
526 float low_system_threshold) {
527 ASSERT(low_system_threshold <= 1.0f);
528 ASSERT(low_system_threshold >= 0.0f);
529 if (low_system_threshold_ != low_system_threshold) {
530 LOG(LS_INFO) << "VAdapt Change Low System Threshold from: "
531 << low_system_threshold_ << " to " << low_system_threshold;
532 low_system_threshold_ = low_system_threshold;
533 }
534}
535
536void CoordinatedVideoAdapter::set_process_threshold(float process_threshold) {
537 ASSERT(process_threshold <= 1.0f);
538 ASSERT(process_threshold >= 0.0f);
539 if (process_threshold_ != process_threshold) {
540 LOG(LS_INFO) << "VAdapt Change High Process Threshold from: "
541 << process_threshold_ << " to " << process_threshold;
542 process_threshold_ = process_threshold;
543 }
544}
545
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000546// A Bandwidth GD request for new resolution
547void CoordinatedVideoAdapter::OnEncoderResolutionRequest(
548 int width, int height, AdaptRequest request) {
549 talk_base::CritScope cs(&request_critical_section_);
550 if (!gd_adaptation_) {
551 return;
552 }
553 int old_encoder_desired_num_pixels = encoder_desired_num_pixels_;
554 if (KEEP != request) {
555 int new_encoder_desired_num_pixels = width * height;
556 int old_num_pixels = GetOutputNumPixels();
557 if (new_encoder_desired_num_pixels != old_num_pixels) {
558 LOG(LS_VERBOSE) << "VAdapt GD resolution stale. Ignored";
559 } else {
560 // Update the encoder desired format based on the request.
561 encoder_desired_num_pixels_ = new_encoder_desired_num_pixels;
562 StepPixelCount(request, &encoder_desired_num_pixels_);
563 }
564 }
565 int new_width, new_height;
566 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
567
568 // Ignore up or keep if no change.
569 if (DOWNGRADE != request && view_switch_ && !changed) {
570 encoder_desired_num_pixels_ = old_encoder_desired_num_pixels;
571 LOG(LS_VERBOSE) << "VAdapt ignoring GD request.";
572 }
573
574 LOG(LS_INFO) << "VAdapt GD Request: "
575 << (DOWNGRADE == request ? "down" :
576 (UPGRADE == request ? "up" : "keep"))
577 << " From: " << width << "x" << height
578 << " Pixels: " << encoder_desired_num_pixels_
579 << " Changed: " << (changed ? "true" : "false")
580 << " To: " << new_width << "x" << new_height;
581}
582
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000583// A Bandwidth GD request for new resolution
584void CoordinatedVideoAdapter::OnCpuResolutionRequest(AdaptRequest request) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000585 talk_base::CritScope cs(&request_critical_section_);
586 if (!cpu_adaptation_) {
587 return;
588 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000589 // Update how many times we have downgraded due to the cpu load.
590 switch (request) {
591 case DOWNGRADE:
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000592 // Ignore downgrades if we have downgraded the maximum times.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000593 if (cpu_downgrade_count_ < kMaxCpuDowngrades) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000594 ++cpu_downgrade_count_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000595 } else {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000596 LOG(LS_VERBOSE) << "VAdapt CPU load high but do not downgrade "
597 "because maximum downgrades reached";
598 SignalCpuAdaptationUnable();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000599 }
600 break;
601 case UPGRADE:
602 if (cpu_downgrade_count_ > 0) {
603 bool is_min = IsMinimumFormat(cpu_desired_num_pixels_);
604 if (is_min) {
605 --cpu_downgrade_count_;
606 } else {
607 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
608 "because cpu is not limiting resolution";
609 }
610 } else {
611 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
612 "because minimum downgrades reached";
613 }
614 break;
615 case KEEP:
616 default:
617 break;
618 }
619 if (KEEP != request) {
620 // TODO(fbarchard): compute stepping up/down from OutputNumPixels but
621 // clamp to inputpixels / 4 (2 steps)
622 cpu_desired_num_pixels_ = cpu_downgrade_count_ == 0 ? INT_MAX :
623 static_cast<int>(input_format().width * input_format().height >>
624 cpu_downgrade_count_);
625 }
626 int new_width, new_height;
627 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
628 LOG(LS_INFO) << "VAdapt CPU Request: "
629 << (DOWNGRADE == request ? "down" :
630 (UPGRADE == request ? "up" : "keep"))
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000631 << " Steps: " << cpu_downgrade_count_
632 << " Changed: " << (changed ? "true" : "false")
633 << " To: " << new_width << "x" << new_height;
634}
635
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000636// A CPU request for new resolution
637// TODO(fbarchard): Move outside adapter.
638void CoordinatedVideoAdapter::OnCpuLoadUpdated(
639 int current_cpus, int max_cpus, float process_load, float system_load) {
640 talk_base::CritScope cs(&request_critical_section_);
641 if (!cpu_adaptation_) {
642 return;
643 }
644 // Update the moving average of system load. Even if we aren't smoothing,
645 // we'll still calculate this information, in case smoothing is later enabled.
646 system_load_average_ = kCpuLoadWeightCoefficient * system_load +
647 (1.0f - kCpuLoadWeightCoefficient) * system_load_average_;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000648 ++cpu_load_num_samples_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000649 if (cpu_smoothing_) {
650 system_load = system_load_average_;
651 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000652 AdaptRequest request = FindCpuRequest(current_cpus, max_cpus,
653 process_load, system_load);
654 // Make sure we're not adapting too quickly.
655 if (request != KEEP) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000656 if (cpu_load_num_samples_ < cpu_load_min_samples_) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000657 LOG(LS_VERBOSE) << "VAdapt CPU load high/low but do not adapt until "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000658 << (cpu_load_min_samples_ - cpu_load_num_samples_)
659 << " more samples";
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000660 request = KEEP;
661 }
662 }
663
664 OnCpuResolutionRequest(request);
665}
666
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000667// Called by cpu adapter on up requests.
668bool CoordinatedVideoAdapter::IsMinimumFormat(int pixels) {
669 // Find closest scale factor that matches input resolution to min_num_pixels
670 // and set that for output resolution. This is not needed for VideoAdapter,
671 // but provides feedback to unittests and users on expected resolution.
672 // Actual resolution is based on input frame.
673 VideoFormat new_output = output_format();
674 VideoFormat input = input_format();
675 if (input_format().IsSize0x0()) {
676 input = new_output;
677 }
678 float scale = 1.0f;
679 if (!input.IsSize0x0()) {
680 scale = FindClosestScale(input.width,
681 input.height,
682 pixels);
683 }
684 new_output.width = static_cast<int>(input.width * scale + .5f);
685 new_output.height = static_cast<int>(input.height * scale + .5f);
686 int new_pixels = new_output.width * new_output.height;
687 int num_pixels = GetOutputNumPixels();
688 return new_pixels <= num_pixels;
689}
690
691// Called by all coordinators when there is a change.
692bool CoordinatedVideoAdapter::AdaptToMinimumFormat(int* new_width,
693 int* new_height) {
694 VideoFormat new_output = output_format();
695 VideoFormat input = input_format();
696 if (input_format().IsSize0x0()) {
697 input = new_output;
698 }
699 int old_num_pixels = GetOutputNumPixels();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000700 int min_num_pixels = INT_MAX;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000701 adapt_reason_ = ADAPTREASON_NONE;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000702
703 // Reduce resolution based on encoder bandwidth (GD).
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000704 if (encoder_desired_num_pixels_ &&
705 (encoder_desired_num_pixels_ < min_num_pixels)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000706 adapt_reason_ |= ADAPTREASON_BANDWIDTH;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000707 min_num_pixels = encoder_desired_num_pixels_;
708 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000709 // Reduce resolution based on CPU.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000710 if (cpu_adaptation_ && cpu_desired_num_pixels_ &&
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000711 (cpu_desired_num_pixels_ <= min_num_pixels)) {
712 if (cpu_desired_num_pixels_ < min_num_pixels) {
713 adapt_reason_ = ADAPTREASON_CPU;
714 } else {
715 adapt_reason_ |= ADAPTREASON_CPU;
716 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000717 min_num_pixels = cpu_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000718 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000719 // Round resolution for GD or CPU to allow 1/2 to map to 9/16.
720 if (!input.IsSize0x0() && min_num_pixels != INT_MAX) {
721 float scale = FindClosestScale(input.width, input.height, min_num_pixels);
722 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
723 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000724 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000725 // Reduce resolution based on View Request.
726 if (view_desired_num_pixels_ <= min_num_pixels) {
727 if (view_desired_num_pixels_ < min_num_pixels) {
728 adapt_reason_ = ADAPTREASON_VIEW;
729 } else {
730 adapt_reason_ |= ADAPTREASON_VIEW;
731 }
732 min_num_pixels = view_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000734 // Snap to a scale factor.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000735 float scale = 1.0f;
736 if (!input.IsSize0x0()) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000737 scale = FindLowerScale(input.width, input.height, min_num_pixels);
738 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
739 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000740 }
741 if (scale == 1.0f) {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000742 adapt_reason_ = ADAPTREASON_NONE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000743 }
744 *new_width = new_output.width = static_cast<int>(input.width * scale + .5f);
745 *new_height = new_output.height = static_cast<int>(input.height * scale +
746 .5f);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000747 SetOutputNumPixels(min_num_pixels);
748
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000749 new_output.interval = view_desired_interval_;
750 SetOutputFormat(new_output);
751 int new_num_pixels = GetOutputNumPixels();
752 bool changed = new_num_pixels != old_num_pixels;
753
754 static const char* kReasons[8] = {
755 "None",
756 "CPU",
757 "BANDWIDTH",
758 "CPU+BANDWIDTH",
759 "VIEW",
760 "CPU+VIEW",
761 "BANDWIDTH+VIEW",
762 "CPU+BANDWIDTH+VIEW",
763 };
764
765 LOG(LS_VERBOSE) << "VAdapt Status View: " << view_desired_num_pixels_
766 << " GD: " << encoder_desired_num_pixels_
767 << " CPU: " << cpu_desired_num_pixels_
768 << " Pixels: " << min_num_pixels
769 << " Input: " << input.width
770 << "x" << input.height
771 << " Scale: " << scale
772 << " Resolution: " << new_output.width
773 << "x" << new_output.height
774 << " Changed: " << (changed ? "true" : "false")
775 << " Reason: " << kReasons[adapt_reason_];
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000776
777 if (changed) {
778 // When any adaptation occurs, historic CPU load levels are no longer
779 // accurate. Clear out our state so we can re-learn at the new normal.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000780 cpu_load_num_samples_ = 0;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000781 system_load_average_ = kCpuLoadInitialAverage;
782 }
783
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000784 return changed;
785}
786
787} // namespace cricket