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