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