Coverage Report

Created: 2026-02-14 06:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libvpx/vp8/encoder/bitstream.c
Line
Count
Source
1
/*
2
 *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3
 *
4
 *  Use of this source code is governed by a BSD-style license
5
 *  that can be found in the LICENSE file in the root of the source
6
 *  tree. An additional intellectual property rights grant can be found
7
 *  in the file PATENTS.  All contributing project authors may
8
 *  be found in the AUTHORS file in the root of the source tree.
9
 */
10
11
#include "vp8/common/header.h"
12
#include "encodemv.h"
13
#include "vp8/common/entropymode.h"
14
#include "vp8/common/findnearmv.h"
15
#include "mcomp.h"
16
#include "vp8/common/systemdependent.h"
17
#include <assert.h>
18
#include <stdio.h>
19
#include <limits.h>
20
#include "vpx/vpx_encoder.h"
21
#include "vpx_mem/vpx_mem.h"
22
#include "vpx_ports/compiler_attributes.h"
23
#include "vpx_ports/system_state.h"
24
#include "bitstream.h"
25
26
#include "defaultcoefcounts.h"
27
#include "vp8/common/common.h"
28
29
const int vp8cx_base_skip_false_prob[128] = {
30
  255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
31
  255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
32
  255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
33
  255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 251, 248, 244, 240,
34
  236, 232, 229, 225, 221, 217, 213, 208, 204, 199, 194, 190, 187, 183, 179,
35
  175, 172, 168, 164, 160, 157, 153, 149, 145, 142, 138, 134, 130, 127, 124,
36
  120, 117, 114, 110, 107, 104, 101, 98,  95,  92,  89,  86,  83,  80,  77,
37
  74,  71,  68,  65,  62,  59,  56,  53,  50,  47,  44,  41,  38,  35,  32,
38
  30,  28,  26,  24,  22,  20,  18,  16,
39
};
40
41
#if defined(SECTIONBITS_OUTPUT)
42
unsigned __int64 Sectionbits[500];
43
#endif
44
45
#ifdef MODE_STATS
46
int count_mb_seg[4] = { 0, 0, 0, 0 };
47
#endif
48
49
static void update_mode(vp8_writer *const w, int n, vp8_token tok[/* n */],
50
                        vp8_tree tree, vp8_prob Pnew[/* n-1 */],
51
                        vp8_prob Pcur[/* n-1 */],
52
                        unsigned int bct[/* n-1 */][2],
53
192k
                        const unsigned int num_events[/* n */]) {
54
192k
  unsigned int new_b = 0, old_b = 0;
55
192k
  int i = 0;
56
57
192k
  vp8_tree_probs_from_distribution(n--, tok, tree, Pnew, bct, num_events, 256,
58
192k
                                   1);
59
60
674k
  do {
61
674k
    new_b += vp8_cost_branch(bct[i], Pnew[i]);
62
674k
    old_b += vp8_cost_branch(bct[i], Pcur[i]);
63
674k
  } while (++i < n);
64
65
192k
  if (new_b + (n << 8) < old_b) {
66
43
    int j = 0;
67
68
43
    vp8_write_bit(w, 1);
69
70
149
    do {
71
149
      const vp8_prob p = Pnew[j];
72
73
149
      vp8_write_literal(w, Pcur[j] = p ? p : 1, 8);
74
149
    } while (++j < n);
75
43
  } else
76
192k
    vp8_write_bit(w, 0);
77
192k
}
78
79
96.2k
static void update_mbintra_mode_probs(VP8_COMP *cpi) {
80
96.2k
  VP8_COMMON *const x = &cpi->common;
81
82
96.2k
  vp8_writer *const w = cpi->bc;
83
84
96.2k
  {
85
96.2k
    vp8_prob Pnew[VP8_YMODES - 1];
86
96.2k
    unsigned int bct[VP8_YMODES - 1][2];
87
88
96.2k
    update_mode(w, VP8_YMODES, vp8_ymode_encodings, vp8_ymode_tree, Pnew,
89
96.2k
                x->fc.ymode_prob, bct, (unsigned int *)cpi->mb.ymode_count);
90
96.2k
  }
91
96.2k
  {
92
96.2k
    vp8_prob Pnew[VP8_UV_MODES - 1];
93
96.2k
    unsigned int bct[VP8_UV_MODES - 1][2];
94
95
96.2k
    update_mode(w, VP8_UV_MODES, vp8_uv_mode_encodings, vp8_uv_mode_tree, Pnew,
96
96.2k
                x->fc.uv_mode_prob, bct, (unsigned int *)cpi->mb.uv_mode_count);
97
96.2k
  }
98
96.2k
}
99
100
629k
static void write_ymode(vp8_writer *bc, int m, const vp8_prob *p) {
101
629k
  vp8_write_token(bc, vp8_ymode_tree, p, vp8_ymode_encodings + m);
102
629k
}
103
104
999k
static void kfwrite_ymode(vp8_writer *bc, int m, const vp8_prob *p) {
105
999k
  vp8_write_token(bc, vp8_kf_ymode_tree, p, vp8_kf_ymode_encodings + m);
106
999k
}
107
108
1.62M
static void write_uv_mode(vp8_writer *bc, int m, const vp8_prob *p) {
109
1.62M
  vp8_write_token(bc, vp8_uv_mode_tree, p, vp8_uv_mode_encodings + m);
110
1.62M
}
111
112
12.5M
static void write_bmode(vp8_writer *bc, int m, const vp8_prob *p) {
113
12.5M
  vp8_write_token(bc, vp8_bmode_tree, p, vp8_bmode_encodings + m);
114
12.5M
}
115
116
114k
static void write_split(vp8_writer *bc, int x) {
117
114k
  vp8_write_token(bc, vp8_mbsplit_tree, vp8_mbsplit_probs,
118
114k
                  vp8_mbsplit_encodings + x);
119
114k
}
120
121
void VPX_NO_UNSIGNED_SHIFT_CHECK vp8_pack_tokens(vp8_writer *w,
122
                                                 const TOKENEXTRA *p,
123
118k
                                                 int xcount) {
124
118k
  const TOKENEXTRA *stop = p + xcount;
125
118k
  unsigned int split;
126
118k
  int shift;
127
118k
  int count = w->count;
128
118k
  unsigned int range = w->range;
129
118k
  unsigned int lowvalue = w->lowvalue;
130
131
372M
  while (p < stop) {
132
372M
    const int t = p->Token;
133
372M
    vp8_token *a = vp8_coef_encodings + t;
134
372M
    const vp8_extra_bit_struct *b = vp8_extra_bits + t;
135
372M
    int i = 0;
136
372M
    const unsigned char *pp = p->context_tree;
137
372M
    int v = a->value;
138
372M
    int n = a->Len;
139
140
372M
    if (p->skip_eob_node) {
141
53.0M
      n--;
142
53.0M
      i = 2;
143
53.0M
    }
144
145
1.83G
    do {
146
1.83G
      const int bb = (v >> --n) & 1;
147
1.83G
      split = 1 + (((range - 1) * pp[i >> 1]) >> 8);
148
1.83G
      i = vp8_coef_tree[i + bb];
149
150
1.83G
      if (bb) {
151
1.33G
        lowvalue += split;
152
1.33G
        range = range - split;
153
1.33G
      } else {
154
498M
        range = split;
155
498M
      }
156
157
1.83G
      shift = vp8_norm[range];
158
1.83G
      range <<= shift;
159
1.83G
      count += shift;
160
161
1.83G
      if (count >= 0) {
162
125M
        int offset = shift - count;
163
164
125M
        if ((lowvalue << (offset - 1)) & 0x80000000) {
165
778
          int x = w->pos - 1;
166
167
1.01k
          while (x >= 0 && w->buffer[x] == 0xff) {
168
237
            w->buffer[x] = (unsigned char)0;
169
237
            x--;
170
237
          }
171
172
778
          w->buffer[x] += 1;
173
778
        }
174
175
125M
        validate_buffer(w->buffer + w->pos, 1, w->buffer_end, w->error);
176
177
125M
        w->buffer[w->pos++] = (lowvalue >> (24 - offset)) & 0xff;
178
125M
        shift = count;
179
125M
        lowvalue = (int)(((uint64_t)lowvalue << offset) & 0xffffff);
180
125M
        count -= 8;
181
125M
      }
182
183
1.83G
      lowvalue <<= shift;
184
1.83G
    } while (n);
185
186
372M
    if (b->base_val) {
187
298M
      const int e = p->Extra, L = b->Len;
188
189
298M
      if (L) {
190
195M
        const unsigned char *proba = b->prob;
191
195M
        const int v2 = e >> 1;
192
195M
        int n2 = L; /* number of bits in v2, assumed nonzero */
193
195M
        i = 0;
194
195
588M
        do {
196
588M
          const int bb = (v2 >> --n2) & 1;
197
588M
          split = 1 + (((range - 1) * proba[i >> 1]) >> 8);
198
588M
          i = b->tree[i + bb];
199
200
588M
          if (bb) {
201
253M
            lowvalue += split;
202
253M
            range = range - split;
203
334M
          } else {
204
334M
            range = split;
205
334M
          }
206
207
588M
          shift = vp8_norm[range];
208
588M
          range <<= shift;
209
588M
          count += shift;
210
211
588M
          if (count >= 0) {
212
71.5M
            int offset = shift - count;
213
214
71.5M
            if ((lowvalue << (offset - 1)) & 0x80000000) {
215
455
              int x = w->pos - 1;
216
217
561
              while (x >= 0 && w->buffer[x] == 0xff) {
218
106
                w->buffer[x] = (unsigned char)0;
219
106
                x--;
220
106
              }
221
222
455
              w->buffer[x] += 1;
223
455
            }
224
225
71.5M
            validate_buffer(w->buffer + w->pos, 1, w->buffer_end, w->error);
226
227
71.5M
            w->buffer[w->pos++] = (lowvalue >> (24 - offset)) & 0xff;
228
71.5M
            shift = count;
229
71.5M
            lowvalue = (int)(((uint64_t)lowvalue << offset) & 0xffffff);
230
71.5M
            count -= 8;
231
71.5M
          }
232
233
588M
          lowvalue <<= shift;
234
588M
        } while (n2);
235
195M
      }
236
237
298M
      {
238
298M
        split = (range + 1) >> 1;
239
240
298M
        if (e & 1) {
241
149M
          lowvalue += split;
242
149M
          range = range - split;
243
149M
        } else {
244
149M
          range = split;
245
149M
        }
246
247
298M
        range <<= 1;
248
249
298M
        if ((lowvalue & 0x80000000)) {
250
373
          int x = w->pos - 1;
251
252
717
          while (x >= 0 && w->buffer[x] == 0xff) {
253
344
            w->buffer[x] = (unsigned char)0;
254
344
            x--;
255
344
          }
256
257
373
          w->buffer[x] += 1;
258
373
        }
259
260
298M
        lowvalue <<= 1;
261
262
298M
        if (!++count) {
263
37.3M
          count = -8;
264
265
37.3M
          validate_buffer(w->buffer + w->pos, 1, w->buffer_end, w->error);
266
267
37.3M
          w->buffer[w->pos++] = (lowvalue >> 24);
268
37.3M
          lowvalue &= 0xffffff;
269
37.3M
        }
270
298M
      }
271
298M
    }
272
273
372M
    ++p;
274
372M
  }
275
276
118k
  w->count = count;
277
118k
  w->lowvalue = lowvalue;
278
118k
  w->range = range;
279
118k
}
280
281
0
static void write_partition_size(unsigned char *cx_data, int size) {
282
0
  signed char csize;
283
284
0
  csize = size & 0xff;
285
0
  *cx_data = csize;
286
0
  csize = (size >> 8) & 0xff;
287
0
  *(cx_data + 1) = csize;
288
0
  csize = (size >> 16) & 0xff;
289
0
  *(cx_data + 2) = csize;
290
0
}
291
292
static void pack_tokens_into_partitions(VP8_COMP *cpi, unsigned char *cx_data,
293
                                        unsigned char *cx_data_end,
294
0
                                        int num_part) {
295
0
  int i;
296
0
  unsigned char *ptr = cx_data;
297
0
  unsigned char *ptr_end = cx_data_end;
298
0
  vp8_writer *w;
299
300
0
  for (i = 0; i < num_part; ++i) {
301
0
    int mb_row;
302
303
0
    w = cpi->bc + i + 1;
304
305
0
    vp8_start_encode(w, ptr, ptr_end);
306
307
0
    for (mb_row = i; mb_row < cpi->common.mb_rows; mb_row += num_part) {
308
0
      const TOKENEXTRA *p = cpi->tplist[mb_row].start;
309
0
      const TOKENEXTRA *stop = cpi->tplist[mb_row].stop;
310
0
      int tokens = (int)(stop - p);
311
312
0
      vp8_pack_tokens(w, p, tokens);
313
0
    }
314
315
0
    vp8_stop_encode(w);
316
0
    ptr += w->pos;
317
0
  }
318
0
}
319
320
#if CONFIG_MULTITHREAD
321
0
static void pack_mb_row_tokens(VP8_COMP *cpi, vp8_writer *w) {
322
0
  int mb_row;
323
324
0
  for (mb_row = 0; mb_row < cpi->common.mb_rows; ++mb_row) {
325
0
    const TOKENEXTRA *p = cpi->tplist[mb_row].start;
326
0
    const TOKENEXTRA *stop = cpi->tplist[mb_row].stop;
327
0
    int tokens = (int)(stop - p);
328
329
0
    vp8_pack_tokens(w, p, tokens);
330
0
  }
331
0
}
332
#endif  // CONFIG_MULTITHREAD
333
334
static void write_mv_ref(vp8_writer *w, MB_PREDICTION_MODE m,
335
534k
                         const vp8_prob *p) {
336
534k
  assert(NEARESTMV <= m && m <= SPLITMV);
337
534k
  vp8_write_token(w, vp8_mv_ref_tree, p,
338
534k
                  vp8_mv_ref_encoding_array + (m - NEARESTMV));
339
534k
}
340
341
static void write_sub_mv_ref(vp8_writer *w, B_PREDICTION_MODE m,
342
780k
                             const vp8_prob *p) {
343
780k
  assert(LEFT4X4 <= m && m <= NEW4X4);
344
780k
  vp8_write_token(w, vp8_sub_mv_ref_tree, p,
345
780k
                  vp8_sub_mv_ref_encoding_array + (m - LEFT4X4));
346
780k
}
347
348
static void write_mv(vp8_writer *w, const MV *mv, const int_mv *ref,
349
505k
                     const MV_CONTEXT *mvc) {
350
505k
  MV e;
351
505k
  e.row = mv->row - ref->as_mv.row;
352
505k
  e.col = mv->col - ref->as_mv.col;
353
354
505k
  vp8_encode_motion_vector(w, &e, mvc);
355
505k
}
356
357
static void write_mb_features(vp8_writer *w, const MB_MODE_INFO *mi,
358
0
                              const MACROBLOCKD *x) {
359
  /* Encode the MB segment id. */
360
0
  if (x->segmentation_enabled && x->update_mb_segmentation_map) {
361
0
    switch (mi->segment_id) {
362
0
      case 0:
363
0
        vp8_write(w, 0, x->mb_segment_tree_probs[0]);
364
0
        vp8_write(w, 0, x->mb_segment_tree_probs[1]);
365
0
        break;
366
0
      case 1:
367
0
        vp8_write(w, 0, x->mb_segment_tree_probs[0]);
368
0
        vp8_write(w, 1, x->mb_segment_tree_probs[1]);
369
0
        break;
370
0
      case 2:
371
0
        vp8_write(w, 1, x->mb_segment_tree_probs[0]);
372
0
        vp8_write(w, 0, x->mb_segment_tree_probs[2]);
373
0
        break;
374
0
      case 3:
375
0
        vp8_write(w, 1, x->mb_segment_tree_probs[0]);
376
0
        vp8_write(w, 1, x->mb_segment_tree_probs[2]);
377
0
        break;
378
379
      /* TRAP.. This should not happen */
380
0
      default:
381
0
        vp8_write(w, 0, x->mb_segment_tree_probs[0]);
382
0
        vp8_write(w, 0, x->mb_segment_tree_probs[1]);
383
0
        break;
384
0
    }
385
0
  }
386
0
}
387
200k
void vp8_convert_rfct_to_prob(VP8_COMP *const cpi) {
388
200k
  const int *const rfct = cpi->mb.count_mb_ref_frame_usage;
389
200k
  const int rf_intra = rfct[INTRA_FRAME];
390
200k
  const int rf_inter =
391
200k
      rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
392
393
  /* Calculate the probabilities used to code the ref frame based on usage */
394
200k
  if (!(cpi->prob_intra_coded = rf_intra * 255 / (rf_intra + rf_inter))) {
395
94.2k
    cpi->prob_intra_coded = 1;
396
94.2k
  }
397
398
200k
  cpi->prob_last_coded = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
399
400
200k
  if (!cpi->prob_last_coded) cpi->prob_last_coded = 1;
401
402
200k
  cpi->prob_gf_coded = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
403
200k
                           ? (rfct[GOLDEN_FRAME] * 255) /
404
50.3k
                                 (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
405
200k
                           : 128;
406
407
200k
  if (!cpi->prob_gf_coded) cpi->prob_gf_coded = 1;
408
200k
}
409
410
96.2k
static void pack_inter_mode_mvs(VP8_COMP *const cpi) {
411
96.2k
  VP8_COMMON *const pc = &cpi->common;
412
96.2k
  vp8_writer *const w = cpi->bc;
413
96.2k
  const MV_CONTEXT *mvc = pc->fc.mvc;
414
415
96.2k
  MODE_INFO *m = pc->mi;
416
96.2k
  const int mis = pc->mode_info_stride;
417
96.2k
  int mb_row = -1;
418
419
96.2k
  int prob_skip_false = 0;
420
421
96.2k
  cpi->mb.partition_info = cpi->mb.pi;
422
423
96.2k
  vp8_convert_rfct_to_prob(cpi);
424
425
96.2k
  if (pc->mb_no_coeff_skip) {
426
96.2k
    int total_mbs = pc->mb_rows * pc->mb_cols;
427
428
96.2k
    prob_skip_false = (total_mbs - cpi->mb.skip_true_count) * 256 / total_mbs;
429
430
96.2k
    if (prob_skip_false <= 1) prob_skip_false = 1;
431
432
96.2k
    if (prob_skip_false > 255) prob_skip_false = 255;
433
434
96.2k
    cpi->prob_skip_false = prob_skip_false;
435
96.2k
    vp8_write_literal(w, prob_skip_false, 8);
436
96.2k
  }
437
438
96.2k
  vp8_write_literal(w, cpi->prob_intra_coded, 8);
439
96.2k
  vp8_write_literal(w, cpi->prob_last_coded, 8);
440
96.2k
  vp8_write_literal(w, cpi->prob_gf_coded, 8);
441
442
96.2k
  update_mbintra_mode_probs(cpi);
443
444
96.2k
  vp8_write_mvprobs(cpi);
445
446
318k
  while (++mb_row < pc->mb_rows) {
447
221k
    int mb_col = -1;
448
449
1.38M
    while (++mb_col < pc->mb_cols) {
450
1.16M
      const MB_MODE_INFO *const mi = &m->mbmi;
451
1.16M
      const MV_REFERENCE_FRAME rf = mi->ref_frame;
452
1.16M
      const MB_PREDICTION_MODE mode = mi->mode;
453
454
1.16M
      MACROBLOCKD *xd = &cpi->mb.e_mbd;
455
456
      /* Distance of Mb to the various image edges.
457
       * These specified to 8th pel as they are always compared to MV
458
       * values that are in 1/8th pel units
459
       */
460
1.16M
      xd->mb_to_left_edge = -((mb_col * 16) << 3);
461
1.16M
      xd->mb_to_right_edge = ((pc->mb_cols - 1 - mb_col) * 16) << 3;
462
1.16M
      xd->mb_to_top_edge = -((mb_row * 16) << 3);
463
1.16M
      xd->mb_to_bottom_edge = ((pc->mb_rows - 1 - mb_row) * 16) << 3;
464
465
1.16M
      if (cpi->mb.e_mbd.update_mb_segmentation_map) {
466
0
        write_mb_features(w, mi, &cpi->mb.e_mbd);
467
0
      }
468
469
1.16M
      if (pc->mb_no_coeff_skip) {
470
1.16M
        vp8_encode_bool(w, m->mbmi.mb_skip_coeff, prob_skip_false);
471
1.16M
      }
472
473
1.16M
      if (rf == INTRA_FRAME) {
474
629k
        vp8_write(w, 0, cpi->prob_intra_coded);
475
629k
        write_ymode(w, mode, pc->fc.ymode_prob);
476
477
629k
        if (mode == B_PRED) {
478
223k
          int j = 0;
479
480
3.58M
          do {
481
3.58M
            write_bmode(w, m->bmi[j].as_mode, pc->fc.bmode_prob);
482
3.58M
          } while (++j < 16);
483
223k
        }
484
485
629k
        write_uv_mode(w, mi->uv_mode, pc->fc.uv_mode_prob);
486
629k
      } else { /* inter coded */
487
534k
        int_mv best_mv;
488
534k
        vp8_prob mv_ref_p[VP8_MVREFS - 1];
489
490
534k
        vp8_write(w, 1, cpi->prob_intra_coded);
491
492
534k
        if (rf == LAST_FRAME)
493
468k
          vp8_write(w, 0, cpi->prob_last_coded);
494
65.6k
        else {
495
65.6k
          vp8_write(w, 1, cpi->prob_last_coded);
496
65.6k
          vp8_write(w, (rf == GOLDEN_FRAME) ? 0 : 1, cpi->prob_gf_coded);
497
65.6k
        }
498
499
534k
        {
500
534k
          int_mv n1, n2;
501
534k
          int ct[4];
502
503
534k
          vp8_find_near_mvs(xd, m, &n1, &n2, &best_mv, ct, rf,
504
534k
                            pc->ref_frame_sign_bias);
505
534k
          vp8_clamp_mv2(&best_mv, xd);
506
507
534k
          vp8_mv_ref_probs(mv_ref_p, ct);
508
534k
        }
509
510
534k
        write_mv_ref(w, mode, mv_ref_p);
511
512
534k
        switch (mode) /* new, split require MVs */
513
534k
        {
514
196k
          case NEWMV: write_mv(w, &mi->mv.as_mv, &best_mv, mvc); break;
515
516
114k
          case SPLITMV: {
517
114k
            int j = 0;
518
519
#ifdef MODE_STATS
520
            ++count_mb_seg[mi->partitioning];
521
#endif
522
523
114k
            write_split(w, mi->partitioning);
524
525
780k
            do {
526
780k
              B_PREDICTION_MODE blockmode;
527
780k
              int_mv blockmv;
528
780k
              const int *const L = vp8_mbsplits[mi->partitioning];
529
780k
              int k = -1; /* first block in subset j */
530
780k
              int mv_contz;
531
780k
              int_mv leftmv, abovemv;
532
533
780k
              blockmode = cpi->mb.partition_info->bmi[j].mode;
534
780k
              blockmv = cpi->mb.partition_info->bmi[j].mv;
535
5.93M
              while (j != L[++k]) {
536
5.15M
                assert(k < 16);
537
5.15M
              }
538
780k
              leftmv.as_int = left_block_mv(m, k);
539
780k
              abovemv.as_int = above_block_mv(m, k, mis);
540
780k
              mv_contz = vp8_mv_cont(&leftmv, &abovemv);
541
542
780k
              write_sub_mv_ref(w, blockmode, vp8_sub_mv_ref_prob2[mv_contz]);
543
544
780k
              if (blockmode == NEW4X4) {
545
309k
                write_mv(w, &blockmv.as_mv, &best_mv, (const MV_CONTEXT *)mvc);
546
309k
              }
547
780k
            } while (++j < cpi->mb.partition_info->count);
548
114k
            break;
549
0
          }
550
223k
          default: break;
551
534k
        }
552
534k
      }
553
554
1.16M
      ++m;
555
1.16M
      cpi->mb.partition_info++;
556
1.16M
    }
557
558
221k
    ++m; /* skip L prediction border */
559
221k
    cpi->mb.partition_info++;
560
221k
  }
561
96.2k
}
562
563
21.7k
static void write_kfmodes(VP8_COMP *cpi) {
564
21.7k
  vp8_writer *const bc = cpi->bc;
565
21.7k
  const VP8_COMMON *const c = &cpi->common;
566
  /* const */
567
21.7k
  MODE_INFO *m = c->mi;
568
569
21.7k
  int mb_row = -1;
570
21.7k
  int prob_skip_false = 0;
571
572
21.7k
  if (c->mb_no_coeff_skip) {
573
21.7k
    int total_mbs = c->mb_rows * c->mb_cols;
574
575
21.7k
    prob_skip_false = (total_mbs - cpi->mb.skip_true_count) * 256 / total_mbs;
576
577
21.7k
    if (prob_skip_false <= 1) prob_skip_false = 1;
578
579
21.7k
    if (prob_skip_false >= 255) prob_skip_false = 255;
580
581
21.7k
    cpi->prob_skip_false = prob_skip_false;
582
21.7k
    vp8_write_literal(bc, prob_skip_false, 8);
583
21.7k
  }
584
585
140k
  while (++mb_row < c->mb_rows) {
586
118k
    int mb_col = -1;
587
588
1.11M
    while (++mb_col < c->mb_cols) {
589
999k
      const int ym = m->mbmi.mode;
590
591
999k
      if (cpi->mb.e_mbd.update_mb_segmentation_map) {
592
0
        write_mb_features(bc, &m->mbmi, &cpi->mb.e_mbd);
593
0
      }
594
595
999k
      if (c->mb_no_coeff_skip) {
596
999k
        vp8_encode_bool(bc, m->mbmi.mb_skip_coeff, prob_skip_false);
597
999k
      }
598
599
999k
      kfwrite_ymode(bc, ym, vp8_kf_ymode_prob);
600
601
999k
      if (ym == B_PRED) {
602
560k
        const int mis = c->mode_info_stride;
603
560k
        int i = 0;
604
605
8.96M
        do {
606
8.96M
          const B_PREDICTION_MODE A = above_block_mode(m, i, mis);
607
8.96M
          const B_PREDICTION_MODE L = left_block_mode(m, i);
608
8.96M
          const int bm = m->bmi[i].as_mode;
609
610
8.96M
          write_bmode(bc, bm, vp8_kf_bmode_prob[A][L]);
611
8.96M
        } while (++i < 16);
612
560k
      }
613
614
999k
      write_uv_mode(bc, (m++)->mbmi.uv_mode, vp8_kf_uv_mode_prob);
615
999k
    }
616
617
118k
    m++; /* skip L prediction border */
618
118k
  }
619
21.7k
}
620
621
#if 0
622
/* This function is used for debugging probability trees. */
623
static void print_prob_tree(vp8_prob
624
     coef_probs[BLOCK_TYPES][COEF_BANDS][PREV_COEF_CONTEXTS][ENTROPY_NODES])
625
{
626
    /* print coef probability tree */
627
    int i,j,k,l;
628
    FILE* f = fopen("enc_tree_probs.txt", "a");
629
    fprintf(f, "{\n");
630
    for (i = 0; i < BLOCK_TYPES; ++i)
631
    {
632
        fprintf(f, "  {\n");
633
        for (j = 0; j < COEF_BANDS; ++j)
634
        {
635
            fprintf(f, "    {\n");
636
            for (k = 0; k < PREV_COEF_CONTEXTS; ++k)
637
            {
638
                fprintf(f, "      {");
639
                for (l = 0; l < ENTROPY_NODES; ++l)
640
                {
641
                    fprintf(f, "%3u, ",
642
                            (unsigned int)(coef_probs [i][j][k][l]));
643
                }
644
                fprintf(f, " }\n");
645
            }
646
            fprintf(f, "    }\n");
647
        }
648
        fprintf(f, "  }\n");
649
    }
650
    fprintf(f, "}\n");
651
    fclose(f);
652
}
653
#endif
654
655
static void sum_probs_over_prev_coef_context(
656
    const unsigned int probs[PREV_COEF_CONTEXTS][MAX_ENTROPY_TOKENS],
657
0
    unsigned int *out) {
658
0
  int i, j;
659
0
  for (i = 0; i < MAX_ENTROPY_TOKENS; ++i) {
660
0
    for (j = 0; j < PREV_COEF_CONTEXTS; ++j) {
661
0
      const unsigned int tmp = out[i];
662
0
      out[i] += probs[j][i];
663
      /* check for wrap */
664
0
      if (out[i] < tmp) out[i] = UINT_MAX;
665
0
    }
666
0
  }
667
0
}
668
669
static int prob_update_savings(const unsigned int *ct, const vp8_prob oldp,
670
284M
                               const vp8_prob newp, const vp8_prob upd) {
671
284M
  const int old_b = vp8_cost_branch(ct, oldp);
672
284M
  const int new_b = vp8_cost_branch(ct, newp);
673
284M
  const int update_b = 8 + ((vp8_cost_one(upd) - vp8_cost_zero(upd)) >> 8);
674
675
284M
  return old_b - new_b - update_b;
676
284M
}
677
678
0
static int independent_coef_context_savings(VP8_COMP *cpi) {
679
0
  MACROBLOCK *const x = &cpi->mb;
680
0
  int savings = 0;
681
0
  int i = 0;
682
0
  do {
683
0
    int j = 0;
684
0
    do {
685
0
      int k = 0;
686
0
      unsigned int prev_coef_count_sum[MAX_ENTROPY_TOKENS] = { 0 };
687
0
      int prev_coef_savings[MAX_ENTROPY_TOKENS] = { 0 };
688
0
      const unsigned int(*probs)[MAX_ENTROPY_TOKENS];
689
      /* Calculate new probabilities given the constraint that
690
       * they must be equal over the prev coef contexts
691
       */
692
693
0
      probs = (const unsigned int(*)[MAX_ENTROPY_TOKENS])x->coef_counts[i][j];
694
695
      /* Reset to default probabilities at key frames */
696
0
      if (cpi->common.frame_type == KEY_FRAME) {
697
0
        probs = default_coef_counts[i][j];
698
0
      }
699
700
0
      sum_probs_over_prev_coef_context(probs, prev_coef_count_sum);
701
702
0
      do {
703
        /* at every context */
704
705
        /* calc probs and branch cts for this frame only */
706
0
        int t = 0; /* token/prob index */
707
708
0
        vp8_tree_probs_from_distribution(
709
0
            MAX_ENTROPY_TOKENS, vp8_coef_encodings, vp8_coef_tree,
710
0
            cpi->frame_coef_probs[i][j][k], cpi->frame_branch_ct[i][j][k],
711
0
            prev_coef_count_sum, 256, 1);
712
713
0
        do {
714
0
          const unsigned int *ct = cpi->frame_branch_ct[i][j][k][t];
715
0
          const vp8_prob newp = cpi->frame_coef_probs[i][j][k][t];
716
0
          const vp8_prob oldp = cpi->common.fc.coef_probs[i][j][k][t];
717
0
          const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
718
0
          const int s = prob_update_savings(ct, oldp, newp, upd);
719
720
0
          if (cpi->common.frame_type != KEY_FRAME ||
721
0
              (cpi->common.frame_type == KEY_FRAME && newp != oldp)) {
722
0
            prev_coef_savings[t] += s;
723
0
          }
724
0
        } while (++t < ENTROPY_NODES);
725
0
      } while (++k < PREV_COEF_CONTEXTS);
726
0
      k = 0;
727
0
      do {
728
        /* We only update probabilities if we can save bits, except
729
         * for key frames where we have to update all probabilities
730
         * to get the equal probabilities across the prev coef
731
         * contexts.
732
         */
733
0
        if (prev_coef_savings[k] > 0 || cpi->common.frame_type == KEY_FRAME) {
734
0
          savings += prev_coef_savings[k];
735
0
        }
736
0
      } while (++k < ENTROPY_NODES);
737
0
    } while (++j < COEF_BANDS);
738
0
  } while (++i < BLOCK_TYPES);
739
0
  return savings;
740
0
}
741
742
151k
static int default_coef_context_savings(VP8_COMP *cpi) {
743
151k
  MACROBLOCK *const x = &cpi->mb;
744
151k
  int savings = 0;
745
151k
  int i = 0;
746
606k
  do {
747
606k
    int j = 0;
748
4.85M
    do {
749
4.85M
      int k = 0;
750
14.5M
      do {
751
        /* at every context */
752
753
        /* calc probs and branch cts for this frame only */
754
14.5M
        int t = 0; /* token/prob index */
755
756
14.5M
        vp8_tree_probs_from_distribution(
757
14.5M
            MAX_ENTROPY_TOKENS, vp8_coef_encodings, vp8_coef_tree,
758
14.5M
            cpi->frame_coef_probs[i][j][k], cpi->frame_branch_ct[i][j][k],
759
14.5M
            x->coef_counts[i][j][k], 256, 1);
760
761
160M
        do {
762
160M
          const unsigned int *ct = cpi->frame_branch_ct[i][j][k][t];
763
160M
          const vp8_prob newp = cpi->frame_coef_probs[i][j][k][t];
764
160M
          const vp8_prob oldp = cpi->common.fc.coef_probs[i][j][k][t];
765
160M
          const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
766
160M
          const int s = prob_update_savings(ct, oldp, newp, upd);
767
768
160M
          if (s > 0) {
769
2.90M
            savings += s;
770
2.90M
          }
771
160M
        } while (++t < ENTROPY_NODES);
772
14.5M
      } while (++k < PREV_COEF_CONTEXTS);
773
4.85M
    } while (++j < COEF_BANDS);
774
606k
  } while (++i < BLOCK_TYPES);
775
151k
  return savings;
776
151k
}
777
778
void vp8_calc_ref_frame_costs(int *ref_frame_cost, int prob_intra,
779
383k
                              int prob_last, int prob_garf) {
780
383k
  assert(prob_intra >= 0);
781
383k
  assert(prob_intra <= 255);
782
383k
  assert(prob_last >= 0);
783
383k
  assert(prob_last <= 255);
784
383k
  assert(prob_garf >= 0);
785
383k
  assert(prob_garf <= 255);
786
383k
  ref_frame_cost[INTRA_FRAME] = vp8_cost_zero(prob_intra);
787
383k
  ref_frame_cost[LAST_FRAME] =
788
383k
      vp8_cost_one(prob_intra) + vp8_cost_zero(prob_last);
789
383k
  ref_frame_cost[GOLDEN_FRAME] = vp8_cost_one(prob_intra) +
790
383k
                                 vp8_cost_one(prob_last) +
791
383k
                                 vp8_cost_zero(prob_garf);
792
383k
  ref_frame_cost[ALTREF_FRAME] = vp8_cost_one(prob_intra) +
793
383k
                                 vp8_cost_one(prob_last) +
794
383k
                                 vp8_cost_one(prob_garf);
795
383k
}
796
797
151k
int vp8_estimate_entropy_savings(VP8_COMP *cpi) {
798
151k
  int savings = 0;
799
800
151k
  const int *const rfct = cpi->mb.count_mb_ref_frame_usage;
801
151k
  const int rf_intra = rfct[INTRA_FRAME];
802
151k
  const int rf_inter =
803
151k
      rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
804
151k
  int new_intra, new_last, new_garf, oldtotal, newtotal;
805
151k
  int ref_frame_cost[MAX_REF_FRAMES];
806
807
151k
  vpx_clear_system_state();
808
809
151k
  if (cpi->common.frame_type != KEY_FRAME) {
810
115k
    if (!(new_intra = rf_intra * 255 / (rf_intra + rf_inter))) new_intra = 1;
811
812
115k
    new_last = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
813
814
115k
    new_garf = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
815
115k
                   ? (rfct[GOLDEN_FRAME] * 255) /
816
28.9k
                         (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
817
115k
                   : 128;
818
819
115k
    vp8_calc_ref_frame_costs(ref_frame_cost, new_intra, new_last, new_garf);
820
821
115k
    newtotal = rfct[INTRA_FRAME] * ref_frame_cost[INTRA_FRAME] +
822
115k
               rfct[LAST_FRAME] * ref_frame_cost[LAST_FRAME] +
823
115k
               rfct[GOLDEN_FRAME] * ref_frame_cost[GOLDEN_FRAME] +
824
115k
               rfct[ALTREF_FRAME] * ref_frame_cost[ALTREF_FRAME];
825
826
    /* old costs */
827
115k
    vp8_calc_ref_frame_costs(ref_frame_cost, cpi->prob_intra_coded,
828
115k
                             cpi->prob_last_coded, cpi->prob_gf_coded);
829
830
115k
    oldtotal = rfct[INTRA_FRAME] * ref_frame_cost[INTRA_FRAME] +
831
115k
               rfct[LAST_FRAME] * ref_frame_cost[LAST_FRAME] +
832
115k
               rfct[GOLDEN_FRAME] * ref_frame_cost[GOLDEN_FRAME] +
833
115k
               rfct[ALTREF_FRAME] * ref_frame_cost[ALTREF_FRAME];
834
835
115k
    savings += (oldtotal - newtotal) / 256;
836
115k
  }
837
838
151k
  if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS) {
839
0
    savings += independent_coef_context_savings(cpi);
840
151k
  } else {
841
151k
    savings += default_coef_context_savings(cpi);
842
151k
  }
843
844
151k
  return savings;
845
151k
}
846
847
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
848
int vp8_update_coef_context(VP8_COMP *cpi) {
849
  int savings = 0;
850
851
  if (cpi->common.frame_type == KEY_FRAME) {
852
    /* Reset to default counts/probabilities at key frames */
853
    vp8_copy(cpi->mb.coef_counts, default_coef_counts);
854
  }
855
856
  if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS)
857
    savings += independent_coef_context_savings(cpi);
858
  else
859
    savings += default_coef_context_savings(cpi);
860
861
  return savings;
862
}
863
#endif
864
865
118k
void vp8_update_coef_probs(VP8_COMP *cpi) {
866
118k
  int i = 0;
867
118k
#if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
868
118k
  vp8_writer *const w = cpi->bc;
869
118k
#endif
870
871
118k
  vpx_clear_system_state();
872
873
472k
  do {
874
472k
    int j = 0;
875
876
3.77M
    do {
877
3.77M
      int k = 0;
878
3.77M
      int prev_coef_savings[ENTROPY_NODES] = { 0 };
879
3.77M
      if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS) {
880
0
        for (k = 0; k < PREV_COEF_CONTEXTS; ++k) {
881
0
          int t; /* token/prob index */
882
0
          for (t = 0; t < ENTROPY_NODES; ++t) {
883
0
            const unsigned int *ct = cpi->frame_branch_ct[i][j][k][t];
884
0
            const vp8_prob newp = cpi->frame_coef_probs[i][j][k][t];
885
0
            const vp8_prob oldp = cpi->common.fc.coef_probs[i][j][k][t];
886
0
            const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
887
888
0
            prev_coef_savings[t] += prob_update_savings(ct, oldp, newp, upd);
889
0
          }
890
0
        }
891
0
        k = 0;
892
0
      }
893
11.3M
      do {
894
        /* note: use result from vp8_estimate_entropy_savings, so no
895
         * need to call vp8_tree_probs_from_distribution here.
896
         */
897
898
        /* at every context */
899
900
        /* calc probs and branch cts for this frame only */
901
11.3M
        int t = 0; /* token/prob index */
902
903
124M
        do {
904
124M
          const vp8_prob newp = cpi->frame_coef_probs[i][j][k][t];
905
906
124M
          vp8_prob *Pold = cpi->common.fc.coef_probs[i][j][k] + t;
907
124M
          const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
908
909
124M
          int s = prev_coef_savings[t];
910
124M
          int u = 0;
911
912
124M
          if (!(cpi->oxcf.error_resilient_mode &
913
124M
                VPX_ERROR_RESILIENT_PARTITIONS)) {
914
124M
            s = prob_update_savings(cpi->frame_branch_ct[i][j][k][t], *Pold,
915
124M
                                    newp, upd);
916
124M
          }
917
918
124M
          if (s > 0) u = 1;
919
920
          /* Force updates on key frames if the new is different,
921
           * so that we can be sure we end up with equal probabilities
922
           * over the prev coef contexts.
923
           */
924
124M
          if ((cpi->oxcf.error_resilient_mode &
925
124M
               VPX_ERROR_RESILIENT_PARTITIONS) &&
926
0
              cpi->common.frame_type == KEY_FRAME && newp != *Pold) {
927
0
            u = 1;
928
0
          }
929
930
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
931
          cpi->update_probs[i][j][k][t] = u;
932
#else
933
124M
          vp8_write(w, u, upd);
934
124M
#endif
935
936
124M
          if (u) {
937
            /* send/use new probability */
938
939
2.06M
            *Pold = newp;
940
2.06M
#if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
941
2.06M
            vp8_write_literal(w, newp, 8);
942
2.06M
#endif
943
2.06M
          }
944
945
124M
        } while (++t < ENTROPY_NODES);
946
947
11.3M
      } while (++k < PREV_COEF_CONTEXTS);
948
3.77M
    } while (++j < COEF_BANDS);
949
472k
  } while (++i < BLOCK_TYPES);
