blob: 3ebebef247c9b71f7a620c53d7b1699822408c72 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
marpan@webrtc.org9d76b4e2012-02-28 23:39:31 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Henrik Kjellander2557b862015-11-18 22:00:21 +010011#include "webrtc/modules/video_coding/media_optimization.h"
stefan@webrtc.orge0d6fa42012-03-20 22:10:56 +000012
pbos854e84c2015-11-16 16:39:06 -080013#include "webrtc/base/logging.h"
Henrik Kjellander2557b862015-11-18 22:00:21 +010014#include "webrtc/modules/video_coding/content_metrics_processing.h"
15#include "webrtc/modules/video_coding/qm_select.h"
kjellander@webrtc.orgb7ce9642015-11-18 23:04:10 +010016#include "webrtc/modules/video_coding/utility/frame_dropper.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010017#include "webrtc/system_wrappers/include/clock.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000018
19namespace webrtc {
stefan@webrtc.orga64300a2013-03-04 15:24:40 +000020namespace media_optimization {
andresp@webrtc.orge682aa52013-12-19 10:59:48 +000021namespace {
22void UpdateProtectionCallback(
23 VCMProtectionMethod* selected_method,
24 uint32_t* video_rate_bps,
25 uint32_t* nack_overhead_rate_bps,
26 uint32_t* fec_overhead_rate_bps,
27 VCMProtectionCallback* video_protection_callback) {
28 FecProtectionParams delta_fec_params;
29 FecProtectionParams key_fec_params;
30 // Get the FEC code rate for Key frames (set to 0 when NA).
31 key_fec_params.fec_rate = selected_method->RequiredProtectionFactorK();
32
33 // Get the FEC code rate for Delta frames (set to 0 when NA).
34 delta_fec_params.fec_rate = selected_method->RequiredProtectionFactorD();
35
36 // Get the FEC-UEP protection status for Key frames: UEP on/off.
37 key_fec_params.use_uep_protection = selected_method->RequiredUepProtectionK();
38
39 // Get the FEC-UEP protection status for Delta frames: UEP on/off.
40 delta_fec_params.use_uep_protection =
41 selected_method->RequiredUepProtectionD();
42
43 // The RTP module currently requires the same |max_fec_frames| for both
44 // key and delta frames.
45 delta_fec_params.max_fec_frames = selected_method->MaxFramesFec();
46 key_fec_params.max_fec_frames = selected_method->MaxFramesFec();
47
48 // Set the FEC packet mask type. |kFecMaskBursty| is more effective for
49 // consecutive losses and little/no packet re-ordering. As we currently
50 // do not have feedback data on the degree of correlated losses and packet
51 // re-ordering, we keep default setting to |kFecMaskRandom| for now.
52 delta_fec_params.fec_mask_type = kFecMaskRandom;
53 key_fec_params.fec_mask_type = kFecMaskRandom;
54
55 // TODO(Marco): Pass FEC protection values per layer.
56 video_protection_callback->ProtectionRequest(&delta_fec_params,
57 &key_fec_params,
58 video_rate_bps,
59 nack_overhead_rate_bps,
60 fec_overhead_rate_bps);
61}
62} // namespace
63
64struct MediaOptimization::EncodedFrameSample {
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +000065 EncodedFrameSample(size_t size_bytes,
andresp@webrtc.orge682aa52013-12-19 10:59:48 +000066 uint32_t timestamp,
67 int64_t time_complete_ms)
68 : size_bytes(size_bytes),
69 timestamp(timestamp),
70 time_complete_ms(time_complete_ms) {}
71
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +000072 size_t size_bytes;
andresp@webrtc.orge682aa52013-12-19 10:59:48 +000073 uint32_t timestamp;
74 int64_t time_complete_ms;
75};
niklase@google.com470e71d2011-07-07 08:21:25 +000076
stefan@webrtc.org34c5da62014-04-11 14:08:35 +000077MediaOptimization::MediaOptimization(Clock* clock)
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +000078 : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
79 clock_(clock),
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +000080 max_bit_rate_(0),
81 send_codec_type_(kVideoCodecUnknown),
82 codec_width_(0),
83 codec_height_(0),
84 user_frame_rate_(0),
henrik.lundin@webrtc.orgb426c462013-09-24 07:41:53 +000085 frame_dropper_(new FrameDropper),
86 loss_prot_logic_(
87 new VCMLossProtectionLogic(clock_->TimeInMilliseconds())),
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +000088 fraction_lost_(0),
89 send_statistics_zero_encode_(0),
90 max_payload_size_(1460),
pbos73674632015-10-29 15:45:00 -070091 video_target_bitrate_(0),
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +000092 incoming_frame_rate_(0),
93 enable_qm_(false),
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +000094 encoded_frame_samples_(),
95 avg_sent_bit_rate_bps_(0),
96 avg_sent_framerate_(0),
97 key_frame_cnt_(0),
98 delta_frame_cnt_(0),
henrik.lundin@webrtc.orgb426c462013-09-24 07:41:53 +000099 content_(new VCMContentMetricsProcessing()),
100 qm_resolution_(new VCMQmResolution()),
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000101 last_qm_update_time_(0),
102 last_change_time_(0),
henrik.lundin@webrtc.org544b17c2013-09-26 12:05:15 +0000103 num_layers_(0),
henrik.lundin@webrtc.orgce8e0932013-11-18 12:18:43 +0000104 suspension_enabled_(false),
105 video_suspended_(false),
106 suspension_threshold_bps_(0),
107 suspension_window_bps_(0) {
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000108 memset(send_statistics_, 0, sizeof(send_statistics_));
109 memset(incoming_frame_times_, -1, sizeof(incoming_frame_times_));
niklase@google.com470e71d2011-07-07 08:21:25 +0000110}
111
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000112MediaOptimization::~MediaOptimization(void) {
113 loss_prot_logic_->Release();
niklase@google.com470e71d2011-07-07 08:21:25 +0000114}
115
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000116void MediaOptimization::Reset() {
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000117 CriticalSectionScoped lock(crit_sect_.get());
118 SetEncodingDataInternal(
119 kVideoCodecUnknown, 0, 0, 0, 0, 0, 0, max_payload_size_);
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000120 memset(incoming_frame_times_, -1, sizeof(incoming_frame_times_));
121 incoming_frame_rate_ = 0.0;
122 frame_dropper_->Reset();
123 loss_prot_logic_->Reset(clock_->TimeInMilliseconds());
124 frame_dropper_->SetRates(0, 0);
125 content_->Reset();
126 qm_resolution_->Reset();
127 loss_prot_logic_->UpdateFrameRate(incoming_frame_rate_);
128 loss_prot_logic_->Reset(clock_->TimeInMilliseconds());
129 send_statistics_zero_encode_ = 0;
pbos73674632015-10-29 15:45:00 -0700130 video_target_bitrate_ = 0;
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000131 codec_width_ = 0;
132 codec_height_ = 0;
133 user_frame_rate_ = 0;
134 key_frame_cnt_ = 0;
135 delta_frame_cnt_ = 0;
136 last_qm_update_time_ = 0;
137 last_change_time_ = 0;
138 encoded_frame_samples_.clear();
139 avg_sent_bit_rate_bps_ = 0;
140 num_layers_ = 1;
niklase@google.com470e71d2011-07-07 08:21:25 +0000141}
142
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000143void MediaOptimization::SetEncodingData(VideoCodecType send_codec_type,
144 int32_t max_bit_rate,
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000145 uint32_t target_bitrate,
146 uint16_t width,
147 uint16_t height,
Peter Boströmdf664532015-05-12 12:22:14 +0200148 uint32_t frame_rate,
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000149 int num_layers,
150 int32_t mtu) {
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000151 CriticalSectionScoped lock(crit_sect_.get());
152 SetEncodingDataInternal(send_codec_type,
153 max_bit_rate,
154 frame_rate,
155 target_bitrate,
156 width,
157 height,
158 num_layers,
159 mtu);
160}
161
162void MediaOptimization::SetEncodingDataInternal(VideoCodecType send_codec_type,
163 int32_t max_bit_rate,
164 uint32_t frame_rate,
165 uint32_t target_bitrate,
166 uint16_t width,
167 uint16_t height,
168 int num_layers,
169 int32_t mtu) {
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000170 // Everything codec specific should be reset here since this means the codec
171 // has changed. If native dimension values have changed, then either user
172 // initiated change, or QM initiated change. Will be able to determine only
173 // after the processing of the first frame.
174 last_change_time_ = clock_->TimeInMilliseconds();
175 content_->Reset();
176 content_->UpdateFrameRate(frame_rate);
177
178 max_bit_rate_ = max_bit_rate;
179 send_codec_type_ = send_codec_type;
pbos73674632015-10-29 15:45:00 -0700180 video_target_bitrate_ = target_bitrate;
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000181 float target_bitrate_kbps = static_cast<float>(target_bitrate) / 1000.0f;
182 loss_prot_logic_->UpdateBitRate(target_bitrate_kbps);
183 loss_prot_logic_->UpdateFrameRate(static_cast<float>(frame_rate));
184 loss_prot_logic_->UpdateFrameSize(width, height);
185 loss_prot_logic_->UpdateNumLayers(num_layers);
186 frame_dropper_->Reset();
187 frame_dropper_->SetRates(target_bitrate_kbps, static_cast<float>(frame_rate));
188 user_frame_rate_ = static_cast<float>(frame_rate);
189 codec_width_ = width;
190 codec_height_ = height;
191 num_layers_ = (num_layers <= 1) ? 1 : num_layers; // Can also be zero.
192 max_payload_size_ = mtu;
193 qm_resolution_->Initialize(target_bitrate_kbps,
194 user_frame_rate_,
195 codec_width_,
196 codec_height_,
197 num_layers_);
198}
199
200uint32_t MediaOptimization::SetTargetRates(
201 uint32_t target_bitrate,
202 uint8_t fraction_lost,
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000203 int64_t round_trip_time_ms,
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000204 VCMProtectionCallback* protection_callback,
205 VCMQMSettingsCallback* qmsettings_callback) {
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000206 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000207 VCMProtectionMethod* selected_method = loss_prot_logic_->SelectedMethod();
208 float target_bitrate_kbps = static_cast<float>(target_bitrate) / 1000.0f;
209 loss_prot_logic_->UpdateBitRate(target_bitrate_kbps);
210 loss_prot_logic_->UpdateRtt(round_trip_time_ms);
niklase@google.com470e71d2011-07-07 08:21:25 +0000211
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000212 // Get frame rate for encoder: this is the actual/sent frame rate.
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000213 float actual_frame_rate = SentFrameRateInternal();
niklase@google.com470e71d2011-07-07 08:21:25 +0000214
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000215 // Sanity check.
216 if (actual_frame_rate < 1.0) {
217 actual_frame_rate = 1.0;
218 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000219
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000220 // Update frame rate for the loss protection logic class: frame rate should
221 // be the actual/sent rate.
222 loss_prot_logic_->UpdateFrameRate(actual_frame_rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000223
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000224 fraction_lost_ = fraction_lost;
niklase@google.com470e71d2011-07-07 08:21:25 +0000225
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000226 // Returns the filtered packet loss, used for the protection setting.
227 // The filtered loss may be the received loss (no filter), or some
228 // filtered value (average or max window filter).
229 // Use max window filter for now.
230 FilterPacketLossMode filter_mode = kMaxFilter;
231 uint8_t packet_loss_enc = loss_prot_logic_->FilteredLoss(
232 clock_->TimeInMilliseconds(), filter_mode, fraction_lost);
niklase@google.com470e71d2011-07-07 08:21:25 +0000233
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000234 // For now use the filtered loss for computing the robustness settings.
235 loss_prot_logic_->UpdateFilteredLossPr(packet_loss_enc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000236
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000237 // Rate cost of the protection methods.
pbos73674632015-10-29 15:45:00 -0700238 float protection_overhead_rate = 0.0f;
niklase@google.com470e71d2011-07-07 08:21:25 +0000239
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000240 // Update protection settings, when applicable.
241 float sent_video_rate_kbps = 0.0f;
mflodmanfcf54bd2015-04-14 21:28:08 +0200242 if (loss_prot_logic_->SelectedType() != kNone) {
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000243 // Update protection method with content metrics.
244 selected_method->UpdateContentMetrics(content_->ShortTermAvgData());
marpan@google.com86548c62011-07-12 17:12:57 +0000245
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000246 // Update method will compute the robustness settings for the given
247 // protection method and the overhead cost
248 // the protection method is set by the user via SetVideoProtection.
249 loss_prot_logic_->UpdateMethod();
niklase@google.com470e71d2011-07-07 08:21:25 +0000250
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000251 // Update protection callback with protection settings.
252 uint32_t sent_video_rate_bps = 0;
253 uint32_t sent_nack_rate_bps = 0;
254 uint32_t sent_fec_rate_bps = 0;
255 // Get the bit cost of protection method, based on the amount of
256 // overhead data actually transmitted (including headers) the last
257 // second.
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000258 if (protection_callback) {
259 UpdateProtectionCallback(selected_method,
260 &sent_video_rate_bps,
261 &sent_nack_rate_bps,
262 &sent_fec_rate_bps,
263 protection_callback);
264 }
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000265 uint32_t sent_total_rate_bps =
266 sent_video_rate_bps + sent_nack_rate_bps + sent_fec_rate_bps;
267 // Estimate the overhead costs of the next second as staying the same
268 // wrt the source bitrate.
269 if (sent_total_rate_bps > 0) {
pbos73674632015-10-29 15:45:00 -0700270 protection_overhead_rate =
271 static_cast<float>(sent_nack_rate_bps + sent_fec_rate_bps) /
272 sent_total_rate_bps;
niklase@google.com470e71d2011-07-07 08:21:25 +0000273 }
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000274 // Cap the overhead estimate to 50%.
pbos73674632015-10-29 15:45:00 -0700275 if (protection_overhead_rate > 0.5)
276 protection_overhead_rate = 0.5;
niklase@google.com470e71d2011-07-07 08:21:25 +0000277
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000278 // Get the effective packet loss for encoder ER when applicable. Should be
279 // passed to encoder via fraction_lost.
280 packet_loss_enc = selected_method->RequiredPacketLossER();
281 sent_video_rate_kbps = static_cast<float>(sent_video_rate_bps) / 1000.0f;
282 }
stefan@webrtc.orgf4c82862011-12-13 15:38:14 +0000283
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000284 // Source coding rate: total rate - protection overhead.
pbos73674632015-10-29 15:45:00 -0700285 video_target_bitrate_ = target_bitrate * (1.0 - protection_overhead_rate);
286
287 // Cap target video bitrate to codec maximum.
288 if (max_bit_rate_ > 0 && video_target_bitrate_ > max_bit_rate_) {
289 video_target_bitrate_ = max_bit_rate_;
290 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000291
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000292 // Update encoding rates following protection settings.
293 float target_video_bitrate_kbps =
pbos73674632015-10-29 15:45:00 -0700294 static_cast<float>(video_target_bitrate_) / 1000.0f;
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000295 frame_dropper_->SetRates(target_video_bitrate_kbps, incoming_frame_rate_);
296
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000297 if (enable_qm_ && qmsettings_callback) {
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000298 // Update QM with rates.
299 qm_resolution_->UpdateRates(target_video_bitrate_kbps,
300 sent_video_rate_kbps,
301 incoming_frame_rate_,
302 fraction_lost_);
303 // Check for QM selection.
304 bool select_qm = CheckStatusForQMchange();
305 if (select_qm) {
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000306 SelectQuality(qmsettings_callback);
niklase@google.com470e71d2011-07-07 08:21:25 +0000307 }
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000308 // Reset the short-term averaged content data.
309 content_->ResetShortTermAvgData();
310 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000311
henrik.lundin@webrtc.orgce8e0932013-11-18 12:18:43 +0000312 CheckSuspendConditions();
henrik.lundin@webrtc.org544b17c2013-09-26 12:05:15 +0000313
pbos73674632015-10-29 15:45:00 -0700314 return video_target_bitrate_;
niklase@google.com470e71d2011-07-07 08:21:25 +0000315}
316
pbosba8c15b2015-07-14 09:36:34 -0700317void MediaOptimization::SetProtectionMethod(VCMProtectionMethodEnum method) {
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000318 CriticalSectionScoped lock(crit_sect_.get());
pbos@webrtc.orgcade82c2015-03-12 10:39:24 +0000319 loss_prot_logic_->SetMethod(method);
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000320}
321
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000322uint32_t MediaOptimization::InputFrameRate() {
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000323 CriticalSectionScoped lock(crit_sect_.get());
324 return InputFrameRateInternal();
325}
326
327uint32_t MediaOptimization::InputFrameRateInternal() {
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000328 ProcessIncomingFrameRate(clock_->TimeInMilliseconds());
329 return uint32_t(incoming_frame_rate_ + 0.5f);
330}
331
332uint32_t MediaOptimization::SentFrameRate() {
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000333 CriticalSectionScoped lock(crit_sect_.get());
334 return SentFrameRateInternal();
335}
336
337uint32_t MediaOptimization::SentFrameRateInternal() {
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000338 PurgeOldFrameSamples(clock_->TimeInMilliseconds());
339 UpdateSentFramerate();
340 return avg_sent_framerate_;
341}
342
343uint32_t MediaOptimization::SentBitRate() {
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000344 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000345 const int64_t now_ms = clock_->TimeInMilliseconds();
346 PurgeOldFrameSamples(now_ms);
347 UpdateSentBitrate(now_ms);
348 return avg_sent_bit_rate_bps_;
349}
350
pbos@webrtc.org273a4142014-12-01 15:23:21 +0000351int32_t MediaOptimization::UpdateWithEncodedData(
352 const EncodedImage& encoded_image) {
353 size_t encoded_length = encoded_image._length;
354 uint32_t timestamp = encoded_image._timeStamp;
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000355 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000356 const int64_t now_ms = clock_->TimeInMilliseconds();
357 PurgeOldFrameSamples(now_ms);
358 if (encoded_frame_samples_.size() > 0 &&
359 encoded_frame_samples_.back().timestamp == timestamp) {
360 // Frames having the same timestamp are generated from the same input
361 // frame. We don't want to double count them, but only increment the
362 // size_bytes.
363 encoded_frame_samples_.back().size_bytes += encoded_length;
364 encoded_frame_samples_.back().time_complete_ms = now_ms;
365 } else {
366 encoded_frame_samples_.push_back(
367 EncodedFrameSample(encoded_length, timestamp, now_ms));
368 }
369 UpdateSentBitrate(now_ms);
370 UpdateSentFramerate();
371 if (encoded_length > 0) {
Peter Boström49e196a2015-10-23 15:58:18 +0200372 const bool delta_frame = encoded_image._frameType != kVideoFrameKey;
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000373
374 frame_dropper_->Fill(encoded_length, delta_frame);
375 if (max_payload_size_ > 0 && encoded_length > 0) {
376 const float min_packets_per_frame =
377 encoded_length / static_cast<float>(max_payload_size_);
378 if (delta_frame) {
379 loss_prot_logic_->UpdatePacketsPerFrame(min_packets_per_frame,
380 clock_->TimeInMilliseconds());
381 } else {
382 loss_prot_logic_->UpdatePacketsPerFrameKey(
383 min_packets_per_frame, clock_->TimeInMilliseconds());
384 }
385
386 if (enable_qm_) {
387 // Update quality select with encoded length.
pbos@webrtc.org273a4142014-12-01 15:23:21 +0000388 qm_resolution_->UpdateEncodedSize(encoded_length);
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000389 }
390 }
391 if (!delta_frame && encoded_length > 0) {
392 loss_prot_logic_->UpdateKeyFrameSize(static_cast<float>(encoded_length));
393 }
394
395 // Updating counters.
396 if (delta_frame) {
397 delta_frame_cnt_++;
398 } else {
399 key_frame_cnt_++;
400 }
401 }
402
403 return VCM_OK;
404}
405
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000406void MediaOptimization::EnableQM(bool enable) {
407 CriticalSectionScoped lock(crit_sect_.get());
408 enable_qm_ = enable;
409}
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000410
411void MediaOptimization::EnableFrameDropper(bool enable) {
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000412 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000413 frame_dropper_->Enable(enable);
414}
415
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000416void MediaOptimization::SuspendBelowMinBitrate(int threshold_bps,
417 int window_bps) {
418 CriticalSectionScoped lock(crit_sect_.get());
419 assert(threshold_bps > 0 && window_bps >= 0);
420 suspension_threshold_bps_ = threshold_bps;
421 suspension_window_bps_ = window_bps;
422 suspension_enabled_ = true;
423 video_suspended_ = false;
424}
425
426bool MediaOptimization::IsVideoSuspended() const {
427 CriticalSectionScoped lock(crit_sect_.get());
428 return video_suspended_;
429}
430
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000431bool MediaOptimization::DropFrame() {
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000432 CriticalSectionScoped lock(crit_sect_.get());
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000433 UpdateIncomingFrameRate();
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000434 // Leak appropriate number of bytes.
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000435 frame_dropper_->Leak((uint32_t)(InputFrameRateInternal() + 0.5f));
henrik.lundin@webrtc.orgce8e0932013-11-18 12:18:43 +0000436 if (video_suspended_) {
henrik.lundin@webrtc.org544b17c2013-09-26 12:05:15 +0000437 return true; // Drop all frames when muted.
438 }
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000439 return frame_dropper_->DropFrame();
440}
441
wuchengli@chromium.orgae7cfd72014-06-30 08:01:47 +0000442void MediaOptimization::UpdateContentData(
443 const VideoContentMetrics* content_metrics) {
444 CriticalSectionScoped lock(crit_sect_.get());
445 // Updating content metrics.
446 if (content_metrics == NULL) {
447 // Disable QM if metrics are NULL.
448 enable_qm_ = false;
449 qm_resolution_->Reset();
450 } else {
451 content_->UpdateContentData(content_metrics);
452 }
453}
454
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000455void MediaOptimization::UpdateIncomingFrameRate() {
456 int64_t now = clock_->TimeInMilliseconds();
457 if (incoming_frame_times_[0] == 0) {
458 // No shifting if this is the first time.
459 } else {
460 // Shift all times one step.
461 for (int32_t i = (kFrameCountHistorySize - 2); i >= 0; i--) {
462 incoming_frame_times_[i + 1] = incoming_frame_times_[i];
463 }
464 }
465 incoming_frame_times_[0] = now;
466 ProcessIncomingFrameRate(now);
467}
468
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000469int32_t MediaOptimization::SelectQuality(
470 VCMQMSettingsCallback* video_qmsettings_callback) {
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000471 // Reset quantities for QM select.
472 qm_resolution_->ResetQM();
473
474 // Update QM will long-term averaged content metrics.
475 qm_resolution_->UpdateContent(content_->LongTermAvgData());
476
477 // Select quality mode.
478 VCMResolutionScale* qm = NULL;
479 int32_t ret = qm_resolution_->SelectResolution(&qm);
480 if (ret < 0) {
481 return ret;
482 }
483
484 // Check for updates to spatial/temporal modes.
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000485 QMUpdate(qm, video_qmsettings_callback);
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000486
487 // Reset all the rate and related frame counters quantities.
488 qm_resolution_->ResetRates();
489
490 // Reset counters.
491 last_qm_update_time_ = clock_->TimeInMilliseconds();
492
493 // Reset content metrics.
494 content_->Reset();
495
496 return VCM_OK;
497}
498
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000499void MediaOptimization::PurgeOldFrameSamples(int64_t now_ms) {
500 while (!encoded_frame_samples_.empty()) {
501 if (now_ms - encoded_frame_samples_.front().time_complete_ms >
stefan@webrtc.orgf4944d42013-03-18 17:04:52 +0000502 kBitrateAverageWinMs) {
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000503 encoded_frame_samples_.pop_front();
stefan@webrtc.orgf4944d42013-03-18 17:04:52 +0000504 } else {
505 break;
niklase@google.com470e71d2011-07-07 08:21:25 +0000506 }
stefan@webrtc.orgf4944d42013-03-18 17:04:52 +0000507 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000508}
509
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000510void MediaOptimization::UpdateSentBitrate(int64_t now_ms) {
511 if (encoded_frame_samples_.empty()) {
512 avg_sent_bit_rate_bps_ = 0;
stefan@webrtc.orgf4944d42013-03-18 17:04:52 +0000513 return;
514 }
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000515 size_t framesize_sum = 0;
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000516 for (FrameSampleList::iterator it = encoded_frame_samples_.begin();
517 it != encoded_frame_samples_.end();
518 ++it) {
stefan@webrtc.orgf4944d42013-03-18 17:04:52 +0000519 framesize_sum += it->size_bytes;
520 }
521 float denom = static_cast<float>(
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000522 now_ms - encoded_frame_samples_.front().time_complete_ms);
stefan@webrtc.orgf4944d42013-03-18 17:04:52 +0000523 if (denom >= 1.0f) {
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000524 avg_sent_bit_rate_bps_ =
stefan@webrtc.org0bae1fa2014-11-05 14:05:29 +0000525 static_cast<uint32_t>(framesize_sum * 8.0f * 1000.0f / denom + 0.5f);
stefan@webrtc.orgf4944d42013-03-18 17:04:52 +0000526 } else {
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000527 avg_sent_bit_rate_bps_ = framesize_sum * 8;
stefan@webrtc.orgf4944d42013-03-18 17:04:52 +0000528 }
529}
530
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000531void MediaOptimization::UpdateSentFramerate() {
532 if (encoded_frame_samples_.size() <= 1) {
533 avg_sent_framerate_ = encoded_frame_samples_.size();
stefan@webrtc.orgf4944d42013-03-18 17:04:52 +0000534 return;
535 }
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000536 int denom = encoded_frame_samples_.back().timestamp -
537 encoded_frame_samples_.front().timestamp;
stefan@webrtc.orgf4944d42013-03-18 17:04:52 +0000538 if (denom > 0) {
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000539 avg_sent_framerate_ =
540 (90000 * (encoded_frame_samples_.size() - 1) + denom / 2) / denom;
stefan@webrtc.orgf4944d42013-03-18 17:04:52 +0000541 } else {
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000542 avg_sent_framerate_ = encoded_frame_samples_.size();
stefan@webrtc.orgf4944d42013-03-18 17:04:52 +0000543 }
544}
niklase@google.com470e71d2011-07-07 08:21:25 +0000545
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000546bool MediaOptimization::QMUpdate(
547 VCMResolutionScale* qm,
548 VCMQMSettingsCallback* video_qmsettings_callback) {
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000549 // Check for no change.
marpan@webrtc.orge22d81c2012-03-20 18:21:53 +0000550 if (!qm->change_resolution_spatial && !qm->change_resolution_temporal) {
marpan@webrtc.orgaccf6072012-03-07 17:16:10 +0000551 return false;
552 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000553
marpan@webrtc.orgaccf6072012-03-07 17:16:10 +0000554 // Check for change in frame rate.
marpan@webrtc.orge22d81c2012-03-20 18:21:53 +0000555 if (qm->change_resolution_temporal) {
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000556 incoming_frame_rate_ = qm->frame_rate;
marpan@webrtc.orge22d81c2012-03-20 18:21:53 +0000557 // Reset frame rate estimate.
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000558 memset(incoming_frame_times_, -1, sizeof(incoming_frame_times_));
marpan@webrtc.orgaccf6072012-03-07 17:16:10 +0000559 }
marpan@google.com86548c62011-07-12 17:12:57 +0000560
marpan@webrtc.orgaccf6072012-03-07 17:16:10 +0000561 // Check for change in frame size.
marpan@webrtc.orge22d81c2012-03-20 18:21:53 +0000562 if (qm->change_resolution_spatial) {
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000563 codec_width_ = qm->codec_width;
564 codec_height_ = qm->codec_height;
marpan@webrtc.orgaccf6072012-03-07 17:16:10 +0000565 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000566
stefan@webrtc.org34c5da62014-04-11 14:08:35 +0000567 LOG(LS_INFO) << "Media optimizer requests the video resolution to be changed "
568 "to " << qm->codec_width << "x" << qm->codec_height << "@"
569 << qm->frame_rate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000570
marpan@webrtc.orge22d81c2012-03-20 18:21:53 +0000571 // Update VPM with new target frame rate and frame size.
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000572 // Note: use |qm->frame_rate| instead of |_incoming_frame_rate| for updating
573 // target frame rate in VPM frame dropper. The quantity |_incoming_frame_rate|
marpan@webrtc.orge22d81c2012-03-20 18:21:53 +0000574 // will vary/fluctuate, and since we don't want to change the state of the
575 // VPM frame dropper, unless a temporal action was selected, we use the
576 // quantity |qm->frame_rate| for updating.
andresp@webrtc.orge682aa52013-12-19 10:59:48 +0000577 video_qmsettings_callback->SetVideoQMSettings(
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000578 qm->frame_rate, codec_width_, codec_height_);
579 content_->UpdateFrameRate(qm->frame_rate);
580 qm_resolution_->UpdateCodecParameters(
581 qm->frame_rate, codec_width_, codec_height_);
marpan@webrtc.orgaccf6072012-03-07 17:16:10 +0000582 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000583}
584
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000585// Check timing constraints and look for significant change in:
586// (1) scene content,
587// (2) target bit rate.
588bool MediaOptimization::CheckStatusForQMchange() {
589 bool status = true;
590
591 // Check that we do not call QMSelect too often, and that we waited some time
592 // (to sample the metrics) from the event last_change_time
593 // last_change_time is the time where user changed the size/rate/frame rate
594 // (via SetEncodingData).
595 int64_t now = clock_->TimeInMilliseconds();
596 if ((now - last_qm_update_time_) < kQmMinIntervalMs ||
597 (now - last_change_time_) < kQmMinIntervalMs) {
598 status = false;
599 }
600
601 return status;
niklase@google.com470e71d2011-07-07 08:21:25 +0000602}
603
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000604// Allowing VCM to keep track of incoming frame rate.
605void MediaOptimization::ProcessIncomingFrameRate(int64_t now) {
606 int32_t num = 0;
607 int32_t nr_of_frames = 0;
608 for (num = 1; num < (kFrameCountHistorySize - 1); ++num) {
609 if (incoming_frame_times_[num] <= 0 ||
610 // don't use data older than 2 s
611 now - incoming_frame_times_[num] > kFrameHistoryWinMs) {
612 break;
613 } else {
614 nr_of_frames++;
niklase@google.com470e71d2011-07-07 08:21:25 +0000615 }
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000616 }
617 if (num > 1) {
Erik Språng66a641a2015-06-11 14:20:07 +0200618 const int64_t diff =
619 incoming_frame_times_[0] - incoming_frame_times_[num - 1];
620 incoming_frame_rate_ = 0.0; // No frame rate estimate available.
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000621 if (diff > 0) {
622 incoming_frame_rate_ = nr_of_frames * 1000.0f / static_cast<float>(diff);
niklase@google.com470e71d2011-07-07 08:21:25 +0000623 }
henrik.lundin@webrtc.orgbec11ef2013-09-23 19:54:25 +0000624 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000625}
626
henrik.lundin@webrtc.orgce8e0932013-11-18 12:18:43 +0000627void MediaOptimization::CheckSuspendConditions() {
pbos73674632015-10-29 15:45:00 -0700628 // Check conditions for SuspendBelowMinBitrate. |video_target_bitrate_| is in
629 // bps.
henrik.lundin@webrtc.orgce8e0932013-11-18 12:18:43 +0000630 if (suspension_enabled_) {
631 if (!video_suspended_) {
henrik.lundin@webrtc.org544b17c2013-09-26 12:05:15 +0000632 // Check if we just went below the threshold.
pbos73674632015-10-29 15:45:00 -0700633 if (video_target_bitrate_ < suspension_threshold_bps_) {
henrik.lundin@webrtc.orgce8e0932013-11-18 12:18:43 +0000634 video_suspended_ = true;
henrik.lundin@webrtc.org544b17c2013-09-26 12:05:15 +0000635 }
636 } else {
henrik.lundin@webrtc.orgce8e0932013-11-18 12:18:43 +0000637 // Video is already suspended. Check if we just went over the threshold
henrik.lundin@webrtc.org544b17c2013-09-26 12:05:15 +0000638 // with a margin.
pbos73674632015-10-29 15:45:00 -0700639 if (video_target_bitrate_ >
henrik.lundin@webrtc.orgce8e0932013-11-18 12:18:43 +0000640 suspension_threshold_bps_ + suspension_window_bps_) {
641 video_suspended_ = false;
henrik.lundin@webrtc.org544b17c2013-09-26 12:05:15 +0000642 }
643 }
644 }
645}
646
stefan@webrtc.orga64300a2013-03-04 15:24:40 +0000647} // namespace media_optimization
648} // namespace webrtc