1 // Copyright 2011 Google Inc. All Rights Reserved.
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 // -----------------------------------------------------------------------------
10 // frame coding and analysis
12 // Author: Skal (pascal.massimino@gmail.com)
19 #include "./vp8enci.h"
21 #include "../webp/format_constants.h" // RIFF constants
23 #define SEGMENT_VISU 0
24 #define DEBUG_SEARCH 0 // useful to track search convergence
26 // On-the-fly info about the current set of residuals. Handy to avoid
27 // passing zillions of params.
31 const int16_t* coeffs
;
39 //------------------------------------------------------------------------------
40 // multi-pass convergence
42 #define HEADER_SIZE_ESTIMATE (RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE + \
43 VP8_FRAME_HEADER_SIZE)
44 #define DQ_LIMIT 0.4 // convergence is considered reached if dq < DQ_LIMIT
45 // we allow 2k of extra head-room in PARTITION0 limit.
46 #define PARTITION0_SIZE_LIMIT ((VP8_MAX_PARTITION0_SIZE - 2048ULL) << 11)
48 typedef struct { // struct for organizing convergence in either size or PSNR
52 double value
, last_value
; // PSNR or size
57 static int InitPassStats(const VP8Encoder
* const enc
, PassStats
* const s
) {
58 const uint64_t target_size
= (uint64_t)enc
->config_
->target_size
;
59 const int do_size_search
= (target_size
!= 0);
60 const float target_PSNR
= enc
->config_
->target_PSNR
;
64 s
->q
= s
->last_q
= enc
->config_
->quality
;
65 s
->target
= do_size_search
? (double)target_size
66 : (target_PSNR
> 0.) ? target_PSNR
67 : 40.; // default, just in case
68 s
->value
= s
->last_value
= 0.;
69 s
->do_size_search
= do_size_search
;
70 return do_size_search
;
73 static float Clamp(float v
, float min
, float max
) {
74 return (v
< min
) ? min
: (v
> max
) ? max
: v
;
77 static float ComputeNextQ(PassStats
* const s
) {
80 dq
= (s
->value
> s
->target
) ? -s
->dq
: s
->dq
;
82 } else if (s
->value
!= s
->last_value
) {
83 const double slope
= (s
->target
- s
->value
) / (s
->last_value
- s
->value
);
84 dq
= (float)(slope
* (s
->last_q
- s
->q
));
86 dq
= 0.; // we're done?!
88 // Limit variable to avoid large swings.
89 s
->dq
= Clamp(dq
, -30.f
, 30.f
);
91 s
->last_value
= s
->value
;
92 s
->q
= Clamp(s
->q
+ s
->dq
, 0.f
, 100.f
);
96 //------------------------------------------------------------------------------
97 // Tables for level coding
99 const uint8_t VP8EncBands
[16 + 1] = {
100 0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7,
104 const uint8_t VP8Cat3
[] = { 173, 148, 140 };
105 const uint8_t VP8Cat4
[] = { 176, 155, 140, 135 };
106 const uint8_t VP8Cat5
[] = { 180, 157, 141, 134, 130 };
107 const uint8_t VP8Cat6
[] =
108 { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 };
110 //------------------------------------------------------------------------------
111 // Reset the statistics about: number of skips, token proba, level cost,...
113 static void ResetStats(VP8Encoder
* const enc
) {
114 VP8Proba
* const proba
= &enc
->proba_
;
115 VP8CalculateLevelCosts(proba
);
119 //------------------------------------------------------------------------------
120 // Skip decision probability
122 #define SKIP_PROBA_THRESHOLD 250 // value below which using skip_proba is OK.
124 static int CalcSkipProba(uint64_t nb
, uint64_t total
) {
125 return (int)(total
? (total
- nb
) * 255 / total
: 255);
128 // Returns the bit-cost for coding the skip probability.
129 static int FinalizeSkipProba(VP8Encoder
* const enc
) {
130 VP8Proba
* const proba
= &enc
->proba_
;
131 const int nb_mbs
= enc
->mb_w_
* enc
->mb_h_
;
132 const int nb_events
= proba
->nb_skip_
;
134 proba
->skip_proba_
= CalcSkipProba(nb_events
, nb_mbs
);
135 proba
->use_skip_proba_
= (proba
->skip_proba_
< SKIP_PROBA_THRESHOLD
);
136 size
= 256; // 'use_skip_proba' bit
137 if (proba
->use_skip_proba_
) {
138 size
+= nb_events
* VP8BitCost(1, proba
->skip_proba_
)
139 + (nb_mbs
- nb_events
) * VP8BitCost(0, proba
->skip_proba_
);
140 size
+= 8 * 256; // cost of signaling the skip_proba_ itself.
145 //------------------------------------------------------------------------------
146 // Recording of token probabilities.
148 static void ResetTokenStats(VP8Encoder
* const enc
) {
149 VP8Proba
* const proba
= &enc
->proba_
;
150 memset(proba
->stats_
, 0, sizeof(proba
->stats_
));
153 // Record proba context used
154 static int Record(int bit
, proba_t
* const stats
) {
156 if (p
>= 0xffff0000u
) { // an overflow is inbound.
157 p
= ((p
+ 1u) >> 1) & 0x7fff7fffu
; // -> divide the stats by 2.
159 // record bit count (lower 16 bits) and increment total count (upper 16 bits).
160 p
+= 0x00010000u
+ bit
;
165 // We keep the table free variant around for reference, in case.
166 #define USE_LEVEL_CODE_TABLE
168 // Simulate block coding, but only record statistics.
169 // Note: no need to record the fixed probas.
170 static int RecordCoeffs(int ctx
, const VP8Residual
* const res
) {
172 // should be stats[VP8EncBands[n]], but it's equivalent for n=0 or 1
173 proba_t
* s
= res
->stats
[n
][ctx
];
178 while (n
<= res
->last
) {
180 Record(1, s
+ 0); // order of record doesn't matter
181 while ((v
= res
->coeffs
[n
++]) == 0) {
183 s
= res
->stats
[VP8EncBands
[n
]][0];
186 if (!Record(2u < (unsigned int)(v
+ 1), s
+ 2)) { // v = -1 or 1
187 s
= res
->stats
[VP8EncBands
[n
]][1];
190 #if !defined(USE_LEVEL_CODE_TABLE)
191 if (!Record(v
> 4, s
+ 3)) {
192 if (Record(v
!= 2, s
+ 4))
193 Record(v
== 4, s
+ 5);
194 } else if (!Record(v
> 10, s
+ 6)) {
195 Record(v
> 6, s
+ 7);
196 } else if (!Record((v
>= 3 + (8 << 2)), s
+ 8)) {
197 Record((v
>= 3 + (8 << 1)), s
+ 9);
199 Record((v
>= 3 + (8 << 3)), s
+ 10);
202 if (v
> MAX_VARIABLE_LEVEL
)
203 v
= MAX_VARIABLE_LEVEL
;
206 const int bits
= VP8LevelCodes
[v
- 1][1];
207 int pattern
= VP8LevelCodes
[v
- 1][0];
209 for (i
= 0; (pattern
>>= 1) != 0; ++i
) {
210 const int mask
= 2 << i
;
211 if (pattern
& 1) Record(!!(bits
& mask
), s
+ 3 + i
);
215 s
= res
->stats
[VP8EncBands
[n
]][2];
218 if (n
< 16) Record(0, s
+ 0);
222 // Collect statistics and deduce probabilities for next coding pass.
223 // Return the total bit-cost for coding the probability updates.
224 static int CalcTokenProba(int nb
, int total
) {
226 return nb
? (255 - nb
* 255 / total
) : 255;
229 // Cost of coding 'nb' 1's and 'total-nb' 0's using 'proba' probability.
230 static int BranchCost(int nb
, int total
, int proba
) {
231 return nb
* VP8BitCost(1, proba
) + (total
- nb
) * VP8BitCost(0, proba
);
234 static int FinalizeTokenProbas(VP8Proba
* const proba
) {
238 for (t
= 0; t
< NUM_TYPES
; ++t
) {
239 for (b
= 0; b
< NUM_BANDS
; ++b
) {
240 for (c
= 0; c
< NUM_CTX
; ++c
) {
241 for (p
= 0; p
< NUM_PROBAS
; ++p
) {
242 const proba_t stats
= proba
->stats_
[t
][b
][c
][p
];
243 const int nb
= (stats
>> 0) & 0xffff;
244 const int total
= (stats
>> 16) & 0xffff;
245 const int update_proba
= VP8CoeffsUpdateProba
[t
][b
][c
][p
];
246 const int old_p
= VP8CoeffsProba0
[t
][b
][c
][p
];
247 const int new_p
= CalcTokenProba(nb
, total
);
248 const int old_cost
= BranchCost(nb
, total
, old_p
)
249 + VP8BitCost(0, update_proba
);
250 const int new_cost
= BranchCost(nb
, total
, new_p
)
251 + VP8BitCost(1, update_proba
)
253 const int use_new_p
= (old_cost
> new_cost
);
254 size
+= VP8BitCost(use_new_p
, update_proba
);
255 if (use_new_p
) { // only use proba that seem meaningful enough.
256 proba
->coeffs_
[t
][b
][c
][p
] = new_p
;
257 has_changed
|= (new_p
!= old_p
);
260 proba
->coeffs_
[t
][b
][c
][p
] = old_p
;
266 proba
->dirty_
= has_changed
;
270 //------------------------------------------------------------------------------
271 // Finalize Segment probability based on the coding tree
273 static int GetProba(int a
, int b
) {
274 const int total
= a
+ b
;
275 return (total
== 0) ? 255 // that's the default probability.
276 : (255 * a
+ total
/ 2) / total
; // rounded proba
279 static void SetSegmentProbas(VP8Encoder
* const enc
) {
280 int p
[NUM_MB_SEGMENTS
] = { 0 };
283 for (n
= 0; n
< enc
->mb_w_
* enc
->mb_h_
; ++n
) {
284 const VP8MBInfo
* const mb
= &enc
->mb_info_
[n
];
287 if (enc
->pic_
->stats
!= NULL
) {
288 for (n
= 0; n
< NUM_MB_SEGMENTS
; ++n
) {
289 enc
->pic_
->stats
->segment_size
[n
] = p
[n
];
292 if (enc
->segment_hdr_
.num_segments_
> 1) {
293 uint8_t* const probas
= enc
->proba_
.segments_
;
294 probas
[0] = GetProba(p
[0] + p
[1], p
[2] + p
[3]);
295 probas
[1] = GetProba(p
[0], p
[1]);
296 probas
[2] = GetProba(p
[2], p
[3]);
298 enc
->segment_hdr_
.update_map_
=
299 (probas
[0] != 255) || (probas
[1] != 255) || (probas
[2] != 255);
300 enc
->segment_hdr_
.size_
=
301 p
[0] * (VP8BitCost(0, probas
[0]) + VP8BitCost(0, probas
[1])) +
302 p
[1] * (VP8BitCost(0, probas
[0]) + VP8BitCost(1, probas
[1])) +
303 p
[2] * (VP8BitCost(1, probas
[0]) + VP8BitCost(0, probas
[2])) +
304 p
[3] * (VP8BitCost(1, probas
[0]) + VP8BitCost(1, probas
[2]));
306 enc
->segment_hdr_
.update_map_
= 0;
307 enc
->segment_hdr_
.size_
= 0;
311 //------------------------------------------------------------------------------
312 // helper functions for residuals struct VP8Residual.
314 static void InitResidual(int first
, int coeff_type
,
315 VP8Encoder
* const enc
, VP8Residual
* const res
) {
316 res
->coeff_type
= coeff_type
;
317 res
->prob
= enc
->proba_
.coeffs_
[coeff_type
];
318 res
->stats
= enc
->proba_
.stats_
[coeff_type
];
319 res
->cost
= enc
->proba_
.level_cost_
[coeff_type
];
323 static void SetResidualCoeffs(const int16_t* const coeffs
,
324 VP8Residual
* const res
) {
327 for (n
= 15; n
>= res
->first
; --n
) {
333 res
->coeffs
= coeffs
;
336 //------------------------------------------------------------------------------
339 static int GetResidualCost(int ctx0
, const VP8Residual
* const res
) {
341 // should be prob[VP8EncBands[n]], but it's equivalent for n=0 or 1
342 int p0
= res
->prob
[n
][ctx0
][0];
343 const uint16_t* t
= res
->cost
[n
][ctx0
];
347 return VP8BitCost(0, p0
);
349 cost
= VP8BitCost(1, p0
);
350 for (; n
< res
->last
; ++n
) {
351 const int v
= abs(res
->coeffs
[n
]);
352 const int b
= VP8EncBands
[n
+ 1];
353 const int ctx
= (v
>= 2) ? 2 : v
;
354 cost
+= VP8LevelCost(t
, v
);
355 t
= res
->cost
[b
][ctx
];
356 // the masking trick is faster than "if (v) cost += ..." with clang
357 cost
+= (v
? ~0U : 0) & VP8BitCost(1, res
->prob
[b
][ctx
][0]);
359 // Last coefficient is always non-zero
361 const int v
= abs(res
->coeffs
[n
]);
363 cost
+= VP8LevelCost(t
, v
);
365 const int b
= VP8EncBands
[n
+ 1];
366 const int ctx
= (v
== 1) ? 1 : 2;
367 const int last_p0
= res
->prob
[b
][ctx
][0];
368 cost
+= VP8BitCost(0, last_p0
);
374 int VP8GetCostLuma4(VP8EncIterator
* const it
, const int16_t levels
[16]) {
375 const int x
= (it
->i4_
& 3), y
= (it
->i4_
>> 2);
377 VP8Encoder
* const enc
= it
->enc_
;
381 InitResidual(0, 3, enc
, &res
);
382 ctx
= it
->top_nz_
[x
] + it
->left_nz_
[y
];
383 SetResidualCoeffs(levels
, &res
);
384 R
+= GetResidualCost(ctx
, &res
);
388 int VP8GetCostLuma16(VP8EncIterator
* const it
, const VP8ModeScore
* const rd
) {
390 VP8Encoder
* const enc
= it
->enc_
;
394 VP8IteratorNzToBytes(it
); // re-import the non-zero context
397 InitResidual(0, 1, enc
, &res
);
398 SetResidualCoeffs(rd
->y_dc_levels
, &res
);
399 R
+= GetResidualCost(it
->top_nz_
[8] + it
->left_nz_
[8], &res
);
402 InitResidual(1, 0, enc
, &res
);
403 for (y
= 0; y
< 4; ++y
) {
404 for (x
= 0; x
< 4; ++x
) {
405 const int ctx
= it
->top_nz_
[x
] + it
->left_nz_
[y
];
406 SetResidualCoeffs(rd
->y_ac_levels
[x
+ y
* 4], &res
);
407 R
+= GetResidualCost(ctx
, &res
);
408 it
->top_nz_
[x
] = it
->left_nz_
[y
] = (res
.last
>= 0);
414 int VP8GetCostUV(VP8EncIterator
* const it
, const VP8ModeScore
* const rd
) {
416 VP8Encoder
* const enc
= it
->enc_
;
420 VP8IteratorNzToBytes(it
); // re-import the non-zero context
422 InitResidual(0, 2, enc
, &res
);
423 for (ch
= 0; ch
<= 2; ch
+= 2) {
424 for (y
= 0; y
< 2; ++y
) {
425 for (x
= 0; x
< 2; ++x
) {
426 const int ctx
= it
->top_nz_
[4 + ch
+ x
] + it
->left_nz_
[4 + ch
+ y
];
427 SetResidualCoeffs(rd
->uv_levels
[ch
* 2 + x
+ y
* 2], &res
);
428 R
+= GetResidualCost(ctx
, &res
);
429 it
->top_nz_
[4 + ch
+ x
] = it
->left_nz_
[4 + ch
+ y
] = (res
.last
>= 0);
436 //------------------------------------------------------------------------------
437 // Coefficient coding
439 static int PutCoeffs(VP8BitWriter
* const bw
, int ctx
, const VP8Residual
* res
) {
441 // should be prob[VP8EncBands[n]], but it's equivalent for n=0 or 1
442 const uint8_t* p
= res
->prob
[n
][ctx
];
443 if (!VP8PutBit(bw
, res
->last
>= 0, p
[0])) {
448 const int c
= res
->coeffs
[n
++];
449 const int sign
= c
< 0;
450 int v
= sign
? -c
: c
;
451 if (!VP8PutBit(bw
, v
!= 0, p
[1])) {
452 p
= res
->prob
[VP8EncBands
[n
]][0];
455 if (!VP8PutBit(bw
, v
> 1, p
[2])) {
456 p
= res
->prob
[VP8EncBands
[n
]][1];
458 if (!VP8PutBit(bw
, v
> 4, p
[3])) {
459 if (VP8PutBit(bw
, v
!= 2, p
[4]))
460 VP8PutBit(bw
, v
== 4, p
[5]);
461 } else if (!VP8PutBit(bw
, v
> 10, p
[6])) {
462 if (!VP8PutBit(bw
, v
> 6, p
[7])) {
463 VP8PutBit(bw
, v
== 6, 159);
465 VP8PutBit(bw
, v
>= 9, 165);
466 VP8PutBit(bw
, !(v
& 1), 145);
471 if (v
< 3 + (8 << 1)) { // VP8Cat3 (3b)
472 VP8PutBit(bw
, 0, p
[8]);
473 VP8PutBit(bw
, 0, p
[9]);
477 } else if (v
< 3 + (8 << 2)) { // VP8Cat4 (4b)
478 VP8PutBit(bw
, 0, p
[8]);
479 VP8PutBit(bw
, 1, p
[9]);
483 } else if (v
< 3 + (8 << 3)) { // VP8Cat5 (5b)
484 VP8PutBit(bw
, 1, p
[8]);
485 VP8PutBit(bw
, 0, p
[10]);
489 } else { // VP8Cat6 (11b)
490 VP8PutBit(bw
, 1, p
[8]);
491 VP8PutBit(bw
, 1, p
[10]);
497 VP8PutBit(bw
, !!(v
& mask
), *tab
++);
501 p
= res
->prob
[VP8EncBands
[n
]][2];
503 VP8PutBitUniform(bw
, sign
);
504 if (n
== 16 || !VP8PutBit(bw
, n
<= res
->last
, p
[0])) {
511 static void CodeResiduals(VP8BitWriter
* const bw
, VP8EncIterator
* const it
,
512 const VP8ModeScore
* const rd
) {
515 uint64_t pos1
, pos2
, pos3
;
516 const int i16
= (it
->mb_
->type_
== 1);
517 const int segment
= it
->mb_
->segment_
;
518 VP8Encoder
* const enc
= it
->enc_
;
520 VP8IteratorNzToBytes(it
);
522 pos1
= VP8BitWriterPos(bw
);
524 InitResidual(0, 1, enc
, &res
);
525 SetResidualCoeffs(rd
->y_dc_levels
, &res
);
526 it
->top_nz_
[8] = it
->left_nz_
[8] =
527 PutCoeffs(bw
, it
->top_nz_
[8] + it
->left_nz_
[8], &res
);
528 InitResidual(1, 0, enc
, &res
);
530 InitResidual(0, 3, enc
, &res
);
534 for (y
= 0; y
< 4; ++y
) {
535 for (x
= 0; x
< 4; ++x
) {
536 const int ctx
= it
->top_nz_
[x
] + it
->left_nz_
[y
];
537 SetResidualCoeffs(rd
->y_ac_levels
[x
+ y
* 4], &res
);
538 it
->top_nz_
[x
] = it
->left_nz_
[y
] = PutCoeffs(bw
, ctx
, &res
);
541 pos2
= VP8BitWriterPos(bw
);
544 InitResidual(0, 2, enc
, &res
);
545 for (ch
= 0; ch
<= 2; ch
+= 2) {
546 for (y
= 0; y
< 2; ++y
) {
547 for (x
= 0; x
< 2; ++x
) {
548 const int ctx
= it
->top_nz_
[4 + ch
+ x
] + it
->left_nz_
[4 + ch
+ y
];
549 SetResidualCoeffs(rd
->uv_levels
[ch
* 2 + x
+ y
* 2], &res
);
550 it
->top_nz_
[4 + ch
+ x
] = it
->left_nz_
[4 + ch
+ y
] =
551 PutCoeffs(bw
, ctx
, &res
);
555 pos3
= VP8BitWriterPos(bw
);
556 it
->luma_bits_
= pos2
- pos1
;
557 it
->uv_bits_
= pos3
- pos2
;
558 it
->bit_count_
[segment
][i16
] += it
->luma_bits_
;
559 it
->bit_count_
[segment
][2] += it
->uv_bits_
;
560 VP8IteratorBytesToNz(it
);
563 // Same as CodeResiduals, but doesn't actually write anything.
564 // Instead, it just records the event distribution.
565 static void RecordResiduals(VP8EncIterator
* const it
,
566 const VP8ModeScore
* const rd
) {
569 VP8Encoder
* const enc
= it
->enc_
;
571 VP8IteratorNzToBytes(it
);
573 if (it
->mb_
->type_
== 1) { // i16x16
574 InitResidual(0, 1, enc
, &res
);
575 SetResidualCoeffs(rd
->y_dc_levels
, &res
);
576 it
->top_nz_
[8] = it
->left_nz_
[8] =
577 RecordCoeffs(it
->top_nz_
[8] + it
->left_nz_
[8], &res
);
578 InitResidual(1, 0, enc
, &res
);
580 InitResidual(0, 3, enc
, &res
);
584 for (y
= 0; y
< 4; ++y
) {
585 for (x
= 0; x
< 4; ++x
) {
586 const int ctx
= it
->top_nz_
[x
] + it
->left_nz_
[y
];
587 SetResidualCoeffs(rd
->y_ac_levels
[x
+ y
* 4], &res
);
588 it
->top_nz_
[x
] = it
->left_nz_
[y
] = RecordCoeffs(ctx
, &res
);
593 InitResidual(0, 2, enc
, &res
);
594 for (ch
= 0; ch
<= 2; ch
+= 2) {
595 for (y
= 0; y
< 2; ++y
) {
596 for (x
= 0; x
< 2; ++x
) {
597 const int ctx
= it
->top_nz_
[4 + ch
+ x
] + it
->left_nz_
[4 + ch
+ y
];
598 SetResidualCoeffs(rd
->uv_levels
[ch
* 2 + x
+ y
* 2], &res
);
599 it
->top_nz_
[4 + ch
+ x
] = it
->left_nz_
[4 + ch
+ y
] =
600 RecordCoeffs(ctx
, &res
);
605 VP8IteratorBytesToNz(it
);
608 //------------------------------------------------------------------------------
611 #if !defined(DISABLE_TOKEN_BUFFER)
613 static void RecordTokens(VP8EncIterator
* const it
, const VP8ModeScore
* const rd
,
614 VP8TBuffer
* const tokens
) {
617 VP8Encoder
* const enc
= it
->enc_
;
619 VP8IteratorNzToBytes(it
);
620 if (it
->mb_
->type_
== 1) { // i16x16
621 const int ctx
= it
->top_nz_
[8] + it
->left_nz_
[8];
622 InitResidual(0, 1, enc
, &res
);
623 SetResidualCoeffs(rd
->y_dc_levels
, &res
);
624 it
->top_nz_
[8] = it
->left_nz_
[8] =
625 VP8RecordCoeffTokens(ctx
, 1,
626 res
.first
, res
.last
, res
.coeffs
, tokens
);
627 RecordCoeffs(ctx
, &res
);
628 InitResidual(1, 0, enc
, &res
);
630 InitResidual(0, 3, enc
, &res
);
634 for (y
= 0; y
< 4; ++y
) {
635 for (x
= 0; x
< 4; ++x
) {
636 const int ctx
= it
->top_nz_
[x
] + it
->left_nz_
[y
];
637 SetResidualCoeffs(rd
->y_ac_levels
[x
+ y
* 4], &res
);
638 it
->top_nz_
[x
] = it
->left_nz_
[y
] =
639 VP8RecordCoeffTokens(ctx
, res
.coeff_type
,
640 res
.first
, res
.last
, res
.coeffs
, tokens
);
641 RecordCoeffs(ctx
, &res
);
646 InitResidual(0, 2, enc
, &res
);
647 for (ch
= 0; ch
<= 2; ch
+= 2) {
648 for (y
= 0; y
< 2; ++y
) {
649 for (x
= 0; x
< 2; ++x
) {
650 const int ctx
= it
->top_nz_
[4 + ch
+ x
] + it
->left_nz_
[4 + ch
+ y
];
651 SetResidualCoeffs(rd
->uv_levels
[ch
* 2 + x
+ y
* 2], &res
);
652 it
->top_nz_
[4 + ch
+ x
] = it
->left_nz_
[4 + ch
+ y
] =
653 VP8RecordCoeffTokens(ctx
, 2,
654 res
.first
, res
.last
, res
.coeffs
, tokens
);
655 RecordCoeffs(ctx
, &res
);
659 VP8IteratorBytesToNz(it
);
662 #endif // !DISABLE_TOKEN_BUFFER
664 //------------------------------------------------------------------------------
665 // ExtraInfo map / Debug function
668 static void SetBlock(uint8_t* p
, int value
, int size
) {
670 for (y
= 0; y
< size
; ++y
) {
671 memset(p
, value
, size
);
677 static void ResetSSE(VP8Encoder
* const enc
) {
681 // Note: enc->sse_[3] is managed by alpha.c
685 static void StoreSSE(const VP8EncIterator
* const it
) {
686 VP8Encoder
* const enc
= it
->enc_
;
687 const uint8_t* const in
= it
->yuv_in_
;
688 const uint8_t* const out
= it
->yuv_out_
;
689 // Note: not totally accurate at boundary. And doesn't include in-loop filter.
690 enc
->sse_
[0] += VP8SSE16x16(in
+ Y_OFF
, out
+ Y_OFF
);
691 enc
->sse_
[1] += VP8SSE8x8(in
+ U_OFF
, out
+ U_OFF
);
692 enc
->sse_
[2] += VP8SSE8x8(in
+ V_OFF
, out
+ V_OFF
);
693 enc
->sse_count_
+= 16 * 16;
696 static void StoreSideInfo(const VP8EncIterator
* const it
) {
697 VP8Encoder
* const enc
= it
->enc_
;
698 const VP8MBInfo
* const mb
= it
->mb_
;
699 WebPPicture
* const pic
= enc
->pic_
;
701 if (pic
->stats
!= NULL
) {
703 enc
->block_count_
[0] += (mb
->type_
== 0);
704 enc
->block_count_
[1] += (mb
->type_
== 1);
705 enc
->block_count_
[2] += (mb
->skip_
!= 0);
708 if (pic
->extra_info
!= NULL
) {
709 uint8_t* const info
= &pic
->extra_info
[it
->x_
+ it
->y_
* enc
->mb_w_
];
710 switch (pic
->extra_info_type
) {
711 case 1: *info
= mb
->type_
; break;
712 case 2: *info
= mb
->segment_
; break;
713 case 3: *info
= enc
->dqm_
[mb
->segment_
].quant_
; break;
714 case 4: *info
= (mb
->type_
== 1) ? it
->preds_
[0] : 0xff; break;
715 case 5: *info
= mb
->uv_mode_
; break;
717 const int b
= (int)((it
->luma_bits_
+ it
->uv_bits_
+ 7) >> 3);
718 *info
= (b
> 255) ? 255 : b
; break;
720 case 7: *info
= mb
->alpha_
; break;
721 default: *info
= 0; break;
724 #if SEGMENT_VISU // visualize segments and prediction modes
725 SetBlock(it
->yuv_out_
+ Y_OFF
, mb
->segment_
* 64, 16);
726 SetBlock(it
->yuv_out_
+ U_OFF
, it
->preds_
[0] * 64, 8);
727 SetBlock(it
->yuv_out_
+ V_OFF
, mb
->uv_mode_
* 64, 8);
731 static double GetPSNR(uint64_t mse
, uint64_t size
) {
732 return (mse
> 0 && size
> 0) ? 10. * log10(255. * 255. * size
/ mse
) : 99;
735 //------------------------------------------------------------------------------
736 // StatLoop(): only collect statistics (number of skips, token usage, ...).
737 // This is used for deciding optimal probabilities. It also modifies the
738 // quantizer value if some target (size, PSNR) was specified.
740 static void SetLoopParams(VP8Encoder
* const enc
, float q
) {
741 // Make sure the quality parameter is inside valid bounds
742 q
= Clamp(q
, 0.f
, 100.f
);
744 VP8SetSegmentParams(enc
, q
); // setup segment quantizations and filters
745 SetSegmentProbas(enc
); // compute segment probabilities
751 static uint64_t OneStatPass(VP8Encoder
* const enc
, VP8RDLevel rd_opt
,
752 int nb_mbs
, int percent_delta
,
753 PassStats
* const s
) {
756 uint64_t size_p0
= 0;
757 uint64_t distortion
= 0;
758 const uint64_t pixel_count
= nb_mbs
* 384;
760 VP8IteratorInit(enc
, &it
);
761 SetLoopParams(enc
, s
->q
);
764 VP8IteratorImport(&it
, NULL
);
765 if (VP8Decimate(&it
, &info
, rd_opt
)) {
766 // Just record the number of skips and act like skip_proba is not used.
767 enc
->proba_
.nb_skip_
++;
769 RecordResiduals(&it
, &info
);
770 size
+= info
.R
+ info
.H
;
772 distortion
+= info
.D
;
773 if (percent_delta
&& !VP8IteratorProgress(&it
, percent_delta
))
775 VP8IteratorSaveBoundary(&it
);
776 } while (VP8IteratorNext(&it
) && --nb_mbs
> 0);
778 size_p0
+= enc
->segment_hdr_
.size_
;
779 if (s
->do_size_search
) {
780 size
+= FinalizeSkipProba(enc
);
781 size
+= FinalizeTokenProbas(&enc
->proba_
);
782 size
= ((size
+ size_p0
+ 1024) >> 11) + HEADER_SIZE_ESTIMATE
;
783 s
->value
= (double)size
;
785 s
->value
= GetPSNR(distortion
, pixel_count
);
790 static int StatLoop(VP8Encoder
* const enc
) {
791 const int method
= enc
->method_
;
792 const int do_search
= enc
->do_search_
;
793 const int fast_probe
= ((method
== 0 || method
== 3) && !do_search
);
794 int num_pass_left
= enc
->config_
->pass
;
795 const int task_percent
= 20;
796 const int percent_per_pass
=
797 (task_percent
+ num_pass_left
/ 2) / num_pass_left
;
798 const int final_percent
= enc
->percent_
+ task_percent
;
799 const VP8RDLevel rd_opt
=
800 (method
>= 3 || do_search
) ? RD_OPT_BASIC
: RD_OPT_NONE
;
801 int nb_mbs
= enc
->mb_w_
* enc
->mb_h_
;
804 InitPassStats(enc
, &stats
);
805 ResetTokenStats(enc
);
807 // Fast mode: quick analysis pass over few mbs. Better than nothing.
809 if (method
== 3) { // we need more stats for method 3 to be reliable.
810 nb_mbs
= (nb_mbs
> 200) ? nb_mbs
>> 1 : 100;
812 nb_mbs
= (nb_mbs
> 200) ? nb_mbs
>> 2 : 50;
816 while (num_pass_left
-- > 0) {
817 const int is_last_pass
= (fabs(stats
.dq
) <= DQ_LIMIT
) ||
818 (num_pass_left
== 0) ||
819 (enc
->max_i4_header_bits_
== 0);
820 const uint64_t size_p0
=
821 OneStatPass(enc
, rd_opt
, nb_mbs
, percent_per_pass
, &stats
);
822 if (size_p0
== 0) return 0;
823 #if (DEBUG_SEARCH > 0)
824 printf("#%d value:%.1lf -> %.1lf q:%.2f -> %.2f\n",
825 num_pass_left
, stats
.last_value
, stats
.value
, stats
.last_q
, stats
.q
);
827 if (enc
->max_i4_header_bits_
> 0 && size_p0
> PARTITION0_SIZE_LIMIT
) {
829 enc
->max_i4_header_bits_
>>= 1; // strengthen header bit limitation...
830 continue; // ...and start over
835 // If no target size: just do several pass without changing 'q'
837 ComputeNextQ(&stats
);
838 if (fabs(stats
.dq
) <= DQ_LIMIT
) break;
841 if (!do_search
|| !stats
.do_size_search
) {
842 // Need to finalize probas now, since it wasn't done during the search.
843 FinalizeSkipProba(enc
);
844 FinalizeTokenProbas(&enc
->proba_
);
846 VP8CalculateLevelCosts(&enc
->proba_
); // finalize costs
847 return WebPReportProgress(enc
->pic_
, final_percent
, &enc
->percent_
);
850 //------------------------------------------------------------------------------
854 static const int kAverageBytesPerMB
[8] = { 50, 24, 16, 9, 7, 5, 3, 2 };
856 static int PreLoopInitialize(VP8Encoder
* const enc
) {
859 const int average_bytes_per_MB
= kAverageBytesPerMB
[enc
->base_quant_
>> 4];
860 const int bytes_per_parts
=
861 enc
->mb_w_
* enc
->mb_h_
* average_bytes_per_MB
/ enc
->num_parts_
;
862 // Initialize the bit-writers
863 for (p
= 0; ok
&& p
< enc
->num_parts_
; ++p
) {
864 ok
= VP8BitWriterInit(enc
->parts_
+ p
, bytes_per_parts
);
866 if (!ok
) VP8EncFreeBitWriters(enc
); // malloc error occurred
870 static int PostLoopFinalize(VP8EncIterator
* const it
, int ok
) {
871 VP8Encoder
* const enc
= it
->enc_
;
872 if (ok
) { // Finalize the partitions, check for extra errors.
874 for (p
= 0; p
< enc
->num_parts_
; ++p
) {
875 VP8BitWriterFinish(enc
->parts_
+ p
);
876 ok
&= !enc
->parts_
[p
].error_
;
880 if (ok
) { // All good. Finish up.
881 if (enc
->pic_
->stats
!= NULL
) { // finalize byte counters...
883 for (i
= 0; i
<= 2; ++i
) {
884 for (s
= 0; s
< NUM_MB_SEGMENTS
; ++s
) {
885 enc
->residual_bytes_
[i
][s
] = (int)((it
->bit_count_
[s
][i
] + 7) >> 3);
889 VP8AdjustFilterStrength(it
); // ...and store filter stats.
891 // Something bad happened -> need to do some memory cleanup.
892 VP8EncFreeBitWriters(enc
);
897 //------------------------------------------------------------------------------
898 // VP8EncLoop(): does the final bitstream coding.
900 static void ResetAfterSkip(VP8EncIterator
* const it
) {
901 if (it
->mb_
->type_
== 1) {
902 *it
->nz_
= 0; // reset all predictors
905 *it
->nz_
&= (1 << 24); // preserve the dc_nz bit
909 int VP8EncLoop(VP8Encoder
* const enc
) {
911 int ok
= PreLoopInitialize(enc
);
914 StatLoop(enc
); // stats-collection loop
916 VP8IteratorInit(enc
, &it
);
920 const int dont_use_skip
= !enc
->proba_
.use_skip_proba_
;
921 const VP8RDLevel rd_opt
= enc
->rd_opt_level_
;
923 VP8IteratorImport(&it
, NULL
);
924 // Warning! order is important: first call VP8Decimate() and
925 // *then* decide how to code the skip decision if there's one.
926 if (!VP8Decimate(&it
, &info
, rd_opt
) || dont_use_skip
) {
927 CodeResiduals(it
.bw_
, &it
, &info
);
928 } else { // reset predictors after a skip
931 #ifdef WEBP_EXPERIMENTAL_FEATURES
932 if (enc
->use_layer_
) {
933 VP8EncCodeLayerBlock(&it
);
937 VP8StoreFilterStats(&it
);
938 VP8IteratorExport(&it
);
939 ok
= VP8IteratorProgress(&it
, 20);
940 VP8IteratorSaveBoundary(&it
);
941 } while (ok
&& VP8IteratorNext(&it
));
943 return PostLoopFinalize(&it
, ok
);
946 //------------------------------------------------------------------------------
947 // Single pass using Token Buffer.
949 #if !defined(DISABLE_TOKEN_BUFFER)
951 #define MIN_COUNT 96 // minimum number of macroblocks before updating stats
953 int VP8EncTokenLoop(VP8Encoder
* const enc
) {
954 // Roughly refresh the proba eight times per pass
955 int max_count
= (enc
->mb_w_
* enc
->mb_h_
) >> 3;
956 int num_pass_left
= enc
->config_
->pass
;
957 const int do_search
= enc
->do_search_
;
959 VP8Proba
* const proba
= &enc
->proba_
;
960 const VP8RDLevel rd_opt
= enc
->rd_opt_level_
;
961 const uint64_t pixel_count
= enc
->mb_w_
* enc
->mb_h_
* 384;
965 InitPassStats(enc
, &stats
);
966 ok
= PreLoopInitialize(enc
);
969 if (max_count
< MIN_COUNT
) max_count
= MIN_COUNT
;
971 assert(enc
->num_parts_
== 1);
972 assert(enc
->use_tokens_
);
973 assert(proba
->use_skip_proba_
== 0);
974 assert(rd_opt
>= RD_OPT_BASIC
); // otherwise, token-buffer won't be useful
975 assert(num_pass_left
> 0);
977 while (ok
&& num_pass_left
-- > 0) {
978 const int is_last_pass
= (fabs(stats
.dq
) <= DQ_LIMIT
) ||
979 (num_pass_left
== 0) ||
980 (enc
->max_i4_header_bits_
== 0);
981 uint64_t size_p0
= 0;
982 uint64_t distortion
= 0;
984 VP8IteratorInit(enc
, &it
);
985 SetLoopParams(enc
, stats
.q
);
987 ResetTokenStats(enc
);
988 VP8InitFilter(&it
); // don't collect stats until last pass (too costly)
990 VP8TBufferClear(&enc
->tokens_
);
993 VP8IteratorImport(&it
, NULL
);
995 FinalizeTokenProbas(proba
);
996 VP8CalculateLevelCosts(proba
); // refresh cost tables for rd-opt
999 VP8Decimate(&it
, &info
, rd_opt
);
1000 RecordTokens(&it
, &info
, &enc
->tokens_
);
1002 distortion
+= info
.D
;
1003 #ifdef WEBP_EXPERIMENTAL_FEATURES
1004 if (enc
->use_layer_
) {
1005 VP8EncCodeLayerBlock(&it
);
1010 VP8StoreFilterStats(&it
);
1011 VP8IteratorExport(&it
);
1012 ok
= VP8IteratorProgress(&it
, 20);
1014 VP8IteratorSaveBoundary(&it
);
1015 } while (ok
&& VP8IteratorNext(&it
));
1018 size_p0
+= enc
->segment_hdr_
.size_
;
1019 if (stats
.do_size_search
) {
1020 uint64_t size
= FinalizeTokenProbas(&enc
->proba_
);
1021 size
+= VP8EstimateTokenSize(&enc
->tokens_
,
1022 (const uint8_t*)proba
->coeffs_
);
1023 size
= (size
+ size_p0
+ 1024) >> 11; // -> size in bytes
1024 size
+= HEADER_SIZE_ESTIMATE
;
1025 stats
.value
= (double)size
;
1026 } else { // compute and store PSNR
1027 stats
.value
= GetPSNR(distortion
, pixel_count
);
1030 #if (DEBUG_SEARCH > 0)
1031 printf("#%2d metric:%.1lf -> %.1lf last_q=%.2lf q=%.2lf dq=%.2lf\n",
1032 num_pass_left
, stats
.last_value
, stats
.value
,
1033 stats
.last_q
, stats
.q
, stats
.dq
);
1035 if (size_p0
> PARTITION0_SIZE_LIMIT
) {
1037 enc
->max_i4_header_bits_
>>= 1; // strengthen header bit limitation...
1038 continue; // ...and start over
1044 ComputeNextQ(&stats
); // Adjust q
1048 if (!stats
.do_size_search
) {
1049 FinalizeTokenProbas(&enc
->proba_
);
1051 ok
= VP8EmitTokens(&enc
->tokens_
, enc
->parts_
+ 0,
1052 (const uint8_t*)proba
->coeffs_
, 1);
1054 ok
= ok
&& WebPReportProgress(enc
->pic_
, enc
->percent_
+ 20, &enc
->percent_
);
1055 return PostLoopFinalize(&it
, ok
);
1060 int VP8EncTokenLoop(VP8Encoder
* const enc
) {
1062 return 0; // we shouldn't be here.
1065 #endif // DISABLE_TOKEN_BUFFER
1067 //------------------------------------------------------------------------------