950
118k
}
951
952
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
953
static void pack_coef_probs(VP8_COMP *cpi) {
954
  int i = 0;
955
  vp8_writer *const w = cpi->bc;
956
957
  do {
958
    int j = 0;
959
960
    do {
961
      int k = 0;
962
963
      do {
964
        int t = 0; /* token/prob index */
965
966
        do {
967
          const vp8_prob newp = cpi->common.fc.coef_probs[i][j][k][t];
968
          const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
969
970
          const char u = cpi->update_probs[i][j][k][t];
971
972
          vp8_write(w, u, upd);
973
974
          if (u) {
975
            /* send/use new probability */
976
            vp8_write_literal(w, newp, 8);
977
          }
978
        } while (++t < ENTROPY_NODES);
979
      } while (++k < PREV_COEF_CONTEXTS);
980
    } while (++j < COEF_BANDS);
981
  } while (++i < BLOCK_TYPES);
982
}
983
#endif
984
985
#ifdef PACKET_TESTING
986
FILE *vpxlogc = 0;
987
#endif
988
989
590k
static void put_delta_q(vp8_writer *bc, int delta_q) {
990
590k
  if (delta_q != 0) {
991
0
    vp8_write_bit(bc, 1);
992
0
    vp8_write_literal(bc, abs(delta_q), 4);
993
994
0
    if (delta_q < 0)
995
0
      vp8_write_bit(bc, 1);
996
0
    else
997
0
      vp8_write_bit(bc, 0);
998
0
  } else
999
590k
    vp8_write_bit(bc, 0);
1000
590k
}
1001
1002
void vp8_pack_bitstream(VP8_COMP *cpi, unsigned char *dest,
1003
118k
                        unsigned char *dest_end, size_t *size) {
1004
118k
  int i, j;
1005
118k
  VP8_HEADER oh;
1006
118k
  VP8_COMMON *const pc = &cpi->common;
1007
118k
  vp8_writer *const bc = cpi->bc;
1008
118k
  MACROBLOCKD *const xd = &cpi->mb.e_mbd;
1009
118k
  int extra_bytes_packed = 0;
1010
1011
118k
  unsigned char *cx_data = dest;
1012
118k
  unsigned char *cx_data_end = dest_end;
1013
118k
  const int *mb_feature_data_bits;
1014
1015
118k
  oh.show_frame = (int)pc->show_frame;
1016
118k
  oh.type = (int)pc->frame_type;
1017
118k
  oh.version = pc->version;
1018
118k
  oh.first_partition_length_in_bytes = 0;
1019
1020
118k
  mb_feature_data_bits = vp8_mb_feature_data_bits;
1021
1022
118k
  bc[0].error = &pc->error;
1023
1024
118k
  validate_buffer(cx_data, 3, cx_data_end, &pc->error);
1025
118k
  cx_data += 3;
1026
1027
#if defined(SECTIONBITS_OUTPUT)
1028
  Sectionbits[active_section = 1] += sizeof(VP8_HEADER) * 8 * 256;
1029
#endif
1030
1031
  /* every keyframe send startcode, width, height, scale factor, clamp
1032
   * and color type
1033
   */
1034
118k
  if (oh.type == KEY_FRAME) {
1035
21.7k
    int v;
1036
1037
21.7k
    validate_buffer(cx_data, 7, cx_data_end, &pc->error);
1038
1039
    /* Start / synch code */
1040
21.7k
    cx_data[0] = 0x9D;
1041
21.7k
    cx_data[1] = 0x01;
1042
21.7k
    cx_data[2] = 0x2a;
1043
1044
    /* Pack scale and frame size into 16 bits. Store it 8 bits at a time.
1045
     * https://tools.ietf.org/html/rfc6386
1046
     * 9.1. Uncompressed Data Chunk
1047
     * 16 bits      :     (2 bits Horizontal Scale << 14) | Width (14 bits)
1048
     * 16 bits      :     (2 bits Vertical Scale << 14) | Height (14 bits)
1049
     */
1050
21.7k
    v = (pc->horiz_scale << 14) | pc->Width;
1051
21.7k
    cx_data[3] = v & 0xff;
1052
21.7k
    cx_data[4] = v >> 8;
1053
1054
21.7k
    v = (pc->vert_scale << 14) | pc->Height;
1055
21.7k
    cx_data[5] = v & 0xff;
1056
21.7k
    cx_data[6] = v >> 8;
1057
1058
21.7k
    extra_bytes_packed = 7;
1059
21.7k
    cx_data += extra_bytes_packed;
1060
1061
21.7k
    vp8_start_encode(bc, cx_data, cx_data_end);
1062
1063
    /* signal clr type */
1064
21.7k
    vp8_write_bit(bc, 0);
1065
21.7k
    vp8_write_bit(bc, pc->clamp_type);
1066
1067
96.2k
  } else {
1068
96.2k
    vp8_start_encode(bc, cx_data, cx_data_end);
1069
96.2k
  }
1070
1071
  /* Signal whether or not Segmentation is enabled */
1072
118k
  vp8_write_bit(bc, xd->segmentation_enabled);
1073
1074
  /*  Indicate which features are enabled */
1075
118k
  if (xd->segmentation_enabled) {
1076
    /* Signal whether or not the segmentation map is being updated. */
1077
0
    vp8_write_bit(bc, xd->update_mb_segmentation_map);
1078
0
    vp8_write_bit(bc, xd->update_mb_segmentation_data);
1079
1080
0
    if (xd->update_mb_segmentation_data) {
1081
0
      signed char Data;
1082
1083
0
      vp8_write_bit(bc, xd->mb_segment_abs_delta);
1084
1085
      /* For each segmentation feature (Quant and loop filter level) */
1086
0
      for (i = 0; i < MB_LVL_MAX; ++i) {
1087
        /* For each of the segments */
1088
0
        for (j = 0; j < MAX_MB_SEGMENTS; ++j) {
1089
0
          Data = xd->segment_feature_data[i][j];
1090
1091
          /* Frame level data */
1092
0
          if (Data) {
1093
0
            vp8_write_bit(bc, 1);
1094
1095
0
            if (Data < 0) {
1096
0
              Data = -Data;
1097
0
              vp8_write_literal(bc, Data, mb_feature_data_bits[i]);
1098
0
              vp8_write_bit(bc, 1);
1099
0
            } else {
1100
0
              vp8_write_literal(bc, Data, mb_feature_data_bits[i]);
1101
0
              vp8_write_bit(bc, 0);
1102
0
            }
1103
0
          } else
1104
0
            vp8_write_bit(bc, 0);
1105
0
        }
1106
0
      }
1107
0
    }
1108
1109
0
    if (xd->update_mb_segmentation_map) {
1110
      /* Write the probs used to decode the segment id for each mb */
1111
0
      for (i = 0; i < MB_FEATURE_TREE_PROBS; ++i) {
1112
0
        int Data = xd->mb_segment_tree_probs[i];
1113
1114
0
        if (Data != 255) {
1115
0
          vp8_write_bit(bc, 1);
1116
0
          vp8_write_literal(bc, Data, 8);
1117
0
        } else
1118
0
          vp8_write_bit(bc, 0);
1119
0
      }
1120
0
    }
1121
0
  }
1122
1123
118k
  vp8_write_bit(bc, pc->filter_type);
1124
118k
  vp8_write_literal(bc, pc->filter_level, 6);
1125
118k
  vp8_write_literal(bc, pc->sharpness_level, 3);
1126
1127
  /* Write out loop filter deltas applied at the MB level based on mode
1128
   * or ref frame (if they are enabled).
1129
   */
1130
118k
  vp8_write_bit(bc, xd->mode_ref_lf_delta_enabled);
1131
1132
118k
  if (xd->mode_ref_lf_delta_enabled) {
1133
    /* Do the deltas need to be updated */
1134
118k
    int send_update =
1135
118k
        xd->mode_ref_lf_delta_update || cpi->oxcf.error_resilient_mode;
1136
1137
118k
    vp8_write_bit(bc, send_update);
1138
118k
    if (send_update) {
1139
21.7k
      int Data;
1140
1141
      /* Send update */
1142
108k
      for (i = 0; i < MAX_REF_LF_DELTAS; ++i) {
1143
87.1k
        Data = xd->ref_lf_deltas[i];
1144
1145
        /* Frame level data */
1146
87.1k
        if (xd->ref_lf_deltas[i] != xd->last_ref_lf_deltas[i] ||
1147
65.3k
            cpi->oxcf.error_resilient_mode) {
1148
65.3k
          xd->last_ref_lf_deltas[i] = xd->ref_lf_deltas[i];
1149
65.3k
          vp8_write_bit(bc, 1);
1150
1151
65.3k
          if (Data > 0) {
1152
21.7k
            vp8_write_literal(bc, (Data & 0x3F), 6);
1153
21.7k
            vp8_write_bit(bc, 0); /* sign */
1154
43.5k
          } else {
1155
43.5k
            Data = -Data;
1156
43.5k
            vp8_write_literal(bc, (Data & 0x3F), 6);
1157
43.5k
            vp8_write_bit(bc, 1); /* sign */
1158
43.5k
          }
1159
65.3k
        } else
1160
87.1k
          vp8_write_bit(bc, 0);
1161
87.1k
      }
1162
1163
      /* Send update */
1164
108k
      for (i = 0; i < MAX_MODE_LF_DELTAS; ++i) {
1165
87.1k
        Data = xd->mode_lf_deltas[i];
1166
1167
87.1k
        if (xd->mode_lf_deltas[i] != xd->last_mode_lf_deltas[i] ||
1168
87.1k
            cpi->oxcf.error_resilient_mode) {
1169
87.1k
          xd->last_mode_lf_deltas[i] = xd->mode_lf_deltas[i];
1170
87.1k
          vp8_write_bit(bc, 1);
1171
1172
87.1k
          if (Data > 0) {
1173
65.3k
            vp8_write_literal(bc, (Data & 0x3F), 6);
1174
65.3k
            vp8_write_bit(bc, 0); /* sign */
1175
65.3k
          } else {
1176
21.7k
            Data = -Data;
1177
21.7k
            vp8_write_literal(bc, (Data & 0x3F), 6);
1178
21.7k
            vp8_write_bit(bc, 1); /* sign */
1179
21.7k
          }
1180
87.1k
        } else
1181
87.1k
          vp8_write_bit(bc, 0);
1182
87.1k
      }
1183
21.7k
    }
1184
118k
  }
1185
1186
  /* signal here is multi token partition is enabled */
1187
118k
  vp8_write_literal(bc, pc->multi_token_partition, 2);
1188
1189
  /* Frame Qbaseline quantizer index */
1190
118k
  vp8_write_literal(bc, pc->base_qindex, 7);
1191
1192
  /* Transmit Dc, Second order and Uv quantizer delta information */
1193
118k
  put_delta_q(bc, pc->y1dc_delta_q);
1194
118k
  put_delta_q(bc, pc->y2dc_delta_q);
1195
118k
  put_delta_q(bc, pc->y2ac_delta_q);
1196
118k
  put_delta_q(bc, pc->uvdc_delta_q);
1197
118k
  put_delta_q(bc, pc->uvac_delta_q);
1198
1199
  /* When there is a key frame all reference buffers are updated using
1200
   * the new key frame
1201
   */
1202
118k
  if (pc->frame_type != KEY_FRAME) {
1203
    /* Should the GF or ARF be updated using the transmitted frame
1204
     * or buffer
1205
     */
1206
96.2k
    vp8_write_bit(bc, pc->refresh_golden_frame);
1207
96.2k
    vp8_write_bit(bc, pc->refresh_alt_ref_frame);
1208
1209
    /* If not being updated from current frame should either GF or ARF
1210
     * be updated from another buffer
1211
     */
1212
96.2k
    if (!pc->refresh_golden_frame)
1213
87.6k
      vp8_write_literal(bc, pc->copy_buffer_to_gf, 2);
1214
1215
96.2k
    if (!pc->refresh_alt_ref_frame)
1216
96.2k
      vp8_write_literal(bc, pc->copy_buffer_to_arf, 2);
1217
1218
    /* Indicate reference frame sign bias for Golden and ARF frames
1219
     * (always 0 for last frame buffer)
1220
     */
1221
96.2k
    vp8_write_bit(bc, pc->ref_frame_sign_bias[GOLDEN_FRAME]);
1222
96.2k
    vp8_write_bit(bc, pc->ref_frame_sign_bias[ALTREF_FRAME]);
1223
96.2k
  }
1224
1225
118k
#if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
1226
118k
  if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS) {
1227
0
    if (pc->frame_type == KEY_FRAME) {
1228
0
      pc->refresh_entropy_probs = 1;
1229
0
    } else {
1230
0
      pc->refresh_entropy_probs = 0;
1231
0
    }
1232
0
  }
