blob: 21da78a4d105d2a4d02ece3e6c194a213629d4b9 [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.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +000039// The number of milliseconds of data to require before acting on cpu sampling
40// information.
41static const size_t kCpuLoadMinSampleTime = 5000;
42// 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),
168 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
178void VideoAdapter::SetInputFormat(const VideoFrame& in_frame) {
179 talk_base::CritScope cs(&critical_section_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000180 input_format_.width = static_cast<int>(in_frame.GetWidth());
181 input_format_.height = static_cast<int>(in_frame.GetHeight());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000182}
183
184void VideoAdapter::SetInputFormat(const VideoFormat& format) {
185 talk_base::CritScope cs(&critical_section_);
186 input_format_ = format;
187 output_format_.interval = talk_base::_max(
188 output_format_.interval, input_format_.interval);
189}
190
191void VideoAdapter::SetOutputFormat(const VideoFormat& format) {
192 talk_base::CritScope cs(&critical_section_);
193 output_format_ = format;
194 output_num_pixels_ = output_format_.width * output_format_.height;
195 output_format_.interval = talk_base::_max(
196 output_format_.interval, input_format_.interval);
197}
198
199const VideoFormat& VideoAdapter::input_format() {
200 talk_base::CritScope cs(&critical_section_);
201 return input_format_;
202}
203
204const VideoFormat& VideoAdapter::output_format() {
205 talk_base::CritScope cs(&critical_section_);
206 return output_format_;
207}
208
209void VideoAdapter::SetBlackOutput(bool black) {
210 talk_base::CritScope cs(&critical_section_);
211 black_output_ = black;
212}
213
214// Constrain output resolution to this many pixels overall
215void VideoAdapter::SetOutputNumPixels(int num_pixels) {
216 output_num_pixels_ = num_pixels;
217}
218
219int VideoAdapter::GetOutputNumPixels() const {
220 return output_num_pixels_;
221}
222
223// TODO(fbarchard): Add AdaptFrameRate function that only drops frames but
224// not resolution.
225bool VideoAdapter::AdaptFrame(const VideoFrame* in_frame,
226 const VideoFrame** out_frame) {
227 talk_base::CritScope cs(&critical_section_);
228 if (!in_frame || !out_frame) {
229 return false;
230 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000231 ++frames_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000232
233 // Update input to actual frame dimensions.
234 SetInputFormat(*in_frame);
235
236 // Drop the input frame if necessary.
237 bool should_drop = false;
238 if (!output_num_pixels_) {
239 // Drop all frames as the output format is 0x0.
240 should_drop = true;
241 } else {
242 // Drop some frames based on input fps and output fps.
243 // Normally output fps is less than input fps.
244 // TODO(fbarchard): Consider adjusting interval to reflect the adjusted
245 // interval between frames after dropping some frames.
246 interval_next_frame_ += input_format_.interval;
247 if (output_format_.interval > 0) {
248 if (interval_next_frame_ >= output_format_.interval) {
249 interval_next_frame_ %= output_format_.interval;
250 } else {
251 should_drop = true;
252 }
253 }
254 }
255 if (should_drop) {
256 *out_frame = NULL;
257 return true;
258 }
259
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000260 float scale = 1.f;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000261 if (output_num_pixels_) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000262 scale = VideoAdapter::FindClosestViewScale(
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000263 static_cast<int>(in_frame->GetWidth()),
264 static_cast<int>(in_frame->GetHeight()),
265 output_num_pixels_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000266 output_format_.width = static_cast<int>(in_frame->GetWidth() * scale + .5f);
267 output_format_.height = static_cast<int>(in_frame->GetHeight() * scale +
268 .5f);
269 }
270
271 if (!StretchToOutputFrame(in_frame)) {
272 return false;
273 }
274
275 *out_frame = output_frame_.get();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000276
277 // Show VAdapt log every 300 frames. (10 seconds)
278 // TODO(fbarchard): Consider GetLogSeverity() to change interval to less
279 // for LS_VERBOSE and more for LS_INFO.
280 bool show = frames_ % 300 == 0;
281 if (in_frame->GetWidth() != (*out_frame)->GetWidth() ||
282 in_frame->GetHeight() != (*out_frame)->GetHeight()) {
283 ++adapted_frames_;
284 }
285 // TODO(fbarchard): LOG the previous output resolution and track input
286 // resolution changes as well. Consider dropping the statistics into their
287 // own class which could be queried publically.
288 bool changed = false;
289 if (previous_width && (previous_width != (*out_frame)->GetWidth() ||
290 previous_height != (*out_frame)->GetHeight())) {
291 show = true;
292 ++adaption_changes_;
293 changed = true;
294 }
295 if (show) {
296 // TODO(fbarchard): Reduce to LS_VERBOSE when adapter info is not needed
297 // in default calls.
298 LOG(LS_INFO) << "VAdapt Frame: " << adapted_frames_
299 << " / " << frames_
300 << " Changes: " << adaption_changes_
301 << " Input: " << in_frame->GetWidth()
302 << "x" << in_frame->GetHeight()
303 << " Scale: " << scale
304 << " Output: " << (*out_frame)->GetWidth()
305 << "x" << (*out_frame)->GetHeight()
306 << " Changed: " << (changed ? "true" : "false");
307 }
308 previous_width = (*out_frame)->GetWidth();
309 previous_height = (*out_frame)->GetHeight();
310
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000311 return true;
312}
313
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000314// Scale or Blacken the frame. Returns true if successful.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000315bool VideoAdapter::StretchToOutputFrame(const VideoFrame* in_frame) {
316 int output_width = output_format_.width;
317 int output_height = output_format_.height;
318
319 // Create and stretch the output frame if it has not been created yet or its
320 // size is not same as the expected.
321 bool stretched = false;
322 if (!output_frame_ ||
323 output_frame_->GetWidth() != static_cast<size_t>(output_width) ||
324 output_frame_->GetHeight() != static_cast<size_t>(output_height)) {
325 output_frame_.reset(
326 in_frame->Stretch(output_width, output_height, true, true));
327 if (!output_frame_) {
328 LOG(LS_WARNING) << "Adapter failed to stretch frame to "
329 << output_width << "x" << output_height;
330 return false;
331 }
332 stretched = true;
333 is_black_ = false;
334 }
335
336 if (!black_output_) {
337 if (!stretched) {
338 // The output frame does not need to be blacken and has not been stretched
339 // from the input frame yet, stretch the input frame. This is the most
340 // common case.
341 in_frame->StretchToFrame(output_frame_.get(), true, true);
342 }
343 is_black_ = false;
344 } else {
345 if (!is_black_) {
346 output_frame_->SetToBlack();
347 is_black_ = true;
348 }
349 output_frame_->SetElapsedTime(in_frame->GetElapsedTime());
350 output_frame_->SetTimeStamp(in_frame->GetTimeStamp());
351 }
352
353 return true;
354}
355
356///////////////////////////////////////////////////////////////////////
357// Implementation of CoordinatedVideoAdapter
358CoordinatedVideoAdapter::CoordinatedVideoAdapter()
359 : cpu_adaptation_(false),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000360 cpu_smoothing_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000361 gd_adaptation_(true),
362 view_adaptation_(true),
363 view_switch_(false),
364 cpu_downgrade_count_(0),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000365 cpu_adapt_wait_time_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000366 high_system_threshold_(kHighSystemCpuThreshold),
367 low_system_threshold_(kLowSystemCpuThreshold),
368 process_threshold_(kProcessCpuThreshold),
369 view_desired_num_pixels_(INT_MAX),
370 view_desired_interval_(0),
371 encoder_desired_num_pixels_(INT_MAX),
372 cpu_desired_num_pixels_(INT_MAX),
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000373 adapt_reason_(0),
374 system_load_average_(kCpuLoadInitialAverage) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000375}
376
377// Helper function to UPGRADE or DOWNGRADE a number of pixels
378void CoordinatedVideoAdapter::StepPixelCount(
379 CoordinatedVideoAdapter::AdaptRequest request,
380 int* num_pixels) {
381 switch (request) {
382 case CoordinatedVideoAdapter::DOWNGRADE:
383 *num_pixels /= 2;
384 break;
385
386 case CoordinatedVideoAdapter::UPGRADE:
387 *num_pixels *= 2;
388 break;
389
390 default: // No change in pixel count
391 break;
392 }
393 return;
394}
395
396// Find the adaptation request of the cpu based on the load. Return UPGRADE if
397// the load is low, DOWNGRADE if the load is high, and KEEP otherwise.
398CoordinatedVideoAdapter::AdaptRequest CoordinatedVideoAdapter::FindCpuRequest(
399 int current_cpus, int max_cpus,
400 float process_load, float system_load) {
401 // Downgrade if system is high and plugin is at least more than midrange.
402 if (system_load >= high_system_threshold_ * max_cpus &&
403 process_load >= process_threshold_ * current_cpus) {
404 return CoordinatedVideoAdapter::DOWNGRADE;
405 // Upgrade if system is low.
406 } else if (system_load < low_system_threshold_ * max_cpus) {
407 return CoordinatedVideoAdapter::UPGRADE;
408 }
409 return CoordinatedVideoAdapter::KEEP;
410}
411
412// A remote view request for a new resolution.
413void CoordinatedVideoAdapter::OnOutputFormatRequest(const VideoFormat& format) {
414 talk_base::CritScope cs(&request_critical_section_);
415 if (!view_adaptation_) {
416 return;
417 }
418 // Set output for initial aspect ratio in mediachannel unittests.
419 int old_num_pixels = GetOutputNumPixels();
420 SetOutputFormat(format);
421 SetOutputNumPixels(old_num_pixels);
422 view_desired_num_pixels_ = format.width * format.height;
423 view_desired_interval_ = format.interval;
424 int new_width, new_height;
425 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
426 LOG(LS_INFO) << "VAdapt View Request: "
427 << format.width << "x" << format.height
428 << " Pixels: " << view_desired_num_pixels_
429 << " Changed: " << (changed ? "true" : "false")
430 << " To: " << new_width << "x" << new_height;
431}
432
433// A Bandwidth GD request for new resolution
434void CoordinatedVideoAdapter::OnEncoderResolutionRequest(
435 int width, int height, AdaptRequest request) {
436 talk_base::CritScope cs(&request_critical_section_);
437 if (!gd_adaptation_) {
438 return;
439 }
440 int old_encoder_desired_num_pixels = encoder_desired_num_pixels_;
441 if (KEEP != request) {
442 int new_encoder_desired_num_pixels = width * height;
443 int old_num_pixels = GetOutputNumPixels();
444 if (new_encoder_desired_num_pixels != old_num_pixels) {
445 LOG(LS_VERBOSE) << "VAdapt GD resolution stale. Ignored";
446 } else {
447 // Update the encoder desired format based on the request.
448 encoder_desired_num_pixels_ = new_encoder_desired_num_pixels;
449 StepPixelCount(request, &encoder_desired_num_pixels_);
450 }
451 }
452 int new_width, new_height;
453 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
454
455 // Ignore up or keep if no change.
456 if (DOWNGRADE != request && view_switch_ && !changed) {
457 encoder_desired_num_pixels_ = old_encoder_desired_num_pixels;
458 LOG(LS_VERBOSE) << "VAdapt ignoring GD request.";
459 }
460
461 LOG(LS_INFO) << "VAdapt GD Request: "
462 << (DOWNGRADE == request ? "down" :
463 (UPGRADE == request ? "up" : "keep"))
464 << " From: " << width << "x" << height
465 << " Pixels: " << encoder_desired_num_pixels_
466 << " Changed: " << (changed ? "true" : "false")
467 << " To: " << new_width << "x" << new_height;
468}
469
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000470// A Bandwidth GD request for new resolution
471void CoordinatedVideoAdapter::OnCpuResolutionRequest(AdaptRequest request) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000472 talk_base::CritScope cs(&request_critical_section_);
473 if (!cpu_adaptation_) {
474 return;
475 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000476 // Update how many times we have downgraded due to the cpu load.
477 switch (request) {
478 case DOWNGRADE:
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000479 // Ignore downgrades if we have downgraded the maximum times.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000480 if (cpu_downgrade_count_ < kMaxCpuDowngrades) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000481 ++cpu_downgrade_count_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000482 } else {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000483 LOG(LS_VERBOSE) << "VAdapt CPU load high but do not downgrade "
484 "because maximum downgrades reached";
485 SignalCpuAdaptationUnable();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000486 }
487 break;
488 case UPGRADE:
489 if (cpu_downgrade_count_ > 0) {
490 bool is_min = IsMinimumFormat(cpu_desired_num_pixels_);
491 if (is_min) {
492 --cpu_downgrade_count_;
493 } else {
494 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
495 "because cpu is not limiting resolution";
496 }
497 } else {
498 LOG(LS_VERBOSE) << "VAdapt CPU load low but do not upgrade "
499 "because minimum downgrades reached";
500 }
501 break;
502 case KEEP:
503 default:
504 break;
505 }
506 if (KEEP != request) {
507 // TODO(fbarchard): compute stepping up/down from OutputNumPixels but
508 // clamp to inputpixels / 4 (2 steps)
509 cpu_desired_num_pixels_ = cpu_downgrade_count_ == 0 ? INT_MAX :
510 static_cast<int>(input_format().width * input_format().height >>
511 cpu_downgrade_count_);
512 }
513 int new_width, new_height;
514 bool changed = AdaptToMinimumFormat(&new_width, &new_height);
515 LOG(LS_INFO) << "VAdapt CPU Request: "
516 << (DOWNGRADE == request ? "down" :
517 (UPGRADE == request ? "up" : "keep"))
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000518 << " Steps: " << cpu_downgrade_count_
519 << " Changed: " << (changed ? "true" : "false")
520 << " To: " << new_width << "x" << new_height;
521}
522
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000523// A CPU request for new resolution
524// TODO(fbarchard): Move outside adapter.
525void CoordinatedVideoAdapter::OnCpuLoadUpdated(
526 int current_cpus, int max_cpus, float process_load, float system_load) {
527 talk_base::CritScope cs(&request_critical_section_);
528 if (!cpu_adaptation_) {
529 return;
530 }
531 // Update the moving average of system load. Even if we aren't smoothing,
532 // we'll still calculate this information, in case smoothing is later enabled.
533 system_load_average_ = kCpuLoadWeightCoefficient * system_load +
534 (1.0f - kCpuLoadWeightCoefficient) * system_load_average_;
535 if (cpu_smoothing_) {
536 system_load = system_load_average_;
537 }
538 // If we haven't started taking samples yet, wait until we have at least
539 // the correct number of samples per the wait time.
540 if (cpu_adapt_wait_time_ == 0) {
541 cpu_adapt_wait_time_ = talk_base::TimeAfter(kCpuLoadMinSampleTime);
542 }
543 AdaptRequest request = FindCpuRequest(current_cpus, max_cpus,
544 process_load, system_load);
545 // Make sure we're not adapting too quickly.
546 if (request != KEEP) {
547 if (talk_base::TimeIsLater(talk_base::Time(),
548 cpu_adapt_wait_time_)) {
549 LOG(LS_VERBOSE) << "VAdapt CPU load high/low but do not adapt until "
550 << talk_base::TimeUntil(cpu_adapt_wait_time_) << " ms";
551 request = KEEP;
552 }
553 }
554
555 OnCpuResolutionRequest(request);
556}
557
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000558// Called by cpu adapter on up requests.
559bool CoordinatedVideoAdapter::IsMinimumFormat(int pixels) {
560 // Find closest scale factor that matches input resolution to min_num_pixels
561 // and set that for output resolution. This is not needed for VideoAdapter,
562 // but provides feedback to unittests and users on expected resolution.
563 // Actual resolution is based on input frame.
564 VideoFormat new_output = output_format();
565 VideoFormat input = input_format();
566 if (input_format().IsSize0x0()) {
567 input = new_output;
568 }
569 float scale = 1.0f;
570 if (!input.IsSize0x0()) {
571 scale = FindClosestScale(input.width,
572 input.height,
573 pixels);
574 }
575 new_output.width = static_cast<int>(input.width * scale + .5f);
576 new_output.height = static_cast<int>(input.height * scale + .5f);
577 int new_pixels = new_output.width * new_output.height;
578 int num_pixels = GetOutputNumPixels();
579 return new_pixels <= num_pixels;
580}
581
582// Called by all coordinators when there is a change.
583bool CoordinatedVideoAdapter::AdaptToMinimumFormat(int* new_width,
584 int* new_height) {
585 VideoFormat new_output = output_format();
586 VideoFormat input = input_format();
587 if (input_format().IsSize0x0()) {
588 input = new_output;
589 }
590 int old_num_pixels = GetOutputNumPixels();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000591 int min_num_pixels = INT_MAX;
592 adapt_reason_ = 0;
593
594 // Reduce resolution based on encoder bandwidth (GD).
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000595 if (encoder_desired_num_pixels_ &&
596 (encoder_desired_num_pixels_ < min_num_pixels)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000597 adapt_reason_ |= ADAPTREASON_BANDWIDTH;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000598 min_num_pixels = encoder_desired_num_pixels_;
599 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000600 // Reduce resolution based on CPU.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000601 if (cpu_adaptation_ && cpu_desired_num_pixels_ &&
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000602 (cpu_desired_num_pixels_ <= min_num_pixels)) {
603 if (cpu_desired_num_pixels_ < min_num_pixels) {
604 adapt_reason_ = ADAPTREASON_CPU;
605 } else {
606 adapt_reason_ |= ADAPTREASON_CPU;
607 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000608 min_num_pixels = cpu_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000609 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000610 // Round resolution for GD or CPU to allow 1/2 to map to 9/16.
611 if (!input.IsSize0x0() && min_num_pixels != INT_MAX) {
612 float scale = FindClosestScale(input.width, input.height, min_num_pixels);
613 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
614 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000615 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000616 // Reduce resolution based on View Request.
617 if (view_desired_num_pixels_ <= min_num_pixels) {
618 if (view_desired_num_pixels_ < min_num_pixels) {
619 adapt_reason_ = ADAPTREASON_VIEW;
620 } else {
621 adapt_reason_ |= ADAPTREASON_VIEW;
622 }
623 min_num_pixels = view_desired_num_pixels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000624 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000625 // Snap to a scale factor.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000626 float scale = 1.0f;
627 if (!input.IsSize0x0()) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000628 scale = FindLowerScale(input.width, input.height, min_num_pixels);
629 min_num_pixels = static_cast<int>(input.width * scale + .5f) *
630 static_cast<int>(input.height * scale + .5f);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000631 }
632 if (scale == 1.0f) {
633 adapt_reason_ = 0;
634 }
635 *new_width = new_output.width = static_cast<int>(input.width * scale + .5f);
636 *new_height = new_output.height = static_cast<int>(input.height * scale +
637 .5f);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000638 SetOutputNumPixels(min_num_pixels);
639
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000640 new_output.interval = view_desired_interval_;
641 SetOutputFormat(new_output);
642 int new_num_pixels = GetOutputNumPixels();
643 bool changed = new_num_pixels != old_num_pixels;
644
645 static const char* kReasons[8] = {
646 "None",
647 "CPU",
648 "BANDWIDTH",
649 "CPU+BANDWIDTH",
650 "VIEW",
651 "CPU+VIEW",
652 "BANDWIDTH+VIEW",
653 "CPU+BANDWIDTH+VIEW",
654 };
655
656 LOG(LS_VERBOSE) << "VAdapt Status View: " << view_desired_num_pixels_
657 << " GD: " << encoder_desired_num_pixels_
658 << " CPU: " << cpu_desired_num_pixels_
659 << " Pixels: " << min_num_pixels
660 << " Input: " << input.width
661 << "x" << input.height
662 << " Scale: " << scale
663 << " Resolution: " << new_output.width
664 << "x" << new_output.height
665 << " Changed: " << (changed ? "true" : "false")
666 << " Reason: " << kReasons[adapt_reason_];
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000667
668 if (changed) {
669 // When any adaptation occurs, historic CPU load levels are no longer
670 // accurate. Clear out our state so we can re-learn at the new normal.
671 cpu_adapt_wait_time_ = talk_base::TimeAfter(kCpuLoadMinSampleTime);
672 system_load_average_ = kCpuLoadInitialAverage;
673 }
674
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000675 return changed;
676}
677
678} // namespace cricket