Coverage Report

Created: 2025-11-16 07:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libvpx/vp9/encoder/vp9_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 <assert.h>
12
#include <stdint.h>
13
#include <stdio.h>
14
#include <limits.h>
15
16
#include "vpx/vpx_encoder.h"
17
#include "vpx_dsp/bitwriter_buffer.h"
18
#include "vpx_dsp/vpx_dsp_common.h"
19
#include "vpx_mem/vpx_mem.h"
20
#include "vpx_ports/mem_ops.h"
21
#include "vpx_ports/system_state.h"
22
#if CONFIG_BITSTREAM_DEBUG
23
#include "vpx_util/vpx_debug_util.h"
24
#endif  // CONFIG_BITSTREAM_DEBUG
25
26
#include "vp9/common/vp9_entropy.h"
27
#include "vp9/common/vp9_entropymode.h"
28
#include "vp9/common/vp9_entropymv.h"
29
#include "vp9/common/vp9_mvref_common.h"
30
#include "vp9/common/vp9_pred_common.h"
31
#include "vp9/common/vp9_seg_common.h"
32
#include "vp9/common/vp9_tile_common.h"
33
34
#include "vp9/encoder/vp9_cost.h"
35
#include "vp9/encoder/vp9_bitstream.h"
36
#include "vp9/encoder/vp9_encodemv.h"
37
#include "vp9/encoder/vp9_mcomp.h"
38
#include "vp9/encoder/vp9_segmentation.h"
39
#include "vp9/encoder/vp9_subexp.h"
40
#include "vp9/encoder/vp9_tokenize.h"
41
42
static const struct vp9_token intra_mode_encodings[INTRA_MODES] = {
43
  { 0, 1 },  { 6, 3 },   { 28, 5 },  { 30, 5 }, { 58, 6 },
44
  { 59, 6 }, { 126, 7 }, { 127, 7 }, { 62, 6 }, { 2, 2 }
45
};
46
static const struct vp9_token
47
    switchable_interp_encodings[SWITCHABLE_FILTERS] = { { 0, 1 },
48
                                                        { 2, 2 },
49
                                                        { 3, 2 } };
50
static const struct vp9_token partition_encodings[PARTITION_TYPES] = {
51
  { 0, 1 }, { 2, 2 }, { 6, 3 }, { 7, 3 }
52
};
53
static const struct vp9_token inter_mode_encodings[INTER_MODES] = {
54
  { 2, 2 }, { 6, 3 }, { 0, 1 }, { 7, 3 }
55
};
56
57
static void write_intra_mode(vpx_writer *w, PREDICTION_MODE mode,
58
5.28M
                             const vpx_prob *probs) {
59
5.28M
  assert(!is_inter_mode(mode));
60
5.28M
  vp9_write_token(w, vp9_intra_mode_tree, probs, &intra_mode_encodings[mode]);
61
5.28M
}
62
63
static void write_inter_mode(vpx_writer *w, PREDICTION_MODE mode,
64
1.06M
                             const vpx_prob *probs) {
65
1.06M
  assert(is_inter_mode(mode));
66
1.06M
  vp9_write_token(w, vp9_inter_mode_tree, probs,
67
1.06M
                  &inter_mode_encodings[INTER_OFFSET(mode)]);
68
1.06M
}
69
70
static void encode_unsigned_max(struct vpx_write_bit_buffer *wb, int data,
71
0
                                int max) {
72
0
  vpx_wb_write_literal(wb, data, get_unsigned_bits(max));
73
0
}
74
75
static void prob_diff_update(const vpx_tree_index *tree,
76
                             vpx_prob probs[/*n - 1*/],
77
                             const unsigned int counts[/*n - 1*/], int n,
78
1.16M
                             vpx_writer *w) {
79
1.16M
  int i;
80
1.16M
  unsigned int branch_ct[32][2];
81
82
  // Assuming max number of probabilities <= 32
83
1.16M
  assert(n <= 32);
84
85
1.16M
  vp9_tree_probs_from_distribution(tree, branch_ct, counts);
86
5.60M
  for (i = 0; i < n - 1; ++i)
87
4.43M
    vp9_cond_prob_diff_update(w, &probs[i], branch_ct[i]);
88
1.16M
}
89
90
static void write_selected_tx_size(const VP9_COMMON *cm,
91
471k
                                   const MACROBLOCKD *const xd, vpx_writer *w) {
92
471k
  TX_SIZE tx_size = xd->mi[0]->tx_size;
93
471k
  BLOCK_SIZE bsize = xd->mi[0]->sb_type;
94
471k
  const TX_SIZE max_tx_size = max_txsize_lookup[bsize];
95
471k
  const vpx_prob *const tx_probs =
96
471k
      get_tx_probs(max_tx_size, get_tx_size_context(xd), &cm->fc->tx_probs);
97
471k
  vpx_write(w, tx_size != TX_4X4, tx_probs[0]);
98
471k
  if (tx_size != TX_4X4 && max_tx_size >= TX_16X16) {
99
89.1k
    vpx_write(w, tx_size != TX_8X8, tx_probs[1]);
100
89.1k
    if (tx_size != TX_8X8 && max_tx_size >= TX_32X32)
101
39.9k
      vpx_write(w, tx_size != TX_16X16, tx_probs[2]);
102
89.1k
  }
103
471k
}
104
105
static int write_skip(const VP9_COMMON *cm, const MACROBLOCKD *const xd,
106
2.04M
                      int segment_id, const MODE_INFO *mi, vpx_writer *w) {
107
2.04M
  if (segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP)) {
108
0
    return 1;
109
2.04M
  } else {
110
2.04M
    const int skip = mi->skip;
111
2.04M
    vpx_write(w, skip, vp9_get_skip_prob(cm, xd));
112
2.04M
    return skip;
113
2.04M
  }
114
2.04M
}
115
116
static void update_skip_probs(VP9_COMMON *cm, vpx_writer *w,
117
54.1k
                              FRAME_COUNTS *counts) {
118
54.1k
  int k;
119
120
216k
  for (k = 0; k < SKIP_CONTEXTS; ++k)
121
162k
    vp9_cond_prob_diff_update(w, &cm->fc->skip_probs[k], counts->skip[k]);
122
54.1k
}
123
124
static void update_switchable_interp_probs(VP9_COMMON *cm, vpx_writer *w,
125
11.7k
                                           FRAME_COUNTS *counts) {
126
11.7k
  int j;
127
58.9k
  for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
128
47.1k
    prob_diff_update(vp9_switchable_interp_tree,
129
47.1k
                     cm->fc->switchable_interp_prob[j],
130
47.1k
                     counts->switchable_interp[j], SWITCHABLE_FILTERS, w);
131
11.7k
}
132
133
static void pack_mb_tokens(vpx_writer *w, TOKENEXTRA **tp,
134
                           const TOKENEXTRA *const stop,
135
2.04M
                           vpx_bit_depth_t bit_depth) {
136
2.04M
  const TOKENEXTRA *p;
137
2.04M
  const vp9_extra_bit *const extra_bits =
138
2.04M
#if CONFIG_VP9_HIGHBITDEPTH
139
2.04M
      (bit_depth == VPX_BITS_12)   ? vp9_extra_bits_high12
140
2.04M
      : (bit_depth == VPX_BITS_10) ? vp9_extra_bits_high10
141
2.04M
                                   : vp9_extra_bits;
142
#else
143
      vp9_extra_bits;
144
  (void)bit_depth;
145
#endif  // CONFIG_VP9_HIGHBITDEPTH
146
147
105M
  for (p = *tp; p < stop && p->token != EOSB_TOKEN; ++p) {
148
103M
    if (p->token == EOB_TOKEN) {
149
5.29M
      vpx_write(w, 0, p->context_tree[0]);
150
5.29M
      continue;
151
5.29M
    }
152
98.1M
    vpx_write(w, 1, p->context_tree[0]);
153
128M
    while (p->token == ZERO_TOKEN) {
154
30.0M
      vpx_write(w, 0, p->context_tree[1]);
155
30.0M
      ++p;
156
30.0M
      if (p == stop || p->token == EOSB_TOKEN) {
157
0
        *tp = (TOKENEXTRA *)(uintptr_t)p + (p->token == EOSB_TOKEN);
158
0
        return;
159
0
      }
160
30.0M
    }
161
162
98.1M
    {
163
98.1M
      const int t = p->token;
164
98.1M
      const vpx_prob *const context_tree = p->context_tree;
165
98.1M
      assert(t != ZERO_TOKEN);
166
98.1M
      assert(t != EOB_TOKEN);
167
98.1M
      assert(t != EOSB_TOKEN);
168
98.1M
      vpx_write(w, 1, context_tree[1]);
169
98.1M
      if (t == ONE_TOKEN) {
170
19.0M
        vpx_write(w, 0, context_tree[2]);
171
19.0M
        vpx_write_bit(w, p->extra & 1);
172
79.1M
      } else {  // t >= TWO_TOKEN && t < EOB_TOKEN
173
79.1M
        const struct vp9_token *const a = &vp9_coef_encodings[t];
174
79.1M
        int v = a->value;
175
79.1M
        int n = a->len;
176
79.1M
        const int e = p->extra;
177
79.1M
        vpx_write(w, 1, context_tree[2]);
178
79.1M
        vp9_write_tree(w, vp9_coef_con_tree,
179
79.1M
                       vp9_pareto8_full[context_tree[PIVOT_NODE] - 1], v,
180
79.1M
                       n - UNCONSTRAINED_NODES, 0);
181
79.1M
        if (t >= CATEGORY1_TOKEN) {
182
54.9M
          const vp9_extra_bit *const b = &extra_bits[t];
183
54.9M
          const unsigned char *pb = b->prob;
184
54.9M
          v = e >> 1;
185
54.9M
          n = b->len;  // number of bits in v, assumed nonzero
186
211M
          do {
187
211M
            const int bb = (v >> --n) & 1;
188
211M
            vpx_write(w, bb, *pb++);
189
211M
          } while (n);
190
54.9M
        }
191
79.1M
        vpx_write_bit(w, e & 1);
192
79.1M
      }
193
98.1M
    }
194
98.1M
  }
195
2.04M
  *tp = (TOKENEXTRA *)(uintptr_t)p + (p->token == EOSB_TOKEN);
196
2.04M
}
197
198
static void write_segment_id(vpx_writer *w, const struct segmentation *seg,
199
0
                             int segment_id) {
200
0
  if (seg->enabled && seg->update_map)
201
0
    vp9_write_tree(w, vp9_segment_tree, seg->tree_probs, segment_id, 3, 0);
202
0
}
203
204
// This function encodes the reference frame
205
static void write_ref_frames(const VP9_COMMON *cm, const MACROBLOCKD *const xd,
206
516k
                             vpx_writer *w) {
207
516k
  const MODE_INFO *const mi = xd->mi[0];
208
516k
  const int is_compound = has_second_ref(mi);
209
516k
  const int segment_id = mi->segment_id;
210
211
  // If segment level coding of this signal is disabled...
212
  // or the segment allows multiple reference frame options
213
516k
  if (segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME)) {
214
0
    assert(!is_compound);
215
0
    assert(mi->ref_frame[0] ==
216
0
           get_segdata(&cm->seg, segment_id, SEG_LVL_REF_FRAME));
217
516k
  } else {
218
    // does the feature use compound prediction or not
219
    // (if not specified at the frame/segment level)
220
516k
    if (cm->reference_mode == REFERENCE_MODE_SELECT) {
221
0
      vpx_write(w, is_compound, vp9_get_reference_mode_prob(cm, xd));
222
516k
    } else {
223
516k
      assert((!is_compound) == (cm->reference_mode == SINGLE_REFERENCE));
224
516k
    }
225
226
516k
    if (is_compound) {
227
0
      const int idx = cm->ref_frame_sign_bias[cm->comp_fixed_ref];
228
0
      vpx_write(w, mi->ref_frame[!idx] == cm->comp_var_ref[1],
229
0
                vp9_get_pred_prob_comp_ref_p(cm, xd));
230
516k
    } else {
231
516k
      const int bit0 = mi->ref_frame[0] != LAST_FRAME;
232
516k
      vpx_write(w, bit0, vp9_get_pred_prob_single_ref_p1(cm, xd));
233
516k
      if (bit0) {
234
183k
        const int bit1 = mi->ref_frame[0] != GOLDEN_FRAME;
235
183k
        vpx_write(w, bit1, vp9_get_pred_prob_single_ref_p2(cm, xd));
236
183k
      }
237
516k
    }
238
516k
  }