1233
118k
#endif
1234
1235
118k
  vp8_write_bit(bc, pc->refresh_entropy_probs);
1236
1237
118k
  if (pc->frame_type != KEY_FRAME) vp8_write_bit(bc, pc->refresh_last_frame);
1238
1239
118k
  vpx_clear_system_state();
1240
1241
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1242
  pack_coef_probs(cpi);
1243
#else
1244
118k
  if (pc->refresh_entropy_probs == 0) {
1245
    /* save a copy for later refresh */
1246
0
    pc->lfc = pc->fc;
1247
0
  }
1248
1249
118k
  vp8_update_coef_probs(cpi);
1250
118k
#endif
1251
1252
  /* Write out the mb_no_coeff_skip flag */
1253
118k
  vp8_write_bit(bc, pc->mb_no_coeff_skip);
1254
1255
118k
  if (pc->frame_type == KEY_FRAME) {
1256
21.7k
    write_kfmodes(cpi);
1257
96.2k
  } else {
1258
96.2k
    pack_inter_mode_mvs(cpi);
1259
96.2k
  }
1260
1261
118k
  vp8_stop_encode(bc);
1262
1263
118k
  cx_data += bc->pos;
1264
1265
118k
  oh.first_partition_length_in_bytes = cpi->bc->pos;
