blob: b47eeb55d37ace7312a91b5b246ad2cdf03dc119 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
stefan@webrtc.orgc35f5ce2012-04-11 07:42:25 +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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/video_coding/media_opt_util.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Yves Gerey3e707812018-11-28 16:47:49 +010013#include <assert.h>
pbos@webrtc.orga4407322013-07-16 12:32:05 +000014#include <math.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020015
philipel9d3ab612015-12-21 04:12:39 -080016#include <algorithm>
17
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "modules/video_coding/fec_rate_table.h"
Yves Gerey3e707812018-11-28 16:47:49 +010019#include "modules/video_coding/internal_defines.h"
Sergio Garcia Murillo43800f92018-06-21 16:16:38 +020020#include "modules/video_coding/utility/simulcast_rate_allocator.h"
Yves Gerey3e707812018-11-28 16:47:49 +010021#include "rtc_base/checks.h"
Rasmus Brandt2b9317a2019-10-30 13:01:46 +010022#include "rtc_base/experiments/rate_control_settings.h"
Emircan Uysaler704a7bd2018-08-06 16:14:10 -070023#include "rtc_base/numerics/safe_conversions.h"
mikhal@webrtc.org0e7d9d82011-12-19 19:04:49 +000024
niklase@google.com470e71d2011-07-07 08:21:25 +000025namespace webrtc {
Peter Boström9cb1f302015-04-01 11:39:49 +020026// Max value of loss rates in off-line model
27static const int kPacketLossMax = 129;
28
stefan@webrtc.orga64300a2013-03-04 15:24:40 +000029namespace media_optimization {
niklase@google.com470e71d2011-07-07 08:21:25 +000030
Stefan Holmerdbdb3a02018-07-17 16:03:46 +020031VCMProtectionParameters::VCMProtectionParameters()
32 : rtt(0),
33 lossPr(0.0f),
34 bitRate(0.0f),
35 packetsPerFrame(0.0f),
36 packetsPerFrameKey(0.0f),
37 frameRate(0.0f),
38 keyFrameSize(0.0f),
39 fecRateDelta(0),
40 fecRateKey(0),
41 codecWidth(0),
42 codecHeight(0),
43 numLayers(1) {}
44
Peter Boström9cb1f302015-04-01 11:39:49 +020045VCMProtectionMethod::VCMProtectionMethod()
46 : _effectivePacketLoss(0),
47 _protectionFactorK(0),
48 _protectionFactorD(0),
49 _scaleProtKey(2.0f),
50 _maxPayloadSize(1460),
Peter Boström9cb1f302015-04-01 11:39:49 +020051 _corrFecCost(1.0),
philipel9d3ab612015-12-21 04:12:39 -080052 _type(kNone) {}
mikhal@webrtc.orga057a952011-08-26 21:17:34 +000053
pbosc0430522016-05-01 17:19:05 -070054VCMProtectionMethod::~VCMProtectionMethod() {}
marpan@google.com86548c62011-07-12 17:12:57 +000055
Stefan Holmerdbdb3a02018-07-17 16:03:46 +020056enum VCMProtectionMethodEnum VCMProtectionMethod::Type() const {
57 return _type;
58}
59
60uint8_t VCMProtectionMethod::RequiredPacketLossER() {
61 return _effectivePacketLoss;
62}
63
64uint8_t VCMProtectionMethod::RequiredProtectionFactorK() {
65 return _protectionFactorK;
66}
67
68uint8_t VCMProtectionMethod::RequiredProtectionFactorD() {
69 return _protectionFactorD;
70}
71
72bool VCMProtectionMethod::RequiredUepProtectionK() {
73 return _useUepProtectionK;
74}
75
76bool VCMProtectionMethod::RequiredUepProtectionD() {
77 return _useUepProtectionD;
78}
79
80int VCMProtectionMethod::MaxFramesFec() const {
81 return 1;
82}
83
pkasting@chromium.org16825b12015-01-12 21:51:21 +000084VCMNackFecMethod::VCMNackFecMethod(int64_t lowRttNackThresholdMs,
85 int64_t highRttNackThresholdMs)
stefan@webrtc.org932ab182011-11-29 11:33:31 +000086 : VCMFecMethod(),
87 _lowRttNackMs(lowRttNackThresholdMs),
stefan@webrtc.orgc35f5ce2012-04-11 07:42:25 +000088 _highRttNackMs(highRttNackThresholdMs),
89 _maxFramesFec(1) {
stefan@webrtc.org932ab182011-11-29 11:33:31 +000090 assert(lowRttNackThresholdMs >= -1 && highRttNackThresholdMs >= -1);
91 assert(highRttNackThresholdMs == -1 ||
92 lowRttNackThresholdMs <= highRttNackThresholdMs);
93 assert(lowRttNackThresholdMs > -1 || highRttNackThresholdMs == -1);
94 _type = kNackFec;
mikhal@google.com77408882011-07-22 22:05:25 +000095}
96
philipel9d3ab612015-12-21 04:12:39 -080097VCMNackFecMethod::~VCMNackFecMethod() {
98 //
mikhal@google.com77408882011-07-22 22:05:25 +000099}
philipel9d3ab612015-12-21 04:12:39 -0800100bool VCMNackFecMethod::ProtectionFactor(
101 const VCMProtectionParameters* parameters) {
102 // Hybrid Nack FEC has three operational modes:
103 // 1. Low RTT (below kLowRttNackMs) - Nack only: Set FEC rate
104 // (_protectionFactorD) to zero. -1 means no FEC.
105 // 2. High RTT (above _highRttNackMs) - FEC Only: Keep FEC factors.
106 // -1 means always allow NACK.
107 // 3. Medium RTT values - Hybrid mode: We will only nack the
108 // residual following the decoding of the FEC (refer to JB logic). FEC
109 // delta protection factor will be adjusted based on the RTT.
mikhal@google.com022716b2011-07-20 23:12:57 +0000110
philipel9d3ab612015-12-21 04:12:39 -0800111 // Otherwise: we count on FEC; if the RTT is below a threshold, then we
112 // nack the residual, based on a decision made in the JB.
mikhal@google.com022716b2011-07-20 23:12:57 +0000113
philipel9d3ab612015-12-21 04:12:39 -0800114 // Compute the protection factors
115 VCMFecMethod::ProtectionFactor(parameters);
116 if (_lowRttNackMs == -1 || parameters->rtt < _lowRttNackMs) {
117 _protectionFactorD = 0;
118 VCMFecMethod::UpdateProtectionFactorD(_protectionFactorD);
mikhal@google.com320813c2011-08-03 20:47:50 +0000119
mikhal@google.com679450f2011-08-01 22:14:58 +0000120 // When in Hybrid mode (RTT range), adjust FEC rates based on the
121 // RTT (NACK effectiveness) - adjustment factor is in the range [0,1].
philipel9d3ab612015-12-21 04:12:39 -0800122 } else if (_highRttNackMs == -1 || parameters->rtt < _highRttNackMs) {
123 // TODO(mikhal): Disabling adjustment temporarily.
124 // uint16_t rttIndex = (uint16_t) parameters->rtt;
125 float adjustRtt = 1.0f; // (float)VCMNackFecTable[rttIndex] / 100.0f;
niklase@google.com470e71d2011-07-07 08:21:25 +0000126
philipel9d3ab612015-12-21 04:12:39 -0800127 // Adjust FEC with NACK on (for delta frame only)
128 // table depends on RTT relative to rttMax (NACK Threshold)
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700129 _protectionFactorD = rtc::saturated_cast<uint8_t>(
130 adjustRtt * rtc::saturated_cast<float>(_protectionFactorD));
philipel9d3ab612015-12-21 04:12:39 -0800131 // update FEC rates after applying adjustment
132 VCMFecMethod::UpdateProtectionFactorD(_protectionFactorD);
133 }
mikhal@google.com679450f2011-08-01 22:14:58 +0000134
philipel9d3ab612015-12-21 04:12:39 -0800135 return true;
mikhal@google.com022716b2011-07-20 23:12:57 +0000136}
niklase@google.com470e71d2011-07-07 08:21:25 +0000137
stefan@webrtc.orgc35f5ce2012-04-11 07:42:25 +0000138int VCMNackFecMethod::ComputeMaxFramesFec(
139 const VCMProtectionParameters* parameters) {
140 if (parameters->numLayers > 2) {
141 // For more than 2 temporal layers we will only have FEC on the base layer,
142 // and the base layers will be pretty far apart. Therefore we force one
143 // frame FEC.
144 return 1;
145 }
146 // We set the max number of frames to base the FEC on so that on average
147 // we will have complete frames in one RTT. Note that this is an upper
148 // bound, and that the actual number of frames used for FEC is decided by the
149 // RTP module based on the actual number of packets and the protection factor.
philipel9d3ab612015-12-21 04:12:39 -0800150 float base_layer_framerate =
151 parameters->frameRate /
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700152 rtc::saturated_cast<float>(1 << (parameters->numLayers - 1));
philipel9d3ab612015-12-21 04:12:39 -0800153 int max_frames_fec = std::max(
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700154 rtc::saturated_cast<int>(
155 2.0f * base_layer_framerate * parameters->rtt / 1000.0f + 0.5f),
philipel9d3ab612015-12-21 04:12:39 -0800156 1);
stefan@webrtc.orgc35f5ce2012-04-11 07:42:25 +0000157 // |kUpperLimitFramesFec| is the upper limit on how many frames we
158 // allow any FEC to be based on.
159 if (max_frames_fec > kUpperLimitFramesFec) {
160 max_frames_fec = kUpperLimitFramesFec;
161 }
162 return max_frames_fec;
163}
164
165int VCMNackFecMethod::MaxFramesFec() const {
166 return _maxFramesFec;
167}
168
marpan@webrtc.org88ad06b2012-04-20 16:05:24 +0000169bool VCMNackFecMethod::BitRateTooLowForFec(
170 const VCMProtectionParameters* parameters) {
171 // Bitrate below which we turn off FEC, regardless of reported packet loss.
172 // The condition should depend on resolution and content. For now, use
173 // threshold on bytes per frame, with some effect for the frame size.
174 // The condition for turning off FEC is also based on other factors,
175 // such as |_numLayers|, |_maxFramesFec|, and |_rtt|.
176 int estimate_bytes_per_frame = 1000 * BitsPerFrame(parameters) / 8;
177 int max_bytes_per_frame = kMaxBytesPerFrameForFec;
178 int num_pixels = parameters->codecWidth * parameters->codecHeight;
179 if (num_pixels <= 352 * 288) {
180 max_bytes_per_frame = kMaxBytesPerFrameForFecLow;
181 } else if (num_pixels > 640 * 480) {
182 max_bytes_per_frame = kMaxBytesPerFrameForFecHigh;
183 }
philipel9d3ab612015-12-21 04:12:39 -0800184 // TODO(marpan): add condition based on maximum frames used for FEC,
marpan@webrtc.org88ad06b2012-04-20 16:05:24 +0000185 // and expand condition based on frame size.
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000186 // Max round trip time threshold in ms.
187 const int64_t kMaxRttTurnOffFec = 200;
marpan@webrtc.org88ad06b2012-04-20 16:05:24 +0000188 if (estimate_bytes_per_frame < max_bytes_per_frame &&
philipel9d3ab612015-12-21 04:12:39 -0800189 parameters->numLayers < 3 && parameters->rtt < kMaxRttTurnOffFec) {
marpan@webrtc.org88ad06b2012-04-20 16:05:24 +0000190 return true;
191 }
192 return false;
193}
194
philipel9d3ab612015-12-21 04:12:39 -0800195bool VCMNackFecMethod::EffectivePacketLoss(
196 const VCMProtectionParameters* parameters) {
197 // Set the effective packet loss for encoder (based on FEC code).
198 // Compute the effective packet loss and residual packet loss due to FEC.
199 VCMFecMethod::EffectivePacketLoss(parameters);
200 return true;
mikhal@google.com022716b2011-07-20 23:12:57 +0000201}
niklase@google.com470e71d2011-07-07 08:21:25 +0000202
philipel9d3ab612015-12-21 04:12:39 -0800203bool VCMNackFecMethod::UpdateParameters(
204 const VCMProtectionParameters* parameters) {
205 ProtectionFactor(parameters);
206 EffectivePacketLoss(parameters);
207 _maxFramesFec = ComputeMaxFramesFec(parameters);
208 if (BitRateTooLowForFec(parameters)) {
209 _protectionFactorK = 0;
210 _protectionFactorD = 0;
211 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000212
philipel9d3ab612015-12-21 04:12:39 -0800213 // Protection/fec rates obtained above are defined relative to total number
214 // of packets (total rate: source + fec) FEC in RTP module assumes
215 // protection factor is defined relative to source number of packets so we
216 // should convert the factor to reduce mismatch between mediaOpt's rate and
217 // the actual one
218 _protectionFactorK = VCMFecMethod::ConvertFECRate(_protectionFactorK);
219 _protectionFactorD = VCMFecMethod::ConvertFECRate(_protectionFactorD);
niklase@google.com470e71d2011-07-07 08:21:25 +0000220
philipel9d3ab612015-12-21 04:12:39 -0800221 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000222}
223
philipel9d3ab612015-12-21 04:12:39 -0800224VCMNackMethod::VCMNackMethod() : VCMProtectionMethod() {
225 _type = kNack;
mikhal@webrtc.orga057a952011-08-26 21:17:34 +0000226}
227
philipel9d3ab612015-12-21 04:12:39 -0800228VCMNackMethod::~VCMNackMethod() {
229 //
mikhal@webrtc.orga057a952011-08-26 21:17:34 +0000230}
231
philipel9d3ab612015-12-21 04:12:39 -0800232bool VCMNackMethod::EffectivePacketLoss(
233 const VCMProtectionParameters* parameter) {
234 // Effective Packet Loss, NA in current version.
235 _effectivePacketLoss = 0;
236 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000237}
238
philipel9d3ab612015-12-21 04:12:39 -0800239bool VCMNackMethod::UpdateParameters(
240 const VCMProtectionParameters* parameters) {
241 // Compute the effective packet loss
242 EffectivePacketLoss(parameters);
niklase@google.com470e71d2011-07-07 08:21:25 +0000243
philipel9d3ab612015-12-21 04:12:39 -0800244 // nackCost = (bitRate - nackCost) * (lossPr)
245 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000246}
247
Rasmus Brandt2b9317a2019-10-30 13:01:46 +0100248VCMFecMethod::VCMFecMethod()
249 : VCMProtectionMethod(),
250 rate_control_settings_(RateControlSettings::ParseFromFieldTrials()) {
philipel9d3ab612015-12-21 04:12:39 -0800251 _type = kFec;
mikhal@webrtc.orga057a952011-08-26 21:17:34 +0000252}
Rasmus Brandt2b9317a2019-10-30 13:01:46 +0100253
254VCMFecMethod::~VCMFecMethod() = default;
mikhal@webrtc.orga057a952011-08-26 21:17:34 +0000255
philipel9d3ab612015-12-21 04:12:39 -0800256uint8_t VCMFecMethod::BoostCodeRateKey(uint8_t packetFrameDelta,
257 uint8_t packetFrameKey) const {
258 uint8_t boostRateKey = 2;
259 // Default: ratio scales the FEC protection up for I frames
260 uint8_t ratio = 1;
niklase@google.com470e71d2011-07-07 08:21:25 +0000261
philipel9d3ab612015-12-21 04:12:39 -0800262 if (packetFrameDelta > 0) {
263 ratio = (int8_t)(packetFrameKey / packetFrameDelta);
264 }
265 ratio = VCM_MAX(boostRateKey, ratio);
niklase@google.com470e71d2011-07-07 08:21:25 +0000266
philipel9d3ab612015-12-21 04:12:39 -0800267 return ratio;
niklase@google.com470e71d2011-07-07 08:21:25 +0000268}
269
philipel9d3ab612015-12-21 04:12:39 -0800270uint8_t VCMFecMethod::ConvertFECRate(uint8_t codeRateRTP) const {
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700271 return rtc::saturated_cast<uint8_t>(
272 VCM_MIN(255, (0.5 + 255.0 * codeRateRTP /
273 rtc::saturated_cast<float>(255 - codeRateRTP))));
niklase@google.com470e71d2011-07-07 08:21:25 +0000274}
275
mikhal@google.com679450f2011-08-01 22:14:58 +0000276// Update FEC with protectionFactorD
philipel9d3ab612015-12-21 04:12:39 -0800277void VCMFecMethod::UpdateProtectionFactorD(uint8_t protectionFactorD) {
278 _protectionFactorD = protectionFactorD;
mikhal@google.com679450f2011-08-01 22:14:58 +0000279}
280
mikhal@webrtc.orgd0752c32011-10-19 15:48:30 +0000281// Update FEC with protectionFactorK
philipel9d3ab612015-12-21 04:12:39 -0800282void VCMFecMethod::UpdateProtectionFactorK(uint8_t protectionFactorK) {
283 _protectionFactorK = protectionFactorK;
mikhal@webrtc.orgd0752c32011-10-19 15:48:30 +0000284}
285
philipel9d3ab612015-12-21 04:12:39 -0800286bool VCMFecMethod::ProtectionFactor(const VCMProtectionParameters* parameters) {
287 // FEC PROTECTION SETTINGS: varies with packet loss and bitrate
niklase@google.com470e71d2011-07-07 08:21:25 +0000288
philipel9d3ab612015-12-21 04:12:39 -0800289 // No protection if (filtered) packetLoss is 0
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700290 uint8_t packetLoss = rtc::saturated_cast<uint8_t>(255 * parameters->lossPr);
philipel9d3ab612015-12-21 04:12:39 -0800291 if (packetLoss == 0) {
292 _protectionFactorK = 0;
293 _protectionFactorD = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000294 return true;
philipel9d3ab612015-12-21 04:12:39 -0800295 }
296
297 // Parameters for FEC setting:
298 // first partition size, thresholds, table pars, spatial resoln fac.
299
300 // First partition protection: ~ 20%
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700301 uint8_t firstPartitionProt = rtc::saturated_cast<uint8_t>(255 * 0.20);
philipel9d3ab612015-12-21 04:12:39 -0800302
303 // Minimum protection level needed to generate one FEC packet for one
304 // source packet/frame (in RTP sender)
305 uint8_t minProtLevelFec = 85;
306
307 // Threshold on packetLoss and bitRrate/frameRate (=average #packets),
308 // above which we allocate protection to cover at least first partition.
309 uint8_t lossThr = 0;
310 uint8_t packetNumThr = 1;
311
312 // Parameters for range of rate index of table.
313 const uint8_t ratePar1 = 5;
314 const uint8_t ratePar2 = 49;
315
316 // Spatial resolution size, relative to a reference size.
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700317 float spatialSizeToRef = rtc::saturated_cast<float>(parameters->codecWidth *
318 parameters->codecHeight) /
319 (rtc::saturated_cast<float>(704 * 576));
philipel9d3ab612015-12-21 04:12:39 -0800320 // resolnFac: This parameter will generally increase/decrease the FEC rate
321 // (for fixed bitRate and packetLoss) based on system size.
322 // Use a smaller exponent (< 1) to control/soften system size effect.
323 const float resolnFac = 1.0 / powf(spatialSizeToRef, 0.3f);
324
325 const int bitRatePerFrame = BitsPerFrame(parameters);
326
327 // Average number of packets per frame (source and fec):
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700328 const uint8_t avgTotPackets = rtc::saturated_cast<uint8_t>(
329 1.5f + rtc::saturated_cast<float>(bitRatePerFrame) * 1000.0f /
330 rtc::saturated_cast<float>(8.0 * _maxPayloadSize));
philipel9d3ab612015-12-21 04:12:39 -0800331
332 // FEC rate parameters: for P and I frame
333 uint8_t codeRateDelta = 0;
334 uint8_t codeRateKey = 0;
335
336 // Get index for table: the FEC protection depends on an effective rate.
337 // The range on the rate index corresponds to rates (bps)
338 // from ~200k to ~8000k, for 30fps
339 const uint16_t effRateFecTable =
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700340 rtc::saturated_cast<uint16_t>(resolnFac * bitRatePerFrame);
341 uint8_t rateIndexTable = rtc::saturated_cast<uint8_t>(
brandtr05f845d2016-11-16 22:59:39 -0800342 VCM_MAX(VCM_MIN((effRateFecTable - ratePar1) / ratePar1, ratePar2), 0));
philipel9d3ab612015-12-21 04:12:39 -0800343
344 // Restrict packet loss range to 50:
345 // current tables defined only up to 50%
346 if (packetLoss >= kPacketLossMax) {
347 packetLoss = kPacketLossMax - 1;
348 }
349 uint16_t indexTable = rateIndexTable * kPacketLossMax + packetLoss;
350
351 // Check on table index
brandtr71b1c1f2017-01-12 06:16:24 -0800352 RTC_DCHECK_LT(indexTable, kFecRateTableSize);
philipel9d3ab612015-12-21 04:12:39 -0800353
354 // Protection factor for P frame
brandtr71b1c1f2017-01-12 06:16:24 -0800355 codeRateDelta = kFecRateTable[indexTable];
philipel9d3ab612015-12-21 04:12:39 -0800356
357 if (packetLoss > lossThr && avgTotPackets > packetNumThr) {
358 // Set a minimum based on first partition size.
359 if (codeRateDelta < firstPartitionProt) {
360 codeRateDelta = firstPartitionProt;
361 }
362 }
363
364 // Check limit on amount of protection for P frame; 50% is max.
365 if (codeRateDelta >= kPacketLossMax) {
366 codeRateDelta = kPacketLossMax - 1;
367 }
368
philipel9d3ab612015-12-21 04:12:39 -0800369 // For Key frame:
370 // Effectively at a higher rate, so we scale/boost the rate
371 // The boost factor may depend on several factors: ratio of packet
372 // number of I to P frames, how much protection placed on P frames, etc.
brandtr05f845d2016-11-16 22:59:39 -0800373 const uint8_t packetFrameDelta =
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700374 rtc::saturated_cast<uint8_t>(0.5 + parameters->packetsPerFrame);
philipel9d3ab612015-12-21 04:12:39 -0800375 const uint8_t packetFrameKey =
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700376 rtc::saturated_cast<uint8_t>(0.5 + parameters->packetsPerFrameKey);
philipel9d3ab612015-12-21 04:12:39 -0800377 const uint8_t boostKey = BoostCodeRateKey(packetFrameDelta, packetFrameKey);
378
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700379 rateIndexTable = rtc::saturated_cast<uint8_t>(VCM_MAX(
philipel9d3ab612015-12-21 04:12:39 -0800380 VCM_MIN(1 + (boostKey * effRateFecTable - ratePar1) / ratePar1, ratePar2),
brandtr05f845d2016-11-16 22:59:39 -0800381 0));
philipel9d3ab612015-12-21 04:12:39 -0800382 uint16_t indexTableKey = rateIndexTable * kPacketLossMax + packetLoss;
383
brandtr71b1c1f2017-01-12 06:16:24 -0800384 indexTableKey = VCM_MIN(indexTableKey, kFecRateTableSize);
philipel9d3ab612015-12-21 04:12:39 -0800385
386 // Check on table index
brandtr71b1c1f2017-01-12 06:16:24 -0800387 assert(indexTableKey < kFecRateTableSize);
philipel9d3ab612015-12-21 04:12:39 -0800388
389 // Protection factor for I frame
brandtr71b1c1f2017-01-12 06:16:24 -0800390 codeRateKey = kFecRateTable[indexTableKey];
philipel9d3ab612015-12-21 04:12:39 -0800391
392 // Boosting for Key frame.
393 int boostKeyProt = _scaleProtKey * codeRateDelta;
394 if (boostKeyProt >= kPacketLossMax) {
395 boostKeyProt = kPacketLossMax - 1;
396 }
397
398 // Make sure I frame protection is at least larger than P frame protection,
399 // and at least as high as filtered packet loss.
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700400 codeRateKey = rtc::saturated_cast<uint8_t>(
philipel9d3ab612015-12-21 04:12:39 -0800401 VCM_MAX(packetLoss, VCM_MAX(boostKeyProt, codeRateKey)));
402
403 // Check limit on amount of protection for I frame: 50% is max.
404 if (codeRateKey >= kPacketLossMax) {
405 codeRateKey = kPacketLossMax - 1;
406 }
407
408 _protectionFactorK = codeRateKey;
409 _protectionFactorD = codeRateDelta;
410
411 // Generally there is a rate mis-match between the FEC cost estimated
412 // in mediaOpt and the actual FEC cost sent out in RTP module.
413 // This is more significant at low rates (small # of source packets), where
414 // the granularity of the FEC decreases. In this case, non-zero protection
415 // in mediaOpt may generate 0 FEC packets in RTP sender (since actual #FEC
416 // is based on rounding off protectionFactor on actual source packet number).
417 // The correction factor (_corrFecCost) attempts to corrects this, at least
418 // for cases of low rates (small #packets) and low protection levels.
419
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700420 float numPacketsFl =
421 1.0f + (rtc::saturated_cast<float>(bitRatePerFrame) * 1000.0 /
422 rtc::saturated_cast<float>(8.0 * _maxPayloadSize) +
423 0.5);
philipel9d3ab612015-12-21 04:12:39 -0800424
425 const float estNumFecGen =
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700426 0.5f +
427 rtc::saturated_cast<float>(_protectionFactorD * numPacketsFl / 255.0f);
philipel9d3ab612015-12-21 04:12:39 -0800428
429 // We reduce cost factor (which will reduce overhead for FEC and
430 // hybrid method) and not the protectionFactor.
431 _corrFecCost = 1.0f;
432 if (estNumFecGen < 1.1f && _protectionFactorD < minProtLevelFec) {
433 _corrFecCost = 0.5f;
434 }
435 if (estNumFecGen < 0.9f && _protectionFactorD < minProtLevelFec) {
436 _corrFecCost = 0.0f;
437 }
438
philipel9d3ab612015-12-21 04:12:39 -0800439 // DONE WITH FEC PROTECTION SETTINGS
440 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000441}
442
mikhal@webrtc.org0e7d9d82011-12-19 19:04:49 +0000443int VCMFecMethod::BitsPerFrame(const VCMProtectionParameters* parameters) {
444 // When temporal layers are available FEC will only be applied on the base
445 // layer.
Erik Språngd92288f2018-07-04 10:07:40 +0200446 const float bitRateRatio =
447 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
Rasmus Brandt2b9317a2019-10-30 13:01:46 +0100448 parameters->numLayers, 0,
449 rate_control_settings_.Vp8BaseHeavyTl3RateAllocation());
thakis@chromium.org65bc2542012-08-13 19:26:12 +0000450 float frameRateRatio = powf(1 / 2.0, parameters->numLayers - 1);
mikhal@webrtc.org0e7d9d82011-12-19 19:04:49 +0000451 float bitRate = parameters->bitRate * bitRateRatio;
452 float frameRate = parameters->frameRate * frameRateRatio;
453
454 // TODO(mikhal): Update factor following testing.
455 float adjustmentFactor = 1;
456
Peter Boström5e8351b2016-01-28 23:55:29 +0100457 if (frameRate < 1.0f)
458 frameRate = 1.0f;
mikhal@webrtc.org0e7d9d82011-12-19 19:04:49 +0000459 // Average bits per frame (units of kbits)
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700460 return rtc::saturated_cast<int>(adjustmentFactor * bitRate / frameRate);
mikhal@webrtc.org0e7d9d82011-12-19 19:04:49 +0000461}
462
philipel9d3ab612015-12-21 04:12:39 -0800463bool VCMFecMethod::EffectivePacketLoss(
464 const VCMProtectionParameters* parameters) {
465 // Effective packet loss to encoder is based on RPL (residual packet loss)
466 // this is a soft setting based on degree of FEC protection
467 // RPL = received/input packet loss - average_FEC_recovery
468 // note: received/input packet loss may be filtered based on FilteredLoss
niklase@google.com470e71d2011-07-07 08:21:25 +0000469
philipel9d3ab612015-12-21 04:12:39 -0800470 // Effective Packet Loss, NA in current version.
471 _effectivePacketLoss = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000472
philipel9d3ab612015-12-21 04:12:39 -0800473 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000474}
475
philipel9d3ab612015-12-21 04:12:39 -0800476bool VCMFecMethod::UpdateParameters(const VCMProtectionParameters* parameters) {
477 // Compute the protection factor
478 ProtectionFactor(parameters);
niklase@google.com470e71d2011-07-07 08:21:25 +0000479
philipel9d3ab612015-12-21 04:12:39 -0800480 // Compute the effective packet loss
481 EffectivePacketLoss(parameters);
niklase@google.com470e71d2011-07-07 08:21:25 +0000482
philipel9d3ab612015-12-21 04:12:39 -0800483 // Protection/fec rates obtained above is defined relative to total number
484 // of packets (total rate: source+fec) FEC in RTP module assumes protection
485 // factor is defined relative to source number of packets so we should
486 // convert the factor to reduce mismatch between mediaOpt suggested rate and
487 // the actual rate
488 _protectionFactorK = ConvertFECRate(_protectionFactorK);
489 _protectionFactorD = ConvertFECRate(_protectionFactorD);
niklase@google.com470e71d2011-07-07 08:21:25 +0000490
philipel9d3ab612015-12-21 04:12:39 -0800491 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000492}
philipel9d3ab612015-12-21 04:12:39 -0800493VCMLossProtectionLogic::VCMLossProtectionLogic(int64_t nowMs)
494 : _currentParameters(),
495 _rtt(0),
496 _lossPr(0.0f),
497 _bitRate(0.0f),
498 _frameRate(0.0f),
499 _keyFrameSize(0.0f),
500 _fecRateKey(0),
501 _fecRateDelta(0),
502 _lastPrUpdateT(0),
503 _lossPr255(0.9999f),
504 _lossPrHistory(),
505 _shortMaxLossPr255(0),
506 _packetsPerFrame(0.9999f),
507 _packetsPerFrameKey(0.9999f),
Ying Wang1f262cc2018-08-23 13:54:08 +0200508 _codecWidth(704),
509 _codecHeight(576),
philipel9d3ab612015-12-21 04:12:39 -0800510 _numLayers(1) {
511 Reset(nowMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000512}
513
philipel9d3ab612015-12-21 04:12:39 -0800514VCMLossProtectionLogic::~VCMLossProtectionLogic() {
515 Release();
niklase@google.com470e71d2011-07-07 08:21:25 +0000516}
517
pbos@webrtc.orgcade82c2015-03-12 10:39:24 +0000518void VCMLossProtectionLogic::SetMethod(
519 enum VCMProtectionMethodEnum newMethodType) {
pbosba8c15b2015-07-14 09:36:34 -0700520 if (_selectedMethod && _selectedMethod->Type() == newMethodType)
521 return;
mikhal@webrtc.orga057a952011-08-26 21:17:34 +0000522
philipel9d3ab612015-12-21 04:12:39 -0800523 switch (newMethodType) {
pbos@webrtc.orgcade82c2015-03-12 10:39:24 +0000524 case kNack:
pbosba8c15b2015-07-14 09:36:34 -0700525 _selectedMethod.reset(new VCMNackMethod());
pbos@webrtc.orgcade82c2015-03-12 10:39:24 +0000526 break;
527 case kFec:
pbosba8c15b2015-07-14 09:36:34 -0700528 _selectedMethod.reset(new VCMFecMethod());
pbos@webrtc.orgcade82c2015-03-12 10:39:24 +0000529 break;
530 case kNackFec:
pbosba8c15b2015-07-14 09:36:34 -0700531 _selectedMethod.reset(new VCMNackFecMethod(kLowRttNackMs, -1));
pbos@webrtc.orgcade82c2015-03-12 10:39:24 +0000532 break;
533 case kNone:
pbosba8c15b2015-07-14 09:36:34 -0700534 _selectedMethod.reset();
pbos@webrtc.orgcade82c2015-03-12 10:39:24 +0000535 break;
536 }
537 UpdateMethod();
niklase@google.com470e71d2011-07-07 08:21:25 +0000538}
539
philipel9d3ab612015-12-21 04:12:39 -0800540void VCMLossProtectionLogic::UpdateRtt(int64_t rtt) {
541 _rtt = rtt;
niklase@google.com470e71d2011-07-07 08:21:25 +0000542}
543
philipel9d3ab612015-12-21 04:12:39 -0800544void VCMLossProtectionLogic::UpdateMaxLossHistory(uint8_t lossPr255,
545 int64_t now) {
546 if (_lossPrHistory[0].timeMs >= 0 &&
547 now - _lossPrHistory[0].timeMs < kLossPrShortFilterWinMs) {
548 if (lossPr255 > _shortMaxLossPr255) {
549 _shortMaxLossPr255 = lossPr255;
niklase@google.com470e71d2011-07-07 08:21:25 +0000550 }
philipel9d3ab612015-12-21 04:12:39 -0800551 } else {
552 // Only add a new value to the history once a second
553 if (_lossPrHistory[0].timeMs == -1) {
554 // First, no shift
555 _shortMaxLossPr255 = lossPr255;
556 } else {
557 // Shift
558 for (int32_t i = (kLossPrHistorySize - 2); i >= 0; i--) {
559 _lossPrHistory[i + 1].lossPr255 = _lossPrHistory[i].lossPr255;
560 _lossPrHistory[i + 1].timeMs = _lossPrHistory[i].timeMs;
561 }
562 }
563 if (_shortMaxLossPr255 == 0) {
564 _shortMaxLossPr255 = lossPr255;
565 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000566
philipel9d3ab612015-12-21 04:12:39 -0800567 _lossPrHistory[0].lossPr255 = _shortMaxLossPr255;
568 _lossPrHistory[0].timeMs = now;
569 _shortMaxLossPr255 = 0;
570 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000571}
572
philipel9d3ab612015-12-21 04:12:39 -0800573uint8_t VCMLossProtectionLogic::MaxFilteredLossPr(int64_t nowMs) const {
574 uint8_t maxFound = _shortMaxLossPr255;
575 if (_lossPrHistory[0].timeMs == -1) {
niklase@google.com470e71d2011-07-07 08:21:25 +0000576 return maxFound;
philipel9d3ab612015-12-21 04:12:39 -0800577 }
578 for (int32_t i = 0; i < kLossPrHistorySize; i++) {
579 if (_lossPrHistory[i].timeMs == -1) {
580 break;
581 }
582 if (nowMs - _lossPrHistory[i].timeMs >
583 kLossPrHistorySize * kLossPrShortFilterWinMs) {
584 // This sample (and all samples after this) is too old
585 break;
586 }
587 if (_lossPrHistory[i].lossPr255 > maxFound) {
588 // This sample is the largest one this far into the history
589 maxFound = _lossPrHistory[i].lossPr255;
590 }
591 }
592 return maxFound;
niklase@google.com470e71d2011-07-07 08:21:25 +0000593}
594
philipel9d3ab612015-12-21 04:12:39 -0800595uint8_t VCMLossProtectionLogic::FilteredLoss(int64_t nowMs,
596 FilterPacketLossMode filter_mode,
597 uint8_t lossPr255) {
marpan@webrtc.org2dad3fb2012-01-09 18:18:36 +0000598 // Update the max window filter.
599 UpdateMaxLossHistory(lossPr255, nowMs);
600
601 // Update the recursive average filter.
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700602 _lossPr255.Apply(rtc::saturated_cast<float>(nowMs - _lastPrUpdateT),
603 rtc::saturated_cast<float>(lossPr255));
marpan@webrtc.org2dad3fb2012-01-09 18:18:36 +0000604 _lastPrUpdateT = nowMs;
605
606 // Filtered loss: default is received loss (no filtering).
pbos@webrtc.org7b859cc2013-04-02 15:54:38 +0000607 uint8_t filtered_loss = lossPr255;
marpan@webrtc.org2dad3fb2012-01-09 18:18:36 +0000608
609 switch (filter_mode) {
610 case kNoFilter:
611 break;
612 case kAvgFilter:
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700613 filtered_loss = rtc::saturated_cast<uint8_t>(_lossPr255.filtered() + 0.5);
marpan@webrtc.org2dad3fb2012-01-09 18:18:36 +0000614 break;
615 case kMaxFilter:
616 filtered_loss = MaxFilteredLossPr(nowMs);
617 break;
618 }
619
620 return filtered_loss;
niklase@google.com470e71d2011-07-07 08:21:25 +0000621}
622
philipel9d3ab612015-12-21 04:12:39 -0800623void VCMLossProtectionLogic::UpdateFilteredLossPr(uint8_t packetLossEnc) {
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700624 _lossPr = rtc::saturated_cast<float>(packetLossEnc) / 255.0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000625}
626
philipel9d3ab612015-12-21 04:12:39 -0800627void VCMLossProtectionLogic::UpdateBitRate(float bitRate) {
628 _bitRate = bitRate;
niklase@google.com470e71d2011-07-07 08:21:25 +0000629}
630
philipel9d3ab612015-12-21 04:12:39 -0800631void VCMLossProtectionLogic::UpdatePacketsPerFrame(float nPackets,
632 int64_t nowMs) {
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700633 _packetsPerFrame.Apply(
634 rtc::saturated_cast<float>(nowMs - _lastPacketPerFrameUpdateT), nPackets);
philipel9d3ab612015-12-21 04:12:39 -0800635 _lastPacketPerFrameUpdateT = nowMs;
niklase@google.com470e71d2011-07-07 08:21:25 +0000636}
637
philipel9d3ab612015-12-21 04:12:39 -0800638void VCMLossProtectionLogic::UpdatePacketsPerFrameKey(float nPackets,
639 int64_t nowMs) {
640 _packetsPerFrameKey.Apply(
Emircan Uysaler704a7bd2018-08-06 16:14:10 -0700641 rtc::saturated_cast<float>(nowMs - _lastPacketPerFrameUpdateTKey),
642 nPackets);
philipel9d3ab612015-12-21 04:12:39 -0800643 _lastPacketPerFrameUpdateTKey = nowMs;
niklase@google.com470e71d2011-07-07 08:21:25 +0000644}
645
philipel9d3ab612015-12-21 04:12:39 -0800646void VCMLossProtectionLogic::UpdateKeyFrameSize(float keyFrameSize) {
647 _keyFrameSize = keyFrameSize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000648}
649
perkjc2c24f72016-07-11 01:47:32 -0700650void VCMLossProtectionLogic::UpdateFrameSize(size_t width, size_t height) {
philipel9d3ab612015-12-21 04:12:39 -0800651 _codecWidth = width;
652 _codecHeight = height;
niklase@google.com470e71d2011-07-07 08:21:25 +0000653}
654
mikhal@webrtc.org0e7d9d82011-12-19 19:04:49 +0000655void VCMLossProtectionLogic::UpdateNumLayers(int numLayers) {
656 _numLayers = (numLayers == 0) ? 1 : numLayers;
657}
658
philipel9d3ab612015-12-21 04:12:39 -0800659bool VCMLossProtectionLogic::UpdateMethod() {
660 if (!_selectedMethod)
661 return false;
662 _currentParameters.rtt = _rtt;
663 _currentParameters.lossPr = _lossPr;
664 _currentParameters.bitRate = _bitRate;
665 _currentParameters.frameRate = _frameRate; // rename actual frame rate?
666 _currentParameters.keyFrameSize = _keyFrameSize;
667 _currentParameters.fecRateDelta = _fecRateDelta;
668 _currentParameters.fecRateKey = _fecRateKey;
669 _currentParameters.packetsPerFrame = _packetsPerFrame.filtered();
670 _currentParameters.packetsPerFrameKey = _packetsPerFrameKey.filtered();
671 _currentParameters.codecWidth = _codecWidth;
672 _currentParameters.codecHeight = _codecHeight;
673 _currentParameters.numLayers = _numLayers;
674 return _selectedMethod->UpdateParameters(&_currentParameters);
niklase@google.com470e71d2011-07-07 08:21:25 +0000675}
676
philipel9d3ab612015-12-21 04:12:39 -0800677VCMProtectionMethod* VCMLossProtectionLogic::SelectedMethod() const {
678 return _selectedMethod.get();
niklase@google.com470e71d2011-07-07 08:21:25 +0000679}
680
pbos@webrtc.orgcade82c2015-03-12 10:39:24 +0000681VCMProtectionMethodEnum VCMLossProtectionLogic::SelectedType() const {
pbosba8c15b2015-07-14 09:36:34 -0700682 return _selectedMethod ? _selectedMethod->Type() : kNone;
mikhal@webrtc.orga057a952011-08-26 21:17:34 +0000683}
684
philipel9d3ab612015-12-21 04:12:39 -0800685void VCMLossProtectionLogic::Reset(int64_t nowMs) {
686 _lastPrUpdateT = nowMs;
687 _lastPacketPerFrameUpdateT = nowMs;
688 _lastPacketPerFrameUpdateTKey = nowMs;
689 _lossPr255.Reset(0.9999f);
690 _packetsPerFrame.Reset(0.9999f);
691 _fecRateDelta = _fecRateKey = 0;
692 for (int32_t i = 0; i < kLossPrHistorySize; i++) {
693 _lossPrHistory[i].lossPr255 = 0;
694 _lossPrHistory[i].timeMs = -1;
695 }
696 _shortMaxLossPr255 = 0;
697 Release();
mikhal@webrtc.orga057a952011-08-26 21:17:34 +0000698}
699
pbosba8c15b2015-07-14 09:36:34 -0700700void VCMLossProtectionLogic::Release() {
701 _selectedMethod.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +0000702}
703
stefan@webrtc.orga64300a2013-03-04 15:24:40 +0000704} // namespace media_optimization
705} // namespace webrtc