239
516k
}
240
241
static void pack_inter_mode_mvs(VP9_COMP *cpi, const MACROBLOCKD *const xd,
242
                                const MB_MODE_INFO_EXT *const mbmi_ext,
243
                                vpx_writer *w,
244
                                unsigned int *const max_mv_magnitude,
245
1.36M
                                int interp_filter_selected[][SWITCHABLE]) {
246
1.36M
  VP9_COMMON *const cm = &cpi->common;
247
1.36M
  const nmv_context *nmvc = &cm->fc->nmvc;
248
1.36M
  const struct segmentation *const seg = &cm->seg;
249
1.36M
  const MODE_INFO *const mi = xd->mi[0];
250
1.36M
  const PREDICTION_MODE mode = mi->mode;
251
1.36M
  const int segment_id = mi->segment_id;
252
1.36M
  const BLOCK_SIZE bsize = mi->sb_type;
253
1.36M
  const int allow_hp = cm->allow_high_precision_mv;
254
1.36M
  const int is_inter = is_inter_block(mi);
255
1.36M
  const int is_compound = has_second_ref(mi);
256
1.36M
  int skip, ref;
257
258
1.36M
  if (seg->update_map) {
259
0
    if (seg->temporal_update) {
260
0
      const int pred_flag = mi->seg_id_predicted;
261
0
      vpx_prob pred_prob = vp9_get_pred_prob_seg_id(seg, xd);
262
0
      vpx_write(w, pred_flag, pred_prob);
263
0
      if (!pred_flag) write_segment_id(w, seg, segment_id);
264
0
    } else {
265
0
      write_segment_id(w, seg, segment_id);
266
0
    }
267
0
  }
268
269
1.36M
  skip = write_skip(cm, xd, segment_id, mi, w);
270
271
1.36M
  if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME))
272
1.36M
    vpx_write(w, is_inter, vp9_get_intra_inter_prob(cm, xd));
273
274
1.36M
  if (bsize >= BLOCK_8X8 && cm->tx_mode == TX_MODE_SELECT &&
275
225k
      !(is_inter && skip)) {
276
211k
    write_selected_tx_size(cm, xd, w);
277
211k
  }
278
279
1.36M
  if (!is_inter) {
280
845k
    if (bsize >= BLOCK_8X8) {
281
326k
      write_intra_mode(w, mode, cm->fc->y_mode_prob[size_group_lookup[bsize]]);
282
519k
    } else {
283
519k
      int idx, idy;
284
519k
      const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
285
519k
      const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
286
1.49M
      for (idy = 0; idy < 2; idy += num_4x4_h) {
287
2.69M
        for (idx = 0; idx < 2; idx += num_4x4_w) {
288
1.72M
          const PREDICTION_MODE b_mode = mi->bmi[idy * 2 + idx].as_mode;
289
1.72M
          write_intra_mode(w, b_mode, cm->fc->y_mode_prob[0]);
290
1.72M
        }
291
974k
      }
292
519k
    }
293
845k
    write_intra_mode(w, mi->uv_mode, cm->fc->uv_mode_prob[mode]);
294
845k
  } else {
295
516k
    const int mode_ctx = mbmi_ext->mode_context[mi->ref_frame[0]];
296
516k
    const vpx_prob *const inter_probs = cm->fc->inter_mode_probs[mode_ctx];
297
516k
    write_ref_frames(cm, xd, w);
298
299
    // If segment skip is not enabled code the mode.
300
516k
    if (!segfeature_active(seg, segment_id, SEG_LVL_SKIP)) {
301
516k
      if (bsize >= BLOCK_8X8) {
302
291k
        write_inter_mode(w, mode, inter_probs);
303
291k
      }
304
516k
    }
305
306
516k
    if (cm->interp_filter == SWITCHABLE) {
307
210k
      const int ctx = get_pred_context_switchable_interp(xd);
308
210k
      vp9_write_token(w, vp9_switchable_interp_tree,
309
210k
                      cm->fc->switchable_interp_prob[ctx],
310
210k
                      &switchable_interp_encodings[mi->interp_filter]);
311
210k
      ++interp_filter_selected[0][mi->interp_filter];
312
305k
    } else {
313
305k
      assert(mi->interp_filter == cm->interp_filter);
314
305k
    }
315
316
516k
    if (bsize < BLOCK_8X8) {
317
224k
      const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
318
224k
      const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
319
224k
      int idx, idy;
320
656k
      for (idy = 0; idy < 2; idy += num_4x4_h) {
321
1.20M
        for (idx = 0; idx < 2; idx += num_4x4_w) {
322
768k
          const int j = idy * 2 + idx;
323
768k
          const PREDICTION_MODE b_mode = mi->bmi[j].as_mode;
324
768k
          write_inter_mode(w, b_mode, inter_probs);
325
768k
          if (b_mode == NEWMV) {
326
394k
            for (ref = 0; ref < 1 + is_compound; ++ref)
327
197k
              vp9_encode_mv(cpi, w, &mi->bmi[j].as_mv[ref].as_mv,
328
197k
                            &mbmi_ext->ref_mvs[mi->ref_frame[ref]][0].as_mv,
329
197k
                            nmvc, allow_hp, max_mv_magnitude);
330
197k
          }
331
768k
        }
332
431k
      }
333
291k
    } else {
334
291k
      if (mode == NEWMV) {
335
168k
        for (ref = 0; ref < 1 + is_compound; ++ref)
336
84.3k
          vp9_encode_mv(cpi, w, &mi->mv[ref].as_mv,
337
84.3k
                        &mbmi_ext->ref_mvs[mi->ref_frame[ref]][0].as_mv, nmvc,
338
84.3k
                        allow_hp, max_mv_magnitude);
339
84.3k
      }
340
291k
    }
341
516k
  }
