blob: 29be805317be1dd9dbe12024852f247e88da70c2 [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.org28e20752013-07-10 00:45:36 +000033#include "talk/media/base/videoframe.h"
34
35namespace cricket {
36
37// TODO(fbarchard): Make downgrades settable
38static const int kMaxCpuDowngrades = 2; // Downgrade at most 2 times for CPU.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +000039// The number of cpu samples to require before adapting. This value depends on
40// the cpu monitor sampling frequency being 2000ms.
41static const int kCpuLoadMinSamples = 3;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +000042// The amount of weight to give to each new cpu load sample. The lower the
43// value, the slower we'll adapt to changing cpu conditions.
44static const float kCpuLoadWeightCoefficient = 0.4f;
45// The seed value for the cpu load moving average.
46static const float kCpuLoadInitialAverage = 0.5f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000047
henrike@webrtc.org28e20752013-07-10 00:45:36 +000048// Desktop needs 1/8 scale for HD (1280 x 720) to QQVGA (160 x 90)
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000049static const float kScaleFactors[] = {
50 1.f / 1.f, // Full size.
51 3.f / 4.f, // 3/4 scale.
52 1.f / 2.f, // 1/2 scale.
53 3.f / 8.f, // 3/8 scale.
54 1.f / 4.f, // 1/4 scale.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055 3.f / 16.f, // 3/16 scale.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000056 1.f / 8.f, // 1/8 scale.
57 0.f // End of table.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000060// TODO(fbarchard): Use this table (optionally) for CPU and GD as well.
61static const float kViewScaleFactors[] = {
62 1.f / 1.f, // Full size.
63 3.f / 4.f, // 3/4 scale.
64 2.f / 3.f, // 2/3 scale. // Allow 1080p to 720p.
65 1.f / 2.f, // 1/2 scale.
66 3.f / 8.f, // 3/8 scale.
67 1.f / 3.f, // 1/3 scale. // Allow 1080p to 360p.
68 1.f / 4.f, // 1/4 scale.
69 3.f / 16.f, // 3/16 scale.
70 1.f / 8.f, // 1/8 scale.
71 0.f // End of table.
72};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000074const float* VideoAdapter::GetViewScaleFactors() const {
75 return scale_third_ ? kViewScaleFactors : kScaleFactors;
76}
77
78// For resolutions that would scale down a little instead of up a little,
79// bias toward scaling up a little. This will tend to choose 3/4 scale instead
80// of 2/3 scale, when the 2/3 is not an exact match.
81static const float kUpBias = -0.9f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000082// Find the scale factor that, when applied to width and height, is closest
83// to num_pixels.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000084float VideoAdapter::FindScale(const float* scale_factors,
85 const float upbias,
86 int width, int height,
87 int target_num_pixels) {
88 const float kMinNumPixels = 160 * 90;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089 if (!target_num_pixels) {
90 return 0.f;
91 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +000092 float best_distance = static_cast<float>(INT_MAX);
93 float best_scale = 1.f; // Default to unscaled if nothing matches.
94 float pixels = static_cast<float>(width * height);
95 for (int i = 0; ; ++i) {
96 float scale = scale_factors[i];
97 float test_num_pixels = pixels * scale * scale;
98 // Do not consider scale factors that produce too small images.
99 // Scale factor of 0 at end of table will also exit here.
100 if (test_num_pixels < kMinNumPixels) {
101 break;
102 }
103 float diff = target_num_pixels - test_num_pixels;
104 // If resolution is higher than desired, bias the difference based on
105 // preference for slightly larger for nearest, or avoid completely if
106 // looking for lower resolutions only.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 if (diff < 0) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000108 diff = diff * kUpBias;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109 }
110 if (diff < best_distance) {
111 best_distance = diff;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000112 best_scale = scale;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000113 if (best_distance == 0) { // Found exact match.
114 break;
115 }
116 }
117 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000118 return best_scale;
119}
120
121// Find the closest scale factor.
122float VideoAdapter::FindClosestScale(int width, int height,
123 int target_num_pixels) {
124 return FindScale(kScaleFactors, kUpBias,
125 width, height, target_num_pixels);
126}
127
128// Find the closest view scale factor.
129float VideoAdapter::FindClosestViewScale(int width, int height,
130 int target_num_pixels) {
131 return FindScale(GetViewScaleFactors(), kUpBias,
132 width, height, target_num_pixels);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133}
134
135// Finds the scale factor that, when applied to width and height, produces
136// fewer than num_pixels.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000137static const float kUpAvoidBias = -1000000000.f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000138float VideoAdapter::FindLowerScale(int width, int height,
139 int target_num_pixels) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000140 return FindScale(GetViewScaleFactors(), kUpAvoidBias,
141 width, height, target_num_pixels);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000142}
143
144// There are several frame sizes used by Adapter. This explains them
145// input_format - set once by server to frame size expected from the camera.
146// output_format - size that output would like to be. Includes framerate.
147// output_num_pixels - size that output should be constrained to. Used to
148// compute output_format from in_frame.
149// in_frame - actual camera captured frame size, which is typically the same
150// as input_format. This can also be rotated or cropped for aspect ratio.
151// out_frame - actual frame output by adapter. Should be a direct scale of
152// in_frame maintaining rotation and aspect ratio.
153// OnOutputFormatRequest - server requests you send this resolution based on
154// view requests.
155// OnEncoderResolutionRequest - encoder requests you send this resolution based
156// on bandwidth
157// OnCpuLoadUpdated - cpu monitor requests you send this resolution based on
158// cpu load.
159
160///////////////////////////////////////////////////////////////////////
161// Implementation of VideoAdapter
162VideoAdapter::VideoAdapter()
163 : output_num_pixels_(INT_MAX),
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000164 scale_third_(false),
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000165 frames_in_(0),
166 frames_out_(0),
167 frames_scaled_(0),
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000168 adaption_changes_(0),
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000169 previous_width_(0),
170 previous_height_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000171 black_output_(false),
172 is_black_(false),
173 interval_next_frame_(0) {
174}
175
176VideoAdapter::~VideoAdapter() {
177}
178
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000179void VideoAdapter::SetInputFormat(const VideoFormat& format) {
180 talk_base::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000181 int64 old_input_interval = input_format_.interval;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000182 input_format_ = format;
183 output_format_.interval = talk_base::_max(
184 output_format_.interval, input_format_.interval);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000185 if (old_input_interval != input_format_.interval) {
wu@webrtc.org0de29502014-02-13 19:54:28 +0000186 LOG(LS_INFO) << "VAdapt Input Interval: " << input_format_.interval;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000187 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000188}
189
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000190void CoordinatedVideoAdapter::SetInputFormat(const VideoFormat& format) {
191 int previous_width = input_format().width;
192 int previous_height = input_format().height;
193 bool is_resolution_change = previous_width > 0 && format.width > 0 &&
194 (previous_width != format.width ||
195 previous_height != format.height);
196 VideoAdapter::SetInputFormat(format);
197 if (is_resolution_change) {
198 int width, height;
199 // Trigger the adaptation logic again, to potentially reset the adaptation
200 // state for things like view requests that may not longer be capping
201 // output (or may now cap output).
202 AdaptToMinimumFormat(&width, &height);
203 LOG(LS_INFO) << "VAdapt Input Resolution Change: "
204 << "Previous input resolution: "
205 << previous_width << "x" << previous_height
206 << " New input resolution: "
207 << format.width << "x" << format.height
208 << " New output resolution: "
209 << width << "x" << height;
210 }
211}
212
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000213void VideoAdapter::SetOutputFormat(const VideoFormat& format) {
214 talk_base::CritScope cs(&critical_section_);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000215 int64 old_output_interval = output_format_.interval;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000216 output_format_ = format;
217 output_num_pixels_ = output_format_.width * output_format_.height;
218 output_format_.interval = talk_base::_max(
219 output_format_.interval, input_format_.interval);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000220 if (old_output_interval != output_format_.interval) {
wu@webrtc.org0de29502014-02-13 19:54:28 +0000221 LOG(LS_INFO) << "VAdapt Output Interval: " << output_format_.interval;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000222 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000223}
224
225const VideoFormat& VideoAdapter::input_format() {
226 talk_base::CritScope cs(&critical_section_);
227 return input_format_;
228}
229
230const VideoFormat& VideoAdapter::output_format() {
231 talk_base::CritScope cs(&critical_section_);
232 return output_format_;
233}
234
235void VideoAdapter::SetBlackOutput(bool black) {
236 talk_base::CritScope cs(&critical_section_);
237 black_output_ = black;
238}
239
240// Constrain output resolution to this many pixels overall
241void VideoAdapter::SetOutputNumPixels(int num_pixels) {
242 output_num_pixels_ = num_pixels;
243}
244
245int VideoAdapter::GetOutputNumPixels() const {
246 return output_num_pixels_;
247}
248
249// TODO(fbarchard): Add AdaptFrameRate function that only drops frames but
250// not resolution.
251bool VideoAdapter::AdaptFrame(const VideoFrame* in_frame,
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000252 VideoFrame** out_frame) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000253 talk_base::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000254 if (!in_frame || !out_frame) {
255 return false;
256 }
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000257 ++frames_in_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000258
259 // Update input to actual frame dimensions.
mallinath@webrtc.orgab5a0912013-09-07 00:12:57 +0000260 VideoFormat format(static_cast<int>(in_frame->GetWidth()),
261 static_cast<int>(in_frame->GetHeight()),
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000262 input_format_.interval, input_format_.fourcc);
263 SetInputFormat(format);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000264
265 // Drop the input frame if necessary.
266 bool should_drop = false;
267 if (!output_num_pixels_) {
268 // Drop all frames as the output format is 0x0.
269 should_drop = true;
270 } else {
271 // Drop some frames based on input fps and output fps.
272 // Normally output fps is less than input fps.
273 // TODO(fbarchard): Consider adjusting interval to reflect the adjusted
274 // interval between frames after dropping some frames.
275 interval_next_frame_ += input_format_.interval;
276 if (output_format_.interval > 0) {
277 if (interval_next_frame_ >= output_format_.interval) {
278 interval_next_frame_ %= output_format_.interval;
279 } else {
280 should_drop = true;
281 }
282 }
283 }
284 if (should_drop) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000285 // Show VAdapt log every 90 frames dropped. (3 seconds)
wu@webrtc.org0de29502014-02-13 19:54:28 +0000286 // TODO(fbarchard): Consider GetLogSeverity() to change interval to less
287 // for LS_VERBOSE and more for LS_INFO.
288 bool show = (frames_in_ - frames_out_) % 90 == 0;
289
290 if (show) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000291 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
292 // in default calls.
wu@webrtc.org0de29502014-02-13 19:54:28 +0000293 LOG(LS_INFO) << "VAdapt Drop Frame: " << frames_scaled_
294 << " / " << frames_out_
295 << " / " << frames_in_
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000296 << " Changes: " << adaption_changes_
297 << " Input: " << in_frame->GetWidth()
298 << "x" << in_frame->GetHeight()
299 << " i" << input_format_.interval
300 << " Output: i" << output_format_.interval;
301 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000302 *out_frame = NULL;
303 return true;
304 }
305
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000306 float scale = 1.f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000307 if (output_num_pixels_) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000308 scale = VideoAdapter::FindClosestViewScale(
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000309 static_cast<int>(in_frame->GetWidth()),
310 static_cast<int>(in_frame->GetHeight()),
311 output_num_pixels_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000312 output_format_.width = static_cast<int>(in_frame->GetWidth() * scale + .5f);
313 output_format_.height = static_cast<int>(in_frame->GetHeight() * scale +
314 .5f);
315 }
316
317 if (!StretchToOutputFrame(in_frame)) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000318 LOG(LS_VERBOSE) << "VAdapt Stretch Failed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000319 return false;
320 }
321
322 *out_frame = output_frame_.get();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000323
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000324 ++frames_out_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000325 if (in_frame->GetWidth() != (*out_frame)->GetWidth() ||
326 in_frame->GetHeight() != (*out_frame)->GetHeight()) {
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000327 ++frames_scaled_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000328 }
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000329 // Show VAdapt log every 90 frames output. (3 seconds)
330 // TODO(fbarchard): Consider GetLogSeverity() to change interval to less
331 // for LS_VERBOSE and more for LS_INFO.
332 bool show = (frames_out_) % 90 == 0;
333
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000334 // TODO(fbarchard): LOG the previous output resolution and track input
335 // resolution changes as well. Consider dropping the statistics into their
336 // own class which could be queried publically.
337 bool changed = false;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000338 if (previous_width_ && (previous_width_ != (*out_frame)->GetWidth() ||
339 previous_height_ != (*out_frame)->GetHeight())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000340 show = true;
341 ++adaption_changes_;
342 changed = true;
343 }
344 if (show) {
345 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
346 // in default calls.
wu@webrtc.org0de29502014-02-13 19:54:28 +0000347 LOG(LS_INFO) << "VAdapt Frame: " << frames_scaled_
348 << " / " << frames_out_
349 << " / " << frames_in_
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000350 << " Changes: " << adaption_changes_
351 << " Input: " << in_frame->GetWidth()
352 << "x" << in_frame->GetHeight()
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000353 << " i" << input_format_.interval
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000354 << " Scale: " << scale
355 << " Output: " << (*out_frame)->GetWidth()
356 << "x" << (*out_frame)->GetHeight()
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000357 << " i" << output_format_.interval
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000358 << " Changed: " << (changed ? "true" : "false");
359 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000360 previous_width_ = (*out_frame)->GetWidth();
361 previous_height_ = (*out_frame)->GetHeight();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000362
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000363 return true;
364}
365
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000366// Scale or Blacken the frame. Returns true if successful.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000367bool VideoAdapter::StretchToOutputFrame(const VideoFrame* in_frame) {
368 int output_width = output_format_.width;
369 int output_height = output_format_.height;
370
371 // Create and stretch the output frame if it has not been created yet or its
372 // size is not same as the expected.
373 bool stretched = false;
374 if (!output_frame_ ||
375 output_frame_->GetWidth() != static_cast<size_t>(output_width) ||
376 output_frame_->GetHeight() != static_cast<size_t>(output_height)) {
377 output_frame_.reset(
378 in_frame->Stretch(output_width, output_height, true, true));
379 if (!output_frame_) {
380 LOG(LS_WARNING) << "Adapter failed to stretch frame to "
381 << output_width << "x" << output_height;
382 return false;
383 }
384 stretched = true;
385 is_black_ = false;
386 }
387
388 if (!black_output_) {
389 if (!stretched) {
390 // The output frame does not need to be blacken and has not been stretched
391 // from the input frame yet, stretch the input frame. This is the most
392 // common case.
393 in_frame->StretchToFrame(output_frame_.get(), true, true);
394 }
395 is_black_ = false;
396 } else {
397 if (!is_black_) {
398 output_frame_->SetToBlack();
399 is_black_ = true;
400 }
401 output_frame_->SetElapsedTime(in_frame->GetElapsedTime());
402 output_frame_->SetTimeStamp(in_frame->GetTimeStamp());
403 }
404
405 return true;
406}
407
408///////////////////////////////////////////////////////////////////////
409// Implementation of CoordinatedVideoAdapter
410CoordinatedVideoAdapter::CoordinatedVideoAdapter()
wu@webrtc.org9caf2762013-12-11 18:25:07 +0000411 : cpu_adaptation_(true),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000412 cpu_smoothing_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000413 gd_adaptation_(true),
414 view_adaptation_(true),
415 view_switch_(false),
416 cpu_downgrade_count_(0),
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000417 cpu_load_min_samples_(kCpuLoadMinSamples),
418 cpu_load_num_samples_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000419 high_system_threshold_(kHighSystemCpuThreshold),
420 low_system_threshold_(kLowSystemCpuThreshold),
421 process_threshold_(kProcessCpuThreshold),
422 view_desired_num_pixels_(INT_MAX),
423 view_desired_interval_(0),
424 encoder_desired_num_pixels_(INT_MAX),
425 cpu_desired_num_pixels_(INT_MAX),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000426 adapt_reason_(0),
427 system_load_average_(kCpuLoadInitialAverage) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000428}
429
430// Helper function to UPGRADE or DOWNGRADE a number of pixels
431void CoordinatedVideoAdapter::StepPixelCount(
432 CoordinatedVideoAdapter::AdaptRequest request,
433 int* num_pixels) {
434 switch (request) {
435 case CoordinatedVideoAdapter::DOWNGRADE:
436 *num_pixels /= 2;
437 break;
438
439 case CoordinatedVideoAdapter::UPGRADE:
440 *num_pixels *= 2;
441 break;
442
443 default: // No change in pixel count
444 break;
445 }
446 return;
447}
448
449// Find the adaptation request of the cpu based on the load. Return UPGRADE if
450// the load is low, DOWNGRADE if the load is high, and KEEP otherwise.
451CoordinatedVideoAdapter::AdaptRequest CoordinatedVideoAdapter::FindCpuRequest(
452 int current_cpus, int max_cpus,
453 float process_load, float system_load) {
454 // Downgrade if system is high and plugin is at least more than midrange.
455 if (system_load >= high_system_threshold_ * max_cpus &&
456 process_load >= process_threshold_ * current_cpus) {
457 return CoordinatedVideoAdapter::DOWNGRADE;
458 // Upgrade if system is low.
459 } else if (system_load < low_system_threshold_ * max_cpus) {
460 return CoordinatedVideoAdapter::UPGRADE;
461 }
462 return CoordinatedVideoAdapter::KEEP;
463}
464
465// A remote view request for a new resolution.
466void CoordinatedVideoAdapter::OnOutputFormatRequest(const VideoFormat& format) {
467 talk_base::CritScope cs(&request_critical_section_);
468 if (!view_adaptation_) {
469 return;
470 }
471 // Set output for initial aspect ratio in mediachannel unittests.
472 int old_num_pixels = GetOutputNumPixels();
473 SetOutputFormat(format);
474 SetOutputNumPixels(old_num_pixels);
475 view_desired_num_pixels_ = format.width * format.height;
476 view_desired_interval_ = format.interval;
477 int new_width, new_height;
478 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
479 LOG(LS_INFO) << "VAdapt View Request: "
480 << format.width << "x" << format.height
481 << " Pixels: " << view_desired_num_pixels_
482 << " Changed: " << (changed ? "true" : "false")
483 << " To: " << new_width << "x" << new_height;
484}
485
486// A Bandwidth GD request for new resolution
487void CoordinatedVideoAdapter::OnEncoderResolutionRequest(
488 int width, int height, AdaptRequest request) {
489 talk_base::CritScope cs(&request_critical_section_);
490 if (!gd_adaptation_) {
491 return;
492 }
493 int old_encoder_desired_num_pixels = encoder_desired_num_pixels_;
494 if (KEEP != request) {
495 int new_encoder_desired_num_pixels = width * height;
496 int old_num_pixels = GetOutputNumPixels();
497 if (new_encoder_desired_num_pixels != old_num_pixels) {
498 LOG(LS_VERBOSE) << "VAdapt GD resolution stale. Ignored";
499 } else {
500 // Update the encoder desired format based on the request.
501 encoder_desired_num_pixels_ = new_encoder_desired_num_pixels;
502 StepPixelCount(request, &encoder_desired_num_pixels_);
503 }
504 }
505 int new_width, new_height;
506 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
507
508 // Ignore up or keep if no change.
509 if (DOWNGRADE != request && view_switch_ && !changed) {
510 encoder_desired_num_pixels_ = old_encoder_desired_num_pixels;
511 LOG(LS_VERBOSE) << "VAdapt ignoring GD request.";
512 }
513
514 LOG(LS_INFO) << "VAdapt GD Request: "
515 << (DOWNGRADE == request ? "down" :
516 (UPGRADE == request ? "up" : "keep"))
517 << " From: " << width << "x" << height
518 << " Pixels: " << encoder_desired_num_pixels_
519 << " Changed: " << (changed ? "true" : "false")
520 << " To: " << new_width << "x" << new_height;
521}
522
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000523// A Bandwidth GD request for new resolution
524void CoordinatedVideoAdapter::OnCpuResolutionRequest(AdaptRequest request) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000525 talk_base::CritScope cs(&request_critical_section_);
526 if (!cpu_adaptation_) {
527 return;
528 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000529 // Update how many times we have downgraded due to the cpu load.
530 switch (request) {
531 case DOWNGRADE:
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000532 // Ignore downgrades if we have downgraded the maximum times.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000533 if (cpu_downgrade_count_ < kMaxCpuDowngrades) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000534 ++cpu_downgrade_count_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000535 } else {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000536 LOG(LS_VERBOSE) << "VAdapt CPU load high but do not downgrade "
537 "because maximum downgrades reached";
538 SignalCpuAdaptationUnable();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000539 }
540 break;
541 case UPGRADE:
542 if (cpu_downgrade_count_ > 0) {
543 bool is_min = IsMinimumFormat(cpu_desired_num_pixels_);
544 if (is_min) {
545 --cpu_downgrade_count_;
546 } else {
547 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
548 "because cpu is not limiting resolution";
549 }
550 } else {
551 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
552 "because minimum downgrades reached";
553 }
554 break;
555 case KEEP:
556 default:
557 break;
558 }
559 if (KEEP != request) {
560 // TODO(fbarchard): compute stepping up/down from OutputNumPixels but
561 // clamp to inputpixels / 4 (2 steps)
562 cpu_desired_num_pixels_ = cpu_downgrade_count_ == 0 ? INT_MAX :
563 static_cast<int>(input_format().width * input_format().height >>
564 cpu_downgrade_count_);
565 }
566 int new_width, new_height;
567 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
568 LOG(LS_INFO) << "VAdapt CPU Request: "
569 << (DOWNGRADE == request ? "down" :
570 (UPGRADE == request ? "up" : "keep"))
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000571 << " Steps: " << cpu_downgrade_count_
572 << " Changed: " << (changed ? "true" : "false")
573 << " To: " << new_width << "x" << new_height;
574}
575
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000576// A CPU request for new resolution
577// TODO(fbarchard): Move outside adapter.
578void CoordinatedVideoAdapter::OnCpuLoadUpdated(
579 int current_cpus, int max_cpus, float process_load, float system_load) {
580 talk_base::CritScope cs(&request_critical_section_);
581 if (!cpu_adaptation_) {
582 return;
583 }
584 // Update the moving average of system load. Even if we aren't smoothing,
585 // we'll still calculate this information, in case smoothing is later enabled.
586 system_load_average_ = kCpuLoadWeightCoefficient * system_load +
587 (1.0f - kCpuLoadWeightCoefficient) * system_load_average_;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000588 ++cpu_load_num_samples_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000589 if (cpu_smoothing_) {
590 system_load = system_load_average_;
591 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000592 AdaptRequest request = FindCpuRequest(current_cpus, max_cpus,
593 process_load, system_load);
594 // Make sure we're not adapting too quickly.
595 if (request != KEEP) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000596 if (cpu_load_num_samples_ < cpu_load_min_samples_) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000597 LOG(LS_VERBOSE) << "VAdapt CPU load high/low but do not adapt until "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000598 << (cpu_load_min_samples_ - cpu_load_num_samples_)
599 << " more samples";
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000600 request = KEEP;
601 }
602 }
603
604 OnCpuResolutionRequest(request);
605}
606
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000607// Called by cpu adapter on up requests.
608bool CoordinatedVideoAdapter::IsMinimumFormat(int pixels) {
609 // Find closest scale factor that matches input resolution to min_num_pixels
610 // and set that for output resolution. This is not needed for VideoAdapter,
611 // but provides feedback to unittests and users on expected resolution.
612 // Actual resolution is based on input frame.
613 VideoFormat new_output = output_format();
614 VideoFormat input = input_format();
615 if (input_format().IsSize0x0()) {
616 input = new_output;
617 }
618 float scale = 1.0f;
619 if (!input.IsSize0x0()) {
620 scale = FindClosestScale(input.width,
621 input.height,
622 pixels);
623 }
624 new_output.width = static_cast<int>(input.width * scale + .5f);
625 new_output.height = static_cast<int>(input.height * scale + .5f);
626 int new_pixels = new_output.width * new_output.height;
627 int num_pixels = GetOutputNumPixels();
628 return new_pixels <= num_pixels;
629}
630
631// Called by all coordinators when there is a change.
632bool CoordinatedVideoAdapter::AdaptToMinimumFormat(int* new_width,
633 int* new_height) {
634 VideoFormat new_output = output_format();
635 VideoFormat input = input_format();
636 if (input_format().IsSize0x0()) {
637 input = new_output;
638 }
639 int old_num_pixels = GetOutputNumPixels();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000640 int min_num_pixels = INT_MAX;
641 adapt_reason_ = 0;
642
643 // Reduce resolution based on encoder bandwidth (GD).
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000644 if (encoder_desired_num_pixels_ &&
645 (encoder_desired_num_pixels_ < min_num_pixels)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000646 adapt_reason_ |= ADAPTREASON_BANDWIDTH;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000647 min_num_pixels = encoder_desired_num_pixels_;
648 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000649 // Reduce resolution based on CPU.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000650 if (cpu_adaptation_ && cpu_desired_num_pixels_ &&
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000651 (cpu_desired_num_pixels_ <= min_num_pixels)) {
652 if (cpu_desired_num_pixels_ < min_num_pixels) {
653 adapt_reason_ = ADAPTREASON_CPU;
654 } else {
655 adapt_reason_ |= ADAPTREASON_CPU;
656 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000657 min_num_pixels = cpu_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000658 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000659 // Round resolution for GD or CPU to allow 1/2 to map to 9/16.
660 if (!input.IsSize0x0() && min_num_pixels != INT_MAX) {
661 float scale = FindClosestScale(input.width, input.height, min_num_pixels);
662 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
663 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000664 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000665 // Reduce resolution based on View Request.
666 if (view_desired_num_pixels_ <= min_num_pixels) {
667 if (view_desired_num_pixels_ < min_num_pixels) {
668 adapt_reason_ = ADAPTREASON_VIEW;
669 } else {
670 adapt_reason_ |= ADAPTREASON_VIEW;
671 }
672 min_num_pixels = view_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000673 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000674 // Snap to a scale factor.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000675 float scale = 1.0f;
676 if (!input.IsSize0x0()) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000677 scale = FindLowerScale(input.width, input.height, min_num_pixels);
678 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
679 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000680 }
681 if (scale == 1.0f) {
682 adapt_reason_ = 0;
683 }
684 *new_width = new_output.width = static_cast<int>(input.width * scale + .5f);
685 *new_height = new_output.height = static_cast<int>(input.height * scale +
686 .5f);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000687 SetOutputNumPixels(min_num_pixels);
688
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689 new_output.interval = view_desired_interval_;
690 SetOutputFormat(new_output);
691 int new_num_pixels = GetOutputNumPixels();
692 bool changed = new_num_pixels != old_num_pixels;
693
694 static const char* kReasons[8] = {
695 "None",
696 "CPU",
697 "BANDWIDTH",
698 "CPU+BANDWIDTH",
699 "VIEW",
700 "CPU+VIEW",
701 "BANDWIDTH+VIEW",
702 "CPU+BANDWIDTH+VIEW",
703 };
704
705 LOG(LS_VERBOSE) << "VAdapt Status View: " << view_desired_num_pixels_
706 << " GD: " << encoder_desired_num_pixels_
707 << " CPU: " << cpu_desired_num_pixels_
708 << " Pixels: " << min_num_pixels
709 << " Input: " << input.width
710 << "x" << input.height
711 << " Scale: " << scale
712 << " Resolution: " << new_output.width
713 << "x" << new_output.height
714 << " Changed: " << (changed ? "true" : "false")
715 << " Reason: " << kReasons[adapt_reason_];
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000716
717 if (changed) {
718 // When any adaptation occurs, historic CPU load levels are no longer
719 // accurate. Clear out our state so we can re-learn at the new normal.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000720 cpu_load_num_samples_ = 0;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000721 system_load_average_ = kCpuLoadInitialAverage;
722 }
723
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000724 return changed;
725}
726
727} // namespace cricket