1266
1267
  /* update frame tag */
1268
118k
  {
1269
    /* Pack partition size, show frame, version and frame type into to 24 bits.
1270
     * Store it 8 bits at a time.
1271
     * https://tools.ietf.org/html/rfc6386
1272
     * 9.1. Uncompressed Data Chunk
1273
     *    The uncompressed data chunk comprises a common (for key frames and
1274
     *    interframes) 3-byte frame tag that contains four fields, as follows:
1275
     *
1276
     *    1.  A 1-bit frame type (0 for key frames, 1 for interframes).
1277
     *
1278
     *    2.  A 3-bit version number (0 - 3 are defined as four different
1279
     *        profiles with different decoding complexity; other values may be
1280
     *        defined for future variants of the VP8 data format).
1281
     *
1282
     *    3.  A 1-bit show_frame flag (0 when current frame is not for display,
1283
     *        1 when current frame is for display).
1284
     *
1285
     *    4.  A 19-bit field containing the size of the first data partition in
1286
     *        bytes
1287
     */
1288
118k
    int v = (oh.first_partition_length_in_bytes << 5) | (oh.show_frame << 4) |
1289
118k
            (oh.version << 1) | oh.type;
1290
1291
118k
    dest[0] = v & 0xff;
1292
118k
    dest[1] = (v >> 8) & 0xff;
1293
118k
    dest[2] = v >> 16;
1294
118k
  }