342
1.36M
}
343
344
static void write_mb_modes_kf(const VP9_COMMON *cm, const MACROBLOCKD *xd,
345
685k
                              vpx_writer *w) {
346
685k
  const struct segmentation *const seg = &cm->seg;
347
685k
  const MODE_INFO *const mi = xd->mi[0];
348
685k
  const MODE_INFO *const above_mi = xd->above_mi;
349
685k
  const MODE_INFO *const left_mi = xd->left_mi;
350
685k
  const BLOCK_SIZE bsize = mi->sb_type;
351
352
685k
  if (seg->update_map) write_segment_id(w, seg, mi->segment_id);
353
354
685k
  write_skip(cm, xd, mi->segment_id, mi, w);
355
356
685k
  if (bsize >= BLOCK_8X8 && cm->tx_mode == TX_MODE_SELECT)
357
259k
    write_selected_tx_size(cm, xd, w);
358
359
685k
  if (bsize >= BLOCK_8X8) {
360
293k
    write_intra_mode(w, mi->mode, get_y_mode_probs(mi, above_mi, left_mi, 0));
361
392k
  } else {
362
392k
    const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
363
392k
    const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
364
392k
    int idx, idy;
365
366
1.14M
    for (idy = 0; idy < 2; idy += num_4x4_h) {
367
2.15M
      for (idx = 0; idx < 2; idx += num_4x4_w) {
368
1.40M
        const int block = idy * 2 + idx;
369
1.40M
        write_intra_mode(w, mi->bmi[block].as_mode,
370
1.40M
                         get_y_mode_probs(mi, above_mi, left_mi, block));
371
1.40M
      }
372
751k
    }
373
392k
  }
374
375
685k
  write_intra_mode(w, mi->uv_mode, vp9_kf_uv_mode_prob[mi->mode]);
376
685k
}
377
378
static void write_modes_b(VP9_COMP *cpi, MACROBLOCKD *const xd,
379
                          const TileInfo *const tile, vpx_writer *w,
380
                          TOKENEXTRA **tok, const TOKENEXTRA *const tok_end,
381
                          int mi_row, int mi_col,
382
                          unsigned int *const max_mv_magnitude,
383
2.04M
                          int interp_filter_selected[][SWITCHABLE]) {
384
2.04M
  const VP9_COMMON *const cm = &cpi->common;
385
2.04M
  const MB_MODE_INFO_EXT *const mbmi_ext =
386
2.04M
      cpi->td.mb.mbmi_ext_base + (mi_row * cm->mi_cols + mi_col);
387
2.04M
  MODE_INFO *m;
388
389
2.04M
  xd->mi = cm->mi_grid_visible + (mi_row * cm->mi_stride + mi_col);
390
2.04M
  m = xd->mi[0];
391
392
2.04M
  set_mi_row_col(xd, tile, mi_row, num_8x8_blocks_high_lookup[m->sb_type],
393
2.04M
                 mi_col, num_8x8_blocks_wide_lookup[m->sb_type], cm->mi_rows,
394
2.04M
                 cm->mi_cols);
395
2.04M
  if (frame_is_intra_only(cm)) {
396
685k
    write_mb_modes_kf(cm, xd, w);
397
1.36M
  } else {
398
1.36M
    pack_inter_mode_mvs(cpi, xd, mbmi_ext, w, max_mv_magnitude,
399
1.36M
                        interp_filter_selected);
400
1.36M
  }
401
402
2.04M
  assert(*tok < tok_end);
403
2.04M
  pack_mb_tokens(w, tok, tok_end, cm->bit_depth);
404
2.04M
}
405
406
static void write_partition(const VP9_COMMON *const cm,
407
                            const MACROBLOCKD *const xd, int hbs, int mi_row,
408
                            int mi_col, PARTITION_TYPE p, BLOCK_SIZE bsize,
409
2.75M
                            vpx_writer *w) {
410
2.75M
  const int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
411
2.75M
  const vpx_prob *const probs = xd->partition_probs[ctx];
412
2.75M
  const int has_rows = (mi_row + hbs) < cm->mi_rows;
413
2.75M
  const int has_cols = (mi_col + hbs) < cm->mi_cols;
414
415
2.75M
  if (has_rows && has_cols) {
416
2.54M
    vp9_write_token(w, vp9_partition_tree, probs, &partition_encodings[p]);
417
2.54M
  } else if (!has_rows && has_cols) {
418
118k
    assert(p == PARTITION_SPLIT || p == PARTITION_HORZ);
419
118k
    vpx_write(w, p == PARTITION_SPLIT, probs[1]);
420
118k
  } else if (has_rows && !has_cols) {
421
47.7k
    assert(p == PARTITION_SPLIT || p == PARTITION_VERT);
422
47.7k
    vpx_write(w, p == PARTITION_SPLIT, probs[2]);
423
47.7k
  } else {
424
43.8k
    assert(p == PARTITION_SPLIT);
425
43.8k
  }
426
2.75M
}
427
428
static void write_modes_sb(VP9_COMP *cpi, MACROBLOCKD *const xd,
429
                           const TileInfo *const tile, vpx_writer *w,
430
                           TOKENEXTRA **tok, const TOKENEXTRA *const tok_end,
431
                           int mi_row, int mi_col, BLOCK_SIZE bsize,
432
                           unsigned int *const max_mv_magnitude,
433
3.15M
                           int interp_filter_selected[][SWITCHABLE]) {
434
3.15M
  const VP9_COMMON *const cm = &cpi->common;
435
3.15M
  const int bsl = b_width_log2_lookup[bsize];
436
3.15M
  const int bs = (1 << bsl) / 4;
437
3.15M
  PARTITION_TYPE partition;
438
3.15M
  BLOCK_SIZE subsize;
439
3.15M
  const MODE_INFO *m = NULL;
440
441
3.15M
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
442
443
2.75M
  m = cm->mi_grid_visible[mi_row * cm->mi_stride + mi_col];
444
445
2.75M
  partition = partition_lookup[bsl][m->sb_type];
446
2.75M
  write_partition(cm, xd, bs, mi_row, mi_col, partition, bsize, w);
447
2.75M
  subsize = get_subsize(bsize, partition);
448
2.75M
  if (subsize < BLOCK_8X8) {
449
1.13M
    write_modes_b(cpi, xd, tile, w, tok, tok_end, mi_row, mi_col,
450
1.13M
                  max_mv_magnitude, interp_filter_selected);
451
1.61M
  } else {
452
1.61M
    switch (partition) {
453
773k
      case PARTITION_NONE:
454
773k
        write_modes_b(cpi, xd, tile, w, tok, tok_end, mi_row, mi_col,
455
773k
                      max_mv_magnitude, interp_filter_selected);
456
773k
        break;
457
53.7k
      case PARTITION_HORZ:
458
53.7k
        write_modes_b(cpi, xd, tile, w, tok, tok_end, mi_row, mi_col,
459
53.7k
                      max_mv_magnitude, interp_filter_selected);
460
53.7k
        if (mi_row + bs < cm->mi_rows)
461
33.4k
          write_modes_b(cpi, xd, tile, w, tok, tok_end, mi_row + bs, mi_col,
462
33.4k
                        max_mv_magnitude, interp_filter_selected);
463
53.7k
        break;
464
30.7k
      case PARTITION_VERT:
465
30.7k
        write_modes_b(cpi, xd, tile, w, tok, tok_end, mi_row, mi_col,
466
30.7k
                      max_mv_magnitude, interp_filter_selected);
467
30.7k
        if (mi_col + bs < cm->mi_cols)
468
19.9k
          write_modes_b(cpi, xd, tile, w, tok, tok_end, mi_row, mi_col + bs,
469
19.9k
                        max_mv_magnitude, interp_filter_selected);
470
30.7k
        break;
471
760k
      default:
472
760k
        assert(partition == PARTITION_SPLIT);
473
760k
        write_modes_sb(cpi, xd, tile, w, tok, tok_end, mi_row, mi_col, subsize,
474
760k
                       max_mv_magnitude, interp_filter_selected);
475
760k
        write_modes_sb(cpi, xd, tile, w, tok, tok_end, mi_row, mi_col + bs,
476
760k
                       subsize, max_mv_magnitude, interp_filter_selected);
477
760k
        write_modes_sb(cpi, xd, tile, w, tok, tok_end, mi_row + bs, mi_col,
478
760k
                       subsize, max_mv_magnitude, interp_filter_selected);
479
760k
        write_modes_sb(cpi, xd, tile, w, tok, tok_end, mi_row + bs, mi_col + bs,
480
760k
                       subsize, max_mv_magnitude, interp_filter_selected);
481
760k
        break;
482
1.61M
    }
483
1.61M
  }
484
485
  // update partition context
486
2.75M
  if (bsize >= BLOCK_8X8 &&
487
2.75M
      (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
488
1.99M
    update_partition_context(xd, mi_row, mi_col, subsize, bsize);
489
2.75M
}
490
491
static void write_modes(VP9_COMP *cpi, MACROBLOCKD *const xd,
492
                        const TileInfo *const tile, vpx_writer *w, int tile_row,
493
                        int tile_col, unsigned int *const max_mv_magnitude,
494
58.9k
                        int interp_filter_selected[][SWITCHABLE]) {
495
58.9k
  const VP9_COMMON *const cm = &cpi->common;
496
58.9k
  int mi_row, mi_col, tile_sb_row;
497
58.9k
  TOKENEXTRA *tok = NULL;
498
58.9k
  TOKENEXTRA *tok_end = NULL;
499
500
58.9k
  set_partition_probs(cm, xd);
501
502
135k
  for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
503
76.1k
       mi_row += MI_BLOCK_SIZE) {
504
76.1k
    tile_sb_row = mi_cols_aligned_to_sb(mi_row - tile->mi_row_start) >>
505
76.1k
                  MI_BLOCK_SIZE_LOG2;
506
76.1k
    tok = cpi->tplist[tile_row][tile_col][tile_sb_row].start;
507
76.1k
    tok_end = tok + cpi->tplist[tile_row][tile_col][tile_sb_row].count;
508
509
76.1k
    vp9_zero(xd->left_seg_context);
510
192k
    for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
511
116k
         mi_col += MI_BLOCK_SIZE)
512
116k
      write_modes_sb(cpi, xd, tile, w, &tok, tok_end, mi_row, mi_col,
513
116k
                     BLOCK_64X64, max_mv_magnitude, interp_filter_selected);
514
515
76.1k
    assert(tok == cpi->tplist[tile_row][tile_col][tile_sb_row].stop);
516
76.1k
  }
517
58.9k
}
518
519
static void build_tree_distribution(VP9_COMP *cpi, TX_SIZE tx_size,
520
                                    vp9_coeff_stats *coef_branch_ct,
521
39.9k
                                    vp9_coeff_probs_model *coef_probs) {
522
39.9k
  vp9_coeff_count *coef_counts = cpi->td.rd_counts.coef_counts[tx_size];
523
39.9k
  unsigned int(*eob_branch_ct)[REF_TYPES][COEF_BANDS][COEFF_CONTEXTS] =
524
39.9k
      cpi->common.counts.eob_branch[tx_size];
525
39.9k
  int i, j, k, l, m;
526
527
119k
  for (i = 0; i < PLANE_TYPES; ++i) {
528
239k
    for (j = 0; j < REF_TYPES; ++j) {
529
1.11M
      for (k = 0; k < COEF_BANDS; ++k) {
530
6.23M
        for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
531
5.27M
          vp9_tree_probs_from_distribution(vp9_coef_tree,
532
5.27M
                                           coef_branch_ct[i][j][k][l],
533
5.27M
                                           coef_counts[i][j][k][l]);
534
5.27M
          coef_branch_ct[i][j][k][l][0][1] =
535
5.27M
              eob_branch_ct[i][j][k][l] - coef_branch_ct[i][j][k][l][0][0];
536
21.1M
          for (m = 0; m < UNCONSTRAINED_NODES; ++m)
537
15.8M
            coef_probs[i][j][k][l][m] =
538
15.8M
                get_binary_prob(coef_branch_ct[i][j][k][l][m][0],
539
15.8M
                                coef_branch_ct[i][j][k][l][m][1]);
540
5.27M
        }
541
959k
      }
542
159k
    }
543
79.9k
  }
