Commit | Line | Data |
---|---|---|
72b9787e JB |
1 | /***************************************************************************** |
2 | * Copyright (C) 2013 x265 project | |
3 | * | |
4 | * Authors: Sumalatha Polureddy <sumalatha@multicorewareinc.com> | |
5 | * Aarthi Priya Thirumalai <aarthi@multicorewareinc.com> | |
6 | * Xun Xu, PPLive Corporation <xunxu@pptv.com> | |
7 | * | |
8 | * This program is free software; you can redistribute it and/or modify | |
9 | * it under the terms of the GNU General Public License as published by | |
10 | * the Free Software Foundation; either version 2 of the License, or | |
11 | * (at your option) any later version. | |
12 | * | |
13 | * This program is distributed in the hope that it will be useful, | |
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | |
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
16 | * GNU General Public License for more details. | |
17 | * | |
18 | * You should have received a copy of the GNU General Public License | |
19 | * along with this program; if not, write to the Free Software | |
20 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA. | |
21 | * | |
22 | * This program is also available under a commercial proprietary license. | |
23 | * For more information, contact us at license @ x265.com. | |
24 | *****************************************************************************/ | |
25 | ||
26 | #include "common.h" | |
27 | #include "param.h" | |
28 | #include "frame.h" | |
29 | #include "framedata.h" | |
30 | #include "picyuv.h" | |
31 | ||
32 | #include "encoder.h" | |
33 | #include "slicetype.h" | |
34 | #include "ratecontrol.h" | |
35 | #include "sei.h" | |
36 | ||
37 | #define BR_SHIFT 6 | |
38 | #define CPB_SHIFT 4 | |
39 | ||
40 | using namespace x265; | |
41 | ||
42 | /* Amortize the partial cost of I frames over the next N frames */ | |
43 | const double RateControl::s_amortizeFraction = 0.85; | |
44 | const int RateControl::s_amortizeFrames = 75; | |
45 | const int RateControl::s_slidingWindowFrames = 20; | |
46 | const char *RateControl::s_defaultStatFileName = "x265_2pass.log"; | |
47 | ||
48 | namespace { | |
49 | #define CMP_OPT_FIRST_PASS(opt, param_val)\ | |
50 | {\ | |
51 | bErr = 0;\ | |
52 | p = strstr(opts, opt "=");\ | |
53 | char* q = strstr(opts, "no-"opt);\ | |
54 | if (p && sscanf(p, opt "=%d" , &i) && param_val != i)\ | |
55 | bErr = 1;\ | |
56 | else if (!param_val && !q && !p)\ | |
57 | bErr = 1;\ | |
58 | else if (param_val && (q || !strstr(opts, opt)))\ | |
59 | bErr = 1;\ | |
60 | if (bErr)\ | |
61 | {\ | |
62 | x265_log(m_param, X265_LOG_ERROR, "different " opt " setting than first pass (%d vs %d)\n", param_val, i);\ | |
63 | return false;\ | |
64 | }\ | |
65 | } | |
66 | ||
67 | inline int calcScale(uint32_t x) | |
68 | { | |
69 | static uint8_t lut[16] = {4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0}; | |
70 | int y, z = (((x & 0xffff) - 1) >> 27) & 16; | |
71 | x >>= z; | |
72 | z += y = (((x & 0xff) - 1) >> 28) & 8; | |
73 | x >>= y; | |
74 | z += y = (((x & 0xf) - 1) >> 29) & 4; | |
75 | x >>= y; | |
76 | return z + lut[x&0xf]; | |
77 | } | |
78 | ||
79 | inline int calcLength(uint32_t x) | |
80 | { | |
81 | static uint8_t lut[16] = {4, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0}; | |
82 | int y, z = (((x >> 16) - 1) >> 27) & 16; | |
83 | x >>= z ^ 16; | |
84 | z += y = ((x - 0x100) >> 28) & 8; | |
85 | x >>= y ^ 8; | |
86 | z += y = ((x - 0x10) >> 29) & 4; | |
87 | x >>= y ^ 4; | |
88 | return z + lut[x]; | |
89 | } | |
90 | ||
91 | inline void reduceFraction(int* n, int* d) | |
92 | { | |
93 | int a = *n; | |
94 | int b = *d; | |
95 | int c; | |
96 | if (!a || !b) | |
97 | return; | |
98 | c = a % b; | |
99 | while (c) | |
100 | { | |
101 | a = b; | |
102 | b = c; | |
103 | c = a % b; | |
104 | } | |
105 | *n /= b; | |
106 | *d /= b; | |
107 | } | |
108 | ||
109 | inline char *strcatFilename(const char *input, const char *suffix) | |
110 | { | |
111 | char *output = X265_MALLOC(char, strlen(input) + strlen(suffix) + 1); | |
112 | if (!output) | |
113 | { | |
114 | x265_log(NULL, X265_LOG_ERROR, "unable to allocate memory for filename\n"); | |
115 | return NULL; | |
116 | } | |
117 | strcpy(output, input); | |
118 | strcat(output, suffix); | |
119 | return output; | |
120 | } | |
121 | ||
122 | inline double qScale2bits(RateControlEntry *rce, double qScale) | |
123 | { | |
124 | if (qScale < 0.1) | |
125 | qScale = 0.1; | |
126 | return (rce->coeffBits + .1) * pow(rce->qScale / qScale, 1.1) | |
127 | + rce->mvBits * pow(X265_MAX(rce->qScale, 1) / X265_MAX(qScale, 1), 0.5) | |
128 | + rce->miscBits; | |
129 | } | |
130 | ||
131 | inline void copyRceData(RateControlEntry* rce, RateControlEntry* rce2Pass) | |
132 | { | |
133 | rce->coeffBits = rce2Pass->coeffBits; | |
134 | rce->mvBits = rce2Pass->mvBits; | |
135 | rce->miscBits = rce2Pass->miscBits; | |
136 | rce->iCuCount = rce2Pass->iCuCount; | |
137 | rce->pCuCount = rce2Pass->pCuCount; | |
138 | rce->skipCuCount = rce2Pass->skipCuCount; | |
139 | rce->keptAsRef = rce2Pass->keptAsRef; | |
140 | rce->qScale = rce2Pass->qScale; | |
141 | rce->newQScale = rce2Pass->newQScale; | |
142 | rce->expectedBits = rce2Pass->expectedBits; | |
143 | rce->expectedVbv = rce2Pass->expectedVbv; | |
144 | rce->blurredComplexity = rce2Pass->blurredComplexity; | |
145 | rce->sliceType = rce2Pass->sliceType; | |
146 | } | |
147 | ||
148 | } // end anonymous namespace | |
149 | /* Compute variance to derive AC energy of each block */ | |
150 | static inline uint32_t acEnergyVar(Frame *curFrame, uint64_t sum_ssd, int shift, int i) | |
151 | { | |
152 | uint32_t sum = (uint32_t)sum_ssd; | |
153 | uint32_t ssd = (uint32_t)(sum_ssd >> 32); | |
154 | ||
155 | curFrame->m_lowres.wp_sum[i] += sum; | |
156 | curFrame->m_lowres.wp_ssd[i] += ssd; | |
157 | return ssd - ((uint64_t)sum * sum >> shift); | |
158 | } | |
159 | ||
160 | /* Find the energy of each block in Y/Cb/Cr plane */ | |
161 | static inline uint32_t acEnergyPlane(Frame *curFrame, pixel* src, intptr_t srcStride, int bChroma, int colorFormat) | |
162 | { | |
163 | if ((colorFormat != X265_CSP_I444) && bChroma) | |
164 | { | |
165 | ALIGN_VAR_8(pixel, pix[8 * 8]); | |
166 | primitives.luma_copy_pp[LUMA_8x8](pix, 8, src, srcStride); | |
167 | return acEnergyVar(curFrame, primitives.var[BLOCK_8x8](pix, 8), 6, bChroma); | |
168 | } | |
169 | else | |
170 | return acEnergyVar(curFrame, primitives.var[BLOCK_16x16](src, srcStride), 8, bChroma); | |
171 | } | |
172 | ||
173 | /* Find the total AC energy of each block in all planes */ | |
174 | uint32_t RateControl::acEnergyCu(Frame* curFrame, uint32_t block_x, uint32_t block_y) | |
175 | { | |
176 | intptr_t stride = curFrame->m_origPicYuv->m_stride; | |
177 | intptr_t cStride = curFrame->m_origPicYuv->m_strideC; | |
178 | intptr_t blockOffsetLuma = block_x + (block_y * stride); | |
179 | int colorFormat = m_param->internalCsp; | |
180 | int hShift = CHROMA_H_SHIFT(colorFormat); | |
181 | int vShift = CHROMA_V_SHIFT(colorFormat); | |
182 | intptr_t blockOffsetChroma = (block_x >> hShift) + ((block_y >> vShift) * cStride); | |
183 | ||
184 | uint32_t var; | |
185 | ||
186 | var = acEnergyPlane(curFrame, curFrame->m_origPicYuv->m_picOrg[0] + blockOffsetLuma, stride, 0, colorFormat); | |
187 | var += acEnergyPlane(curFrame, curFrame->m_origPicYuv->m_picOrg[1] + blockOffsetChroma, cStride, 1, colorFormat); | |
188 | var += acEnergyPlane(curFrame, curFrame->m_origPicYuv->m_picOrg[2] + blockOffsetChroma, cStride, 2, colorFormat); | |
189 | x265_emms(); | |
190 | return var; | |
191 | } | |
192 | ||
193 | void RateControl::calcAdaptiveQuantFrame(Frame *curFrame) | |
194 | { | |
195 | /* Actual adaptive quantization */ | |
196 | int maxCol = curFrame->m_origPicYuv->m_picWidth; | |
197 | int maxRow = curFrame->m_origPicYuv->m_picHeight; | |
198 | ||
199 | for (int y = 0; y < 3; y++) | |
200 | { | |
201 | curFrame->m_lowres.wp_ssd[y] = 0; | |
202 | curFrame->m_lowres.wp_sum[y] = 0; | |
203 | } | |
204 | ||
205 | /* Calculate Qp offset for each 16x16 block in the frame */ | |
206 | int block_xy = 0; | |
207 | int block_x = 0, block_y = 0; | |
208 | double strength = 0.f; | |
209 | if (m_param->rc.aqMode == X265_AQ_NONE || m_param->rc.aqStrength == 0) | |
210 | { | |
211 | /* Need to init it anyways for CU tree */ | |
212 | int cuWidth = ((maxCol / 2) + X265_LOWRES_CU_SIZE - 1) >> X265_LOWRES_CU_BITS; | |
213 | int cuHeight = ((maxRow / 2) + X265_LOWRES_CU_SIZE - 1) >> X265_LOWRES_CU_BITS; | |
214 | int cuCount = cuWidth * cuHeight; | |
215 | ||
216 | if (m_param->rc.aqMode && m_param->rc.aqStrength == 0) | |
217 | { | |
218 | memset(curFrame->m_lowres.qpCuTreeOffset, 0, cuCount * sizeof(double)); | |
219 | memset(curFrame->m_lowres.qpAqOffset, 0, cuCount * sizeof(double)); | |
220 | for (int cuxy = 0; cuxy < cuCount; cuxy++) | |
221 | curFrame->m_lowres.invQscaleFactor[cuxy] = 256; | |
222 | } | |
223 | ||
224 | /* Need variance data for weighted prediction */ | |
225 | if (m_param->bEnableWeightedPred || m_param->bEnableWeightedBiPred) | |
226 | { | |
227 | for (block_y = 0; block_y < maxRow; block_y += 16) | |
228 | for (block_x = 0; block_x < maxCol; block_x += 16) | |
229 | acEnergyCu(curFrame, block_x, block_y); | |
230 | } | |
231 | } | |
232 | else | |
233 | { | |
234 | block_xy = 0; | |
235 | double avg_adj_pow2 = 0, avg_adj = 0, qp_adj = 0; | |
236 | if (m_param->rc.aqMode == X265_AQ_AUTO_VARIANCE) | |
237 | { | |
238 | double bit_depth_correction = pow(1 << (X265_DEPTH - 8), 0.5); | |
239 | for (block_y = 0; block_y < maxRow; block_y += 16) | |
240 | { | |
241 | for (block_x = 0; block_x < maxCol; block_x += 16) | |
242 | { | |
243 | uint32_t energy = acEnergyCu(curFrame, block_x, block_y); | |
244 | qp_adj = pow(energy + 1, 0.1); | |
245 | curFrame->m_lowres.qpCuTreeOffset[block_xy] = qp_adj; | |
246 | avg_adj += qp_adj; | |
247 | avg_adj_pow2 += qp_adj * qp_adj; | |
248 | block_xy++; | |
249 | } | |
250 | } | |
251 | ||
252 | avg_adj /= m_ncu; | |
253 | avg_adj_pow2 /= m_ncu; | |
254 | strength = m_param->rc.aqStrength * avg_adj / bit_depth_correction; | |
255 | avg_adj = avg_adj - 0.5f * (avg_adj_pow2 - (11.f * bit_depth_correction)) / avg_adj; | |
256 | } | |
257 | else | |
258 | strength = m_param->rc.aqStrength * 1.0397f; | |
259 | ||
260 | block_xy = 0; | |
261 | for (block_y = 0; block_y < maxRow; block_y += 16) | |
262 | { | |
263 | for (block_x = 0; block_x < maxCol; block_x += 16) | |
264 | { | |
265 | if (m_param->rc.aqMode == X265_AQ_AUTO_VARIANCE) | |
266 | { | |
267 | qp_adj = curFrame->m_lowres.qpCuTreeOffset[block_xy]; | |
268 | qp_adj = strength * (qp_adj - avg_adj); | |
269 | } | |
270 | else | |
271 | { | |
272 | uint32_t energy = acEnergyCu(curFrame, block_x, block_y); | |
273 | qp_adj = strength * (X265_LOG2(X265_MAX(energy, 1)) - (14.427f + 2 * (X265_DEPTH - 8))); | |
274 | } | |
275 | curFrame->m_lowres.qpAqOffset[block_xy] = qp_adj; | |
276 | curFrame->m_lowres.qpCuTreeOffset[block_xy] = qp_adj; | |
277 | curFrame->m_lowres.invQscaleFactor[block_xy] = x265_exp2fix8(qp_adj); | |
278 | block_xy++; | |
279 | } | |
280 | } | |
281 | } | |
282 | ||
283 | if (m_param->bEnableWeightedPred || m_param->bEnableWeightedBiPred) | |
284 | { | |
285 | int hShift = CHROMA_H_SHIFT(m_param->internalCsp); | |
286 | int vShift = CHROMA_V_SHIFT(m_param->internalCsp); | |
287 | maxCol = ((maxCol + 8) >> 4) << 4; | |
288 | maxRow = ((maxRow + 8) >> 4) << 4; | |
289 | int width[3] = { maxCol, maxCol >> hShift, maxCol >> hShift }; | |
290 | int height[3] = { maxRow, maxRow >> vShift, maxRow >> vShift }; | |
291 | ||
292 | for (int i = 0; i < 3; i++) | |
293 | { | |
294 | uint64_t sum, ssd; | |
295 | sum = curFrame->m_lowres.wp_sum[i]; | |
296 | ssd = curFrame->m_lowres.wp_ssd[i]; | |
297 | curFrame->m_lowres.wp_ssd[i] = ssd - (sum * sum + (width[i] * height[i]) / 2) / (width[i] * height[i]); | |
298 | } | |
299 | } | |
300 | } | |
301 | ||
302 | RateControl::RateControl(x265_param *p) | |
303 | { | |
304 | m_param = p; | |
305 | int lowresCuWidth = ((m_param->sourceWidth / 2) + X265_LOWRES_CU_SIZE - 1) >> X265_LOWRES_CU_BITS; | |
306 | int lowresCuHeight = ((m_param->sourceHeight / 2) + X265_LOWRES_CU_SIZE - 1) >> X265_LOWRES_CU_BITS; | |
307 | m_ncu = lowresCuWidth * lowresCuHeight; | |
308 | ||
309 | if (m_param->rc.cuTree) | |
310 | m_qCompress = 1; | |
311 | else | |
312 | m_qCompress = m_param->rc.qCompress; | |
313 | ||
314 | // validate for param->rc, maybe it is need to add a function like x265_parameters_valiate() | |
315 | m_residualFrames = 0; | |
316 | m_partialResidualFrames = 0; | |
317 | m_residualCost = 0; | |
318 | m_partialResidualCost = 0; | |
319 | m_rateFactorMaxIncrement = 0; | |
320 | m_rateFactorMaxDecrement = 0; | |
321 | m_fps = m_param->fpsNum / m_param->fpsDenom; | |
322 | m_startEndOrder.set(0); | |
323 | m_bTerminated = false; | |
324 | m_finalFrameCount = 0; | |
325 | m_numEntries = 0; | |
326 | if (m_param->rc.rateControlMode == X265_RC_CRF) | |
327 | { | |
328 | m_param->rc.qp = (int)m_param->rc.rfConstant; | |
329 | m_param->rc.bitrate = 0; | |
330 | ||
331 | double baseCplx = m_ncu * (m_param->bframes ? 120 : 80); | |
332 | double mbtree_offset = m_param->rc.cuTree ? (1.0 - m_param->rc.qCompress) * 13.5 : 0; | |
333 | m_rateFactorConstant = pow(baseCplx, 1 - m_qCompress) / | |
334 | x265_qp2qScale(m_param->rc.rfConstant + mbtree_offset); | |
335 | if (m_param->rc.rfConstantMax) | |
336 | { | |
337 | m_rateFactorMaxIncrement = m_param->rc.rfConstantMax - m_param->rc.rfConstant; | |
338 | if (m_rateFactorMaxIncrement <= 0) | |
339 | { | |
340 | x265_log(m_param, X265_LOG_WARNING, "CRF max must be greater than CRF\n"); | |
341 | m_rateFactorMaxIncrement = 0; | |
342 | } | |
343 | } | |
344 | if (m_param->rc.rfConstantMin) | |
345 | m_rateFactorMaxDecrement = m_param->rc.rfConstant - m_param->rc.rfConstantMin; | |
346 | } | |
347 | m_isAbr = m_param->rc.rateControlMode != X265_RC_CQP && !m_param->rc.bStatRead; | |
348 | m_2pass = m_param->rc.rateControlMode == X265_RC_ABR && m_param->rc.bStatRead; | |
349 | m_bitrate = m_param->rc.bitrate * 1000; | |
350 | m_frameDuration = (double)m_param->fpsDenom / m_param->fpsNum; | |
351 | m_qp = m_param->rc.qp; | |
352 | m_lastRceq = 1; /* handles the cmplxrsum when the previous frame cost is zero */ | |
353 | m_shortTermCplxSum = 0; | |
354 | m_shortTermCplxCount = 0; | |
355 | m_lastNonBPictType = I_SLICE; | |
356 | m_isAbrReset = false; | |
357 | m_lastAbrResetPoc = -1; | |
358 | m_statFileOut = NULL; | |
359 | m_cutreeStatFileOut = m_cutreeStatFileIn = NULL; | |
360 | m_rce2Pass = NULL; | |
361 | ||
362 | // vbv initialization | |
363 | m_param->rc.vbvBufferSize = Clip3(0, 2000000, m_param->rc.vbvBufferSize); | |
364 | m_param->rc.vbvMaxBitrate = Clip3(0, 2000000, m_param->rc.vbvMaxBitrate); | |
365 | m_param->rc.vbvBufferInit = Clip3(0.0, 2000000.0, m_param->rc.vbvBufferInit); | |
366 | m_singleFrameVbv = 0; | |
367 | if (m_param->rc.vbvBufferSize) | |
368 | { | |
369 | if (m_param->rc.rateControlMode == X265_RC_CQP) | |
370 | { | |
371 | x265_log(m_param, X265_LOG_WARNING, "VBV is incompatible with constant QP, ignored.\n"); | |
372 | m_param->rc.vbvBufferSize = 0; | |
373 | m_param->rc.vbvMaxBitrate = 0; | |
374 | } | |
375 | else if (m_param->rc.vbvMaxBitrate == 0) | |
376 | { | |
377 | if (m_param->rc.rateControlMode == X265_RC_ABR) | |
378 | { | |
379 | x265_log(m_param, X265_LOG_WARNING, "VBV maxrate unspecified, assuming CBR\n"); | |
380 | m_param->rc.vbvMaxBitrate = m_param->rc.bitrate; | |
381 | } | |
382 | else | |
383 | { | |
384 | x265_log(m_param, X265_LOG_WARNING, "VBV bufsize set but maxrate unspecified, ignored\n"); | |
385 | m_param->rc.vbvBufferSize = 0; | |
386 | } | |
387 | } | |
388 | else if (m_param->rc.vbvMaxBitrate < m_param->rc.bitrate && | |
389 | m_param->rc.rateControlMode == X265_RC_ABR) | |
390 | { | |
391 | x265_log(m_param, X265_LOG_WARNING, "max bitrate less than average bitrate, assuming CBR\n"); | |
392 | m_param->rc.bitrate = m_param->rc.vbvMaxBitrate; | |
393 | } | |
394 | } | |
395 | else if (m_param->rc.vbvMaxBitrate) | |
396 | { | |
397 | x265_log(m_param, X265_LOG_WARNING, "VBV maxrate specified, but no bufsize, ignored\n"); | |
398 | m_param->rc.vbvMaxBitrate = 0; | |
399 | } | |
400 | m_isVbv = m_param->rc.vbvMaxBitrate > 0 && m_param->rc.vbvBufferSize > 0; | |
401 | if (m_param->bEmitHRDSEI && !m_isVbv) | |
402 | { | |
403 | x265_log(m_param, X265_LOG_WARNING, "NAL HRD parameters require VBV parameters, ignored\n"); | |
404 | m_param->bEmitHRDSEI = 0; | |
405 | } | |
406 | ||
407 | m_isCbr = m_param->rc.rateControlMode == X265_RC_ABR && m_isVbv && !m_2pass && m_param->rc.vbvMaxBitrate <= m_param->rc.bitrate; | |
408 | m_leadingBframes = m_param->bframes; | |
409 | m_bframeBits = 0; | |
410 | m_leadingNoBSatd = 0; | |
411 | m_ipOffset = 6.0 * X265_LOG2(m_param->rc.ipFactor); | |
412 | m_pbOffset = 6.0 * X265_LOG2(m_param->rc.pbFactor); | |
413 | ||
414 | /* Adjust the first frame in order to stabilize the quality level compared to the rest */ | |
415 | #define ABR_INIT_QP_MIN (24) | |
416 | #define ABR_INIT_QP_MAX (40) | |
417 | #define CRF_INIT_QP (int)m_param->rc.rfConstant | |
418 | for (int i = 0; i < 3; i++) | |
419 | m_lastQScaleFor[i] = x265_qp2qScale(m_param->rc.rateControlMode == X265_RC_CRF ? CRF_INIT_QP : ABR_INIT_QP_MIN); | |
420 | ||
421 | if (m_param->rc.rateControlMode == X265_RC_CQP) | |
422 | { | |
423 | if (m_qp && !m_param->bLossless) | |
424 | { | |
425 | m_qpConstant[P_SLICE] = m_qp; | |
426 | m_qpConstant[I_SLICE] = Clip3(0, QP_MAX_MAX, (int)(m_qp - m_ipOffset + 0.5)); | |
427 | m_qpConstant[B_SLICE] = Clip3(0, QP_MAX_MAX, (int)(m_qp + m_pbOffset + 0.5)); | |
428 | } | |
429 | else | |
430 | { | |
431 | m_qpConstant[P_SLICE] = m_qpConstant[I_SLICE] = m_qpConstant[B_SLICE] = m_qp; | |
432 | } | |
433 | } | |
434 | ||
435 | /* qstep - value set as encoder specific */ | |
436 | m_lstep = pow(2, m_param->rc.qpStep / 6.0); | |
437 | ||
438 | for (int i = 0; i < 2; i++) | |
439 | m_cuTreeStats.qpBuffer[i] = NULL; | |
440 | } | |
441 | ||
442 | bool RateControl::init(const SPS *sps) | |
443 | { | |
444 | if (m_isVbv) | |
445 | { | |
446 | /* We don't support changing the ABR bitrate right now, | |
447 | * so if the stream starts as CBR, keep it CBR. */ | |
448 | if (m_param->rc.vbvBufferSize < (int)(m_param->rc.vbvMaxBitrate / m_fps)) | |
449 | { | |
450 | m_param->rc.vbvBufferSize = (int)(m_param->rc.vbvMaxBitrate / m_fps); | |
451 | x265_log(m_param, X265_LOG_WARNING, "VBV buffer size cannot be smaller than one frame, using %d kbit\n", | |
452 | m_param->rc.vbvBufferSize); | |
453 | } | |
454 | int vbvBufferSize = m_param->rc.vbvBufferSize * 1000; | |
455 | int vbvMaxBitrate = m_param->rc.vbvMaxBitrate * 1000; | |
456 | ||
457 | if (m_param->bEmitHRDSEI) | |
458 | { | |
459 | const HRDInfo* hrd = &sps->vuiParameters.hrdParameters; | |
460 | vbvBufferSize = hrd->cpbSizeValue << (hrd->cpbSizeScale + CPB_SHIFT); | |
461 | vbvMaxBitrate = hrd->bitRateValue << (hrd->bitRateScale + BR_SHIFT); | |
462 | } | |
463 | m_bufferRate = vbvMaxBitrate / m_fps; | |
464 | m_vbvMaxRate = vbvMaxBitrate; | |
465 | m_bufferSize = vbvBufferSize; | |
466 | m_singleFrameVbv = m_bufferRate * 1.1 > m_bufferSize; | |
467 | ||
468 | if (m_param->rc.vbvBufferInit > 1.) | |
469 | m_param->rc.vbvBufferInit = Clip3(0.0, 1.0, m_param->rc.vbvBufferInit / m_param->rc.vbvBufferSize); | |
470 | m_param->rc.vbvBufferInit = Clip3(0.0, 1.0, X265_MAX(m_param->rc.vbvBufferInit, m_bufferRate / m_bufferSize)); | |
471 | m_bufferFillFinal = m_bufferSize * m_param->rc.vbvBufferInit; | |
472 | } | |
473 | ||
474 | m_totalBits = 0; | |
475 | m_framesDone = 0; | |
476 | m_residualCost = 0; | |
477 | m_partialResidualCost = 0; | |
478 | for (int i = 0; i < s_slidingWindowFrames; i++) | |
479 | { | |
480 | m_satdCostWindow[i] = 0; | |
481 | m_encodedBitsWindow[i] = 0; | |
482 | } | |
483 | m_sliderPos = 0; | |
484 | ||
485 | /* 720p videos seem to be a good cutoff for cplxrSum */ | |
486 | double tuneCplxFactor = (m_param->rc.cuTree && m_ncu > 3600) ? 2.5 : 1; | |
487 | ||
488 | /* estimated ratio that produces a reasonable QP for the first I-frame */ | |
489 | m_cplxrSum = .01 * pow(7.0e5, m_qCompress) * pow(m_ncu, 0.5) * tuneCplxFactor; | |
490 | m_wantedBitsWindow = m_bitrate * m_frameDuration; | |
491 | m_accumPNorm = .01; | |
492 | m_accumPQp = (m_param->rc.rateControlMode == X265_RC_CRF ? CRF_INIT_QP : ABR_INIT_QP_MIN) * m_accumPNorm; | |
493 | ||
494 | /* Frame Predictors and Row predictors used in vbv */ | |
495 | for (int i = 0; i < 5; i++) | |
496 | { | |
497 | m_pred[i].coeff = 2.0; | |
498 | m_pred[i].count = 1.0; | |
499 | m_pred[i].decay = 0.5; | |
500 | m_pred[i].offset = 0.0; | |
501 | } | |
502 | m_predBfromP = m_pred[0]; | |
503 | if (!m_statFileOut && (m_param->rc.bStatWrite || m_param->rc.bStatRead)) | |
504 | { | |
505 | /* If the user hasn't defined the stat filename, use the default value */ | |
506 | const char *fileName = m_param->rc.statFileName; | |
507 | if (!fileName) | |
508 | fileName = s_defaultStatFileName; | |
509 | /* Load stat file and init 2pass algo */ | |
510 | if (m_param->rc.bStatRead) | |
511 | { | |
512 | m_expectedBitsSum = 0; | |
513 | char *p, *statsIn, *statsBuf; | |
514 | /* read 1st pass stats */ | |
515 | statsIn = statsBuf = x265_slurp_file(fileName); | |
516 | if (!statsBuf) | |
517 | return false; | |
518 | if (m_param->rc.cuTree) | |
519 | { | |
520 | char *tmpFile = strcatFilename(fileName, ".cutree"); | |
521 | if (!tmpFile) | |
522 | return false; | |
523 | m_cutreeStatFileIn = fopen(tmpFile, "rb"); | |
524 | X265_FREE(tmpFile); | |
525 | if (!m_cutreeStatFileIn) | |
526 | { | |
527 | x265_log(m_param, X265_LOG_ERROR, "can't open stats file %s\n", tmpFile); | |
528 | return false; | |
529 | } | |
530 | } | |
531 | ||
532 | /* check whether 1st pass options were compatible with current options */ | |
533 | if (strncmp(statsBuf, "#options:", 9)) | |
534 | { | |
535 | x265_log(m_param, X265_LOG_ERROR,"options list in stats file not valid\n"); | |
536 | return false; | |
537 | } | |
538 | { | |
539 | int i, j; | |
540 | uint32_t k , l; | |
541 | bool bErr = false; | |
542 | char *opts = statsBuf; | |
543 | statsIn = strchr(statsBuf, '\n'); | |
544 | if (!statsIn) | |
545 | { | |
546 | x265_log(m_param, X265_LOG_ERROR, "Malformed stats file\n"); | |
547 | return false; | |
548 | } | |
549 | *statsIn = '\0'; | |
550 | statsIn++; | |
551 | if (sscanf(opts, "#options: %dx%d", &i, &j) != 2) | |
552 | { | |
553 | x265_log(m_param, X265_LOG_ERROR, "Resolution specified in stats file not valid\n"); | |
554 | return false; | |
555 | } | |
556 | if ((p = strstr(opts, " fps=")) == 0 || sscanf(p, " fps=%u/%u", &k, &l) != 2) | |
557 | { | |
558 | x265_log(m_param, X265_LOG_ERROR, "fps specified in stats file not valid\n"); | |
559 | return false; | |
560 | } | |
561 | if (k != m_param->fpsNum || l != m_param->fpsDenom) | |
562 | { | |
563 | x265_log(m_param, X265_LOG_ERROR, "fps mismatch with 1st pass (%u/%u vs %u/%u)\n", | |
564 | m_param->fpsNum, m_param->fpsDenom, k, l); | |
565 | return false; | |
566 | } | |
567 | CMP_OPT_FIRST_PASS("bitdepth", m_param->internalBitDepth); | |
568 | CMP_OPT_FIRST_PASS("weightp", m_param->bEnableWeightedPred); | |
569 | CMP_OPT_FIRST_PASS("bframes", m_param->bframes); | |
570 | CMP_OPT_FIRST_PASS("b-pyramid", m_param->bBPyramid); | |
571 | CMP_OPT_FIRST_PASS("open-gop", m_param->bOpenGOP); | |
572 | CMP_OPT_FIRST_PASS("keyint", m_param->keyframeMax); | |
573 | CMP_OPT_FIRST_PASS("scenecut", m_param->scenecutThreshold); | |
574 | ||
575 | if ((p = strstr(opts, "b-adapt=")) != 0 && sscanf(p, "b-adapt=%d", &i) && i >= X265_B_ADAPT_NONE && i <= X265_B_ADAPT_TRELLIS) | |
576 | { | |
577 | m_param->bFrameAdaptive = i; | |
578 | } | |
579 | else if (m_param->bframes) | |
580 | { | |
581 | x265_log(m_param, X265_LOG_ERROR, "b-adapt method specified in stats file not valid\n"); | |
582 | return false; | |
583 | } | |
584 | ||
585 | if ((p = strstr(opts, "rc-lookahead=")) != 0 && sscanf(p, "rc-lookahead=%d", &i)) | |
586 | m_param->lookaheadDepth = i; | |
587 | } | |
588 | /* find number of pics */ | |
589 | p = statsIn; | |
590 | int numEntries; | |
591 | for (numEntries = -1; p; numEntries++) | |
592 | p = strchr(p + 1, ';'); | |
593 | if (!numEntries) | |
594 | { | |
595 | x265_log(m_param, X265_LOG_ERROR, "empty stats file\n"); | |
596 | return false; | |
597 | } | |
598 | m_numEntries = numEntries; | |
599 | ||
600 | if (m_param->totalFrames < m_numEntries && m_param->totalFrames > 0) | |
601 | { | |
602 | x265_log(m_param, X265_LOG_WARNING, "2nd pass has fewer frames than 1st pass (%d vs %d)\n", | |
603 | m_param->totalFrames, m_numEntries); | |
604 | } | |
605 | if (m_param->totalFrames > m_numEntries) | |
606 | { | |
607 | x265_log(m_param, X265_LOG_ERROR, "2nd pass has more frames than 1st pass (%d vs %d)\n", | |
608 | m_param->totalFrames, m_numEntries); | |
609 | return false; | |
610 | } | |
611 | ||
612 | m_rce2Pass = X265_MALLOC(RateControlEntry, m_numEntries); | |
613 | if (!m_rce2Pass) | |
614 | { | |
615 | x265_log(m_param, X265_LOG_ERROR, "Rce Entries for 2 pass cannot be allocated\n"); | |
616 | return false; | |
617 | } | |
618 | /* init all to skipped p frames */ | |
619 | for (int i = 0; i < m_numEntries; i++) | |
620 | { | |
621 | RateControlEntry *rce = &m_rce2Pass[i]; | |
622 | rce->sliceType = P_SLICE; | |
623 | rce->qScale = rce->newQScale = x265_qp2qScale(20); | |
624 | rce->miscBits = m_ncu + 10; | |
625 | rce->newQp = 0; | |
626 | } | |
627 | /* read stats */ | |
628 | p = statsIn; | |
629 | double totalQpAq = 0; | |
630 | for (int i = 0; i < m_numEntries; i++) | |
631 | { | |
632 | RateControlEntry *rce; | |
633 | int frameNumber; | |
634 | char picType; | |
635 | int e; | |
636 | char *next; | |
637 | double qpRc, qpAq; | |
638 | next = strstr(p, ";"); | |
639 | if (next) | |
640 | *next++ = 0; | |
641 | e = sscanf(p, " in:%d ", &frameNumber); | |
642 | if (frameNumber < 0 || frameNumber >= m_numEntries) | |
643 | { | |
644 | x265_log(m_param, X265_LOG_ERROR, "bad frame number (%d) at stats line %d\n", frameNumber, i); | |
645 | return false; | |
646 | } | |
647 | rce = &m_rce2Pass[frameNumber]; | |
648 | e += sscanf(p, " in:%*d out:%*d type:%c q:%lf q-aq:%lf tex:%d mv:%d misc:%d icu:%lf pcu:%lf scu:%lf", | |
649 | &picType, &qpRc, &qpAq, &rce->coeffBits, | |
650 | &rce->mvBits, &rce->miscBits, &rce->iCuCount, &rce->pCuCount, | |
651 | &rce->skipCuCount); | |
652 | rce->keptAsRef = true; | |
653 | if (picType == 'b' || picType == 'p') | |
654 | rce->keptAsRef = false; | |
655 | if (picType == 'I' || picType == 'i') | |
656 | rce->sliceType = I_SLICE; | |
657 | else if (picType == 'P' || picType == 'p') | |
658 | rce->sliceType = P_SLICE; | |
659 | else if (picType == 'B' || picType == 'b') | |
660 | rce->sliceType = B_SLICE; | |
661 | else | |
662 | e = -1; | |
663 | if (e < 10) | |
664 | { | |
665 | x265_log(m_param, X265_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e); | |
666 | return false; | |
667 | } | |
668 | rce->qScale = x265_qp2qScale(qpRc); | |
669 | totalQpAq += qpAq; | |
670 | p = next; | |
671 | } | |
672 | X265_FREE(statsBuf); | |
673 | ||
674 | if (m_param->rc.rateControlMode == X265_RC_ABR) | |
675 | { | |
676 | if (!initPass2()) | |
677 | return false; | |
678 | } /* else we're using constant quant, so no need to run the bitrate allocation */ | |
679 | } | |
680 | /* Open output file */ | |
681 | /* If input and output files are the same, output to a temp file | |
682 | * and move it to the real name only when it's complete */ | |
683 | if (m_param->rc.bStatWrite) | |
684 | { | |
685 | char *p, *statFileTmpname; | |
686 | statFileTmpname = strcatFilename(fileName, ".temp"); | |
687 | if (!statFileTmpname) | |
688 | return false; | |
689 | m_statFileOut = fopen(statFileTmpname, "wb"); | |
690 | X265_FREE(statFileTmpname); | |
691 | if (!m_statFileOut) | |
692 | { | |
693 | x265_log(m_param, X265_LOG_ERROR, "can't open stats file %s\n", statFileTmpname); | |
694 | return false; | |
695 | } | |
696 | p = x265_param2string(m_param); | |
697 | if (p) | |
698 | fprintf(m_statFileOut, "#options: %s\n", p); | |
699 | X265_FREE(p); | |
700 | if (m_param->rc.cuTree && !m_param->rc.bStatRead) | |
701 | { | |
702 | statFileTmpname = strcatFilename(fileName, ".cutree.temp"); | |
703 | if (!statFileTmpname) | |
704 | return false; | |
705 | m_cutreeStatFileOut = fopen(statFileTmpname, "wb"); | |
706 | X265_FREE(statFileTmpname); | |
707 | if (!m_cutreeStatFileOut) | |
708 | { | |
709 | x265_log(m_param, X265_LOG_ERROR, "can't open mbtree stats file %s\n", statFileTmpname); | |
710 | return false; | |
711 | } | |
712 | } | |
713 | } | |
714 | if (m_param->rc.cuTree) | |
715 | { | |
716 | m_cuTreeStats.qpBuffer[0] = X265_MALLOC(uint16_t, m_ncu * sizeof(uint16_t)); | |
717 | if (m_param->bBPyramid && m_param->rc.bStatRead) | |
718 | m_cuTreeStats.qpBuffer[1] = X265_MALLOC(uint16_t, m_ncu * sizeof(uint16_t)); | |
719 | m_cuTreeStats.qpBufPos = -1; | |
720 | } | |
721 | } | |
722 | return true; | |
723 | } | |
724 | ||
725 | void RateControl::initHRD(SPS *sps) | |
726 | { | |
727 | int vbvBufferSize = m_param->rc.vbvBufferSize * 1000; | |
728 | int vbvMaxBitrate = m_param->rc.vbvMaxBitrate * 1000; | |
729 | ||
730 | // Init HRD | |
731 | HRDInfo* hrd = &sps->vuiParameters.hrdParameters; | |
732 | hrd->cbrFlag = m_isCbr; | |
733 | ||
734 | // normalize HRD size and rate to the value / scale notation | |
735 | hrd->bitRateScale = Clip3(0, 15, calcScale(vbvMaxBitrate) - BR_SHIFT); | |
736 | hrd->bitRateValue = (vbvMaxBitrate >> (hrd->bitRateScale + BR_SHIFT)); | |
737 | ||
738 | hrd->cpbSizeScale = Clip3(0, 15, calcScale(vbvBufferSize) - CPB_SHIFT); | |
739 | hrd->cpbSizeValue = (vbvBufferSize >> (hrd->cpbSizeScale + CPB_SHIFT)); | |
740 | int bitRateUnscale = hrd->bitRateValue << (hrd->bitRateScale + BR_SHIFT); | |
741 | int cpbSizeUnscale = hrd->cpbSizeValue << (hrd->cpbSizeScale + CPB_SHIFT); | |
742 | ||
743 | // arbitrary | |
744 | #define MAX_DURATION 0.5 | |
745 | ||
746 | TimingInfo *time = &sps->vuiParameters.timingInfo; | |
747 | int maxCpbOutputDelay = (int)(X265_MIN(m_param->keyframeMax * MAX_DURATION * time->timeScale / time->numUnitsInTick, INT_MAX)); | |
748 | int maxDpbOutputDelay = (int)(sps->maxDecPicBuffering * MAX_DURATION * time->timeScale / time->numUnitsInTick); | |
749 | int maxDelay = (int)(90000.0 * cpbSizeUnscale / bitRateUnscale + 0.5); | |
750 | ||
751 | hrd->initialCpbRemovalDelayLength = 2 + Clip3(4, 22, 32 - calcLength(maxDelay)); | |
752 | hrd->cpbRemovalDelayLength = Clip3(4, 31, 32 - calcLength(maxCpbOutputDelay)); | |
753 | hrd->dpbOutputDelayLength = Clip3(4, 31, 32 - calcLength(maxDpbOutputDelay)); | |
754 | ||
755 | #undef MAX_DURATION | |
756 | } | |
757 | ||
758 | bool RateControl::initPass2() | |
759 | { | |
760 | uint64_t allConstBits = 0; | |
761 | uint64_t allAvailableBits = uint64_t(m_param->rc.bitrate * 1000. * m_numEntries * m_frameDuration); | |
762 | double rateFactor, stepMult; | |
763 | double qBlur = m_param->rc.qblur; | |
764 | double cplxBlur = m_param->rc.complexityBlur; | |
765 | const int filterSize = (int)(qBlur * 4) | 1; | |
766 | double expectedBits; | |
767 | double *qScale, *blurredQscale; | |
768 | double baseCplx = m_ncu * (m_param->bframes ? 120 : 80); | |
769 | double clippedDuration = CLIP_DURATION(m_frameDuration) / BASE_FRAME_DURATION; | |
770 | ||
771 | /* find total/average complexity & const_bits */ | |
772 | for (int i = 0; i < m_numEntries; i++) | |
773 | allConstBits += m_rce2Pass[i].miscBits; | |
774 | ||
775 | if (allAvailableBits < allConstBits) | |
776 | { | |
777 | x265_log(m_param, X265_LOG_ERROR, "requested bitrate is too low. estimated minimum is %d kbps\n", | |
778 | (int)(allConstBits * m_fps / m_numEntries * 1000.)); | |
779 | return false; | |
780 | } | |
781 | ||
782 | /* Blur complexities, to reduce local fluctuation of QP. | |
783 | * We don't blur the QPs directly, because then one very simple frame | |
784 | * could drag down the QP of a nearby complex frame and give it more | |
785 | * bits than intended. */ | |
786 | for (int i = 0; i < m_numEntries; i++) | |
787 | { | |
788 | double weightSum = 0; | |
789 | double cplxSum = 0; | |
790 | double weight = 1.0; | |
791 | double gaussianWeight; | |
792 | /* weighted average of cplx of future frames */ | |
793 | for (int j = 1; j < cplxBlur * 2 && j < m_numEntries - i; j++) | |
794 | { | |
795 | RateControlEntry *rcj = &m_rce2Pass[i + j]; | |
796 | weight *= 1 - pow(rcj->iCuCount / m_ncu, 2); | |
797 | if (weight < 0.0001) | |
798 | break; | |
799 | gaussianWeight = weight * exp(-j * j / 200.0); | |
800 | weightSum += gaussianWeight; | |
801 | cplxSum += gaussianWeight * (qScale2bits(rcj, 1) - rcj->miscBits) / clippedDuration; | |
802 | } | |
803 | /* weighted average of cplx of past frames */ | |
804 | weight = 1.0; | |
805 | for (int j = 0; j <= cplxBlur * 2 && j <= i; j++) | |
806 | { | |
807 | RateControlEntry *rcj = &m_rce2Pass[i - j]; | |
808 | gaussianWeight = weight * exp(-j * j / 200.0); | |
809 | weightSum += gaussianWeight; | |
810 | cplxSum += gaussianWeight * (qScale2bits(rcj, 1) - rcj->miscBits) / clippedDuration; | |
811 | weight *= 1 - pow(rcj->iCuCount / m_ncu, 2); | |
812 | if (weight < .0001) | |
813 | break; | |
814 | } | |
815 | m_rce2Pass[i].blurredComplexity = cplxSum / weightSum; | |
816 | } | |
817 | ||
818 | CHECKED_MALLOC(qScale, double, m_numEntries); | |
819 | if (filterSize > 1) | |
820 | { | |
821 | CHECKED_MALLOC(blurredQscale, double, m_numEntries); | |
822 | } | |
823 | else | |
824 | blurredQscale = qScale; | |
825 | ||
826 | /* Search for a factor which, when multiplied by the RCEQ values from | |
827 | * each frame, adds up to the desired total size. | |
828 | * There is no exact closed-form solution because of VBV constraints and | |
829 | * because qscale2bits is not invertible, but we can start with the simple | |
830 | * approximation of scaling the 1st pass by the ratio of bitrates. | |
831 | * The search range is probably overkill, but speed doesn't matter here. */ | |
832 | ||
833 | expectedBits = 1; | |
834 | for (int i = 0; i < m_numEntries; i++) | |
835 | { | |
836 | RateControlEntry* rce = &m_rce2Pass[i]; | |
837 | double q = getQScale(rce, 1.0); | |
838 | expectedBits += qScale2bits(rce, q); | |
839 | m_lastQScaleFor[rce->sliceType] = q; | |
840 | } | |
841 | stepMult = allAvailableBits / expectedBits; | |
842 | ||
843 | rateFactor = 0; | |
844 | for (double step = 1E4 * stepMult; step > 1E-7 * stepMult; step *= 0.5) | |
845 | { | |
846 | expectedBits = 0; | |
847 | rateFactor += step; | |
848 | ||
849 | m_lastNonBPictType = -1; | |
850 | m_lastAccumPNorm = 1; | |
851 | m_accumPNorm = 0; | |
852 | ||
853 | m_lastQScaleFor[0] = m_lastQScaleFor[1] = | |
854 | m_lastQScaleFor[2] = pow(baseCplx, 1 - m_qCompress) / rateFactor; | |
855 | ||
856 | /* find qscale */ | |
857 | for (int i = 0; i < m_numEntries; i++) | |
858 | { | |
859 | RateControlEntry *rce = &m_rce2Pass[i]; | |
860 | qScale[i] = getQScale(rce, rateFactor); | |
861 | m_lastQScaleFor[rce->sliceType] = qScale[i]; | |
862 | } | |
863 | ||
864 | /* fixed I/B qscale relative to P */ | |
865 | for (int i = m_numEntries - 1; i >= 0; i--) | |
866 | { | |
867 | qScale[i] = getDiffLimitedQScale(&m_rce2Pass[i], qScale[i]); | |
868 | X265_CHECK(qScale[i] >= 0, "qScale became negative\n"); | |
869 | } | |
870 | ||
871 | /* smooth curve */ | |
872 | if (filterSize > 1) | |
873 | { | |
874 | X265_CHECK(filterSize % 2 == 1, "filterSize not an odd number\n"); | |
875 | for (int i = 0; i < m_numEntries; i++) | |
876 | { | |
877 | double q = 0.0, sum = 0.0; | |
878 | ||
879 | for (int j = 0; j < filterSize; j++) | |
880 | { | |
881 | int idx = i + j - filterSize / 2; | |
882 | double d = idx - i; | |
883 | double coeff = qBlur == 0 ? 1.0 : exp(-d * d / (qBlur * qBlur)); | |
884 | if (idx < 0 || idx >= m_numEntries) | |
885 | continue; | |
886 | if (m_rce2Pass[i].sliceType != m_rce2Pass[idx].sliceType) | |
887 | continue; | |
888 | q += qScale[idx] * coeff; | |
889 | sum += coeff; | |
890 | } | |
891 | blurredQscale[i] = q / sum; | |
892 | } | |
893 | } | |
894 | ||
895 | /* find expected bits */ | |
896 | for (int i = 0; i < m_numEntries; i++) | |
897 | { | |
898 | RateControlEntry *rce = &m_rce2Pass[i]; | |
899 | rce->newQScale = clipQscale(NULL, rce, blurredQscale[i]); // check if needed | |
900 | X265_CHECK(rce->newQScale >= 0, "new Qscale is negative\n"); | |
901 | expectedBits += qScale2bits(rce, rce->newQScale); | |
902 | } | |
903 | ||
904 | if (expectedBits > allAvailableBits) | |
905 | rateFactor -= step; | |
906 | } | |
907 | ||
908 | X265_FREE(qScale); | |
909 | if (filterSize > 1) | |
910 | X265_FREE(blurredQscale); | |
911 | ||
912 | if (m_isVbv) | |
913 | if (!vbv2Pass(allAvailableBits)) | |
914 | return false; | |
915 | expectedBits = countExpectedBits(); | |
916 | ||
917 | if (fabs(expectedBits / allAvailableBits - 1.0) > 0.01) | |
918 | { | |
919 | double avgq = 0; | |
920 | for (int i = 0; i < m_numEntries; i++) | |
921 | avgq += m_rce2Pass[i].newQScale; | |
922 | avgq = x265_qScale2qp(avgq / m_numEntries); | |
923 | ||
924 | if (expectedBits > allAvailableBits || !m_isVbv) | |
925 | x265_log(m_param, X265_LOG_WARNING, "Error: 2pass curve failed to converge\n"); | |
926 | x265_log(m_param, X265_LOG_WARNING, "target: %.2f kbit/s, expected: %.2f kbit/s, avg QP: %.4f\n", | |
927 | (double)m_param->rc.bitrate, | |
928 | expectedBits * m_fps / (m_numEntries * 1000.), | |
929 | avgq); | |
930 | if (expectedBits < allAvailableBits && avgq < QP_MIN + 2) | |
931 | { | |
932 | x265_log(m_param, X265_LOG_WARNING, "try reducing target bitrate\n"); | |
933 | } | |
934 | else if (expectedBits > allAvailableBits && avgq > QP_MAX_SPEC - 2) | |
935 | { | |
936 | x265_log(m_param, X265_LOG_WARNING, "try increasing target bitrate\n"); | |
937 | } | |
938 | else if (!(m_2pass && m_isVbv)) | |
939 | x265_log(m_param, X265_LOG_WARNING, "internal error\n"); | |
940 | } | |
941 | ||
942 | return true; | |
943 | ||
944 | fail: | |
945 | x265_log(m_param, X265_LOG_WARNING, "two-pass ABR initialization failed\n"); | |
946 | return false; | |
947 | } | |
948 | ||
949 | bool RateControl::vbv2Pass(uint64_t allAvailableBits) | |
950 | { | |
951 | /* for each interval of bufferFull .. underflow, uniformly increase the qp of all | |
952 | * frames in the interval until either buffer is full at some intermediate frame or the | |
953 | * last frame in the interval no longer underflows. Recompute intervals and repeat. | |
954 | * Then do the converse to put bits back into overflow areas until target size is met */ | |
955 | ||
956 | double *fills; | |
957 | double expectedBits = 0; | |
958 | double adjustment; | |
959 | double prevBits = 0; | |
960 | int t0, t1; | |
961 | int iterations = 0 , adjMin, adjMax; | |
962 | CHECKED_MALLOC(fills, double, m_numEntries + 1); | |
963 | fills++; | |
964 | ||
965 | /* adjust overall stream size */ | |
966 | do | |
967 | { | |
968 | iterations++; | |
969 | prevBits = expectedBits; | |
970 | ||
971 | if (expectedBits) | |
972 | { /* not first iteration */ | |
973 | adjustment = X265_MAX(X265_MIN(expectedBits / allAvailableBits, 0.999), 0.9); | |
974 | fills[-1] = m_bufferSize * m_param->rc.vbvBufferInit; | |
975 | t0 = 0; | |
976 | /* fix overflows */ | |
977 | adjMin = 1; | |
978 | while (adjMin && findUnderflow(fills, &t0, &t1, 1)) | |
979 | { | |
980 | adjMin = fixUnderflow(t0, t1, adjustment, MIN_QPSCALE, MAX_MAX_QPSCALE); | |
981 | t0 = t1; | |
982 | } | |
983 | } | |
984 | ||
985 | fills[-1] = m_bufferSize * (1. - m_param->rc.vbvBufferInit); | |
986 | t0 = 0; | |
987 | /* fix underflows -- should be done after overflow, as we'd better undersize target than underflowing VBV */ | |
988 | adjMax = 1; | |
989 | while (adjMax && findUnderflow(fills, &t0, &t1, 0)) | |
990 | adjMax = fixUnderflow(t0, t1, 1.001, MIN_QPSCALE, MAX_MAX_QPSCALE ); | |
991 | ||
992 | expectedBits = countExpectedBits(); | |
993 | } | |
994 | while ((expectedBits < .995 * allAvailableBits) && ((int64_t)(expectedBits+.5) > (int64_t)(prevBits+.5))); | |
995 | ||
996 | if (!adjMax) | |
997 | x265_log(m_param, X265_LOG_WARNING, "vbv-maxrate issue, qpmax or vbv-maxrate too low\n"); | |
998 | ||
999 | /* store expected vbv filling values for tracking when encoding */ | |
1000 | for (int i = 0; i < m_numEntries; i++) | |
1001 | m_rce2Pass[i].expectedVbv = m_bufferSize - fills[i]; | |
1002 | ||
1003 | X265_FREE(fills - 1); | |
1004 | return true; | |
1005 | ||
1006 | fail: | |
1007 | x265_log(m_param, X265_LOG_ERROR, "malloc failure in two-pass VBV init\n"); | |
1008 | return false; | |
1009 | } | |
1010 | ||
1011 | /* In 2pass, force the same frame types as in the 1st pass */ | |
1012 | int RateControl::rateControlSliceType(int frameNum) | |
1013 | { | |
1014 | if (m_param->rc.bStatRead) | |
1015 | { | |
1016 | if (frameNum >= m_numEntries) | |
1017 | { | |
1018 | /* We could try to initialize everything required for ABR and | |
1019 | * adaptive B-frames, but that would be complicated. | |
1020 | * So just calculate the average QP used so far. */ | |
1021 | m_param->rc.qp = (m_accumPQp < 1) ? ABR_INIT_QP_MAX : (int)(m_accumPQp + 0.5); | |
1022 | m_qpConstant[P_SLICE] = Clip3(0, QP_MAX_MAX, m_param->rc.qp); | |
1023 | m_qpConstant[I_SLICE] = Clip3(0, QP_MAX_MAX, (int)(m_param->rc.qp - m_ipOffset + 0.5)); | |
1024 | m_qpConstant[B_SLICE] = Clip3(0, QP_MAX_MAX, (int)(m_param->rc.qp + m_pbOffset + 0.5)); | |
1025 | ||
1026 | x265_log(m_param, X265_LOG_ERROR, "2nd pass has more frames than 1st pass (%d)\n", m_numEntries); | |
1027 | x265_log(m_param, X265_LOG_ERROR, "continuing anyway, at constant QP=%d\n", m_param->rc.qp); | |
1028 | if (m_param->bFrameAdaptive) | |
1029 | x265_log(m_param, X265_LOG_ERROR, "disabling adaptive B-frames\n"); | |
1030 | ||
1031 | m_isAbr = 0; | |
1032 | m_2pass = 0; | |
1033 | m_param->rc.rateControlMode = X265_RC_CQP; | |
1034 | m_param->rc.bStatRead = 0; | |
1035 | m_param->bFrameAdaptive = 0; | |
1036 | m_param->scenecutThreshold = 0; | |
1037 | m_param->rc.cuTree = 0; | |
1038 | if (m_param->bframes > 1) | |
1039 | m_param->bframes = 1; | |
1040 | return X265_TYPE_AUTO; | |
1041 | } | |
1042 | int frameType = m_rce2Pass[frameNum].sliceType == I_SLICE ? (frameNum > 0 && m_param->bOpenGOP ? X265_TYPE_I : X265_TYPE_IDR) | |
1043 | : m_rce2Pass[frameNum].sliceType == P_SLICE ? X265_TYPE_P | |
1044 | : (m_rce2Pass[frameNum].sliceType == B_SLICE && m_rce2Pass[frameNum].keptAsRef? X265_TYPE_BREF : X265_TYPE_B); | |
1045 | return frameType; | |
1046 | } | |
1047 | else | |
1048 | return X265_TYPE_AUTO; | |
1049 | } | |
1050 | ||
1051 | int RateControl::rateControlStart(Frame* curFrame, RateControlEntry* rce, Encoder* enc) | |
1052 | { | |
1053 | int orderValue = m_startEndOrder.get(); | |
1054 | int startOrdinal = rce->encodeOrder * 2; | |
1055 | ||
1056 | while (orderValue < startOrdinal && !m_bTerminated) | |
1057 | orderValue = m_startEndOrder.waitForChange(orderValue); | |
1058 | ||
1059 | if (!curFrame) | |
1060 | { | |
1061 | // faked rateControlStart calls when the encoder is flushing | |
1062 | m_startEndOrder.incr(); | |
1063 | return 0; | |
1064 | } | |
1065 | ||
1066 | FrameData& curEncData = *curFrame->m_encData; | |
1067 | m_curSlice = curEncData.m_slice; | |
1068 | m_sliceType = m_curSlice->m_sliceType; | |
1069 | rce->sliceType = m_sliceType; | |
1070 | rce->poc = m_curSlice->m_poc; | |
1071 | if (m_param->rc.bStatRead) | |
1072 | { | |
1073 | X265_CHECK(rce->poc >= 0 && rce->poc < m_numEntries, "bad encode ordinal\n"); | |
1074 | copyRceData(rce, &m_rce2Pass[rce->poc]); | |
1075 | } | |
1076 | rce->isActive = true; | |
1077 | if (m_sliceType == B_SLICE) | |
1078 | rce->bframes = m_leadingBframes; | |
1079 | else | |
1080 | m_leadingBframes = curFrame->m_lowres.leadingBframes; | |
1081 | ||
1082 | rce->bLastMiniGopBFrame = curFrame->m_lowres.bLastMiniGopBFrame; | |
1083 | rce->bufferRate = m_bufferRate; | |
1084 | rce->rowCplxrSum = 0.0; | |
1085 | rce->rowTotalBits = 0; | |
1086 | if (m_isVbv) | |
1087 | { | |
1088 | if (rce->rowPreds[0][0].count == 0) | |
1089 | { | |
1090 | for (int i = 0; i < 3; i++) | |
1091 | { | |
1092 | for (int j = 0; j < 2; j++) | |
1093 | { | |
1094 | rce->rowPreds[i][j].coeff = 0.25; | |
1095 | rce->rowPreds[i][j].count = 1.0; | |
1096 | rce->rowPreds[i][j].decay = 0.5; | |
1097 | rce->rowPreds[i][j].offset = 0.0; | |
1098 | } | |
1099 | } | |
1100 | } | |
1101 | rce->rowPred[0] = &rce->rowPreds[m_sliceType][0]; | |
1102 | rce->rowPred[1] = &rce->rowPreds[m_sliceType][1]; | |
1103 | m_predictedBits = m_totalBits; | |
1104 | updateVbvPlan(enc); | |
1105 | rce->bufferFill = m_bufferFill; | |
1106 | ||
1107 | int mincr = enc->m_vps.ptl.minCrForLevel; | |
1108 | /* Profiles above Main10 don't require maxAU size check, so just set the maximum to a large value. */ | |
1109 | if (enc->m_vps.ptl.profileIdc > Profile::MAIN10 || enc->m_vps.ptl.levelIdc == Level::NONE) | |
1110 | rce->frameSizeMaximum = 1e9; | |
1111 | else | |
1112 | { | |
1113 | /* The spec has a special case for the first frame. */ | |
1114 | if (rce->encodeOrder == 0) | |
1115 | { | |
1116 | /* 1.5 * (Max( PicSizeInSamplesY, fR * MaxLumaSr) + MaxLumaSr * (AuCpbRemovalTime[ 0 ] -AuNominalRemovalTime[ 0 ])) ? MinCr */ | |
1117 | double fr = 1. / 300; | |
1118 | int picSizeInSamplesY = m_param->sourceWidth * m_param->sourceHeight; | |
1119 | rce->frameSizeMaximum = 8 * 1.5 * X265_MAX(picSizeInSamplesY, fr * enc->m_vps.ptl.maxLumaSrForLevel) / mincr; | |
1120 | } | |
1121 | else | |
1122 | { | |
1123 | /* 1.5 * MaxLumaSr * (AuCpbRemovalTime[ n ] - AyCpbRemovalTime[ n - 1 ]) ? MinCr */ | |
1124 | rce->frameSizeMaximum = 8 * 1.5 * enc->m_vps.ptl.maxLumaSrForLevel * m_frameDuration / mincr; | |
1125 | } | |
1126 | } | |
1127 | } | |
1128 | if (m_isAbr || m_2pass) // ABR,CRF | |
1129 | { | |
1130 | if (m_isAbr || m_isVbv) | |
1131 | { | |
1132 | m_currentSatd = curFrame->m_lowres.satdCost >> (X265_DEPTH - 8); | |
1133 | /* Update rce for use in rate control VBV later */ | |
1134 | rce->lastSatd = m_currentSatd; | |
1135 | } | |
1136 | double q = x265_qScale2qp(rateEstimateQscale(curFrame, rce)); | |
1137 | q = Clip3((double)QP_MIN, (double)QP_MAX_MAX, q); | |
1138 | m_qp = int(q + 0.5); | |
1139 | rce->qpaRc = curEncData.m_avgQpRc = curEncData.m_avgQpAq = q; | |
1140 | /* copy value of lastRceq into thread local rce struct *to be used in RateControlEnd() */ | |
1141 | rce->qRceq = m_lastRceq; | |
1142 | accumPQpUpdate(); | |
1143 | } | |
1144 | else // CQP | |
1145 | { | |
1146 | if (m_sliceType == B_SLICE && IS_REFERENCED(curFrame)) | |
1147 | m_qp = (m_qpConstant[B_SLICE] + m_qpConstant[P_SLICE]) / 2; | |
1148 | else | |
1149 | m_qp = m_qpConstant[m_sliceType]; | |
1150 | curEncData.m_avgQpAq = curEncData.m_avgQpRc = m_qp; | |
1151 | } | |
1152 | if (m_sliceType != B_SLICE) | |
1153 | { | |
1154 | m_lastNonBPictType = m_sliceType; | |
1155 | m_leadingNoBSatd = m_currentSatd; | |
1156 | } | |
1157 | rce->leadingNoBSatd = m_leadingNoBSatd; | |
1158 | if (curFrame->m_forceqp) | |
1159 | { | |
1160 | m_qp = int32_t(curFrame->m_forceqp + 0.5) - 1; | |
1161 | m_qp = Clip3(QP_MIN, QP_MAX_MAX, m_qp); | |
1162 | rce->qpaRc = curEncData.m_avgQpRc = curEncData.m_avgQpAq = m_qp; | |
1163 | } | |
1164 | // Do not increment m_startEndOrder here. Make rateControlEnd of previous thread | |
1165 | // to wait until rateControlUpdateStats of this frame is called | |
1166 | m_framesDone++; | |
1167 | return m_qp; | |
1168 | } | |
1169 | ||
1170 | void RateControl::accumPQpUpdate() | |
1171 | { | |
1172 | m_accumPQp *= .95; | |
1173 | m_accumPNorm *= .95; | |
1174 | m_accumPNorm += 1; | |
1175 | if (m_sliceType == I_SLICE) | |
1176 | m_accumPQp += m_qp + m_ipOffset; | |
1177 | else | |
1178 | m_accumPQp += m_qp; | |
1179 | } | |
1180 | ||
1181 | double RateControl::getDiffLimitedQScale(RateControlEntry *rce, double q) | |
1182 | { | |
1183 | // force I/B quants as a function of P quants | |
1184 | const double lastPqScale = m_lastQScaleFor[P_SLICE]; | |
1185 | const double lastNonBqScale = m_lastQScaleFor[m_lastNonBPictType]; | |
1186 | if (rce->sliceType == I_SLICE) | |
1187 | { | |
1188 | double iq = q; | |
1189 | double pq = x265_qp2qScale(m_accumPQp / m_accumPNorm); | |
1190 | double ipFactor = fabs(m_param->rc.ipFactor); | |
1191 | /* don't apply ipFactor if the following frame is also I */ | |
1192 | if (m_accumPNorm <= 0) | |
1193 | q = iq; | |
1194 | else if (m_param->rc.ipFactor < 0) | |
1195 | q = iq / ipFactor; | |
1196 | else if (m_accumPNorm >= 1) | |
1197 | q = pq / ipFactor; | |
1198 | else | |
1199 | q = m_accumPNorm * pq / ipFactor + (1 - m_accumPNorm) * iq; | |
1200 | } | |
1201 | else if (rce->sliceType == B_SLICE) | |
1202 | { | |
1203 | if (m_param->rc.pbFactor > 0) | |
1204 | q = lastNonBqScale; | |
1205 | if (!rce->keptAsRef) | |
1206 | q *= fabs(m_param->rc.pbFactor); | |
1207 | } | |
1208 | else if (rce->sliceType == P_SLICE | |
1209 | && m_lastNonBPictType == P_SLICE | |
1210 | && rce->coeffBits == 0) | |
1211 | { | |
1212 | q = lastPqScale; | |
1213 | } | |
1214 | ||
1215 | /* last qscale / qdiff stuff */ | |
1216 | if (m_lastNonBPictType == rce->sliceType && | |
1217 | (rce->sliceType != I_SLICE || m_lastAccumPNorm < 1)) | |
1218 | { | |
1219 | double maxQscale = m_lastQScaleFor[rce->sliceType] * m_lstep; | |
1220 | double minQscale = m_lastQScaleFor[rce->sliceType] / m_lstep; | |
1221 | q = Clip3(minQscale, maxQscale, q); | |
1222 | } | |
1223 | ||
1224 | m_lastQScaleFor[rce->sliceType] = q; | |
1225 | if (rce->sliceType != B_SLICE) | |
1226 | m_lastNonBPictType = rce->sliceType; | |
1227 | if (rce->sliceType == I_SLICE) | |
1228 | { | |
1229 | m_lastAccumPNorm = m_accumPNorm; | |
1230 | m_accumPNorm = 0; | |
1231 | m_accumPQp = 0; | |
1232 | } | |
1233 | if (rce->sliceType == P_SLICE) | |
1234 | { | |
1235 | double mask = 1 - pow(rce->iCuCount / m_ncu, 2); | |
1236 | m_accumPQp = mask * (x265_qScale2qp(q) + m_accumPQp); | |
1237 | m_accumPNorm = mask * (1 + m_accumPNorm); | |
1238 | } | |
1239 | ||
1240 | return q; | |
1241 | } | |
1242 | ||
1243 | double RateControl::countExpectedBits() | |
1244 | { | |
1245 | double expectedBits = 0; | |
1246 | for( int i = 0; i < m_numEntries; i++ ) | |
1247 | { | |
1248 | RateControlEntry *rce = &m_rce2Pass[i]; | |
1249 | rce->expectedBits = (uint64_t)expectedBits; | |
1250 | expectedBits += qScale2bits(rce, rce->newQScale); | |
1251 | } | |
1252 | return expectedBits; | |
1253 | } | |
1254 | ||
1255 | bool RateControl::findUnderflow(double *fills, int *t0, int *t1, int over) | |
1256 | { | |
1257 | /* find an interval ending on an overflow or underflow (depending on whether | |
1258 | * we're adding or removing bits), and starting on the earliest frame that | |
1259 | * can influence the buffer fill of that end frame. */ | |
1260 | const double bufferMin = .1 * m_bufferSize; | |
1261 | const double bufferMax = .9 * m_bufferSize; | |
1262 | double fill = fills[*t0 - 1]; | |
1263 | double parity = over ? 1. : -1.; | |
1264 | int start = -1, end = -1; | |
1265 | for (int i = *t0; i < m_numEntries; i++) | |
1266 | { | |
1267 | fill += (m_frameDuration * m_vbvMaxRate - | |
1268 | qScale2bits(&m_rce2Pass[i], m_rce2Pass[i].newQScale)) * parity; | |
1269 | fill = Clip3(0.0, m_bufferSize, fill); | |
1270 | fills[i] = fill; | |
1271 | if (fill <= bufferMin || i == 0) | |
1272 | { | |
1273 | if (end >= 0) | |
1274 | break; | |
1275 | start = i; | |
1276 | } | |
1277 | else if (fill >= bufferMax && start >= 0) | |
1278 | end = i; | |
1279 | } | |
1280 | *t0 = start; | |
1281 | *t1 = end; | |
1282 | return start >= 0 && end >= 0; | |
1283 | } | |
1284 | ||
1285 | bool RateControl::fixUnderflow(int t0, int t1, double adjustment, double qscaleMin, double qscaleMax) | |
1286 | { | |
1287 | double qscaleOrig, qscaleNew; | |
1288 | bool adjusted = false; | |
1289 | if (t0 > 0) | |
1290 | t0++; | |
1291 | for (int i = t0; i <= t1; i++) | |
1292 | { | |
1293 | qscaleOrig = m_rce2Pass[i].newQScale; | |
1294 | qscaleOrig = Clip3(qscaleMin, qscaleMax, qscaleOrig); | |
1295 | qscaleNew = qscaleOrig * adjustment; | |
1296 | qscaleNew = Clip3(qscaleMin, qscaleMax, qscaleNew); | |
1297 | m_rce2Pass[i].newQScale = qscaleNew; | |
1298 | adjusted = adjusted || (qscaleNew != qscaleOrig); | |
1299 | } | |
1300 | return adjusted; | |
1301 | } | |
1302 | ||
1303 | bool RateControl::cuTreeReadFor2Pass(Frame* frame) | |
1304 | { | |
1305 | uint8_t sliceTypeActual = (uint8_t)m_rce2Pass[frame->m_poc].sliceType; | |
1306 | ||
1307 | if (m_rce2Pass[frame->m_poc].keptAsRef) | |
1308 | { | |
1309 | uint8_t type; | |
1310 | if (m_cuTreeStats.qpBufPos < 0) | |
1311 | { | |
1312 | do | |
1313 | { | |
1314 | m_cuTreeStats.qpBufPos++; | |
1315 | ||
1316 | if (!fread(&type, 1, 1, m_cutreeStatFileIn)) | |
1317 | goto fail; | |
1318 | if (fread(m_cuTreeStats.qpBuffer[m_cuTreeStats.qpBufPos], sizeof(uint16_t), m_ncu, m_cutreeStatFileIn) != (size_t)m_ncu) | |
1319 | goto fail; | |
1320 | ||
1321 | if (type != sliceTypeActual && m_cuTreeStats.qpBufPos == 1) | |
1322 | { | |
1323 | x265_log(m_param, X265_LOG_ERROR, "CU-tree frametype %d doesn't match actual frametype %d.\n", type, sliceTypeActual); | |
1324 | return false; | |
1325 | } | |
1326 | } | |
1327 | while(type != sliceTypeActual); | |
1328 | } | |
1329 | for (int i = 0; i < m_ncu; i++) | |
1330 | { | |
1331 | int16_t qpFix8 = m_cuTreeStats.qpBuffer[m_cuTreeStats.qpBufPos][i]; | |
1332 | frame->m_lowres.qpCuTreeOffset[i] = (double)(qpFix8) / 256.0; | |
1333 | frame->m_lowres.invQscaleFactor[i] = x265_exp2fix8(frame->m_lowres.qpCuTreeOffset[i]); | |
1334 | } | |
1335 | m_cuTreeStats.qpBufPos--; | |
1336 | } | |
1337 | else | |
1338 | calcAdaptiveQuantFrame(frame); | |
1339 | return true; | |
1340 | ||
1341 | fail: | |
1342 | x265_log(m_param, X265_LOG_ERROR, "Incomplete CU-tree stats file.\n"); | |
1343 | return false; | |
1344 | } | |
1345 | ||
1346 | double RateControl::rateEstimateQscale(Frame* curFrame, RateControlEntry *rce) | |
1347 | { | |
1348 | double q; | |
1349 | ||
1350 | if (m_2pass) | |
1351 | { | |
1352 | if (m_sliceType != rce->sliceType) | |
1353 | { | |
1354 | x265_log(m_param, X265_LOG_ERROR, "slice=%c but 2pass stats say %c\n", | |
1355 | g_sliceTypeToChar[m_sliceType], g_sliceTypeToChar[rce->sliceType]); | |
1356 | } | |
1357 | } | |
1358 | else | |
1359 | { | |
1360 | if (m_isAbr) | |
1361 | { | |
1362 | double slidingWindowCplxSum = 0; | |
1363 | int start = m_sliderPos > s_slidingWindowFrames ? m_sliderPos : 0; | |
1364 | for (int cnt = 0; cnt < s_slidingWindowFrames; cnt++, start++) | |
1365 | { | |
1366 | int pos = start % s_slidingWindowFrames; | |
1367 | slidingWindowCplxSum *= 0.5; | |
1368 | if (!m_satdCostWindow[pos]) | |
1369 | break; | |
1370 | slidingWindowCplxSum += m_satdCostWindow[pos] / (CLIP_DURATION(m_frameDuration) / BASE_FRAME_DURATION); | |
1371 | } | |
1372 | rce->movingAvgSum = slidingWindowCplxSum; | |
1373 | m_satdCostWindow[m_sliderPos % s_slidingWindowFrames] = rce->lastSatd; | |
1374 | m_sliderPos++; | |
1375 | } | |
1376 | } | |
1377 | ||
1378 | if (m_sliceType == B_SLICE) | |
1379 | { | |
1380 | /* B-frames don't have independent rate control, but rather get the | |
1381 | * average QP of the two adjacent P-frames + an offset */ | |
1382 | Slice* prevRefSlice = m_curSlice->m_refPicList[0][0]->m_encData->m_slice; | |
1383 | Slice* nextRefSlice = m_curSlice->m_refPicList[1][0]->m_encData->m_slice; | |
1384 | double q0 = m_curSlice->m_refPicList[0][0]->m_encData->m_avgQpRc; | |
1385 | double q1 = m_curSlice->m_refPicList[1][0]->m_encData->m_avgQpRc; | |
1386 | bool i0 = prevRefSlice->m_sliceType == I_SLICE; | |
1387 | bool i1 = nextRefSlice->m_sliceType == I_SLICE; | |
1388 | int dt0 = abs(m_curSlice->m_poc - prevRefSlice->m_poc); | |
1389 | int dt1 = abs(m_curSlice->m_poc - nextRefSlice->m_poc); | |
1390 | ||
1391 | // Skip taking a reference frame before the Scenecut if ABR has been reset. | |
1392 | if (m_lastAbrResetPoc >= 0) | |
1393 | { | |
1394 | if (prevRefSlice->m_sliceType == P_SLICE && prevRefSlice->m_poc < m_lastAbrResetPoc) | |
1395 | { | |
1396 | i0 = i1; | |
1397 | dt0 = dt1; | |
1398 | q0 = q1; | |
1399 | } | |
1400 | } | |
1401 | if (prevRefSlice->m_sliceType == B_SLICE && IS_REFERENCED(m_curSlice->m_refPicList[0][0])) | |
1402 | q0 -= m_pbOffset / 2; | |
1403 | if (nextRefSlice->m_sliceType == B_SLICE && IS_REFERENCED(m_curSlice->m_refPicList[1][0])) | |
1404 | q1 -= m_pbOffset / 2; | |
1405 | if (i0 && i1) | |
1406 | q = (q0 + q1) / 2 + m_ipOffset; | |
1407 | else if (i0) | |
1408 | q = q1; | |
1409 | else if (i1) | |
1410 | q = q0; | |
1411 | else | |
1412 | q = (q0 * dt1 + q1 * dt0) / (dt0 + dt1); | |
1413 | ||
1414 | if (IS_REFERENCED(curFrame)) | |
1415 | q += m_pbOffset / 2; | |
1416 | else | |
1417 | q += m_pbOffset; | |
1418 | rce->qpNoVbv = q; | |
1419 | double qScale = x265_qp2qScale(q); | |
1420 | ||
1421 | if (!m_2pass && m_isVbv) | |
1422 | { | |
1423 | if (m_leadingBframes > 5) | |
1424 | { | |
1425 | qScale = clipQscale(curFrame, rce, qScale); | |
1426 | m_lastQScaleFor[m_sliceType] = qScale; | |
1427 | } | |
1428 | rce->frameSizePlanned = predictSize(&m_predBfromP, qScale, (double)m_leadingNoBSatd); | |
1429 | } | |
1430 | else if (m_2pass && m_isVbv) | |
1431 | { | |
1432 | rce->frameSizePlanned = qScale2bits(rce, qScale); | |
1433 | } | |
1434 | /* Limit planned size by MinCR */ | |
1435 | if (m_isVbv) | |
1436 | rce->frameSizePlanned = X265_MIN(rce->frameSizePlanned, rce->frameSizeMaximum); | |
1437 | rce->frameSizeEstimated = rce->frameSizePlanned; | |
1438 | rce->newQScale = qScale; | |
1439 | return qScale; | |
1440 | } | |
1441 | else | |
1442 | { | |
1443 | double abrBuffer = 2 * m_param->rc.rateTolerance * m_bitrate; | |
1444 | if (m_2pass) | |
1445 | { | |
1446 | int64_t diff; | |
1447 | if (!m_isVbv) | |
1448 | { | |
1449 | m_predictedBits = m_totalBits; | |
1450 | if (rce->encodeOrder < m_param->frameNumThreads) | |
1451 | m_predictedBits += (int64_t)(rce->encodeOrder * m_bitrate / m_fps); | |
1452 | else | |
1453 | m_predictedBits += (int64_t)(m_param->frameNumThreads * m_bitrate / m_fps); | |
1454 | } | |
1455 | /* Adjust ABR buffer based on distance to the end of the video. */ | |
1456 | if (m_numEntries > rce->encodeOrder) | |
1457 | { | |
1458 | uint64_t finalBits = m_rce2Pass[m_numEntries - 1].expectedBits; | |
1459 | double videoPos = (double)rce->expectedBits / finalBits; | |
1460 | double scaleFactor = sqrt((1 - videoPos) * m_numEntries); | |
1461 | abrBuffer *= 0.5 * X265_MAX(scaleFactor, 0.5); | |
1462 | } | |
1463 | diff = m_predictedBits - (int64_t)rce->expectedBits; | |
1464 | q = rce->newQScale; | |
1465 | q /= Clip3(0.5, 2.0, (double)(abrBuffer - diff) / abrBuffer); | |
1466 | if (m_expectedBitsSum > 0) | |
1467 | { | |
1468 | /* Adjust quant based on the difference between | |
1469 | * achieved and expected bitrate so far */ | |
1470 | double curTime = (double)rce->encodeOrder / m_numEntries; | |
1471 | double w = Clip3(0.0, 1.0, curTime * 100); | |
1472 | q *= pow((double)m_totalBits / m_expectedBitsSum, w); | |
1473 | } | |
1474 | rce->qpNoVbv = x265_qScale2qp(q); | |
1475 | if (m_isVbv) | |
1476 | { | |
1477 | /* Do not overflow vbv */ | |
1478 | double expectedSize = qScale2bits(rce, q); | |
1479 | double expectedVbv = m_bufferFill + m_bufferRate - expectedSize; | |
1480 | double expectedFullness = rce->expectedVbv / m_bufferSize; | |
1481 | double qmax = q * (2 - expectedFullness); | |
1482 | double sizeConstraint = 1 + expectedFullness; | |
1483 | qmax = X265_MAX(qmax, rce->newQScale); | |
1484 | if (expectedFullness < .05) | |
1485 | qmax = MAX_MAX_QPSCALE; | |
1486 | qmax = X265_MIN(qmax, MAX_MAX_QPSCALE); | |
1487 | while (((expectedVbv < rce->expectedVbv/sizeConstraint) && (q < qmax)) || | |
1488 | ((expectedVbv < 0) && (q < MAX_MAX_QPSCALE))) | |
1489 | { | |
1490 | q *= 1.05; | |
1491 | expectedSize = qScale2bits(rce, q); | |
1492 | expectedVbv = m_bufferFill + m_bufferRate - expectedSize; | |
1493 | } | |
1494 | } | |
1495 | q = Clip3(MIN_QPSCALE, MAX_MAX_QPSCALE, q); | |
1496 | } | |
1497 | else | |
1498 | { | |
1499 | /* 1pass ABR */ | |
1500 | ||
1501 | /* Calculate the quantizer which would have produced the desired | |
1502 | * average bitrate if it had been applied to all frames so far. | |
1503 | * Then modulate that quant based on the current frame's complexity | |
1504 | * relative to the average complexity so far (using the 2pass RCEQ). | |
1505 | * Then bias the quant up or down if total size so far was far from | |
1506 | * the target. | |
1507 | * Result: Depending on the value of rate_tolerance, there is a | |
1508 | * tradeoff between quality and bitrate precision. But at large | |
1509 | * tolerances, the bit distribution approaches that of 2pass. */ | |
1510 | ||
1511 | double wantedBits, overflow = 1; | |
1512 | ||
1513 | m_shortTermCplxSum *= 0.5; | |
1514 | m_shortTermCplxCount *= 0.5; | |
1515 | m_shortTermCplxSum += m_currentSatd / (CLIP_DURATION(m_frameDuration) / BASE_FRAME_DURATION); | |
1516 | m_shortTermCplxCount++; | |
1517 | /* coeffBits to be used in 2-pass */ | |
1518 | rce->coeffBits = (int)m_currentSatd; | |
1519 | rce->blurredComplexity = m_shortTermCplxSum / m_shortTermCplxCount; | |
1520 | rce->mvBits = 0; | |
1521 | rce->sliceType = m_sliceType; | |
1522 | ||
1523 | if (m_param->rc.rateControlMode == X265_RC_CRF) | |
1524 | { | |
1525 | q = getQScale(rce, m_rateFactorConstant); | |
1526 | } | |
1527 | else | |
1528 | { | |
1529 | if (!m_param->rc.bStatRead) | |
1530 | checkAndResetABR(rce, false); | |
1531 | q = getQScale(rce, m_wantedBitsWindow / m_cplxrSum); | |
1532 | ||
1533 | /* ABR code can potentially be counterproductive in CBR, so just | |
1534 | * don't bother. Don't run it if the frame complexity is zero | |
1535 | * either. */ | |
1536 | if (!m_isCbr && m_currentSatd) | |
1537 | { | |
1538 | /* use framesDone instead of POC as poc count is not serial with bframes enabled */ | |
1539 | double timeDone = (double)(m_framesDone - m_param->frameNumThreads + 1) * m_frameDuration; | |
1540 | wantedBits = timeDone * m_bitrate; | |
1541 | if (wantedBits > 0 && m_totalBits > 0 && !m_partialResidualFrames) | |
1542 | { | |
1543 | abrBuffer *= X265_MAX(1, sqrt(timeDone)); | |
1544 | overflow = Clip3(.5, 2.0, 1.0 + (m_totalBits - wantedBits) / abrBuffer); | |
1545 | q *= overflow; | |
1546 | } | |
1547 | } | |
1548 | } | |
1549 | ||
1550 | if (m_sliceType == I_SLICE && m_param->keyframeMax > 1 | |
1551 | && m_lastNonBPictType != I_SLICE && !m_isAbrReset) | |
1552 | { | |
1553 | q = x265_qp2qScale(m_accumPQp / m_accumPNorm); | |
1554 | q /= fabs(m_param->rc.ipFactor); | |
1555 | } | |
1556 | else if (m_framesDone > 0) | |
1557 | { | |
1558 | if (m_param->rc.rateControlMode != X265_RC_CRF) | |
1559 | { | |
1560 | double lqmin = 0, lqmax = 0; | |
1561 | lqmin = m_lastQScaleFor[m_sliceType] / m_lstep; | |
1562 | lqmax = m_lastQScaleFor[m_sliceType] * m_lstep; | |
1563 | if (!m_partialResidualFrames) | |
1564 | { | |
1565 | if (overflow > 1.1 && m_framesDone > 3) | |
1566 | lqmax *= m_lstep; | |
1567 | else if (overflow < 0.9) | |
1568 | lqmin /= m_lstep; | |
1569 | } | |
1570 | q = Clip3(lqmin, lqmax, q); | |
1571 | } | |
1572 | } | |
1573 | else if (m_qCompress != 1 && m_param->rc.rateControlMode == X265_RC_CRF) | |
1574 | { | |
1575 | q = x265_qp2qScale(CRF_INIT_QP) / fabs(m_param->rc.ipFactor); | |
1576 | } | |
1577 | else if (m_framesDone == 0 && !m_isVbv) | |
1578 | { | |
1579 | /* for ABR alone, clip the first I frame qp */ | |
1580 | double lqmax = x265_qp2qScale(ABR_INIT_QP_MAX) * m_lstep; | |
1581 | q = X265_MIN(lqmax, q); | |
1582 | } | |
1583 | q = Clip3(MIN_QPSCALE, MAX_MAX_QPSCALE, q); | |
1584 | rce->qpNoVbv = x265_qScale2qp(q); | |
1585 | q = clipQscale(curFrame, rce, q); | |
1586 | } | |
1587 | m_lastQScaleFor[m_sliceType] = q; | |
1588 | if ((m_curSlice->m_poc == 0 || m_lastQScaleFor[P_SLICE] < q) && !(m_2pass && !m_isVbv)) | |
1589 | m_lastQScaleFor[P_SLICE] = q * fabs(m_param->rc.ipFactor); | |
1590 | ||
1591 | if (m_2pass && m_isVbv) | |
1592 | rce->frameSizePlanned = qScale2bits(rce, q); | |
1593 | else | |
1594 | rce->frameSizePlanned = predictSize(&m_pred[m_sliceType], q, (double)m_currentSatd); | |
1595 | ||
1596 | /* Always use up the whole VBV in this case. */ | |
1597 | if (m_singleFrameVbv) | |
1598 | rce->frameSizePlanned = m_bufferRate; | |
1599 | /* Limit planned size by MinCR */ | |
1600 | if (m_isVbv) | |
1601 | rce->frameSizePlanned = X265_MIN(rce->frameSizePlanned, rce->frameSizeMaximum); | |
1602 | rce->frameSizeEstimated = rce->frameSizePlanned; | |
1603 | rce->newQScale = q; | |
1604 | return q; | |
1605 | } | |
1606 | } | |
1607 | ||
1608 | void RateControl::rateControlUpdateStats(RateControlEntry* rce) | |
1609 | { | |
1610 | if (!m_param->rc.bStatWrite && !m_param->rc.bStatRead) | |
1611 | { | |
1612 | if (rce->sliceType == I_SLICE) | |
1613 | { | |
1614 | /* previous I still had a residual; roll it into the new loan */ | |
1615 | if (m_partialResidualFrames) | |
1616 | rce->rowTotalBits += m_partialResidualCost * m_partialResidualFrames; | |
1617 | ||
1618 | m_partialResidualFrames = X265_MIN(s_amortizeFrames, m_param->keyframeMax); | |
1619 | m_partialResidualCost = (int)((rce->rowTotalBits * s_amortizeFraction) /m_partialResidualFrames); | |
1620 | rce->rowTotalBits -= m_partialResidualCost * m_partialResidualFrames; | |
1621 | } | |
1622 | else if (m_partialResidualFrames) | |
1623 | { | |
1624 | rce->rowTotalBits += m_partialResidualCost; | |
1625 | m_partialResidualFrames--; | |
1626 | } | |
1627 | } | |
1628 | if (rce->sliceType != B_SLICE) | |
1629 | rce->rowCplxrSum = rce->rowTotalBits * x265_qp2qScale(rce->qpaRc) / rce->qRceq; | |
1630 | else | |
1631 | rce->rowCplxrSum = rce->rowTotalBits * x265_qp2qScale(rce->qpaRc) / (rce->qRceq * fabs(m_param->rc.pbFactor)); | |
1632 | ||
1633 | m_cplxrSum += rce->rowCplxrSum; | |
1634 | m_totalBits += rce->rowTotalBits; | |
1635 | ||
1636 | /* do not allow the next frame to enter rateControlStart() until this | |
1637 | * frame has updated its mid-frame statistics */ | |
1638 | m_startEndOrder.incr(); | |
1639 | ||
1640 | if (rce->encodeOrder < m_param->frameNumThreads - 1) | |
1641 | m_startEndOrder.incr(); // faked rateControlEnd calls for negative frames | |
1642 | } | |
1643 | ||
1644 | void RateControl::checkAndResetABR(RateControlEntry* rce, bool isFrameDone) | |
1645 | { | |
1646 | double abrBuffer = 2 * m_param->rc.rateTolerance * m_bitrate; | |
1647 | ||
1648 | // Check if current Slice is a scene cut that follows low detailed/blank frames | |
1649 | if (rce->lastSatd > 4 * rce->movingAvgSum) | |
1650 | { | |
1651 | if (!m_isAbrReset && rce->movingAvgSum > 0) | |
1652 | { | |
1653 | int64_t shrtTermWantedBits = (int64_t) (X265_MIN(m_sliderPos, s_slidingWindowFrames) * m_bitrate * m_frameDuration); | |
1654 | int64_t shrtTermTotalBitsSum = 0; | |
1655 | // Reset ABR if prev frames are blank to prevent further sudden overflows/ high bit rate spikes. | |
1656 | for (int i = 0; i < s_slidingWindowFrames ; i++) | |
1657 | shrtTermTotalBitsSum += m_encodedBitsWindow[i]; | |
1658 | double underflow = (shrtTermTotalBitsSum - shrtTermWantedBits) / abrBuffer; | |
1659 | const double epsilon = 0.0001f; | |
1660 | if (underflow < epsilon && !isFrameDone) | |
1661 | { | |
1662 | init(m_curSlice->m_sps); | |
1663 | m_shortTermCplxSum = rce->lastSatd / (CLIP_DURATION(m_frameDuration) / BASE_FRAME_DURATION); | |
1664 | m_shortTermCplxCount = 1; | |
1665 | m_isAbrReset = true; | |
1666 | m_lastAbrResetPoc = rce->poc; | |
1667 | } | |
1668 | } | |
1669 | else | |
1670 | { | |
1671 | // Clear flag to reset ABR and continue as usual. | |
1672 | m_isAbrReset = false; | |
1673 | } | |
1674 | } | |
1675 | } | |
1676 | ||
1677 | void RateControl::hrdFullness(SEIBufferingPeriod *seiBP) | |
1678 | { | |
1679 | const VUI* vui = &m_curSlice->m_sps->vuiParameters; | |
1680 | const HRDInfo* hrd = &vui->hrdParameters; | |
1681 | int num = 90000; | |
1682 | int denom = hrd->bitRateValue << (hrd->bitRateScale + BR_SHIFT); | |
1683 | reduceFraction(&num, &denom); | |
1684 | int64_t cpbState = (int64_t)m_bufferFillFinal; | |
1685 | int64_t cpbSize = (int64_t)hrd->cpbSizeValue << (hrd->cpbSizeScale + CPB_SHIFT); | |
1686 | ||
1687 | if (cpbState < 0 || cpbState > cpbSize) | |
1688 | { | |
1689 | x265_log(m_param, X265_LOG_WARNING, "CPB %s: %.0lf bits in a %.0lf-bit buffer\n", | |
1690 | cpbState < 0 ? "underflow" : "overflow", (float)cpbState/denom, (float)cpbSize/denom); | |
1691 | } | |
1692 | ||
1693 | seiBP->m_initialCpbRemovalDelay = (uint32_t)(num * cpbState + denom) / denom; | |
1694 | seiBP->m_initialCpbRemovalDelayOffset = (uint32_t)(num * cpbSize + denom) / denom - seiBP->m_initialCpbRemovalDelay; | |
1695 | } | |
1696 | ||
1697 | void RateControl::updateVbvPlan(Encoder* enc) | |
1698 | { | |
1699 | m_bufferFill = m_bufferFillFinal; | |
1700 | enc->updateVbvPlan(this); | |
1701 | } | |
1702 | ||
1703 | double RateControl::predictSize(Predictor *p, double q, double var) | |
1704 | { | |
1705 | return (p->coeff * var + p->offset) / (q * p->count); | |
1706 | } | |
1707 | ||
1708 | double RateControl::clipQscale(Frame* curFrame, RateControlEntry* rce, double q) | |
1709 | { | |
1710 | // B-frames are not directly subject to VBV, | |
1711 | // since they are controlled by referenced P-frames' QPs. | |
1712 | double q0 = q; | |
1713 | if (m_isVbv && m_currentSatd > 0 && curFrame) | |
1714 | { | |
1715 | if (m_param->lookaheadDepth || m_param->rc.cuTree || | |
1716 | m_param->scenecutThreshold || | |
1717 | (m_param->bFrameAdaptive && m_param->bframes)) | |
1718 | { | |
1719 | /* Lookahead VBV: If lookahead is done, raise the quantizer as necessary | |
1720 | * such that no frames in the lookahead overflow and such that the buffer | |
1721 | * is in a reasonable state by the end of the lookahead. */ | |
1722 | int loopTerminate = 0; | |
1723 | /* Avoid an infinite loop. */ | |
1724 | for (int iterations = 0; iterations < 1000 && loopTerminate != 3; iterations++) | |
1725 | { | |
1726 | double frameQ[3]; | |
1727 | double curBits; | |
1728 | if (m_sliceType == B_SLICE) | |
1729 | curBits = predictSize(&m_predBfromP, q, (double)m_currentSatd); | |
1730 | else | |
1731 | curBits = predictSize(&m_pred[m_sliceType], q, (double)m_currentSatd); | |
1732 | double bufferFillCur = m_bufferFill - curBits; | |
1733 | double targetFill; | |
1734 | double totalDuration = 0; | |
1735 | frameQ[P_SLICE] = m_sliceType == I_SLICE ? q * m_param->rc.ipFactor : (m_sliceType == B_SLICE ? q / m_param->rc.pbFactor : q); | |
1736 | frameQ[B_SLICE] = frameQ[P_SLICE] * m_param->rc.pbFactor; | |
1737 | frameQ[I_SLICE] = frameQ[P_SLICE] / m_param->rc.ipFactor; | |
1738 | /* Loop over the planned future frames. */ | |
1739 | for (int j = 0; bufferFillCur >= 0; j++) | |
1740 | { | |
1741 | int type = curFrame->m_lowres.plannedType[j]; | |
1742 | if (type == X265_TYPE_AUTO) | |
1743 | break; | |
1744 | totalDuration += m_frameDuration; | |
1745 | double wantedFrameSize = m_vbvMaxRate * m_frameDuration; | |
1746 | if (bufferFillCur + wantedFrameSize <= m_bufferSize) | |
1747 | bufferFillCur += wantedFrameSize; | |
1748 | int64_t satd = curFrame->m_lowres.plannedSatd[j] >> (X265_DEPTH - 8); | |
1749 | type = IS_X265_TYPE_I(type) ? I_SLICE : IS_X265_TYPE_B(type) ? B_SLICE : P_SLICE; | |
1750 | curBits = predictSize(&m_pred[type], frameQ[type], (double)satd); | |
1751 | bufferFillCur -= curBits; | |
1752 | } | |
1753 | ||
1754 | /* Try to get the buffer at least 50% filled, but don't set an impossible goal. */ | |
1755 | targetFill = X265_MIN(m_bufferFill + totalDuration * m_vbvMaxRate * 0.5, m_bufferSize * 0.5); | |
1756 | if (bufferFillCur < targetFill) | |
1757 | { | |
1758 | q *= 1.01; | |
1759 | loopTerminate |= 1; | |
1760 | continue; | |
1761 | } | |
1762 | /* Try to get the buffer no more than 80% filled, but don't set an impossible goal. */ | |
1763 | targetFill = Clip3(m_bufferSize * 0.8, m_bufferSize, m_bufferFill - totalDuration * m_vbvMaxRate * 0.5); | |
1764 | if (m_isCbr && bufferFillCur > targetFill) | |
1765 | { | |
1766 | q /= 1.01; | |
1767 | loopTerminate |= 2; | |
1768 | continue; | |
1769 | } | |
1770 | break; | |
1771 | } | |
1772 | q = X265_MAX(q0 / 2, q); | |
1773 | } | |
1774 | else | |
1775 | { | |
1776 | /* Fallback to old purely-reactive algorithm: no lookahead. */ | |
1777 | if ((m_sliceType == P_SLICE || m_sliceType == B_SLICE || | |
1778 | (m_sliceType == I_SLICE && m_lastNonBPictType == I_SLICE)) && | |
1779 | m_bufferFill / m_bufferSize < 0.5) | |
1780 | { | |
1781 | q /= Clip3(0.5, 1.0, 2.0 * m_bufferFill / m_bufferSize); | |
1782 | } | |
1783 | // Now a hard threshold to make sure the frame fits in VBV. | |
1784 | // This one is mostly for I-frames. | |
1785 | double bits = predictSize(&m_pred[m_sliceType], q, (double)m_currentSatd); | |
1786 | ||
1787 | // For small VBVs, allow the frame to use up the entire VBV. | |
1788 | double maxFillFactor; | |
1789 | maxFillFactor = m_bufferSize >= 5 * m_bufferRate ? 2 : 1; | |
1790 | // For single-frame VBVs, request that the frame use up the entire VBV. | |
1791 | double minFillFactor = m_singleFrameVbv ? 1 : 2; | |
1792 | ||
1793 | for (int iterations = 0; iterations < 10; iterations++) | |
1794 | { | |
1795 | double qf = 1.0; | |
1796 | if (bits > m_bufferFill / maxFillFactor) | |
1797 | qf = Clip3(0.2, 1.0, m_bufferFill / (maxFillFactor * bits)); | |
1798 | q /= qf; | |
1799 | bits *= qf; | |
1800 | if (bits < m_bufferRate / minFillFactor) | |
1801 | q *= bits * minFillFactor / m_bufferRate; | |
1802 | bits = predictSize(&m_pred[m_sliceType], q, (double)m_currentSatd); | |
1803 | } | |
1804 | ||
1805 | q = X265_MAX(q0, q); | |
1806 | } | |
1807 | ||
1808 | /* Apply MinCR restrictions */ | |
1809 | double pbits = predictSize(&m_pred[m_sliceType], q, (double)m_currentSatd); | |
1810 | if (pbits > rce->frameSizeMaximum) | |
1811 | q *= pbits / rce->frameSizeMaximum; | |
1812 | ||
1813 | // Check B-frame complexity, and use up any bits that would | |
1814 | // overflow before the next P-frame. | |
1815 | if (m_leadingBframes <= 5 && m_sliceType == P_SLICE && !m_singleFrameVbv) | |
1816 | { | |
1817 | int nb = m_leadingBframes; | |
1818 | double bits = predictSize(&m_pred[m_sliceType], q, (double)m_currentSatd); | |
1819 | double bbits = predictSize(&m_predBfromP, q * m_param->rc.pbFactor, (double)m_currentSatd); | |
1820 | double space; | |
1821 | if (bbits > m_bufferRate) | |
1822 | nb = 0; | |
1823 | double pbbits = nb * bbits; | |
1824 | ||
1825 | space = m_bufferFill + (1 + nb) * m_bufferRate - m_bufferSize; | |
1826 | if (pbbits < space) | |
1827 | q *= X265_MAX(pbbits / space, bits / (0.5 * m_bufferSize)); | |
1828 | ||
1829 | q = X265_MAX(q0 / 2, q); | |
1830 | } | |
1831 | ||
1832 | if (!m_isCbr || (m_isAbr && m_currentSatd >= rce->movingAvgSum && q <= q0 / 2)) | |
1833 | q = X265_MAX(q0, q); | |
1834 | ||
1835 | if (m_rateFactorMaxIncrement) | |
1836 | { | |
1837 | double qpNoVbv = x265_qScale2qp(q0); | |
1838 | double qmax = X265_MIN(MAX_MAX_QPSCALE,x265_qp2qScale(qpNoVbv + m_rateFactorMaxIncrement)); | |
1839 | return Clip3(MIN_QPSCALE, qmax, q); | |
1840 | } | |
1841 | } | |
1842 | if (m_2pass) | |
1843 | { | |
1844 | double min = log(MIN_QPSCALE); | |
1845 | double max = log(MAX_MAX_QPSCALE); | |
1846 | q = (log(q) - min) / (max - min) - 0.5; | |
1847 | q = 1.0 / (1.0 + exp(-4 * q)); | |
1848 | q = q*(max - min) + min; | |
1849 | return exp(q); | |
1850 | } | |
1851 | return Clip3(MIN_QPSCALE, MAX_MAX_QPSCALE, q); | |
1852 | } | |
1853 | ||
1854 | double RateControl::predictRowsSizeSum(Frame* curFrame, RateControlEntry* rce, double qpVbv, int32_t& encodedBitsSoFar) | |
1855 | { | |
1856 | uint32_t rowSatdCostSoFar = 0, totalSatdBits = 0; | |
1857 | encodedBitsSoFar = 0; | |
1858 | ||
1859 | double qScale = x265_qp2qScale(qpVbv); | |
1860 | FrameData& curEncData = *curFrame->m_encData; | |
1861 | int picType = curEncData.m_slice->m_sliceType; | |
1862 | Frame* refFrame = curEncData.m_slice->m_refPicList[0][0]; | |
1863 | ||
1864 | uint32_t maxRows = curEncData.m_slice->m_sps->numCuInHeight; | |
1865 | uint32_t maxCols = curEncData.m_slice->m_sps->numCuInWidth; | |
1866 | ||
1867 | for (uint32_t row = 0; row < maxRows; row++) | |
1868 | { | |
1869 | encodedBitsSoFar += curEncData.m_rowStat[row].encodedBits; | |
1870 | rowSatdCostSoFar = curEncData.m_rowStat[row].diagSatd; | |
1871 | uint32_t satdCostForPendingCus = curEncData.m_rowStat[row].satdForVbv - rowSatdCostSoFar; | |
1872 | satdCostForPendingCus >>= X265_DEPTH - 8; | |
1873 | if (satdCostForPendingCus > 0) | |
1874 | { | |
1875 | double pred_s = predictSize(rce->rowPred[0], qScale, satdCostForPendingCus); | |
1876 | uint32_t refRowSatdCost = 0, refRowBits = 0, intraCost = 0; | |
1877 | double refQScale = 0; | |
1878 | ||
1879 | if (picType != I_SLICE) | |
1880 | { | |
1881 | FrameData& refEncData = *refFrame->m_encData; | |
1882 | uint32_t endCuAddr = maxCols * (row + 1); | |
1883 | for (uint32_t cuAddr = curEncData.m_rowStat[row].numEncodedCUs + 1; cuAddr < endCuAddr; cuAddr++) | |
1884 | { | |
1885 | refRowSatdCost += refEncData.m_cuStat[cuAddr].vbvCost; | |
1886 | refRowBits += refEncData.m_cuStat[cuAddr].totalBits; | |
1887 | intraCost += curEncData.m_cuStat[cuAddr].intraVbvCost; | |
1888 | } | |
1889 | ||
1890 | refRowSatdCost >>= X265_DEPTH - 8; | |
1891 | refQScale = refEncData.m_rowStat[row].diagQpScale; | |
1892 | } | |
1893 | ||
1894 | if (picType == I_SLICE || qScale >= refQScale) | |
1895 | { | |
1896 | if (picType == P_SLICE | |
1897 | && !refFrame | |
1898 | && refFrame->m_encData->m_slice->m_sliceType == picType | |
1899 | && refQScale > 0 | |
1900 | && refRowSatdCost > 0) | |
1901 | { | |
1902 | if (abs(int32_t(refRowSatdCost - satdCostForPendingCus)) < (int32_t)satdCostForPendingCus / 2) | |
1903 | { | |
1904 | double predTotal = refRowBits * satdCostForPendingCus / refRowSatdCost * refQScale / qScale; | |
1905 | totalSatdBits += int32_t((pred_s + predTotal) * 0.5); | |
1906 | continue; | |
1907 | } | |
1908 | } | |
1909 | totalSatdBits += int32_t(pred_s); | |
1910 | } | |
1911 | else | |
1912 | { | |
1913 | /* Our QP is lower than the reference! */ | |
1914 | double pred_intra = predictSize(rce->rowPred[1], qScale, intraCost); | |
1915 | /* Sum: better to overestimate than underestimate by using only one of the two predictors. */ | |
1916 | totalSatdBits += int32_t(pred_intra + pred_s); | |
1917 | } | |
1918 | } | |
1919 | } | |
1920 | ||
1921 | return totalSatdBits + encodedBitsSoFar; | |
1922 | } | |
1923 | ||
1924 | int RateControl::rowDiagonalVbvRateControl(Frame* curFrame, uint32_t row, RateControlEntry* rce, double& qpVbv) | |
1925 | { | |
1926 | FrameData& curEncData = *curFrame->m_encData; | |
1927 | double qScaleVbv = x265_qp2qScale(qpVbv); | |
1928 | uint64_t rowSatdCost = curEncData.m_rowStat[row].diagSatd; | |
1929 | double encodedBits = curEncData.m_rowStat[row].encodedBits; | |
1930 | ||
1931 | if (row == 1) | |
1932 | { | |
1933 | rowSatdCost += curEncData.m_rowStat[0].diagSatd; | |
1934 | encodedBits += curEncData.m_rowStat[0].encodedBits; | |
1935 | } | |
1936 | rowSatdCost >>= X265_DEPTH - 8; | |
1937 | updatePredictor(rce->rowPred[0], qScaleVbv, (double)rowSatdCost, encodedBits); | |
1938 | if (curEncData.m_slice->m_sliceType == P_SLICE) | |
1939 | { | |
1940 | Frame* refFrame = curEncData.m_slice->m_refPicList[0][0]; | |
1941 | if (qpVbv < refFrame->m_encData->m_rowStat[row].diagQp) | |
1942 | { | |
1943 | uint64_t intraRowSatdCost = curEncData.m_rowStat[row].diagIntraSatd; | |
1944 | if (row == 1) | |
1945 | intraRowSatdCost += curEncData.m_rowStat[0].diagIntraSatd; | |
1946 | ||
1947 | updatePredictor(rce->rowPred[1], qScaleVbv, (double)intraRowSatdCost, encodedBits); | |
1948 | } | |
1949 | } | |
1950 | ||
1951 | int canReencodeRow = 1; | |
1952 | /* tweak quality based on difference from predicted size */ | |
1953 | double prevRowQp = qpVbv; | |
1954 | double qpAbsoluteMax = QP_MAX_MAX; | |
1955 | double qpAbsoluteMin = QP_MIN; | |
1956 | if (m_rateFactorMaxIncrement) | |
1957 | qpAbsoluteMax = X265_MIN(qpAbsoluteMax, rce->qpNoVbv + m_rateFactorMaxIncrement); | |
1958 | ||
1959 | if (m_rateFactorMaxDecrement) | |
1960 | qpAbsoluteMin = X265_MAX(qpAbsoluteMin, rce->qpNoVbv - m_rateFactorMaxDecrement); | |
1961 | ||
1962 | double qpMax = X265_MIN(prevRowQp + m_param->rc.qpStep, qpAbsoluteMax); | |
1963 | double qpMin = X265_MAX(prevRowQp - m_param->rc.qpStep, qpAbsoluteMin); | |
1964 | double stepSize = 0.5; | |
1965 | double bufferLeftPlanned = rce->bufferFill - rce->frameSizePlanned; | |
1966 | ||
1967 | const SPS& sps = *curEncData.m_slice->m_sps; | |
1968 | double maxFrameError = X265_MAX(0.05, 1.0 / sps.numCuInHeight); | |
1969 | ||
1970 | if (row < sps.numCuInHeight - 1) | |
1971 | { | |
1972 | /* B-frames shouldn't use lower QP than their reference frames. */ | |
1973 | if (rce->sliceType == B_SLICE) | |
1974 | { | |
1975 | Frame* refSlice1 = curEncData.m_slice->m_refPicList[0][0]; | |
1976 | Frame* refSlice2 = curEncData.m_slice->m_refPicList[1][0]; | |
1977 | qpMin = X265_MAX(qpMin, X265_MAX(refSlice1->m_encData->m_rowStat[row].diagQp, refSlice2->m_encData->m_rowStat[row].diagQp)); | |
1978 | qpVbv = X265_MAX(qpVbv, qpMin); | |
1979 | } | |
1980 | /* More threads means we have to be more cautious in letting ratecontrol use up extra bits. */ | |
1981 | double rcTol = bufferLeftPlanned / m_param->frameNumThreads * m_param->rc.rateTolerance; | |
1982 | int32_t encodedBitsSoFar = 0; | |
1983 | double accFrameBits = predictRowsSizeSum(curFrame, rce, qpVbv, encodedBitsSoFar); | |
1984 | ||
1985 | /* * Don't increase the row QPs until a sufficent amount of the bits of | |
1986 | * the frame have been processed, in case a flat area at the top of the | |
1987 | * frame was measured inaccurately. */ | |
1988 | if (encodedBitsSoFar < 0.05f * rce->frameSizePlanned) | |
1989 | qpMax = qpAbsoluteMax = prevRowQp; | |
1990 | ||
1991 | if (rce->sliceType != I_SLICE) | |
1992 | rcTol *= 0.5; | |
1993 | ||
1994 | if (!m_isCbr) | |
1995 | qpMin = X265_MAX(qpMin, rce->qpNoVbv); | |
1996 | ||
1997 | while (qpVbv < qpMax | |
1998 | && ((accFrameBits > rce->frameSizePlanned + rcTol) || | |
1999 | (rce->bufferFill - accFrameBits < bufferLeftPlanned * 0.5) || | |
2000 | (accFrameBits > rce->frameSizePlanned && qpVbv < rce->qpNoVbv))) | |
2001 | { | |
2002 | qpVbv += stepSize; | |
2003 | accFrameBits = predictRowsSizeSum(curFrame, rce, qpVbv, encodedBitsSoFar); | |
2004 | } | |
2005 | ||
2006 | while (qpVbv > qpMin | |
2007 | && (qpVbv > curEncData.m_rowStat[0].diagQp || m_singleFrameVbv) | |
2008 | && ((accFrameBits < rce->frameSizePlanned * 0.8f && qpVbv <= prevRowQp) | |
2009 | || accFrameBits < (rce->bufferFill - m_bufferSize + m_bufferRate) * 1.1)) | |
2010 | { | |
2011 | qpVbv -= stepSize; | |
2012 | accFrameBits = predictRowsSizeSum(curFrame, rce, qpVbv, encodedBitsSoFar); | |
2013 | } | |
2014 | ||
2015 | /* avoid VBV underflow or MinCr violation */ | |
2016 | while ((qpVbv < qpAbsoluteMax) | |
2017 | && ((rce->bufferFill - accFrameBits < m_bufferRate * maxFrameError) || | |
2018 | (rce->frameSizeMaximum - accFrameBits < rce->frameSizeMaximum * maxFrameError))) | |
2019 | { | |
2020 | qpVbv += stepSize; | |
2021 | accFrameBits = predictRowsSizeSum(curFrame, rce, qpVbv, encodedBitsSoFar); | |
2022 | } | |
2023 | ||
2024 | rce->frameSizeEstimated = accFrameBits; | |
2025 | ||
2026 | /* If the current row was large enough to cause a large QP jump, try re-encoding it. */ | |
2027 | if (qpVbv > qpMax && prevRowQp < qpMax && canReencodeRow) | |
2028 | { | |
2029 | /* Bump QP to halfway in between... close enough. */ | |
2030 | qpVbv = Clip3(prevRowQp + 1.0f, qpMax, (prevRowQp + qpVbv) * 0.5); | |
2031 | return -1; | |
2032 | } | |
2033 | ||
2034 | if (m_param->rc.rfConstantMin) | |
2035 | { | |
2036 | if (qpVbv < qpMin && prevRowQp > qpMin && canReencodeRow) | |
2037 | { | |
2038 | qpVbv = Clip3(qpMin, prevRowQp, (prevRowQp + qpVbv) * 0.5); | |
2039 | return -1; | |
2040 | } | |
2041 | } | |
2042 | } | |
2043 | else | |
2044 | { | |
2045 | int32_t encodedBitsSoFar = 0; | |
2046 | rce->frameSizeEstimated = predictRowsSizeSum(curFrame, rce, qpVbv, encodedBitsSoFar); | |
2047 | ||
2048 | /* Last-ditch attempt: if the last row of the frame underflowed the VBV, | |
2049 | * try again. */ | |
2050 | if ((rce->frameSizeEstimated > (rce->bufferFill - m_bufferRate * maxFrameError) && | |
2051 | qpVbv < qpMax && canReencodeRow)) | |
2052 | { | |
2053 | qpVbv = qpMax; | |
2054 | return -1; | |
2055 | } | |
2056 | } | |
2057 | return 0; | |
2058 | } | |
2059 | ||
2060 | /* modify the bitrate curve from pass1 for one frame */ | |
2061 | double RateControl::getQScale(RateControlEntry *rce, double rateFactor) | |
2062 | { | |
2063 | double q; | |
2064 | ||
2065 | if (m_param->rc.cuTree) | |
2066 | { | |
2067 | // Scale and units are obtained from rateNum and rateDenom for videos with fixed frame rates. | |
2068 | double timescale = (double)m_param->fpsDenom / (2 * m_param->fpsNum); | |
2069 | q = pow(BASE_FRAME_DURATION / CLIP_DURATION(2 * timescale), 1 - m_param->rc.qCompress); | |
2070 | } | |
2071 | else | |
2072 | q = pow(rce->blurredComplexity, 1 - m_param->rc.qCompress); | |
2073 | // avoid NaN's in the Rceq | |
2074 | if (rce->coeffBits + rce->mvBits == 0) | |
2075 | q = m_lastQScaleFor[rce->sliceType]; | |
2076 | else | |
2077 | { | |
2078 | m_lastRceq = q; | |
2079 | q /= rateFactor; | |
2080 | } | |
2081 | return q; | |
2082 | } | |
2083 | ||
2084 | void RateControl::updatePredictor(Predictor *p, double q, double var, double bits) | |
2085 | { | |
2086 | if (var < 10) | |
2087 | return; | |
2088 | const double range = 1.5; | |
2089 | double old_coeff = p->coeff / p->count; | |
2090 | double new_coeff = bits * q / var; | |
2091 | double new_coeff_clipped = Clip3(old_coeff / range, old_coeff * range, new_coeff); | |
2092 | double new_offset = bits * q - new_coeff_clipped * var; | |
2093 | if (new_offset >= 0) | |
2094 | new_coeff = new_coeff_clipped; | |
2095 | else | |
2096 | new_offset = 0; | |
2097 | p->count *= p->decay; | |
2098 | p->coeff *= p->decay; | |
2099 | p->offset *= p->decay; | |
2100 | p->count++; | |
2101 | p->coeff += new_coeff; | |
2102 | p->offset += new_offset; | |
2103 | } | |
2104 | ||
2105 | void RateControl::updateVbv(int64_t bits, RateControlEntry* rce) | |
2106 | { | |
2107 | if (rce->lastSatd >= m_ncu) | |
2108 | updatePredictor(&m_pred[rce->sliceType], x265_qp2qScale(rce->qpaRc), (double)rce->lastSatd, (double)bits); | |
2109 | if (!m_isVbv) | |
2110 | return; | |
2111 | ||
2112 | m_bufferFillFinal -= bits; | |
2113 | ||
2114 | if (m_bufferFillFinal < 0) | |
2115 | x265_log(m_param, X265_LOG_WARNING, "poc:%d, VBV underflow (%.0f bits)\n", rce->poc, m_bufferFillFinal); | |
2116 | ||
2117 | m_bufferFillFinal = X265_MAX(m_bufferFillFinal, 0); | |
2118 | m_bufferFillFinal += m_bufferRate; | |
2119 | m_bufferFillFinal = X265_MIN(m_bufferFillFinal, m_bufferSize); | |
2120 | } | |
2121 | ||
2122 | /* After encoding one frame, update rate control state */ | |
2123 | int RateControl::rateControlEnd(Frame* curFrame, int64_t bits, RateControlEntry* rce, FrameStats* stats) | |
2124 | { | |
2125 | int orderValue = m_startEndOrder.get(); | |
2126 | int endOrdinal = (rce->encodeOrder + m_param->frameNumThreads) * 2 - 1; | |
2127 | while (orderValue < endOrdinal && !m_bTerminated) | |
2128 | { | |
2129 | /* no more frames are being encoded, so fake the start event if we would | |
2130 | * have blocked on it. Note that this does not enforce rateControlEnd() | |
2131 | * ordering during flush, but this has no impact on the outputs */ | |
2132 | if (m_finalFrameCount && orderValue >= 2 * m_finalFrameCount) | |
2133 | break; | |
2134 | orderValue = m_startEndOrder.waitForChange(orderValue); | |
2135 | } | |
2136 | ||
2137 | FrameData& curEncData = *curFrame->m_encData; | |
2138 | int64_t actualBits = bits; | |
2139 | Slice *slice = curEncData.m_slice; | |
2140 | if (m_isAbr) | |
2141 | { | |
2142 | if (m_param->rc.rateControlMode == X265_RC_ABR && !m_param->rc.bStatRead) | |
2143 | checkAndResetABR(rce, true); | |
2144 | ||
2145 | if (m_param->rc.rateControlMode == X265_RC_CRF) | |
2146 | { | |
2147 | if (int(curEncData.m_avgQpRc + 0.5) == slice->m_sliceQp) | |
2148 | curEncData.m_rateFactor = m_rateFactorConstant; | |
2149 | else | |
2150 | { | |
2151 | /* If vbv changed the frame QP recalculate the rate-factor */ | |
2152 | double baseCplx = m_ncu * (m_param->bframes ? 120 : 80); | |
2153 | double mbtree_offset = m_param->rc.cuTree ? (1.0 - m_param->rc.qCompress) * 13.5 : 0; | |
2154 | curEncData.m_rateFactor = pow(baseCplx, 1 - m_qCompress) / | |
2155 | x265_qp2qScale(int(curEncData.m_avgQpRc + 0.5) + mbtree_offset); | |
2156 | } | |
2157 | } | |
2158 | } | |
2159 | ||
2160 | if (m_param->rc.aqMode || m_isVbv) | |
2161 | { | |
2162 | if (m_isVbv) | |
2163 | { | |
2164 | for (uint32_t i = 0; i < slice->m_sps->numCuInHeight; i++) | |
2165 | curEncData.m_avgQpRc += curEncData.m_rowStat[i].sumQpRc; | |
2166 | ||
2167 | curEncData.m_avgQpRc /= slice->m_sps->numCUsInFrame; | |
2168 | rce->qpaRc = curEncData.m_avgQpRc; | |
2169 | ||
2170 | // copy avg RC qp to m_avgQpAq. To print out the correct qp when aq/cutree is disabled. | |
2171 | curEncData.m_avgQpAq = curEncData.m_avgQpRc; | |
2172 | } | |
2173 | ||
2174 | if (m_param->rc.aqMode) | |
2175 | { | |
2176 | for (uint32_t i = 0; i < slice->m_sps->numCuInHeight; i++) | |
2177 | curEncData.m_avgQpAq += curEncData.m_rowStat[i].sumQpAq; | |
2178 | ||
2179 | curEncData.m_avgQpAq /= slice->m_sps->numCUsInFrame; | |
2180 | } | |
2181 | } | |
2182 | ||
2183 | // Write frame stats into the stats file if 2 pass is enabled. | |
2184 | if (m_param->rc.bStatWrite) | |
2185 | { | |
2186 | char cType = rce->sliceType == I_SLICE ? (rce->poc > 0 && m_param->bOpenGOP ? 'i' : 'I') | |
2187 | : rce->sliceType == P_SLICE ? 'P' | |
2188 | : IS_REFERENCED(curFrame) ? 'B' : 'b'; | |
2189 | if (fprintf(m_statFileOut, | |
2190 | "in:%d out:%d type:%c q:%.2f q-aq:%.2f tex:%d mv:%d misc:%d icu:%.2f pcu:%.2f scu:%.2f ;\n", | |
2191 | rce->poc, rce->encodeOrder, | |
2192 | cType, curEncData.m_avgQpRc, curEncData.m_avgQpAq, | |
2193 | stats->coeffBits, | |
2194 | stats->mvBits, | |
2195 | stats->miscBits, | |
2196 | stats->percentIntra * m_ncu, | |
2197 | stats->percentInter * m_ncu, | |
2198 | stats->percentSkip * m_ncu) < 0) | |
2199 | goto writeFailure; | |
2200 | /* Don't re-write the data in multi-pass mode. */ | |
2201 | if (m_param->rc.cuTree && IS_REFERENCED(curFrame) && !m_param->rc.bStatRead) | |
2202 | { | |
2203 | uint8_t sliceType = (uint8_t)rce->sliceType; | |
2204 | for (int i = 0; i < m_ncu; i++) | |
2205 | m_cuTreeStats.qpBuffer[0][i] = (uint16_t)(curFrame->m_lowres.qpCuTreeOffset[i] * 256.0); | |
2206 | if (fwrite(&sliceType, 1, 1, m_cutreeStatFileOut) < 1) | |
2207 | goto writeFailure; | |
2208 | if (fwrite(m_cuTreeStats.qpBuffer[0], sizeof(uint16_t), m_ncu, m_cutreeStatFileOut) < (size_t)m_ncu) | |
2209 | goto writeFailure; | |
2210 | } | |
2211 | } | |
2212 | if (m_isAbr && !m_isAbrReset) | |
2213 | { | |
2214 | /* amortize part of each I slice over the next several frames, up to | |
2215 | * keyint-max, to avoid over-compensating for the large I slice cost */ | |
2216 | if (!m_param->rc.bStatWrite && !m_param->rc.bStatRead) | |
2217 | { | |
2218 | if (rce->sliceType == I_SLICE) | |
2219 | { | |
2220 | /* previous I still had a residual; roll it into the new loan */ | |
2221 | if (m_residualFrames) | |
2222 | bits += m_residualCost * m_residualFrames; | |
2223 | m_residualFrames = X265_MIN(s_amortizeFrames, m_param->keyframeMax); | |
2224 | m_residualCost = (int)((bits * s_amortizeFraction) / m_residualFrames); | |
2225 | bits -= m_residualCost * m_residualFrames; | |
2226 | } | |
2227 | else if (m_residualFrames) | |
2228 | { | |
2229 | bits += m_residualCost; | |
2230 | m_residualFrames--; | |
2231 | } | |
2232 | } | |
2233 | if (rce->sliceType != B_SLICE) | |
2234 | { | |
2235 | /* The factor 1.5 is to tune up the actual bits, otherwise the cplxrSum is scaled too low | |
2236 | * to improve short term compensation for next frame. */ | |
2237 | m_cplxrSum += (bits * x265_qp2qScale(rce->qpaRc) / rce->qRceq) - (rce->rowCplxrSum); | |
2238 | } | |
2239 | else | |
2240 | { | |
2241 | /* Depends on the fact that B-frame's QP is an offset from the following P-frame's. | |
2242 | * Not perfectly accurate with B-refs, but good enough. */ | |
2243 | m_cplxrSum += (bits * x265_qp2qScale(rce->qpaRc) / (rce->qRceq * fabs(m_param->rc.pbFactor))) - (rce->rowCplxrSum); | |
2244 | } | |
2245 | m_wantedBitsWindow += m_frameDuration * m_bitrate; | |
2246 | m_totalBits += bits - rce->rowTotalBits; | |
2247 | int pos = m_sliderPos - m_param->frameNumThreads; | |
2248 | if (pos >= 0) | |
2249 | m_encodedBitsWindow[pos % s_slidingWindowFrames] = actualBits; | |
2250 | } | |
2251 | ||
2252 | if (m_2pass) | |
2253 | { | |
2254 | m_expectedBitsSum += qScale2bits(rce, x265_qp2qScale(rce->newQp)); | |
2255 | m_totalBits += bits - rce->rowTotalBits; | |
2256 | } | |
2257 | ||
2258 | if (m_isVbv) | |
2259 | { | |
2260 | if (rce->sliceType == B_SLICE) | |
2261 | { | |
2262 | m_bframeBits += actualBits; | |
2263 | if (rce->bLastMiniGopBFrame) | |
2264 | { | |
2265 | if (rce->bframes != 0) | |
2266 | updatePredictor(&m_predBfromP, x265_qp2qScale(rce->qpaRc), (double)rce->leadingNoBSatd, (double)m_bframeBits / rce->bframes); | |
2267 | m_bframeBits = 0; | |
2268 | } | |
2269 | } | |
2270 | updateVbv(actualBits, rce); | |
2271 | ||
2272 | if (m_param->bEmitHRDSEI) | |
2273 | { | |
2274 | const VUI *vui = &curEncData.m_slice->m_sps->vuiParameters; | |
2275 | const HRDInfo *hrd = &vui->hrdParameters; | |
2276 | const TimingInfo *time = &vui->timingInfo; | |
2277 | if (!curFrame->m_poc) | |
2278 | { | |
2279 | // first access unit initializes the HRD | |
2280 | rce->hrdTiming->cpbInitialAT = 0; | |
2281 | rce->hrdTiming->cpbRemovalTime = m_nominalRemovalTime = (double)m_bufPeriodSEI.m_initialCpbRemovalDelay / 90000; | |
2282 | } | |
2283 | else | |
2284 | { | |
2285 | rce->hrdTiming->cpbRemovalTime = m_nominalRemovalTime + (double)rce->picTimingSEI->m_auCpbRemovalDelay * time->numUnitsInTick / time->timeScale; | |
2286 | double cpbEarliestAT = rce->hrdTiming->cpbRemovalTime - (double)m_bufPeriodSEI.m_initialCpbRemovalDelay / 90000; | |
2287 | if (!curFrame->m_lowres.bKeyframe) | |
2288 | cpbEarliestAT -= (double)m_bufPeriodSEI.m_initialCpbRemovalDelayOffset / 90000; | |
2289 | ||
2290 | rce->hrdTiming->cpbInitialAT = hrd->cbrFlag ? m_prevCpbFinalAT : X265_MAX(m_prevCpbFinalAT, cpbEarliestAT); | |
2291 | } | |
2292 | ||
2293 | uint32_t cpbsizeUnscale = hrd->cpbSizeValue << (hrd->cpbSizeScale + CPB_SHIFT); | |
2294 | rce->hrdTiming->cpbFinalAT = m_prevCpbFinalAT = rce->hrdTiming->cpbInitialAT + actualBits / cpbsizeUnscale; | |
2295 | rce->hrdTiming->dpbOutputTime = (double)rce->picTimingSEI->m_picDpbOutputDelay * time->numUnitsInTick / time->timeScale + rce->hrdTiming->cpbRemovalTime; | |
2296 | } | |
2297 | } | |
2298 | // Allow rateControlStart of next frame only when rateControlEnd of previous frame is over | |
2299 | m_startEndOrder.incr(); | |
2300 | rce->isActive = false; | |
2301 | return 0; | |
2302 | ||
2303 | writeFailure: | |
2304 | x265_log(m_param, X265_LOG_ERROR, "RatecontrolEnd: stats file write failure\n"); | |
2305 | return 1; | |
2306 | } | |
2307 | ||
2308 | #if defined(_MSC_VER) | |
2309 | #pragma warning(disable: 4996) // POSIX function names are just fine, thank you | |
2310 | #endif | |
2311 | ||
2312 | /* called when the encoder is flushing, and thus the final frame count is | |
2313 | * unambiguously known */ | |
2314 | void RateControl::setFinalFrameCount(int count) | |
2315 | { | |
2316 | m_finalFrameCount = count; | |
2317 | /* unblock waiting threads */ | |
2318 | m_startEndOrder.set(m_startEndOrder.get()); | |
2319 | } | |
2320 | ||
2321 | /* called when the encoder is closing, and no more frames will be output. | |
2322 | * all blocked functions must finish so the frame encoder threads can be | |
2323 | * closed */ | |
2324 | void RateControl::terminate() | |
2325 | { | |
2326 | m_bTerminated = true; | |
2327 | /* unblock waiting threads */ | |
2328 | m_startEndOrder.set(m_startEndOrder.get()); | |
2329 | } | |
2330 | ||
2331 | void RateControl::destroy() | |
2332 | { | |
2333 | const char *fileName = m_param->rc.statFileName; | |
2334 | if (!fileName) | |
2335 | fileName = s_defaultStatFileName; | |
2336 | ||
2337 | if (m_statFileOut) | |
2338 | { | |
2339 | fclose(m_statFileOut); | |
2340 | char *tmpFileName = strcatFilename(fileName, ".temp"); | |
2341 | int bError = 1; | |
2342 | if (tmpFileName) | |
2343 | { | |
2344 | unlink(fileName); | |
2345 | bError = rename(tmpFileName, fileName); | |
2346 | } | |
2347 | if (bError) | |
2348 | { | |
2349 | x265_log(m_param, X265_LOG_ERROR, "failed to rename output stats file to \"%s\"\n", | |
2350 | fileName); | |
2351 | } | |
2352 | X265_FREE(tmpFileName); | |
2353 | } | |
2354 | ||
2355 | if (m_cutreeStatFileOut) | |
2356 | { | |
2357 | fclose(m_cutreeStatFileOut); | |
2358 | char *tmpFileName = strcatFilename(fileName, ".cutree.temp"); | |
2359 | char *newFileName = strcatFilename(fileName, ".cutree"); | |
2360 | int bError = 1; | |
2361 | if (tmpFileName && newFileName) | |
2362 | { | |
2363 | unlink(newFileName); | |
2364 | bError = rename(tmpFileName, newFileName); | |
2365 | } | |
2366 | if (bError) | |
2367 | { | |
2368 | x265_log(m_param, X265_LOG_ERROR, "failed to rename cutree output stats file to \"%s\"\n", | |
2369 | newFileName); | |
2370 | } | |
2371 | X265_FREE(tmpFileName); | |
2372 | X265_FREE(newFileName); | |
2373 | } | |
2374 | ||
2375 | if (m_cutreeStatFileIn) | |
2376 | fclose(m_cutreeStatFileIn); | |
2377 | ||
2378 | X265_FREE(m_rce2Pass); | |
2379 | for (int i = 0; i < 2; i++) | |
2380 | X265_FREE(m_cuTreeStats.qpBuffer[i]); | |
2381 | } | |
2382 |