1// Copyright 2011 Google Inc. All Rights Reserved. 2// 3// Use of this source code is governed by a BSD-style license 4// that can be found in the COPYING file in the root of the source 5// tree. An additional intellectual property rights grant can be found 6// in the file PATENTS. All contributing project authors may 7// be found in the AUTHORS file in the root of the source tree. 8// ----------------------------------------------------------------------------- 9// 10// frame coding and analysis 11// 12// Author: Skal (pascal.massimino@gmail.com) 13 14#include <string.h> 15#include <math.h> 16 17#include "./cost_enc.h" 18#include "./vp8i_enc.h" 19#include "../dsp/dsp.h" 20#include "../webp/format_constants.h" // RIFF constants 21 22#define SEGMENT_VISU 0 23#define DEBUG_SEARCH 0 // useful to track search convergence 24 25//------------------------------------------------------------------------------ 26// multi-pass convergence 27 28#define HEADER_SIZE_ESTIMATE (RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE + \ 29 VP8_FRAME_HEADER_SIZE) 30#define DQ_LIMIT 0.4 // convergence is considered reached if dq < DQ_LIMIT 31// we allow 2k of extra head-room in PARTITION0 limit. 32#define PARTITION0_SIZE_LIMIT ((VP8_MAX_PARTITION0_SIZE - 2048ULL) << 11) 33 34typedef struct { // struct for organizing convergence in either size or PSNR 35 int is_first; 36 float dq; 37 float q, last_q; 38 double value, last_value; // PSNR or size 39 double target; 40 int do_size_search; 41} PassStats; 42 43static int InitPassStats(const VP8Encoder* const enc, PassStats* const s) { 44 const uint64_t target_size = (uint64_t)enc->config_->target_size; 45 const int do_size_search = (target_size != 0); 46 const float target_PSNR = enc->config_->target_PSNR; 47 48 s->is_first = 1; 49 s->dq = 10.f; 50 s->q = s->last_q = enc->config_->quality; 51 s->target = do_size_search ? (double)target_size 52 : (target_PSNR > 0.) ? target_PSNR 53 : 40.; // default, just in case 54 s->value = s->last_value = 0.; 55 s->do_size_search = do_size_search; 56 return do_size_search; 57} 58 59static float Clamp(float v, float min, float max) { 60 return (v < min) ? min : (v > max) ? max : v; 61} 62 63static float ComputeNextQ(PassStats* const s) { 64 float dq; 65 if (s->is_first) { 66 dq = (s->value > s->target) ? -s->dq : s->dq; 67 s->is_first = 0; 68 } else if (s->value != s->last_value) { 69 const double slope = (s->target - s->value) / (s->last_value - s->value); 70 dq = (float)(slope * (s->last_q - s->q)); 71 } else { 72 dq = 0.; // we're done?! 73 } 74 // Limit variable to avoid large swings. 75 s->dq = Clamp(dq, -30.f, 30.f); 76 s->last_q = s->q; 77 s->last_value = s->value; 78 s->q = Clamp(s->q + s->dq, 0.f, 100.f); 79 return s->q; 80} 81 82//------------------------------------------------------------------------------ 83// Tables for level coding 84 85const uint8_t VP8Cat3[] = { 173, 148, 140 }; 86const uint8_t VP8Cat4[] = { 176, 155, 140, 135 }; 87const uint8_t VP8Cat5[] = { 180, 157, 141, 134, 130 }; 88const uint8_t VP8Cat6[] = 89 { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 }; 90 91//------------------------------------------------------------------------------ 92// Reset the statistics about: number of skips, token proba, level cost,... 93 94static void ResetStats(VP8Encoder* const enc) { 95 VP8EncProba* const proba = &enc->proba_; 96 VP8CalculateLevelCosts(proba); 97 proba->nb_skip_ = 0; 98} 99 100//------------------------------------------------------------------------------ 101// Skip decision probability 102 103#define SKIP_PROBA_THRESHOLD 250 // value below which using skip_proba is OK. 104 105static int CalcSkipProba(uint64_t nb, uint64_t total) { 106 return (int)(total ? (total - nb) * 255 / total : 255); 107} 108 109// Returns the bit-cost for coding the skip probability. 110static int FinalizeSkipProba(VP8Encoder* const enc) { 111 VP8EncProba* const proba = &enc->proba_; 112 const int nb_mbs = enc->mb_w_ * enc->mb_h_; 113 const int nb_events = proba->nb_skip_; 114 int size; 115 proba->skip_proba_ = CalcSkipProba(nb_events, nb_mbs); 116 proba->use_skip_proba_ = (proba->skip_proba_ < SKIP_PROBA_THRESHOLD); 117 size = 256; // 'use_skip_proba' bit 118 if (proba->use_skip_proba_) { 119 size += nb_events * VP8BitCost(1, proba->skip_proba_) 120 + (nb_mbs - nb_events) * VP8BitCost(0, proba->skip_proba_); 121 size += 8 * 256; // cost of signaling the skip_proba_ itself. 122 } 123 return size; 124} 125 126// Collect statistics and deduce probabilities for next coding pass. 127// Return the total bit-cost for coding the probability updates. 128static int CalcTokenProba(int nb, int total) { 129 assert(nb <= total); 130 return nb ? (255 - nb * 255 / total) : 255; 131} 132 133// Cost of coding 'nb' 1's and 'total-nb' 0's using 'proba' probability. 134static int BranchCost(int nb, int total, int proba) { 135 return nb * VP8BitCost(1, proba) + (total - nb) * VP8BitCost(0, proba); 136} 137 138static void ResetTokenStats(VP8Encoder* const enc) { 139 VP8EncProba* const proba = &enc->proba_; 140 memset(proba->stats_, 0, sizeof(proba->stats_)); 141} 142 143static int FinalizeTokenProbas(VP8EncProba* const proba) { 144 int has_changed = 0; 145 int size = 0; 146 int t, b, c, p; 147 for (t = 0; t < NUM_TYPES; ++t) { 148 for (b = 0; b < NUM_BANDS; ++b) { 149 for (c = 0; c < NUM_CTX; ++c) { 150 for (p = 0; p < NUM_PROBAS; ++p) { 151 const proba_t stats = proba->stats_[t][b][c][p]; 152 const int nb = (stats >> 0) & 0xffff; 153 const int total = (stats >> 16) & 0xffff; 154 const int update_proba = VP8CoeffsUpdateProba[t][b][c][p]; 155 const int old_p = VP8CoeffsProba0[t][b][c][p]; 156 const int new_p = CalcTokenProba(nb, total); 157 const int old_cost = BranchCost(nb, total, old_p) 158 + VP8BitCost(0, update_proba); 159 const int new_cost = BranchCost(nb, total, new_p) 160 + VP8BitCost(1, update_proba) 161 + 8 * 256; 162 const int use_new_p = (old_cost > new_cost); 163 size += VP8BitCost(use_new_p, update_proba); 164 if (use_new_p) { // only use proba that seem meaningful enough. 165 proba->coeffs_[t][b][c][p] = new_p; 166 has_changed |= (new_p != old_p); 167 size += 8 * 256; 168 } else { 169 proba->coeffs_[t][b][c][p] = old_p; 170 } 171 } 172 } 173 } 174 } 175 proba->dirty_ = has_changed; 176 return size; 177} 178 179//------------------------------------------------------------------------------ 180// Finalize Segment probability based on the coding tree 181 182static int GetProba(int a, int b) { 183 const int total = a + b; 184 return (total == 0) ? 255 // that's the default probability. 185 : (255 * a + total / 2) / total; // rounded proba 186} 187 188static void ResetSegments(VP8Encoder* const enc) { 189 int n; 190 for (n = 0; n < enc->mb_w_ * enc->mb_h_; ++n) { 191 enc->mb_info_[n].segment_ = 0; 192 } 193} 194 195static void SetSegmentProbas(VP8Encoder* const enc) { 196 int p[NUM_MB_SEGMENTS] = { 0 }; 197 int n; 198 199 for (n = 0; n < enc->mb_w_ * enc->mb_h_; ++n) { 200 const VP8MBInfo* const mb = &enc->mb_info_[n]; 201 p[mb->segment_]++; 202 } 203 if (enc->pic_->stats != NULL) { 204 for (n = 0; n < NUM_MB_SEGMENTS; ++n) { 205 enc->pic_->stats->segment_size[n] = p[n]; 206 } 207 } 208 if (enc->segment_hdr_.num_segments_ > 1) { 209 uint8_t* const probas = enc->proba_.segments_; 210 probas[0] = GetProba(p[0] + p[1], p[2] + p[3]); 211 probas[1] = GetProba(p[0], p[1]); 212 probas[2] = GetProba(p[2], p[3]); 213 214 enc->segment_hdr_.update_map_ = 215 (probas[0] != 255) || (probas[1] != 255) || (probas[2] != 255); 216 if (!enc->segment_hdr_.update_map_) ResetSegments(enc); 217 enc->segment_hdr_.size_ = 218 p[0] * (VP8BitCost(0, probas[0]) + VP8BitCost(0, probas[1])) + 219 p[1] * (VP8BitCost(0, probas[0]) + VP8BitCost(1, probas[1])) + 220 p[2] * (VP8BitCost(1, probas[0]) + VP8BitCost(0, probas[2])) + 221 p[3] * (VP8BitCost(1, probas[0]) + VP8BitCost(1, probas[2])); 222 } else { 223 enc->segment_hdr_.update_map_ = 0; 224 enc->segment_hdr_.size_ = 0; 225 } 226} 227 228//------------------------------------------------------------------------------ 229// Coefficient coding 230 231static int PutCoeffs(VP8BitWriter* const bw, int ctx, const VP8Residual* res) { 232 int n = res->first; 233 // should be prob[VP8EncBands[n]], but it's equivalent for n=0 or 1 234 const uint8_t* p = res->prob[n][ctx]; 235 if (!VP8PutBit(bw, res->last >= 0, p[0])) { 236 return 0; 237 } 238 239 while (n < 16) { 240 const int c = res->coeffs[n++]; 241 const int sign = c < 0; 242 int v = sign ? -c : c; 243 if (!VP8PutBit(bw, v != 0, p[1])) { 244 p = res->prob[VP8EncBands[n]][0]; 245 continue; 246 } 247 if (!VP8PutBit(bw, v > 1, p[2])) { 248 p = res->prob[VP8EncBands[n]][1]; 249 } else { 250 if (!VP8PutBit(bw, v > 4, p[3])) { 251 if (VP8PutBit(bw, v != 2, p[4])) { 252 VP8PutBit(bw, v == 4, p[5]); 253 } 254 } else if (!VP8PutBit(bw, v > 10, p[6])) { 255 if (!VP8PutBit(bw, v > 6, p[7])) { 256 VP8PutBit(bw, v == 6, 159); 257 } else { 258 VP8PutBit(bw, v >= 9, 165); 259 VP8PutBit(bw, !(v & 1), 145); 260 } 261 } else { 262 int mask; 263 const uint8_t* tab; 264 if (v < 3 + (8 << 1)) { // VP8Cat3 (3b) 265 VP8PutBit(bw, 0, p[8]); 266 VP8PutBit(bw, 0, p[9]); 267 v -= 3 + (8 << 0); 268 mask = 1 << 2; 269 tab = VP8Cat3; 270 } else if (v < 3 + (8 << 2)) { // VP8Cat4 (4b) 271 VP8PutBit(bw, 0, p[8]); 272 VP8PutBit(bw, 1, p[9]); 273 v -= 3 + (8 << 1); 274 mask = 1 << 3; 275 tab = VP8Cat4; 276 } else if (v < 3 + (8 << 3)) { // VP8Cat5 (5b) 277 VP8PutBit(bw, 1, p[8]); 278 VP8PutBit(bw, 0, p[10]); 279 v -= 3 + (8 << 2); 280 mask = 1 << 4; 281 tab = VP8Cat5; 282 } else { // VP8Cat6 (11b) 283 VP8PutBit(bw, 1, p[8]); 284 VP8PutBit(bw, 1, p[10]); 285 v -= 3 + (8 << 3); 286 mask = 1 << 10; 287 tab = VP8Cat6; 288 } 289 while (mask) { 290 VP8PutBit(bw, !!(v & mask), *tab++); 291 mask >>= 1; 292 } 293 } 294 p = res->prob[VP8EncBands[n]][2]; 295 } 296 VP8PutBitUniform(bw, sign); 297 if (n == 16 || !VP8PutBit(bw, n <= res->last, p[0])) { 298 return 1; // EOB 299 } 300 } 301 return 1; 302} 303 304static void CodeResiduals(VP8BitWriter* const bw, VP8EncIterator* const it, 305 const VP8ModeScore* const rd) { 306 int x, y, ch; 307 VP8Residual res; 308 uint64_t pos1, pos2, pos3; 309 const int i16 = (it->mb_->type_ == 1); 310 const int segment = it->mb_->segment_; 311 VP8Encoder* const enc = it->enc_; 312 313 VP8IteratorNzToBytes(it); 314 315 pos1 = VP8BitWriterPos(bw); 316 if (i16) { 317 VP8InitResidual(0, 1, enc, &res); 318 VP8SetResidualCoeffs(rd->y_dc_levels, &res); 319 it->top_nz_[8] = it->left_nz_[8] = 320 PutCoeffs(bw, it->top_nz_[8] + it->left_nz_[8], &res); 321 VP8InitResidual(1, 0, enc, &res); 322 } else { 323 VP8InitResidual(0, 3, enc, &res); 324 } 325 326 // luma-AC 327 for (y = 0; y < 4; ++y) { 328 for (x = 0; x < 4; ++x) { 329 const int ctx = it->top_nz_[x] + it->left_nz_[y]; 330 VP8SetResidualCoeffs(rd->y_ac_levels[x + y * 4], &res); 331 it->top_nz_[x] = it->left_nz_[y] = PutCoeffs(bw, ctx, &res); 332 } 333 } 334 pos2 = VP8BitWriterPos(bw); 335 336 // U/V 337 VP8InitResidual(0, 2, enc, &res); 338 for (ch = 0; ch <= 2; ch += 2) { 339 for (y = 0; y < 2; ++y) { 340 for (x = 0; x < 2; ++x) { 341 const int ctx = it->top_nz_[4 + ch + x] + it->left_nz_[4 + ch + y]; 342 VP8SetResidualCoeffs(rd->uv_levels[ch * 2 + x + y * 2], &res); 343 it->top_nz_[4 + ch + x] = it->left_nz_[4 + ch + y] = 344 PutCoeffs(bw, ctx, &res); 345 } 346 } 347 } 348 pos3 = VP8BitWriterPos(bw); 349 it->luma_bits_ = pos2 - pos1; 350 it->uv_bits_ = pos3 - pos2; 351 it->bit_count_[segment][i16] += it->luma_bits_; 352 it->bit_count_[segment][2] += it->uv_bits_; 353 VP8IteratorBytesToNz(it); 354} 355 356// Same as CodeResiduals, but doesn't actually write anything. 357// Instead, it just records the event distribution. 358static void RecordResiduals(VP8EncIterator* const it, 359 const VP8ModeScore* const rd) { 360 int x, y, ch; 361 VP8Residual res; 362 VP8Encoder* const enc = it->enc_; 363 364 VP8IteratorNzToBytes(it); 365 366 if (it->mb_->type_ == 1) { // i16x16 367 VP8InitResidual(0, 1, enc, &res); 368 VP8SetResidualCoeffs(rd->y_dc_levels, &res); 369 it->top_nz_[8] = it->left_nz_[8] = 370 VP8RecordCoeffs(it->top_nz_[8] + it->left_nz_[8], &res); 371 VP8InitResidual(1, 0, enc, &res); 372 } else { 373 VP8InitResidual(0, 3, enc, &res); 374 } 375 376 // luma-AC 377 for (y = 0; y < 4; ++y) { 378 for (x = 0; x < 4; ++x) { 379 const int ctx = it->top_nz_[x] + it->left_nz_[y]; 380 VP8SetResidualCoeffs(rd->y_ac_levels[x + y * 4], &res); 381 it->top_nz_[x] = it->left_nz_[y] = VP8RecordCoeffs(ctx, &res); 382 } 383 } 384 385 // U/V 386 VP8InitResidual(0, 2, enc, &res); 387 for (ch = 0; ch <= 2; ch += 2) { 388 for (y = 0; y < 2; ++y) { 389 for (x = 0; x < 2; ++x) { 390 const int ctx = it->top_nz_[4 + ch + x] + it->left_nz_[4 + ch + y]; 391 VP8SetResidualCoeffs(rd->uv_levels[ch * 2 + x + y * 2], &res); 392 it->top_nz_[4 + ch + x] = it->left_nz_[4 + ch + y] = 393 VP8RecordCoeffs(ctx, &res); 394 } 395 } 396 } 397 398 VP8IteratorBytesToNz(it); 399} 400 401//------------------------------------------------------------------------------ 402// Token buffer 403 404#if !defined(DISABLE_TOKEN_BUFFER) 405 406static int RecordTokens(VP8EncIterator* const it, const VP8ModeScore* const rd, 407 VP8TBuffer* const tokens) { 408 int x, y, ch; 409 VP8Residual res; 410 VP8Encoder* const enc = it->enc_; 411 412 VP8IteratorNzToBytes(it); 413 if (it->mb_->type_ == 1) { // i16x16 414 const int ctx = it->top_nz_[8] + it->left_nz_[8]; 415 VP8InitResidual(0, 1, enc, &res); 416 VP8SetResidualCoeffs(rd->y_dc_levels, &res); 417 it->top_nz_[8] = it->left_nz_[8] = 418 VP8RecordCoeffTokens(ctx, &res, tokens); 419 VP8InitResidual(1, 0, enc, &res); 420 } else { 421 VP8InitResidual(0, 3, enc, &res); 422 } 423 424 // luma-AC 425 for (y = 0; y < 4; ++y) { 426 for (x = 0; x < 4; ++x) { 427 const int ctx = it->top_nz_[x] + it->left_nz_[y]; 428 VP8SetResidualCoeffs(rd->y_ac_levels[x + y * 4], &res); 429 it->top_nz_[x] = it->left_nz_[y] = 430 VP8RecordCoeffTokens(ctx, &res, tokens); 431 } 432 } 433 434 // U/V 435 VP8InitResidual(0, 2, enc, &res); 436 for (ch = 0; ch <= 2; ch += 2) { 437 for (y = 0; y < 2; ++y) { 438 for (x = 0; x < 2; ++x) { 439 const int ctx = it->top_nz_[4 + ch + x] + it->left_nz_[4 + ch + y]; 440 VP8SetResidualCoeffs(rd->uv_levels[ch * 2 + x + y * 2], &res); 441 it->top_nz_[4 + ch + x] = it->left_nz_[4 + ch + y] = 442 VP8RecordCoeffTokens(ctx, &res, tokens); 443 } 444 } 445 } 446 VP8IteratorBytesToNz(it); 447 return !tokens->error_; 448} 449 450#endif // !DISABLE_TOKEN_BUFFER 451 452//------------------------------------------------------------------------------ 453// ExtraInfo map / Debug function 454 455#if SEGMENT_VISU 456static void SetBlock(uint8_t* p, int value, int size) { 457 int y; 458 for (y = 0; y < size; ++y) { 459 memset(p, value, size); 460 p += BPS; 461 } 462} 463#endif 464 465static void ResetSSE(VP8Encoder* const enc) { 466 enc->sse_[0] = 0; 467 enc->sse_[1] = 0; 468 enc->sse_[2] = 0; 469 // Note: enc->sse_[3] is managed by alpha.c 470 enc->sse_count_ = 0; 471} 472 473static void StoreSSE(const VP8EncIterator* const it) { 474 VP8Encoder* const enc = it->enc_; 475 const uint8_t* const in = it->yuv_in_; 476 const uint8_t* const out = it->yuv_out_; 477 // Note: not totally accurate at boundary. And doesn't include in-loop filter. 478 enc->sse_[0] += VP8SSE16x16(in + Y_OFF_ENC, out + Y_OFF_ENC); 479 enc->sse_[1] += VP8SSE8x8(in + U_OFF_ENC, out + U_OFF_ENC); 480 enc->sse_[2] += VP8SSE8x8(in + V_OFF_ENC, out + V_OFF_ENC); 481 enc->sse_count_ += 16 * 16; 482} 483 484static void StoreSideInfo(const VP8EncIterator* const it) { 485 VP8Encoder* const enc = it->enc_; 486 const VP8MBInfo* const mb = it->mb_; 487 WebPPicture* const pic = enc->pic_; 488 489 if (pic->stats != NULL) { 490 StoreSSE(it); 491 enc->block_count_[0] += (mb->type_ == 0); 492 enc->block_count_[1] += (mb->type_ == 1); 493 enc->block_count_[2] += (mb->skip_ != 0); 494 } 495 496 if (pic->extra_info != NULL) { 497 uint8_t* const info = &pic->extra_info[it->x_ + it->y_ * enc->mb_w_]; 498 switch (pic->extra_info_type) { 499 case 1: *info = mb->type_; break; 500 case 2: *info = mb->segment_; break; 501 case 3: *info = enc->dqm_[mb->segment_].quant_; break; 502 case 4: *info = (mb->type_ == 1) ? it->preds_[0] : 0xff; break; 503 case 5: *info = mb->uv_mode_; break; 504 case 6: { 505 const int b = (int)((it->luma_bits_ + it->uv_bits_ + 7) >> 3); 506 *info = (b > 255) ? 255 : b; break; 507 } 508 case 7: *info = mb->alpha_; break; 509 default: *info = 0; break; 510 } 511 } 512#if SEGMENT_VISU // visualize segments and prediction modes 513 SetBlock(it->yuv_out_ + Y_OFF_ENC, mb->segment_ * 64, 16); 514 SetBlock(it->yuv_out_ + U_OFF_ENC, it->preds_[0] * 64, 8); 515 SetBlock(it->yuv_out_ + V_OFF_ENC, mb->uv_mode_ * 64, 8); 516#endif 517} 518 519static double GetPSNR(uint64_t mse, uint64_t size) { 520 return (mse > 0 && size > 0) ? 10. * log10(255. * 255. * size / mse) : 99; 521} 522 523//------------------------------------------------------------------------------ 524// StatLoop(): only collect statistics (number of skips, token usage, ...). 525// This is used for deciding optimal probabilities. It also modifies the 526// quantizer value if some target (size, PSNR) was specified. 527 528static void SetLoopParams(VP8Encoder* const enc, float q) { 529 // Make sure the quality parameter is inside valid bounds 530 q = Clamp(q, 0.f, 100.f); 531 532 VP8SetSegmentParams(enc, q); // setup segment quantizations and filters 533 SetSegmentProbas(enc); // compute segment probabilities 534 535 ResetStats(enc); 536 ResetSSE(enc); 537} 538 539static uint64_t OneStatPass(VP8Encoder* const enc, VP8RDLevel rd_opt, 540 int nb_mbs, int percent_delta, 541 PassStats* const s) { 542 VP8EncIterator it; 543 uint64_t size = 0; 544 uint64_t size_p0 = 0; 545 uint64_t distortion = 0; 546 const uint64_t pixel_count = nb_mbs * 384; 547 548 VP8IteratorInit(enc, &it); 549 SetLoopParams(enc, s->q); 550 do { 551 VP8ModeScore info; 552 VP8IteratorImport(&it, NULL); 553 if (VP8Decimate(&it, &info, rd_opt)) { 554 // Just record the number of skips and act like skip_proba is not used. 555 enc->proba_.nb_skip_++; 556 } 557 RecordResiduals(&it, &info); 558 size += info.R + info.H; 559 size_p0 += info.H; 560 distortion += info.D; 561 if (percent_delta && !VP8IteratorProgress(&it, percent_delta)) { 562 return 0; 563 } 564 VP8IteratorSaveBoundary(&it); 565 } while (VP8IteratorNext(&it) && --nb_mbs > 0); 566 567 size_p0 += enc->segment_hdr_.size_; 568 if (s->do_size_search) { 569 size += FinalizeSkipProba(enc); 570 size += FinalizeTokenProbas(&enc->proba_); 571 size = ((size + size_p0 + 1024) >> 11) + HEADER_SIZE_ESTIMATE; 572 s->value = (double)size; 573 } else { 574 s->value = GetPSNR(distortion, pixel_count); 575 } 576 return size_p0; 577} 578 579static int StatLoop(VP8Encoder* const enc) { 580 const int method = enc->method_; 581 const int do_search = enc->do_search_; 582 const int fast_probe = ((method == 0 || method == 3) && !do_search); 583 int num_pass_left = enc->config_->pass; 584 const int task_percent = 20; 585 const int percent_per_pass = 586 (task_percent + num_pass_left / 2) / num_pass_left; 587 const int final_percent = enc->percent_ + task_percent; 588 const VP8RDLevel rd_opt = 589 (method >= 3 || do_search) ? RD_OPT_BASIC : RD_OPT_NONE; 590 int nb_mbs = enc->mb_w_ * enc->mb_h_; 591 PassStats stats; 592 593 InitPassStats(enc, &stats); 594 ResetTokenStats(enc); 595 596 // Fast mode: quick analysis pass over few mbs. Better than nothing. 597 if (fast_probe) { 598 if (method == 3) { // we need more stats for method 3 to be reliable. 599 nb_mbs = (nb_mbs > 200) ? nb_mbs >> 1 : 100; 600 } else { 601 nb_mbs = (nb_mbs > 200) ? nb_mbs >> 2 : 50; 602 } 603 } 604 605 while (num_pass_left-- > 0) { 606 const int is_last_pass = (fabs(stats.dq) <= DQ_LIMIT) || 607 (num_pass_left == 0) || 608 (enc->max_i4_header_bits_ == 0); 609 const uint64_t size_p0 = 610 OneStatPass(enc, rd_opt, nb_mbs, percent_per_pass, &stats); 611 if (size_p0 == 0) return 0; 612#if (DEBUG_SEARCH > 0) 613 printf("#%d value:%.1lf -> %.1lf q:%.2f -> %.2f\n", 614 num_pass_left, stats.last_value, stats.value, stats.last_q, stats.q); 615#endif 616 if (enc->max_i4_header_bits_ > 0 && size_p0 > PARTITION0_SIZE_LIMIT) { 617 ++num_pass_left; 618 enc->max_i4_header_bits_ >>= 1; // strengthen header bit limitation... 619 continue; // ...and start over 620 } 621 if (is_last_pass) { 622 break; 623 } 624 // If no target size: just do several pass without changing 'q' 625 if (do_search) { 626 ComputeNextQ(&stats); 627 if (fabs(stats.dq) <= DQ_LIMIT) break; 628 } 629 } 630 if (!do_search || !stats.do_size_search) { 631 // Need to finalize probas now, since it wasn't done during the search. 632 FinalizeSkipProba(enc); 633 FinalizeTokenProbas(&enc->proba_); 634 } 635 VP8CalculateLevelCosts(&enc->proba_); // finalize costs 636 return WebPReportProgress(enc->pic_, final_percent, &enc->percent_); 637} 638 639//------------------------------------------------------------------------------ 640// Main loops 641// 642 643static const int kAverageBytesPerMB[8] = { 50, 24, 16, 9, 7, 5, 3, 2 }; 644 645static int PreLoopInitialize(VP8Encoder* const enc) { 646 int p; 647 int ok = 1; 648 const int average_bytes_per_MB = kAverageBytesPerMB[enc->base_quant_ >> 4]; 649 const int bytes_per_parts = 650 enc->mb_w_ * enc->mb_h_ * average_bytes_per_MB / enc->num_parts_; 651 // Initialize the bit-writers 652 for (p = 0; ok && p < enc->num_parts_; ++p) { 653 ok = VP8BitWriterInit(enc->parts_ + p, bytes_per_parts); 654 } 655 if (!ok) { 656 VP8EncFreeBitWriters(enc); // malloc error occurred 657 WebPEncodingSetError(enc->pic_, VP8_ENC_ERROR_OUT_OF_MEMORY); 658 } 659 return ok; 660} 661 662static int PostLoopFinalize(VP8EncIterator* const it, int ok) { 663 VP8Encoder* const enc = it->enc_; 664 if (ok) { // Finalize the partitions, check for extra errors. 665 int p; 666 for (p = 0; p < enc->num_parts_; ++p) { 667 VP8BitWriterFinish(enc->parts_ + p); 668 ok &= !enc->parts_[p].error_; 669 } 670 } 671 672 if (ok) { // All good. Finish up. 673 if (enc->pic_->stats != NULL) { // finalize byte counters... 674 int i, s; 675 for (i = 0; i <= 2; ++i) { 676 for (s = 0; s < NUM_MB_SEGMENTS; ++s) { 677 enc->residual_bytes_[i][s] = (int)((it->bit_count_[s][i] + 7) >> 3); 678 } 679 } 680 } 681 VP8AdjustFilterStrength(it); // ...and store filter stats. 682 } else { 683 // Something bad happened -> need to do some memory cleanup. 684 VP8EncFreeBitWriters(enc); 685 } 686 return ok; 687} 688 689//------------------------------------------------------------------------------ 690// VP8EncLoop(): does the final bitstream coding. 691 692static void ResetAfterSkip(VP8EncIterator* const it) { 693 if (it->mb_->type_ == 1) { 694 *it->nz_ = 0; // reset all predictors 695 it->left_nz_[8] = 0; 696 } else { 697 *it->nz_ &= (1 << 24); // preserve the dc_nz bit 698 } 699} 700 701int VP8EncLoop(VP8Encoder* const enc) { 702 VP8EncIterator it; 703 int ok = PreLoopInitialize(enc); 704 if (!ok) return 0; 705 706 StatLoop(enc); // stats-collection loop 707 708 VP8IteratorInit(enc, &it); 709 VP8InitFilter(&it); 710 do { 711 VP8ModeScore info; 712 const int dont_use_skip = !enc->proba_.use_skip_proba_; 713 const VP8RDLevel rd_opt = enc->rd_opt_level_; 714 715 VP8IteratorImport(&it, NULL); 716 // Warning! order is important: first call VP8Decimate() and 717 // *then* decide how to code the skip decision if there's one. 718 if (!VP8Decimate(&it, &info, rd_opt) || dont_use_skip) { 719 CodeResiduals(it.bw_, &it, &info); 720 } else { // reset predictors after a skip 721 ResetAfterSkip(&it); 722 } 723 StoreSideInfo(&it); 724 VP8StoreFilterStats(&it); 725 VP8IteratorExport(&it); 726 ok = VP8IteratorProgress(&it, 20); 727 VP8IteratorSaveBoundary(&it); 728 } while (ok && VP8IteratorNext(&it)); 729 730 return PostLoopFinalize(&it, ok); 731} 732 733//------------------------------------------------------------------------------ 734// Single pass using Token Buffer. 735 736#if !defined(DISABLE_TOKEN_BUFFER) 737 738#define MIN_COUNT 96 // minimum number of macroblocks before updating stats 739 740int VP8EncTokenLoop(VP8Encoder* const enc) { 741 // Roughly refresh the proba eight times per pass 742 int max_count = (enc->mb_w_ * enc->mb_h_) >> 3; 743 int num_pass_left = enc->config_->pass; 744 const int do_search = enc->do_search_; 745 VP8EncIterator it; 746 VP8EncProba* const proba = &enc->proba_; 747 const VP8RDLevel rd_opt = enc->rd_opt_level_; 748 const uint64_t pixel_count = enc->mb_w_ * enc->mb_h_ * 384; 749 PassStats stats; 750 int ok; 751 752 InitPassStats(enc, &stats); 753 ok = PreLoopInitialize(enc); 754 if (!ok) return 0; 755 756 if (max_count < MIN_COUNT) max_count = MIN_COUNT; 757 758 assert(enc->num_parts_ == 1); 759 assert(enc->use_tokens_); 760 assert(proba->use_skip_proba_ == 0); 761 assert(rd_opt >= RD_OPT_BASIC); // otherwise, token-buffer won't be useful 762 assert(num_pass_left > 0); 763 764 while (ok && num_pass_left-- > 0) { 765 const int is_last_pass = (fabs(stats.dq) <= DQ_LIMIT) || 766 (num_pass_left == 0) || 767 (enc->max_i4_header_bits_ == 0); 768 uint64_t size_p0 = 0; 769 uint64_t distortion = 0; 770 int cnt = max_count; 771 VP8IteratorInit(enc, &it); 772 SetLoopParams(enc, stats.q); 773 if (is_last_pass) { 774 ResetTokenStats(enc); 775 VP8InitFilter(&it); // don't collect stats until last pass (too costly) 776 } 777 VP8TBufferClear(&enc->tokens_); 778 do { 779 VP8ModeScore info; 780 VP8IteratorImport(&it, NULL); 781 if (--cnt < 0) { 782 FinalizeTokenProbas(proba); 783 VP8CalculateLevelCosts(proba); // refresh cost tables for rd-opt 784 cnt = max_count; 785 } 786 VP8Decimate(&it, &info, rd_opt); 787 ok = RecordTokens(&it, &info, &enc->tokens_); 788 if (!ok) { 789 WebPEncodingSetError(enc->pic_, VP8_ENC_ERROR_OUT_OF_MEMORY); 790 break; 791 } 792 size_p0 += info.H; 793 distortion += info.D; 794 if (is_last_pass) { 795 StoreSideInfo(&it); 796 VP8StoreFilterStats(&it); 797 VP8IteratorExport(&it); 798 ok = VP8IteratorProgress(&it, 20); 799 } 800 VP8IteratorSaveBoundary(&it); 801 } while (ok && VP8IteratorNext(&it)); 802 if (!ok) break; 803 804 size_p0 += enc->segment_hdr_.size_; 805 if (stats.do_size_search) { 806 uint64_t size = FinalizeTokenProbas(&enc->proba_); 807 size += VP8EstimateTokenSize(&enc->tokens_, 808 (const uint8_t*)proba->coeffs_); 809 size = (size + size_p0 + 1024) >> 11; // -> size in bytes 810 size += HEADER_SIZE_ESTIMATE; 811 stats.value = (double)size; 812 } else { // compute and store PSNR 813 stats.value = GetPSNR(distortion, pixel_count); 814 } 815 816#if (DEBUG_SEARCH > 0) 817 printf("#%2d metric:%.1lf -> %.1lf last_q=%.2lf q=%.2lf dq=%.2lf\n", 818 num_pass_left, stats.last_value, stats.value, 819 stats.last_q, stats.q, stats.dq); 820#endif 821 if (enc->max_i4_header_bits_ > 0 && size_p0 > PARTITION0_SIZE_LIMIT) { 822 ++num_pass_left; 823 enc->max_i4_header_bits_ >>= 1; // strengthen header bit limitation... 824 continue; // ...and start over 825 } 826 if (is_last_pass) { 827 break; // done 828 } 829 if (do_search) { 830 ComputeNextQ(&stats); // Adjust q 831 } 832 } 833 if (ok) { 834 if (!stats.do_size_search) { 835 FinalizeTokenProbas(&enc->proba_); 836 } 837 ok = VP8EmitTokens(&enc->tokens_, enc->parts_ + 0, 838 (const uint8_t*)proba->coeffs_, 1); 839 } 840 ok = ok && WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_); 841 return PostLoopFinalize(&it, ok); 842} 843 844#else 845 846int VP8EncTokenLoop(VP8Encoder* const enc) { 847 (void)enc; 848 return 0; // we shouldn't be here. 849} 850 851#endif // DISABLE_TOKEN_BUFFER 852 853//------------------------------------------------------------------------------ 854 855