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