1295
1296
118k
  *size = VP8_HEADER_SIZE + extra_bytes_packed + cpi->bc->pos;
1297
1298
118k
  cpi->partition_sz[0] = (unsigned int)*size;
1299
1300
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1301
  {
1302
    const int num_part = (1 << pc->multi_token_partition);
1303
    unsigned char *dp = cpi->partition_d[0] + cpi->partition_sz[0];
1304
1305
    if (num_part > 1) {
1306
      /* write token part sizes (all but last) if more than 1 */
1307
      validate_buffer(dp, 3 * (num_part - 1), cpi->partition_d_end[0],
1308
                      &pc->error);
1309
1310
      cpi->partition_sz[0] += 3 * (num_part - 1);
1311
1312
      for (i = 1; i < num_part; ++i) {
1313
        write_partition_size(dp, cpi->partition_sz[i]);
1314
        dp += 3;
1315
      }
1316
    }
1317
1318
    if (!cpi->output_partition) {
1319
      /* concatenate partition buffers */
1320
      for (i = 0; i < num_part; ++i) {
1321
        memmove(dp, cpi->partition_d[i + 1], cpi->partition_sz[i + 1]);
1322
        cpi->partition_d[i + 1] = dp;
1323
        dp += cpi->partition_sz[i + 1];
1324
      }
1325
    }
1326
1327
    /* update total size */
1328
    *size = 0;
1329
    for (i = 0; i < num_part + 1; ++i) {
1330
      *size += cpi->partition_sz[i];
1331
    }
1332
  }