544
39.9k
}
545
546
static void update_coef_probs_common(vpx_writer *const bc, VP9_COMP *cpi,
547
                                     TX_SIZE tx_size,
548
                                     vp9_coeff_stats *frame_branch_ct,
549
39.9k
                                     vp9_coeff_probs_model *new_coef_probs) {
550
39.9k
  vp9_coeff_probs_model *old_coef_probs = cpi->common.fc->coef_probs[tx_size];
551
39.9k
  const vpx_prob upd = DIFF_UPDATE_PROB;
552
39.9k
  const int entropy_nodes_update = UNCONSTRAINED_NODES;
553
39.9k
  int i, j, k, l, t;
554
39.9k
  int stepsize = cpi->sf.coeff_prob_appx_step;
555
556
39.9k
  switch (cpi->sf.use_fast_coef_updates) {
557
39.9k
    case TWO_LOOP: {
558
      /* dry run to see if there is any update at all needed */
559
39.9k
      int64_t savings = 0;
560
39.9k
      int update[2] = { 0, 0 };
561
119k
      for (i = 0; i < PLANE_TYPES; ++i) {
562
239k
        for (j = 0; j < REF_TYPES; ++j) {
563
1.11M
          for (k = 0; k < COEF_BANDS; ++k) {
564
6.23M
            for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
565
21.1M
              for (t = 0; t < entropy_nodes_update; ++t) {
566
15.8M
                vpx_prob newp = new_coef_probs[i][j][k][l][t];
567
15.8M
                const vpx_prob oldp = old_coef_probs[i][j][k][l][t];
568
15.8M
                int64_t s;
569
15.8M
                int u = 0;
570
15.8M
                if (t == PIVOT_NODE)
571
5.27M
                  s = vp9_prob_diff_update_savings_search_model(
572
5.27M
                      frame_branch_ct[i][j][k][l][0], oldp, &newp, upd,
573
5.27M
                      stepsize);
574
10.5M
                else
575
10.5M
                  s = vp9_prob_diff_update_savings_search(
576
10.5M
                      frame_branch_ct[i][j][k][l][t], oldp, &newp, upd);
577
15.8M
                if (s > 0 && newp != oldp) u = 1;
578
15.8M
                if (u)
579
572k
                  savings += s - (int)(vp9_cost_zero(upd));
580
15.2M
                else
581
15.2M
                  savings -= (int)(vp9_cost_zero(upd));
582
15.8M
                update[u]++;
583
15.8M
              }
584
5.27M
            }
585
959k
          }
586
159k
        }
587
79.9k
      }
588
589
      // printf("Update %d %d, savings %d\n", update[0], update[1], savings);
590
      /* Is coef updated at all */
591
39.9k
      if (update[1] == 0 || savings < 0) {
592
14.1k
        vpx_write_bit(bc, 0);
593
14.1k
        return;
594
14.1k
      }
595
25.8k
      vpx_write_bit(bc, 1);
596
77.4k
      for (i = 0; i < PLANE_TYPES; ++i) {
597
154k
        for (j = 0; j < REF_TYPES; ++j) {
598
723k
          for (k = 0; k < COEF_BANDS; ++k) {
599
4.02M
            for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
600
              // calc probs and branch cts for this frame only
601
13.6M
              for (t = 0; t < entropy_nodes_update; ++t) {
602
10.2M
                vpx_prob newp = new_coef_probs[i][j][k][l][t];
603
10.2M
                vpx_prob *oldp = old_coef_probs[i][j][k][l] + t;
604
10.2M
                int64_t s;
605
10.2M
                int u = 0;
606
10.2M
                if (t == PIVOT_NODE)
607
3.40M
                  s = vp9_prob_diff_update_savings_search_model(
608
3.40M
                      frame_branch_ct[i][j][k][l][0], *oldp, &newp, upd,
609
3.40M
                      stepsize);
610
6.81M
                else
611
6.81M
                  s = vp9_prob_diff_update_savings_search(
612
6.81M
                      frame_branch_ct[i][j][k][l][t], *oldp, &newp, upd);
613
10.2M
                if (s > 0 && newp != *oldp) u = 1;
614
10.2M
                vpx_write(bc, u, upd);
615
10.2M
                if (u) {
616
                  /* send/use new probability */
617
563k
                  vp9_write_prob_diff_update(bc, newp, *oldp);
618
563k
                  *oldp = newp;
619
563k
                }
620
10.2M
              }
621
3.40M
            }
622
619k
          }
623
103k
        }
624
51.6k
      }
625
25.8k
      return;
626
39.9k
    }
627
628
0
    default: {
629
0
      int updates = 0;
630
0
      int noupdates_before_first = 0;
631
0
      assert(cpi->sf.use_fast_coef_updates == ONE_LOOP_REDUCED);
632
0
      for (i = 0; i < PLANE_TYPES; ++i) {
633
0
        for (j = 0; j < REF_TYPES; ++j) {
634
0
          for (k = 0; k < COEF_BANDS; ++k) {
635
0
            for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
636
              // calc probs and branch cts for this frame only
637
0
              for (t = 0; t < entropy_nodes_update; ++t) {
638
0
                vpx_prob newp = new_coef_probs[i][j][k][l][t];
639
0
                vpx_prob *oldp = old_coef_probs[i][j][k][l] + t;
640
0
                int64_t s;
641
0
                int u = 0;
642
643
0
                if (t == PIVOT_NODE) {
644
0
                  s = vp9_prob_diff_update_savings_search_model(
645
0
                      frame_branch_ct[i][j][k][l][0], *oldp, &newp, upd,
646
0
                      stepsize);
647
0
                } else {
648
0
                  s = vp9_prob_diff_update_savings_search(
649
0
                      frame_branch_ct[i][j][k][l][t], *oldp, &newp, upd);
650
0
                }
651
652
0
                if (s > 0 && newp != *oldp) u = 1;
653
0
                updates += u;
654
0
                if (u == 0 && updates == 0) {
655
0
                  noupdates_before_first++;
656
0
                  continue;
657
0
                }
658
0
                if (u == 1 && updates == 1) {
659
0
                  int v;
660
                  // first update
661
0
                  vpx_write_bit(bc, 1);
662
0
                  for (v = 0; v < noupdates_before_first; ++v)
663
0
                    vpx_write(bc, 0, upd);
664
0
                }
665
0
                vpx_write(bc, u, upd);
666
0
                if (u) {
667
                  /* send/use new probability */
668
0
                  vp9_write_prob_diff_update(bc, newp, *oldp);
669
0
                  *oldp = newp;
670
0
                }
671
0
              }
672
0
            }
673
0
          }
674
0
        }
675
0
      }
676
0
      if (updates == 0) {
677
0
        vpx_write_bit(bc, 0);  // no updates
678
0
      }
679
0
      return;
680
39.9k
    }
681
39.9k
  }
682
39.9k
}
683
684
54.1k
static void update_coef_probs(VP9_COMP *cpi, vpx_writer *w) {
685
54.1k
  const TX_MODE tx_mode = cpi->common.tx_mode;
686
54.1k
  const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
687
54.1k
  TX_SIZE tx_size;
688
226k
  for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size) {
689
172k
    vp9_coeff_stats frame_branch_ct[PLANE_TYPES];
690
172k
    vp9_coeff_probs_model frame_coef_probs[PLANE_TYPES];
691
172k
    if (cpi->td.counts->tx.tx_totals[tx_size] <= 20 ||
692
132k
        (tx_size >= TX_16X16 && cpi->sf.tx_size_search_method == USE_TX_8X8)) {
693
132k
      vpx_write_bit(w, 0);
694
132k
    } else {
695
39.9k
      build_tree_distribution(cpi, tx_size, frame_branch_ct, frame_coef_probs);
696
39.9k
      update_coef_probs_common(w, cpi, tx_size, frame_branch_ct,
697
39.9k
                               frame_coef_probs);
698
39.9k
    }
699
172k
  }
