/work/vvenc/source/Lib/EncoderLib/RateCtrl.cpp
Line | Count | Source |
1 | | /* ----------------------------------------------------------------------------- |
2 | | The copyright in this software is being made available under the Clear BSD |
3 | | License, included below. No patent rights, trademark rights and/or |
4 | | other Intellectual Property Rights other than the copyrights concerning |
5 | | the Software are granted under this license. |
6 | | |
7 | | The Clear BSD License |
8 | | |
9 | | Copyright (c) 2019-2026, Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V. & The VVenC Authors. |
10 | | All rights reserved. |
11 | | |
12 | | Redistribution and use in source and binary forms, with or without modification, |
13 | | are permitted (subject to the limitations in the disclaimer below) provided that |
14 | | the following conditions are met: |
15 | | |
16 | | * Redistributions of source code must retain the above copyright notice, |
17 | | this list of conditions and the following disclaimer. |
18 | | |
19 | | * Redistributions in binary form must reproduce the above copyright |
20 | | notice, this list of conditions and the following disclaimer in the |
21 | | documentation and/or other materials provided with the distribution. |
22 | | |
23 | | * Neither the name of the copyright holder nor the names of its |
24 | | contributors may be used to endorse or promote products derived from this |
25 | | software without specific prior written permission. |
26 | | |
27 | | NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY |
28 | | THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND |
29 | | CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
30 | | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A |
31 | | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR |
32 | | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, |
33 | | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
34 | | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR |
35 | | BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER |
36 | | IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
37 | | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
38 | | POSSIBILITY OF SUCH DAMAGE. |
39 | | |
40 | | |
41 | | ------------------------------------------------------------------------------------------- */ |
42 | | |
43 | | |
44 | | /** \file RateCtrl.cpp |
45 | | \brief Rate control manager class |
46 | | */ |
47 | | #ifdef VVENC_ENABLE_THIRDPARTY_JSON |
48 | | #include <nlohmann/json.hpp> |
49 | | #endif |
50 | | |
51 | | #include "vvenc/version.h" |
52 | | #include "RateCtrl.h" |
53 | | #include "CommonLib/Picture.h" |
54 | | |
55 | | #include <cmath> |
56 | | |
57 | | namespace vvenc { |
58 | | |
59 | | //sequence level |
60 | | EncRCSeq::EncRCSeq() |
61 | 0 | { |
62 | 0 | twoPass = false; |
63 | 0 | isLookAhead = false; |
64 | 0 | isIntraGOP = false; |
65 | 0 | isRateSavingMode = false; |
66 | 0 | frameRate = 0.0; |
67 | 0 | targetRate = 0; |
68 | 0 | maxGopRate = 0; |
69 | 0 | gopSize = 0; |
70 | 0 | intraPeriod = 0; |
71 | 0 | bitsUsed = 0; |
72 | 0 | bitsUsedQPLimDiff = 0; |
73 | 0 | estimatedBitUsage = 0; |
74 | 0 | rateBoostFac = 1.0; |
75 | 0 | std::memset (qpCorrection, 0, sizeof (qpCorrection)); |
76 | 0 | std::memset (actualBitCnt, 0, sizeof (actualBitCnt)); |
77 | 0 | std::memset (targetBitCnt, 0, sizeof (targetBitCnt)); |
78 | 0 | lastAverageQP = 0; |
79 | 0 | lastIntraQP = 0; |
80 | 0 | lastIntraSM = 0.0; |
81 | 0 | scRelax = false; |
82 | 0 | bitDepth = 0; |
83 | 0 | } |
84 | | |
85 | | EncRCSeq::~EncRCSeq() |
86 | 0 | { |
87 | 0 | destroy(); |
88 | 0 | } |
89 | | |
90 | | void EncRCSeq::create( bool twoPassRC, bool lookAhead, int targetBitrate, int maxBitrate, double frRate, int intraPer, int GOPSize, int bitDpth, std::list<TRCPassStats> &firstPassStats ) |
91 | 0 | { |
92 | 0 | destroy(); |
93 | 0 | twoPass = twoPassRC; |
94 | 0 | isLookAhead = lookAhead; |
95 | 0 | targetRate = std::min( INT32_MAX / 3, targetBitrate ); |
96 | 0 | maxGopRate = int( 0.5 + std::min( (double) INT32_MAX, (double) std::min( 3 * targetRate, maxBitrate ) * GOPSize / frRate ) ); // 1.5x-3x is the valid range |
97 | 0 | frameRate = frRate; |
98 | 0 | intraPeriod = Clip3<unsigned>( GOPSize, 4 * VVENC_MAX_GOP, intraPer ); |
99 | 0 | gopSize = GOPSize; |
100 | 0 | firstPassData = firstPassStats; |
101 | 0 | bitDepth = bitDpth; |
102 | |
|
103 | 0 | int bitdepthLumaScale = 2 * ( bitDepth - 8 - DISTORTION_PRECISION_ADJUSTMENT( bitDepth ) ); |
104 | 0 | minEstLambda = 0.1; |
105 | 0 | maxEstLambda = 65535.9375 * pow( 2.0, bitdepthLumaScale ); |
106 | |
|
107 | 0 | bitsUsed = 0; |
108 | 0 | bitsUsedQPLimDiff = 0; |
109 | 0 | estimatedBitUsage = 0; |
110 | 0 | std::memset (qpCorrection, 0, sizeof (qpCorrection)); |
111 | 0 | std::memset (actualBitCnt, 0, sizeof (actualBitCnt)); |
112 | 0 | std::memset (targetBitCnt, 0, sizeof (targetBitCnt)); |
113 | 0 | } |
114 | | |
115 | | void EncRCSeq::destroy() |
116 | 0 | { |
117 | 0 | return; |
118 | 0 | } |
119 | | |
120 | | void EncRCSeq::updateAfterPic (const int actBits, const int tgtBits) |
121 | 0 | { |
122 | 0 | estimatedBitUsage += tgtBits; |
123 | |
|
124 | 0 | if (isLookAhead) |
125 | 0 | { |
126 | 0 | const uint64_t* const tlBits = actualBitCnt; // recently updated in EncRCPic::updateAfterPicture() |
127 | |
|
128 | 0 | bitsUsed = tlBits[0] + tlBits[1] + tlBits[2] + tlBits[3] + tlBits[4] + tlBits[5] + tlBits[6] + tlBits[7]; |
129 | 0 | } |
130 | 0 | else |
131 | 0 | { |
132 | 0 | bitsUsed += actBits; |
133 | 0 | } |
134 | 0 | } |
135 | | |
136 | | //picture level |
137 | | EncRCPic::EncRCPic() |
138 | 0 | { |
139 | 0 | encRCSeq = NULL; |
140 | 0 | frameLevel = 0; |
141 | 0 | targetBits = 0; |
142 | 0 | tmpTargetBits = 0; |
143 | 0 | picQP = 0; |
144 | 0 | picBits = 0; |
145 | 0 | poc = 0; |
146 | 0 | refreshParams = false; |
147 | 0 | visActSteady = 0; |
148 | 0 | } |
149 | | |
150 | | EncRCPic::~EncRCPic() |
151 | 0 | { |
152 | 0 | destroy(); |
153 | 0 | } |
154 | | |
155 | | static void addToPictureList( const EncRCSeq* encRCSeq, std::list<std::shared_ptr<EncRCPic>>& listPreviousPictures, std::shared_ptr<EncRCPic> thisPtr ) |
156 | 0 | { |
157 | 0 | if ( listPreviousPictures.size() > std::min( VVENC_MAX_GOP, 2 * encRCSeq->gopSize ) ) |
158 | 0 | { |
159 | 0 | listPreviousPictures.pop_front(); |
160 | 0 | } |
161 | |
|
162 | 0 | listPreviousPictures.push_back( thisPtr ); |
163 | 0 | } |
164 | | |
165 | | void EncRCPic::create( EncRCSeq* encRcSeq, int frameLvl, int framePoc ) |
166 | 0 | { |
167 | 0 | destroy(); |
168 | 0 | encRCSeq = encRcSeq; |
169 | 0 | poc = framePoc; |
170 | 0 | frameLevel = frameLvl; |
171 | 0 | } |
172 | | |
173 | | void EncRCPic::destroy() |
174 | 0 | { |
175 | 0 | encRCSeq = NULL; |
176 | 0 | } |
177 | | |
178 | | void EncRCPic::clipTargetQP (std::list<std::shared_ptr<EncRCPic>>& listPreviousPictures, const int baseQP, const int refrIncrFac, const int maxTL, const double resRatio, int &qp, int* qpAvg) |
179 | 0 | { |
180 | 0 | const int rShift = (resRatio < 0.03125 ? 12 : (resRatio < 0.125 ? 13 : (resRatio < 0.5 ? 14 : 15))); |
181 | 0 | const int initQP = qp; |
182 | 0 | int lastCurrTLQP = -1; |
183 | 0 | int lastPrevTLQP = -1; |
184 | 0 | int lastMaxTLBits = 0; |
185 | 0 | int halvedAvgQP = -1; |
186 | 0 | std::list<std::shared_ptr<EncRCPic>>::iterator it; |
187 | |
|
188 | 0 | for (it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++) |
189 | 0 | { |
190 | 0 | if ((*it)->frameLevel == frameLevel && (*it)->picQP >= 0) // current temporal level |
191 | 0 | { |
192 | 0 | lastCurrTLQP = (*it)->picQP; |
193 | 0 | } |
194 | 0 | if ((*it)->frameLevel == frameLevel - 1 && (*it)->picQP >= 0) // last temporal level |
195 | 0 | { |
196 | 0 | lastPrevTLQP = (frameLevel == 1 ? ((*it)->picQP * 3) >> 2 : std::max<int> (encRCSeq->lastIntraQP, (*it)->picQP)); |
197 | 0 | } |
198 | 0 | if ((*it)->frameLevel == 1 && frameLevel == 0 && refreshParams && lastCurrTLQP < 0) |
199 | 0 | { |
200 | 0 | lastCurrTLQP = (*it)->picQP; |
201 | 0 | } |
202 | 0 | if ((*it)->frameLevel > maxTL && (*it)->poc + 32 + encRCSeq->gopSize > poc) |
203 | 0 | { |
204 | 0 | lastMaxTLBits += (*it)->picBits; |
205 | 0 | } |
206 | 0 | halvedAvgQP += (*it)->picQP; |
207 | 0 | } |
208 | |
|
209 | 0 | if (qpAvg && !listPreviousPictures.empty()) *qpAvg = int ((halvedAvgQP + 1 + (listPreviousPictures.size() >> 1)) / listPreviousPictures.size()); |
210 | |
|
211 | 0 | if (listPreviousPictures.size() >= 1) halvedAvgQP = int ((halvedAvgQP + 1 + listPreviousPictures.size()) / (2 * listPreviousPictures.size())); |
212 | 0 | if (frameLevel <= 1 && lastPrevTLQP < halvedAvgQP) lastPrevTLQP = halvedAvgQP; // TL0I |
213 | 0 | if (frameLevel == 1 && lastCurrTLQP < 0) lastCurrTLQP = encRCSeq->lastIntraQP; // TL0B |
214 | 0 | if (frameLevel == 0 && !(lastMaxTLBits >> rShift) && maxTL) qp++; // frozen-image mode |
215 | |
|
216 | 0 | qp = Clip3 (frameLevel + std::max (0, baseQP >> 1), MAX_QP, qp); |
217 | |
|
218 | 0 | if (lastCurrTLQP >= 0) // limit QP changes among prev. frames from same temporal level |
219 | 0 | { |
220 | 0 | const int clipRange = (refreshParams ? 5 + (encRCSeq->intraPeriod + (encRCSeq->gopSize >> 1)) / encRCSeq->gopSize : std::max (3, 6 - (frameLevel >> 1))); |
221 | |
|
222 | 0 | qp = Clip3 (lastCurrTLQP - clipRange, std::min (MAX_QP, lastCurrTLQP + (refreshParams ? (refrIncrFac * clipRange) >> 1 : clipRange)), qp); |
223 | 0 | } |
224 | 0 | if (lastPrevTLQP >= 0) // prevent QP from being lower than QPs at lower temporal level |
225 | 0 | { |
226 | 0 | qp = Clip3 (std::min (MAX_QP, lastPrevTLQP + 1), MAX_QP, qp); |
227 | 0 | } |
228 | 0 | else if (encRCSeq->lastIntraQP >= -1 && (frameLevel == 1 || frameLevel == 2)) |
229 | 0 | { |
230 | 0 | qp = Clip3 ((encRCSeq->lastIntraQP >> 1) + 1, MAX_QP, qp); |
231 | 0 | } |
232 | |
|
233 | 0 | if (qp != initQP) // adjust target bits according to QP change as in VCIP paper eq.(4) |
234 | 0 | { |
235 | 0 | targetBits = (int) std::max (1.0, 0.5 + targetBits * pow (2.0, (initQP - qp) / ((105.0 / 128.0) * sqrt ((double) std::max (1, initQP))))); |
236 | 0 | } |
237 | 0 | } |
238 | | |
239 | | void EncRCPic::updateAfterPicture (const int picActualBits, const int averageQP) |
240 | 0 | { |
241 | 0 | picQP = averageQP; |
242 | 0 | picBits = (uint16_t) Clip3 (0, 65535, picActualBits); |
243 | |
|
244 | 0 | if ((frameLevel <= 7) && (picActualBits > 0) && (targetBits > 0)) // update, for initRateControlPic() |
245 | 0 | { |
246 | 0 | const uint16_t vaMin = 1u << (encRCSeq->bitDepth - 6); |
247 | 0 | const double clipVal = (visActSteady > 0 && visActSteady < vaMin + 48 ? 0.25 * (visActSteady - vaMin) : 12.0); |
248 | |
|
249 | 0 | encRCSeq->actualBitCnt[frameLevel] += (uint64_t) picActualBits; |
250 | 0 | encRCSeq->targetBitCnt[frameLevel] += (uint64_t) targetBits; |
251 | |
|
252 | 0 | if (refreshParams && frameLevel <= 2) encRCSeq->lastAverageQP = 0; |
253 | |
|
254 | 0 | encRCSeq->qpCorrection[frameLevel] = (105.0 / 128.0) * sqrt ((double) std::max (1, encRCSeq->lastAverageQP)) * log ((double) encRCSeq->actualBitCnt[frameLevel] / (double) encRCSeq->targetBitCnt[frameLevel]) / log (2.0); // adjust target bits as in VCIP paper eq.(4) |
255 | 0 | encRCSeq->qpCorrection[frameLevel] = Clip3 (-clipVal, clipVal, encRCSeq->qpCorrection[frameLevel]); |
256 | |
|
257 | 0 | if (frameLevel > std::max (1, int (log ((double) encRCSeq->gopSize) / log (2.0)))) |
258 | 0 | { |
259 | 0 | double highTlQpCorr = 0.0; |
260 | |
|
261 | 0 | for (int l = 2; l <= 7; l++) // stabilization when corrections differ between low and high levels |
262 | 0 | { |
263 | 0 | highTlQpCorr += encRCSeq->qpCorrection[l]; |
264 | 0 | } |
265 | 0 | if (highTlQpCorr > 1.0) // attenuate low-level QP correction towards 0 when bits need to be saved |
266 | 0 | { |
267 | 0 | if (encRCSeq->qpCorrection[0] < -1.0e-9) encRCSeq->qpCorrection[0] /= highTlQpCorr; |
268 | 0 | if (encRCSeq->qpCorrection[1] < -1.0e-9) encRCSeq->qpCorrection[1] /= highTlQpCorr; |
269 | 0 | } |
270 | 0 | } |
271 | 0 | } |
272 | 0 | } |
273 | | |
274 | | RateCtrl::RateCtrl(MsgLog& logger) |
275 | 1.43k | : msg ( logger ) |
276 | 1.43k | { |
277 | 1.43k | m_pcEncCfg = nullptr; |
278 | 1.43k | encRCSeq = NULL; |
279 | 1.43k | flushPOC = -1; |
280 | 1.43k | rcPass = 0; |
281 | 1.43k | rcIsFinalPass = true; |
282 | 1.43k | #ifdef VVENC_ENABLE_THIRDPARTY_JSON |
283 | 1.43k | m_pqpaStatsWritten = 0; |
284 | 1.43k | #endif |
285 | 1.43k | m_numPicStatsTotal = 0; |
286 | 1.43k | m_numPicAddedToList = 0; |
287 | 1.43k | m_updateNoisePoc = -1; |
288 | 1.43k | m_resetNoise = true; |
289 | 1.43k | m_gopMEErrorCBufIdx = 0; |
290 | 1.43k | m_maxPicMotionError = 0; |
291 | 1.43k | std::fill_n( m_gopMEErrorCBuf, QPA_MAX_NOISE_LEVELS, 0 ); |
292 | 1.43k | std::fill_n( m_minNoiseLevels, QPA_MAX_NOISE_LEVELS, 255u ); |
293 | 1.43k | std::fill_n( m_tempDownSamplStats, VVENC_MAX_TLAYER + 1, TRCPassStats() ); |
294 | 1.43k | } |
295 | | |
296 | | RateCtrl::~RateCtrl() |
297 | 1.43k | { |
298 | 1.43k | destroy(); |
299 | 1.43k | } |
300 | | |
301 | | void RateCtrl::destroy() |
302 | 4.29k | { |
303 | 4.29k | if ( encRCSeq != NULL ) |
304 | 0 | { |
305 | 0 | delete encRCSeq; |
306 | 0 | encRCSeq = NULL; |
307 | 0 | } |
308 | 4.29k | m_listRCPictures.clear(); |
309 | | |
310 | 4.29k | #ifdef VVENC_ENABLE_THIRDPARTY_JSON |
311 | 4.29k | if ( m_rcStatsFHandle.is_open() ) |
312 | 0 | { |
313 | 0 | m_rcStatsFHandle.close(); |
314 | 0 | } |
315 | 4.29k | m_pqpaStatsWritten = 0; |
316 | 4.29k | #endif |
317 | 4.29k | } |
318 | | |
319 | | void RateCtrl::init( const VVEncCfg& encCfg ) |
320 | 0 | { |
321 | 0 | destroy(); |
322 | |
|
323 | 0 | m_pcEncCfg = &encCfg; |
324 | |
|
325 | 0 | encRCSeq = new EncRCSeq; |
326 | 0 | encRCSeq->create( m_pcEncCfg->m_RCNumPasses == 2, m_pcEncCfg->m_LookAhead == 1, m_pcEncCfg->m_RCTargetBitrate, m_pcEncCfg->m_RCMaxBitrate, (double)m_pcEncCfg->m_FrameRate / m_pcEncCfg->m_FrameScale, |
327 | 0 | m_pcEncCfg->m_IntraPeriod, m_pcEncCfg->m_GOPSize, m_pcEncCfg->m_internalBitDepth[CH_L], getFirstPassStats() ); |
328 | 0 | } |
329 | | |
330 | | int RateCtrl::getBaseQP() |
331 | 0 | { |
332 | | // estimate near-optimal base QP for PPS in second RC pass |
333 | 0 | double d = (3840.0 * 2160.0) / double (m_pcEncCfg->m_SourceWidth * m_pcEncCfg->m_SourceHeight); |
334 | 0 | const double firstQPOffset = sqrt ((d * m_pcEncCfg->m_RCTargetBitrate) / 500000.0); |
335 | 0 | std::list<TRCPassStats>& firstPassData = m_listRCFirstPassStats; |
336 | 0 | int baseQP = MAX_QP; |
337 | |
|
338 | 0 | if (firstPassData.size() > 0 && encRCSeq->frameRate > 0.0) |
339 | 0 | { |
340 | 0 | const int firstPassBaseQP = (m_pcEncCfg->m_RCInitialQP > 0 ? std::min (MAX_QP, m_pcEncCfg->m_RCInitialQP) : std::max (0, MAX_QP_INIT_QPA - (m_pcEncCfg->m_FirstPassMode > 2 ? 4 : 2) - int (0.5 + firstQPOffset))); |
341 | 0 | uint64_t sumFrBits = 0; // sum of first-pass frame bits |
342 | |
|
343 | 0 | for (auto& stats : firstPassData) |
344 | 0 | { |
345 | 0 | sumFrBits += stats.numBits; |
346 | 0 | } |
347 | 0 | if (m_pcEncCfg->m_usePerceptQPA && m_pcEncCfg->m_LookAhead) // account for very low visual activity |
348 | 0 | { |
349 | 0 | const double hpEnerPic = sqrt (32.0 * double (1 << (2 * encRCSeq->bitDepth - 10)) * sqrt (d)); |
350 | 0 | uint32_t hpEner = 0; |
351 | |
|
352 | 0 | for (auto& stats : firstPassData) |
353 | 0 | { |
354 | 0 | hpEner += stats.visActY; |
355 | 0 | } |
356 | 0 | if (hpEner > 0 && hpEner < hpEnerPic * firstPassData.size()) // similar to applyQPAdaptationSlice |
357 | 0 | { |
358 | 0 | sumFrBits = uint64_t (0.5 + sumFrBits * sqrt (hpEner / (hpEnerPic * firstPassData.size()))); |
359 | 0 | } |
360 | 0 | } |
361 | 0 | baseQP = int (24.5 - log (std::max (1.0, d)) / log (2.0)); // QPstart, round(24 + 2*log2(resRatio)) |
362 | 0 | d = (double) m_pcEncCfg->m_RCTargetBitrate * (double) firstPassData.size() / (encRCSeq->frameRate * sumFrBits); |
363 | 0 | d = firstPassBaseQP - (105.0 / 128.0) * sqrt ((double) std::max (1, firstPassBaseQP)) * log (d) / log (2.0); |
364 | 0 | baseQP = int (0.5 + d + 0.5 * std::max (0.0, baseQP - d)); |
365 | 0 | } |
366 | 0 | else if (m_pcEncCfg->m_LookAhead) |
367 | 0 | { |
368 | 0 | baseQP = int (24.5 - log (std::max (1.0, d)) / log (2.0)); // QPstart, round(24 + 2*log2(resRatio)) |
369 | 0 | d = MAX_QP_INIT_QPA - 2.0 - 1.5 * firstQPOffset - 0.5 * log ((double) encRCSeq->intraPeriod / encRCSeq->gopSize) / log (2.0); |
370 | 0 | baseQP = int (0.5 + d + 0.5 * std::max (0.0, baseQP - d)); |
371 | 0 | } |
372 | |
|
373 | 0 | return Clip3 (0, MAX_QP, baseQP); |
374 | 0 | } |
375 | | |
376 | | void RateCtrl::setRCPass(const VVEncCfg& encCfg, const int pass, const char* statsFName) |
377 | 1.43k | { |
378 | 1.43k | m_pcEncCfg = &encCfg; |
379 | 1.43k | rcPass = pass; |
380 | 1.43k | rcIsFinalPass = (pass >= m_pcEncCfg->m_RCNumPasses - 1); |
381 | | |
382 | 1.43k | #ifdef VVENC_ENABLE_THIRDPARTY_JSON |
383 | 1.43k | if( m_rcStatsFHandle.is_open() ) m_rcStatsFHandle.close(); |
384 | | |
385 | 1.43k | const std::string name = statsFName != nullptr ? statsFName : ""; |
386 | 1.43k | if( name.length() ) |
387 | 0 | { |
388 | 0 | openStatsFile( name ); |
389 | 0 | if( rcIsFinalPass ) |
390 | 0 | { |
391 | 0 | readStatsFile(); |
392 | 0 | } |
393 | 0 | } |
394 | | #else |
395 | | CHECK( statsFName != nullptr && strlen( statsFName ) > 0, "reading/writing rate control statistics file not supported, please compile with json enabled" ); |
396 | | #endif |
397 | | |
398 | 1.43k | if (rcIsFinalPass && (encCfg.m_FirstPassMode > 2)) |
399 | 0 | { |
400 | 0 | adjustStatsDownsample(); |
401 | 0 | } |
402 | 1.43k | } |
403 | | |
404 | | #ifdef VVENC_ENABLE_THIRDPARTY_JSON |
405 | | void RateCtrl::openStatsFile(const std::string& name) |
406 | 0 | { |
407 | 0 | if( rcIsFinalPass ) |
408 | 0 | { |
409 | 0 | m_rcStatsFHandle.open( name, std::ios::in ); |
410 | 0 | CHECK( m_rcStatsFHandle.fail(), "unable to open rate control statistics file for reading" ); |
411 | 0 | readStatsHeader(); |
412 | 0 | } |
413 | 0 | else |
414 | 0 | { |
415 | 0 | m_rcStatsFHandle.open( name, std::ios::trunc | std::ios::out ); |
416 | 0 | CHECK( m_rcStatsFHandle.fail(), "unable to open rate control statistics file for writing" ); |
417 | 0 | writeStatsHeader(); |
418 | 0 | } |
419 | 0 | } |
420 | | |
421 | | void RateCtrl::writeStatsHeader() |
422 | 0 | { |
423 | 0 | nlohmann::json header = { |
424 | 0 | { "version", VVENC_VERSION }, |
425 | 0 | { "SourceWidth", m_pcEncCfg->m_SourceWidth }, |
426 | 0 | { "SourceHeight", m_pcEncCfg->m_SourceHeight }, |
427 | 0 | { "CTUSize", m_pcEncCfg->m_CTUSize }, |
428 | 0 | { "GOPSize", m_pcEncCfg->m_GOPSize }, |
429 | 0 | { "IntraPeriod", m_pcEncCfg->m_IntraPeriod }, |
430 | 0 | { "PQPA", m_pcEncCfg->m_usePerceptQPA }, |
431 | 0 | { "QP", m_pcEncCfg->m_QP }, |
432 | 0 | { "RCInitialQP", m_pcEncCfg->m_RCInitialQP } |
433 | 0 | }; |
434 | 0 | m_rcStatsFHandle << header << std::endl; |
435 | 0 | } |
436 | | |
437 | | void RateCtrl::readStatsHeader() |
438 | 0 | { |
439 | 0 | std::string line; |
440 | 0 | if( ! std::getline( m_rcStatsFHandle, line ) ) |
441 | 0 | { |
442 | 0 | THROW( "unable to read header from rate control statistics file" ); |
443 | 0 | } |
444 | 0 | nlohmann::json header = nlohmann::json::parse( line ); |
445 | 0 | if( header.find( "version" ) == header.end() || ! header[ "version" ].is_string() |
446 | 0 | || header.find( "SourceWidth" ) == header.end() || ! header[ "SourceWidth" ].is_number() |
447 | 0 | || header.find( "SourceHeight" ) == header.end() || ! header[ "SourceHeight" ].is_number() |
448 | 0 | || header.find( "CTUSize" ) == header.end() || ! header[ "CTUSize" ].is_number() |
449 | 0 | || header.find( "GOPSize" ) == header.end() || ! header[ "GOPSize" ].is_number() |
450 | 0 | || header.find( "IntraPeriod" ) == header.end() || ! header[ "IntraPeriod" ].is_number() |
451 | 0 | || header.find( "PQPA" ) == header.end() || ! header[ "PQPA" ].is_boolean() |
452 | 0 | || header.find( "QP" ) == header.end() || ! header[ "QP" ].is_number() |
453 | 0 | || header.find( "RCInitialQP" ) == header.end() || ! header[ "RCInitialQP" ].is_number() |
454 | 0 | ) |
455 | 0 | { |
456 | 0 | THROW( "header line in rate control statistics file not recognized" ); |
457 | 0 | } |
458 | 0 | if( header[ "version" ] != VVENC_VERSION ) msg.log( VVENC_WARNING, "WARNING: wrong version in rate control statistics file\n" ); |
459 | 0 | if( header[ "SourceWidth" ] != m_pcEncCfg->m_SourceWidth ) msg.log( VVENC_WARNING, "WARNING: wrong frame width in rate control statistics file\n" ); |
460 | 0 | if( header[ "SourceHeight" ] != m_pcEncCfg->m_SourceHeight ) msg.log( VVENC_WARNING, "WARNING: wrong frame height in rate control statistics file\n" ); |
461 | 0 | if( header[ "CTUSize" ] != m_pcEncCfg->m_CTUSize ) msg.log( VVENC_WARNING, "WARNING: wrong CTU size in rate control statistics file\n" ); |
462 | 0 | if( header[ "GOPSize" ] != m_pcEncCfg->m_GOPSize ) msg.log( VVENC_WARNING, "WARNING: wrong GOP size in rate control statistics file\n" ); |
463 | 0 | if( header[ "IntraPeriod" ] != m_pcEncCfg->m_IntraPeriod ) msg.log( VVENC_WARNING, "WARNING: wrong intra period in rate control statistics file\n" ); |
464 | 0 | } |
465 | | #endif // VVENC_ENABLE_THIRDPARTY_JSON |
466 | | |
467 | | void RateCtrl::storeStatsData( TRCPassStats statsData ) |
468 | 0 | { |
469 | 0 | if( m_pcEncCfg->m_FirstPassMode == 2 || m_pcEncCfg->m_FirstPassMode == 4) |
470 | 0 | { |
471 | 0 | CHECK( statsData.tempLayer > VVENC_MAX_TLAYER, "array index out of bounds" ); |
472 | 0 | if( statsData.numBits ) |
473 | 0 | { |
474 | 0 | m_tempDownSamplStats[ statsData.tempLayer ] = statsData; |
475 | 0 | } |
476 | 0 | else |
477 | 0 | { |
478 | 0 | const TRCPassStats& srcData = m_tempDownSamplStats[ statsData.tempLayer ]; |
479 | 0 | CHECK( srcData.numBits == 0, "miss stats data from previous frame for temporal down-sampling" ); |
480 | 0 | CHECK( statsData.poc - srcData.poc >= m_pcEncCfg->m_GOPSize, "miss stats data from previous frame for temporal down-sampling" ); |
481 | 0 | statsData.qp = srcData.qp; |
482 | 0 | statsData.lambda = srcData.lambda; |
483 | 0 | if( statsData.visActY == 0 && statsData.spVisAct == 0 ) |
484 | 0 | statsData.spVisAct = srcData.spVisAct; |
485 | 0 | if( statsData.visActY == 0 ) |
486 | 0 | statsData.visActY = srcData.visActY; |
487 | 0 | statsData.numBits = srcData.numBits; |
488 | 0 | statsData.psnrY = srcData.psnrY; |
489 | 0 | } |
490 | 0 | } |
491 | 0 | #ifdef VVENC_ENABLE_THIRDPARTY_JSON |
492 | 0 | nlohmann::json data = { |
493 | 0 | { "poc", statsData.poc }, |
494 | 0 | { "qp", statsData.qp }, |
495 | 0 | { "lambda", statsData.lambda }, |
496 | 0 | { "visActY", statsData.visActY }, |
497 | 0 | { "numBits", statsData.numBits }, |
498 | 0 | { "psnrY", statsData.psnrY }, |
499 | 0 | { "isIntra", statsData.isIntra }, |
500 | 0 | { "tempLayer", statsData.tempLayer }, |
501 | 0 | { "isStartOfIntra", statsData.isStartOfIntra }, |
502 | 0 | { "isStartOfGop", statsData.isStartOfGop }, |
503 | 0 | { "gopNum", statsData.gopNum }, |
504 | 0 | { "scType", statsData.scType }, |
505 | 0 | }; |
506 | |
|
507 | 0 | if( m_pcEncCfg->m_FirstPassMode > 2 ) |
508 | 0 | { |
509 | 0 | data[ "spVisAct" ] = statsData.spVisAct; |
510 | 0 | statsData.spVisAct = data[ "spVisAct" ]; |
511 | 0 | } |
512 | |
|
513 | 0 | if( m_rcStatsFHandle.is_open() ) |
514 | 0 | { |
515 | 0 | CHECK( ! m_rcStatsFHandle.good(), "unable to write to rate control statistics file" ); |
516 | 0 | if( m_listRCIntraPQPAStats.size() > m_pqpaStatsWritten ) |
517 | 0 | { |
518 | 0 | std::vector<uint8_t> pqpaTemp; |
519 | 0 | while( m_pqpaStatsWritten < (int)m_listRCIntraPQPAStats.size() ) |
520 | 0 | { |
521 | 0 | pqpaTemp.push_back( m_listRCIntraPQPAStats[ m_pqpaStatsWritten ] ); |
522 | 0 | m_pqpaStatsWritten++; |
523 | 0 | } |
524 | 0 | data[ "pqpaStats" ] = pqpaTemp; |
525 | 0 | } |
526 | 0 | m_rcStatsFHandle << data << std::endl; |
527 | 0 | } |
528 | 0 | else |
529 | 0 | { |
530 | | // ensure same precision for internal and written data by serializing internal data as well |
531 | 0 | std::stringstream iss; |
532 | 0 | iss << data; |
533 | 0 | data = nlohmann::json::parse( iss.str() ); |
534 | 0 | std::list<TRCPassStats>& listRCFirstPassStats = m_pcEncCfg->m_LookAhead ? m_firstPassCache : m_listRCFirstPassStats; |
535 | 0 | listRCFirstPassStats.push_back( TRCPassStats( data[ "poc" ], |
536 | 0 | data[ "qp" ], |
537 | 0 | data[ "lambda" ], |
538 | 0 | data[ "visActY" ], |
539 | 0 | data[ "numBits" ], |
540 | 0 | data[ "psnrY" ], |
541 | 0 | data[ "isIntra" ], |
542 | 0 | data[ "tempLayer" ], |
543 | 0 | data[ "isStartOfIntra" ], |
544 | 0 | data[ "isStartOfGop" ], |
545 | 0 | data[ "gopNum" ], |
546 | 0 | data[ "scType" ], |
547 | 0 | statsData.spVisAct, |
548 | 0 | statsData.motionEstError, |
549 | 0 | statsData.minNoiseLevels |
550 | 0 | ) ); |
551 | 0 | } |
552 | 0 | m_numPicStatsTotal++; |
553 | | #else |
554 | | m_listRCFirstPassStats.push_back( statsData ); |
555 | | |
556 | | if( m_pcEncCfg->m_LookAhead && (int) m_listRCFirstPassStats.size() > encRCSeq->intraPeriod + encRCSeq->gopSize + 1 ) |
557 | | { |
558 | | m_listRCFirstPassStats.pop_front(); |
559 | | } |
560 | | #endif |
561 | 0 | } |
562 | | |
563 | | #ifdef VVENC_ENABLE_THIRDPARTY_JSON |
564 | | void RateCtrl::readStatsFile() |
565 | 0 | { |
566 | 0 | CHECK( ! m_rcStatsFHandle.good(), "unable to read from rate control statistics file" ); |
567 | |
|
568 | 0 | uint8_t minNoiseLevels[ QPA_MAX_NOISE_LEVELS ]; |
569 | 0 | std::fill_n( minNoiseLevels, QPA_MAX_NOISE_LEVELS, 255u ); |
570 | |
|
571 | 0 | int lineNum = 2; |
572 | 0 | std::string line; |
573 | 0 | while( std::getline( m_rcStatsFHandle, line ) ) |
574 | 0 | { |
575 | 0 | nlohmann::json data = nlohmann::json::parse( line ); |
576 | 0 | if( data.find( "poc" ) == data.end() || ! data[ "poc" ].is_number() |
577 | 0 | || data.find( "qp" ) == data.end() || ! data[ "qp" ].is_number() |
578 | 0 | || data.find( "lambda" ) == data.end() || ! data[ "lambda" ].is_number() |
579 | 0 | || data.find( "visActY" ) == data.end() || ! data[ "visActY" ].is_number() |
580 | 0 | || data.find( "numBits" ) == data.end() || ! data[ "numBits" ].is_number() |
581 | 0 | || data.find( "psnrY" ) == data.end() || ! data[ "psnrY" ].is_number() |
582 | 0 | || data.find( "isIntra" ) == data.end() || ! data[ "isIntra" ].is_boolean() |
583 | 0 | || data.find( "tempLayer" ) == data.end() || ! data[ "tempLayer" ].is_number() |
584 | 0 | || data.find( "isStartOfIntra" ) == data.end() || ! data[ "isStartOfIntra" ].is_boolean() |
585 | 0 | || data.find( "isStartOfGop" ) == data.end() || ! data[ "isStartOfGop" ].is_boolean() |
586 | 0 | || data.find( "gopNum" ) == data.end() || ! data[ "gopNum" ].is_number() |
587 | 0 | || data.find( "scType" ) == data.end() || ! data[ "scType" ].is_number() ) |
588 | 0 | { |
589 | 0 | THROW( "syntax of rate control statistics file in line " << lineNum << " not recognized: (" << line << ")" ); |
590 | 0 | } |
591 | 0 | int spVisAct = 0; |
592 | 0 | if( data.find( "spVisAct" ) != data.end() ) |
593 | 0 | { |
594 | 0 | CHECK( ! data[ "spVisAct" ].is_number(), "spatial visual activity in rate control statistics file must be a number" ); |
595 | 0 | spVisAct = data[ "spVisAct" ]; |
596 | 0 | } |
597 | 0 | m_listRCFirstPassStats.push_back( TRCPassStats( data[ "poc" ], |
598 | 0 | data[ "qp" ], |
599 | 0 | data[ "lambda" ], |
600 | 0 | data[ "visActY" ], |
601 | 0 | data[ "numBits" ], |
602 | 0 | data[ "psnrY" ], |
603 | 0 | data[ "isIntra" ], |
604 | 0 | data[ "tempLayer" ], |
605 | 0 | data[ "isStartOfIntra" ], |
606 | 0 | data[ "isStartOfGop" ], |
607 | 0 | data[ "gopNum" ], |
608 | 0 | data[ "scType" ], |
609 | 0 | spVisAct, |
610 | 0 | 0, // motionEstError |
611 | 0 | minNoiseLevels |
612 | 0 | ) ); |
613 | 0 | if( data.find( "pqpaStats" ) != data.end() ) |
614 | 0 | { |
615 | 0 | CHECK( ! data[ "pqpaStats" ].is_array(), "pqpa array data in rate control statistics file not recognized" ); |
616 | 0 | std::vector<uint8_t> pqpaTemp = data[ "pqpaStats" ]; |
617 | 0 | for( auto el : pqpaTemp ) |
618 | 0 | { |
619 | 0 | m_listRCIntraPQPAStats.push_back( el ); |
620 | 0 | } |
621 | 0 | } |
622 | 0 | lineNum++; |
623 | 0 | } |
624 | 0 | } |
625 | | #endif |
626 | | |
627 | | void RateCtrl::adjustStatsDownsample() |
628 | 0 | { |
629 | 0 | int64_t meanValue = 0; //MCTF or Activity |
630 | 0 | int amount = 0; |
631 | 0 | auto itr = m_listRCFirstPassStats.begin(); |
632 | 0 | for (; itr != m_listRCFirstPassStats.end(); itr++) |
633 | 0 | { |
634 | 0 | auto& stat = *itr; |
635 | 0 | int statValue = stat.spVisAct; |
636 | 0 | if (statValue != 0) |
637 | 0 | { |
638 | 0 | meanValue += statValue; |
639 | 0 | amount++; |
640 | 0 | } |
641 | 0 | stat.numBits = stat.numBits << 1; |
642 | 0 | } |
643 | 0 | if (meanValue != 0) |
644 | 0 | { |
645 | 0 | meanValue = meanValue / amount; |
646 | 0 | int64_t sumVar = 0; |
647 | 0 | int numVar = 0; |
648 | 0 | auto itrv = m_listRCFirstPassStats.begin(); |
649 | 0 | for (; itrv != m_listRCFirstPassStats.end(); itrv++) |
650 | 0 | { |
651 | 0 | auto& stat = *itrv; |
652 | 0 | if (stat.spVisAct != 0) |
653 | 0 | { |
654 | 0 | sumVar += (std::abs(stat.spVisAct - meanValue) * std::abs(stat.spVisAct - meanValue)); |
655 | 0 | numVar++; |
656 | 0 | } |
657 | 0 | } |
658 | 0 | if (numVar) |
659 | 0 | { |
660 | 0 | sumVar = sumVar / std::max(1, numVar - 1); |
661 | 0 | sumVar = int64_t (0.5 + sqrt((double) sumVar)); |
662 | 0 | } |
663 | 0 | int value_gopbefore = 0; |
664 | 0 | int value_gopcur = 0; |
665 | 0 | int num_gopcur = 0; |
666 | 0 | int gopcur = 0; |
667 | 0 | bool doChangeBits = false; |
668 | 0 | auto itr = m_listRCFirstPassStats.begin(); |
669 | 0 | for (; itr != m_listRCFirstPassStats.end(); itr++) |
670 | 0 | { |
671 | 0 | auto& stat = *itr; |
672 | 0 | int statValue = stat.spVisAct; |
673 | 0 | if (gopcur != stat.gopNum) |
674 | 0 | { |
675 | 0 | gopcur = stat.gopNum; |
676 | 0 | if (num_gopcur) |
677 | 0 | { |
678 | 0 | value_gopbefore = value_gopcur / num_gopcur; |
679 | 0 | } |
680 | 0 | else |
681 | 0 | { |
682 | 0 | value_gopbefore = value_gopcur; |
683 | 0 | } |
684 | 0 | value_gopcur = 0; |
685 | 0 | num_gopcur = 0; |
686 | 0 | doChangeBits = false; |
687 | 0 | } |
688 | 0 | if (statValue != 0) |
689 | 0 | { |
690 | 0 | value_gopcur += statValue; |
691 | 0 | num_gopcur++; |
692 | 0 | doChangeBits = false; |
693 | 0 | if (stat.gopNum != 0) |
694 | 0 | { |
695 | 0 | const int64_t var_cur = std::abs(statValue - meanValue); |
696 | 0 | if (var_cur > (sumVar << 1)) |
697 | 0 | { |
698 | 0 | doChangeBits = true; |
699 | 0 | } |
700 | 0 | else |
701 | 0 | { |
702 | 0 | int rate1 = (((value_gopcur / num_gopcur) * 100) / meanValue); |
703 | 0 | int rate2 = (value_gopbefore == 0) ? 100 : (((value_gopcur / num_gopcur) * 100) / value_gopbefore); |
704 | 0 | if ((rate1 > 140) || (rate1 < 60) |
705 | 0 | || (rate2 > 140) || (rate2 < 60)) |
706 | 0 | { |
707 | 0 | doChangeBits = true; |
708 | 0 | } |
709 | 0 | } |
710 | 0 | } |
711 | 0 | } |
712 | 0 | if ((stat.gopNum != 0) && doChangeBits && (stat.tempLayer > 1)) |
713 | 0 | { |
714 | 0 | stat.numBits = (stat.numBits * 3) >> 1; |
715 | 0 | } |
716 | 0 | } |
717 | 0 | } |
718 | 0 | } |
719 | | |
720 | | void RateCtrl::setRCRateSavingState( const int maxRate ) |
721 | 0 | { |
722 | 0 | if ( m_pcEncCfg->m_LookAhead && maxRate < encRCSeq->targetRate ) // end of video: incomplete I-period? |
723 | 0 | { |
724 | 0 | encRCSeq->isIntraGOP = false; |
725 | 0 | } |
726 | 0 | encRCSeq->isRateSavingMode = true; |
727 | 0 | } |
728 | | |
729 | | void RateCtrl::processFirstPassData( const bool flush, const int poc /*= -1*/ ) |
730 | 0 | { |
731 | 0 | if( m_pcEncCfg->m_RCNumPasses > 1 ) |
732 | 0 | { |
733 | | // two pass rc |
734 | 0 | CHECK( m_pcEncCfg->m_LookAhead, "two pass rc does not support look-ahead mode" ); |
735 | |
|
736 | 0 | xProcessFirstPassData( flush, poc ); |
737 | 0 | } |
738 | 0 | else |
739 | 0 | { |
740 | | // single pass rc |
741 | 0 | CHECK( !m_pcEncCfg->m_LookAhead, "single pass rc should be only used in look-ahead mode" ); |
742 | 0 | CHECK( m_firstPassCache.size() == 0, "no data available from the first pass" ); |
743 | 0 | CHECK( poc < 0, "no valid poc given" ); |
744 | | |
745 | | // fetch RC data for the next look-ahead chunk |
746 | | // the next look-ahead chunk starts with a given POC, so find a pic for a given POC in cache |
747 | | // NOTE!!!: pictures in cache are in coding order |
748 | |
|
749 | 0 | auto picCacheItr = find_if( m_firstPassCache.begin(), m_firstPassCache.end(), [poc]( auto& picStat ) { return picStat.poc == poc; } ); |
750 | |
|
751 | 0 | for( int count = 0; picCacheItr != m_firstPassCache.end(); ++picCacheItr ) |
752 | 0 | { |
753 | 0 | auto& picStat = *picCacheItr; |
754 | 0 | count++; |
755 | 0 | if( !picStat.addedToList ) |
756 | 0 | { |
757 | 0 | picStat.addedToList = true; |
758 | 0 | m_numPicAddedToList++; |
759 | 0 | m_listRCFirstPassStats.push_back( picStat ); |
760 | 0 | if( m_pcEncCfg->m_LookAhead && (int) m_listRCFirstPassStats.size() > encRCSeq->intraPeriod + encRCSeq->gopSize + 1 ) |
761 | 0 | { |
762 | 0 | m_listRCFirstPassStats.pop_front(); |
763 | 0 | m_firstPassCache.pop_front(); |
764 | 0 | } |
765 | | |
766 | | // the chunk is considered to contain a particular number of pictures up to the picture starting the next GOP (including it) |
767 | | // in flush-mode, ensure the deterministic definition of last chunk |
768 | 0 | if( ( count >= m_pcEncCfg->m_GOPSize + 1 || ( m_listRCFirstPassStats.size() > 2 && picStat.isStartOfGop ) ) && !( flush && m_numPicAddedToList > m_numPicStatsTotal - m_pcEncCfg->m_GOPSize ) ) |
769 | 0 | break; |
770 | 0 | } |
771 | 0 | } |
772 | | // enable flush only in last chunk (provides correct calculation of flushPOC) |
773 | 0 | xProcessFirstPassData( flush && ( m_numPicAddedToList == m_numPicStatsTotal ), poc ); |
774 | 0 | } |
775 | 0 | } |
776 | | |
777 | | void RateCtrl::xProcessFirstPassData( const bool flush, const int poc ) |
778 | 0 | { |
779 | 0 | CHECK( m_listRCFirstPassStats.size() == 0, "No data available from the first pass!" ); |
780 | |
|
781 | 0 | m_listRCFirstPassStats.sort( []( const TRCPassStats& a, const TRCPassStats& b ) { return a.poc < b.poc; } ); |
782 | |
|
783 | 0 | if ( flush || !m_pcEncCfg->m_LookAhead ) |
784 | 0 | { |
785 | | // store start POC of last chunk of pictures |
786 | 0 | flushPOC = m_listRCFirstPassStats.back().poc - std::max( 32, m_pcEncCfg->m_GOPSize ); |
787 | 0 | } |
788 | 0 | if ( flush && m_pcEncCfg->m_LookAhead ) |
789 | 0 | { |
790 | 0 | encRCSeq->isRateSavingMode = true; |
791 | 0 | } |
792 | | |
793 | | // perform a simple scene change detection on first-pass data and update RC parameters when new scenes are detected |
794 | 0 | detectSceneCuts(); |
795 | | |
796 | | // process and scale GOP and frame bits using the data from the first pass to account for different target bitrates |
797 | 0 | processGops(); |
798 | |
|
799 | 0 | if( m_pcEncCfg->m_GOPSize > 8 |
800 | 0 | && m_pcEncCfg->m_IntraPeriod >= m_pcEncCfg->m_GOPSize |
801 | 0 | && ( m_pcEncCfg->m_usePerceptQPA || m_pcEncCfg->m_vvencMCTF.MCTF > 0 ) |
802 | 0 | && m_pcEncCfg->m_RCNumPasses == 1 ) |
803 | 0 | { |
804 | 0 | updateMotionErrStatsGop( flush, poc ); |
805 | 0 | } |
806 | |
|
807 | 0 | encRCSeq->firstPassData = m_listRCFirstPassStats; |
808 | 0 | } |
809 | | |
810 | | double RateCtrl::getAverageBitsFromFirstPass() |
811 | 0 | { |
812 | 0 | const uint16_t vaMin = 1u << (encRCSeq->bitDepth - 6); |
813 | 0 | const int16_t factor = (m_pcEncCfg->m_QP > 27 ? 2 : 3); |
814 | 0 | const uint32_t shift = (m_pcEncCfg->m_QP > 37 ? 1 : 4); |
815 | 0 | int vaTm1 = 0, vaTm2 = 0; // temporal memories |
816 | 0 | uint64_t totalBitsFirstPass = 0; |
817 | 0 | std::list<TRCPassStats>::iterator it; |
818 | |
|
819 | 0 | if (encRCSeq->intraPeriod > 1 && encRCSeq->gopSize > 1 && m_pcEncCfg->m_LookAhead) |
820 | 0 | { |
821 | 0 | const int gopsInIp = (2 * encRCSeq->intraPeriod + (encRCSeq->gopSize >> 1)) / encRCSeq->gopSize; |
822 | 0 | int l = 2 - (gopsInIp & 1); // fract. tuning |
823 | 0 | uint64_t tlBits [8] = { 0 }; |
824 | 0 | unsigned tlCount[8] = { 0 }; |
825 | |
|
826 | 0 | for (it = m_listRCFirstPassStats.begin(); it != m_listRCFirstPassStats.end(); it++) // sum per level |
827 | 0 | { |
828 | 0 | if (tlBits[it->tempLayer] > 0 && it->refreshParameters) |
829 | 0 | { |
830 | | // take maximum of average temporal level-wise bit counts from last scene and from current scene |
831 | 0 | tlBits[it->tempLayer] = (tlBits[it->tempLayer] + (tlCount[it->tempLayer] >> 1)) / std::max (1u, tlCount[it->tempLayer]); |
832 | 0 | tlBits[it->tempLayer] = std::max (tlBits[it->tempLayer], (uint64_t) it->numBits); |
833 | 0 | tlCount[it->tempLayer] = 1; |
834 | 0 | } |
835 | 0 | else |
836 | 0 | { |
837 | 0 | tlBits[it->tempLayer] += it->numBits; |
838 | 0 | tlCount[it->tempLayer]++; |
839 | 0 | } |
840 | 0 | } |
841 | 0 | if (tlBits[0] == 0) |
842 | 0 | { |
843 | 0 | l = 0; // no I-frame in the analysis range |
844 | 0 | } |
845 | |
|
846 | 0 | totalBitsFirstPass = (2 * tlBits[0] + (tlCount[0] >> 1)) / std::max (1u, tlCount[0]) + |
847 | 0 | ((gopsInIp - l) * tlBits[1] + (tlCount[1] >> 1)) / std::max (1u, tlCount[1]); |
848 | 0 | for (l = 2; l <= 7; l++) |
849 | 0 | { |
850 | 0 | totalBitsFirstPass += ((gopsInIp << (l - 2)) * tlBits[l] + (tlCount[l] >> 1)) / std::max (1u, tlCount[l]); |
851 | 0 | } |
852 | |
|
853 | 0 | return totalBitsFirstPass / (2.0 * encRCSeq->intraPeriod); |
854 | 0 | } |
855 | | |
856 | 0 | for (it = m_listRCFirstPassStats.begin(); it != m_listRCFirstPassStats.end(); it++) // for two-pass RC |
857 | 0 | { |
858 | 0 | const int vaTmp = std::max (0, (it->visActY << (12 - encRCSeq->bitDepth)) - it->spVisAct); |
859 | 0 | const int vaSum = vaTmp + vaTm2; // improve rate match on temporally downsampled or very dark videos |
860 | |
|
861 | 0 | if (vaSum > 0 && vaTm1 * 2 * factor < vaSum && vaTm2 * 4 > vaTmp * 3 && vaTm2 * 3 < vaTmp * 4) |
862 | 0 | { |
863 | 0 | totalBitsFirstPass += (it->numBits * uint64_t (vaSum + vaTm1 * 2) * factor + (vaSum * 2)) / (vaSum * (factor + 1)); |
864 | 0 | } |
865 | 0 | else |
866 | 0 | { |
867 | 0 | totalBitsFirstPass += (it->visActY >= vaMin && it->visActY < vaMin + (1u << shift) ? (it->numBits * (it->visActY + 1u - vaMin)) >> shift : it->numBits); |
868 | 0 | } |
869 | |
|
870 | 0 | vaTm2 = vaTm1; |
871 | 0 | vaTm1 = vaTmp; |
872 | 0 | } |
873 | |
|
874 | 0 | return totalBitsFirstPass / (double) m_listRCFirstPassStats.size(); |
875 | 0 | } |
876 | | |
877 | | void RateCtrl::detectSceneCuts() |
878 | 0 | { |
879 | 0 | const int minPocDif = (encRCSeq->gopSize + 1) >> 1; |
880 | 0 | double psnrTL01Prev = 0.0; |
881 | 0 | int sceneCutPocPrev = -minPocDif; |
882 | 0 | uint16_t visActPrev = 0; |
883 | 0 | bool needRefresh[8] = { false }; |
884 | 0 | std::list<TRCPassStats>::iterator it = m_listRCFirstPassStats.begin(); |
885 | |
|
886 | 0 | visActPrev = it->visActY; |
887 | 0 | if (it->tempLayer <= 1) psnrTL01Prev = it->psnrY; |
888 | 0 | it->refreshParameters = (it->poc == 0); |
889 | |
|
890 | 0 | for (it++; it != m_listRCFirstPassStats.end(); it++) |
891 | 0 | { |
892 | 0 | const int tmpLevel = it->tempLayer; |
893 | 0 | const bool isTL01 = (tmpLevel <= 1); |
894 | |
|
895 | 0 | it->isNewScene = ((it->visActY * 64 > visActPrev * 181) || (isTL01 && it->visActY <= (1u << (encRCSeq->bitDepth - 6))) || (isTL01 && it->visActY + 3 > visActPrev && psnrTL01Prev > 0.0 && std::abs (it->psnrY - psnrTL01Prev) > 4.5)); |
896 | |
|
897 | 0 | if (it->isNewScene) // filter out scene cuts which happen too closely to the last detected scene cut |
898 | 0 | { |
899 | 0 | if (it->poc >= sceneCutPocPrev + minPocDif) |
900 | 0 | { |
901 | 0 | for (int frameLevel = 0; frameLevel <= m_pcEncCfg->m_maxTLayer + 1; frameLevel++) |
902 | 0 | { |
903 | 0 | needRefresh[frameLevel] = true; |
904 | 0 | } |
905 | 0 | sceneCutPocPrev = it->poc; |
906 | 0 | } |
907 | 0 | else |
908 | 0 | { |
909 | 0 | it->isNewScene = false; |
910 | 0 | } |
911 | 0 | } |
912 | 0 | if (it->scType == SCT_TL0_SCENE_CUT && !needRefresh[0]) // assume scene cuts at all adapted I-frames |
913 | 0 | { |
914 | 0 | it->isNewScene = needRefresh[0] = needRefresh[1] = needRefresh[2] = true; |
915 | 0 | } |
916 | |
|
917 | 0 | it->refreshParameters = needRefresh[tmpLevel]; |
918 | 0 | needRefresh[tmpLevel] = false; |
919 | |
|
920 | 0 | visActPrev = it->visActY; |
921 | 0 | if (isTL01) psnrTL01Prev = it->psnrY; |
922 | 0 | } |
923 | 0 | } |
924 | | |
925 | | void RateCtrl::processGops() |
926 | 0 | { |
927 | 0 | const double bp1pf = getAverageBitsFromFirstPass(); // first-pass bits/frame |
928 | 0 | const double ratio = (double) encRCSeq->targetRate / (encRCSeq->frameRate * bp1pf); // 2nd-to-1st pass |
929 | 0 | double fac; |
930 | 0 | int vecIdx; |
931 | 0 | int gopNum; |
932 | 0 | std::list<TRCPassStats>::iterator it; |
933 | 0 | std::vector<uint32_t> gopBits (2 + (m_listRCFirstPassStats.back().gopNum - m_listRCFirstPassStats.front().gopNum)); // +2 for the first I frame (GOP) and a potential last incomplete GOP |
934 | 0 | std::vector<float> gopTempVal (2 + (m_listRCFirstPassStats.back().gopNum - m_listRCFirstPassStats.front().gopNum)); |
935 | |
|
936 | 0 | vecIdx = 0; |
937 | 0 | gopNum = m_listRCFirstPassStats.front().gopNum; |
938 | 0 | for (it = m_listRCFirstPassStats.begin(); it != m_listRCFirstPassStats.end(); it++) // scaling, part 1 |
939 | 0 | { |
940 | 0 | if (it->gopNum > gopNum) |
941 | 0 | { |
942 | 0 | vecIdx++; |
943 | 0 | gopNum = it->gopNum; |
944 | 0 | } |
945 | 0 | CHECK (vecIdx >= (int) gopBits.size(), "array idx out of bounds"); |
946 | 0 | it->targetBits = (int) std::max (1.0, 0.5 + it->numBits * ratio); |
947 | 0 | gopBits[vecIdx] += (uint32_t) it->targetBits; // sum is gf in VCIP'21 paper |
948 | |
|
949 | 0 | if (it->poc == 0 && it->isIntra) // put the first I-frame into separate GOP |
950 | 0 | { |
951 | 0 | vecIdx++; |
952 | 0 | } |
953 | 0 | } |
954 | | |
955 | 0 | vecIdx = 0; |
956 | 0 | fac = 1.0 / gopBits[vecIdx]; |
957 | 0 | gopTempVal[vecIdx] = 1.0f; |
958 | 0 | gopNum = m_listRCFirstPassStats.front().gopNum; |
959 | 0 | for (it = m_listRCFirstPassStats.begin(); it != m_listRCFirstPassStats.end(); it++) // scaling, part 2 |
960 | 0 | { |
961 | 0 | if (it->gopNum > gopNum) |
962 | 0 | { |
963 | 0 | vecIdx++; |
964 | 0 | fac = 1.0 / gopBits[vecIdx]; |
965 | 0 | gopTempVal[vecIdx] = (it->isIntra ? float (it->targetBits * fac) : 0.0f); |
966 | 0 | gopNum = it->gopNum; |
967 | 0 | } |
968 | 0 | it->frameInGopRatio = it->targetBits * fac; // i.e., rf/gf in VCIP'21 paper |
969 | |
|
970 | 0 | if (it->poc == 0 && it->isIntra) // put the first I-frame into separate GOP |
971 | 0 | { |
972 | 0 | vecIdx++; |
973 | 0 | fac = 1.0 / gopBits[vecIdx]; |
974 | 0 | gopTempVal[vecIdx] = 0.0f; // relax rate constraint a bit in first 2 GOPs |
975 | 0 | } |
976 | 0 | } |
977 | |
|
978 | 0 | if (!encRCSeq->isLookAhead && encRCSeq->maxGopRate < INT32_MAX) // pre-capper |
979 | 0 | { |
980 | 0 | double savedBits = 0.0, scale = 0.0, maxBits; |
981 | 0 | uint32_t savedGOPs = 0; |
982 | |
|
983 | 0 | for (vecIdx = 0; vecIdx < (int) gopBits.size(); vecIdx++) |
984 | 0 | { |
985 | 0 | if (gopTempVal[vecIdx] > 0.0f) |
986 | 0 | { |
987 | 0 | scale = (double) encRCSeq->maxGopRate * encRCSeq->intraPeriod / (encRCSeq->intraPeriod + gopTempVal[vecIdx] * encRCSeq->gopSize); |
988 | 0 | } |
989 | 0 | maxBits = scale * (1.0 + gopTempVal[vecIdx]); |
990 | |
|
991 | 0 | if ((double) gopBits[vecIdx] > maxBits) |
992 | 0 | { |
993 | 0 | gopTempVal[vecIdx] = float (maxBits / gopBits[vecIdx]); // saving ratio |
994 | 0 | savedBits += gopBits[vecIdx] - maxBits; |
995 | 0 | savedGOPs++; |
996 | 0 | } |
997 | 0 | else |
998 | 0 | { |
999 | 0 | gopTempVal[vecIdx] = 0.f; // signal to next loop that rate is below cap |
1000 | 0 | } |
1001 | 0 | } |
1002 | |
|
1003 | 0 | if (savedGOPs > 0) // distribute saved bits equally across not capped GOPs |
1004 | 0 | { |
1005 | 0 | savedBits /= gopBits.size() - savedGOPs; |
1006 | 0 | vecIdx = 0; |
1007 | 0 | scale = (double) encRCSeq->maxGopRate * encRCSeq->intraPeriod / (encRCSeq->intraPeriod + 1.0 /*frameInGopRatio*/ * encRCSeq->gopSize); |
1008 | 0 | maxBits = scale * (1.0 + 1.0 /*frameInGopRatio*/); |
1009 | 0 | fac = (gopTempVal[vecIdx] > 0.0f ? gopTempVal[vecIdx] : std::min (maxBits, gopBits[vecIdx] + savedBits) / gopBits[vecIdx]); |
1010 | 0 | gopNum = m_listRCFirstPassStats.front().gopNum; |
1011 | 0 | for (it = m_listRCFirstPassStats.begin(); it != m_listRCFirstPassStats.end(); it++) // cap, part 3 |
1012 | 0 | { |
1013 | 0 | if (it->gopNum > gopNum) |
1014 | 0 | { |
1015 | 0 | vecIdx++; |
1016 | 0 | if (it->isIntra) |
1017 | 0 | { |
1018 | 0 | scale = (double) encRCSeq->maxGopRate * encRCSeq->intraPeriod / (encRCSeq->intraPeriod + it->frameInGopRatio * encRCSeq->gopSize); |
1019 | 0 | } |
1020 | 0 | maxBits = scale * (it->isIntra ? 1.0 + it->frameInGopRatio : 1.0); |
1021 | 0 | fac = (gopTempVal[vecIdx] > 0.0f ? gopTempVal[vecIdx] : std::min (maxBits, gopBits[vecIdx] + savedBits) / gopBits[vecIdx]); |
1022 | 0 | gopNum = it->gopNum; |
1023 | 0 | } |
1024 | 0 | it->targetBits = (int) std::max (1.0, 0.5 + it->targetBits * fac); |
1025 | |
|
1026 | 0 | if (it->poc == 0 && it->isIntra) // put first I-frame into separate GOP |
1027 | 0 | { |
1028 | 0 | vecIdx++; |
1029 | | // maxBits = scale * 1.0; relax rate constraint a bit in first 2 GOPs |
1030 | 0 | fac = (gopTempVal[vecIdx] > 0.0f ? gopTempVal[vecIdx] : std::min (maxBits, gopBits[vecIdx] + savedBits) / gopBits[vecIdx]); |
1031 | 0 | } |
1032 | 0 | } |
1033 | 0 | } |
1034 | 0 | } |
1035 | 0 | } |
1036 | | |
1037 | | void RateCtrl::updateMotionErrStatsGop( const bool flush, const int poc ) |
1038 | 0 | { |
1039 | 0 | CHECK( poc <= m_updateNoisePoc, "given TL0 poc before last TL0 poc" ); |
1040 | |
|
1041 | 0 | const bool bIncomplete = ( poc - m_updateNoisePoc ) < m_pcEncCfg->m_GOPSize; |
1042 | | |
1043 | | // reset only if full gop pics available or previous gop ends with intra frame |
1044 | 0 | if( ! bIncomplete || m_resetNoise ) |
1045 | 0 | { |
1046 | 0 | m_maxPicMotionError = 0; |
1047 | 0 | std::fill_n( m_minNoiseLevels, QPA_MAX_NOISE_LEVELS, 255u ); |
1048 | 0 | } |
1049 | 0 | m_resetNoise = true; |
1050 | | |
1051 | | // currently disabled for last incomplete gop (TODO: check) |
1052 | 0 | if( bIncomplete && flush ) |
1053 | 0 | { |
1054 | 0 | m_maxPicMotionError = 0; |
1055 | 0 | std::fill_n( m_minNoiseLevels, QPA_MAX_NOISE_LEVELS, 255u ); |
1056 | 0 | return; |
1057 | 0 | } |
1058 | | |
1059 | | // continue with stats after last used poc |
1060 | 0 | const int startPoc = m_updateNoisePoc + 1; |
1061 | 0 | auto itr = find_if( m_listRCFirstPassStats.begin(), m_listRCFirstPassStats.end(), [ startPoc ]( const auto& stat ) { return stat.poc == startPoc; } ); |
1062 | 0 | if( itr == m_listRCFirstPassStats.end() ) |
1063 | 0 | { |
1064 | 0 | itr = m_listRCFirstPassStats.begin(); |
1065 | 0 | } |
1066 | |
|
1067 | 0 | for( ; itr != m_listRCFirstPassStats.end(); itr++ ) |
1068 | 0 | { |
1069 | 0 | const auto& stat = *itr; |
1070 | 0 | if( stat.poc > poc ) |
1071 | 0 | { |
1072 | 0 | m_gopMEErrorCBufIdx = ( m_gopMEErrorCBufIdx + 1u ) & uint8_t( QPA_MAX_NOISE_LEVELS - 1 ); |
1073 | 0 | m_gopMEErrorCBuf[ m_gopMEErrorCBufIdx ] = m_maxPicMotionError; |
1074 | 0 | m_resetNoise = stat.isIntra; // in case last update poc is intra, we cannot reuse the old noise levels for the next gop |
1075 | 0 | break; |
1076 | 0 | } |
1077 | 0 | m_maxPicMotionError = std::max( m_maxPicMotionError, stat.motionEstError ); |
1078 | |
|
1079 | 0 | for( int i = 0; i < QPA_MAX_NOISE_LEVELS; i++ ) |
1080 | 0 | { |
1081 | 0 | if( stat.minNoiseLevels[ i ] < m_minNoiseLevels[ i ] ) |
1082 | 0 | { |
1083 | 0 | m_minNoiseLevels[ i ] = stat.minNoiseLevels[ i ]; |
1084 | 0 | } |
1085 | 0 | } |
1086 | 0 | } |
1087 | | |
1088 | | // store highest poc used for current update |
1089 | 0 | m_updateNoisePoc = poc; |
1090 | 0 | } |
1091 | | |
1092 | | double RateCtrl::getLookAheadBoostFac( const int thresholdDivisor ) |
1093 | 0 | { |
1094 | 0 | const unsigned thresh = 64 / std::max (1, thresholdDivisor); |
1095 | 0 | unsigned num = 0, sum = 0; |
1096 | |
|
1097 | 0 | for (int i = 0; i < QPA_MAX_NOISE_LEVELS; i++) // go through non-zero values in circ. buffer |
1098 | 0 | { |
1099 | 0 | if (m_gopMEErrorCBuf[i] > 0) |
1100 | 0 | { |
1101 | 0 | num++; |
1102 | 0 | sum += m_gopMEErrorCBuf[i]; |
1103 | 0 | } |
1104 | 0 | } |
1105 | |
|
1106 | 0 | if (num > 0 && m_gopMEErrorCBuf[m_gopMEErrorCBufIdx] * num > sum + thresh * num) // boosting |
1107 | 0 | { |
1108 | 0 | return double (m_gopMEErrorCBuf[m_gopMEErrorCBufIdx] * num) / (sum + thresh * num); |
1109 | 0 | } |
1110 | 0 | return 1.0; |
1111 | 0 | } |
1112 | | |
1113 | | double RateCtrl::updateQPstartModelVal() |
1114 | 0 | { |
1115 | 0 | unsigned num = 0, sum = 0; |
1116 | |
|
1117 | 0 | for (int avgIndex = 0; avgIndex < QPA_MAX_NOISE_LEVELS; avgIndex++) // go through all ranges |
1118 | 0 | { |
1119 | 0 | if (m_minNoiseLevels[avgIndex] < 255) |
1120 | 0 | { |
1121 | 0 | num++; |
1122 | 0 | sum += m_minNoiseLevels[avgIndex]; |
1123 | 0 | } |
1124 | 0 | } |
1125 | |
|
1126 | 0 | if (num == 0 || sum == 0) return 24.0; // default if no data, else noise level equivalent QP |
1127 | | |
1128 | 0 | return 24.0 + 0.5 * (6.0 * log ((double) sum / (double) num) / log (2.0) - 1.0 - 24.0); |
1129 | 0 | } |
1130 | | |
1131 | | void RateCtrl::addRCPassStats( const int poc, |
1132 | | const int qp, |
1133 | | const double lambda, |
1134 | | const uint16_t visActY, |
1135 | | const uint32_t numBits, |
1136 | | const double psnrY, |
1137 | | const bool isIntra, |
1138 | | const uint32_t tempLayer, |
1139 | | const bool isStartOfIntra, |
1140 | | const bool isStartOfGop, |
1141 | | const int gopNum, |
1142 | | const SceneType scType, |
1143 | | int spVisAct, |
1144 | | const uint16_t motEstError, |
1145 | | const uint8_t minNoiseLevels[ QPA_MAX_NOISE_LEVELS ] ) |
1146 | 0 | { |
1147 | 0 | storeStatsData (TRCPassStats (poc, qp, lambda, visActY, numBits, psnrY, isIntra, tempLayer + int (!isIntra), isStartOfIntra, isStartOfGop, gopNum, scType, spVisAct, motEstError, minNoiseLevels)); |
1148 | 0 | } |
1149 | | |
1150 | | void RateCtrl::updateAfterPicEncRC( const Picture* pic ) |
1151 | 0 | { |
1152 | 0 | const int clipBits = std::max( pic->encRCPic->targetBits, pic->actualTotalBits ); |
1153 | |
|
1154 | 0 | pic->encRCPic->updateAfterPicture( pic->isMeanQPLimited ? clipBits : pic->actualTotalBits, pic->slices[ 0 ]->sliceQp ); |
1155 | 0 | addToPictureList( encRCSeq, m_listRCPictures, pic->encRCPic ); |
1156 | 0 | encRCSeq->updateAfterPic( pic->actualTotalBits, pic->encRCPic->tmpTargetBits ); |
1157 | |
|
1158 | 0 | if ( encRCSeq->isLookAhead ) |
1159 | 0 | { |
1160 | 0 | if ( pic->isMeanQPLimited ) encRCSeq->bitsUsedQPLimDiff += pic->actualTotalBits - clipBits; |
1161 | 0 | encRCSeq->bitsUsed += encRCSeq->bitsUsedQPLimDiff; // sum up actual, not ideal bit counts |
1162 | 0 | } |
1163 | 0 | } |
1164 | | |
1165 | | void RateCtrl::initRateControlPic( Picture& pic, Slice* slice, int& qp, double& finalLambda ) |
1166 | 0 | { |
1167 | 0 | const int frameLevel = ( slice->isIntra() ? 0 : slice->TLayer + 1 ); |
1168 | 0 | double lambda = encRCSeq->maxEstLambda; |
1169 | 0 | int sliceQP = MAX_QP; |
1170 | | |
1171 | | // not std::make_shared: GCC 16 without LTO speculates that the json output adapter's shared_ptr (operator<< in this file) |
1172 | | // holds an in-place EncRCPic and reports a false -Warray-bounds on its destructor, which fails -Werror builds |
1173 | 0 | pic.encRCPic = std::shared_ptr<EncRCPic>( new EncRCPic() ); |
1174 | 0 | pic.encRCPic->create( encRCSeq, frameLevel, slice->poc ); |
1175 | |
|
1176 | 0 | if ( frameLevel <= 7 ) |
1177 | 0 | { |
1178 | 0 | if ( m_pcEncCfg->m_RCNumPasses == 2 || m_pcEncCfg->m_LookAhead ) |
1179 | 0 | { |
1180 | 0 | std::list<TRCPassStats>::iterator it; |
1181 | |
|
1182 | 0 | for ( it = encRCSeq->firstPassData.begin(); it != encRCSeq->firstPassData.end(); it++ ) |
1183 | 0 | { |
1184 | 0 | if ( it->poc == slice->poc && it->numBits > 0 ) |
1185 | 0 | { |
1186 | 0 | const double sqrOfResRatio = std::min( 1.0, double( m_pcEncCfg->m_SourceWidth * m_pcEncCfg->m_SourceHeight ) / ( 3840.0 * 2160.0 ) ); |
1187 | 0 | const int firstPassSliceQP = it->qp; |
1188 | 0 | const int budgetRelaxScale = ( encRCSeq->maxGopRate + 0.5 < 2.0 * (double)encRCSeq->targetRate * encRCSeq->gopSize / encRCSeq->frameRate ? 2 : 3 ); // quarters |
1189 | 0 | const bool isRateCapperMax = ( encRCSeq->maxGopRate + 0.5 >= 3.0 * (double)encRCSeq->targetRate * encRCSeq->gopSize / encRCSeq->frameRate ); |
1190 | 0 | const bool isEndOfSequence = ( it->poc >= flushPOC && flushPOC >= 0 ); |
1191 | 0 | const double dLimit = ( isRateCapperMax ? 3.0 : 0.5 * budgetRelaxScale + 0.5 ); |
1192 | 0 | double d = (double)it->targetBits, tmpVal; |
1193 | |
|
1194 | 0 | pic.encRCPic->visActSteady = it->visActY; |
1195 | |
|
1196 | 0 | if ( it->refreshParameters ) // reset counters for budget usage in subsequent frames |
1197 | 0 | { |
1198 | 0 | encRCSeq->qpCorrection[ frameLevel ] = ( it->poc == 0 && it->isIntra && d < it->numBits ? std::max( -1.0 * it->visActY / double( 1 << ( encRCSeq->bitDepth - 3 ) ), 1.0 - it->numBits / d ) : 0.0 ); |
1199 | 0 | if ( !m_pcEncCfg->m_LookAhead ) |
1200 | 0 | { |
1201 | 0 | encRCSeq->actualBitCnt[ frameLevel ] = encRCSeq->targetBitCnt[ frameLevel ] = 0; |
1202 | 0 | } |
1203 | 0 | pic.encRCPic->refreshParams = true; |
1204 | 0 | } |
1205 | 0 | if ( it->isIntra ) // update temp stationarity for budget usage in subsequent frames |
1206 | 0 | { |
1207 | 0 | encRCSeq->lastIntraSM = it->frameInGopRatio; |
1208 | 0 | } |
1209 | 0 | if ( it->isStartOfGop ) |
1210 | 0 | { |
1211 | 0 | bool allowMoreRatePeaks = false; |
1212 | 0 | encRCSeq->rateBoostFac = 1.0; |
1213 | |
|
1214 | 0 | if ( m_pcEncCfg->m_LookAhead && !encRCSeq->isRateSavingMode ) // rate boost factor |
1215 | 0 | { |
1216 | 0 | encRCSeq->rateBoostFac = getLookAheadBoostFac( isRateCapperMax ? 2 : budgetRelaxScale - 1 ); |
1217 | 0 | allowMoreRatePeaks = ( encRCSeq->rateBoostFac > 1.0 && isRateCapperMax ); |
1218 | 0 | if ( allowMoreRatePeaks && !isEndOfSequence ) |
1219 | 0 | { |
1220 | 0 | encRCSeq->lastIntraSM = 1.0; |
1221 | 0 | } |
1222 | 0 | if ( encRCSeq->rateBoostFac > 1.0 && !isEndOfSequence ) |
1223 | 0 | { |
1224 | 0 | encRCSeq->estimatedBitUsage = std::max( encRCSeq->estimatedBitUsage, encRCSeq->bitsUsed ); // TL<2: relax constraint |
1225 | 0 | } |
1226 | 0 | } |
1227 | 0 | encRCSeq->isIntraGOP = ( ( it->isStartOfIntra || allowMoreRatePeaks ) && !isEndOfSequence && !encRCSeq->isRateSavingMode ); |
1228 | 0 | } |
1229 | 0 | else if ( frameLevel == 2 && it->refreshParameters && encRCSeq->scRelax && !isEndOfSequence && !encRCSeq->isRateSavingMode ) |
1230 | 0 | { |
1231 | 0 | encRCSeq->estimatedBitUsage = std::max( encRCSeq->estimatedBitUsage, encRCSeq->bitsUsed ); // cut: relax rate constraint |
1232 | 0 | } |
1233 | 0 | encRCSeq->scRelax = ( frameLevel < 2 && it->refreshParameters && encRCSeq->estimatedBitUsage > encRCSeq->bitsUsed ); |
1234 | |
|
1235 | 0 | CHECK( slice->TLayer >= 7, "analyzed RC frame must have TLayer < 7" ); |
1236 | |
|
1237 | 0 | tmpVal = ( encRCSeq->isIntraGOP ? 0.5 + 0.5 * encRCSeq->lastIntraSM : 0.5 ); // IGOP |
1238 | 0 | if ( !isEndOfSequence && !m_pcEncCfg->m_LookAhead && frameLevel == 2 && encRCSeq->maxGopRate + 0.5 < 3.0 * (double)encRCSeq->targetRate * encRCSeq->gopSize / encRCSeq->frameRate ) |
1239 | 0 | { |
1240 | 0 | encRCSeq->estimatedBitUsage = std::max( encRCSeq->estimatedBitUsage, ( budgetRelaxScale * encRCSeq->estimatedBitUsage + ( 4 - budgetRelaxScale ) * encRCSeq->bitsUsed + 2 ) >> 2 ); |
1241 | 0 | } |
1242 | |
|
1243 | 0 | if ( encRCSeq->rateBoostFac > 1.0 ) |
1244 | 0 | { |
1245 | 0 | it->targetBits = int( it->targetBits * encRCSeq->rateBoostFac + 0.5 ); // boosting |
1246 | 0 | } |
1247 | 0 | pic.encRCPic->tmpTargetBits = it->targetBits; |
1248 | | |
1249 | | // calculate the difference of under or overspent bits and adjust the current target bits based on the GOP and frame ratio |
1250 | 0 | d = pic.encRCPic->tmpTargetBits + std::min( (int64_t) encRCSeq->maxGopRate, encRCSeq->estimatedBitUsage - encRCSeq->bitsUsed ) * tmpVal * it->frameInGopRatio; |
1251 | | |
1252 | | // try to hit target rate more aggressively in last coded frames, lambda/QP clipping below will ensure smooth value change |
1253 | 0 | if ( isEndOfSequence ) |
1254 | 0 | { |
1255 | 0 | d += std::min( (int64_t) encRCSeq->maxGopRate, encRCSeq->estimatedBitUsage - encRCSeq->bitsUsed ) * ( 1.0 - tmpVal ) * it->frameInGopRatio; |
1256 | 0 | } |
1257 | 0 | else if ( d > dLimit * pic.encRCPic->tmpTargetBits ) |
1258 | 0 | { |
1259 | 0 | d = pic.encRCPic->tmpTargetBits * dLimit; // prevent large spendings after easy scenes |
1260 | 0 | } |
1261 | 0 | else if ( d * dLimit < pic.encRCPic->tmpTargetBits ) |
1262 | 0 | { |
1263 | 0 | d = pic.encRCPic->tmpTargetBits / dLimit; // prevent small spendings after hard scenes |
1264 | 0 | } |
1265 | |
|
1266 | 0 | if ( !isEndOfSequence && it->isStartOfGop && it->poc > 0 ) // target bitrate capping |
1267 | 0 | { |
1268 | 0 | const double scale = encRCSeq->intraPeriod / ( encRCSeq->intraPeriod + encRCSeq->lastIntraSM * encRCSeq->gopSize ); |
1269 | 0 | const double fBits = scale * ( encRCSeq->isIntraGOP ? 1.0 + encRCSeq->lastIntraSM : 1.0 ) * it->frameInGopRatio; // IGOP |
1270 | |
|
1271 | 0 | if ( d > fBits * encRCSeq->maxGopRate ) d = fBits * encRCSeq->maxGopRate; |
1272 | 0 | } |
1273 | 0 | d = std::max( 1.0, d ); |
1274 | 0 | pic.encRCPic->targetBits = int( d + 0.5 ); |
1275 | |
|
1276 | 0 | tmpVal = updateQPstartModelVal() + log (sqrOfResRatio) / log (2.0); // GOP's QPstart |
1277 | 0 | d /= (double)it->numBits; |
1278 | 0 | d = firstPassSliceQP - ( 105.0 / 128.0 ) * sqrt( (double)std::max( 1, firstPassSliceQP ) ) * log( d ) / log( 2.0 ); |
1279 | 0 | sliceQP = int( 0.5 + d + ( it->isIntra ? 0.375 : 0.5 ) * std::max( 0.0, tmpVal - d ) + encRCSeq->qpCorrection[ frameLevel ] ); |
1280 | |
|
1281 | 0 | const int sqp_bckp = sliceQP; |
1282 | 0 | pic.encRCPic->clipTargetQP( getPicList(), ( m_pcEncCfg->m_LookAhead ? getBaseQP() : m_pcEncCfg->m_QP ) + ( it->isIntra ? m_pcEncCfg->m_intraQPOffset : 0 ), 5 - budgetRelaxScale, |
1283 | 0 | ( it->poc < encRCSeq->gopSize ? 0 : ( m_pcEncCfg->m_maxTLayer + 1 ) >> 1 ), sqrOfResRatio, sliceQP, &encRCSeq->lastAverageQP ); |
1284 | | |
1285 | 0 | if( it->isIntra && sliceQP >= sqp_bckp ) |
1286 | 0 | { |
1287 | 0 | sliceQP -= (it->visActY < 64 ? 2 : std::max( 0, (encRCSeq->bitDepth < 10 ? 7 : 8) - floorLog2(it->visActY))); |
1288 | 0 | } |
1289 | | |
1290 | 0 | lambda = it->lambda * pow( 2.0, double( sliceQP - firstPassSliceQP ) / 3.0 ); |
1291 | 0 | lambda = Clip3( encRCSeq->minEstLambda, encRCSeq->maxEstLambda, lambda ); |
1292 | |
|
1293 | 0 | if ( m_pcEncCfg->m_LookAhead ) // update frame bit ratios for bit budget calculation |
1294 | 0 | { |
1295 | 0 | if ( it->isStartOfGop ) |
1296 | 0 | { |
1297 | 0 | if ( it->poc == 0 && it->isIntra ) // handle first I-frame being in separate GOP |
1298 | 0 | { |
1299 | 0 | uint32_t gopBits = it->numBits; |
1300 | 0 | std::list<TRCPassStats>::iterator itNext = it; |
1301 | |
|
1302 | 0 | for ( itNext++; itNext != encRCSeq->firstPassData.end() && !itNext->isStartOfGop; itNext++ ) |
1303 | 0 | { |
1304 | 0 | gopBits += itNext->numBits; |
1305 | 0 | } |
1306 | 0 | encRCSeq->lastIntraSM = (double)it->numBits / gopBits; |
1307 | 0 | } |
1308 | 0 | else if ( it->isIntra && !it->isStartOfIntra && !isEndOfSequence && !encRCSeq->isRateSavingMode && encRCSeq->estimatedBitUsage - encRCSeq->bitsUsed < pic.encRCPic->targetBits ) |
1309 | 0 | { |
1310 | 0 | encRCSeq->bitsUsedQPLimDiff += ( encRCSeq->estimatedBitUsage - encRCSeq->bitsUsed - pic.encRCPic->targetBits ) >> 1; |
1311 | 0 | } |
1312 | 0 | } |
1313 | 0 | } |
1314 | 0 | if ( it->isIntra ) // update history for parameter clipping in subsequent key frames |
1315 | 0 | { |
1316 | 0 | encRCSeq->lastIntraQP = sliceQP; |
1317 | 0 | } |
1318 | |
|
1319 | 0 | break; |
1320 | 0 | } |
1321 | 0 | } |
1322 | 0 | } |
1323 | 0 | } |
1324 | | |
1325 | 0 | qp = sliceQP; |
1326 | 0 | finalLambda = lambda; |
1327 | 0 | } |
1328 | | |
1329 | | } |