• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <limits.h>
12 #include <math.h>
13 #include <stdio.h>
14 
15 #include "./vp9_rtcd.h"
16 #include "./vpx_dsp_rtcd.h"
17 #include "./vpx_config.h"
18 
19 #include "vpx_ports/mem.h"
20 #include "vpx_ports/vpx_timer.h"
21 #include "vpx_ports/system_state.h"
22 
23 #include "vp9/common/vp9_common.h"
24 #include "vp9/common/vp9_entropy.h"
25 #include "vp9/common/vp9_entropymode.h"
26 #include "vp9/common/vp9_idct.h"
27 #include "vp9/common/vp9_mvref_common.h"
28 #include "vp9/common/vp9_pred_common.h"
29 #include "vp9/common/vp9_quant_common.h"
30 #include "vp9/common/vp9_reconintra.h"
31 #include "vp9/common/vp9_reconinter.h"
32 #include "vp9/common/vp9_seg_common.h"
33 #include "vp9/common/vp9_tile_common.h"
34 
35 #include "vp9/encoder/vp9_aq_complexity.h"
36 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
37 #include "vp9/encoder/vp9_aq_variance.h"
38 #include "vp9/encoder/vp9_encodeframe.h"
39 #include "vp9/encoder/vp9_encodemb.h"
40 #include "vp9/encoder/vp9_encodemv.h"
41 #include "vp9/encoder/vp9_ethread.h"
42 #include "vp9/encoder/vp9_extend.h"
43 #include "vp9/encoder/vp9_pickmode.h"
44 #include "vp9/encoder/vp9_rd.h"
45 #include "vp9/encoder/vp9_rdopt.h"
46 #include "vp9/encoder/vp9_segmentation.h"
47 #include "vp9/encoder/vp9_tokenize.h"
48 
49 static void encode_superblock(VP9_COMP *cpi, ThreadData * td,
50                               TOKENEXTRA **t, int output_enabled,
51                               int mi_row, int mi_col, BLOCK_SIZE bsize,
52                               PICK_MODE_CONTEXT *ctx);
53 
54 // This is used as a reference when computing the source variance for the
55 //  purposes of activity masking.
56 // Eventually this should be replaced by custom no-reference routines,
57 //  which will be faster.
58 static const uint8_t VP9_VAR_OFFS[64] = {
59     128, 128, 128, 128, 128, 128, 128, 128,
60     128, 128, 128, 128, 128, 128, 128, 128,
61     128, 128, 128, 128, 128, 128, 128, 128,
62     128, 128, 128, 128, 128, 128, 128, 128,
63     128, 128, 128, 128, 128, 128, 128, 128,
64     128, 128, 128, 128, 128, 128, 128, 128,
65     128, 128, 128, 128, 128, 128, 128, 128,
66     128, 128, 128, 128, 128, 128, 128, 128
67 };
68 
69 #if CONFIG_VP9_HIGHBITDEPTH
70 static const uint16_t VP9_HIGH_VAR_OFFS_8[64] = {
71     128, 128, 128, 128, 128, 128, 128, 128,
72     128, 128, 128, 128, 128, 128, 128, 128,
73     128, 128, 128, 128, 128, 128, 128, 128,
74     128, 128, 128, 128, 128, 128, 128, 128,
75     128, 128, 128, 128, 128, 128, 128, 128,
76     128, 128, 128, 128, 128, 128, 128, 128,
77     128, 128, 128, 128, 128, 128, 128, 128,
78     128, 128, 128, 128, 128, 128, 128, 128
79 };
80 
81 static const uint16_t VP9_HIGH_VAR_OFFS_10[64] = {
82     128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4,
83     128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4,
84     128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4,
85     128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4,
86     128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4,
87     128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4,
88     128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4,
89     128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4, 128*4
90 };
91 
92 static const uint16_t VP9_HIGH_VAR_OFFS_12[64] = {
93     128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16,
94     128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16,
95     128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16,
96     128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16,
97     128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16,
98     128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16,
99     128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16,
100     128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16, 128*16
101 };
102 #endif  // CONFIG_VP9_HIGHBITDEPTH
103 
vp9_get_sby_perpixel_variance(VP9_COMP * cpi,const struct buf_2d * ref,BLOCK_SIZE bs)104 unsigned int vp9_get_sby_perpixel_variance(VP9_COMP *cpi,
105                                            const struct buf_2d *ref,
106                                            BLOCK_SIZE bs) {
107   unsigned int sse;
108   const unsigned int var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
109                                               VP9_VAR_OFFS, 0, &sse);
110   return ROUND_POWER_OF_TWO(var, num_pels_log2_lookup[bs]);
111 }
112 
113 #if CONFIG_VP9_HIGHBITDEPTH
vp9_high_get_sby_perpixel_variance(VP9_COMP * cpi,const struct buf_2d * ref,BLOCK_SIZE bs,int bd)114 unsigned int vp9_high_get_sby_perpixel_variance(
115     VP9_COMP *cpi, const struct buf_2d *ref, BLOCK_SIZE bs, int bd) {
116   unsigned int var, sse;
117   switch (bd) {
118     case 10:
119       var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
120                                CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10),
121                                0, &sse);
122       break;
123     case 12:
124       var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
125                                CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12),
126                                0, &sse);
127       break;
128     case 8:
129     default:
130       var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
131                                CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8),
132                                0, &sse);
133       break;
134   }
135   return ROUND_POWER_OF_TWO(var, num_pels_log2_lookup[bs]);
136 }
137 #endif  // CONFIG_VP9_HIGHBITDEPTH
138 
get_sby_perpixel_diff_variance(VP9_COMP * cpi,const struct buf_2d * ref,int mi_row,int mi_col,BLOCK_SIZE bs)139 static unsigned int get_sby_perpixel_diff_variance(VP9_COMP *cpi,
140                                                    const struct buf_2d *ref,
141                                                    int mi_row, int mi_col,
142                                                    BLOCK_SIZE bs) {
143   unsigned int sse, var;
144   uint8_t *last_y;
145   const YV12_BUFFER_CONFIG *last = get_ref_frame_buffer(cpi, LAST_FRAME);
146 
147   assert(last != NULL);
148   last_y =
149       &last->y_buffer[mi_row * MI_SIZE * last->y_stride + mi_col * MI_SIZE];
150   var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride, last_y, last->y_stride, &sse);
151   return ROUND_POWER_OF_TWO(var, num_pels_log2_lookup[bs]);
152 }
153 
get_rd_var_based_fixed_partition(VP9_COMP * cpi,MACROBLOCK * x,int mi_row,int mi_col)154 static BLOCK_SIZE get_rd_var_based_fixed_partition(VP9_COMP *cpi, MACROBLOCK *x,
155                                                    int mi_row,
156                                                    int mi_col) {
157   unsigned int var = get_sby_perpixel_diff_variance(cpi, &x->plane[0].src,
158                                                     mi_row, mi_col,
159                                                     BLOCK_64X64);
160   if (var < 8)
161     return BLOCK_64X64;
162   else if (var < 128)
163     return BLOCK_32X32;
164   else if (var < 2048)
165     return BLOCK_16X16;
166   else
167     return BLOCK_8X8;
168 }
169 
170 // Lighter version of set_offsets that only sets the mode info
171 // pointers.
set_mode_info_offsets(VP9_COMMON * const cm,MACROBLOCK * const x,MACROBLOCKD * const xd,int mi_row,int mi_col)172 static INLINE void set_mode_info_offsets(VP9_COMMON *const cm,
173                                          MACROBLOCK *const x,
174                                          MACROBLOCKD *const xd,
175                                          int mi_row,
176                                          int mi_col) {
177   const int idx_str = xd->mi_stride * mi_row + mi_col;
178   xd->mi = cm->mi_grid_visible + idx_str;
179   xd->mi[0] = cm->mi + idx_str;
180   x->mbmi_ext = x->mbmi_ext_base + (mi_row * cm->mi_cols + mi_col);
181 }
182 
set_offsets(VP9_COMP * cpi,const TileInfo * const tile,MACROBLOCK * const x,int mi_row,int mi_col,BLOCK_SIZE bsize)183 static void set_offsets(VP9_COMP *cpi, const TileInfo *const tile,
184                         MACROBLOCK *const x, int mi_row, int mi_col,
185                         BLOCK_SIZE bsize) {
186   VP9_COMMON *const cm = &cpi->common;
187   MACROBLOCKD *const xd = &x->e_mbd;
188   MB_MODE_INFO *mbmi;
189   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
190   const int mi_height = num_8x8_blocks_high_lookup[bsize];
191   const struct segmentation *const seg = &cm->seg;
192 
193   set_skip_context(xd, mi_row, mi_col);
194 
195   set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
196 
197   mbmi = &xd->mi[0]->mbmi;
198 
199   // Set up destination pointers.
200   vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
201 
202   // Set up limit values for MV components.
203   // Mv beyond the range do not produce new/different prediction block.
204   x->mv_row_min = -(((mi_row + mi_height) * MI_SIZE) + VP9_INTERP_EXTEND);
205   x->mv_col_min = -(((mi_col + mi_width) * MI_SIZE) + VP9_INTERP_EXTEND);
206   x->mv_row_max = (cm->mi_rows - mi_row) * MI_SIZE + VP9_INTERP_EXTEND;
207   x->mv_col_max = (cm->mi_cols - mi_col) * MI_SIZE + VP9_INTERP_EXTEND;
208 
209   // Set up distance of MB to edge of frame in 1/8th pel units.
210   assert(!(mi_col & (mi_width - 1)) && !(mi_row & (mi_height - 1)));
211   set_mi_row_col(xd, tile, mi_row, mi_height, mi_col, mi_width,
212                  cm->mi_rows, cm->mi_cols);
213 
214   // Set up source buffers.
215   vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
216 
217   // R/D setup.
218   x->rddiv = cpi->rd.RDDIV;
219   x->rdmult = cpi->rd.RDMULT;
220 
221   // Setup segment ID.
222   if (seg->enabled) {
223     if (cpi->oxcf.aq_mode != VARIANCE_AQ) {
224       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
225                                                  : cm->last_frame_seg_map;
226       mbmi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
227     }
228     vp9_init_plane_quantizers(cpi, x);
229 
230     x->encode_breakout = cpi->segment_encode_breakout[mbmi->segment_id];
231   } else {
232     mbmi->segment_id = 0;
233     x->encode_breakout = cpi->encode_breakout;
234   }
235 
236   // required by vp9_append_sub8x8_mvs_for_idx() and vp9_find_best_ref_mvs()
237   xd->tile = *tile;
238 }
239 
duplicate_mode_info_in_sb(VP9_COMMON * cm,MACROBLOCKD * xd,int mi_row,int mi_col,BLOCK_SIZE bsize)240 static void duplicate_mode_info_in_sb(VP9_COMMON *cm, MACROBLOCKD *xd,
241                                       int mi_row, int mi_col,
242                                       BLOCK_SIZE bsize) {
243   const int block_width = num_8x8_blocks_wide_lookup[bsize];
244   const int block_height = num_8x8_blocks_high_lookup[bsize];
245   int i, j;
246   for (j = 0; j < block_height; ++j)
247     for (i = 0; i < block_width; ++i) {
248       if (mi_row + j < cm->mi_rows && mi_col + i < cm->mi_cols)
249         xd->mi[j * xd->mi_stride + i] = xd->mi[0];
250     }
251 }
252 
set_block_size(VP9_COMP * const cpi,MACROBLOCK * const x,MACROBLOCKD * const xd,int mi_row,int mi_col,BLOCK_SIZE bsize)253 static void set_block_size(VP9_COMP * const cpi,
254                            MACROBLOCK *const x,
255                            MACROBLOCKD *const xd,
256                            int mi_row, int mi_col,
257                            BLOCK_SIZE bsize) {
258   if (cpi->common.mi_cols > mi_col && cpi->common.mi_rows > mi_row) {
259     set_mode_info_offsets(&cpi->common, x, xd, mi_row, mi_col);
260     xd->mi[0]->mbmi.sb_type = bsize;
261   }
262 }
263 
264 typedef struct {
265   int64_t sum_square_error;
266   int64_t sum_error;
267   int log2_count;
268   int variance;
269 } var;
270 
271 typedef struct {
272   var none;
273   var horz[2];
274   var vert[2];
275 } partition_variance;
276 
277 typedef struct {
278   partition_variance part_variances;
279   var split[4];
280 } v4x4;
281 
282 typedef struct {
283   partition_variance part_variances;
284   v4x4 split[4];
285 } v8x8;
286 
287 typedef struct {
288   partition_variance part_variances;
289   v8x8 split[4];
290 } v16x16;
291 
292 typedef struct {
293   partition_variance part_variances;
294   v16x16 split[4];
295 } v32x32;
296 
297 typedef struct {
298   partition_variance part_variances;
299   v32x32 split[4];
300 } v64x64;
301 
302 typedef struct {
303   partition_variance *part_variances;
304   var *split[4];
305 } variance_node;
306 
307 typedef enum {
308   V16X16,
309   V32X32,
310   V64X64,
311 } TREE_LEVEL;
312 
tree_to_node(void * data,BLOCK_SIZE bsize,variance_node * node)313 static void tree_to_node(void *data, BLOCK_SIZE bsize, variance_node *node) {
314   int i;
315   node->part_variances = NULL;
316   switch (bsize) {
317     case BLOCK_64X64: {
318       v64x64 *vt = (v64x64 *) data;
319       node->part_variances = &vt->part_variances;
320       for (i = 0; i < 4; i++)
321         node->split[i] = &vt->split[i].part_variances.none;
322       break;
323     }
324     case BLOCK_32X32: {
325       v32x32 *vt = (v32x32 *) data;
326       node->part_variances = &vt->part_variances;
327       for (i = 0; i < 4; i++)
328         node->split[i] = &vt->split[i].part_variances.none;
329       break;
330     }
331     case BLOCK_16X16: {
332       v16x16 *vt = (v16x16 *) data;
333       node->part_variances = &vt->part_variances;
334       for (i = 0; i < 4; i++)
335         node->split[i] = &vt->split[i].part_variances.none;
336       break;
337     }
338     case BLOCK_8X8: {
339       v8x8 *vt = (v8x8 *) data;
340       node->part_variances = &vt->part_variances;
341       for (i = 0; i < 4; i++)
342         node->split[i] = &vt->split[i].part_variances.none;
343       break;
344     }
345     case BLOCK_4X4: {
346       v4x4 *vt = (v4x4 *) data;
347       node->part_variances = &vt->part_variances;
348       for (i = 0; i < 4; i++)
349         node->split[i] = &vt->split[i];
350       break;
351     }
352     default: {
353       assert(0);
354       break;
355     }
356   }
357 }
358 
359 // Set variance values given sum square error, sum error, count.
fill_variance(int64_t s2,int64_t s,int c,var * v)360 static void fill_variance(int64_t s2, int64_t s, int c, var *v) {
361   v->sum_square_error = s2;
362   v->sum_error = s;
363   v->log2_count = c;
364 }
365 
get_variance(var * v)366 static void get_variance(var *v) {
367   v->variance = (int)(256 * (v->sum_square_error -
368       ((v->sum_error * v->sum_error) >> v->log2_count)) >> v->log2_count);
369 }
370 
sum_2_variances(const var * a,const var * b,var * r)371 static void sum_2_variances(const var *a, const var *b, var *r) {
372   assert(a->log2_count == b->log2_count);
373   fill_variance(a->sum_square_error + b->sum_square_error,
374                 a->sum_error + b->sum_error, a->log2_count + 1, r);
375 }
376 
fill_variance_tree(void * data,BLOCK_SIZE bsize)377 static void fill_variance_tree(void *data, BLOCK_SIZE bsize) {
378   variance_node node;
379   memset(&node, 0, sizeof(node));
380   tree_to_node(data, bsize, &node);
381   sum_2_variances(node.split[0], node.split[1], &node.part_variances->horz[0]);
382   sum_2_variances(node.split[2], node.split[3], &node.part_variances->horz[1]);
383   sum_2_variances(node.split[0], node.split[2], &node.part_variances->vert[0]);
384   sum_2_variances(node.split[1], node.split[3], &node.part_variances->vert[1]);
385   sum_2_variances(&node.part_variances->vert[0], &node.part_variances->vert[1],
386                   &node.part_variances->none);
387 }
388 
set_vt_partitioning(VP9_COMP * cpi,MACROBLOCK * const x,MACROBLOCKD * const xd,void * data,BLOCK_SIZE bsize,int mi_row,int mi_col,int64_t threshold,BLOCK_SIZE bsize_min,int force_split)389 static int set_vt_partitioning(VP9_COMP *cpi,
390                                MACROBLOCK *const x,
391                                MACROBLOCKD *const xd,
392                                void *data,
393                                BLOCK_SIZE bsize,
394                                int mi_row,
395                                int mi_col,
396                                int64_t threshold,
397                                BLOCK_SIZE bsize_min,
398                                int force_split) {
399   VP9_COMMON * const cm = &cpi->common;
400   variance_node vt;
401   const int block_width = num_8x8_blocks_wide_lookup[bsize];
402   const int block_height = num_8x8_blocks_high_lookup[bsize];
403   const int low_res = (cm->width <= 352 && cm->height <= 288);
404 
405   assert(block_height == block_width);
406   tree_to_node(data, bsize, &vt);
407 
408   if (force_split == 1)
409     return 0;
410 
411   // For bsize=bsize_min (16x16/8x8 for 8x8/4x4 downsampling), select if
412   // variance is below threshold, otherwise split will be selected.
413   // No check for vert/horiz split as too few samples for variance.
414   if (bsize == bsize_min) {
415     // Variance already computed to set the force_split.
416     if (low_res || cm->frame_type == KEY_FRAME)
417       get_variance(&vt.part_variances->none);
418     if (mi_col + block_width / 2 < cm->mi_cols &&
419         mi_row + block_height / 2 < cm->mi_rows &&
420         vt.part_variances->none.variance < threshold) {
421       set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
422       return 1;
423     }
424     return 0;
425   } else if (bsize > bsize_min) {
426     // Variance already computed to set the force_split.
427     if (low_res || cm->frame_type == KEY_FRAME)
428       get_variance(&vt.part_variances->none);
429     // For key frame: take split for bsize above 32X32 or very high variance.
430     if (cm->frame_type == KEY_FRAME &&
431         (bsize > BLOCK_32X32 ||
432         vt.part_variances->none.variance > (threshold << 4))) {
433       return 0;
434     }
435     // If variance is low, take the bsize (no split).
436     if (mi_col + block_width / 2 < cm->mi_cols &&
437         mi_row + block_height / 2 < cm->mi_rows &&
438         vt.part_variances->none.variance < threshold) {
439       set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
440       return 1;
441     }
442 
443     // Check vertical split.
444     if (mi_row + block_height / 2 < cm->mi_rows) {
445       BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_VERT);
446       get_variance(&vt.part_variances->vert[0]);
447       get_variance(&vt.part_variances->vert[1]);
448       if (vt.part_variances->vert[0].variance < threshold &&
449           vt.part_variances->vert[1].variance < threshold &&
450           get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
451         set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
452         set_block_size(cpi, x, xd, mi_row, mi_col + block_width / 2, subsize);
453         return 1;
454       }
455     }
456     // Check horizontal split.
457     if (mi_col + block_width / 2 < cm->mi_cols) {
458       BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_HORZ);
459       get_variance(&vt.part_variances->horz[0]);
460       get_variance(&vt.part_variances->horz[1]);
461       if (vt.part_variances->horz[0].variance < threshold &&
462           vt.part_variances->horz[1].variance < threshold &&
463           get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
464         set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
465         set_block_size(cpi, x, xd, mi_row + block_height / 2, mi_col, subsize);
466         return 1;
467       }
468     }
469 
470     return 0;
471   }
472   return 0;
473 }
474 
475 // Set the variance split thresholds for following the block sizes:
476 // 0 - threshold_64x64, 1 - threshold_32x32, 2 - threshold_16x16,
477 // 3 - vbp_threshold_8x8. vbp_threshold_8x8 (to split to 4x4 partition) is
478 // currently only used on key frame.
set_vbp_thresholds(VP9_COMP * cpi,int64_t thresholds[],int q)479 static void set_vbp_thresholds(VP9_COMP *cpi, int64_t thresholds[], int q) {
480   VP9_COMMON *const cm = &cpi->common;
481   const int is_key_frame = (cm->frame_type == KEY_FRAME);
482   const int threshold_multiplier = is_key_frame ? 20 : 1;
483   const int64_t threshold_base = (int64_t)(threshold_multiplier *
484       cpi->y_dequant[q][1]);
485   if (is_key_frame) {
486     thresholds[0] = threshold_base;
487     thresholds[1] = threshold_base >> 2;
488     thresholds[2] = threshold_base >> 2;
489     thresholds[3] = threshold_base << 2;
490   } else {
491     thresholds[1] = threshold_base;
492     if (cm->width <= 352 && cm->height <= 288) {
493       thresholds[0] = threshold_base >> 2;
494       thresholds[2] = threshold_base << 3;
495     } else {
496       thresholds[0] = threshold_base;
497       thresholds[1] = (5 * threshold_base) >> 2;
498       if (cm->width >= 1920 && cm->height >= 1080)
499         thresholds[1] = (7 * threshold_base) >> 2;
500       thresholds[2] = threshold_base << cpi->oxcf.speed;
501     }
502   }
503 }
504 
vp9_set_variance_partition_thresholds(VP9_COMP * cpi,int q)505 void vp9_set_variance_partition_thresholds(VP9_COMP *cpi, int q) {
506   VP9_COMMON *const cm = &cpi->common;
507   SPEED_FEATURES *const sf = &cpi->sf;
508   const int is_key_frame = (cm->frame_type == KEY_FRAME);
509   if (sf->partition_search_type != VAR_BASED_PARTITION &&
510       sf->partition_search_type != REFERENCE_PARTITION) {
511     return;
512   } else {
513     set_vbp_thresholds(cpi, cpi->vbp_thresholds, q);
514     // The thresholds below are not changed locally.
515     if (is_key_frame) {
516       cpi->vbp_threshold_sad = 0;
517       cpi->vbp_bsize_min = BLOCK_8X8;
518     } else {
519       if (cm->width <= 352 && cm->height <= 288)
520         cpi->vbp_threshold_sad = 100;
521       else
522         cpi->vbp_threshold_sad = (cpi->y_dequant[q][1] << 1) > 1000 ?
523             (cpi->y_dequant[q][1] << 1) : 1000;
524       cpi->vbp_bsize_min = BLOCK_16X16;
525     }
526     cpi->vbp_threshold_minmax = 15 + (q >> 3);
527   }
528 }
529 
530 // Compute the minmax over the 8x8 subblocks.
compute_minmax_8x8(const uint8_t * s,int sp,const uint8_t * d,int dp,int x16_idx,int y16_idx,int highbd_flag,int pixels_wide,int pixels_high)531 static int compute_minmax_8x8(const uint8_t *s, int sp, const uint8_t *d,
532                               int dp, int x16_idx, int y16_idx,
533 #if CONFIG_VP9_HIGHBITDEPTH
534                               int highbd_flag,
535 #endif
536                               int pixels_wide,
537                               int pixels_high) {
538   int k;
539   int minmax_max = 0;
540   int minmax_min = 255;
541   // Loop over the 4 8x8 subblocks.
542   for (k = 0; k < 4; k++) {
543     int x8_idx = x16_idx + ((k & 1) << 3);
544     int y8_idx = y16_idx + ((k >> 1) << 3);
545     int min = 0;
546     int max = 0;
547     if (x8_idx < pixels_wide && y8_idx < pixels_high) {
548 #if CONFIG_VP9_HIGHBITDEPTH
549       if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
550         vp9_highbd_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
551                               d + y8_idx * dp + x8_idx, dp,
552                               &min, &max);
553       } else {
554         vp9_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
555                        d + y8_idx * dp + x8_idx, dp,
556                        &min, &max);
557       }
558 #else
559       vp9_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
560                      d + y8_idx * dp + x8_idx, dp,
561                      &min, &max);
562 #endif
563       if ((max - min) > minmax_max)
564         minmax_max = (max - min);
565       if ((max - min) < minmax_min)
566         minmax_min = (max - min);
567     }
568   }
569   return (minmax_max - minmax_min);
570 }
571 
fill_variance_4x4avg(const uint8_t * s,int sp,const uint8_t * d,int dp,int x8_idx,int y8_idx,v8x8 * vst,int highbd_flag,int pixels_wide,int pixels_high,int is_key_frame)572 static void fill_variance_4x4avg(const uint8_t *s, int sp, const uint8_t *d,
573                                  int dp, int x8_idx, int y8_idx, v8x8 *vst,
574 #if CONFIG_VP9_HIGHBITDEPTH
575                                  int highbd_flag,
576 #endif
577                                  int pixels_wide,
578                                  int pixels_high,
579                                  int is_key_frame) {
580   int k;
581   for (k = 0; k < 4; k++) {
582     int x4_idx = x8_idx + ((k & 1) << 2);
583     int y4_idx = y8_idx + ((k >> 1) << 2);
584     unsigned int sse = 0;
585     int sum = 0;
586     if (x4_idx < pixels_wide && y4_idx < pixels_high) {
587       int s_avg;
588       int d_avg = 128;
589 #if CONFIG_VP9_HIGHBITDEPTH
590       if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
591         s_avg = vp9_highbd_avg_4x4(s + y4_idx * sp + x4_idx, sp);
592         if (!is_key_frame)
593           d_avg = vp9_highbd_avg_4x4(d + y4_idx * dp + x4_idx, dp);
594       } else {
595         s_avg = vp9_avg_4x4(s + y4_idx * sp + x4_idx, sp);
596         if (!is_key_frame)
597           d_avg = vp9_avg_4x4(d + y4_idx * dp + x4_idx, dp);
598       }
599 #else
600       s_avg = vp9_avg_4x4(s + y4_idx * sp + x4_idx, sp);
601       if (!is_key_frame)
602         d_avg = vp9_avg_4x4(d + y4_idx * dp + x4_idx, dp);
603 #endif
604       sum = s_avg - d_avg;
605       sse = sum * sum;
606     }
607     fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
608   }
609 }
610 
fill_variance_8x8avg(const uint8_t * s,int sp,const uint8_t * d,int dp,int x16_idx,int y16_idx,v16x16 * vst,int highbd_flag,int pixels_wide,int pixels_high,int is_key_frame)611 static void fill_variance_8x8avg(const uint8_t *s, int sp, const uint8_t *d,
612                                  int dp, int x16_idx, int y16_idx, v16x16 *vst,
613 #if CONFIG_VP9_HIGHBITDEPTH
614                                  int highbd_flag,
615 #endif
616                                  int pixels_wide,
617                                  int pixels_high,
618                                  int is_key_frame) {
619   int k;
620   for (k = 0; k < 4; k++) {
621     int x8_idx = x16_idx + ((k & 1) << 3);
622     int y8_idx = y16_idx + ((k >> 1) << 3);
623     unsigned int sse = 0;
624     int sum = 0;
625     if (x8_idx < pixels_wide && y8_idx < pixels_high) {
626       int s_avg;
627       int d_avg = 128;
628 #if CONFIG_VP9_HIGHBITDEPTH
629       if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
630         s_avg = vp9_highbd_avg_8x8(s + y8_idx * sp + x8_idx, sp);
631         if (!is_key_frame)
632           d_avg = vp9_highbd_avg_8x8(d + y8_idx * dp + x8_idx, dp);
633       } else {
634         s_avg = vp9_avg_8x8(s + y8_idx * sp + x8_idx, sp);
635         if (!is_key_frame)
636           d_avg = vp9_avg_8x8(d + y8_idx * dp + x8_idx, dp);
637       }
638 #else
639       s_avg = vp9_avg_8x8(s + y8_idx * sp + x8_idx, sp);
640       if (!is_key_frame)
641         d_avg = vp9_avg_8x8(d + y8_idx * dp + x8_idx, dp);
642 #endif
643       sum = s_avg - d_avg;
644       sse = sum * sum;
645     }
646     fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
647   }
648 }
649 
650 // This function chooses partitioning based on the variance between source and
651 // reconstructed last, where variance is computed for down-sampled inputs.
choose_partitioning(VP9_COMP * cpi,const TileInfo * const tile,MACROBLOCK * x,int mi_row,int mi_col)652 static int choose_partitioning(VP9_COMP *cpi,
653                                 const TileInfo *const tile,
654                                 MACROBLOCK *x,
655                                 int mi_row, int mi_col) {
656   VP9_COMMON * const cm = &cpi->common;
657   MACROBLOCKD *xd = &x->e_mbd;
658   int i, j, k, m;
659   v64x64 vt;
660   v16x16 vt2[16];
661   int force_split[21];
662   uint8_t *s;
663   const uint8_t *d;
664   int sp;
665   int dp;
666   int pixels_wide = 64, pixels_high = 64;
667   int64_t thresholds[4] = {cpi->vbp_thresholds[0], cpi->vbp_thresholds[1],
668       cpi->vbp_thresholds[2], cpi->vbp_thresholds[3]};
669 
670   // Always use 4x4 partition for key frame.
671   const int is_key_frame = (cm->frame_type == KEY_FRAME);
672   const int use_4x4_partition = is_key_frame;
673   const int low_res = (cm->width <= 352 && cm->height <= 288);
674   int variance4x4downsample[16];
675 
676   int segment_id = CR_SEGMENT_ID_BASE;
677   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled) {
678     const uint8_t *const map = cm->seg.update_map ? cpi->segmentation_map :
679                                                     cm->last_frame_seg_map;
680     segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
681 
682     if (cyclic_refresh_segment_id_boosted(segment_id)) {
683       int q = vp9_get_qindex(&cm->seg, segment_id, cm->base_qindex);
684       set_vbp_thresholds(cpi, thresholds, q);
685     }
686   }
687 
688   set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
689 
690   if (xd->mb_to_right_edge < 0)
691     pixels_wide += (xd->mb_to_right_edge >> 3);
692   if (xd->mb_to_bottom_edge < 0)
693     pixels_high += (xd->mb_to_bottom_edge >> 3);
694 
695   s = x->plane[0].src.buf;
696   sp = x->plane[0].src.stride;
697 
698   if (!is_key_frame && !(is_one_pass_cbr_svc(cpi) &&
699       cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame)) {
700     // In the case of spatial/temporal scalable coding, the assumption here is
701     // that the temporal reference frame will always be of type LAST_FRAME.
702     // TODO(marpan): If that assumption is broken, we need to revisit this code.
703     MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi;
704     unsigned int uv_sad;
705     const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
706 
707     const YV12_BUFFER_CONFIG *yv12_g = NULL;
708     unsigned int y_sad, y_sad_g;
709     const BLOCK_SIZE bsize = BLOCK_32X32
710         + (mi_col + 4 < cm->mi_cols) * 2 + (mi_row + 4 < cm->mi_rows);
711 
712     assert(yv12 != NULL);
713 
714     if (!(is_one_pass_cbr_svc(cpi) && cpi->svc.spatial_layer_id)) {
715       // For now, GOLDEN will not be used for non-zero spatial layers, since
716       // it may not be a temporal reference.
717       yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
718     }
719 
720     if (yv12_g && yv12_g != yv12 &&
721        (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
722       vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
723                            &cm->frame_refs[GOLDEN_FRAME - 1].sf);
724       y_sad_g = cpi->fn_ptr[bsize].sdf(x->plane[0].src.buf,
725                                        x->plane[0].src.stride,
726                                        xd->plane[0].pre[0].buf,
727                                        xd->plane[0].pre[0].stride);
728     } else {
729       y_sad_g = UINT_MAX;
730     }
731 
732     vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
733                          &cm->frame_refs[LAST_FRAME - 1].sf);
734     mbmi->ref_frame[0] = LAST_FRAME;
735     mbmi->ref_frame[1] = NONE;
736     mbmi->sb_type = BLOCK_64X64;
737     mbmi->mv[0].as_int = 0;
738     mbmi->interp_filter = BILINEAR;
739 
740     y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col);
741     if (y_sad_g < y_sad) {
742       vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
743                            &cm->frame_refs[GOLDEN_FRAME - 1].sf);
744       mbmi->ref_frame[0] = GOLDEN_FRAME;
745       mbmi->mv[0].as_int = 0;
746       y_sad = y_sad_g;
747     } else {
748       x->pred_mv[LAST_FRAME] = mbmi->mv[0].as_mv;
749     }
750 
751     vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
752 
753     for (i = 1; i <= 2; ++i) {
754       struct macroblock_plane  *p = &x->plane[i];
755       struct macroblockd_plane *pd = &xd->plane[i];
756       const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
757 
758       if (bs == BLOCK_INVALID)
759         uv_sad = UINT_MAX;
760       else
761         uv_sad = cpi->fn_ptr[bs].sdf(p->src.buf, p->src.stride,
762                                      pd->dst.buf, pd->dst.stride);
763 
764       x->color_sensitivity[i - 1] = uv_sad > (y_sad >> 2);
765     }
766 
767     d = xd->plane[0].dst.buf;
768     dp = xd->plane[0].dst.stride;
769 
770     // If the y_sad is very small, take 64x64 as partition and exit.
771     // Don't check on boosted segment for now, as 64x64 is suppressed there.
772     if (segment_id == CR_SEGMENT_ID_BASE &&
773         y_sad < cpi->vbp_threshold_sad) {
774       const int block_width = num_8x8_blocks_wide_lookup[BLOCK_64X64];
775       const int block_height = num_8x8_blocks_high_lookup[BLOCK_64X64];
776       if (mi_col + block_width / 2 < cm->mi_cols &&
777           mi_row + block_height / 2 < cm->mi_rows) {
778         set_block_size(cpi, x, xd, mi_row, mi_col, BLOCK_64X64);
779         return 0;
780       }
781     }
782   } else {
783     d = VP9_VAR_OFFS;
784     dp = 0;
785 #if CONFIG_VP9_HIGHBITDEPTH
786     if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
787       switch (xd->bd) {
788         case 10:
789           d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10);
790           break;
791         case 12:
792           d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12);
793           break;
794         case 8:
795         default:
796           d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8);
797           break;
798       }
799     }
800 #endif  // CONFIG_VP9_HIGHBITDEPTH
801   }
802 
803   // Index for force_split: 0 for 64x64, 1-4 for 32x32 blocks,
804   // 5-20 for the 16x16 blocks.
805   force_split[0] = 0;
806   // Fill in the entire tree of 8x8 (or 4x4 under some conditions) variances
807   // for splits.
808   for (i = 0; i < 4; i++) {
809     const int x32_idx = ((i & 1) << 5);
810     const int y32_idx = ((i >> 1) << 5);
811     const int i2 = i << 2;
812     force_split[i + 1] = 0;
813     for (j = 0; j < 4; j++) {
814       const int x16_idx = x32_idx + ((j & 1) << 4);
815       const int y16_idx = y32_idx + ((j >> 1) << 4);
816       const int split_index = 5 + i2 + j;
817       v16x16 *vst = &vt.split[i].split[j];
818       force_split[split_index] = 0;
819       variance4x4downsample[i2 + j] = 0;
820       if (!is_key_frame) {
821         fill_variance_8x8avg(s, sp, d, dp, x16_idx, y16_idx, vst,
822 #if CONFIG_VP9_HIGHBITDEPTH
823                             xd->cur_buf->flags,
824 #endif
825                             pixels_wide,
826                             pixels_high,
827                             is_key_frame);
828         fill_variance_tree(&vt.split[i].split[j], BLOCK_16X16);
829         get_variance(&vt.split[i].split[j].part_variances.none);
830         if (vt.split[i].split[j].part_variances.none.variance >
831             thresholds[2]) {
832           // 16X16 variance is above threshold for split, so force split to 8x8
833           // for this 16x16 block (this also forces splits for upper levels).
834           force_split[split_index] = 1;
835           force_split[i + 1] = 1;
836           force_split[0] = 1;
837         } else if (vt.split[i].split[j].part_variances.none.variance >
838                    thresholds[1] &&
839                    !cyclic_refresh_segment_id_boosted(segment_id)) {
840           // We have some nominal amount of 16x16 variance (based on average),
841           // compute the minmax over the 8x8 sub-blocks, and if above threshold,
842           // force split to 8x8 block for this 16x16 block.
843           int minmax = compute_minmax_8x8(s, sp, d, dp, x16_idx, y16_idx,
844 #if CONFIG_VP9_HIGHBITDEPTH
845                                           xd->cur_buf->flags,
846 #endif
847                                           pixels_wide, pixels_high);
848           if (minmax > cpi->vbp_threshold_minmax) {
849             force_split[split_index] = 1;
850             force_split[i + 1] = 1;
851             force_split[0] = 1;
852           }
853         }
854       }
855       // TODO(marpan): There is an issue with variance based on 4x4 average in
856       // svc mode, don't allow it for now.
857       if (is_key_frame || (low_res && !cpi->use_svc &&
858           vt.split[i].split[j].part_variances.none.variance >
859           (thresholds[1] << 1))) {
860         force_split[split_index] = 0;
861         // Go down to 4x4 down-sampling for variance.
862         variance4x4downsample[i2 + j] = 1;
863         for (k = 0; k < 4; k++) {
864           int x8_idx = x16_idx + ((k & 1) << 3);
865           int y8_idx = y16_idx + ((k >> 1) << 3);
866           v8x8 *vst2 = is_key_frame ? &vst->split[k] :
867               &vt2[i2 + j].split[k];
868           fill_variance_4x4avg(s, sp, d, dp, x8_idx, y8_idx, vst2,
869 #if CONFIG_VP9_HIGHBITDEPTH
870                                xd->cur_buf->flags,
871 #endif
872                                pixels_wide,
873                                pixels_high,
874                                is_key_frame);
875         }
876       }
877     }
878   }
879 
880   // Fill the rest of the variance tree by summing split partition values.
881   for (i = 0; i < 4; i++) {
882     const int i2 = i << 2;
883     for (j = 0; j < 4; j++) {
884       if (variance4x4downsample[i2 + j] == 1) {
885         v16x16 *vtemp = (!is_key_frame) ? &vt2[i2 + j] :
886             &vt.split[i].split[j];
887         for (m = 0; m < 4; m++)
888           fill_variance_tree(&vtemp->split[m], BLOCK_8X8);
889         fill_variance_tree(vtemp, BLOCK_16X16);
890       }
891     }
892     fill_variance_tree(&vt.split[i], BLOCK_32X32);
893     // If variance of this 32x32 block is above the threshold, force the block
894     // to split. This also forces a split on the upper (64x64) level.
895     if (!force_split[i + 1]) {
896       get_variance(&vt.split[i].part_variances.none);
897       if (vt.split[i].part_variances.none.variance > thresholds[1]) {
898         force_split[i + 1] = 1;
899         force_split[0] = 1;
900       }
901     }
902   }
903   if (!force_split[0]) {
904     fill_variance_tree(&vt, BLOCK_64X64);
905     get_variance(&vt.part_variances.none);
906   }
907 
908   // Now go through the entire structure, splitting every block size until
909   // we get to one that's got a variance lower than our threshold.
910   if ( mi_col + 8 > cm->mi_cols || mi_row + 8 > cm->mi_rows ||
911       !set_vt_partitioning(cpi, x, xd, &vt, BLOCK_64X64, mi_row, mi_col,
912                            thresholds[0], BLOCK_16X16, force_split[0])) {
913     for (i = 0; i < 4; ++i) {
914       const int x32_idx = ((i & 1) << 2);
915       const int y32_idx = ((i >> 1) << 2);
916       const int i2 = i << 2;
917       if (!set_vt_partitioning(cpi, x, xd, &vt.split[i], BLOCK_32X32,
918                                (mi_row + y32_idx), (mi_col + x32_idx),
919                                thresholds[1], BLOCK_16X16,
920                                force_split[i + 1])) {
921         for (j = 0; j < 4; ++j) {
922           const int x16_idx = ((j & 1) << 1);
923           const int y16_idx = ((j >> 1) << 1);
924           // For inter frames: if variance4x4downsample[] == 1 for this 16x16
925           // block, then the variance is based on 4x4 down-sampling, so use vt2
926           // in set_vt_partioning(), otherwise use vt.
927           v16x16 *vtemp = (!is_key_frame &&
928                            variance4x4downsample[i2 + j] == 1) ?
929                            &vt2[i2 + j] : &vt.split[i].split[j];
930           if (!set_vt_partitioning(cpi, x, xd, vtemp, BLOCK_16X16,
931                                    mi_row + y32_idx + y16_idx,
932                                    mi_col + x32_idx + x16_idx,
933                                    thresholds[2],
934                                    cpi->vbp_bsize_min,
935                                    force_split[5 + i2  + j])) {
936             for (k = 0; k < 4; ++k) {
937               const int x8_idx = (k & 1);
938               const int y8_idx = (k >> 1);
939               if (use_4x4_partition) {
940                 if (!set_vt_partitioning(cpi, x, xd, &vtemp->split[k],
941                                          BLOCK_8X8,
942                                          mi_row + y32_idx + y16_idx + y8_idx,
943                                          mi_col + x32_idx + x16_idx + x8_idx,
944                                          thresholds[3], BLOCK_8X8, 0)) {
945                   set_block_size(cpi, x, xd,
946                                  (mi_row + y32_idx + y16_idx + y8_idx),
947                                  (mi_col + x32_idx + x16_idx + x8_idx),
948                                  BLOCK_4X4);
949                 }
950               } else {
951                 set_block_size(cpi, x, xd,
952                                (mi_row + y32_idx + y16_idx + y8_idx),
953                                (mi_col + x32_idx + x16_idx + x8_idx),
954                                BLOCK_8X8);
955               }
956             }
957           }
958         }
959       }
960     }
961   }
962   return 0;
963 }
964 
update_state(VP9_COMP * cpi,ThreadData * td,PICK_MODE_CONTEXT * ctx,int mi_row,int mi_col,BLOCK_SIZE bsize,int output_enabled)965 static void update_state(VP9_COMP *cpi, ThreadData *td,
966                          PICK_MODE_CONTEXT *ctx,
967                          int mi_row, int mi_col, BLOCK_SIZE bsize,
968                          int output_enabled) {
969   int i, x_idx, y;
970   VP9_COMMON *const cm = &cpi->common;
971   RD_COUNTS *const rdc = &td->rd_counts;
972   MACROBLOCK *const x = &td->mb;
973   MACROBLOCKD *const xd = &x->e_mbd;
974   struct macroblock_plane *const p = x->plane;
975   struct macroblockd_plane *const pd = xd->plane;
976   MODE_INFO *mi = &ctx->mic;
977   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
978   MODE_INFO *mi_addr = xd->mi[0];
979   const struct segmentation *const seg = &cm->seg;
980   const int bw = num_8x8_blocks_wide_lookup[mi->mbmi.sb_type];
981   const int bh = num_8x8_blocks_high_lookup[mi->mbmi.sb_type];
982   const int x_mis = MIN(bw, cm->mi_cols - mi_col);
983   const int y_mis = MIN(bh, cm->mi_rows - mi_row);
984   MV_REF *const frame_mvs =
985       cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
986   int w, h;
987 
988   const int mis = cm->mi_stride;
989   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
990   const int mi_height = num_8x8_blocks_high_lookup[bsize];
991   int max_plane;
992 
993   assert(mi->mbmi.sb_type == bsize);
994 
995   *mi_addr = *mi;
996   *x->mbmi_ext = ctx->mbmi_ext;
997 
998   // If segmentation in use
999   if (seg->enabled) {
1000     // For in frame complexity AQ copy the segment id from the segment map.
1001     if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1002       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
1003                                                  : cm->last_frame_seg_map;
1004       mi_addr->mbmi.segment_id =
1005         get_segment_id(cm, map, bsize, mi_row, mi_col);
1006     }
1007     // Else for cyclic refresh mode update the segment map, set the segment id
1008     // and then update the quantizer.
1009     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
1010       vp9_cyclic_refresh_update_segment(cpi, &xd->mi[0]->mbmi, mi_row,
1011                                         mi_col, bsize, ctx->rate, ctx->dist,
1012                                         x->skip);
1013     }
1014   }
1015 
1016   max_plane = is_inter_block(mbmi) ? MAX_MB_PLANE : 1;
1017   for (i = 0; i < max_plane; ++i) {
1018     p[i].coeff = ctx->coeff_pbuf[i][1];
1019     p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
1020     pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
1021     p[i].eobs = ctx->eobs_pbuf[i][1];
1022   }
1023 
1024   for (i = max_plane; i < MAX_MB_PLANE; ++i) {
1025     p[i].coeff = ctx->coeff_pbuf[i][2];
1026     p[i].qcoeff = ctx->qcoeff_pbuf[i][2];
1027     pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][2];
1028     p[i].eobs = ctx->eobs_pbuf[i][2];
1029   }
1030 
1031   // Restore the coding context of the MB to that that was in place
1032   // when the mode was picked for it
1033   for (y = 0; y < mi_height; y++)
1034     for (x_idx = 0; x_idx < mi_width; x_idx++)
1035       if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > x_idx
1036         && (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > y) {
1037         xd->mi[x_idx + y * mis] = mi_addr;
1038       }
1039 
1040   if (cpi->oxcf.aq_mode)
1041     vp9_init_plane_quantizers(cpi, x);
1042 
1043   if (is_inter_block(mbmi) && mbmi->sb_type < BLOCK_8X8) {
1044     mbmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1045     mbmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1046   }
1047 
1048   x->skip = ctx->skip;
1049   memcpy(x->zcoeff_blk[mbmi->tx_size], ctx->zcoeff_blk,
1050          sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
1051 
1052   if (!output_enabled)
1053     return;
1054 
1055 #if CONFIG_INTERNAL_STATS
1056   if (frame_is_intra_only(cm)) {
1057     static const int kf_mode_index[] = {
1058       THR_DC        /*DC_PRED*/,
1059       THR_V_PRED    /*V_PRED*/,
1060       THR_H_PRED    /*H_PRED*/,
1061       THR_D45_PRED  /*D45_PRED*/,
1062       THR_D135_PRED /*D135_PRED*/,
1063       THR_D117_PRED /*D117_PRED*/,
1064       THR_D153_PRED /*D153_PRED*/,
1065       THR_D207_PRED /*D207_PRED*/,
1066       THR_D63_PRED  /*D63_PRED*/,
1067       THR_TM        /*TM_PRED*/,
1068     };
1069     ++cpi->mode_chosen_counts[kf_mode_index[mbmi->mode]];
1070   } else {
1071     // Note how often each mode chosen as best
1072     ++cpi->mode_chosen_counts[ctx->best_mode_index];
1073   }
1074 #endif
1075   if (!frame_is_intra_only(cm)) {
1076     if (is_inter_block(mbmi)) {
1077       vp9_update_mv_count(td);
1078 
1079       if (cm->interp_filter == SWITCHABLE) {
1080         const int ctx = vp9_get_pred_context_switchable_interp(xd);
1081         ++td->counts->switchable_interp[ctx][mbmi->interp_filter];
1082       }
1083     }
1084 
1085     rdc->comp_pred_diff[SINGLE_REFERENCE] += ctx->single_pred_diff;
1086     rdc->comp_pred_diff[COMPOUND_REFERENCE] += ctx->comp_pred_diff;
1087     rdc->comp_pred_diff[REFERENCE_MODE_SELECT] += ctx->hybrid_pred_diff;
1088 
1089     for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
1090       rdc->filter_diff[i] += ctx->best_filter_diff[i];
1091   }
1092 
1093   for (h = 0; h < y_mis; ++h) {
1094     MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1095     for (w = 0; w < x_mis; ++w) {
1096       MV_REF *const mv = frame_mv + w;
1097       mv->ref_frame[0] = mi->mbmi.ref_frame[0];
1098       mv->ref_frame[1] = mi->mbmi.ref_frame[1];
1099       mv->mv[0].as_int = mi->mbmi.mv[0].as_int;
1100       mv->mv[1].as_int = mi->mbmi.mv[1].as_int;
1101     }
1102   }
1103 }
1104 
vp9_setup_src_planes(MACROBLOCK * x,const YV12_BUFFER_CONFIG * src,int mi_row,int mi_col)1105 void vp9_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src,
1106                           int mi_row, int mi_col) {
1107   uint8_t *const buffers[3] = {src->y_buffer, src->u_buffer, src->v_buffer };
1108   const int strides[3] = {src->y_stride, src->uv_stride, src->uv_stride };
1109   int i;
1110 
1111   // Set current frame pointer.
1112   x->e_mbd.cur_buf = src;
1113 
1114   for (i = 0; i < MAX_MB_PLANE; i++)
1115     setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mi_row, mi_col,
1116                      NULL, x->e_mbd.plane[i].subsampling_x,
1117                      x->e_mbd.plane[i].subsampling_y);
1118 }
1119 
set_mode_info_seg_skip(MACROBLOCK * x,TX_MODE tx_mode,RD_COST * rd_cost,BLOCK_SIZE bsize)1120 static void set_mode_info_seg_skip(MACROBLOCK *x, TX_MODE tx_mode,
1121                                    RD_COST *rd_cost, BLOCK_SIZE bsize) {
1122   MACROBLOCKD *const xd = &x->e_mbd;
1123   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
1124   INTERP_FILTER filter_ref;
1125 
1126   if (xd->up_available)
1127     filter_ref = xd->mi[-xd->mi_stride]->mbmi.interp_filter;
1128   else if (xd->left_available)
1129     filter_ref = xd->mi[-1]->mbmi.interp_filter;
1130   else
1131     filter_ref = EIGHTTAP;
1132 
1133   mbmi->sb_type = bsize;
1134   mbmi->mode = ZEROMV;
1135   mbmi->tx_size = MIN(max_txsize_lookup[bsize],
1136                       tx_mode_to_biggest_tx_size[tx_mode]);
1137   mbmi->skip = 1;
1138   mbmi->uv_mode = DC_PRED;
1139   mbmi->ref_frame[0] = LAST_FRAME;
1140   mbmi->ref_frame[1] = NONE;
1141   mbmi->mv[0].as_int = 0;
1142   mbmi->interp_filter = filter_ref;
1143 
1144   xd->mi[0]->bmi[0].as_mv[0].as_int = 0;
1145   x->skip = 1;
1146 
1147   vp9_rd_cost_init(rd_cost);
1148 }
1149 
set_segment_rdmult(VP9_COMP * const cpi,MACROBLOCK * const x,int8_t segment_id)1150 static int set_segment_rdmult(VP9_COMP *const cpi,
1151                                MACROBLOCK *const x,
1152                                int8_t segment_id) {
1153   int segment_qindex;
1154   VP9_COMMON *const cm = &cpi->common;
1155   vp9_init_plane_quantizers(cpi, x);
1156   vpx_clear_system_state();
1157   segment_qindex = vp9_get_qindex(&cm->seg, segment_id,
1158                                   cm->base_qindex);
1159   return vp9_compute_rd_mult(cpi, segment_qindex + cm->y_dc_delta_q);
1160 }
1161 
rd_pick_sb_modes(VP9_COMP * cpi,TileDataEnc * tile_data,MACROBLOCK * const x,int mi_row,int mi_col,RD_COST * rd_cost,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx,int64_t best_rd)1162 static void rd_pick_sb_modes(VP9_COMP *cpi,
1163                              TileDataEnc *tile_data,
1164                              MACROBLOCK *const x,
1165                              int mi_row, int mi_col, RD_COST *rd_cost,
1166                              BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx,
1167                              int64_t best_rd) {
1168   VP9_COMMON *const cm = &cpi->common;
1169   TileInfo *const tile_info = &tile_data->tile_info;
1170   MACROBLOCKD *const xd = &x->e_mbd;
1171   MB_MODE_INFO *mbmi;
1172   struct macroblock_plane *const p = x->plane;
1173   struct macroblockd_plane *const pd = xd->plane;
1174   const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
1175   int i, orig_rdmult;
1176 
1177   vpx_clear_system_state();
1178 
1179   // Use the lower precision, but faster, 32x32 fdct for mode selection.
1180   x->use_lp32x32fdct = 1;
1181 
1182   set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1183   mbmi = &xd->mi[0]->mbmi;
1184   mbmi->sb_type = bsize;
1185 
1186   for (i = 0; i < MAX_MB_PLANE; ++i) {
1187     p[i].coeff = ctx->coeff_pbuf[i][0];
1188     p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
1189     pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
1190     p[i].eobs = ctx->eobs_pbuf[i][0];
1191   }
1192   ctx->is_coded = 0;
1193   ctx->skippable = 0;
1194   ctx->pred_pixel_ready = 0;
1195   x->skip_recode = 0;
1196 
1197   // Set to zero to make sure we do not use the previous encoded frame stats
1198   mbmi->skip = 0;
1199 
1200 #if CONFIG_VP9_HIGHBITDEPTH
1201   if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1202     x->source_variance =
1203         vp9_high_get_sby_perpixel_variance(cpi, &x->plane[0].src,
1204                                            bsize, xd->bd);
1205   } else {
1206     x->source_variance =
1207       vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
1208   }
1209 #else
1210   x->source_variance =
1211     vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
1212 #endif  // CONFIG_VP9_HIGHBITDEPTH
1213 
1214   // Save rdmult before it might be changed, so it can be restored later.
1215   orig_rdmult = x->rdmult;
1216 
1217   if (aq_mode == VARIANCE_AQ) {
1218     const int energy = bsize <= BLOCK_16X16 ? x->mb_energy
1219                                             : vp9_block_energy(cpi, x, bsize);
1220     if (cm->frame_type == KEY_FRAME ||
1221         cpi->refresh_alt_ref_frame ||
1222         (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref)) {
1223       mbmi->segment_id = vp9_vaq_segment_id(energy);
1224     } else {
1225       const uint8_t *const map = cm->seg.update_map ? cpi->segmentation_map
1226                                                     : cm->last_frame_seg_map;
1227       mbmi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
1228     }
1229     x->rdmult = set_segment_rdmult(cpi, x, mbmi->segment_id);
1230   } else if (aq_mode == COMPLEXITY_AQ) {
1231     x->rdmult = set_segment_rdmult(cpi, x, mbmi->segment_id);
1232   } else if (aq_mode == CYCLIC_REFRESH_AQ) {
1233     const uint8_t *const map = cm->seg.update_map ? cpi->segmentation_map
1234                                                   : cm->last_frame_seg_map;
1235     // If segment is boosted, use rdmult for that segment.
1236     if (cyclic_refresh_segment_id_boosted(
1237             get_segment_id(cm, map, bsize, mi_row, mi_col)))
1238       x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
1239   }
1240 
1241   // Find best coding mode & reconstruct the MB so it is available
1242   // as a predictor for MBs that follow in the SB
1243   if (frame_is_intra_only(cm)) {
1244     vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, best_rd);
1245   } else {
1246     if (bsize >= BLOCK_8X8) {
1247       if (segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP))
1248         vp9_rd_pick_inter_mode_sb_seg_skip(cpi, tile_data, x, rd_cost, bsize,
1249                                            ctx, best_rd);
1250       else
1251         vp9_rd_pick_inter_mode_sb(cpi, tile_data, x, mi_row, mi_col,
1252                                   rd_cost, bsize, ctx, best_rd);
1253     } else {
1254       vp9_rd_pick_inter_mode_sub8x8(cpi, tile_data, x, mi_row, mi_col,
1255                                     rd_cost, bsize, ctx, best_rd);
1256     }
1257   }
1258 
1259 
1260   // Examine the resulting rate and for AQ mode 2 make a segment choice.
1261   if ((rd_cost->rate != INT_MAX) &&
1262       (aq_mode == COMPLEXITY_AQ) && (bsize >= BLOCK_16X16) &&
1263       (cm->frame_type == KEY_FRAME ||
1264        cpi->refresh_alt_ref_frame ||
1265        (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref))) {
1266     vp9_caq_select_segment(cpi, x, bsize, mi_row, mi_col, rd_cost->rate);
1267   }
1268 
1269   x->rdmult = orig_rdmult;
1270 
1271   // TODO(jingning) The rate-distortion optimization flow needs to be
1272   // refactored to provide proper exit/return handle.
1273   if (rd_cost->rate == INT_MAX)
1274     rd_cost->rdcost = INT64_MAX;
1275 
1276   ctx->rate = rd_cost->rate;
1277   ctx->dist = rd_cost->dist;
1278 }
1279 
update_stats(VP9_COMMON * cm,ThreadData * td)1280 static void update_stats(VP9_COMMON *cm, ThreadData *td) {
1281   const MACROBLOCK *x = &td->mb;
1282   const MACROBLOCKD *const xd = &x->e_mbd;
1283   const MODE_INFO *const mi = xd->mi[0];
1284   const MB_MODE_INFO *const mbmi = &mi->mbmi;
1285   const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
1286   const BLOCK_SIZE bsize = mbmi->sb_type;
1287 
1288   if (!frame_is_intra_only(cm)) {
1289     FRAME_COUNTS *const counts = td->counts;
1290     const int inter_block = is_inter_block(mbmi);
1291     const int seg_ref_active = segfeature_active(&cm->seg, mbmi->segment_id,
1292                                                  SEG_LVL_REF_FRAME);
1293     if (!seg_ref_active) {
1294       counts->intra_inter[vp9_get_intra_inter_context(xd)][inter_block]++;
1295       // If the segment reference feature is enabled we have only a single
1296       // reference frame allowed for the segment so exclude it from
1297       // the reference frame counts used to work out probabilities.
1298       if (inter_block) {
1299         const MV_REFERENCE_FRAME ref0 = mbmi->ref_frame[0];
1300         if (cm->reference_mode == REFERENCE_MODE_SELECT)
1301           counts->comp_inter[vp9_get_reference_mode_context(cm, xd)]
1302                             [has_second_ref(mbmi)]++;
1303 
1304         if (has_second_ref(mbmi)) {
1305           counts->comp_ref[vp9_get_pred_context_comp_ref_p(cm, xd)]
1306                           [ref0 == GOLDEN_FRAME]++;
1307         } else {
1308           counts->single_ref[vp9_get_pred_context_single_ref_p1(xd)][0]
1309                             [ref0 != LAST_FRAME]++;
1310           if (ref0 != LAST_FRAME)
1311             counts->single_ref[vp9_get_pred_context_single_ref_p2(xd)][1]
1312                               [ref0 != GOLDEN_FRAME]++;
1313         }
1314       }
1315     }
1316     if (inter_block &&
1317         !segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP)) {
1318       const int mode_ctx = mbmi_ext->mode_context[mbmi->ref_frame[0]];
1319       if (bsize >= BLOCK_8X8) {
1320         const PREDICTION_MODE mode = mbmi->mode;
1321         ++counts->inter_mode[mode_ctx][INTER_OFFSET(mode)];
1322       } else {
1323         const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
1324         const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
1325         int idx, idy;
1326         for (idy = 0; idy < 2; idy += num_4x4_h) {
1327           for (idx = 0; idx < 2; idx += num_4x4_w) {
1328             const int j = idy * 2 + idx;
1329             const PREDICTION_MODE b_mode = mi->bmi[j].as_mode;
1330             ++counts->inter_mode[mode_ctx][INTER_OFFSET(b_mode)];
1331           }
1332         }
1333       }
1334     }
1335   }
1336 }
1337 
restore_context(MACROBLOCK * const x,int mi_row,int mi_col,ENTROPY_CONTEXT a[16* MAX_MB_PLANE],ENTROPY_CONTEXT l[16* MAX_MB_PLANE],PARTITION_CONTEXT sa[8],PARTITION_CONTEXT sl[8],BLOCK_SIZE bsize)1338 static void restore_context(MACROBLOCK *const x, int mi_row, int mi_col,
1339                             ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
1340                             ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
1341                             PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
1342                             BLOCK_SIZE bsize) {
1343   MACROBLOCKD *const xd = &x->e_mbd;
1344   int p;
1345   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1346   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1347   int mi_width = num_8x8_blocks_wide_lookup[bsize];
1348   int mi_height = num_8x8_blocks_high_lookup[bsize];
1349   for (p = 0; p < MAX_MB_PLANE; p++) {
1350     memcpy(
1351         xd->above_context[p] + ((mi_col * 2) >> xd->plane[p].subsampling_x),
1352         a + num_4x4_blocks_wide * p,
1353         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
1354         xd->plane[p].subsampling_x);
1355     memcpy(
1356         xd->left_context[p]
1357             + ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
1358         l + num_4x4_blocks_high * p,
1359         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
1360         xd->plane[p].subsampling_y);
1361   }
1362   memcpy(xd->above_seg_context + mi_col, sa,
1363          sizeof(*xd->above_seg_context) * mi_width);
1364   memcpy(xd->left_seg_context + (mi_row & MI_MASK), sl,
1365          sizeof(xd->left_seg_context[0]) * mi_height);
1366 }
1367 
save_context(MACROBLOCK * const x,int mi_row,int mi_col,ENTROPY_CONTEXT a[16* MAX_MB_PLANE],ENTROPY_CONTEXT l[16* MAX_MB_PLANE],PARTITION_CONTEXT sa[8],PARTITION_CONTEXT sl[8],BLOCK_SIZE bsize)1368 static void save_context(MACROBLOCK *const x, int mi_row, int mi_col,
1369                          ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
1370                          ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
1371                          PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
1372                          BLOCK_SIZE bsize) {
1373   const MACROBLOCKD *const xd = &x->e_mbd;
1374   int p;
1375   const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
1376   const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
1377   int mi_width = num_8x8_blocks_wide_lookup[bsize];
1378   int mi_height = num_8x8_blocks_high_lookup[bsize];
1379 
1380   // buffer the above/left context information of the block in search.
1381   for (p = 0; p < MAX_MB_PLANE; ++p) {
1382     memcpy(
1383         a + num_4x4_blocks_wide * p,
1384         xd->above_context[p] + (mi_col * 2 >> xd->plane[p].subsampling_x),
1385         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
1386         xd->plane[p].subsampling_x);
1387     memcpy(
1388         l + num_4x4_blocks_high * p,
1389         xd->left_context[p]
1390             + ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
1391         (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
1392         xd->plane[p].subsampling_y);
1393   }
1394   memcpy(sa, xd->above_seg_context + mi_col,
1395          sizeof(*xd->above_seg_context) * mi_width);
1396   memcpy(sl, xd->left_seg_context + (mi_row & MI_MASK),
1397          sizeof(xd->left_seg_context[0]) * mi_height);
1398 }
1399 
encode_b(VP9_COMP * cpi,const TileInfo * const tile,ThreadData * td,TOKENEXTRA ** tp,int mi_row,int mi_col,int output_enabled,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)1400 static void encode_b(VP9_COMP *cpi, const TileInfo *const tile,
1401                      ThreadData *td,
1402                      TOKENEXTRA **tp, int mi_row, int mi_col,
1403                      int output_enabled, BLOCK_SIZE bsize,
1404                      PICK_MODE_CONTEXT *ctx) {
1405   MACROBLOCK *const x = &td->mb;
1406   set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
1407   update_state(cpi, td, ctx, mi_row, mi_col, bsize, output_enabled);
1408   encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
1409 
1410   if (output_enabled) {
1411     update_stats(&cpi->common, td);
1412 
1413     (*tp)->token = EOSB_TOKEN;
1414     (*tp)++;
1415   }
1416 }
1417 
encode_sb(VP9_COMP * cpi,ThreadData * td,const TileInfo * const tile,TOKENEXTRA ** tp,int mi_row,int mi_col,int output_enabled,BLOCK_SIZE bsize,PC_TREE * pc_tree)1418 static void encode_sb(VP9_COMP *cpi, ThreadData *td,
1419                       const TileInfo *const tile,
1420                       TOKENEXTRA **tp, int mi_row, int mi_col,
1421                       int output_enabled, BLOCK_SIZE bsize,
1422                       PC_TREE *pc_tree) {
1423   VP9_COMMON *const cm = &cpi->common;
1424   MACROBLOCK *const x = &td->mb;
1425   MACROBLOCKD *const xd = &x->e_mbd;
1426 
1427   const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
1428   int ctx;
1429   PARTITION_TYPE partition;
1430   BLOCK_SIZE subsize = bsize;
1431 
1432   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1433     return;
1434 
1435   if (bsize >= BLOCK_8X8) {
1436     ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
1437     subsize = get_subsize(bsize, pc_tree->partitioning);
1438   } else {
1439     ctx = 0;
1440     subsize = BLOCK_4X4;
1441   }
1442 
1443   partition = partition_lookup[bsl][subsize];
1444   if (output_enabled && bsize != BLOCK_4X4)
1445     td->counts->partition[ctx][partition]++;
1446 
1447   switch (partition) {
1448     case PARTITION_NONE:
1449       encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1450                &pc_tree->none);
1451       break;
1452     case PARTITION_VERT:
1453       encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1454                &pc_tree->vertical[0]);
1455       if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
1456         encode_b(cpi, tile, td, tp, mi_row, mi_col + hbs, output_enabled,
1457                  subsize, &pc_tree->vertical[1]);
1458       }
1459       break;
1460     case PARTITION_HORZ:
1461       encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1462                &pc_tree->horizontal[0]);
1463       if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
1464         encode_b(cpi, tile, td, tp, mi_row + hbs, mi_col, output_enabled,
1465                  subsize, &pc_tree->horizontal[1]);
1466       }
1467       break;
1468     case PARTITION_SPLIT:
1469       if (bsize == BLOCK_8X8) {
1470         encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
1471                  pc_tree->leaf_split[0]);
1472       } else {
1473         encode_sb(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1474                   pc_tree->split[0]);
1475         encode_sb(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
1476                   subsize, pc_tree->split[1]);
1477         encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
1478                   subsize, pc_tree->split[2]);
1479         encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs, output_enabled,
1480                   subsize, pc_tree->split[3]);
1481       }
1482       break;
1483     default:
1484       assert(0 && "Invalid partition type.");
1485       break;
1486   }
1487 
1488   if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
1489     update_partition_context(xd, mi_row, mi_col, subsize, bsize);
1490 }
1491 
1492 // Check to see if the given partition size is allowed for a specified number
1493 // of 8x8 block rows and columns remaining in the image.
1494 // If not then return the largest allowed partition size
find_partition_size(BLOCK_SIZE bsize,int rows_left,int cols_left,int * bh,int * bw)1495 static BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize,
1496                                       int rows_left, int cols_left,
1497                                       int *bh, int *bw) {
1498   if (rows_left <= 0 || cols_left <= 0) {
1499     return MIN(bsize, BLOCK_8X8);
1500   } else {
1501     for (; bsize > 0; bsize -= 3) {
1502       *bh = num_8x8_blocks_high_lookup[bsize];
1503       *bw = num_8x8_blocks_wide_lookup[bsize];
1504       if ((*bh <= rows_left) && (*bw <= cols_left)) {
1505         break;
1506       }
1507     }
1508   }
1509   return bsize;
1510 }
1511 
set_partial_b64x64_partition(MODE_INFO * mi,int mis,int bh_in,int bw_in,int row8x8_remaining,int col8x8_remaining,BLOCK_SIZE bsize,MODE_INFO ** mi_8x8)1512 static void set_partial_b64x64_partition(MODE_INFO *mi, int mis,
1513     int bh_in, int bw_in, int row8x8_remaining, int col8x8_remaining,
1514     BLOCK_SIZE bsize, MODE_INFO **mi_8x8) {
1515   int bh = bh_in;
1516   int r, c;
1517   for (r = 0; r < MI_BLOCK_SIZE; r += bh) {
1518     int bw = bw_in;
1519     for (c = 0; c < MI_BLOCK_SIZE; c += bw) {
1520       const int index = r * mis + c;
1521       mi_8x8[index] = mi + index;
1522       mi_8x8[index]->mbmi.sb_type = find_partition_size(bsize,
1523           row8x8_remaining - r, col8x8_remaining - c, &bh, &bw);
1524     }
1525   }
1526 }
1527 
1528 // This function attempts to set all mode info entries in a given SB64
1529 // to the same block partition size.
1530 // However, at the bottom and right borders of the image the requested size
1531 // may not be allowed in which case this code attempts to choose the largest
1532 // allowable partition.
set_fixed_partitioning(VP9_COMP * cpi,const TileInfo * const tile,MODE_INFO ** mi_8x8,int mi_row,int mi_col,BLOCK_SIZE bsize)1533 static void set_fixed_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
1534                                    MODE_INFO **mi_8x8, int mi_row, int mi_col,
1535                                    BLOCK_SIZE bsize) {
1536   VP9_COMMON *const cm = &cpi->common;
1537   const int mis = cm->mi_stride;
1538   const int row8x8_remaining = tile->mi_row_end - mi_row;
1539   const int col8x8_remaining = tile->mi_col_end - mi_col;
1540   int block_row, block_col;
1541   MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
1542   int bh = num_8x8_blocks_high_lookup[bsize];
1543   int bw = num_8x8_blocks_wide_lookup[bsize];
1544 
1545   assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
1546 
1547   // Apply the requested partition size to the SB64 if it is all "in image"
1548   if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
1549       (row8x8_remaining >= MI_BLOCK_SIZE)) {
1550     for (block_row = 0; block_row < MI_BLOCK_SIZE; block_row += bh) {
1551       for (block_col = 0; block_col < MI_BLOCK_SIZE; block_col += bw) {
1552         int index = block_row * mis + block_col;
1553         mi_8x8[index] = mi_upper_left + index;
1554         mi_8x8[index]->mbmi.sb_type = bsize;
1555       }
1556     }
1557   } else {
1558     // Else this is a partial SB64.
1559     set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
1560         col8x8_remaining, bsize, mi_8x8);
1561   }
1562 }
1563 
1564 static const struct {
1565   int row;
1566   int col;
1567 } coord_lookup[16] = {
1568     // 32x32 index = 0
1569     {0, 0}, {0, 2}, {2, 0}, {2, 2},
1570     // 32x32 index = 1
1571     {0, 4}, {0, 6}, {2, 4}, {2, 6},
1572     // 32x32 index = 2
1573     {4, 0}, {4, 2}, {6, 0}, {6, 2},
1574     // 32x32 index = 3
1575     {4, 4}, {4, 6}, {6, 4}, {6, 6},
1576 };
1577 
set_source_var_based_partition(VP9_COMP * cpi,const TileInfo * const tile,MACROBLOCK * const x,MODE_INFO ** mi_8x8,int mi_row,int mi_col)1578 static void set_source_var_based_partition(VP9_COMP *cpi,
1579                                            const TileInfo *const tile,
1580                                            MACROBLOCK *const x,
1581                                            MODE_INFO **mi_8x8,
1582                                            int mi_row, int mi_col) {
1583   VP9_COMMON *const cm = &cpi->common;
1584   const int mis = cm->mi_stride;
1585   const int row8x8_remaining = tile->mi_row_end - mi_row;
1586   const int col8x8_remaining = tile->mi_col_end - mi_col;
1587   MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
1588 
1589   vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
1590 
1591   assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
1592 
1593   // In-image SB64
1594   if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
1595       (row8x8_remaining >= MI_BLOCK_SIZE)) {
1596     int i, j;
1597     int index;
1598     diff d32[4];
1599     const int offset = (mi_row >> 1) * cm->mb_cols + (mi_col >> 1);
1600     int is_larger_better = 0;
1601     int use32x32 = 0;
1602     unsigned int thr = cpi->source_var_thresh;
1603 
1604     memset(d32, 0, 4 * sizeof(diff));
1605 
1606     for (i = 0; i < 4; i++) {
1607       diff *d16[4];
1608 
1609       for (j = 0; j < 4; j++) {
1610         int b_mi_row = coord_lookup[i * 4 + j].row;
1611         int b_mi_col = coord_lookup[i * 4 + j].col;
1612         int boffset = b_mi_row / 2 * cm->mb_cols +
1613                       b_mi_col / 2;
1614 
1615         d16[j] = cpi->source_diff_var + offset + boffset;
1616 
1617         index = b_mi_row * mis + b_mi_col;
1618         mi_8x8[index] = mi_upper_left + index;
1619         mi_8x8[index]->mbmi.sb_type = BLOCK_16X16;
1620 
1621         // TODO(yunqingwang): If d16[j].var is very large, use 8x8 partition
1622         // size to further improve quality.
1623       }
1624 
1625       is_larger_better = (d16[0]->var < thr) && (d16[1]->var < thr) &&
1626           (d16[2]->var < thr) && (d16[3]->var < thr);
1627 
1628       // Use 32x32 partition
1629       if (is_larger_better) {
1630         use32x32 += 1;
1631 
1632         for (j = 0; j < 4; j++) {
1633           d32[i].sse += d16[j]->sse;
1634           d32[i].sum += d16[j]->sum;
1635         }
1636 
1637         d32[i].var = d32[i].sse - (((int64_t)d32[i].sum * d32[i].sum) >> 10);
1638 
1639         index = coord_lookup[i*4].row * mis + coord_lookup[i*4].col;
1640         mi_8x8[index] = mi_upper_left + index;
1641         mi_8x8[index]->mbmi.sb_type = BLOCK_32X32;
1642       }
1643     }
1644 
1645     if (use32x32 == 4) {
1646       thr <<= 1;
1647       is_larger_better = (d32[0].var < thr) && (d32[1].var < thr) &&
1648           (d32[2].var < thr) && (d32[3].var < thr);
1649 
1650       // Use 64x64 partition
1651       if (is_larger_better) {
1652         mi_8x8[0] = mi_upper_left;
1653         mi_8x8[0]->mbmi.sb_type = BLOCK_64X64;
1654       }
1655     }
1656   } else {   // partial in-image SB64
1657     int bh = num_8x8_blocks_high_lookup[BLOCK_16X16];
1658     int bw = num_8x8_blocks_wide_lookup[BLOCK_16X16];
1659     set_partial_b64x64_partition(mi_upper_left, mis, bh, bw,
1660         row8x8_remaining, col8x8_remaining, BLOCK_16X16, mi_8x8);
1661   }
1662 }
1663 
update_state_rt(VP9_COMP * cpi,ThreadData * td,PICK_MODE_CONTEXT * ctx,int mi_row,int mi_col,int bsize)1664 static void update_state_rt(VP9_COMP *cpi, ThreadData *td,
1665                             PICK_MODE_CONTEXT *ctx,
1666                             int mi_row, int mi_col, int bsize) {
1667   VP9_COMMON *const cm = &cpi->common;
1668   MACROBLOCK *const x = &td->mb;
1669   MACROBLOCKD *const xd = &x->e_mbd;
1670   MODE_INFO *const mi = xd->mi[0];
1671   MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
1672   const struct segmentation *const seg = &cm->seg;
1673   const int bw = num_8x8_blocks_wide_lookup[mi->mbmi.sb_type];
1674   const int bh = num_8x8_blocks_high_lookup[mi->mbmi.sb_type];
1675   const int x_mis = MIN(bw, cm->mi_cols - mi_col);
1676   const int y_mis = MIN(bh, cm->mi_rows - mi_row);
1677 
1678   *(xd->mi[0]) = ctx->mic;
1679   *(x->mbmi_ext) = ctx->mbmi_ext;
1680 
1681   if (seg->enabled && cpi->oxcf.aq_mode) {
1682     // For in frame complexity AQ or variance AQ, copy segment_id from
1683     // segmentation_map.
1684     if (cpi->oxcf.aq_mode == COMPLEXITY_AQ ||
1685         cpi->oxcf.aq_mode == VARIANCE_AQ ) {
1686       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
1687                                                  : cm->last_frame_seg_map;
1688       mbmi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
1689     } else {
1690     // Setting segmentation map for cyclic_refresh.
1691       vp9_cyclic_refresh_update_segment(cpi, mbmi, mi_row, mi_col, bsize,
1692                                         ctx->rate, ctx->dist, x->skip);
1693     }
1694     vp9_init_plane_quantizers(cpi, x);
1695   }
1696 
1697   if (is_inter_block(mbmi)) {
1698     vp9_update_mv_count(td);
1699     if (cm->interp_filter == SWITCHABLE) {
1700       const int pred_ctx = vp9_get_pred_context_switchable_interp(xd);
1701       ++td->counts->switchable_interp[pred_ctx][mbmi->interp_filter];
1702     }
1703 
1704     if (mbmi->sb_type < BLOCK_8X8) {
1705       mbmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1706       mbmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1707     }
1708   }
1709 
1710   if (cm->use_prev_frame_mvs) {
1711     MV_REF *const frame_mvs =
1712         cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
1713     int w, h;
1714 
1715     for (h = 0; h < y_mis; ++h) {
1716       MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1717       for (w = 0; w < x_mis; ++w) {
1718         MV_REF *const mv = frame_mv + w;
1719         mv->ref_frame[0] = mi->mbmi.ref_frame[0];
1720         mv->ref_frame[1] = mi->mbmi.ref_frame[1];
1721         mv->mv[0].as_int = mi->mbmi.mv[0].as_int;
1722         mv->mv[1].as_int = mi->mbmi.mv[1].as_int;
1723       }
1724     }
1725   }
1726 
1727   x->skip = ctx->skip;
1728   x->skip_txfm[0] = mbmi->segment_id ? 0 : ctx->skip_txfm[0];
1729 }
1730 
encode_b_rt(VP9_COMP * cpi,ThreadData * td,const TileInfo * const tile,TOKENEXTRA ** tp,int mi_row,int mi_col,int output_enabled,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)1731 static void encode_b_rt(VP9_COMP *cpi, ThreadData *td,
1732                         const TileInfo *const tile,
1733                         TOKENEXTRA **tp, int mi_row, int mi_col,
1734                         int output_enabled, BLOCK_SIZE bsize,
1735                         PICK_MODE_CONTEXT *ctx) {
1736   MACROBLOCK *const x = &td->mb;
1737   set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
1738   update_state_rt(cpi, td, ctx, mi_row, mi_col, bsize);
1739 
1740 #if CONFIG_VP9_TEMPORAL_DENOISING
1741   if (cpi->oxcf.noise_sensitivity > 0 && output_enabled &&
1742       cpi->common.frame_type != KEY_FRAME) {
1743     vp9_denoiser_denoise(&cpi->denoiser, x, mi_row, mi_col,
1744                          MAX(BLOCK_8X8, bsize), ctx);
1745   }
1746 #endif
1747 
1748   encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
1749   update_stats(&cpi->common, td);
1750 
1751   (*tp)->token = EOSB_TOKEN;
1752   (*tp)++;
1753 }
1754 
encode_sb_rt(VP9_COMP * cpi,ThreadData * td,const TileInfo * const tile,TOKENEXTRA ** tp,int mi_row,int mi_col,int output_enabled,BLOCK_SIZE bsize,PC_TREE * pc_tree)1755 static void encode_sb_rt(VP9_COMP *cpi, ThreadData *td,
1756                          const TileInfo *const tile,
1757                          TOKENEXTRA **tp, int mi_row, int mi_col,
1758                          int output_enabled, BLOCK_SIZE bsize,
1759                          PC_TREE *pc_tree) {
1760   VP9_COMMON *const cm = &cpi->common;
1761   MACROBLOCK *const x = &td->mb;
1762   MACROBLOCKD *const xd = &x->e_mbd;
1763 
1764   const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
1765   int ctx;
1766   PARTITION_TYPE partition;
1767   BLOCK_SIZE subsize;
1768 
1769   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1770     return;
1771 
1772   if (bsize >= BLOCK_8X8) {
1773     const int idx_str = xd->mi_stride * mi_row + mi_col;
1774     MODE_INFO ** mi_8x8 = cm->mi_grid_visible + idx_str;
1775     ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
1776     subsize = mi_8x8[0]->mbmi.sb_type;
1777   } else {
1778     ctx = 0;
1779     subsize = BLOCK_4X4;
1780   }
1781 
1782   partition = partition_lookup[bsl][subsize];
1783   if (output_enabled && bsize != BLOCK_4X4)
1784     td->counts->partition[ctx][partition]++;
1785 
1786   switch (partition) {
1787     case PARTITION_NONE:
1788       encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1789                   &pc_tree->none);
1790       break;
1791     case PARTITION_VERT:
1792       encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1793                   &pc_tree->vertical[0]);
1794       if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
1795         encode_b_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
1796                     subsize, &pc_tree->vertical[1]);
1797       }
1798       break;
1799     case PARTITION_HORZ:
1800       encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1801                   &pc_tree->horizontal[0]);
1802       if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
1803         encode_b_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
1804                     subsize, &pc_tree->horizontal[1]);
1805       }
1806       break;
1807     case PARTITION_SPLIT:
1808       subsize = get_subsize(bsize, PARTITION_SPLIT);
1809       encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
1810                    pc_tree->split[0]);
1811       encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
1812                    subsize, pc_tree->split[1]);
1813       encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
1814                    subsize, pc_tree->split[2]);
1815       encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs,
1816                    output_enabled, subsize, pc_tree->split[3]);
1817       break;
1818     default:
1819       assert(0 && "Invalid partition type.");
1820       break;
1821   }
1822 
1823   if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
1824     update_partition_context(xd, mi_row, mi_col, subsize, bsize);
1825 }
1826 
rd_use_partition(VP9_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,MODE_INFO ** mi_8x8,TOKENEXTRA ** tp,int mi_row,int mi_col,BLOCK_SIZE bsize,int * rate,int64_t * dist,int do_recon,PC_TREE * pc_tree)1827 static void rd_use_partition(VP9_COMP *cpi,
1828                              ThreadData *td,
1829                              TileDataEnc *tile_data,
1830                              MODE_INFO **mi_8x8, TOKENEXTRA **tp,
1831                              int mi_row, int mi_col,
1832                              BLOCK_SIZE bsize,
1833                              int *rate, int64_t *dist,
1834                              int do_recon, PC_TREE *pc_tree) {
1835   VP9_COMMON *const cm = &cpi->common;
1836   TileInfo *const tile_info = &tile_data->tile_info;
1837   MACROBLOCK *const x = &td->mb;
1838   MACROBLOCKD *const xd = &x->e_mbd;
1839   const int mis = cm->mi_stride;
1840   const int bsl = b_width_log2_lookup[bsize];
1841   const int mi_step = num_4x4_blocks_wide_lookup[bsize] / 2;
1842   const int bss = (1 << bsl) / 4;
1843   int i, pl;
1844   PARTITION_TYPE partition = PARTITION_NONE;
1845   BLOCK_SIZE subsize;
1846   ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
1847   PARTITION_CONTEXT sl[8], sa[8];
1848   RD_COST last_part_rdc, none_rdc, chosen_rdc;
1849   BLOCK_SIZE sub_subsize = BLOCK_4X4;
1850   int splits_below = 0;
1851   BLOCK_SIZE bs_type = mi_8x8[0]->mbmi.sb_type;
1852   int do_partition_search = 1;
1853   PICK_MODE_CONTEXT *ctx = &pc_tree->none;
1854 
1855   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
1856     return;
1857 
1858   assert(num_4x4_blocks_wide_lookup[bsize] ==
1859          num_4x4_blocks_high_lookup[bsize]);
1860 
1861   vp9_rd_cost_reset(&last_part_rdc);
1862   vp9_rd_cost_reset(&none_rdc);
1863   vp9_rd_cost_reset(&chosen_rdc);
1864 
1865   partition = partition_lookup[bsl][bs_type];
1866   subsize = get_subsize(bsize, partition);
1867 
1868   pc_tree->partitioning = partition;
1869   save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
1870 
1871   if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode) {
1872     set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1873     x->mb_energy = vp9_block_energy(cpi, x, bsize);
1874   }
1875 
1876   if (do_partition_search &&
1877       cpi->sf.partition_search_type == SEARCH_PARTITION &&
1878       cpi->sf.adjust_partitioning_from_last_frame) {
1879     // Check if any of the sub blocks are further split.
1880     if (partition == PARTITION_SPLIT && subsize > BLOCK_8X8) {
1881       sub_subsize = get_subsize(subsize, PARTITION_SPLIT);
1882       splits_below = 1;
1883       for (i = 0; i < 4; i++) {
1884         int jj = i >> 1, ii = i & 0x01;
1885         MODE_INFO *this_mi = mi_8x8[jj * bss * mis + ii * bss];
1886         if (this_mi && this_mi->mbmi.sb_type >= sub_subsize) {
1887           splits_below = 0;
1888         }
1889       }
1890     }
1891 
1892     // If partition is not none try none unless each of the 4 splits are split
1893     // even further..
1894     if (partition != PARTITION_NONE && !splits_below &&
1895         mi_row + (mi_step >> 1) < cm->mi_rows &&
1896         mi_col + (mi_step >> 1) < cm->mi_cols) {
1897       pc_tree->partitioning = PARTITION_NONE;
1898       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &none_rdc, bsize,
1899                        ctx, INT64_MAX);
1900 
1901       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
1902 
1903       if (none_rdc.rate < INT_MAX) {
1904         none_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
1905         none_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, none_rdc.rate,
1906                                  none_rdc.dist);
1907       }
1908 
1909       restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
1910       mi_8x8[0]->mbmi.sb_type = bs_type;
1911       pc_tree->partitioning = partition;
1912     }
1913   }
1914 
1915   switch (partition) {
1916     case PARTITION_NONE:
1917       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1918                        bsize, ctx, INT64_MAX);
1919       break;
1920     case PARTITION_HORZ:
1921       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1922                        subsize, &pc_tree->horizontal[0],
1923                        INT64_MAX);
1924       if (last_part_rdc.rate != INT_MAX &&
1925           bsize >= BLOCK_8X8 && mi_row + (mi_step >> 1) < cm->mi_rows) {
1926         RD_COST tmp_rdc;
1927         PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
1928         vp9_rd_cost_init(&tmp_rdc);
1929         update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
1930         encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
1931         rd_pick_sb_modes(cpi, tile_data, x,
1932                          mi_row + (mi_step >> 1), mi_col, &tmp_rdc,
1933                          subsize, &pc_tree->horizontal[1], INT64_MAX);
1934         if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1935           vp9_rd_cost_reset(&last_part_rdc);
1936           break;
1937         }
1938         last_part_rdc.rate += tmp_rdc.rate;
1939         last_part_rdc.dist += tmp_rdc.dist;
1940         last_part_rdc.rdcost += tmp_rdc.rdcost;
1941       }
1942       break;
1943     case PARTITION_VERT:
1944       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1945                        subsize, &pc_tree->vertical[0], INT64_MAX);
1946       if (last_part_rdc.rate != INT_MAX &&
1947           bsize >= BLOCK_8X8 && mi_col + (mi_step >> 1) < cm->mi_cols) {
1948         RD_COST tmp_rdc;
1949         PICK_MODE_CONTEXT *ctx = &pc_tree->vertical[0];
1950         vp9_rd_cost_init(&tmp_rdc);
1951         update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
1952         encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
1953         rd_pick_sb_modes(cpi, tile_data, x,
1954                          mi_row, mi_col + (mi_step >> 1), &tmp_rdc,
1955                          subsize, &pc_tree->vertical[bsize > BLOCK_8X8],
1956                          INT64_MAX);
1957         if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1958           vp9_rd_cost_reset(&last_part_rdc);
1959           break;
1960         }
1961         last_part_rdc.rate += tmp_rdc.rate;
1962         last_part_rdc.dist += tmp_rdc.dist;
1963         last_part_rdc.rdcost += tmp_rdc.rdcost;
1964       }
1965       break;
1966     case PARTITION_SPLIT:
1967       if (bsize == BLOCK_8X8) {
1968         rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
1969                          subsize, pc_tree->leaf_split[0], INT64_MAX);
1970         break;
1971       }
1972       last_part_rdc.rate = 0;
1973       last_part_rdc.dist = 0;
1974       last_part_rdc.rdcost = 0;
1975       for (i = 0; i < 4; i++) {
1976         int x_idx = (i & 1) * (mi_step >> 1);
1977         int y_idx = (i >> 1) * (mi_step >> 1);
1978         int jj = i >> 1, ii = i & 0x01;
1979         RD_COST tmp_rdc;
1980         if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
1981           continue;
1982 
1983         vp9_rd_cost_init(&tmp_rdc);
1984         rd_use_partition(cpi, td, tile_data,
1985                          mi_8x8 + jj * bss * mis + ii * bss, tp,
1986                          mi_row + y_idx, mi_col + x_idx, subsize,
1987                          &tmp_rdc.rate, &tmp_rdc.dist,
1988                          i != 3, pc_tree->split[i]);
1989         if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
1990           vp9_rd_cost_reset(&last_part_rdc);
1991           break;
1992         }
1993         last_part_rdc.rate += tmp_rdc.rate;
1994         last_part_rdc.dist += tmp_rdc.dist;
1995       }
1996       break;
1997     default:
1998       assert(0);
1999       break;
2000   }
2001 
2002   pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2003   if (last_part_rdc.rate < INT_MAX) {
2004     last_part_rdc.rate += cpi->partition_cost[pl][partition];
2005     last_part_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2006                                   last_part_rdc.rate, last_part_rdc.dist);
2007   }
2008 
2009   if (do_partition_search
2010       && cpi->sf.adjust_partitioning_from_last_frame
2011       && cpi->sf.partition_search_type == SEARCH_PARTITION
2012       && partition != PARTITION_SPLIT && bsize > BLOCK_8X8
2013       && (mi_row + mi_step < cm->mi_rows ||
2014           mi_row + (mi_step >> 1) == cm->mi_rows)
2015       && (mi_col + mi_step < cm->mi_cols ||
2016           mi_col + (mi_step >> 1) == cm->mi_cols)) {
2017     BLOCK_SIZE split_subsize = get_subsize(bsize, PARTITION_SPLIT);
2018     chosen_rdc.rate = 0;
2019     chosen_rdc.dist = 0;
2020     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2021     pc_tree->partitioning = PARTITION_SPLIT;
2022 
2023     // Split partition.
2024     for (i = 0; i < 4; i++) {
2025       int x_idx = (i & 1) * (mi_step >> 1);
2026       int y_idx = (i >> 1) * (mi_step >> 1);
2027       RD_COST tmp_rdc;
2028       ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2029       PARTITION_CONTEXT sl[8], sa[8];
2030 
2031       if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2032         continue;
2033 
2034       save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2035       pc_tree->split[i]->partitioning = PARTITION_NONE;
2036       rd_pick_sb_modes(cpi, tile_data, x,
2037                        mi_row + y_idx, mi_col + x_idx, &tmp_rdc,
2038                        split_subsize, &pc_tree->split[i]->none, INT64_MAX);
2039 
2040       restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2041 
2042       if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2043         vp9_rd_cost_reset(&chosen_rdc);
2044         break;
2045       }
2046 
2047       chosen_rdc.rate += tmp_rdc.rate;
2048       chosen_rdc.dist += tmp_rdc.dist;
2049 
2050       if (i != 3)
2051         encode_sb(cpi, td, tile_info, tp,  mi_row + y_idx, mi_col + x_idx, 0,
2052                   split_subsize, pc_tree->split[i]);
2053 
2054       pl = partition_plane_context(xd, mi_row + y_idx, mi_col + x_idx,
2055                                    split_subsize);
2056       chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2057     }
2058     pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2059     if (chosen_rdc.rate < INT_MAX) {
2060       chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2061       chosen_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2062                                  chosen_rdc.rate, chosen_rdc.dist);
2063     }
2064   }
2065 
2066   // If last_part is better set the partitioning to that.
2067   if (last_part_rdc.rdcost < chosen_rdc.rdcost) {
2068     mi_8x8[0]->mbmi.sb_type = bsize;
2069     if (bsize >= BLOCK_8X8)
2070       pc_tree->partitioning = partition;
2071     chosen_rdc = last_part_rdc;
2072   }
2073   // If none was better set the partitioning to that.
2074   if (none_rdc.rdcost < chosen_rdc.rdcost) {
2075     if (bsize >= BLOCK_8X8)
2076       pc_tree->partitioning = PARTITION_NONE;
2077     chosen_rdc = none_rdc;
2078   }
2079 
2080   restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2081 
2082   // We must have chosen a partitioning and encoding or we'll fail later on.
2083   // No other opportunities for success.
2084   if (bsize == BLOCK_64X64)
2085     assert(chosen_rdc.rate < INT_MAX && chosen_rdc.dist < INT64_MAX);
2086 
2087   if (do_recon) {
2088     int output_enabled = (bsize == BLOCK_64X64);
2089     encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
2090               pc_tree);
2091   }
2092 
2093   *rate = chosen_rdc.rate;
2094   *dist = chosen_rdc.dist;
2095 }
2096 
2097 static const BLOCK_SIZE min_partition_size[BLOCK_SIZES] = {
2098   BLOCK_4X4,   BLOCK_4X4,   BLOCK_4X4,
2099   BLOCK_4X4,   BLOCK_4X4,   BLOCK_4X4,
2100   BLOCK_8X8,   BLOCK_8X8,   BLOCK_8X8,
2101   BLOCK_16X16, BLOCK_16X16, BLOCK_16X16,
2102   BLOCK_16X16
2103 };
2104 
2105 static const BLOCK_SIZE max_partition_size[BLOCK_SIZES] = {
2106   BLOCK_8X8,   BLOCK_16X16, BLOCK_16X16,
2107   BLOCK_16X16, BLOCK_32X32, BLOCK_32X32,
2108   BLOCK_32X32, BLOCK_64X64, BLOCK_64X64,
2109   BLOCK_64X64, BLOCK_64X64, BLOCK_64X64,
2110   BLOCK_64X64
2111 };
2112 
2113 
2114 // Look at all the mode_info entries for blocks that are part of this
2115 // partition and find the min and max values for sb_type.
2116 // At the moment this is designed to work on a 64x64 SB but could be
2117 // adjusted to use a size parameter.
2118 //
2119 // The min and max are assumed to have been initialized prior to calling this
2120 // function so repeat calls can accumulate a min and max of more than one sb64.
get_sb_partition_size_range(MACROBLOCKD * xd,MODE_INFO ** mi_8x8,BLOCK_SIZE * min_block_size,BLOCK_SIZE * max_block_size,int bs_hist[BLOCK_SIZES])2121 static void get_sb_partition_size_range(MACROBLOCKD *xd, MODE_INFO **mi_8x8,
2122                                         BLOCK_SIZE *min_block_size,
2123                                         BLOCK_SIZE *max_block_size,
2124                                         int bs_hist[BLOCK_SIZES]) {
2125   int sb_width_in_blocks = MI_BLOCK_SIZE;
2126   int sb_height_in_blocks  = MI_BLOCK_SIZE;
2127   int i, j;
2128   int index = 0;
2129 
2130   // Check the sb_type for each block that belongs to this region.
2131   for (i = 0; i < sb_height_in_blocks; ++i) {
2132     for (j = 0; j < sb_width_in_blocks; ++j) {
2133       MODE_INFO *mi = mi_8x8[index+j];
2134       BLOCK_SIZE sb_type = mi ? mi->mbmi.sb_type : 0;
2135       bs_hist[sb_type]++;
2136       *min_block_size = MIN(*min_block_size, sb_type);
2137       *max_block_size = MAX(*max_block_size, sb_type);
2138     }
2139     index += xd->mi_stride;
2140   }
2141 }
2142 
2143 // Next square block size less or equal than current block size.
2144 static const BLOCK_SIZE next_square_size[BLOCK_SIZES] = {
2145   BLOCK_4X4, BLOCK_4X4, BLOCK_4X4,
2146   BLOCK_8X8, BLOCK_8X8, BLOCK_8X8,
2147   BLOCK_16X16, BLOCK_16X16, BLOCK_16X16,
2148   BLOCK_32X32, BLOCK_32X32, BLOCK_32X32,
2149   BLOCK_64X64
2150 };
2151 
2152 // Look at neighboring blocks and set a min and max partition size based on
2153 // what they chose.
rd_auto_partition_range(VP9_COMP * cpi,const TileInfo * const tile,MACROBLOCKD * const xd,int mi_row,int mi_col,BLOCK_SIZE * min_block_size,BLOCK_SIZE * max_block_size)2154 static void rd_auto_partition_range(VP9_COMP *cpi, const TileInfo *const tile,
2155                                     MACROBLOCKD *const xd,
2156                                     int mi_row, int mi_col,
2157                                     BLOCK_SIZE *min_block_size,
2158                                     BLOCK_SIZE *max_block_size) {
2159   VP9_COMMON *const cm = &cpi->common;
2160   MODE_INFO **mi = xd->mi;
2161   const int left_in_image = xd->left_available && mi[-1];
2162   const int above_in_image = xd->up_available && mi[-xd->mi_stride];
2163   const int row8x8_remaining = tile->mi_row_end - mi_row;
2164   const int col8x8_remaining = tile->mi_col_end - mi_col;
2165   int bh, bw;
2166   BLOCK_SIZE min_size = BLOCK_4X4;
2167   BLOCK_SIZE max_size = BLOCK_64X64;
2168   int bs_hist[BLOCK_SIZES] = {0};
2169 
2170   // Trap case where we do not have a prediction.
2171   if (left_in_image || above_in_image || cm->frame_type != KEY_FRAME) {
2172     // Default "min to max" and "max to min"
2173     min_size = BLOCK_64X64;
2174     max_size = BLOCK_4X4;
2175 
2176     // NOTE: each call to get_sb_partition_size_range() uses the previous
2177     // passed in values for min and max as a starting point.
2178     // Find the min and max partition used in previous frame at this location
2179     if (cm->frame_type != KEY_FRAME) {
2180       MODE_INFO **prev_mi =
2181           &cm->prev_mi_grid_visible[mi_row * xd->mi_stride + mi_col];
2182       get_sb_partition_size_range(xd, prev_mi, &min_size, &max_size, bs_hist);
2183     }
2184     // Find the min and max partition sizes used in the left SB64
2185     if (left_in_image) {
2186       MODE_INFO **left_sb64_mi = &mi[-MI_BLOCK_SIZE];
2187       get_sb_partition_size_range(xd, left_sb64_mi, &min_size, &max_size,
2188                                   bs_hist);
2189     }
2190     // Find the min and max partition sizes used in the above SB64.
2191     if (above_in_image) {
2192       MODE_INFO **above_sb64_mi = &mi[-xd->mi_stride * MI_BLOCK_SIZE];
2193       get_sb_partition_size_range(xd, above_sb64_mi, &min_size, &max_size,
2194                                   bs_hist);
2195     }
2196 
2197     // Adjust observed min and max for "relaxed" auto partition case.
2198     if (cpi->sf.auto_min_max_partition_size == RELAXED_NEIGHBORING_MIN_MAX) {
2199       min_size = min_partition_size[min_size];
2200       max_size = max_partition_size[max_size];
2201     }
2202   }
2203 
2204   // Check border cases where max and min from neighbors may not be legal.
2205   max_size = find_partition_size(max_size,
2206                                  row8x8_remaining, col8x8_remaining,
2207                                  &bh, &bw);
2208   // Test for blocks at the edge of the active image.
2209   // This may be the actual edge of the image or where there are formatting
2210   // bars.
2211   if (vp9_active_edge_sb(cpi, mi_row, mi_col)) {
2212     min_size = BLOCK_4X4;
2213   } else {
2214     min_size = MIN(cpi->sf.rd_auto_partition_min_limit,
2215                    MIN(min_size, max_size));
2216   }
2217 
2218   // When use_square_partition_only is true, make sure at least one square
2219   // partition is allowed by selecting the next smaller square size as
2220   // *min_block_size.
2221   if (cpi->sf.use_square_partition_only &&
2222       next_square_size[max_size] < min_size) {
2223      min_size = next_square_size[max_size];
2224   }
2225 
2226   *min_block_size = min_size;
2227   *max_block_size = max_size;
2228 }
2229 
2230 // TODO(jingning) refactor functions setting partition search range
set_partition_range(VP9_COMMON * cm,MACROBLOCKD * xd,int mi_row,int mi_col,BLOCK_SIZE bsize,BLOCK_SIZE * min_bs,BLOCK_SIZE * max_bs)2231 static void set_partition_range(VP9_COMMON *cm, MACROBLOCKD *xd,
2232                                 int mi_row, int mi_col, BLOCK_SIZE bsize,
2233                                 BLOCK_SIZE *min_bs, BLOCK_SIZE *max_bs) {
2234   int mi_width  = num_8x8_blocks_wide_lookup[bsize];
2235   int mi_height = num_8x8_blocks_high_lookup[bsize];
2236   int idx, idy;
2237 
2238   MODE_INFO *mi;
2239   const int idx_str = cm->mi_stride * mi_row + mi_col;
2240   MODE_INFO **prev_mi = &cm->prev_mi_grid_visible[idx_str];
2241   BLOCK_SIZE bs, min_size, max_size;
2242 
2243   min_size = BLOCK_64X64;
2244   max_size = BLOCK_4X4;
2245 
2246   if (prev_mi) {
2247     for (idy = 0; idy < mi_height; ++idy) {
2248       for (idx = 0; idx < mi_width; ++idx) {
2249         mi = prev_mi[idy * cm->mi_stride + idx];
2250         bs = mi ? mi->mbmi.sb_type : bsize;
2251         min_size = MIN(min_size, bs);
2252         max_size = MAX(max_size, bs);
2253       }
2254     }
2255   }
2256 
2257   if (xd->left_available) {
2258     for (idy = 0; idy < mi_height; ++idy) {
2259       mi = xd->mi[idy * cm->mi_stride - 1];
2260       bs = mi ? mi->mbmi.sb_type : bsize;
2261       min_size = MIN(min_size, bs);
2262       max_size = MAX(max_size, bs);
2263     }
2264   }
2265 
2266   if (xd->up_available) {
2267     for (idx = 0; idx < mi_width; ++idx) {
2268       mi = xd->mi[idx - cm->mi_stride];
2269       bs = mi ? mi->mbmi.sb_type : bsize;
2270       min_size = MIN(min_size, bs);
2271       max_size = MAX(max_size, bs);
2272     }
2273   }
2274 
2275   if (min_size == max_size) {
2276     min_size = min_partition_size[min_size];
2277     max_size = max_partition_size[max_size];
2278   }
2279 
2280   *min_bs = min_size;
2281   *max_bs = max_size;
2282 }
2283 
store_pred_mv(MACROBLOCK * x,PICK_MODE_CONTEXT * ctx)2284 static INLINE void store_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
2285   memcpy(ctx->pred_mv, x->pred_mv, sizeof(x->pred_mv));
2286 }
2287 
load_pred_mv(MACROBLOCK * x,PICK_MODE_CONTEXT * ctx)2288 static INLINE void load_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
2289   memcpy(x->pred_mv, ctx->pred_mv, sizeof(x->pred_mv));
2290 }
2291 
2292 #if CONFIG_FP_MB_STATS
2293 const int num_16x16_blocks_wide_lookup[BLOCK_SIZES] =
2294   {1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 4, 4};
2295 const int num_16x16_blocks_high_lookup[BLOCK_SIZES] =
2296   {1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 4, 2, 4};
2297 const int qindex_skip_threshold_lookup[BLOCK_SIZES] =
2298   {0, 10, 10, 30, 40, 40, 60, 80, 80, 90, 100, 100, 120};
2299 const int qindex_split_threshold_lookup[BLOCK_SIZES] =
2300   {0, 3, 3, 7, 15, 15, 30, 40, 40, 60, 80, 80, 120};
2301 const int complexity_16x16_blocks_threshold[BLOCK_SIZES] =
2302   {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 6};
2303 
2304 typedef enum {
2305   MV_ZERO = 0,
2306   MV_LEFT = 1,
2307   MV_UP = 2,
2308   MV_RIGHT = 3,
2309   MV_DOWN = 4,
2310   MV_INVALID
2311 } MOTION_DIRECTION;
2312 
get_motion_direction_fp(uint8_t fp_byte)2313 static INLINE MOTION_DIRECTION get_motion_direction_fp(uint8_t fp_byte) {
2314   if (fp_byte & FPMB_MOTION_ZERO_MASK) {
2315     return MV_ZERO;
2316   } else if (fp_byte & FPMB_MOTION_LEFT_MASK) {
2317     return MV_LEFT;
2318   } else if (fp_byte & FPMB_MOTION_RIGHT_MASK) {
2319     return MV_RIGHT;
2320   } else if (fp_byte & FPMB_MOTION_UP_MASK) {
2321     return MV_UP;
2322   } else {
2323     return MV_DOWN;
2324   }
2325 }
2326 
get_motion_inconsistency(MOTION_DIRECTION this_mv,MOTION_DIRECTION that_mv)2327 static INLINE int get_motion_inconsistency(MOTION_DIRECTION this_mv,
2328                                            MOTION_DIRECTION that_mv) {
2329   if (this_mv == that_mv) {
2330     return 0;
2331   } else {
2332     return abs(this_mv - that_mv) == 2 ? 2 : 1;
2333   }
2334 }
2335 #endif
2336 
2337 // TODO(jingning,jimbankoski,rbultje): properly skip partition types that are
2338 // unlikely to be selected depending on previous rate-distortion optimization
2339 // results, for encoding speed-up.
rd_pick_partition(VP9_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,TOKENEXTRA ** tp,int mi_row,int mi_col,BLOCK_SIZE bsize,RD_COST * rd_cost,int64_t best_rd,PC_TREE * pc_tree)2340 static void rd_pick_partition(VP9_COMP *cpi, ThreadData *td,
2341                               TileDataEnc *tile_data,
2342                               TOKENEXTRA **tp, int mi_row, int mi_col,
2343                               BLOCK_SIZE bsize, RD_COST *rd_cost,
2344                               int64_t best_rd, PC_TREE *pc_tree) {
2345   VP9_COMMON *const cm = &cpi->common;
2346   TileInfo *const tile_info = &tile_data->tile_info;
2347   MACROBLOCK *const x = &td->mb;
2348   MACROBLOCKD *const xd = &x->e_mbd;
2349   const int mi_step = num_8x8_blocks_wide_lookup[bsize] / 2;
2350   ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2351   PARTITION_CONTEXT sl[8], sa[8];
2352   TOKENEXTRA *tp_orig = *tp;
2353   PICK_MODE_CONTEXT *ctx = &pc_tree->none;
2354   int i, pl;
2355   BLOCK_SIZE subsize;
2356   RD_COST this_rdc, sum_rdc, best_rdc;
2357   int do_split = bsize >= BLOCK_8X8;
2358   int do_rect = 1;
2359 
2360   // Override skipping rectangular partition operations for edge blocks
2361   const int force_horz_split = (mi_row + mi_step >= cm->mi_rows);
2362   const int force_vert_split = (mi_col + mi_step >= cm->mi_cols);
2363   const int xss = x->e_mbd.plane[1].subsampling_x;
2364   const int yss = x->e_mbd.plane[1].subsampling_y;
2365 
2366   BLOCK_SIZE min_size = x->min_partition_size;
2367   BLOCK_SIZE max_size = x->max_partition_size;
2368 
2369 #if CONFIG_FP_MB_STATS
2370   unsigned int src_diff_var = UINT_MAX;
2371   int none_complexity = 0;
2372 #endif
2373 
2374   int partition_none_allowed = !force_horz_split && !force_vert_split;
2375   int partition_horz_allowed = !force_vert_split && yss <= xss &&
2376                                bsize >= BLOCK_8X8;
2377   int partition_vert_allowed = !force_horz_split && xss <= yss &&
2378                                bsize >= BLOCK_8X8;
2379   (void) *tp_orig;
2380 
2381   assert(num_8x8_blocks_wide_lookup[bsize] ==
2382              num_8x8_blocks_high_lookup[bsize]);
2383 
2384   vp9_rd_cost_init(&this_rdc);
2385   vp9_rd_cost_init(&sum_rdc);
2386   vp9_rd_cost_reset(&best_rdc);
2387   best_rdc.rdcost = best_rd;
2388 
2389   set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2390 
2391   if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode)
2392     x->mb_energy = vp9_block_energy(cpi, x, bsize);
2393 
2394   if (cpi->sf.cb_partition_search && bsize == BLOCK_16X16) {
2395     int cb_partition_search_ctrl = ((pc_tree->index == 0 || pc_tree->index == 3)
2396         + get_chessboard_index(cm->current_video_frame)) & 0x1;
2397 
2398     if (cb_partition_search_ctrl && bsize > min_size && bsize < max_size)
2399       set_partition_range(cm, xd, mi_row, mi_col, bsize, &min_size, &max_size);
2400   }
2401 
2402   // Determine partition types in search according to the speed features.
2403   // The threshold set here has to be of square block size.
2404   if (cpi->sf.auto_min_max_partition_size) {
2405     partition_none_allowed &= (bsize <= max_size && bsize >= min_size);
2406     partition_horz_allowed &= ((bsize <= max_size && bsize > min_size) ||
2407                                 force_horz_split);
2408     partition_vert_allowed &= ((bsize <= max_size && bsize > min_size) ||
2409                                 force_vert_split);
2410     do_split &= bsize > min_size;
2411   }
2412   if (cpi->sf.use_square_partition_only) {
2413     partition_horz_allowed &= force_horz_split;
2414     partition_vert_allowed &= force_vert_split;
2415   }
2416 
2417   save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2418 
2419 #if CONFIG_FP_MB_STATS
2420   if (cpi->use_fp_mb_stats) {
2421     set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2422     src_diff_var = get_sby_perpixel_diff_variance(cpi, &x->plane[0].src,
2423                                                   mi_row, mi_col, bsize);
2424   }
2425 #endif
2426 
2427 #if CONFIG_FP_MB_STATS
2428   // Decide whether we shall split directly and skip searching NONE by using
2429   // the first pass block statistics
2430   if (cpi->use_fp_mb_stats && bsize >= BLOCK_32X32 && do_split &&
2431       partition_none_allowed && src_diff_var > 4 &&
2432       cm->base_qindex < qindex_split_threshold_lookup[bsize]) {
2433     int mb_row = mi_row >> 1;
2434     int mb_col = mi_col >> 1;
2435     int mb_row_end =
2436         MIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
2437     int mb_col_end =
2438         MIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
2439     int r, c;
2440 
2441     // compute a complexity measure, basically measure inconsistency of motion
2442     // vectors obtained from the first pass in the current block
2443     for (r = mb_row; r < mb_row_end ; r++) {
2444       for (c = mb_col; c < mb_col_end; c++) {
2445         const int mb_index = r * cm->mb_cols + c;
2446 
2447         MOTION_DIRECTION this_mv;
2448         MOTION_DIRECTION right_mv;
2449         MOTION_DIRECTION bottom_mv;
2450 
2451         this_mv =
2452             get_motion_direction_fp(cpi->twopass.this_frame_mb_stats[mb_index]);
2453 
2454         // to its right
2455         if (c != mb_col_end - 1) {
2456           right_mv = get_motion_direction_fp(
2457               cpi->twopass.this_frame_mb_stats[mb_index + 1]);
2458           none_complexity += get_motion_inconsistency(this_mv, right_mv);
2459         }
2460 
2461         // to its bottom
2462         if (r != mb_row_end - 1) {
2463           bottom_mv = get_motion_direction_fp(
2464               cpi->twopass.this_frame_mb_stats[mb_index + cm->mb_cols]);
2465           none_complexity += get_motion_inconsistency(this_mv, bottom_mv);
2466         }
2467 
2468         // do not count its left and top neighbors to avoid double counting
2469       }
2470     }
2471 
2472     if (none_complexity > complexity_16x16_blocks_threshold[bsize]) {
2473       partition_none_allowed = 0;
2474     }
2475   }
2476 #endif
2477 
2478   // PARTITION_NONE
2479   if (partition_none_allowed) {
2480     rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col,
2481                      &this_rdc, bsize, ctx, best_rdc.rdcost);
2482     if (this_rdc.rate != INT_MAX) {
2483       if (bsize >= BLOCK_8X8) {
2484         pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2485         this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2486         this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2487                                  this_rdc.rate, this_rdc.dist);
2488       }
2489 
2490       if (this_rdc.rdcost < best_rdc.rdcost) {
2491         int64_t dist_breakout_thr = cpi->sf.partition_search_breakout_dist_thr;
2492         int rate_breakout_thr = cpi->sf.partition_search_breakout_rate_thr;
2493 
2494         best_rdc = this_rdc;
2495         if (bsize >= BLOCK_8X8)
2496           pc_tree->partitioning = PARTITION_NONE;
2497 
2498         // Adjust dist breakout threshold according to the partition size.
2499         dist_breakout_thr >>= 8 - (b_width_log2_lookup[bsize] +
2500             b_height_log2_lookup[bsize]);
2501 
2502         rate_breakout_thr *= num_pels_log2_lookup[bsize];
2503 
2504         // If all y, u, v transform blocks in this partition are skippable, and
2505         // the dist & rate are within the thresholds, the partition search is
2506         // terminated for current branch of the partition search tree.
2507         // The dist & rate thresholds are set to 0 at speed 0 to disable the
2508         // early termination at that speed.
2509         if (!x->e_mbd.lossless &&
2510             (ctx->skippable && best_rdc.dist < dist_breakout_thr &&
2511             best_rdc.rate < rate_breakout_thr)) {
2512           do_split = 0;
2513           do_rect = 0;
2514         }
2515 
2516 #if CONFIG_FP_MB_STATS
2517         // Check if every 16x16 first pass block statistics has zero
2518         // motion and the corresponding first pass residue is small enough.
2519         // If that is the case, check the difference variance between the
2520         // current frame and the last frame. If the variance is small enough,
2521         // stop further splitting in RD optimization
2522         if (cpi->use_fp_mb_stats && do_split != 0 &&
2523             cm->base_qindex > qindex_skip_threshold_lookup[bsize]) {
2524           int mb_row = mi_row >> 1;
2525           int mb_col = mi_col >> 1;
2526           int mb_row_end =
2527               MIN(mb_row + num_16x16_blocks_high_lookup[bsize], cm->mb_rows);
2528           int mb_col_end =
2529               MIN(mb_col + num_16x16_blocks_wide_lookup[bsize], cm->mb_cols);
2530           int r, c;
2531 
2532           int skip = 1;
2533           for (r = mb_row; r < mb_row_end; r++) {
2534             for (c = mb_col; c < mb_col_end; c++) {
2535               const int mb_index = r * cm->mb_cols + c;
2536               if (!(cpi->twopass.this_frame_mb_stats[mb_index] &
2537                     FPMB_MOTION_ZERO_MASK) ||
2538                   !(cpi->twopass.this_frame_mb_stats[mb_index] &
2539                     FPMB_ERROR_SMALL_MASK)) {
2540                 skip = 0;
2541                 break;
2542               }
2543             }
2544             if (skip == 0) {
2545               break;
2546             }
2547           }
2548           if (skip) {
2549             if (src_diff_var == UINT_MAX) {
2550               set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2551               src_diff_var = get_sby_perpixel_diff_variance(
2552                   cpi, &x->plane[0].src, mi_row, mi_col, bsize);
2553             }
2554             if (src_diff_var < 8) {
2555               do_split = 0;
2556               do_rect = 0;
2557             }
2558           }
2559         }
2560 #endif
2561       }
2562     }
2563     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2564   }
2565 
2566   // store estimated motion vector
2567   if (cpi->sf.adaptive_motion_search)
2568     store_pred_mv(x, ctx);
2569 
2570   // PARTITION_SPLIT
2571   // TODO(jingning): use the motion vectors given by the above search as
2572   // the starting point of motion search in the following partition type check.
2573   if (do_split) {
2574     subsize = get_subsize(bsize, PARTITION_SPLIT);
2575     if (bsize == BLOCK_8X8) {
2576       i = 4;
2577       if (cpi->sf.adaptive_pred_interp_filter && partition_none_allowed)
2578         pc_tree->leaf_split[0]->pred_interp_filter =
2579             ctx->mic.mbmi.interp_filter;
2580       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
2581                        pc_tree->leaf_split[0], best_rdc.rdcost);
2582       if (sum_rdc.rate == INT_MAX)
2583         sum_rdc.rdcost = INT64_MAX;
2584     } else {
2585       for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
2586       const int x_idx = (i & 1) * mi_step;
2587       const int y_idx = (i >> 1) * mi_step;
2588 
2589         if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
2590           continue;
2591 
2592         if (cpi->sf.adaptive_motion_search)
2593           load_pred_mv(x, ctx);
2594 
2595         pc_tree->split[i]->index = i;
2596         rd_pick_partition(cpi, td, tile_data, tp,
2597                           mi_row + y_idx, mi_col + x_idx,
2598                           subsize, &this_rdc,
2599                           best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
2600 
2601         if (this_rdc.rate == INT_MAX) {
2602           sum_rdc.rdcost = INT64_MAX;
2603           break;
2604         } else {
2605           sum_rdc.rate += this_rdc.rate;
2606           sum_rdc.dist += this_rdc.dist;
2607           sum_rdc.rdcost += this_rdc.rdcost;
2608         }
2609       }
2610     }
2611 
2612     if (sum_rdc.rdcost < best_rdc.rdcost && i == 4) {
2613       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2614       sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2615       sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2616                               sum_rdc.rate, sum_rdc.dist);
2617 
2618       if (sum_rdc.rdcost < best_rdc.rdcost) {
2619         best_rdc = sum_rdc;
2620         pc_tree->partitioning = PARTITION_SPLIT;
2621       }
2622     } else {
2623       // skip rectangular partition test when larger block size
2624       // gives better rd cost
2625       if (cpi->sf.less_rectangular_check)
2626         do_rect &= !partition_none_allowed;
2627     }
2628     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2629   }
2630 
2631   // PARTITION_HORZ
2632   if (partition_horz_allowed &&
2633       (do_rect || vp9_active_h_edge(cpi, mi_row, mi_step))) {
2634       subsize = get_subsize(bsize, PARTITION_HORZ);
2635     if (cpi->sf.adaptive_motion_search)
2636       load_pred_mv(x, ctx);
2637     if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2638         partition_none_allowed)
2639       pc_tree->horizontal[0].pred_interp_filter =
2640           ctx->mic.mbmi.interp_filter;
2641     rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
2642                      &pc_tree->horizontal[0], best_rdc.rdcost);
2643 
2644     if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + mi_step < cm->mi_rows &&
2645         bsize > BLOCK_8X8) {
2646       PICK_MODE_CONTEXT *ctx = &pc_tree->horizontal[0];
2647       update_state(cpi, td, ctx, mi_row, mi_col, subsize, 0);
2648       encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, ctx);
2649 
2650       if (cpi->sf.adaptive_motion_search)
2651         load_pred_mv(x, ctx);
2652       if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2653           partition_none_allowed)
2654         pc_tree->horizontal[1].pred_interp_filter =
2655             ctx->mic.mbmi.interp_filter;
2656       rd_pick_sb_modes(cpi, tile_data, x, mi_row + mi_step, mi_col,
2657                        &this_rdc, subsize, &pc_tree->horizontal[1],
2658                        best_rdc.rdcost - sum_rdc.rdcost);
2659       if (this_rdc.rate == INT_MAX) {
2660         sum_rdc.rdcost = INT64_MAX;
2661       } else {
2662         sum_rdc.rate += this_rdc.rate;
2663         sum_rdc.dist += this_rdc.dist;
2664         sum_rdc.rdcost += this_rdc.rdcost;
2665       }
2666     }
2667 
2668     if (sum_rdc.rdcost < best_rdc.rdcost) {
2669       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2670       sum_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
2671       sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
2672       if (sum_rdc.rdcost < best_rdc.rdcost) {
2673         best_rdc = sum_rdc;
2674         pc_tree->partitioning = PARTITION_HORZ;
2675       }
2676     }
2677     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2678   }
2679   // PARTITION_VERT
2680   if (partition_vert_allowed &&
2681       (do_rect || vp9_active_v_edge(cpi, mi_col, mi_step))) {
2682       subsize = get_subsize(bsize, PARTITION_VERT);
2683 
2684     if (cpi->sf.adaptive_motion_search)
2685       load_pred_mv(x, ctx);
2686     if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2687         partition_none_allowed)
2688       pc_tree->vertical[0].pred_interp_filter =
2689           ctx->mic.mbmi.interp_filter;
2690     rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
2691                      &pc_tree->vertical[0], best_rdc.rdcost);
2692     if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + mi_step < cm->mi_cols &&
2693         bsize > BLOCK_8X8) {
2694       update_state(cpi, td, &pc_tree->vertical[0], mi_row, mi_col, subsize, 0);
2695       encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize,
2696                         &pc_tree->vertical[0]);
2697 
2698       if (cpi->sf.adaptive_motion_search)
2699         load_pred_mv(x, ctx);
2700       if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
2701           partition_none_allowed)
2702         pc_tree->vertical[1].pred_interp_filter =
2703             ctx->mic.mbmi.interp_filter;
2704       rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + mi_step,
2705                        &this_rdc, subsize,
2706                        &pc_tree->vertical[1], best_rdc.rdcost - sum_rdc.rdcost);
2707       if (this_rdc.rate == INT_MAX) {
2708         sum_rdc.rdcost = INT64_MAX;
2709       } else {
2710         sum_rdc.rate += this_rdc.rate;
2711         sum_rdc.dist += this_rdc.dist;
2712         sum_rdc.rdcost += this_rdc.rdcost;
2713       }
2714     }
2715 
2716     if (sum_rdc.rdcost < best_rdc.rdcost) {
2717       pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2718       sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
2719       sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
2720                               sum_rdc.rate, sum_rdc.dist);
2721       if (sum_rdc.rdcost < best_rdc.rdcost) {
2722         best_rdc = sum_rdc;
2723         pc_tree->partitioning = PARTITION_VERT;
2724       }
2725     }
2726     restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2727   }
2728 
2729   // TODO(jbb): This code added so that we avoid static analysis
2730   // warning related to the fact that best_rd isn't used after this
2731   // point.  This code should be refactored so that the duplicate
2732   // checks occur in some sub function and thus are used...
2733   (void) best_rd;
2734   *rd_cost = best_rdc;
2735 
2736 
2737   if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX &&
2738       pc_tree->index != 3) {
2739     int output_enabled = (bsize == BLOCK_64X64);
2740     encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
2741               bsize, pc_tree);
2742   }
2743 
2744   if (bsize == BLOCK_64X64) {
2745     assert(tp_orig < *tp);
2746     assert(best_rdc.rate < INT_MAX);
2747     assert(best_rdc.dist < INT64_MAX);
2748   } else {
2749     assert(tp_orig == *tp);
2750   }
2751 }
2752 
encode_rd_sb_row(VP9_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,int mi_row,TOKENEXTRA ** tp)2753 static void encode_rd_sb_row(VP9_COMP *cpi,
2754                              ThreadData *td,
2755                              TileDataEnc *tile_data,
2756                              int mi_row,
2757                              TOKENEXTRA **tp) {
2758   VP9_COMMON *const cm = &cpi->common;
2759   TileInfo *const tile_info = &tile_data->tile_info;
2760   MACROBLOCK *const x = &td->mb;
2761   MACROBLOCKD *const xd = &x->e_mbd;
2762   SPEED_FEATURES *const sf = &cpi->sf;
2763   int mi_col;
2764 
2765   // Initialize the left context for the new SB row
2766   memset(&xd->left_context, 0, sizeof(xd->left_context));
2767   memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
2768 
2769   // Code each SB in the row
2770   for (mi_col = tile_info->mi_col_start; mi_col < tile_info->mi_col_end;
2771        mi_col += MI_BLOCK_SIZE) {
2772     const struct segmentation *const seg = &cm->seg;
2773     int dummy_rate;
2774     int64_t dummy_dist;
2775     RD_COST dummy_rdc;
2776     int i;
2777     int seg_skip = 0;
2778 
2779     const int idx_str = cm->mi_stride * mi_row + mi_col;
2780     MODE_INFO **mi = cm->mi_grid_visible + idx_str;
2781 
2782     if (sf->adaptive_pred_interp_filter) {
2783       for (i = 0; i < 64; ++i)
2784         td->leaf_tree[i].pred_interp_filter = SWITCHABLE;
2785 
2786       for (i = 0; i < 64; ++i) {
2787         td->pc_tree[i].vertical[0].pred_interp_filter = SWITCHABLE;
2788         td->pc_tree[i].vertical[1].pred_interp_filter = SWITCHABLE;
2789         td->pc_tree[i].horizontal[0].pred_interp_filter = SWITCHABLE;
2790         td->pc_tree[i].horizontal[1].pred_interp_filter = SWITCHABLE;
2791       }
2792     }
2793 
2794     vp9_zero(x->pred_mv);
2795     td->pc_root->index = 0;
2796 
2797     if (seg->enabled) {
2798       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
2799                                                  : cm->last_frame_seg_map;
2800       int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
2801       seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
2802     }
2803 
2804     x->source_variance = UINT_MAX;
2805     if (sf->partition_search_type == FIXED_PARTITION || seg_skip) {
2806       const BLOCK_SIZE bsize =
2807           seg_skip ? BLOCK_64X64 : sf->always_this_block_size;
2808       set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
2809       set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
2810       rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
2811                        BLOCK_64X64, &dummy_rate, &dummy_dist, 1, td->pc_root);
2812     } else if (cpi->partition_search_skippable_frame) {
2813       BLOCK_SIZE bsize;
2814       set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
2815       bsize = get_rd_var_based_fixed_partition(cpi, x, mi_row, mi_col);
2816       set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
2817       rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
2818                        BLOCK_64X64, &dummy_rate, &dummy_dist, 1, td->pc_root);
2819     } else if (sf->partition_search_type == VAR_BASED_PARTITION &&
2820                cm->frame_type != KEY_FRAME) {
2821       choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
2822       rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
2823                        BLOCK_64X64, &dummy_rate, &dummy_dist, 1, td->pc_root);
2824     } else {
2825       // If required set upper and lower partition size limits
2826       if (sf->auto_min_max_partition_size) {
2827         set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
2828         rd_auto_partition_range(cpi, tile_info, xd, mi_row, mi_col,
2829                                 &x->min_partition_size,
2830                                 &x->max_partition_size);
2831       }
2832       rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, BLOCK_64X64,
2833                         &dummy_rdc, INT64_MAX, td->pc_root);
2834     }
2835   }
2836 }
2837 
init_encode_frame_mb_context(VP9_COMP * cpi)2838 static void init_encode_frame_mb_context(VP9_COMP *cpi) {
2839   MACROBLOCK *const x = &cpi->td.mb;
2840   VP9_COMMON *const cm = &cpi->common;
2841   MACROBLOCKD *const xd = &x->e_mbd;
2842   const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
2843 
2844   // Copy data over into macro block data structures.
2845   vp9_setup_src_planes(x, cpi->Source, 0, 0);
2846 
2847   vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
2848 
2849   // Note: this memset assumes above_context[0], [1] and [2]
2850   // are allocated as part of the same buffer.
2851   memset(xd->above_context[0], 0,
2852          sizeof(*xd->above_context[0]) *
2853          2 * aligned_mi_cols * MAX_MB_PLANE);
2854   memset(xd->above_seg_context, 0,
2855          sizeof(*xd->above_seg_context) * aligned_mi_cols);
2856 }
2857 
check_dual_ref_flags(VP9_COMP * cpi)2858 static int check_dual_ref_flags(VP9_COMP *cpi) {
2859   const int ref_flags = cpi->ref_frame_flags;
2860 
2861   if (segfeature_active(&cpi->common.seg, 1, SEG_LVL_REF_FRAME)) {
2862     return 0;
2863   } else {
2864     return (!!(ref_flags & VP9_GOLD_FLAG) + !!(ref_flags & VP9_LAST_FLAG)
2865         + !!(ref_flags & VP9_ALT_FLAG)) >= 2;
2866   }
2867 }
2868 
reset_skip_tx_size(VP9_COMMON * cm,TX_SIZE max_tx_size)2869 static void reset_skip_tx_size(VP9_COMMON *cm, TX_SIZE max_tx_size) {
2870   int mi_row, mi_col;
2871   const int mis = cm->mi_stride;
2872   MODE_INFO **mi_ptr = cm->mi_grid_visible;
2873 
2874   for (mi_row = 0; mi_row < cm->mi_rows; ++mi_row, mi_ptr += mis) {
2875     for (mi_col = 0; mi_col < cm->mi_cols; ++mi_col) {
2876       if (mi_ptr[mi_col]->mbmi.tx_size > max_tx_size)
2877         mi_ptr[mi_col]->mbmi.tx_size = max_tx_size;
2878     }
2879   }
2880 }
2881 
get_frame_type(const VP9_COMP * cpi)2882 static MV_REFERENCE_FRAME get_frame_type(const VP9_COMP *cpi) {
2883   if (frame_is_intra_only(&cpi->common))
2884     return INTRA_FRAME;
2885   else if (cpi->rc.is_src_frame_alt_ref && cpi->refresh_golden_frame)
2886     return ALTREF_FRAME;
2887   else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
2888     return GOLDEN_FRAME;
2889   else
2890     return LAST_FRAME;
2891 }
2892 
select_tx_mode(const VP9_COMP * cpi,MACROBLOCKD * const xd)2893 static TX_MODE select_tx_mode(const VP9_COMP *cpi, MACROBLOCKD *const xd) {
2894   if (xd->lossless)
2895     return ONLY_4X4;
2896   if (cpi->common.frame_type == KEY_FRAME &&
2897       cpi->sf.use_nonrd_pick_mode)
2898     return ALLOW_16X16;
2899   if (cpi->sf.tx_size_search_method == USE_LARGESTALL)
2900     return ALLOW_32X32;
2901   else if (cpi->sf.tx_size_search_method == USE_FULL_RD||
2902            cpi->sf.tx_size_search_method == USE_TX_8X8)
2903     return TX_MODE_SELECT;
2904   else
2905     return cpi->common.tx_mode;
2906 }
2907 
hybrid_intra_mode_search(VP9_COMP * cpi,MACROBLOCK * const x,RD_COST * rd_cost,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)2908 static void hybrid_intra_mode_search(VP9_COMP *cpi, MACROBLOCK *const x,
2909                                      RD_COST *rd_cost, BLOCK_SIZE bsize,
2910                                      PICK_MODE_CONTEXT *ctx) {
2911   if (bsize < BLOCK_16X16)
2912     vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
2913   else
2914     vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
2915 }
2916 
nonrd_pick_sb_modes(VP9_COMP * cpi,TileDataEnc * tile_data,MACROBLOCK * const x,int mi_row,int mi_col,RD_COST * rd_cost,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)2917 static void nonrd_pick_sb_modes(VP9_COMP *cpi,
2918                                 TileDataEnc *tile_data, MACROBLOCK *const x,
2919                                 int mi_row, int mi_col, RD_COST *rd_cost,
2920                                 BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
2921   VP9_COMMON *const cm = &cpi->common;
2922   TileInfo *const tile_info = &tile_data->tile_info;
2923   MACROBLOCKD *const xd = &x->e_mbd;
2924   MB_MODE_INFO *mbmi;
2925   set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2926   mbmi = &xd->mi[0]->mbmi;
2927   mbmi->sb_type = bsize;
2928 
2929   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled)
2930     if (cyclic_refresh_segment_id_boosted(mbmi->segment_id))
2931       x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
2932 
2933   if (cm->frame_type == KEY_FRAME)
2934     hybrid_intra_mode_search(cpi, x, rd_cost, bsize, ctx);
2935   else if (segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP))
2936     set_mode_info_seg_skip(x, cm->tx_mode, rd_cost, bsize);
2937   else if (bsize >= BLOCK_8X8)
2938     vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col,
2939                         rd_cost, bsize, ctx);
2940   else
2941     vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col,
2942                                rd_cost, bsize, ctx);
2943 
2944   duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
2945 
2946   if (rd_cost->rate == INT_MAX)
2947     vp9_rd_cost_reset(rd_cost);
2948 
2949   ctx->rate = rd_cost->rate;
2950   ctx->dist = rd_cost->dist;
2951 }
2952 
fill_mode_info_sb(VP9_COMMON * cm,MACROBLOCK * x,int mi_row,int mi_col,BLOCK_SIZE bsize,PC_TREE * pc_tree)2953 static void fill_mode_info_sb(VP9_COMMON *cm, MACROBLOCK *x,
2954                               int mi_row, int mi_col,
2955                               BLOCK_SIZE bsize,
2956                               PC_TREE *pc_tree) {
2957   MACROBLOCKD *xd = &x->e_mbd;
2958   int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2959   PARTITION_TYPE partition = pc_tree->partitioning;
2960   BLOCK_SIZE subsize = get_subsize(bsize, partition);
2961 
2962   assert(bsize >= BLOCK_8X8);
2963 
2964   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
2965     return;
2966 
2967   switch (partition) {
2968     case PARTITION_NONE:
2969       set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
2970       *(xd->mi[0]) = pc_tree->none.mic;
2971       *(x->mbmi_ext) = pc_tree->none.mbmi_ext;
2972       duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
2973       break;
2974     case PARTITION_VERT:
2975       set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
2976       *(xd->mi[0]) = pc_tree->vertical[0].mic;
2977       *(x->mbmi_ext) = pc_tree->vertical[0].mbmi_ext;
2978       duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
2979 
2980       if (mi_col + hbs < cm->mi_cols) {
2981         set_mode_info_offsets(cm, x, xd, mi_row, mi_col + hbs);
2982         *(xd->mi[0]) = pc_tree->vertical[1].mic;
2983         *(x->mbmi_ext) = pc_tree->vertical[1].mbmi_ext;
2984         duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col + hbs, subsize);
2985       }
2986       break;
2987     case PARTITION_HORZ:
2988       set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
2989       *(xd->mi[0]) = pc_tree->horizontal[0].mic;
2990       *(x->mbmi_ext) = pc_tree->horizontal[0].mbmi_ext;
2991       duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
2992       if (mi_row + hbs < cm->mi_rows) {
2993         set_mode_info_offsets(cm, x, xd, mi_row + hbs, mi_col);
2994         *(xd->mi[0]) = pc_tree->horizontal[1].mic;
2995         *(x->mbmi_ext) = pc_tree->horizontal[1].mbmi_ext;
2996         duplicate_mode_info_in_sb(cm, xd, mi_row + hbs, mi_col, subsize);
2997       }
2998       break;
2999     case PARTITION_SPLIT: {
3000       fill_mode_info_sb(cm, x, mi_row, mi_col, subsize, pc_tree->split[0]);
3001       fill_mode_info_sb(cm, x, mi_row, mi_col + hbs, subsize,
3002                         pc_tree->split[1]);
3003       fill_mode_info_sb(cm, x, mi_row + hbs, mi_col, subsize,
3004                         pc_tree->split[2]);
3005       fill_mode_info_sb(cm, x, mi_row + hbs, mi_col + hbs, subsize,
3006                         pc_tree->split[3]);
3007       break;
3008     }
3009     default:
3010       break;
3011   }
3012 }
3013 
3014 // Reset the prediction pixel ready flag recursively.
pred_pixel_ready_reset(PC_TREE * pc_tree,BLOCK_SIZE bsize)3015 static void pred_pixel_ready_reset(PC_TREE *pc_tree, BLOCK_SIZE bsize) {
3016   pc_tree->none.pred_pixel_ready = 0;
3017   pc_tree->horizontal[0].pred_pixel_ready = 0;
3018   pc_tree->horizontal[1].pred_pixel_ready = 0;
3019   pc_tree->vertical[0].pred_pixel_ready = 0;
3020   pc_tree->vertical[1].pred_pixel_ready = 0;
3021 
3022   if (bsize > BLOCK_8X8) {
3023     BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
3024     int i;
3025     for (i = 0; i < 4; ++i)
3026       pred_pixel_ready_reset(pc_tree->split[i], subsize);
3027   }
3028 }
3029 
nonrd_pick_partition(VP9_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,TOKENEXTRA ** tp,int mi_row,int mi_col,BLOCK_SIZE bsize,RD_COST * rd_cost,int do_recon,int64_t best_rd,PC_TREE * pc_tree)3030 static void nonrd_pick_partition(VP9_COMP *cpi, ThreadData *td,
3031                                  TileDataEnc *tile_data,
3032                                  TOKENEXTRA **tp, int mi_row,
3033                                  int mi_col, BLOCK_SIZE bsize, RD_COST *rd_cost,
3034                                  int do_recon, int64_t best_rd,
3035                                  PC_TREE *pc_tree) {
3036   const SPEED_FEATURES *const sf = &cpi->sf;
3037   VP9_COMMON *const cm = &cpi->common;
3038   TileInfo *const tile_info = &tile_data->tile_info;
3039   MACROBLOCK *const x = &td->mb;
3040   MACROBLOCKD *const xd = &x->e_mbd;
3041   const int ms = num_8x8_blocks_wide_lookup[bsize] / 2;
3042   TOKENEXTRA *tp_orig = *tp;
3043   PICK_MODE_CONTEXT *ctx = &pc_tree->none;
3044   int i;
3045   BLOCK_SIZE subsize = bsize;
3046   RD_COST this_rdc, sum_rdc, best_rdc;
3047   int do_split = bsize >= BLOCK_8X8;
3048   int do_rect = 1;
3049   // Override skipping rectangular partition operations for edge blocks
3050   const int force_horz_split = (mi_row + ms >= cm->mi_rows);
3051   const int force_vert_split = (mi_col + ms >= cm->mi_cols);
3052   const int xss = x->e_mbd.plane[1].subsampling_x;
3053   const int yss = x->e_mbd.plane[1].subsampling_y;
3054 
3055   int partition_none_allowed = !force_horz_split && !force_vert_split;
3056   int partition_horz_allowed = !force_vert_split && yss <= xss &&
3057                                bsize >= BLOCK_8X8;
3058   int partition_vert_allowed = !force_horz_split && xss <= yss &&
3059                                bsize >= BLOCK_8X8;
3060   (void) *tp_orig;
3061 
3062   assert(num_8x8_blocks_wide_lookup[bsize] ==
3063              num_8x8_blocks_high_lookup[bsize]);
3064 
3065   vp9_rd_cost_init(&sum_rdc);
3066   vp9_rd_cost_reset(&best_rdc);
3067   best_rdc.rdcost = best_rd;
3068 
3069   // Determine partition types in search according to the speed features.
3070   // The threshold set here has to be of square block size.
3071   if (sf->auto_min_max_partition_size) {
3072     partition_none_allowed &= (bsize <= x->max_partition_size &&
3073                                bsize >= x->min_partition_size);
3074     partition_horz_allowed &= ((bsize <= x->max_partition_size &&
3075                                 bsize > x->min_partition_size) ||
3076                                 force_horz_split);
3077     partition_vert_allowed &= ((bsize <= x->max_partition_size &&
3078                                 bsize > x->min_partition_size) ||
3079                                 force_vert_split);
3080     do_split &= bsize > x->min_partition_size;
3081   }
3082   if (sf->use_square_partition_only) {
3083     partition_horz_allowed &= force_horz_split;
3084     partition_vert_allowed &= force_vert_split;
3085   }
3086 
3087   ctx->pred_pixel_ready = !(partition_vert_allowed ||
3088                             partition_horz_allowed ||
3089                             do_split);
3090 
3091   // PARTITION_NONE
3092   if (partition_none_allowed) {
3093     nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col,
3094                         &this_rdc, bsize, ctx);
3095     ctx->mic.mbmi = xd->mi[0]->mbmi;
3096     ctx->mbmi_ext = *x->mbmi_ext;
3097     ctx->skip_txfm[0] = x->skip_txfm[0];
3098     ctx->skip = x->skip;
3099 
3100     if (this_rdc.rate != INT_MAX) {
3101       int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3102       this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
3103       this_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
3104                               this_rdc.rate, this_rdc.dist);
3105       if (this_rdc.rdcost < best_rdc.rdcost) {
3106         int64_t dist_breakout_thr = sf->partition_search_breakout_dist_thr;
3107         int64_t rate_breakout_thr = sf->partition_search_breakout_rate_thr;
3108 
3109         dist_breakout_thr >>= 8 - (b_width_log2_lookup[bsize] +
3110             b_height_log2_lookup[bsize]);
3111 
3112         rate_breakout_thr *= num_pels_log2_lookup[bsize];
3113 
3114         best_rdc = this_rdc;
3115         if (bsize >= BLOCK_8X8)
3116           pc_tree->partitioning = PARTITION_NONE;
3117 
3118         if (!x->e_mbd.lossless &&
3119             this_rdc.rate < rate_breakout_thr &&
3120             this_rdc.dist < dist_breakout_thr) {
3121           do_split = 0;
3122           do_rect = 0;
3123         }
3124       }
3125     }
3126   }
3127 
3128   // store estimated motion vector
3129   store_pred_mv(x, ctx);
3130 
3131   // PARTITION_SPLIT
3132   if (do_split) {
3133     int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3134     sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
3135     sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
3136     subsize = get_subsize(bsize, PARTITION_SPLIT);
3137     for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
3138       const int x_idx = (i & 1) * ms;
3139       const int y_idx = (i >> 1) * ms;
3140 
3141       if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
3142         continue;
3143       load_pred_mv(x, ctx);
3144       nonrd_pick_partition(cpi, td, tile_data, tp,
3145                            mi_row + y_idx, mi_col + x_idx,
3146                            subsize, &this_rdc, 0,
3147                            best_rdc.rdcost - sum_rdc.rdcost, pc_tree->split[i]);
3148 
3149       if (this_rdc.rate == INT_MAX) {
3150         vp9_rd_cost_reset(&sum_rdc);
3151       } else {
3152         sum_rdc.rate += this_rdc.rate;
3153         sum_rdc.dist += this_rdc.dist;
3154         sum_rdc.rdcost += this_rdc.rdcost;
3155       }
3156     }
3157 
3158     if (sum_rdc.rdcost < best_rdc.rdcost) {
3159       best_rdc = sum_rdc;
3160       pc_tree->partitioning = PARTITION_SPLIT;
3161     } else {
3162       // skip rectangular partition test when larger block size
3163       // gives better rd cost
3164       if (sf->less_rectangular_check)
3165         do_rect &= !partition_none_allowed;
3166     }
3167   }
3168 
3169   // PARTITION_HORZ
3170   if (partition_horz_allowed && do_rect) {
3171     subsize = get_subsize(bsize, PARTITION_HORZ);
3172     if (sf->adaptive_motion_search)
3173       load_pred_mv(x, ctx);
3174     pc_tree->horizontal[0].pred_pixel_ready = 1;
3175     nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
3176                         &pc_tree->horizontal[0]);
3177 
3178     pc_tree->horizontal[0].mic.mbmi = xd->mi[0]->mbmi;
3179     pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
3180     pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
3181     pc_tree->horizontal[0].skip = x->skip;
3182 
3183     if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + ms < cm->mi_rows) {
3184       load_pred_mv(x, ctx);
3185       pc_tree->horizontal[1].pred_pixel_ready = 1;
3186       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + ms, mi_col,
3187                           &this_rdc, subsize,
3188                           &pc_tree->horizontal[1]);
3189 
3190       pc_tree->horizontal[1].mic.mbmi = xd->mi[0]->mbmi;
3191       pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
3192       pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
3193       pc_tree->horizontal[1].skip = x->skip;
3194 
3195       if (this_rdc.rate == INT_MAX) {
3196         vp9_rd_cost_reset(&sum_rdc);
3197       } else {
3198         int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3199         this_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
3200         sum_rdc.rate += this_rdc.rate;
3201         sum_rdc.dist += this_rdc.dist;
3202         sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
3203                                 sum_rdc.rate, sum_rdc.dist);
3204       }
3205     }
3206 
3207     if (sum_rdc.rdcost < best_rdc.rdcost) {
3208       best_rdc = sum_rdc;
3209       pc_tree->partitioning = PARTITION_HORZ;
3210     } else {
3211       pred_pixel_ready_reset(pc_tree, bsize);
3212     }
3213   }
3214 
3215   // PARTITION_VERT
3216   if (partition_vert_allowed && do_rect) {
3217     subsize = get_subsize(bsize, PARTITION_VERT);
3218     if (sf->adaptive_motion_search)
3219       load_pred_mv(x, ctx);
3220     pc_tree->vertical[0].pred_pixel_ready = 1;
3221     nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
3222                         &pc_tree->vertical[0]);
3223     pc_tree->vertical[0].mic.mbmi = xd->mi[0]->mbmi;
3224     pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
3225     pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
3226     pc_tree->vertical[0].skip = x->skip;
3227 
3228     if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + ms < cm->mi_cols) {
3229       load_pred_mv(x, ctx);
3230       pc_tree->vertical[1].pred_pixel_ready = 1;
3231       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + ms,
3232                           &this_rdc, subsize,
3233                           &pc_tree->vertical[1]);
3234       pc_tree->vertical[1].mic.mbmi = xd->mi[0]->mbmi;
3235       pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
3236       pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
3237       pc_tree->vertical[1].skip = x->skip;
3238 
3239       if (this_rdc.rate == INT_MAX) {
3240         vp9_rd_cost_reset(&sum_rdc);
3241       } else {
3242         int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3243         sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
3244         sum_rdc.rate += this_rdc.rate;
3245         sum_rdc.dist += this_rdc.dist;
3246         sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv,
3247                                 sum_rdc.rate, sum_rdc.dist);
3248       }
3249     }
3250 
3251     if (sum_rdc.rdcost < best_rdc.rdcost) {
3252       best_rdc = sum_rdc;
3253       pc_tree->partitioning = PARTITION_VERT;
3254     } else {
3255       pred_pixel_ready_reset(pc_tree, bsize);
3256     }
3257   }
3258 
3259   *rd_cost = best_rdc;
3260 
3261   if (best_rdc.rate == INT_MAX) {
3262     vp9_rd_cost_reset(rd_cost);
3263     return;
3264   }
3265 
3266   // update mode info array
3267   fill_mode_info_sb(cm, x, mi_row, mi_col, bsize, pc_tree);
3268 
3269   if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX && do_recon) {
3270     int output_enabled = (bsize == BLOCK_64X64);
3271     encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
3272                  bsize, pc_tree);
3273   }
3274 
3275   if (bsize == BLOCK_64X64 && do_recon) {
3276     assert(tp_orig < *tp);
3277     assert(best_rdc.rate < INT_MAX);
3278     assert(best_rdc.dist < INT64_MAX);
3279   } else {
3280     assert(tp_orig == *tp);
3281   }
3282 }
3283 
nonrd_select_partition(VP9_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,MODE_INFO ** mi,TOKENEXTRA ** tp,int mi_row,int mi_col,BLOCK_SIZE bsize,int output_enabled,RD_COST * rd_cost,PC_TREE * pc_tree)3284 static void nonrd_select_partition(VP9_COMP *cpi,
3285                                    ThreadData *td,
3286                                    TileDataEnc *tile_data,
3287                                    MODE_INFO **mi,
3288                                    TOKENEXTRA **tp,
3289                                    int mi_row, int mi_col,
3290                                    BLOCK_SIZE bsize, int output_enabled,
3291                                    RD_COST *rd_cost, PC_TREE *pc_tree) {
3292   VP9_COMMON *const cm = &cpi->common;
3293   TileInfo *const tile_info = &tile_data->tile_info;
3294   MACROBLOCK *const x = &td->mb;
3295   MACROBLOCKD *const xd = &x->e_mbd;
3296   const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
3297   const int mis = cm->mi_stride;
3298   PARTITION_TYPE partition;
3299   BLOCK_SIZE subsize;
3300   RD_COST this_rdc;
3301 
3302   vp9_rd_cost_reset(&this_rdc);
3303   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
3304     return;
3305 
3306   subsize = (bsize >= BLOCK_8X8) ? mi[0]->mbmi.sb_type : BLOCK_4X4;
3307   partition = partition_lookup[bsl][subsize];
3308 
3309   if (bsize == BLOCK_32X32 && subsize == BLOCK_32X32) {
3310     x->max_partition_size = BLOCK_32X32;
3311     x->min_partition_size = BLOCK_16X16;
3312     nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize,
3313                          rd_cost, 0, INT64_MAX, pc_tree);
3314   } else if (bsize == BLOCK_32X32 && partition != PARTITION_NONE &&
3315              subsize >= BLOCK_16X16) {
3316     x->max_partition_size = BLOCK_32X32;
3317     x->min_partition_size = BLOCK_8X8;
3318     nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize,
3319                          rd_cost, 0, INT64_MAX, pc_tree);
3320   } else if (bsize == BLOCK_16X16 && partition != PARTITION_NONE) {
3321     x->max_partition_size = BLOCK_16X16;
3322     x->min_partition_size = BLOCK_8X8;
3323     nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize,
3324                          rd_cost, 0, INT64_MAX, pc_tree);
3325   } else {
3326     switch (partition) {
3327       case PARTITION_NONE:
3328         pc_tree->none.pred_pixel_ready = 1;
3329         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost,
3330                             subsize, &pc_tree->none);
3331         pc_tree->none.mic.mbmi = xd->mi[0]->mbmi;
3332         pc_tree->none.mbmi_ext = *x->mbmi_ext;
3333         pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
3334         pc_tree->none.skip = x->skip;
3335         break;
3336       case PARTITION_VERT:
3337         pc_tree->vertical[0].pred_pixel_ready = 1;
3338         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost,
3339                             subsize, &pc_tree->vertical[0]);
3340         pc_tree->vertical[0].mic.mbmi = xd->mi[0]->mbmi;
3341         pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
3342         pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
3343         pc_tree->vertical[0].skip = x->skip;
3344         if (mi_col + hbs < cm->mi_cols) {
3345           pc_tree->vertical[1].pred_pixel_ready = 1;
3346           nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs,
3347                               &this_rdc, subsize, &pc_tree->vertical[1]);
3348           pc_tree->vertical[1].mic.mbmi = xd->mi[0]->mbmi;
3349           pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
3350           pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
3351           pc_tree->vertical[1].skip = x->skip;
3352           if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3353               rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3354             rd_cost->rate += this_rdc.rate;
3355             rd_cost->dist += this_rdc.dist;
3356           }
3357         }
3358         break;
3359       case PARTITION_HORZ:
3360         pc_tree->horizontal[0].pred_pixel_ready = 1;
3361         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost,
3362                             subsize, &pc_tree->horizontal[0]);
3363         pc_tree->horizontal[0].mic.mbmi = xd->mi[0]->mbmi;
3364         pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
3365         pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
3366         pc_tree->horizontal[0].skip = x->skip;
3367         if (mi_row + hbs < cm->mi_rows) {
3368           pc_tree->horizontal[1].pred_pixel_ready = 1;
3369           nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col,
3370                               &this_rdc, subsize, &pc_tree->horizontal[1]);
3371           pc_tree->horizontal[1].mic.mbmi = xd->mi[0]->mbmi;
3372           pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
3373           pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
3374           pc_tree->horizontal[1].skip = x->skip;
3375           if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3376               rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3377             rd_cost->rate += this_rdc.rate;
3378             rd_cost->dist += this_rdc.dist;
3379           }
3380         }
3381         break;
3382       case PARTITION_SPLIT:
3383         subsize = get_subsize(bsize, PARTITION_SPLIT);
3384         nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3385                                subsize, output_enabled, rd_cost,
3386                                pc_tree->split[0]);
3387         nonrd_select_partition(cpi, td, tile_data, mi + hbs, tp,
3388                                mi_row, mi_col + hbs, subsize, output_enabled,
3389                                &this_rdc, pc_tree->split[1]);
3390         if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3391             rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3392           rd_cost->rate += this_rdc.rate;
3393           rd_cost->dist += this_rdc.dist;
3394         }
3395         nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis, tp,
3396                                mi_row + hbs, mi_col, subsize, output_enabled,
3397                                &this_rdc, pc_tree->split[2]);
3398         if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3399             rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3400           rd_cost->rate += this_rdc.rate;
3401           rd_cost->dist += this_rdc.dist;
3402         }
3403         nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
3404                                mi_row + hbs, mi_col + hbs, subsize,
3405                                output_enabled, &this_rdc, pc_tree->split[3]);
3406         if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
3407             rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
3408           rd_cost->rate += this_rdc.rate;
3409           rd_cost->dist += this_rdc.dist;
3410         }
3411         break;
3412       default:
3413         assert(0 && "Invalid partition type.");
3414         break;
3415     }
3416   }
3417 
3418   if (bsize == BLOCK_64X64 && output_enabled)
3419     encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, 1, bsize, pc_tree);
3420 }
3421 
3422 
nonrd_use_partition(VP9_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,MODE_INFO ** mi,TOKENEXTRA ** tp,int mi_row,int mi_col,BLOCK_SIZE bsize,int output_enabled,RD_COST * dummy_cost,PC_TREE * pc_tree)3423 static void nonrd_use_partition(VP9_COMP *cpi,
3424                                 ThreadData *td,
3425                                 TileDataEnc *tile_data,
3426                                 MODE_INFO **mi,
3427                                 TOKENEXTRA **tp,
3428                                 int mi_row, int mi_col,
3429                                 BLOCK_SIZE bsize, int output_enabled,
3430                                 RD_COST *dummy_cost, PC_TREE *pc_tree) {
3431   VP9_COMMON *const cm = &cpi->common;
3432   TileInfo *tile_info = &tile_data->tile_info;
3433   MACROBLOCK *const x = &td->mb;
3434   MACROBLOCKD *const xd = &x->e_mbd;
3435   const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
3436   const int mis = cm->mi_stride;
3437   PARTITION_TYPE partition;
3438   BLOCK_SIZE subsize;
3439 
3440   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
3441     return;
3442 
3443   subsize = (bsize >= BLOCK_8X8) ? mi[0]->mbmi.sb_type : BLOCK_4X4;
3444   partition = partition_lookup[bsl][subsize];
3445 
3446   if (output_enabled && bsize != BLOCK_4X4) {
3447     int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
3448     td->counts->partition[ctx][partition]++;
3449   }
3450 
3451   switch (partition) {
3452     case PARTITION_NONE:
3453       pc_tree->none.pred_pixel_ready = 1;
3454       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
3455                           subsize, &pc_tree->none);
3456       pc_tree->none.mic.mbmi = xd->mi[0]->mbmi;
3457       pc_tree->none.mbmi_ext = *x->mbmi_ext;
3458       pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
3459       pc_tree->none.skip = x->skip;
3460       encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
3461                   subsize, &pc_tree->none);
3462       break;
3463     case PARTITION_VERT:
3464       pc_tree->vertical[0].pred_pixel_ready = 1;
3465       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
3466                           subsize, &pc_tree->vertical[0]);
3467       pc_tree->vertical[0].mic.mbmi = xd->mi[0]->mbmi;
3468       pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
3469       pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
3470       pc_tree->vertical[0].skip = x->skip;
3471       encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
3472                   subsize, &pc_tree->vertical[0]);
3473       if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
3474         pc_tree->vertical[1].pred_pixel_ready = 1;
3475         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs,
3476                             dummy_cost, subsize, &pc_tree->vertical[1]);
3477         pc_tree->vertical[1].mic.mbmi = xd->mi[0]->mbmi;
3478         pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
3479         pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
3480         pc_tree->vertical[1].skip = x->skip;
3481         encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col + hbs,
3482                     output_enabled, subsize, &pc_tree->vertical[1]);
3483       }
3484       break;
3485     case PARTITION_HORZ:
3486       pc_tree->horizontal[0].pred_pixel_ready = 1;
3487       nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
3488                           subsize, &pc_tree->horizontal[0]);
3489       pc_tree->horizontal[0].mic.mbmi = xd->mi[0]->mbmi;
3490       pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
3491       pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
3492       pc_tree->horizontal[0].skip = x->skip;
3493       encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
3494                   subsize, &pc_tree->horizontal[0]);
3495 
3496       if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
3497         pc_tree->horizontal[1].pred_pixel_ready = 1;
3498         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col,
3499                             dummy_cost, subsize, &pc_tree->horizontal[1]);
3500         pc_tree->horizontal[1].mic.mbmi = xd->mi[0]->mbmi;
3501         pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
3502         pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
3503         pc_tree->horizontal[1].skip = x->skip;
3504         encode_b_rt(cpi, td, tile_info, tp, mi_row + hbs, mi_col,
3505                     output_enabled, subsize, &pc_tree->horizontal[1]);
3506       }
3507       break;
3508     case PARTITION_SPLIT:
3509       subsize = get_subsize(bsize, PARTITION_SPLIT);
3510       if (bsize == BLOCK_8X8) {
3511         nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
3512                             subsize, pc_tree->leaf_split[0]);
3513         encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col,
3514                     output_enabled, subsize, pc_tree->leaf_split[0]);
3515       } else {
3516         nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3517                             subsize, output_enabled, dummy_cost,
3518                             pc_tree->split[0]);
3519         nonrd_use_partition(cpi, td, tile_data, mi + hbs, tp,
3520                             mi_row, mi_col + hbs, subsize, output_enabled,
3521                             dummy_cost, pc_tree->split[1]);
3522         nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis, tp,
3523                             mi_row + hbs, mi_col, subsize, output_enabled,
3524                             dummy_cost, pc_tree->split[2]);
3525         nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
3526                             mi_row + hbs, mi_col + hbs, subsize, output_enabled,
3527                             dummy_cost, pc_tree->split[3]);
3528       }
3529       break;
3530     default:
3531       assert(0 && "Invalid partition type.");
3532       break;
3533   }
3534 
3535   if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
3536     update_partition_context(xd, mi_row, mi_col, subsize, bsize);
3537 }
3538 
encode_nonrd_sb_row(VP9_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,int mi_row,TOKENEXTRA ** tp)3539 static void encode_nonrd_sb_row(VP9_COMP *cpi,
3540                                 ThreadData *td,
3541                                 TileDataEnc *tile_data,
3542                                 int mi_row,
3543                                 TOKENEXTRA **tp) {
3544   SPEED_FEATURES *const sf = &cpi->sf;
3545   VP9_COMMON *const cm = &cpi->common;
3546   TileInfo *const tile_info = &tile_data->tile_info;
3547   MACROBLOCK *const x = &td->mb;
3548   MACROBLOCKD *const xd = &x->e_mbd;
3549   int mi_col;
3550 
3551   // Initialize the left context for the new SB row
3552   memset(&xd->left_context, 0, sizeof(xd->left_context));
3553   memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
3554 
3555   // Code each SB in the row
3556   for (mi_col = tile_info->mi_col_start; mi_col < tile_info->mi_col_end;
3557        mi_col += MI_BLOCK_SIZE) {
3558     const struct segmentation *const seg = &cm->seg;
3559     RD_COST dummy_rdc;
3560     const int idx_str = cm->mi_stride * mi_row + mi_col;
3561     MODE_INFO **mi = cm->mi_grid_visible + idx_str;
3562     PARTITION_SEARCH_TYPE partition_search_type = sf->partition_search_type;
3563     BLOCK_SIZE bsize = BLOCK_64X64;
3564     int seg_skip = 0;
3565     x->source_variance = UINT_MAX;
3566     vp9_zero(x->pred_mv);
3567     vp9_rd_cost_init(&dummy_rdc);
3568     x->color_sensitivity[0] = 0;
3569     x->color_sensitivity[1] = 0;
3570 
3571     if (seg->enabled) {
3572       const uint8_t *const map = seg->update_map ? cpi->segmentation_map
3573                                                  : cm->last_frame_seg_map;
3574       int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
3575       seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
3576       if (seg_skip) {
3577         partition_search_type = FIXED_PARTITION;
3578       }
3579     }
3580 
3581     // Set the partition type of the 64X64 block
3582     switch (partition_search_type) {
3583       case VAR_BASED_PARTITION:
3584         // TODO(jingning, marpan): The mode decision and encoding process
3585         // support both intra and inter sub8x8 block coding for RTC mode.
3586         // Tune the thresholds accordingly to use sub8x8 block coding for
3587         // coding performance improvement.
3588         choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
3589         nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3590                             BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
3591         break;
3592       case SOURCE_VAR_BASED_PARTITION:
3593         set_source_var_based_partition(cpi, tile_info, x, mi, mi_row, mi_col);
3594         nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3595                             BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
3596         break;
3597       case FIXED_PARTITION:
3598         if (!seg_skip)
3599           bsize = sf->always_this_block_size;
3600         set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
3601         nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3602                             BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
3603         break;
3604       case REFERENCE_PARTITION:
3605         set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
3606         if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled &&
3607             xd->mi[0]->mbmi.segment_id) {
3608           // Use lower max_partition_size for low resoultions.
3609           if (cm->width <= 352 && cm->height <= 288)
3610             x->max_partition_size = BLOCK_32X32;
3611           else
3612             x->max_partition_size = BLOCK_64X64;
3613           x->min_partition_size = BLOCK_8X8;
3614           nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
3615                                BLOCK_64X64, &dummy_rdc, 1,
3616                                INT64_MAX, td->pc_root);
3617         } else {
3618           choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
3619           // TODO(marpan): Seems like nonrd_select_partition does not support
3620           // 4x4 partition. Since 4x4 is used on key frame, use this switch
3621           // for now.
3622           if (cm->frame_type == KEY_FRAME)
3623             nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3624                                 BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
3625           else
3626             nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
3627                                    BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
3628         }
3629 
3630         break;
3631       default:
3632         assert(0);
3633         break;
3634     }
3635   }
3636 }
3637 // end RTC play code
3638 
set_var_thresh_from_histogram(VP9_COMP * cpi)3639 static int set_var_thresh_from_histogram(VP9_COMP *cpi) {
3640   const SPEED_FEATURES *const sf = &cpi->sf;
3641   const VP9_COMMON *const cm = &cpi->common;
3642 
3643   const uint8_t *src = cpi->Source->y_buffer;
3644   const uint8_t *last_src = cpi->Last_Source->y_buffer;
3645   const int src_stride = cpi->Source->y_stride;
3646   const int last_stride = cpi->Last_Source->y_stride;
3647 
3648   // Pick cutoff threshold
3649   const int cutoff = (MIN(cm->width, cm->height) >= 720) ?
3650       (cm->MBs * VAR_HIST_LARGE_CUT_OFF / 100) :
3651       (cm->MBs * VAR_HIST_SMALL_CUT_OFF / 100);
3652   DECLARE_ALIGNED(16, int, hist[VAR_HIST_BINS]);
3653   diff *var16 = cpi->source_diff_var;
3654 
3655   int sum = 0;
3656   int i, j;
3657 
3658   memset(hist, 0, VAR_HIST_BINS * sizeof(hist[0]));
3659 
3660   for (i = 0; i < cm->mb_rows; i++) {
3661     for (j = 0; j < cm->mb_cols; j++) {
3662 #if CONFIG_VP9_HIGHBITDEPTH
3663       if (cm->use_highbitdepth) {
3664         switch (cm->bit_depth) {
3665           case VPX_BITS_8:
3666             vpx_highbd_8_get16x16var(src, src_stride, last_src, last_stride,
3667                                    &var16->sse, &var16->sum);
3668             break;
3669           case VPX_BITS_10:
3670             vpx_highbd_10_get16x16var(src, src_stride, last_src, last_stride,
3671                                     &var16->sse, &var16->sum);
3672             break;
3673           case VPX_BITS_12:
3674             vpx_highbd_12_get16x16var(src, src_stride, last_src, last_stride,
3675                                       &var16->sse, &var16->sum);
3676             break;
3677           default:
3678             assert(0 && "cm->bit_depth should be VPX_BITS_8, VPX_BITS_10"
3679                    " or VPX_BITS_12");
3680             return -1;
3681         }
3682       } else {
3683         vpx_get16x16var(src, src_stride, last_src, last_stride,
3684                         &var16->sse, &var16->sum);
3685       }
3686 #else
3687       vpx_get16x16var(src, src_stride, last_src, last_stride,
3688                       &var16->sse, &var16->sum);
3689 #endif  // CONFIG_VP9_HIGHBITDEPTH
3690       var16->var = var16->sse -
3691           (((uint32_t)var16->sum * var16->sum) >> 8);
3692 
3693       if (var16->var >= VAR_HIST_MAX_BG_VAR)
3694         hist[VAR_HIST_BINS - 1]++;
3695       else
3696         hist[var16->var / VAR_HIST_FACTOR]++;
3697 
3698       src += 16;
3699       last_src += 16;
3700       var16++;
3701     }
3702 
3703     src = src - cm->mb_cols * 16 + 16 * src_stride;
3704     last_src = last_src - cm->mb_cols * 16 + 16 * last_stride;
3705   }
3706 
3707   cpi->source_var_thresh = 0;
3708 
3709   if (hist[VAR_HIST_BINS - 1] < cutoff) {
3710     for (i = 0; i < VAR_HIST_BINS - 1; i++) {
3711       sum += hist[i];
3712 
3713       if (sum > cutoff) {
3714         cpi->source_var_thresh = (i + 1) * VAR_HIST_FACTOR;
3715         return 0;
3716       }
3717     }
3718   }
3719 
3720   return sf->search_type_check_frequency;
3721 }
3722 
source_var_based_partition_search_method(VP9_COMP * cpi)3723 static void source_var_based_partition_search_method(VP9_COMP *cpi) {
3724   VP9_COMMON *const cm = &cpi->common;
3725   SPEED_FEATURES *const sf = &cpi->sf;
3726 
3727   if (cm->frame_type == KEY_FRAME) {
3728     // For key frame, use SEARCH_PARTITION.
3729     sf->partition_search_type = SEARCH_PARTITION;
3730   } else if (cm->intra_only) {
3731     sf->partition_search_type = FIXED_PARTITION;
3732   } else {
3733     if (cm->last_width != cm->width || cm->last_height != cm->height) {
3734       if (cpi->source_diff_var)
3735         vpx_free(cpi->source_diff_var);
3736 
3737       CHECK_MEM_ERROR(cm, cpi->source_diff_var,
3738                       vpx_calloc(cm->MBs, sizeof(diff)));
3739     }
3740 
3741     if (!cpi->frames_till_next_var_check)
3742       cpi->frames_till_next_var_check = set_var_thresh_from_histogram(cpi);
3743 
3744     if (cpi->frames_till_next_var_check > 0) {
3745       sf->partition_search_type = FIXED_PARTITION;
3746       cpi->frames_till_next_var_check--;
3747     }
3748   }
3749 }
3750 
get_skip_encode_frame(const VP9_COMMON * cm,ThreadData * const td)3751 static int get_skip_encode_frame(const VP9_COMMON *cm, ThreadData *const td) {
3752   unsigned int intra_count = 0, inter_count = 0;
3753   int j;
3754 
3755   for (j = 0; j < INTRA_INTER_CONTEXTS; ++j) {
3756     intra_count += td->counts->intra_inter[j][0];
3757     inter_count += td->counts->intra_inter[j][1];
3758   }
3759 
3760   return (intra_count << 2) < inter_count &&
3761          cm->frame_type != KEY_FRAME &&
3762          cm->show_frame;
3763 }
3764 
vp9_init_tile_data(VP9_COMP * cpi)3765 void vp9_init_tile_data(VP9_COMP *cpi) {
3766   VP9_COMMON *const cm = &cpi->common;
3767   const int tile_cols = 1 << cm->log2_tile_cols;
3768   const int tile_rows = 1 << cm->log2_tile_rows;
3769   int tile_col, tile_row;
3770   TOKENEXTRA *pre_tok = cpi->tile_tok[0][0];
3771   int tile_tok = 0;
3772 
3773   if (cpi->tile_data == NULL || cpi->allocated_tiles < tile_cols * tile_rows) {
3774     if (cpi->tile_data != NULL)
3775       vpx_free(cpi->tile_data);
3776     CHECK_MEM_ERROR(cm, cpi->tile_data,
3777         vpx_malloc(tile_cols * tile_rows * sizeof(*cpi->tile_data)));
3778     cpi->allocated_tiles = tile_cols * tile_rows;
3779 
3780     for (tile_row = 0; tile_row < tile_rows; ++tile_row)
3781       for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
3782         TileDataEnc *tile_data =
3783             &cpi->tile_data[tile_row * tile_cols + tile_col];
3784         int i, j;
3785         for (i = 0; i < BLOCK_SIZES; ++i) {
3786           for (j = 0; j < MAX_MODES; ++j) {
3787             tile_data->thresh_freq_fact[i][j] = 32;
3788             tile_data->mode_map[i][j] = j;
3789           }
3790         }
3791       }
3792   }
3793 
3794   for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
3795     for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
3796       TileInfo *tile_info =
3797           &cpi->tile_data[tile_row * tile_cols + tile_col].tile_info;
3798       vp9_tile_init(tile_info, cm, tile_row, tile_col);
3799 
3800       cpi->tile_tok[tile_row][tile_col] = pre_tok + tile_tok;
3801       pre_tok = cpi->tile_tok[tile_row][tile_col];
3802       tile_tok = allocated_tokens(*tile_info);
3803     }
3804   }
3805 }
3806 
vp9_encode_tile(VP9_COMP * cpi,ThreadData * td,int tile_row,int tile_col)3807 void vp9_encode_tile(VP9_COMP *cpi, ThreadData *td,
3808                      int tile_row, int tile_col) {
3809   VP9_COMMON *const cm = &cpi->common;
3810   const int tile_cols = 1 << cm->log2_tile_cols;
3811   TileDataEnc *this_tile =
3812       &cpi->tile_data[tile_row * tile_cols + tile_col];
3813   const TileInfo * const tile_info = &this_tile->tile_info;
3814   TOKENEXTRA *tok = cpi->tile_tok[tile_row][tile_col];
3815   int mi_row;
3816 
3817   for (mi_row = tile_info->mi_row_start; mi_row < tile_info->mi_row_end;
3818        mi_row += MI_BLOCK_SIZE) {
3819     if (cpi->sf.use_nonrd_pick_mode)
3820       encode_nonrd_sb_row(cpi, td, this_tile, mi_row, &tok);
3821     else
3822       encode_rd_sb_row(cpi, td, this_tile, mi_row, &tok);
3823   }
3824   cpi->tok_count[tile_row][tile_col] =
3825       (unsigned int)(tok - cpi->tile_tok[tile_row][tile_col]);
3826   assert(tok - cpi->tile_tok[tile_row][tile_col] <=
3827       allocated_tokens(*tile_info));
3828 }
3829 
encode_tiles(VP9_COMP * cpi)3830 static void encode_tiles(VP9_COMP *cpi) {
3831   VP9_COMMON *const cm = &cpi->common;
3832   const int tile_cols = 1 << cm->log2_tile_cols;
3833   const int tile_rows = 1 << cm->log2_tile_rows;
3834   int tile_col, tile_row;
3835 
3836   vp9_init_tile_data(cpi);
3837 
3838   for (tile_row = 0; tile_row < tile_rows; ++tile_row)
3839     for (tile_col = 0; tile_col < tile_cols; ++tile_col)
3840       vp9_encode_tile(cpi, &cpi->td, tile_row, tile_col);
3841 }
3842 
3843 #if CONFIG_FP_MB_STATS
input_fpmb_stats(FIRSTPASS_MB_STATS * firstpass_mb_stats,VP9_COMMON * cm,uint8_t ** this_frame_mb_stats)3844 static int input_fpmb_stats(FIRSTPASS_MB_STATS *firstpass_mb_stats,
3845                             VP9_COMMON *cm, uint8_t **this_frame_mb_stats) {
3846   uint8_t *mb_stats_in = firstpass_mb_stats->mb_stats_start +
3847       cm->current_video_frame * cm->MBs * sizeof(uint8_t);
3848 
3849   if (mb_stats_in > firstpass_mb_stats->mb_stats_end)
3850     return EOF;
3851 
3852   *this_frame_mb_stats = mb_stats_in;
3853 
3854   return 1;
3855 }
3856 #endif
3857 
encode_frame_internal(VP9_COMP * cpi)3858 static void encode_frame_internal(VP9_COMP *cpi) {
3859   SPEED_FEATURES *const sf = &cpi->sf;
3860   ThreadData *const td = &cpi->td;
3861   MACROBLOCK *const x = &td->mb;
3862   VP9_COMMON *const cm = &cpi->common;
3863   MACROBLOCKD *const xd = &x->e_mbd;
3864   RD_COUNTS *const rdc = &cpi->td.rd_counts;
3865 
3866   xd->mi = cm->mi_grid_visible;
3867   xd->mi[0] = cm->mi;
3868 
3869   vp9_zero(*td->counts);
3870   vp9_zero(rdc->coef_counts);
3871   vp9_zero(rdc->comp_pred_diff);
3872   vp9_zero(rdc->filter_diff);
3873 
3874   xd->lossless = cm->base_qindex == 0 &&
3875                  cm->y_dc_delta_q == 0 &&
3876                  cm->uv_dc_delta_q == 0 &&
3877                  cm->uv_ac_delta_q == 0;
3878 
3879 #if CONFIG_VP9_HIGHBITDEPTH
3880   if (cm->use_highbitdepth)
3881     x->fwd_txm4x4 = xd->lossless ? vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
3882   else
3883     x->fwd_txm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
3884   x->highbd_itxm_add = xd->lossless ? vp9_highbd_iwht4x4_add :
3885                                       vp9_highbd_idct4x4_add;
3886 #else
3887   x->fwd_txm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
3888 #endif  // CONFIG_VP9_HIGHBITDEPTH
3889   x->itxm_add = xd->lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
3890 
3891   if (xd->lossless)
3892     x->optimize = 0;
3893 
3894   cm->tx_mode = select_tx_mode(cpi, xd);
3895 
3896   vp9_frame_init_quantizer(cpi);
3897 
3898   vp9_initialize_rd_consts(cpi);
3899   vp9_initialize_me_consts(cpi, x, cm->base_qindex);
3900   init_encode_frame_mb_context(cpi);
3901   cm->use_prev_frame_mvs = !cm->error_resilient_mode &&
3902                            cm->width == cm->last_width &&
3903                            cm->height == cm->last_height &&
3904                            !cm->intra_only &&
3905                            cm->last_show_frame;
3906   // Special case: set prev_mi to NULL when the previous mode info
3907   // context cannot be used.
3908   cm->prev_mi = cm->use_prev_frame_mvs ?
3909                 cm->prev_mip + cm->mi_stride + 1 : NULL;
3910 
3911   x->quant_fp = cpi->sf.use_quant_fp;
3912   vp9_zero(x->skip_txfm);
3913   if (sf->use_nonrd_pick_mode) {
3914     // Initialize internal buffer pointers for rtc coding, where non-RD
3915     // mode decision is used and hence no buffer pointer swap needed.
3916     int i;
3917     struct macroblock_plane *const p = x->plane;
3918     struct macroblockd_plane *const pd = xd->plane;
3919     PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
3920 
3921     for (i = 0; i < MAX_MB_PLANE; ++i) {
3922       p[i].coeff = ctx->coeff_pbuf[i][0];
3923       p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
3924       pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
3925       p[i].eobs = ctx->eobs_pbuf[i][0];
3926     }
3927     vp9_zero(x->zcoeff_blk);
3928 
3929     if (cm->frame_type != KEY_FRAME &&
3930         cpi->rc.frames_since_golden == 0 &&
3931         !cpi->use_svc)
3932       cpi->ref_frame_flags &= (~VP9_GOLD_FLAG);
3933 
3934     if (sf->partition_search_type == SOURCE_VAR_BASED_PARTITION)
3935       source_var_based_partition_search_method(cpi);
3936   }
3937 
3938   {
3939     struct vpx_usec_timer emr_timer;
3940     vpx_usec_timer_start(&emr_timer);
3941 
3942 #if CONFIG_FP_MB_STATS
3943   if (cpi->use_fp_mb_stats) {
3944     input_fpmb_stats(&cpi->twopass.firstpass_mb_stats, cm,
3945                      &cpi->twopass.this_frame_mb_stats);
3946   }
3947 #endif
3948 
3949     // If allowed, encoding tiles in parallel with one thread handling one tile.
3950     if (MIN(cpi->oxcf.max_threads, 1 << cm->log2_tile_cols) > 1)
3951       vp9_encode_tiles_mt(cpi);
3952     else
3953       encode_tiles(cpi);
3954 
3955     vpx_usec_timer_mark(&emr_timer);
3956     cpi->time_encode_sb_row += vpx_usec_timer_elapsed(&emr_timer);
3957   }
3958 
3959   sf->skip_encode_frame = sf->skip_encode_sb ?
3960       get_skip_encode_frame(cm, td) : 0;
3961 
3962 #if 0
3963   // Keep record of the total distortion this time around for future use
3964   cpi->last_frame_distortion = cpi->frame_distortion;
3965 #endif
3966 }
3967 
get_interp_filter(const int64_t threshes[SWITCHABLE_FILTER_CONTEXTS],int is_alt_ref)3968 static INTERP_FILTER get_interp_filter(
3969     const int64_t threshes[SWITCHABLE_FILTER_CONTEXTS], int is_alt_ref) {
3970   if (!is_alt_ref &&
3971       threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP] &&
3972       threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP_SHARP] &&
3973       threshes[EIGHTTAP_SMOOTH] > threshes[SWITCHABLE - 1]) {
3974     return EIGHTTAP_SMOOTH;
3975   } else if (threshes[EIGHTTAP_SHARP] > threshes[EIGHTTAP] &&
3976              threshes[EIGHTTAP_SHARP] > threshes[SWITCHABLE - 1]) {
3977     return EIGHTTAP_SHARP;
3978   } else if (threshes[EIGHTTAP] > threshes[SWITCHABLE - 1]) {
3979     return EIGHTTAP;
3980   } else {
3981     return SWITCHABLE;
3982   }
3983 }
3984 
vp9_encode_frame(VP9_COMP * cpi)3985 void vp9_encode_frame(VP9_COMP *cpi) {
3986   VP9_COMMON *const cm = &cpi->common;
3987 
3988   // In the longer term the encoder should be generalized to match the
3989   // decoder such that we allow compound where one of the 3 buffers has a
3990   // different sign bias and that buffer is then the fixed ref. However, this
3991   // requires further work in the rd loop. For now the only supported encoder
3992   // side behavior is where the ALT ref buffer has opposite sign bias to
3993   // the other two.
3994   if (!frame_is_intra_only(cm)) {
3995     if ((cm->ref_frame_sign_bias[ALTREF_FRAME] ==
3996              cm->ref_frame_sign_bias[GOLDEN_FRAME]) ||
3997         (cm->ref_frame_sign_bias[ALTREF_FRAME] ==
3998              cm->ref_frame_sign_bias[LAST_FRAME])) {
3999       cpi->allow_comp_inter_inter = 0;
4000     } else {
4001       cpi->allow_comp_inter_inter = 1;
4002       cm->comp_fixed_ref = ALTREF_FRAME;
4003       cm->comp_var_ref[0] = LAST_FRAME;
4004       cm->comp_var_ref[1] = GOLDEN_FRAME;
4005     }
4006   }
4007 
4008   if (cpi->sf.frame_parameter_update) {
4009     int i;
4010     RD_OPT *const rd_opt = &cpi->rd;
4011     FRAME_COUNTS *counts = cpi->td.counts;
4012     RD_COUNTS *const rdc = &cpi->td.rd_counts;
4013 
4014     // This code does a single RD pass over the whole frame assuming
4015     // either compound, single or hybrid prediction as per whatever has
4016     // worked best for that type of frame in the past.
4017     // It also predicts whether another coding mode would have worked
4018     // better that this coding mode. If that is the case, it remembers
4019     // that for subsequent frames.
4020     // It does the same analysis for transform size selection also.
4021     const MV_REFERENCE_FRAME frame_type = get_frame_type(cpi);
4022     int64_t *const mode_thrs = rd_opt->prediction_type_threshes[frame_type];
4023     int64_t *const filter_thrs = rd_opt->filter_threshes[frame_type];
4024     const int is_alt_ref = frame_type == ALTREF_FRAME;
4025 
4026     /* prediction (compound, single or hybrid) mode selection */
4027     if (is_alt_ref || !cpi->allow_comp_inter_inter)
4028       cm->reference_mode = SINGLE_REFERENCE;
4029     else if (mode_thrs[COMPOUND_REFERENCE] > mode_thrs[SINGLE_REFERENCE] &&
4030              mode_thrs[COMPOUND_REFERENCE] >
4031                  mode_thrs[REFERENCE_MODE_SELECT] &&
4032              check_dual_ref_flags(cpi) &&
4033              cpi->static_mb_pct == 100)
4034       cm->reference_mode = COMPOUND_REFERENCE;
4035     else if (mode_thrs[SINGLE_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT])
4036       cm->reference_mode = SINGLE_REFERENCE;
4037     else
4038       cm->reference_mode = REFERENCE_MODE_SELECT;
4039 
4040     if (cm->interp_filter == SWITCHABLE)
4041       cm->interp_filter = get_interp_filter(filter_thrs, is_alt_ref);
4042 
4043     encode_frame_internal(cpi);
4044 
4045     for (i = 0; i < REFERENCE_MODES; ++i)
4046       mode_thrs[i] = (mode_thrs[i] + rdc->comp_pred_diff[i] / cm->MBs) / 2;
4047 
4048     for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
4049       filter_thrs[i] = (filter_thrs[i] + rdc->filter_diff[i] / cm->MBs) / 2;
4050 
4051     if (cm->reference_mode == REFERENCE_MODE_SELECT) {
4052       int single_count_zero = 0;
4053       int comp_count_zero = 0;
4054 
4055       for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
4056         single_count_zero += counts->comp_inter[i][0];
4057         comp_count_zero += counts->comp_inter[i][1];
4058       }
4059 
4060       if (comp_count_zero == 0) {
4061         cm->reference_mode = SINGLE_REFERENCE;
4062         vp9_zero(counts->comp_inter);
4063       } else if (single_count_zero == 0) {
4064         cm->reference_mode = COMPOUND_REFERENCE;
4065         vp9_zero(counts->comp_inter);
4066       }
4067     }
4068 
4069     if (cm->tx_mode == TX_MODE_SELECT) {
4070       int count4x4 = 0;
4071       int count8x8_lp = 0, count8x8_8x8p = 0;
4072       int count16x16_16x16p = 0, count16x16_lp = 0;
4073       int count32x32 = 0;
4074 
4075       for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
4076         count4x4 += counts->tx.p32x32[i][TX_4X4];
4077         count4x4 += counts->tx.p16x16[i][TX_4X4];
4078         count4x4 += counts->tx.p8x8[i][TX_4X4];
4079 
4080         count8x8_lp += counts->tx.p32x32[i][TX_8X8];
4081         count8x8_lp += counts->tx.p16x16[i][TX_8X8];
4082         count8x8_8x8p += counts->tx.p8x8[i][TX_8X8];
4083 
4084         count16x16_16x16p += counts->tx.p16x16[i][TX_16X16];
4085         count16x16_lp += counts->tx.p32x32[i][TX_16X16];
4086         count32x32 += counts->tx.p32x32[i][TX_32X32];
4087       }
4088       if (count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0 &&
4089           count32x32 == 0) {
4090         cm->tx_mode = ALLOW_8X8;
4091         reset_skip_tx_size(cm, TX_8X8);
4092       } else if (count8x8_8x8p == 0 && count16x16_16x16p == 0 &&
4093                  count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0) {
4094         cm->tx_mode = ONLY_4X4;
4095         reset_skip_tx_size(cm, TX_4X4);
4096       } else if (count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0) {
4097         cm->tx_mode = ALLOW_32X32;
4098       } else if (count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0) {
4099         cm->tx_mode = ALLOW_16X16;
4100         reset_skip_tx_size(cm, TX_16X16);
4101       }
4102     }
4103   } else {
4104     cm->reference_mode = SINGLE_REFERENCE;
4105     encode_frame_internal(cpi);
4106   }
4107 }
4108 
sum_intra_stats(FRAME_COUNTS * counts,const MODE_INFO * mi)4109 static void sum_intra_stats(FRAME_COUNTS *counts, const MODE_INFO *mi) {
4110   const PREDICTION_MODE y_mode = mi->mbmi.mode;
4111   const PREDICTION_MODE uv_mode = mi->mbmi.uv_mode;
4112   const BLOCK_SIZE bsize = mi->mbmi.sb_type;
4113 
4114   if (bsize < BLOCK_8X8) {
4115     int idx, idy;
4116     const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
4117     const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
4118     for (idy = 0; idy < 2; idy += num_4x4_h)
4119       for (idx = 0; idx < 2; idx += num_4x4_w)
4120         ++counts->y_mode[0][mi->bmi[idy * 2 + idx].as_mode];
4121   } else {
4122     ++counts->y_mode[size_group_lookup[bsize]][y_mode];
4123   }
4124 
4125   ++counts->uv_mode[y_mode][uv_mode];
4126 }
4127 
encode_superblock(VP9_COMP * cpi,ThreadData * td,TOKENEXTRA ** t,int output_enabled,int mi_row,int mi_col,BLOCK_SIZE bsize,PICK_MODE_CONTEXT * ctx)4128 static void encode_superblock(VP9_COMP *cpi, ThreadData *td,
4129                               TOKENEXTRA **t, int output_enabled,
4130                               int mi_row, int mi_col, BLOCK_SIZE bsize,
4131                               PICK_MODE_CONTEXT *ctx) {
4132   VP9_COMMON *const cm = &cpi->common;
4133   MACROBLOCK *const x = &td->mb;
4134   MACROBLOCKD *const xd = &x->e_mbd;
4135   MODE_INFO **mi_8x8 = xd->mi;
4136   MODE_INFO *mi = mi_8x8[0];
4137   MB_MODE_INFO *mbmi = &mi->mbmi;
4138   const int seg_skip = segfeature_active(&cm->seg, mbmi->segment_id,
4139                                          SEG_LVL_SKIP);
4140   const int mis = cm->mi_stride;
4141   const int mi_width = num_8x8_blocks_wide_lookup[bsize];
4142   const int mi_height = num_8x8_blocks_high_lookup[bsize];
4143 
4144   x->skip_recode = !x->select_tx_size && mbmi->sb_type >= BLOCK_8X8 &&
4145                    cpi->oxcf.aq_mode != COMPLEXITY_AQ &&
4146                    cpi->oxcf.aq_mode != CYCLIC_REFRESH_AQ &&
4147                    cpi->sf.allow_skip_recode;
4148 
4149   if (!x->skip_recode && !cpi->sf.use_nonrd_pick_mode)
4150     memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
4151 
4152   x->skip_optimize = ctx->is_coded;
4153   ctx->is_coded = 1;
4154   x->use_lp32x32fdct = cpi->sf.use_lp32x32fdct;
4155   x->skip_encode = (!output_enabled && cpi->sf.skip_encode_frame &&
4156                     x->q_index < QIDX_SKIP_THRESH);
4157 
4158   if (x->skip_encode)
4159     return;
4160 
4161   if (!is_inter_block(mbmi)) {
4162     int plane;
4163     mbmi->skip = 1;
4164     for (plane = 0; plane < MAX_MB_PLANE; ++plane)
4165       vp9_encode_intra_block_plane(x, MAX(bsize, BLOCK_8X8), plane);
4166     if (output_enabled)
4167       sum_intra_stats(td->counts, mi);
4168     vp9_tokenize_sb(cpi, td, t, !output_enabled, MAX(bsize, BLOCK_8X8));
4169   } else {
4170     int ref;
4171     const int is_compound = has_second_ref(mbmi);
4172     set_ref_ptrs(cm, xd, mbmi->ref_frame[0], mbmi->ref_frame[1]);
4173     for (ref = 0; ref < 1 + is_compound; ++ref) {
4174       YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi,
4175                                                      mbmi->ref_frame[ref]);
4176       assert(cfg != NULL);
4177       vp9_setup_pre_planes(xd, ref, cfg, mi_row, mi_col,
4178                            &xd->block_refs[ref]->sf);
4179     }
4180     if (!(cpi->sf.reuse_inter_pred_sby && ctx->pred_pixel_ready) || seg_skip)
4181       vp9_build_inter_predictors_sby(xd, mi_row, mi_col, MAX(bsize, BLOCK_8X8));
4182 
4183     vp9_build_inter_predictors_sbuv(xd, mi_row, mi_col, MAX(bsize, BLOCK_8X8));
4184 
4185     vp9_encode_sb(x, MAX(bsize, BLOCK_8X8));
4186     vp9_tokenize_sb(cpi, td, t, !output_enabled, MAX(bsize, BLOCK_8X8));
4187   }
4188 
4189   if (output_enabled) {
4190     if (cm->tx_mode == TX_MODE_SELECT &&
4191         mbmi->sb_type >= BLOCK_8X8  &&
4192         !(is_inter_block(mbmi) && (mbmi->skip || seg_skip))) {
4193       ++get_tx_counts(max_txsize_lookup[bsize], get_tx_size_context(xd),
4194                       &td->counts->tx)[mbmi->tx_size];
4195     } else {
4196       int x, y;
4197       TX_SIZE tx_size;
4198       // The new intra coding scheme requires no change of transform size
4199       if (is_inter_block(&mi->mbmi)) {
4200         tx_size = MIN(tx_mode_to_biggest_tx_size[cm->tx_mode],
4201                       max_txsize_lookup[bsize]);
4202       } else {
4203         tx_size = (bsize >= BLOCK_8X8) ? mbmi->tx_size : TX_4X4;
4204       }
4205 
4206       for (y = 0; y < mi_height; y++)
4207         for (x = 0; x < mi_width; x++)
4208           if (mi_col + x < cm->mi_cols && mi_row + y < cm->mi_rows)
4209             mi_8x8[mis * y + x]->mbmi.tx_size = tx_size;
4210     }
4211     ++td->counts->tx.tx_totals[mbmi->tx_size];
4212     ++td->counts->tx.tx_totals[get_uv_tx_size(mbmi, &xd->plane[1])];
4213   }
4214 }
4215