700
54.1k
}
701
702
static void encode_loopfilter(struct loopfilter *lf,
703
54.1k
                              struct vpx_write_bit_buffer *wb) {
704
54.1k
  int i;
705
706
  // Encode the loop filter level and type
707
54.1k
  vpx_wb_write_literal(wb, lf->filter_level, 6);
708
54.1k
  vpx_wb_write_literal(wb, lf->sharpness_level, 3);
709
710
  // Write out loop filter deltas applied at the MB level based on mode or
711
  // ref frame (if they are enabled).
712
54.1k
  vpx_wb_write_bit(wb, lf->mode_ref_delta_enabled);
713
714
54.1k
  if (lf->mode_ref_delta_enabled) {
715
54.1k
    vpx_wb_write_bit(wb, lf->mode_ref_delta_update);
716
54.1k
    if (lf->mode_ref_delta_update) {
717
64.1k
      for (i = 0; i < MAX_REF_LF_DELTAS; i++) {
718
51.2k
        const int delta = lf->ref_deltas[i];
719
51.2k
        const int changed = delta != lf->last_ref_deltas[i];
720
51.2k
        vpx_wb_write_bit(wb, changed);
721
51.2k
        if (changed) {
722
38.4k
          lf->last_ref_deltas[i] = delta;
723
38.4k
          vpx_wb_write_literal(wb, abs(delta) & 0x3F, 6);
724
38.4k
          vpx_wb_write_bit(wb, delta < 0);
725
38.4k
        }
726
51.2k
      }
727
728
38.4k
      for (i = 0; i < MAX_MODE_LF_DELTAS; i++) {
729
25.6k
        const int delta = lf->mode_deltas[i];
730
25.6k
        const int changed = delta != lf->last_mode_deltas[i];
731
25.6k
        vpx_wb_write_bit(wb, changed);
732
25.6k
        if (changed) {
733
0
          lf->last_mode_deltas[i] = delta;
734
0
          vpx_wb_write_literal(wb, abs(delta) & 0x3F, 6);
735
0
          vpx_wb_write_bit(wb, delta < 0);
736
0
        }
737
25.6k
      }
738
12.8k
    }
739
54.1k
  }
740
54.1k
}
741
742
162k
static void write_delta_q(struct vpx_write_bit_buffer *wb, int delta_q) {
743
162k
  if (delta_q != 0) {
744
0
    vpx_wb_write_bit(wb, 1);
745
0
    vpx_wb_write_literal(wb, abs(delta_q), 4);
746
0
    vpx_wb_write_bit(wb, delta_q < 0);
747
162k
  } else {
748
162k
    vpx_wb_write_bit(wb, 0);
749
162k
  }
750
162k
}
751
752
static void encode_quantization(const VP9_COMMON *const cm,
753
54.1k
                                struct vpx_write_bit_buffer *wb) {
754
54.1k
  vpx_wb_write_literal(wb, cm->base_qindex, QINDEX_BITS);
755
54.1k
  write_delta_q(wb, cm->y_dc_delta_q);
756
54.1k
  write_delta_q(wb, cm->uv_dc_delta_q);
757
54.1k
  write_delta_q(wb, cm->uv_ac_delta_q);
758
54.1k
}
759
760
static void encode_segmentation(VP9_COMMON *cm, MACROBLOCKD *xd,
761
54.1k
                                struct vpx_write_bit_buffer *wb) {
762
54.1k
  int i, j;
763
764
54.1k
  const struct segmentation *seg = &cm->seg;
765
766
54.1k
  vpx_wb_write_bit(wb, seg->enabled);
767
54.1k
  if (!seg->enabled) return;
768
769
  // Segmentation map
770
0
  vpx_wb_write_bit(wb, seg->update_map);
771
0
  if (seg->update_map) {
772
    // Select the coding strategy (temporal or spatial)
773
0
    vp9_choose_segmap_coding_method(cm, xd);
774
    // Write out probabilities used to decode unpredicted  macro-block segments
775
0
    for (i = 0; i < SEG_TREE_PROBS; i++) {
776
0
      const int prob = seg->tree_probs[i];
777
0
      const int update = prob != MAX_PROB;
778
0
      vpx_wb_write_bit(wb, update);
779
0
      if (update) vpx_wb_write_literal(wb, prob, 8);
780
0
    }
781
782
    // Write out the chosen coding method.
783
0
    vpx_wb_write_bit(wb, seg->temporal_update);
784
0
    if (seg->temporal_update) {
785
0
      for (i = 0; i < PREDICTION_PROBS; i++) {
786
0
        const int prob = seg->pred_probs[i];
787
0
        const int update = prob != MAX_PROB;
788
0
        vpx_wb_write_bit(wb, update);
789
0
        if (update) vpx_wb_write_literal(wb, prob, 8);
790
0
      }
791
0
    }
792
0
  }
793
794
  // Segmentation data
795
0
  vpx_wb_write_bit(wb, seg->update_data);
796
0
  if (seg->update_data) {
797
0
    vpx_wb_write_bit(wb, seg->abs_delta);
798
799
0
    for (i = 0; i < MAX_SEGMENTS; i++) {
800
0
      for (j = 0; j < SEG_LVL_MAX; j++) {
801
0
        const int active = segfeature_active(seg, i, j);
802
0
        vpx_wb_write_bit(wb, active);
803
0
        if (active) {
804
0
          const int data = get_segdata(seg, i, j);
805
0
          const int data_max = vp9_seg_feature_data_max(j);
806
807
0
          if (vp9_is_segfeature_signed(j)) {
808
0
            encode_unsigned_max(wb, abs(data), data_max);
809
0
            vpx_wb_write_bit(wb, data < 0);
810
0
          } else {
811
0
            encode_unsigned_max(wb, data, data_max);
812
0
          }
813
0
        }
814
0
      }
815
0
    }
816
0
  }
817
0
}
818
819
static void encode_txfm_probs(VP9_COMMON *cm, vpx_writer *w,
820
46.7k
                              FRAME_COUNTS *counts) {
821
  // Mode
822
46.7k
  vpx_write_literal(w, VPXMIN(cm->tx_mode, ALLOW_32X32), 2);
823
46.7k
  if (cm->tx_mode >= ALLOW_32X32)
824
37.2k
    vpx_write_bit(w, cm->tx_mode == TX_MODE_SELECT);
825
826
  // Probabilities
827
46.7k
  if (cm->tx_mode == TX_MODE_SELECT) {
828
12.9k
    int i, j;
829
12.9k
    unsigned int ct_8x8p[TX_SIZES - 3][2];
830
12.9k
    unsigned int ct_16x16p[TX_SIZES - 2][2];
831
12.9k
    unsigned int ct_32x32p[TX_SIZES - 1][2];
832
833
38.9k
    for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
834
25.9k
      tx_counts_to_branch_counts_8x8(counts->tx.p8x8[i], ct_8x8p);
835
51.8k
      for (j = 0; j < TX_SIZES - 3; j++)
836
25.9k
        vp9_cond_prob_diff_update(w, &cm->fc->tx_probs.p8x8[i][j], ct_8x8p[j]);
837
25.9k
    }
838
839
38.9k
    for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
840
25.9k
      tx_counts_to_branch_counts_16x16(counts->tx.p16x16[i], ct_16x16p);
841
77.8k
      for (j = 0; j < TX_SIZES - 2; j++)
842
51.8k
        vp9_cond_prob_diff_update(w, &cm->fc->tx_probs.p16x16[i][j],
843
51.8k
                                  ct_16x16p[j]);
844
25.9k
    }
845
846
38.9k
    for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
847
25.9k
      tx_counts_to_branch_counts_32x32(counts->tx.p32x32[i], ct_32x32p);
848
103k
      for (j = 0; j < TX_SIZES - 1; j++)
849
77.8k
        vp9_cond_prob_diff_update(w, &cm->fc->tx_probs.p32x32[i][j],
850
77.8k
                                  ct_32x32p[j]);
851
25.9k
    }
852
12.9k
  }
853
46.7k
}
854
855
static void write_interp_filter(INTERP_FILTER filter,
856
41.3k
                                struct vpx_write_bit_buffer *wb) {
857
41.3k
  const int filter_to_literal[] = { 1, 0, 2, 3 };
858
859
41.3k
  vpx_wb_write_bit(wb, filter == SWITCHABLE);
860
41.3k
  if (filter != SWITCHABLE)
861
29.5k
    vpx_wb_write_literal(wb, filter_to_literal[filter], 2);
862
41.3k
}
863
864
41.3k
static void fix_interp_filter(VP9_COMMON *cm, FRAME_COUNTS *counts) {
865
41.3k
  if (cm->interp_filter == SWITCHABLE) {
866
    // Check to see if only one of the filters is actually used
867
17.5k
    int count[SWITCHABLE_FILTERS];
868
17.5k
    int i, j, c = 0;
869
70.3k
    for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
870
52.7k
      count[i] = 0;
871
263k
      for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
872
210k
        count[i] += counts->switchable_interp[j][i];
873
52.7k
      c += (count[i] > 0);
874
52.7k
    }
875
17.5k
    if (c == 1) {
876
      // Only one filter is used. So set the filter at frame level
877
6.66k
      for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
878
6.66k
        if (count[i]) {
879
5.79k
          cm->interp_filter = i;
880
5.79k
          break;
881
5.79k
        }
882
6.66k
      }
883
5.79k
    }
884
17.5k
  }