1333
#else
1334
118k
  if (pc->multi_token_partition != ONE_PARTITION) {
1335
0
    int num_part = 1 << pc->multi_token_partition;
1336
1337
    /* partition size table at the end of first partition */
1338
0
    cpi->partition_sz[0] += 3 * (num_part - 1);
1339
0
    *size += 3 * (num_part - 1);
1340
1341
0
    validate_buffer(cx_data, 3 * (num_part - 1), cx_data_end, &pc->error);
1342
1343
0
    for (i = 1; i < num_part + 1; ++i) {
1344
0
      cpi->bc[i].error = &pc->error;
1345
0
    }
1346
1347
0
    pack_tokens_into_partitions(cpi, cx_data + 3 * (num_part - 1), cx_data_end,
1348
0
                                num_part);
1349
1350
0
    for (i = 1; i < num_part; ++i) {
1351
0
      cpi->partition_sz[i] = cpi->bc[i].pos;
1352
0
      write_partition_size(cx_data, cpi->partition_sz[i]);
1353
0
      cx_data += 3;
1354
0
      *size += cpi->partition_sz[i]; /* add to total */
1355
0
    }
1356
1357
    /* add last partition to total size */
1358
0
    cpi->partition_sz[i] = cpi->bc[i].pos;
1359
0
    *size += cpi->partition_sz[i];
1360
118k
  } else {
1361
118k
    bc[1].error = &pc->error;
1362
1363
118k
    vp8_start_encode(&cpi->bc[1], cx_data, cx_data_end);
1364
1365
118k
#if CONFIG_MULTITHREAD
1366
118k
    if (vpx_atomic_load_acquire(&cpi->b_multi_threaded)) {
1367
0
      pack_mb_row_tokens(cpi, &cpi->bc[1]);
1368
118k
    } else {
1369
118k
      vp8_pack_tokens(&cpi->bc[1], cpi->tok, cpi->tok_count);
1370
118k
    }
1371
#else
1372
    vp8_pack_tokens(&cpi->bc[1], cpi->tok, cpi->tok_count);
1373
#endif  // CONFIG_MULTITHREAD
1374
1375
118k
    vp8_stop_encode(&cpi->bc[1]);
1376
1377
118k
    *size += cpi->bc[1].pos;
1378
118k
    cpi->partition_sz[1] = cpi->bc[1].pos;
1379
118k
  }
1380
118k
#endif
1381
118k
}