blob: 3cd6cac96c878f4243cd766619a4032ffc93ca9e [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),
165 frames_(0),
166 adapted_frames_(0),
167 adaption_changes_(0),
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000168 previous_width_(0),
169 previous_height_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000170 black_output_(false),
171 is_black_(false),
172 interval_next_frame_(0) {
173}
174
175VideoAdapter::~VideoAdapter() {
176}
177
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000178void VideoAdapter::SetInputFormat(const VideoFormat& format) {
179 talk_base::CritScope cs(&critical_section_);
180 input_format_ = format;
181 output_format_.interval = talk_base::_max(
182 output_format_.interval, input_format_.interval);
183}
184
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000185void CoordinatedVideoAdapter::SetInputFormat(const VideoFormat& format) {
186 int previous_width = input_format().width;
187 int previous_height = input_format().height;
188 bool is_resolution_change = previous_width > 0 && format.width > 0 &&
189 (previous_width != format.width ||
190 previous_height != format.height);
191 VideoAdapter::SetInputFormat(format);
192 if (is_resolution_change) {
193 int width, height;
194 // Trigger the adaptation logic again, to potentially reset the adaptation
195 // state for things like view requests that may not longer be capping
196 // output (or may now cap output).
197 AdaptToMinimumFormat(&width, &height);
198 LOG(LS_INFO) << "VAdapt Input Resolution Change: "
199 << "Previous input resolution: "
200 << previous_width << "x" << previous_height
201 << " New input resolution: "
202 << format.width << "x" << format.height
203 << " New output resolution: "
204 << width << "x" << height;
205 }
206}
207
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000208void VideoAdapter::SetOutputFormat(const VideoFormat& format) {
209 talk_base::CritScope cs(&critical_section_);
210 output_format_ = format;
211 output_num_pixels_ = output_format_.width * output_format_.height;
212 output_format_.interval = talk_base::_max(
213 output_format_.interval, input_format_.interval);
214}
215
216const VideoFormat& VideoAdapter::input_format() {
217 talk_base::CritScope cs(&critical_section_);
218 return input_format_;
219}
220
221const VideoFormat& VideoAdapter::output_format() {
222 talk_base::CritScope cs(&critical_section_);
223 return output_format_;
224}
225
226void VideoAdapter::SetBlackOutput(bool black) {
227 talk_base::CritScope cs(&critical_section_);
228 black_output_ = black;
229}
230
231// Constrain output resolution to this many pixels overall
232void VideoAdapter::SetOutputNumPixels(int num_pixels) {
233 output_num_pixels_ = num_pixels;
234}
235
236int VideoAdapter::GetOutputNumPixels() const {
237 return output_num_pixels_;
238}
239
240// TODO(fbarchard): Add AdaptFrameRate function that only drops frames but
241// not resolution.
242bool VideoAdapter::AdaptFrame(const VideoFrame* in_frame,
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000243 VideoFrame** out_frame) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000244 talk_base::CritScope cs(&critical_section_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000245 if (!in_frame || !out_frame) {
246 return false;
247 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000248 ++frames_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000249
250 // Update input to actual frame dimensions.
mallinath@webrtc.orgab5a0912013-09-07 00:12:57 +0000251 VideoFormat format(static_cast<int>(in_frame->GetWidth()),
252 static_cast<int>(in_frame->GetHeight()),
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000253 input_format_.interval, input_format_.fourcc);
254 SetInputFormat(format);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000255
256 // Drop the input frame if necessary.
257 bool should_drop = false;
258 if (!output_num_pixels_) {
259 // Drop all frames as the output format is 0x0.
260 should_drop = true;
261 } else {
262 // Drop some frames based on input fps and output fps.
263 // Normally output fps is less than input fps.
264 // TODO(fbarchard): Consider adjusting interval to reflect the adjusted
265 // interval between frames after dropping some frames.
266 interval_next_frame_ += input_format_.interval;
267 if (output_format_.interval > 0) {
268 if (interval_next_frame_ >= output_format_.interval) {
269 interval_next_frame_ %= output_format_.interval;
270 } else {
271 should_drop = true;
272 }
273 }
274 }
275 if (should_drop) {
276 *out_frame = NULL;
277 return true;
278 }
279
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000280 float scale = 1.f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000281 if (output_num_pixels_) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000282 scale = VideoAdapter::FindClosestViewScale(
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000283 static_cast<int>(in_frame->GetWidth()),
284 static_cast<int>(in_frame->GetHeight()),
285 output_num_pixels_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000286 output_format_.width = static_cast<int>(in_frame->GetWidth() * scale + .5f);
287 output_format_.height = static_cast<int>(in_frame->GetHeight() * scale +
288 .5f);
289 }
290
291 if (!StretchToOutputFrame(in_frame)) {
292 return false;
293 }
294
295 *out_frame = output_frame_.get();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000296
297 // Show VAdapt log every 300 frames. (10 seconds)
298 // TODO(fbarchard): Consider GetLogSeverity() to change interval to less
299 // for LS_VERBOSE and more for LS_INFO.
300 bool show = frames_ % 300 == 0;
301 if (in_frame->GetWidth() != (*out_frame)->GetWidth() ||
302 in_frame->GetHeight() != (*out_frame)->GetHeight()) {
303 ++adapted_frames_;
304 }
305 // TODO(fbarchard): LOG the previous output resolution and track input
306 // resolution changes as well. Consider dropping the statistics into their
307 // own class which could be queried publically.
308 bool changed = false;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000309 if (previous_width_ && (previous_width_ != (*out_frame)->GetWidth() ||
310 previous_height_ != (*out_frame)->GetHeight())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000311 show = true;
312 ++adaption_changes_;
313 changed = true;
314 }
315 if (show) {
316 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
317 // in default calls.
318 LOG(LS_INFO) << "VAdapt Frame: " << adapted_frames_
319 << " / " << frames_
320 << " Changes: " << adaption_changes_
321 << " Input: " << in_frame->GetWidth()
322 << "x" << in_frame->GetHeight()
323 << " Scale: " << scale
324 << " Output: " << (*out_frame)->GetWidth()
325 << "x" << (*out_frame)->GetHeight()
326 << " Changed: " << (changed ? "true" : "false");
327 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000328 previous_width_ = (*out_frame)->GetWidth();
329 previous_height_ = (*out_frame)->GetHeight();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000330
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000331 return true;
332}
333
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000334// Scale or Blacken the frame. Returns true if successful.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000335bool VideoAdapter::StretchToOutputFrame(const VideoFrame* in_frame) {
336 int output_width = output_format_.width;
337 int output_height = output_format_.height;
338
339 // Create and stretch the output frame if it has not been created yet or its
340 // size is not same as the expected.
341 bool stretched = false;
342 if (!output_frame_ ||
343 output_frame_->GetWidth() != static_cast<size_t>(output_width) ||
344 output_frame_->GetHeight() != static_cast<size_t>(output_height)) {
345 output_frame_.reset(
346 in_frame->Stretch(output_width, output_height, true, true));
347 if (!output_frame_) {
348 LOG(LS_WARNING) << "Adapter failed to stretch frame to "
349 << output_width << "x" << output_height;
350 return false;
351 }
352 stretched = true;
353 is_black_ = false;
354 }
355
356 if (!black_output_) {
357 if (!stretched) {
358 // The output frame does not need to be blacken and has not been stretched
359 // from the input frame yet, stretch the input frame. This is the most
360 // common case.
361 in_frame->StretchToFrame(output_frame_.get(), true, true);
362 }
363 is_black_ = false;
364 } else {
365 if (!is_black_) {
366 output_frame_->SetToBlack();
367 is_black_ = true;
368 }
369 output_frame_->SetElapsedTime(in_frame->GetElapsedTime());
370 output_frame_->SetTimeStamp(in_frame->GetTimeStamp());
371 }
372
373 return true;
374}
375
376///////////////////////////////////////////////////////////////////////
377// Implementation of CoordinatedVideoAdapter
378CoordinatedVideoAdapter::CoordinatedVideoAdapter()
wu@webrtc.org9caf2762013-12-11 18:25:07 +0000379 : cpu_adaptation_(true),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000380 cpu_smoothing_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000381 gd_adaptation_(true),
382 view_adaptation_(true),
383 view_switch_(false),
384 cpu_downgrade_count_(0),
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000385 cpu_load_min_samples_(kCpuLoadMinSamples),
386 cpu_load_num_samples_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000387 high_system_threshold_(kHighSystemCpuThreshold),
388 low_system_threshold_(kLowSystemCpuThreshold),
389 process_threshold_(kProcessCpuThreshold),
390 view_desired_num_pixels_(INT_MAX),
391 view_desired_interval_(0),
392 encoder_desired_num_pixels_(INT_MAX),
393 cpu_desired_num_pixels_(INT_MAX),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000394 adapt_reason_(0),
395 system_load_average_(kCpuLoadInitialAverage) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000396}
397
398// Helper function to UPGRADE or DOWNGRADE a number of pixels
399void CoordinatedVideoAdapter::StepPixelCount(
400 CoordinatedVideoAdapter::AdaptRequest request,
401 int* num_pixels) {
402 switch (request) {
403 case CoordinatedVideoAdapter::DOWNGRADE:
404 *num_pixels /= 2;
405 break;
406
407 case CoordinatedVideoAdapter::UPGRADE:
408 *num_pixels *= 2;
409 break;
410
411 default: // No change in pixel count
412 break;
413 }
414 return;
415}
416
417// Find the adaptation request of the cpu based on the load. Return UPGRADE if
418// the load is low, DOWNGRADE if the load is high, and KEEP otherwise.
419CoordinatedVideoAdapter::AdaptRequest CoordinatedVideoAdapter::FindCpuRequest(
420 int current_cpus, int max_cpus,
421 float process_load, float system_load) {
422 // Downgrade if system is high and plugin is at least more than midrange.
423 if (system_load >= high_system_threshold_ * max_cpus &&
424 process_load >= process_threshold_ * current_cpus) {
425 return CoordinatedVideoAdapter::DOWNGRADE;
426 // Upgrade if system is low.
427 } else if (system_load < low_system_threshold_ * max_cpus) {
428 return CoordinatedVideoAdapter::UPGRADE;
429 }
430 return CoordinatedVideoAdapter::KEEP;
431}
432
433// A remote view request for a new resolution.
434void CoordinatedVideoAdapter::OnOutputFormatRequest(const VideoFormat& format) {
435 talk_base::CritScope cs(&request_critical_section_);
436 if (!view_adaptation_) {
437 return;
438 }
439 // Set output for initial aspect ratio in mediachannel unittests.
440 int old_num_pixels = GetOutputNumPixels();
441 SetOutputFormat(format);
442 SetOutputNumPixels(old_num_pixels);
443 view_desired_num_pixels_ = format.width * format.height;
444 view_desired_interval_ = format.interval;
445 int new_width, new_height;
446 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
447 LOG(LS_INFO) << "VAdapt View Request: "
448 << format.width << "x" << format.height
449 << " Pixels: " << view_desired_num_pixels_
450 << " Changed: " << (changed ? "true" : "false")
451 << " To: " << new_width << "x" << new_height;
452}
453
454// A Bandwidth GD request for new resolution
455void CoordinatedVideoAdapter::OnEncoderResolutionRequest(
456 int width, int height, AdaptRequest request) {
457 talk_base::CritScope cs(&request_critical_section_);
458 if (!gd_adaptation_) {
459 return;
460 }
461 int old_encoder_desired_num_pixels = encoder_desired_num_pixels_;
462 if (KEEP != request) {
463 int new_encoder_desired_num_pixels = width * height;
464 int old_num_pixels = GetOutputNumPixels();
465 if (new_encoder_desired_num_pixels != old_num_pixels) {
466 LOG(LS_VERBOSE) << "VAdapt GD resolution stale. Ignored";
467 } else {
468 // Update the encoder desired format based on the request.
469 encoder_desired_num_pixels_ = new_encoder_desired_num_pixels;
470 StepPixelCount(request, &encoder_desired_num_pixels_);
471 }
472 }
473 int new_width, new_height;
474 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
475
476 // Ignore up or keep if no change.
477 if (DOWNGRADE != request && view_switch_ && !changed) {
478 encoder_desired_num_pixels_ = old_encoder_desired_num_pixels;
479 LOG(LS_VERBOSE) << "VAdapt ignoring GD request.";
480 }
481
482 LOG(LS_INFO) << "VAdapt GD Request: "
483 << (DOWNGRADE == request ? "down" :
484 (UPGRADE == request ? "up" : "keep"))
485 << " From: " << width << "x" << height
486 << " Pixels: " << encoder_desired_num_pixels_
487 << " Changed: " << (changed ? "true" : "false")
488 << " To: " << new_width << "x" << new_height;
489}
490
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000491// A Bandwidth GD request for new resolution
492void CoordinatedVideoAdapter::OnCpuResolutionRequest(AdaptRequest request) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000493 talk_base::CritScope cs(&request_critical_section_);
494 if (!cpu_adaptation_) {
495 return;
496 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000497 // Update how many times we have downgraded due to the cpu load.
498 switch (request) {
499 case DOWNGRADE:
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000500 // Ignore downgrades if we have downgraded the maximum times.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000501 if (cpu_downgrade_count_ < kMaxCpuDowngrades) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000502 ++cpu_downgrade_count_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000503 } else {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000504 LOG(LS_VERBOSE) << "VAdapt CPU load high but do not downgrade "
505 "because maximum downgrades reached";
506 SignalCpuAdaptationUnable();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000507 }
508 break;
509 case UPGRADE:
510 if (cpu_downgrade_count_ > 0) {
511 bool is_min = IsMinimumFormat(cpu_desired_num_pixels_);
512 if (is_min) {
513 --cpu_downgrade_count_;
514 } else {
515 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
516 "because cpu is not limiting resolution";
517 }
518 } else {
519 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
520 "because minimum downgrades reached";
521 }
522 break;
523 case KEEP:
524 default:
525 break;
526 }
527 if (KEEP != request) {
528 // TODO(fbarchard): compute stepping up/down from OutputNumPixels but
529 // clamp to inputpixels / 4 (2 steps)
530 cpu_desired_num_pixels_ = cpu_downgrade_count_ == 0 ? INT_MAX :
531 static_cast<int>(input_format().width * input_format().height >>
532 cpu_downgrade_count_);
533 }
534 int new_width, new_height;
535 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
536 LOG(LS_INFO) << "VAdapt CPU Request: "
537 << (DOWNGRADE == request ? "down" :
538 (UPGRADE == request ? "up" : "keep"))
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000539 << " Steps: " << cpu_downgrade_count_
540 << " Changed: " << (changed ? "true" : "false")
541 << " To: " << new_width << "x" << new_height;
542}
543
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000544// A CPU request for new resolution
545// TODO(fbarchard): Move outside adapter.
546void CoordinatedVideoAdapter::OnCpuLoadUpdated(
547 int current_cpus, int max_cpus, float process_load, float system_load) {
548 talk_base::CritScope cs(&request_critical_section_);
549 if (!cpu_adaptation_) {
550 return;
551 }
552 // Update the moving average of system load. Even if we aren't smoothing,
553 // we'll still calculate this information, in case smoothing is later enabled.
554 system_load_average_ = kCpuLoadWeightCoefficient * system_load +
555 (1.0f - kCpuLoadWeightCoefficient) * system_load_average_;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000556 ++cpu_load_num_samples_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000557 if (cpu_smoothing_) {
558 system_load = system_load_average_;
559 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000560 AdaptRequest request = FindCpuRequest(current_cpus, max_cpus,
561 process_load, system_load);
562 // Make sure we're not adapting too quickly.
563 if (request != KEEP) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000564 if (cpu_load_num_samples_ < cpu_load_min_samples_) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000565 LOG(LS_VERBOSE) << "VAdapt CPU load high/low but do not adapt until "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000566 << (cpu_load_min_samples_ - cpu_load_num_samples_)
567 << " more samples";
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000568 request = KEEP;
569 }
570 }
571
572 OnCpuResolutionRequest(request);
573}
574
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000575// Called by cpu adapter on up requests.
576bool CoordinatedVideoAdapter::IsMinimumFormat(int pixels) {
577 // Find closest scale factor that matches input resolution to min_num_pixels
578 // and set that for output resolution. This is not needed for VideoAdapter,
579 // but provides feedback to unittests and users on expected resolution.
580 // Actual resolution is based on input frame.
581 VideoFormat new_output = output_format();
582 VideoFormat input = input_format();
583 if (input_format().IsSize0x0()) {
584 input = new_output;
585 }
586 float scale = 1.0f;
587 if (!input.IsSize0x0()) {
588 scale = FindClosestScale(input.width,
589 input.height,
590 pixels);
591 }
592 new_output.width = static_cast<int>(input.width * scale + .5f);
593 new_output.height = static_cast<int>(input.height * scale + .5f);
594 int new_pixels = new_output.width * new_output.height;
595 int num_pixels = GetOutputNumPixels();
596 return new_pixels <= num_pixels;
597}
598
599// Called by all coordinators when there is a change.
600bool CoordinatedVideoAdapter::AdaptToMinimumFormat(int* new_width,
601 int* new_height) {
602 VideoFormat new_output = output_format();
603 VideoFormat input = input_format();
604 if (input_format().IsSize0x0()) {
605 input = new_output;
606 }
607 int old_num_pixels = GetOutputNumPixels();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000608 int min_num_pixels = INT_MAX;
609 adapt_reason_ = 0;
610
611 // Reduce resolution based on encoder bandwidth (GD).
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000612 if (encoder_desired_num_pixels_ &&
613 (encoder_desired_num_pixels_ < min_num_pixels)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000614 adapt_reason_ |= ADAPTREASON_BANDWIDTH;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000615 min_num_pixels = encoder_desired_num_pixels_;
616 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000617 // Reduce resolution based on CPU.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000618 if (cpu_adaptation_ && cpu_desired_num_pixels_ &&
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000619 (cpu_desired_num_pixels_ <= min_num_pixels)) {
620 if (cpu_desired_num_pixels_ < min_num_pixels) {
621 adapt_reason_ = ADAPTREASON_CPU;
622 } else {
623 adapt_reason_ |= ADAPTREASON_CPU;
624 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000625 min_num_pixels = cpu_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000626 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000627 // Round resolution for GD or CPU to allow 1/2 to map to 9/16.
628 if (!input.IsSize0x0() && min_num_pixels != INT_MAX) {
629 float scale = FindClosestScale(input.width, input.height, min_num_pixels);
630 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
631 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000632 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000633 // Reduce resolution based on View Request.
634 if (view_desired_num_pixels_ <= min_num_pixels) {
635 if (view_desired_num_pixels_ < min_num_pixels) {
636 adapt_reason_ = ADAPTREASON_VIEW;
637 } else {
638 adapt_reason_ |= ADAPTREASON_VIEW;
639 }
640 min_num_pixels = view_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000641 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000642 // Snap to a scale factor.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000643 float scale = 1.0f;
644 if (!input.IsSize0x0()) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000645 scale = FindLowerScale(input.width, input.height, min_num_pixels);
646 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
647 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000648 }
649 if (scale == 1.0f) {
650 adapt_reason_ = 0;
651 }
652 *new_width = new_output.width = static_cast<int>(input.width * scale + .5f);
653 *new_height = new_output.height = static_cast<int>(input.height * scale +
654 .5f);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000655 SetOutputNumPixels(min_num_pixels);
656
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000657 new_output.interval = view_desired_interval_;
658 SetOutputFormat(new_output);
659 int new_num_pixels = GetOutputNumPixels();
660 bool changed = new_num_pixels != old_num_pixels;
661
662 static const char* kReasons[8] = {
663 "None",
664 "CPU",
665 "BANDWIDTH",
666 "CPU+BANDWIDTH",
667 "VIEW",
668 "CPU+VIEW",
669 "BANDWIDTH+VIEW",
670 "CPU+BANDWIDTH+VIEW",
671 };
672
673 LOG(LS_VERBOSE) << "VAdapt Status View: " << view_desired_num_pixels_
674 << " GD: " << encoder_desired_num_pixels_
675 << " CPU: " << cpu_desired_num_pixels_
676 << " Pixels: " << min_num_pixels
677 << " Input: " << input.width
678 << "x" << input.height
679 << " Scale: " << scale
680 << " Resolution: " << new_output.width
681 << "x" << new_output.height
682 << " Changed: " << (changed ? "true" : "false")
683 << " Reason: " << kReasons[adapt_reason_];
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000684
685 if (changed) {
686 // When any adaptation occurs, historic CPU load levels are no longer
687 // accurate. Clear out our state so we can re-learn at the new normal.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000688 cpu_load_num_samples_ = 0;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000689 system_load_average_ = kCpuLoadInitialAverage;
690 }
691
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000692 return changed;
693}
694
695} // namespace cricket