885
41.3k
}
886
887
static void write_tile_info(const VP9_COMMON *const cm,
888
54.1k
                            struct vpx_write_bit_buffer *wb) {
889
54.1k
  int min_log2_tile_cols, max_log2_tile_cols, ones;
890
54.1k
  vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
891
892
  // columns
893
54.1k
  ones = cm->log2_tile_cols - min_log2_tile_cols;
894
55.6k
  while (ones--) vpx_wb_write_bit(wb, 1);
895
896
54.1k
  if (cm->log2_tile_cols < max_log2_tile_cols) vpx_wb_write_bit(wb, 0);
897
898
  // rows
899
54.1k
  vpx_wb_write_bit(wb, cm->log2_tile_rows != 0);
900
54.1k
  if (cm->log2_tile_rows != 0) vpx_wb_write_bit(wb, cm->log2_tile_rows != 1);
901
54.1k
}
902
903
41.3k
int vp9_get_refresh_mask(VP9_COMP *cpi) {
904
41.3k
  if (cpi->ext_ratectrl.ready &&
905
0
      (cpi->ext_ratectrl.funcs.rc_type & VPX_RC_GOP) != 0 &&
906
0
      cpi->ext_ratectrl.funcs.get_gop_decision != NULL) {
907
0
    GF_GROUP *const gf_group = &cpi->twopass.gf_group;
908
0
    const int this_gf_index = gf_group->index;
909
0
    const int update_ref_idx = gf_group->update_ref_idx[this_gf_index];
910
911
0
    if (update_ref_idx != INVALID_IDX) {
912
0
      return (1 << update_ref_idx);
913
0
    } else {
914
0
      return 0;
915
0
    }
916
0
  }
917
41.3k
  if (vp9_preserve_existing_gf(cpi)) {
918
    // We have decided to preserve the previously existing golden frame as our
919
    // new ARF frame. However, in the short term we leave it in the GF slot and,
920
    // if we're updating the GF with the current decoded frame, we save it
921
    // instead to the ARF slot.
922
    // Later, in the function vp9_encoder.c:vp9_update_reference_frames() we
923
    // will swap gld_fb_idx and alt_fb_idx to achieve our objective. We do it
924
    // there so that it can be done outside of the recode loop.
925
    // Note: This is highly specific to the use of ARF as a forward reference,
926
    // and this needs to be generalized as other uses are implemented
927
    // (like RTC/temporal scalability).
928
0
    return (cpi->refresh_last_frame << cpi->lst_fb_idx) |
929
0
           (cpi->refresh_golden_frame << cpi->alt_fb_idx);
930
41.3k
  } else {
931
41.3k
    int arf_idx = cpi->alt_fb_idx;
932
41.3k
    GF_GROUP *const gf_group = &cpi->twopass.gf_group;
933
934
41.3k
    if (cpi->multi_layer_arf) {
935
0
      for (arf_idx = 0; arf_idx < REF_FRAMES; ++arf_idx) {
936
0
        if (arf_idx != cpi->alt_fb_idx && arf_idx != cpi->lst_fb_idx &&
937
0
            arf_idx != cpi->gld_fb_idx) {
938
0
          int idx;
939
0
          for (idx = 0; idx < gf_group->stack_size; ++idx)
940
0
            if (arf_idx == gf_group->arf_index_stack[idx]) break;
941
0
          if (idx == gf_group->stack_size) break;
942
0
        }
943
0
      }
944
0
    }
945
41.3k
    cpi->twopass.gf_group.top_arf_idx = arf_idx;
946
947
41.3k
    if (cpi->use_svc && cpi->svc.use_set_ref_frame_config &&
948
0
        cpi->svc.temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS)
949
0
      return cpi->svc.update_buffer_slot[cpi->svc.spatial_layer_id];
950
41.3k
    return (cpi->refresh_last_frame << cpi->lst_fb_idx) |
951
41.3k
           (cpi->refresh_golden_frame << cpi->gld_fb_idx) |
952
41.3k
           (cpi->refresh_alt_ref_frame << arf_idx);
953
41.3k
  }
954
41.3k
}
955
956
0
static int encode_tile_worker(void *arg1, void *arg2) {
957
0
  VP9_COMP *cpi = (VP9_COMP *)arg1;
958
0
  VP9BitstreamWorkerData *data = (VP9BitstreamWorkerData *)arg2;
959
0
  MACROBLOCKD *const xd = &data->xd;
960
0
  const int tile_row = 0;
961
0
  vpx_start_encode(&data->bit_writer, data->dest, data->dest_size);
962
0
  write_modes(cpi, xd, &cpi->tile_data[data->tile_idx].tile_info,
963
0
              &data->bit_writer, tile_row, data->tile_idx,
964
0
              &data->max_mv_magnitude, data->interp_filter_selected);
965
0
  return vpx_stop_encode(&data->bit_writer) == 0;
966
0
}
967
968
4.01k
void vp9_bitstream_encode_tiles_buffer_dealloc(VP9_COMP *const cpi) {
969
4.01k
  if (cpi->vp9_bitstream_worker_data) {
970
0
    int i;
971
0
    for (i = 1; i < cpi->num_workers; ++i) {
972
0
      vpx_free(cpi->vp9_bitstream_worker_data[i].dest);
973
0
    }
974
0
    vpx_free(cpi->vp9_bitstream_worker_data);
975
0
    cpi->vp9_bitstream_worker_data = NULL;
976
0
  }
977
4.01k
}
978
979
0
static size_t encode_tiles_buffer_alloc_size(const VP9_COMP *cpi) {
980
0
  const VP9_COMMON *cm = &cpi->common;
981
0
  const int image_bps =
982
0
      (8 + 2 * (8 >> (cm->subsampling_x + cm->subsampling_y))) *
983
0
      (1 + (cm->bit_depth > 8));
984
0
  const int64_t size =
985
0
      (int64_t)cpi->oxcf.width * cpi->oxcf.height * image_bps / 8;
986
0
  return (size_t)size;
987
0
}
988
989
static void encode_tiles_buffer_alloc(VP9_COMP *const cpi,
990
0
                                      size_t buffer_alloc_size) {
991
0
  VP9_COMMON *const cm = &cpi->common;
992
0
  int i;
993
0
  const size_t worker_data_size =
994
0
      cpi->num_workers * sizeof(*cpi->vp9_bitstream_worker_data);
995
0
  CHECK_MEM_ERROR(&cm->error, cpi->vp9_bitstream_worker_data,
996
0
                  vpx_memalign(16, worker_data_size));
997
0
  memset(cpi->vp9_bitstream_worker_data, 0, worker_data_size);
998
0
  for (i = 1; i < cpi->num_workers; ++i) {
999
0
    CHECK_MEM_ERROR(&cm->error, cpi->vp9_bitstream_worker_data[i].dest,
1000
0
                    vpx_malloc(buffer_alloc_size));
1001
0
    cpi->vp9_bitstream_worker_data[i].dest_size = buffer_alloc_size;
1002
0
  }
1003
0
}
1004
1005
static size_t encode_tiles_mt(VP9_COMP *cpi, uint8_t *data_ptr,
1006
0
                              size_t data_size) {
1007
0
  const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
1008
0
  VP9_COMMON *const cm = &cpi->common;
1009
0
  const int tile_cols = 1 << cm->log2_tile_cols;
1010
0
  const int num_workers = cpi->num_workers;
1011
0
  size_t total_size = 0;
1012
0
  int tile_col = 0;
1013
0
  int error = 0;
1014
1015
0
  const size_t buffer_alloc_size = encode_tiles_buffer_alloc_size(cpi);
1016
0
  if (!cpi->vp9_bitstream_worker_data ||
1017
0
      cpi->vp9_bitstream_worker_data[1].dest_size != buffer_alloc_size) {
1018
0
    vp9_bitstream_encode_tiles_buffer_dealloc(cpi);
1019
0
    encode_tiles_buffer_alloc(cpi, buffer_alloc_size);
1020
0
  }
1021
1022
0
  while (tile_col < tile_cols) {
1023
0
    int i, j;
1024
0
    for (i = 0; i < num_workers && tile_col < tile_cols; ++i) {
1025
0
      VPxWorker *const worker = &cpi->workers[i];
1026
0
      VP9BitstreamWorkerData *const data = &cpi->vp9_bitstream_worker_data[i];
1027
1028
      // Populate the worker data.
1029
0
      data->xd = cpi->td.mb.e_mbd;
1030
0
      data->tile_idx = tile_col;
1031
0
      data->max_mv_magnitude = cpi->max_mv_magnitude;
1032
0
      memset(data->interp_filter_selected, 0,
1033
0
             sizeof(data->interp_filter_selected[0][0]) * SWITCHABLE);
1034
1035
      // First thread can directly write into the output buffer.
1036
0
      if (i == 0) {
1037
        // If this worker happens to be for the last tile, then do not offset it
1038
        // by 4 for the tile size.
1039
0
        const size_t offset = total_size + (tile_col == tile_cols - 1 ? 0 : 4);
1040
0
        if (data_size < offset) {
1041
0
          vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1042
0
                             "encode_tiles_mt: output buffer full");
1043
0
        }
1044
0
        data->dest = data_ptr + offset;
1045
0
        data->dest_size = data_size - offset;
1046
0
      }
1047
0
      worker->data1 = cpi;
1048
0
      worker->data2 = data;
1049
0
      worker->hook = encode_tile_worker;
1050
0
      worker->had_error = 0;
1051
1052
0
      if (i < num_workers - 1) {
1053
0
        winterface->launch(worker);
1054
0
      } else {
1055
0
        winterface->execute(worker);
1056
0
      }
1057
0
      ++tile_col;
1058
0
    }
1059
0
    for (j = 0; j < i; ++j) {
1060
0
      VPxWorker *const worker = &cpi->workers[j];
1061
0
      VP9BitstreamWorkerData *const data =
1062
0
          (VP9BitstreamWorkerData *)worker->data2;
1063
0
      uint32_t tile_size;
1064
0
      int k;
1065
1066
0
      if (!winterface->sync(worker)) {
1067
0
        error = 1;
1068
0
        continue;
1069
0
      }
1070
1071
0
      tile_size = data->bit_writer.pos;
1072
1073
      // Aggregate per-thread bitstream stats.
1074
0
      cpi->max_mv_magnitude =
1075
0
          VPXMAX(cpi->max_mv_magnitude, data->max_mv_magnitude);
1076
0
      for (k = 0; k < SWITCHABLE; ++k) {
1077
0
        cpi->interp_filter_selected[0][k] += data->interp_filter_selected[0][k];
1078
0
      }
1079
1080
      // Prefix the size of the tile on all but the last.
1081
0
      if (tile_col != tile_cols || j < i - 1) {
1082
0
        if (data_size - total_size < 4) {
1083
0
          error = 1;
1084
0
          continue;
1085
0
        }
1086
0
        mem_put_be32(data_ptr + total_size, tile_size);
1087
0
        total_size += 4;
1088
0
      }
1089
0
      if (j > 0) {
1090
0
        if (data_size - total_size < tile_size) {
1091
0
          error = 1;
1092
0
          continue;
1093
0
        }
1094
0
        memcpy(data_ptr + total_size, data->dest, tile_size);
1095
0
      }
1096
0
      total_size += tile_size;
1097
0
    }
1098
0
    if (error) {
1099
0
      vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1100
0
                         "encode_tiles_mt: output buffer full");
1101
0
    }
1102
0
  }
1103
0
  return total_size;
1104
0
}
1105
1106
54.1k
static size_t encode_tiles(VP9_COMP *cpi, uint8_t *data_ptr, size_t data_size) {
1107
54.1k
  VP9_COMMON *const cm = &cpi->common;
1108
54.1k
  MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
1109
54.1k
  vpx_writer residual_bc;
1110
54.1k
  int tile_row, tile_col;
1111
54.1k
  size_t total_size = 0;
1112
54.1k
  const int tile_cols = 1 << cm->log2_tile_cols;
1113
54.1k
  const int tile_rows = 1 << cm->log2_tile_rows;
1114
1115
54.1k
  memset(cm->above_seg_context, 0,
1116
54.1k
         sizeof(*cm->above_seg_context) * mi_cols_aligned_to_sb(cm->mi_cols));
1117
1118
  // Encoding tiles in parallel is done only for realtime mode now. In other
1119
  // modes the speed up is insignificant and requires further testing to ensure
1120
  // that it does not make the overall process worse in any case.
1121
54.1k
  if (cpi->oxcf.mode == REALTIME && cpi->num_workers > 1 && tile_rows == 1 &&
1122
0
      tile_cols > 1) {
1123
0
    return encode_tiles_mt(cpi, data_ptr, data_size);
1124
0
  }
1125
1126
108k
  for (tile_row = 0; tile_row < tile_rows; tile_row++) {
1127
113k
    for (tile_col = 0; tile_col < tile_cols; tile_col++) {
1128
58.9k
      int tile_idx = tile_row * tile_cols + tile_col;
1129
1130
58.9k
      size_t offset;
1131
58.9k
      if (tile_col < tile_cols - 1 || tile_row < tile_rows - 1)
1132
4.74k
        offset = total_size + 4;
1133
54.1k
      else
1134
54.1k
        offset = total_size;
1135
58.9k
      if (data_size < offset) {
1136
0
        vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1137
0
                           "encode_tiles: output buffer full");
1138
0
      }
1139
58.9k
      vpx_start_encode(&residual_bc, data_ptr + offset, data_size - offset);
1140
1141
58.9k
      write_modes(cpi, xd, &cpi->tile_data[tile_idx].tile_info, &residual_bc,
1142
58.9k
                  tile_row, tile_col, &cpi->max_mv_magnitude,
1143
58.9k
                  cpi->interp_filter_selected);
1144
1145
58.9k
      if (vpx_stop_encode(&residual_bc)) {
1146
85
        vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1147
85
                           "encode_tiles: output buffer full");
1148
85
      }
1149
58.9k
      if (tile_col < tile_cols - 1 || tile_row < tile_rows - 1) {
1150
        // size of this tile
1151
4.74k
        mem_put_be32(data_ptr + total_size, residual_bc.pos);
1152
4.74k
        total_size += 4;
1153
4.74k
      }
1154
1155
58.9k
      total_size += residual_bc.pos;
1156
58.9k
    }
1157
54.1k
  }
1158
54.1k
  return total_size;
1159
54.1k
}
1160
1161
static void write_render_size(const VP9_COMMON *cm,
1162
54.1k
                              struct vpx_write_bit_buffer *wb) {
1163
54.1k
  const int scaling_active =
1164
54.1k
      cm->width != cm->render_width || cm->height != cm->render_height;
1165
54.1k
  vpx_wb_write_bit(wb, scaling_active);
1166
54.1k
  if (scaling_active) {
1167
0
    vpx_wb_write_literal(wb, cm->render_width - 1, 16);
1168
0
    vpx_wb_write_literal(wb, cm->render_height - 1, 16);
1169
0
  }
1170
54.1k
}
1171
1172
static void write_frame_size(const VP9_COMMON *cm,
1173
12.8k
                             struct vpx_write_bit_buffer *wb) {
1174
12.8k
  vpx_wb_write_literal(wb, cm->width - 1, 16);
1175
12.8k
  vpx_wb_write_literal(wb, cm->height - 1, 16);
1176
1177
12.8k
  write_render_size(cm, wb);
1178
12.8k
}
1179
1180
static void write_frame_size_with_refs(VP9_COMP *cpi,
1181
41.3k
                                       struct vpx_write_bit_buffer *wb) {
1182
41.3k
  VP9_COMMON *const cm = &cpi->common;
1183
41.3k
  int found = 0;
1184
1185
41.3k
  MV_REFERENCE_FRAME ref_frame;
1186
41.3k
  for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
1187
41.3k
    YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi, ref_frame);
1188
1189
    // Set "found" to 0 for temporal svc and for spatial svc key frame
1190
41.3k
    if (cpi->use_svc &&
1191
0
        ((cpi->svc.number_temporal_layers > 1 &&
1192
0
          cpi->oxcf.rc_mode == VPX_CBR) ||
1193
0
         (cpi->svc.number_spatial_layers > 1 &&
1194
0
          cpi->svc.layer_context[cpi->svc.spatial_layer_id].is_key_frame))) {
1195
0
      found = 0;
1196
41.3k
    } else if (cfg != NULL) {
1197
41.3k
      found =
1198
41.3k
          cm->width == cfg->y_crop_width && cm->height == cfg->y_crop_height;
1199
41.3k
    }
1200
41.3k
    vpx_wb_write_bit(wb, found);
1201
41.3k
    if (found) {
1202
41.3k
      break;
1203
41.3k
    }
1204
41.3k
  }
1205
1206
41.3k
  if (!found) {
1207
0
    vpx_wb_write_literal(wb, cm->width - 1, 16);
1208
0
    vpx_wb_write_literal(wb, cm->height - 1, 16);
1209
0
  }
1210
1211
41.3k
  write_render_size(cm, wb);
1212
41.3k
}
1213
1214
12.8k
static void write_sync_code(struct vpx_write_bit_buffer *wb) {
1215
12.8k
  vpx_wb_write_literal(wb, VP9_SYNC_CODE_0, 8);
1216
12.8k
  vpx_wb_write_literal(wb, VP9_SYNC_CODE_1, 8);
1217
12.8k
  vpx_wb_write_literal(wb, VP9_SYNC_CODE_2, 8);
1218
12.8k
}
1219
1220
static void write_profile(BITSTREAM_PROFILE profile,
1221
54.1k
                          struct vpx_write_bit_buffer *wb) {
1222
54.1k
  switch (profile) {
1223
54.1k
    case PROFILE_0: vpx_wb_write_literal(wb, 0, 2); break;
1224
0
    case PROFILE_1: vpx_wb_write_literal(wb, 2, 2); break;
1225
0
    case PROFILE_2: vpx_wb_write_literal(wb, 1, 2); break;
1226
0
    default:
1227
0
      assert(profile == PROFILE_3);
1228
0
      vpx_wb_write_literal(wb, 6, 3);
1229
0
      break;
1230
54.1k
  }
1231
54.1k
}
1232
1233
static void write_bitdepth_colorspace_sampling(
1234
12.8k
    VP9_COMMON *const cm, struct vpx_write_bit_buffer *wb) {
1235
12.8k
  if (cm->profile >= PROFILE_2) {
1236
0
    assert(cm->bit_depth > VPX_BITS_8);
1237
0
    vpx_wb_write_bit(wb, cm->bit_depth == VPX_BITS_10 ? 0 : 1);
1238
0
  }
1239
12.8k
  vpx_wb_write_literal(wb, cm->color_space, 3);
1240
12.8k
  if (cm->color_space != VPX_CS_SRGB) {
1241
    // 0: [16, 235] (i.e. xvYCC), 1: [0, 255]
1242
12.8k
    vpx_wb_write_bit(wb, cm->color_range);
1243
12.8k
    if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1244
0
      assert(cm->subsampling_x != 1 || cm->subsampling_y != 1);
1245
0
      vpx_wb_write_bit(wb, cm->subsampling_x);
1246
0
      vpx_wb_write_bit(wb, cm->subsampling_y);
1247
0
      vpx_wb_write_bit(wb, 0);  // unused
1248
12.8k
    } else {
1249
12.8k
      assert(cm->subsampling_x == 1 && cm->subsampling_y == 1);
1250
12.8k
    }
1251
12.8k
  } else {
1252
0
    assert(cm->profile == PROFILE_1 || cm->profile == PROFILE_3);
1253
0
    assert(cm->subsampling_x == 0 && cm->subsampling_y == 0);
1254
0
    vpx_wb_write_bit(wb, 0);  // unused
1255
0
  }
1256
12.8k
}
1257
1258
static void write_uncompressed_header(VP9_COMP *cpi,
1259
54.1k
                                      struct vpx_write_bit_buffer *wb) {
1260
54.1k
  VP9_COMMON *const cm = &cpi->common;
1261
54.1k
  MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
1262
1263
54.1k
  vpx_wb_write_literal(wb, VP9_FRAME_MARKER, 2);
1264
1265
54.1k
  write_profile(cm->profile, wb);
1266
1267
  // If to use show existing frame.
1268
54.1k
  vpx_wb_write_bit(wb, cm->show_existing_frame);
1269
54.1k
  if (cm->show_existing_frame) {
1270
0
    vpx_wb_write_literal(wb, cpi->alt_fb_idx, 3);
1271
0
    return;
1272
0
  }
1273
1274
54.1k
  vpx_wb_write_bit(wb, cm->frame_type);
1275
54.1k
  vpx_wb_write_bit(wb, cm->show_frame);
1276
54.1k
  vpx_wb_write_bit(wb, cm->error_resilient_mode);
1277
1278
54.1k
  if (cm->frame_type == KEY_FRAME) {
1279
12.8k
    write_sync_code(wb);
1280
12.8k
    write_bitdepth_colorspace_sampling(cm, wb);
1281
12.8k
    write_frame_size(cm, wb);
1282
41.3k
  } else {
1283
41.3k
    if (!cm->show_frame) vpx_wb_write_bit(wb, cm->intra_only);
1284
1285
41.3k
    if (!cm->error_resilient_mode)
1286
41.3k
      vpx_wb_write_literal(wb, cm->reset_frame_context, 2);
1287
1288
41.3k
    if (cm->intra_only) {
1289
0
      write_sync_code(wb);
1290
1291
      // Note for profile 0, 420 8bpp is assumed.
1292
0
      if (cm->profile > PROFILE_0) {
1293
0
        write_bitdepth_colorspace_sampling(cm, wb);
1294
0
      }
1295
1296
0
      vpx_wb_write_literal(wb, vp9_get_refresh_mask(cpi), REF_FRAMES);
1297
0
      write_frame_size(cm, wb);
1298
41.3k
    } else {
1299
41.3k
      MV_REFERENCE_FRAME ref_frame;
1300
41.3k
      vpx_wb_write_literal(wb, vp9_get_refresh_mask(cpi), REF_FRAMES);
1301
165k
      for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
1302
124k
        assert(get_ref_frame_map_idx(cpi, ref_frame) != INVALID_IDX);
1303
124k
        vpx_wb_write_literal(wb, get_ref_frame_map_idx(cpi, ref_frame),
1304
124k
                             REF_FRAMES_LOG2);
1305
124k
        vpx_wb_write_bit(wb, cm->ref_frame_sign_bias[ref_frame]);
1306
124k
      }
1307
1308
41.3k
      write_frame_size_with_refs(cpi, wb);
1309
1310
41.3k
      vpx_wb_write_bit(wb, cm->allow_high_precision_mv);
1311
1312
41.3k
      fix_interp_filter(cm, cpi->td.counts);
1313
41.3k
      write_interp_filter(cm->interp_filter, wb);
1314
41.3k
    }
1315
41.3k
  }
1316
1317
54.1k
  if (!cm->error_resilient_mode) {
1318
54.1k
    vpx_wb_write_bit(wb, cm->refresh_frame_context);
1319
54.1k
    vpx_wb_write_bit(wb, cm->frame_parallel_decoding_mode);
1320
54.1k
  }
1321
1322
54.1k
  vpx_wb_write_literal(wb, cm->frame_context_idx, FRAME_CONTEXTS_LOG2);
1323
1324
54.1k
  encode_loopfilter(&cm->lf, wb);
1325
54.1k
  encode_quantization(cm, wb);
1326
54.1k
  encode_segmentation(cm, xd, wb);
1327
1328
54.1k
  write_tile_info(cm, wb);
1329
54.1k
}
1330
1331
static size_t write_compressed_header(VP9_COMP *cpi, uint8_t *data,
1332
54.1k
                                      size_t data_size) {
1333
54.1k
  VP9_COMMON *const cm = &cpi->common;
1334
54.1k
  MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
1335
54.1k
  FRAME_CONTEXT *const fc = cm->fc;
1336
54.1k
  FRAME_COUNTS *counts = cpi->td.counts;
1337
54.1k
  vpx_writer header_bc;
1338
1339
54.1k
  vpx_start_encode(&header_bc, data, data_size);
1340
1341
54.1k
  if (xd->lossless)
1342
7.44k
    cm->tx_mode = ONLY_4X4;
1343
46.7k
  else
1344
46.7k
    encode_txfm_probs(cm, &header_bc, counts);
1345
1346
54.1k
  update_coef_probs(cpi, &header_bc);
1347
54.1k
  update_skip_probs(cm, &header_bc, counts);
1348
1349
54.1k
  if (!frame_is_intra_only(cm)) {
1350
41.3k
    int i;
1351
1352
330k
    for (i = 0; i < INTER_MODE_CONTEXTS; ++i)
1353
289k
      prob_diff_update(vp9_inter_mode_tree, cm->fc->inter_mode_probs[i],
1354
289k
                       counts->inter_mode[i], INTER_MODES, &header_bc);
1355
1356
41.3k
    if (cm->interp_filter == SWITCHABLE)
1357
11.7k
      update_switchable_interp_probs(cm, &header_bc, counts);
1358
1359
206k
    for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
1360
165k
      vp9_cond_prob_diff_update(&header_bc, &fc->intra_inter_prob[i],
1361
165k
                                counts->intra_inter[i]);
1362
1363
41.3k
    if (cpi->allow_comp_inter_inter) {
1364
0
      const int use_compound_pred = cm->reference_mode != SINGLE_REFERENCE;
1365
0
      const int use_hybrid_pred = cm->reference_mode == REFERENCE_MODE_SELECT;
1366
1367
0
      vpx_write_bit(&header_bc, use_compound_pred);
1368
0
      if (use_compound_pred) {
1369
0
        vpx_write_bit(&header_bc, use_hybrid_pred);
1370
0
        if (use_hybrid_pred)
1371
0
          for (i = 0; i < COMP_INTER_CONTEXTS; i++)
1372
0
            vp9_cond_prob_diff_update(&header_bc, &fc->comp_inter_prob[i],
1373
0
                                      counts->comp_inter[i]);
1374
0
      }
1375
0
    }
1376
1377
41.3k
    if (cm->reference_mode != COMPOUND_REFERENCE) {
1378
248k
      for (i = 0; i < REF_CONTEXTS; i++) {
1379
206k
        vp9_cond_prob_diff_update(&header_bc, &fc->single_ref_prob[i][0],
1380
206k
                                  counts->single_ref[i][0]);
1381
206k
        vp9_cond_prob_diff_update(&header_bc, &fc->single_ref_prob[i][1],
1382
206k
                                  counts->single_ref[i][1]);
1383
206k
      }
1384
41.3k
    }
1385
1386
41.3k
    if (cm->reference_mode != SINGLE_REFERENCE)
1387
0
      for (i = 0; i < REF_CONTEXTS; i++)
1388
0
        vp9_cond_prob_diff_update(&header_bc, &fc->comp_ref_prob[i],
1389
0
                                  counts->comp_ref[i]);
1390
1391
206k
    for (i = 0; i < BLOCK_SIZE_GROUPS; ++i)
1392
165k
      prob_diff_update(vp9_intra_mode_tree, cm->fc->y_mode_prob[i],
1393
165k
                       counts->y_mode[i], INTRA_MODES, &header_bc);
1394
1395
703k
    for (i = 0; i < PARTITION_CONTEXTS; ++i)
1396
661k
      prob_diff_update(vp9_partition_tree, fc->partition_prob[i],
1397
661k
                       counts->partition[i], PARTITION_TYPES, &header_bc);
1398
1399
41.3k
    vp9_write_nmv_probs(cm, cm->allow_high_precision_mv, &header_bc,
1400
41.3k
                        &counts->mv);
1401
41.3k
  }
1402
1403
54.1k
  if (vpx_stop_encode(&header_bc)) {
1404
0
    vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1405
0
                       "write_compressed_header: output buffer full");
1406
0
  }
1407
1408
54.1k
  return header_bc.pos;
1409
54.1k
}
1410
1411
void vp9_pack_bitstream(VP9_COMP *cpi, uint8_t *dest, size_t dest_size,
1412
54.1k
                        size_t *size) {
1413
54.1k
  VP9_COMMON *const cm = &cpi->common;
1414
54.1k
  uint8_t *data = dest;
1415
54.1k
  size_t data_size = dest_size;
1416
54.1k
  size_t uncompressed_hdr_size, compressed_hdr_size;
1417
54.1k
  struct vpx_write_bit_buffer wb;
1418
54.1k
  struct vpx_write_bit_buffer saved_wb;
1419
1420
#if CONFIG_BITSTREAM_DEBUG
1421
  bitstream_queue_reset_write();
1422
#endif
1423
1424
54.1k
  vpx_wb_init(&wb, data, data_size);
1425
54.1k
  write_uncompressed_header(cpi, &wb);
1426
54.1k
  if (vpx_wb_has_error(&wb)) {
1427
0
    vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1428
0
                       "vp9_pack_bitstream: output buffer full");
1429
0
  }
1430
1431
  // Skip the rest coding process if use show existing frame.
1432
54.1k
  if (cm->show_existing_frame) {
1433
0
    uncompressed_hdr_size = vpx_wb_bytes_written(&wb);
1434
0
    data += uncompressed_hdr_size;
1435
0
    *size = data - dest;
1436
0
    return;
1437
0
  }
1438
1439
54.1k
  saved_wb = wb;
1440
  // don't know in advance compressed header size
1441
54.1k
  vpx_wb_write_literal(&wb, 0, 16);
1442
54.1k
  if (vpx_wb_has_error(&wb)) {
1443
0
    vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1444
0
                       "vp9_pack_bitstream: output buffer full");
1445
0
  }
1446
1447
54.1k
  uncompressed_hdr_size = vpx_wb_bytes_written(&wb);
1448
54.1k
  data += uncompressed_hdr_size;
1449
54.1k
  data_size -= uncompressed_hdr_size;
1450
1451
54.1k
  vpx_clear_system_state();
1452
1453
54.1k
  compressed_hdr_size = write_compressed_header(cpi, data, data_size);
1454
54.1k
  data += compressed_hdr_size;
1455
54.1k
  data_size -= compressed_hdr_size;
1456
54.1k
  if (compressed_hdr_size > UINT16_MAX) {
1457
0
    vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1458
0
                       "compressed_hdr_size > 16 bits");
1459
0
  }
1460
54.1k
  vpx_wb_write_literal(&saved_wb, (int)compressed_hdr_size, 16);
1461
54.1k
  assert(!vpx_wb_has_error(&saved_wb));
1462
1463
54.1k
  data += encode_tiles(cpi, data, data_size);
1464
1465
54.1k
  *size = data - dest;
1466
54.1k
}