Coverage Report

Created: 2026-07-16 07:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libvpx/vp9/encoder/vp9_encodeframe.c
Line
Count
Source
1
/*
2
 *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3
 *
4
 *  Use of this source code is governed by a BSD-style license
5
 *  that can be found in the LICENSE file in the root of the source
6
 *  tree. An additional intellectual property rights grant can be found
7
 *  in the file PATENTS.  All contributing project authors may
8
 *  be found in the AUTHORS file in the root of the source tree.
9
 */
10
11
#include <float.h>
12
#include <limits.h>
13
#include <math.h>
14
#include <stdio.h>
15
16
#include "./vp9_rtcd.h"
17
#include "./vpx_dsp_rtcd.h"
18
#include "./vpx_config.h"
19
20
#include "vpx_dsp/vpx_dsp_common.h"
21
#include "vpx_ports/mem.h"
22
#include "vpx_ports/vpx_timer.h"
23
#include "vpx_ports/system_state.h"
24
#include "vpx_util/vpx_pthread.h"
25
#if CONFIG_MISMATCH_DEBUG
26
#include "vpx_util/vpx_debug_util.h"
27
#endif  // CONFIG_MISMATCH_DEBUG
28
29
#include "vp9/common/vp9_common.h"
30
#include "vp9/common/vp9_entropy.h"
31
#include "vp9/common/vp9_entropymode.h"
32
#include "vp9/common/vp9_idct.h"
33
#include "vp9/common/vp9_mvref_common.h"
34
#include "vp9/common/vp9_pred_common.h"
35
#include "vp9/common/vp9_quant_common.h"
36
#include "vp9/common/vp9_reconintra.h"
37
#include "vp9/common/vp9_reconinter.h"
38
#include "vp9/common/vp9_seg_common.h"
39
#include "vp9/common/vp9_tile_common.h"
40
#if !CONFIG_REALTIME_ONLY
41
#include "vp9/encoder/vp9_aq_360.h"
42
#include "vp9/encoder/vp9_aq_complexity.h"
43
#endif
44
#include "vp9/encoder/vp9_aq_cyclicrefresh.h"
45
#if !CONFIG_REALTIME_ONLY
46
#include "vp9/encoder/vp9_aq_variance.h"
47
#endif
48
#include "vp9/encoder/vp9_encodeframe.h"
49
#include "vp9/encoder/vp9_encodemb.h"
50
#include "vp9/encoder/vp9_encodemv.h"
51
#include "vp9/encoder/vp9_encoder.h"
52
#include "vp9/encoder/vp9_ethread.h"
53
#include "vp9/encoder/vp9_extend.h"
54
#include "vp9/encoder/vp9_multi_thread.h"
55
#include "vp9/encoder/vp9_partition_models.h"
56
#include "vp9/encoder/vp9_pickmode.h"
57
#include "vp9/encoder/vp9_rd.h"
58
#include "vp9/encoder/vp9_rdopt.h"
59
#include "vp9/encoder/vp9_segmentation.h"
60
#include "vp9/encoder/vp9_tokenize.h"
61
62
static void encode_superblock(VP9_COMP *cpi, ThreadData *td, TOKENEXTRA **t,
63
                              int output_enabled, int mi_row, int mi_col,
64
                              BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx);
65
66
// This is used as a reference when computing the source variance for the
67
//  purpose of activity masking.
68
// Eventually this should be replaced by custom no-reference routines,
69
//  which will be faster.
70
static const uint8_t VP9_VAR_OFFS[64] = {
71
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
72
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
73
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
74
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
75
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128
76
};
77
78
#if CONFIG_VP9_HIGHBITDEPTH
79
static const uint16_t VP9_HIGH_VAR_OFFS_8[64] = {
80
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
81
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
82
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
83
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
84
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128
85
};
86
87
static const uint16_t VP9_HIGH_VAR_OFFS_10[64] = {
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
  128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
91
  128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
92
  128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
93
  128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
94
  128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4,
95
  128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4
96
};
97
98
static const uint16_t VP9_HIGH_VAR_OFFS_12[64] = {
99
  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,
101
  128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
102
  128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
103
  128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
104
  128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
105
  128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
106
  128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
107
  128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16,
108
  128 * 16
109
};
110
#endif  // CONFIG_VP9_HIGHBITDEPTH
111
112
unsigned int vp9_get_sby_variance(VP9_COMP *cpi, const struct buf_2d *ref,
113
6.44M
                                  BLOCK_SIZE bs) {
114
6.44M
  unsigned int sse;
115
6.44M
  const unsigned int var =
116
6.44M
      cpi->fn_ptr[bs].vf(ref->buf, ref->stride, VP9_VAR_OFFS, 0, &sse);
117
6.44M
  return var;
118
6.44M
}
119
120
#if CONFIG_VP9_HIGHBITDEPTH
121
unsigned int vp9_high_get_sby_variance(VP9_COMP *cpi, const struct buf_2d *ref,
122
0
                                       BLOCK_SIZE bs, int bd) {
123
0
  unsigned int var, sse;
124
0
  switch (bd) {
125
0
    case 10:
126
0
      var =
127
0
          cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
128
0
                             CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10), 0, &sse);
129
0
      break;
130
0
    case 12:
131
0
      var =
132
0
          cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
133
0
                             CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12), 0, &sse);
134
0
      break;
135
0
    case 8:
136
0
    default:
137
0
      var =
138
0
          cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
139
0
                             CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8), 0, &sse);
140
0
      break;
141
0
  }
142
0
  return var;
143
0
}
144
#endif  // CONFIG_VP9_HIGHBITDEPTH
145
146
unsigned int vp9_get_sby_perpixel_variance(VP9_COMP *cpi,
147
                                           const struct buf_2d *ref,
148
6.44M
                                           BLOCK_SIZE bs) {
149
6.44M
  return ROUND_POWER_OF_TWO(vp9_get_sby_variance(cpi, ref, bs),
150
6.44M
                            num_pels_log2_lookup[bs]);
151
6.44M
}
152
153
#if CONFIG_VP9_HIGHBITDEPTH
154
unsigned int vp9_high_get_sby_perpixel_variance(VP9_COMP *cpi,
155
                                                const struct buf_2d *ref,
156
0
                                                BLOCK_SIZE bs, int bd) {
157
0
  return (unsigned int)ROUND64_POWER_OF_TWO(
158
0
      (int64_t)vp9_high_get_sby_variance(cpi, ref, bs, bd),
159
0
      num_pels_log2_lookup[bs]);
160
0
}
161
#endif  // CONFIG_VP9_HIGHBITDEPTH
162
163
static void set_segment_index(VP9_COMP *cpi, MACROBLOCK *const x, int mi_row,
164
10.5M
                              int mi_col, BLOCK_SIZE bsize, int segment_index) {
165
10.5M
  VP9_COMMON *const cm = &cpi->common;
166
10.5M
  const struct segmentation *const seg = &cm->seg;
167
10.5M
  MACROBLOCKD *const xd = &x->e_mbd;
168
10.5M
  MODE_INFO *mi = xd->mi[0];
169
170
10.5M
  const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
171
10.5M
  const uint8_t *const map =
172
10.5M
      seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
173
174
  // Initialize the segmentation index as 0.
175
10.5M
  mi->segment_id = 0;
176
177
  // Skip the rest if AQ mode is disabled.
178
10.5M
  if (!seg->enabled) return;
179
180
0
  switch (aq_mode) {
181
0
    case CYCLIC_REFRESH_AQ:
182
0
      mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
183
0
      break;
184
0
#if !CONFIG_REALTIME_ONLY
185
0
    case VARIANCE_AQ:
186
0
      if (cm->frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame ||
187
0
          cpi->force_update_segmentation ||
188
0
          (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref)) {
189
0
        int min_energy;
190
0
        int max_energy;
191
        // Get sub block energy range
192
0
        if (bsize >= BLOCK_32X32) {
193
0
          vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
194
0
                                   &max_energy);
195
0
        } else {
196
0
          min_energy = bsize <= BLOCK_16X16 ? x->mb_energy
197
0
                                            : vp9_block_energy(cpi, x, bsize);
198
0
        }
199
0
        mi->segment_id = vp9_vaq_segment_id(min_energy);
200
0
      } else {
201
0
        mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
202
0
      }
203
0
      break;
204
0
    case EQUATOR360_AQ:
205
0
      if (cm->frame_type == KEY_FRAME || cpi->force_update_segmentation)
206
0
        mi->segment_id = vp9_360aq_segment_id(mi_row, cm->mi_rows);
207
0
      else
208
0
        mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
209
0
      break;
210
0
#endif
211
0
    case LOOKAHEAD_AQ:
212
0
      mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
213
0
      break;
214
0
    case PSNR_AQ: mi->segment_id = segment_index; break;
215
0
    case PERCEPTUAL_AQ: mi->segment_id = x->segment_id; break;
216
0
    default:
217
      // NO_AQ or PSNR_AQ
218
0
      break;
219
0
  }
220
221
  // Set segment index if ROI map or active_map is enabled.
222
0
  if (cpi->roi.enabled || cpi->active_map.enabled)
223
0
    mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
224
225
0
  vp9_init_plane_quantizers(cpi, x);
226
0
}
227
228
// Lighter version of set_offsets that only sets the mode info
229
// pointers.
230
static INLINE void set_mode_info_offsets(VP9_COMMON *const cm,
231
                                         MACROBLOCK *const x,
232
                                         MACROBLOCKD *const xd, int mi_row,
233
28.1M
                                         int mi_col) {
234
28.1M
  const int idx_str = xd->mi_stride * mi_row + mi_col;
235
28.1M
  xd->mi = cm->mi_grid_visible + idx_str;
236
28.1M
  xd->mi[0] = cm->mi + idx_str;
237
28.1M
  x->mbmi_ext = x->mbmi_ext_base + (mi_row * cm->mi_cols + mi_col);
238
28.1M
}
239
240
static void set_ssim_rdmult(VP9_COMP *const cpi, MACROBLOCK *const x,
241
                            const BLOCK_SIZE bsize, const int mi_row,
242
0
                            const int mi_col, int *const rdmult) {
243
0
  const VP9_COMMON *const cm = &cpi->common;
244
245
0
  const int bsize_base = BLOCK_16X16;
246
0
  const int num_8x8_w = num_8x8_blocks_wide_lookup[bsize_base];
247
0
  const int num_8x8_h = num_8x8_blocks_high_lookup[bsize_base];
248
0
  const int num_cols = (cm->mi_cols + num_8x8_w - 1) / num_8x8_w;
249
0
  const int num_rows = (cm->mi_rows + num_8x8_h - 1) / num_8x8_h;
250
0
  const int num_bcols =
251
0
      (num_8x8_blocks_wide_lookup[bsize] + num_8x8_w - 1) / num_8x8_w;
252
0
  const int num_brows =
253
0
      (num_8x8_blocks_high_lookup[bsize] + num_8x8_h - 1) / num_8x8_h;
254
0
  int row, col;
255
0
  double num_of_mi = 0.0;
256
0
  double geom_mean_of_scale = 0.0;
257
258
0
  assert(cpi->oxcf.tuning == VP8_TUNE_SSIM);
259
260
0
  for (row = mi_row / num_8x8_w;
261
0
       row < num_rows && row < mi_row / num_8x8_w + num_brows; ++row) {
262
0
    for (col = mi_col / num_8x8_h;
263
0
         col < num_cols && col < mi_col / num_8x8_h + num_bcols; ++col) {
264
0
      const int index = row * num_cols + col;
265
0
      geom_mean_of_scale += log(cpi->mi_ssim_rdmult_scaling_factors[index]);
266
0
      num_of_mi += 1.0;
267
0
    }
268
0
  }
269
0
  geom_mean_of_scale = exp(geom_mean_of_scale / num_of_mi);
270
271
0
  *rdmult = (int)((double)(*rdmult) * geom_mean_of_scale);
272
0
  *rdmult = VPXMAX(*rdmult, 0);
273
0
  set_error_per_bit(x, *rdmult);
274
0
  vpx_clear_system_state();
275
0
}
276
277
static void set_offsets(VP9_COMP *cpi, const TileInfo *const tile,
278
                        MACROBLOCK *const x, int mi_row, int mi_col,
279
20.5M
                        BLOCK_SIZE bsize) {
280
20.5M
  VP9_COMMON *const cm = &cpi->common;
281
20.5M
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
282
20.5M
  MACROBLOCKD *const xd = &x->e_mbd;
283
20.5M
  const int mi_width = num_8x8_blocks_wide_lookup[bsize];
284
20.5M
  const int mi_height = num_8x8_blocks_high_lookup[bsize];
285
20.5M
  MvLimits *const mv_limits = &x->mv_limits;
286
287
20.5M
  set_skip_context(xd, mi_row, mi_col);
288
289
20.5M
  set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
290
291
  // Set up destination pointers.
292
20.5M
  vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
293
294
  // Set up limit values for MV components.
295
  // Mv beyond the range do not produce new/different prediction block.
296
20.5M
  mv_limits->row_min = -(((mi_row + mi_height) * MI_SIZE) + VP9_INTERP_EXTEND);
297
20.5M
  mv_limits->col_min = -(((mi_col + mi_width) * MI_SIZE) + VP9_INTERP_EXTEND);
298
20.5M
  mv_limits->row_max = (cm->mi_rows - mi_row) * MI_SIZE + VP9_INTERP_EXTEND;
299
20.5M
  mv_limits->col_max = (cm->mi_cols - mi_col) * MI_SIZE + VP9_INTERP_EXTEND;
300
301
  // Set up distance of MB to edge of frame in 1/8th pel units.
302
20.5M
  assert(!(mi_col & (mi_width - 1)) && !(mi_row & (mi_height - 1)));
303
20.5M
  set_mi_row_col(xd, tile, mi_row, mi_height, mi_col, mi_width, cm->mi_rows,
304
20.5M
                 cm->mi_cols);
305
306
  // Set up source buffers.
307
20.5M
  vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
308
309
  // R/D setup.
310
20.5M
  x->rddiv = cpi->rd.RDDIV;
311
20.5M
  x->rdmult = cpi->rd.RDMULT;
312
20.5M
  if (oxcf->tuning == VP8_TUNE_SSIM) {
313
0
    set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &x->rdmult);
314
0
  }
315
316
  // required by vp9_append_sub8x8_mvs_for_idx() and vp9_find_best_ref_mvs()
317
20.5M
  xd->tile = *tile;
318
20.5M
}
319
320
static void duplicate_mode_info_in_sb(VP9_COMMON *cm, MACROBLOCKD *xd,
321
                                      int mi_row, int mi_col,
322
8.90M
                                      BLOCK_SIZE bsize) {
323
8.90M
  const int block_width =
324
8.90M
      VPXMIN(num_8x8_blocks_wide_lookup[bsize], cm->mi_cols - mi_col);
325
8.90M
  const int block_height =
326
8.90M
      VPXMIN(num_8x8_blocks_high_lookup[bsize], cm->mi_rows - mi_row);
327
8.90M
  const int mi_stride = xd->mi_stride;
328
8.90M
  MODE_INFO *const src_mi = xd->mi[0];
329
8.90M
  int i, j;
330
331
19.5M
  for (j = 0; j < block_height; ++j)
332
25.7M
    for (i = 0; i < block_width; ++i) xd->mi[j * mi_stride + i] = src_mi;
333
8.90M
}
334
335
static void set_block_size(VP9_COMP *const cpi, MACROBLOCK *const x,
336
                           MACROBLOCKD *const xd, int mi_row, int mi_col,
337
12.4M
                           BLOCK_SIZE bsize) {
338
12.4M
  if (cpi->common.mi_cols > mi_col && cpi->common.mi_rows > mi_row) {
339
2.61M
    set_mode_info_offsets(&cpi->common, x, xd, mi_row, mi_col);
340
2.61M
    xd->mi[0]->sb_type = bsize;
341
2.61M
  }
342
12.4M
}
343
344
typedef struct {
345
  // This struct is used for computing variance in choose_partitioning(), where
346
  // the max number of samples within a superblock is 16x16 (with 4x4 avg). Even
347
  // in high bitdepth, uint32_t is enough for sum_square_error (2^12 * 2^12 * 16
348
  // * 16 = 2^32).
349
  uint32_t sum_square_error;
350
  int32_t sum_error;
351
  int log2_count;
352
  int variance;
353
} Var;
354
355
typedef struct {
356
  Var none;
357
  Var horz[2];
358
  Var vert[2];
359
} partition_variance;
360
361
typedef struct {
362
  partition_variance part_variances;
363
  Var split[4];
364
} v4x4;
365
366
typedef struct {
367
  partition_variance part_variances;
368
  v4x4 split[4];
369
} v8x8;
370
371
typedef struct {
372
  partition_variance part_variances;
373
  v8x8 split[4];
374
} v16x16;
375
376
typedef struct {
377
  partition_variance part_variances;
378
  v16x16 split[4];
379
} v32x32;
380
381
typedef struct {
382
  partition_variance part_variances;
383
  v32x32 split[4];
384
} v64x64;
385
386
typedef struct {
387
  partition_variance *part_variances;
388
  Var *split[4];
389
} variance_node;
390
391
typedef enum {
392
  V16X16,
393
  V32X32,
394
  V64X64,
395
} TREE_LEVEL;
396
397
14.3M
static void tree_to_node(void *data, BLOCK_SIZE bsize, variance_node *node) {
398
14.3M
  int i;
399
14.3M
  node->part_variances = NULL;
400
14.3M
  switch (bsize) {
401
56.8k
    case BLOCK_64X64: {
402
56.8k
      v64x64 *vt = (v64x64 *)data;
403
56.8k
      node->part_variances = &vt->part_variances;
404
284k
      for (i = 0; i < 4; i++)
405
227k
        node->split[i] = &vt->split[i].part_variances.none;
406
56.8k
      break;
407
0
    }
408
1.91M
    case BLOCK_32X32: {
409
1.91M
      v32x32 *vt = (v32x32 *)data;
410
1.91M
      node->part_variances = &vt->part_variances;
411
9.55M
      for (i = 0; i < 4; i++)
412
7.64M
        node->split[i] = &vt->split[i].part_variances.none;
413
1.91M
      break;
414
0
    }
415
7.72M
    case BLOCK_16X16: {
416
7.72M
      v16x16 *vt = (v16x16 *)data;
417
7.72M
      node->part_variances = &vt->part_variances;
418
38.6M
      for (i = 0; i < 4; i++)
419
30.8M
        node->split[i] = &vt->split[i].part_variances.none;
420
7.72M
      break;
421
0
    }
422
4.69M
    case BLOCK_8X8: {
423
4.69M
      v8x8 *vt = (v8x8 *)data;
424
4.69M
      node->part_variances = &vt->part_variances;
425
23.4M
      for (i = 0; i < 4; i++)
426
18.7M
        node->split[i] = &vt->split[i].part_variances.none;
427
4.69M
      break;
428
0
    }
429
0
    default: {
430
0
      v4x4 *vt = (v4x4 *)data;
431
0
      assert(bsize == BLOCK_4X4);
432
0
      node->part_variances = &vt->part_variances;
433
0
      for (i = 0; i < 4; i++) node->split[i] = &vt->split[i];
434
0
      break;
435
0
    }
436
14.3M
  }
437
14.3M
}
438
439
// Set variance values given sum square error, sum error, count.
440
76.6M
static void fill_variance(uint32_t s2, int32_t s, int c, Var *v) {
441
76.6M
  v->sum_square_error = s2;
442
76.6M
  v->sum_error = s;
443
76.6M
  v->log2_count = c;
444
76.6M
}
445
446
6.54M
static void get_variance(Var *v) {
447
6.54M
  v->variance =
448
6.54M
      (int)(256 * (v->sum_square_error -
449
6.54M
                   (uint32_t)(((int64_t)v->sum_error * v->sum_error) >>
450
6.54M
                              v->log2_count)) >>
451
6.54M
            v->log2_count);
452
6.54M
}
453
454
46.9M
static void sum_2_variances(const Var *a, const Var *b, Var *r) {
455
46.9M
  assert(a->log2_count == b->log2_count);
456
46.9M
  fill_variance(a->sum_square_error + b->sum_square_error,
457
46.9M
                a->sum_error + b->sum_error, a->log2_count + 1, r);
458
46.9M
}
459
460
9.39M
static void fill_variance_tree(void *data, BLOCK_SIZE bsize) {
461
9.39M
  variance_node node;
462
9.39M
  memset(&node, 0, sizeof(node));
463
9.39M
  tree_to_node(data, bsize, &node);
464
9.39M
  sum_2_variances(node.split[0], node.split[1], &node.part_variances->horz[0]);
465
9.39M
  sum_2_variances(node.split[2], node.split[3], &node.part_variances->horz[1]);
466
9.39M
  sum_2_variances(node.split[0], node.split[2], &node.part_variances->vert[0]);
467
9.39M
  sum_2_variances(node.split[1], node.split[3], &node.part_variances->vert[1]);
468
9.39M
  sum_2_variances(&node.part_variances->vert[0], &node.part_variances->vert[1],
469
9.39M
                  &node.part_variances->none);
470
9.39M
}
471
472
static int set_vt_partitioning(VP9_COMP *cpi, MACROBLOCK *const x,
473
                               MACROBLOCKD *const xd, void *data,
474
                               BLOCK_SIZE bsize, int mi_row, int mi_col,
475
                               int64_t threshold, BLOCK_SIZE bsize_min,
476
4.98M
                               int force_split) {
477
4.98M
  VP9_COMMON *const cm = &cpi->common;
478
4.98M
  variance_node vt;
479
4.98M
  const int block_width = num_8x8_blocks_wide_lookup[bsize];
480
4.98M
  const int block_height = num_8x8_blocks_high_lookup[bsize];
481
482
4.98M
  assert(block_height == block_width);
483
4.98M
  tree_to_node(data, bsize, &vt);
484
485
4.98M
  if (force_split == 1) return 0;
486
487
  // For bsize=bsize_min (16x16/8x8 for 8x8/4x4 downsampling), select if
488
  // variance is below threshold, otherwise split will be selected.
489
  // No check for vert/horiz split as too few samples for variance.
490
3.97M
  if (bsize == bsize_min) {
491
    // Variance already computed to set the force_split.
492
3.18M
    if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
493
3.18M
    if (mi_col + block_width / 2 < cm->mi_cols &&
494
774k
        mi_row + block_height / 2 < cm->mi_rows &&
495
422k
        vt.part_variances->none.variance < threshold) {
496
265k
      set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
497
265k
      return 1;
498
265k
    }
499
2.92M
    return 0;
500
3.18M
  } else if (bsize > bsize_min) {
501
    // Variance already computed to set the force_split.
502
783k
    if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
503
    // For key frame: take split for bsize above 32X32 or very high variance.
504
783k
    if (frame_is_intra_only(cm) &&
505
239k
        (bsize > BLOCK_32X32 ||
506
239k
         vt.part_variances->none.variance > (threshold << 4))) {
507
0
      return 0;
508
0
    }
509
    // If variance is low, take the bsize (no split).
510
783k
    if (mi_col + block_width / 2 < cm->mi_cols &&
511
171k
        mi_row + block_height / 2 < cm->mi_rows &&
512
49.1k
        vt.part_variances->none.variance < threshold) {
513
48.9k
      set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
514
48.9k
      return 1;
515
48.9k
    }
516
517
    // Check vertical split.
518
734k
    if (mi_row + block_height / 2 < cm->mi_rows) {
519
42.6k
      BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_VERT);
520
42.6k
      get_variance(&vt.part_variances->vert[0]);
521
42.6k
      get_variance(&vt.part_variances->vert[1]);
522
42.6k
      if (vt.part_variances->vert[0].variance < threshold &&
523
42.1k
          vt.part_variances->vert[1].variance < threshold &&
524
42.0k
          get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
525
42.0k
        set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
526
42.0k
        set_block_size(cpi, x, xd, mi_row, mi_col + block_width / 2, subsize);
527
42.0k
        return 1;
528
42.0k
      }
529
42.6k
    }
530
    // Check horizontal split.
531
692k
    if (mi_col + block_width / 2 < cm->mi_cols) {
532
122k
      BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_HORZ);
533
122k
      get_variance(&vt.part_variances->horz[0]);
534
122k
      get_variance(&vt.part_variances->horz[1]);
535
122k
      if (vt.part_variances->horz[0].variance < threshold &&
536
119k
          vt.part_variances->horz[1].variance < threshold &&
537
118k
          get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
538
118k
        set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
539
118k
        set_block_size(cpi, x, xd, mi_row + block_height / 2, mi_col, subsize);
540
118k
        return 1;
541
118k
      }
542
122k
    }
543
544
573k
    return 0;
545
692k
  }
546
0
  return 0;
547
3.97M
}
548
549
static int64_t scale_part_thresh_sumdiff(int64_t threshold_base, int speed,
550
                                         int width, int height,
551
458k
                                         int content_state) {
552
458k
  if (speed >= 8) {
553
0
    if (width <= 640 && height <= 480)
554
0
      return (5 * threshold_base) >> 2;
555
0
    else if ((content_state == kLowSadLowSumdiff) ||
556
0
             (content_state == kHighSadLowSumdiff) ||
557
0
             (content_state == kLowVarHighSumdiff))
558
0
      return (5 * threshold_base) >> 2;
559
458k
  } else if (speed == 7) {
560
0
    if ((content_state == kLowSadLowSumdiff) ||
561
0
        (content_state == kHighSadLowSumdiff) ||
562
0
        (content_state == kLowVarHighSumdiff)) {
563
0
      return (5 * threshold_base) >> 2;
564
0
    }
565
0
  }
566
458k
  return threshold_base;
567
458k
}
568
569
// Set the variance split thresholds for following the block sizes:
570
// 0 - threshold_64x64, 1 - threshold_32x32, 2 - threshold_16x16,
571
// 3 - vbp_threshold_8x8. vbp_threshold_8x8 (to split to 4x4 partition) is
572
// currently only used on key frame.
573
static void set_vbp_thresholds(VP9_COMP *cpi, int64_t thresholds[], int q,
574
495k
                               int content_state) {
575
495k
  VP9_COMMON *const cm = &cpi->common;
576
495k
  const int is_key_frame = frame_is_intra_only(cm);
577
495k
  const int threshold_multiplier =
578
495k
      is_key_frame ? 20 : cpi->sf.variance_part_thresh_mult;
579
495k
  int64_t threshold_base =
580
495k
      (int64_t)(threshold_multiplier * cpi->y_dequant[q][1]);
581
582
495k
  if (is_key_frame) {
583
37.6k
    thresholds[0] = threshold_base;
584
37.6k
    thresholds[1] = threshold_base >> 2;
585
37.6k
    thresholds[2] = threshold_base >> 2;
586
37.6k
    thresholds[3] = threshold_base << 2;
587
458k
  } else {
588
    // Increase base variance threshold based on estimated noise level.
589
458k
    if (cpi->noise_estimate.enabled && cm->width >= 640 && cm->height >= 480) {
590
0
      NOISE_LEVEL noise_level =
591
0
          vp9_noise_estimate_extract_level(&cpi->noise_estimate);
592
0
      if (noise_level == kHigh)
593
0
        threshold_base = 3 * threshold_base;
594
0
      else if (noise_level == kMedium)
595
0
        threshold_base = threshold_base << 1;
596
0
      else if (noise_level < kLow)
597
0
        threshold_base = (7 * threshold_base) >> 3;
598
0
    }
599
#if CONFIG_VP9_TEMPORAL_DENOISING
600
    if (cpi->oxcf.noise_sensitivity > 0 && denoise_svc(cpi) &&
601
        cpi->oxcf.speed > 5 && cpi->denoiser.denoising_level >= kDenLow)
602
      threshold_base =
603
          vp9_scale_part_thresh(threshold_base, cpi->denoiser.denoising_level,
604
                                content_state, cpi->svc.temporal_layer_id);
605
    else
606
      threshold_base =
607
          scale_part_thresh_sumdiff(threshold_base, cpi->oxcf.speed, cm->width,
608
                                    cm->height, content_state);
609
#else
610
    // Increase base variance threshold based on content_state/sum_diff level.
611
458k
    threshold_base = scale_part_thresh_sumdiff(
612
458k
        threshold_base, cpi->oxcf.speed, cm->width, cm->height, content_state);
613
458k
#endif
614
458k
    thresholds[0] = threshold_base;
615
458k
    thresholds[2] = threshold_base << cpi->oxcf.speed;
616
458k
    if (cm->width >= 1280 && cm->height >= 720 && cpi->oxcf.speed < 7)
617
0
      thresholds[2] = thresholds[2] << 1;
618
458k
    if (cm->width <= 352 && cm->height <= 288) {
619
458k
      thresholds[0] = threshold_base >> 3;
620
458k
      thresholds[1] = threshold_base >> 1;
621
458k
      thresholds[2] = threshold_base << 3;
622
458k
      if (cpi->rc.avg_frame_qindex[INTER_FRAME] > 220)
623
29.2k
        thresholds[2] = thresholds[2] << 2;
624
428k
      else if (cpi->rc.avg_frame_qindex[INTER_FRAME] > 200)
625
18.7k
        thresholds[2] = thresholds[2] << 1;
626
458k
    } else if (cm->width < 1280 && cm->height < 720) {
627
0
      thresholds[1] = (5 * threshold_base) >> 2;
628
0
    } else if (cm->width < 1920 && cm->height < 1080) {
629
0
      thresholds[1] = threshold_base << 1;
630
0
    } else {
631
0
      thresholds[1] = (5 * threshold_base) >> 1;
632
0
    }
633
458k
    if (cpi->sf.disable_16x16part_nonkey) thresholds[2] = INT64_MAX;
634
458k
  }
635
495k
}
636
637
void vp9_set_variance_partition_thresholds(VP9_COMP *cpi, int q,
638
452k
                                           int content_state) {
639
452k
  VP9_COMMON *const cm = &cpi->common;
640
452k
  SPEED_FEATURES *const sf = &cpi->sf;
641
452k
  const int is_key_frame = frame_is_intra_only(cm);
642
452k
  if (sf->partition_search_type != VAR_BASED_PARTITION &&
643
452k
      sf->partition_search_type != REFERENCE_PARTITION) {
644
204k
    return;
645
247k
  } else {
646
247k
    set_vbp_thresholds(cpi, cpi->vbp_thresholds, q, content_state);
647
    // The thresholds below are not changed locally.
648
247k
    if (is_key_frame) {
649
18.8k
      cpi->vbp_threshold_sad = 0;
650
18.8k
      cpi->vbp_threshold_copy = 0;
651
18.8k
      cpi->vbp_bsize_min = BLOCK_8X8;
652
229k
    } else {
653
229k
      if (cm->width <= 352 && cm->height <= 288)
654
229k
        cpi->vbp_threshold_sad = 10;
655
0
      else
656
0
        cpi->vbp_threshold_sad = (cpi->y_dequant[q][1] << 1) > 1000
657
0
                                     ? (cpi->y_dequant[q][1] << 1)
658
0
                                     : 1000;
659
229k
      cpi->vbp_bsize_min = BLOCK_16X16;
660
229k
      if (cm->width <= 352 && cm->height <= 288)
661
229k
        cpi->vbp_threshold_copy = 4000;
662
0
      else if (cm->width <= 640 && cm->height <= 360)
663
0
        cpi->vbp_threshold_copy = 8000;
664
0
      else
665
0
        cpi->vbp_threshold_copy = (cpi->y_dequant[q][1] << 3) > 8000
666
0
                                      ? (cpi->y_dequant[q][1] << 3)
667
0
                                      : 8000;
668
229k
      if (cpi->rc.high_source_sad ||
669
229k
          (cpi->use_svc && cpi->svc.high_source_sad_superframe)) {
670
0
        cpi->vbp_threshold_sad = 0;
671
0
        cpi->vbp_threshold_copy = 0;
672
0
      }
673
229k
    }
674
247k
    cpi->vbp_threshold_minmax = 15 + (q >> 3);
675
247k
  }
676
452k
}
677
678
// Compute the minmax over the 8x8 subblocks.
679
static int compute_minmax_8x8(const uint8_t *s, int sp, const uint8_t *d,
680
                              int dp, int x16_idx, int y16_idx,
681
#if CONFIG_VP9_HIGHBITDEPTH
682
                              int highbd_flag,
683
#endif
684
252k
                              int pixels_wide, int pixels_high) {
685
252k
  int k;
686
252k
  int minmax_max = 0;
687
252k
  int minmax_min = 255;
688
  // Loop over the 4 8x8 subblocks.
689
1.26M
  for (k = 0; k < 4; k++) {
690
1.01M
    int x8_idx = x16_idx + ((k & 1) << 3);
691
1.01M
    int y8_idx = y16_idx + ((k >> 1) << 3);
692
1.01M
    int min = 0;
693
1.01M
    int max = 0;
694
1.01M
    if (x8_idx < pixels_wide && y8_idx < pixels_high) {
695
940k
#if CONFIG_VP9_HIGHBITDEPTH
696
940k
      if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
697
0
        vpx_highbd_minmax_8x8(s + y8_idx * sp + x8_idx, sp,
698
0
                              d + y8_idx * dp + x8_idx, dp, &min, &max);
699
940k
      } else {
700
940k
        vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx,
701
940k
                       dp, &min, &max);
702
940k
      }
703
#else
704
      vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx, dp,
705
                     &min, &max);
706
#endif
707
940k
      if ((max - min) > minmax_max) minmax_max = (max - min);
708
940k
      if ((max - min) < minmax_min) minmax_min = (max - min);
709
940k
    }
710
1.01M
  }
711
252k
  return (minmax_max - minmax_min);
712
252k
}
713
714
static void fill_variance_4x4avg(const uint8_t *s, int sp, const uint8_t *d,
715
                                 int dp, int x8_idx, int y8_idx, v8x8 *vst,
716
#if CONFIG_VP9_HIGHBITDEPTH
717
                                 int highbd_flag,
718
#endif
719
                                 int pixels_wide, int pixels_high,
720
3.88M
                                 int is_key_frame) {
721
3.88M
  int k;
722
19.4M
  for (k = 0; k < 4; k++) {
723
15.5M
    int x4_idx = x8_idx + ((k & 1) << 2);
724
15.5M
    int y4_idx = y8_idx + ((k >> 1) << 2);
725
15.5M
    unsigned int sse = 0;
726
15.5M
    int sum = 0;
727
15.5M
    if (x4_idx < pixels_wide && y4_idx < pixels_high) {
728
10.6M
      int s_avg;
729
10.6M
      int d_avg = 128;
730
10.6M
#if CONFIG_VP9_HIGHBITDEPTH
731
10.6M
      if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
732
0
        s_avg = vpx_highbd_avg_4x4(s + y4_idx * sp + x4_idx, sp);
733
0
        if (!is_key_frame)
734
0
          d_avg = vpx_highbd_avg_4x4(d + y4_idx * dp + x4_idx, dp);
735
10.6M
      } else {
736
10.6M
        s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
737
10.6M
        if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
738
10.6M
      }
739
#else
740
      s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
741
      if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
742
#endif
743
10.6M
      sum = s_avg - d_avg;
744
10.6M
      sse = sum * sum;
745
10.6M
    }
746
15.5M
    fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
747
15.5M
  }
748
3.88M
}
749
750
static void fill_variance_8x8avg(const uint8_t *s, int sp, const uint8_t *d,
751
                                 int dp, int x16_idx, int y16_idx, v16x16 *vst,
752
#if CONFIG_VP9_HIGHBITDEPTH
753
                                 int highbd_flag,
754
#endif
755
                                 int pixels_wide, int pixels_high,
756
3.52M
                                 int is_key_frame) {
757
3.52M
  int k;
758
17.6M
  for (k = 0; k < 4; k++) {
759
14.0M
    int x8_idx = x16_idx + ((k & 1) << 3);
760
14.0M
    int y8_idx = y16_idx + ((k >> 1) << 3);
761
14.0M
    unsigned int sse = 0;
762
14.0M
    int sum = 0;
763
14.0M
    if (x8_idx < pixels_wide && y8_idx < pixels_high) {
764
3.63M
      int s_avg;
765
3.63M
      int d_avg = 128;
766
3.63M
#if CONFIG_VP9_HIGHBITDEPTH
767
3.63M
      if (highbd_flag & YV12_FLAG_HIGHBITDEPTH) {
768
0
        s_avg = vpx_highbd_avg_8x8(s + y8_idx * sp + x8_idx, sp);
769
0
        if (!is_key_frame)
770
0
          d_avg = vpx_highbd_avg_8x8(d + y8_idx * dp + x8_idx, dp);
771
3.63M
      } else {
772
3.63M
        s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
773
3.63M
        if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
774
3.63M
      }
775
#else
776
      s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
777
      if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
778
#endif
779
3.63M
      sum = s_avg - d_avg;
780
3.63M
      sse = sum * sum;
781
3.63M
    }
782
14.0M
    fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
783
14.0M
  }
784
3.52M
}
785
786
// Check if most of the superblock is skin content, and if so, force split to
787
// 32x32, and set x->sb_is_skin for use in mode selection.
788
static int skin_sb_split(VP9_COMP *cpi, const int low_res, int mi_row,
789
0
                         int mi_col, int *force_split) {
790
0
  VP9_COMMON *const cm = &cpi->common;
791
0
#if CONFIG_VP9_HIGHBITDEPTH
792
0
  if (cm->use_highbitdepth) return 0;
793
0
#endif
794
  // Avoid checking superblocks on/near boundary and avoid low resolutions.
795
  // Note superblock may still pick 64X64 if y_sad is very small
796
  // (i.e., y_sad < cpi->vbp_threshold_sad) below. For now leave this as is.
797
0
  if (!low_res && (mi_col >= 8 && mi_col + 8 < cm->mi_cols && mi_row >= 8 &&
798
0
                   mi_row + 8 < cm->mi_rows)) {
799
0
    int num_16x16_skin = 0;
800
0
    int num_16x16_nonskin = 0;
801
0
    const int block_index = mi_row * cm->mi_cols + mi_col;
802
0
    const int bw = num_8x8_blocks_wide_lookup[BLOCK_64X64];
803
0
    const int bh = num_8x8_blocks_high_lookup[BLOCK_64X64];
804
0
    const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
805
0
    const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
806
    // Loop through the 16x16 sub-blocks.
807
0
    int i, j;
808
0
    for (i = 0; i < ymis; i += 2) {
809
0
      for (j = 0; j < xmis; j += 2) {
810
0
        int bl_index = block_index + i * cm->mi_cols + j;
811
0
        int is_skin = cpi->skin_map[bl_index];
812
0
        num_16x16_skin += is_skin;
813
0
        num_16x16_nonskin += (1 - is_skin);
814
0
        if (num_16x16_nonskin > 3) {
815
          // Exit loop if at least 4 of the 16x16 blocks are not skin.
816
0
          i = ymis;
817
0
          break;
818
0
        }
819
0
      }
820
0
    }
821
0
    if (num_16x16_skin > 12) {
822
0
      *force_split = 1;
823
0
      return 1;
824
0
    }
825
0
  }
826
0
  return 0;
827
0
}
828
829
static void set_low_temp_var_flag(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
830
                                  v64x64 *vt, int64_t thresholds[],
831
                                  MV_REFERENCE_FRAME ref_frame_partition,
832
0
                                  int mi_col, int mi_row) {
833
0
  int i, j;
834
0
  VP9_COMMON *const cm = &cpi->common;
835
0
  const int mv_thr = cm->width > 640 ? 8 : 4;
836
  // Check temporal variance for bsize >= 16x16, if LAST_FRAME was selected and
837
  // int_pro mv is small. If the temporal variance is small set the flag
838
  // variance_low for the block. The variance threshold can be adjusted, the
839
  // higher the more aggressive.
840
0
  if (ref_frame_partition == LAST_FRAME &&
841
0
      (cpi->sf.short_circuit_low_temp_var == 1 ||
842
0
       (xd->mi[0]->mv[0].as_mv.col < mv_thr &&
843
0
        xd->mi[0]->mv[0].as_mv.col > -mv_thr &&
844
0
        xd->mi[0]->mv[0].as_mv.row < mv_thr &&
845
0
        xd->mi[0]->mv[0].as_mv.row > -mv_thr))) {
846
0
    if (xd->mi[0]->sb_type == BLOCK_64X64) {
847
0
      if ((vt->part_variances).none.variance < (thresholds[0] >> 1))
848
0
        x->variance_low[0] = 1;
849
0
    } else if (xd->mi[0]->sb_type == BLOCK_64X32) {
850
0
      for (i = 0; i < 2; i++) {
851
0
        if (vt->part_variances.horz[i].variance < (thresholds[0] >> 2))
852
0
          x->variance_low[i + 1] = 1;
853
0
      }
854
0
    } else if (xd->mi[0]->sb_type == BLOCK_32X64) {
855
0
      for (i = 0; i < 2; i++) {
856
0
        if (vt->part_variances.vert[i].variance < (thresholds[0] >> 2))
857
0
          x->variance_low[i + 3] = 1;
858
0
      }
859
0
    } else {
860
0
      for (i = 0; i < 4; i++) {
861
0
        const int idx[4][2] = { { 0, 0 }, { 0, 4 }, { 4, 0 }, { 4, 4 } };
862
0
        const int idx_str =
863
0
            cm->mi_stride * (mi_row + idx[i][0]) + mi_col + idx[i][1];
864
0
        MODE_INFO **this_mi = cm->mi_grid_visible + idx_str;
865
866
0
        if (cm->mi_cols <= mi_col + idx[i][1] ||
867
0
            cm->mi_rows <= mi_row + idx[i][0])
868
0
          continue;
869
870
0
        if ((*this_mi)->sb_type == BLOCK_32X32) {
871
0
          int64_t threshold_32x32 = (cpi->sf.short_circuit_low_temp_var == 1 ||
872
0
                                     cpi->sf.short_circuit_low_temp_var == 3)
873
0
                                        ? ((5 * thresholds[1]) >> 3)
874
0
                                        : (thresholds[1] >> 1);
875
0
          if (vt->split[i].part_variances.none.variance < threshold_32x32)
876
0
            x->variance_low[i + 5] = 1;
877
0
        } else if (cpi->sf.short_circuit_low_temp_var >= 2) {
878
          // For 32x16 and 16x32 blocks, the flag is set on each 16x16 block
879
          // inside.
880
0
          if ((*this_mi)->sb_type == BLOCK_16X16 ||
881
0
              (*this_mi)->sb_type == BLOCK_32X16 ||
882
0
              (*this_mi)->sb_type == BLOCK_16X32) {
883
0
            for (j = 0; j < 4; j++) {
884
0
              if (vt->split[i].split[j].part_variances.none.variance <
885
0
                  (thresholds[2] >> 8))
886
0
                x->variance_low[(i << 2) + j + 9] = 1;
887
0
            }
888
0
          }
889
0
        }
890
0
      }
891
0
    }
892
0
  }
893
0
}
894
895
static void copy_partitioning_helper(VP9_COMP *cpi, MACROBLOCK *x,
896
                                     MACROBLOCKD *xd, BLOCK_SIZE bsize,
897
0
                                     int mi_row, int mi_col) {
898
0
  VP9_COMMON *const cm = &cpi->common;
899
0
  BLOCK_SIZE *prev_part = cpi->prev_partition;
900
0
  int start_pos = mi_row * cm->mi_stride + mi_col;
901
902
0
  const int bsl = b_width_log2_lookup[bsize];
903
0
  const int bs = (1 << bsl) >> 2;
904
0
  BLOCK_SIZE subsize;
905
0
  PARTITION_TYPE partition;
906
907
0
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
908
909
0
  partition = partition_lookup[bsl][prev_part[start_pos]];
910
0
  subsize = get_subsize(bsize, partition);
911
912
0
  if (subsize < BLOCK_8X8) {
913
0
    set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
914
0
  } else {
915
0
    switch (partition) {
916
0
      case PARTITION_NONE:
917
0
        set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
918
0
        break;
919
0
      case PARTITION_HORZ:
920
0
        set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
921
0
        set_block_size(cpi, x, xd, mi_row + bs, mi_col, subsize);
922
0
        break;
923
0
      case PARTITION_VERT:
924
0
        set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
925
0
        set_block_size(cpi, x, xd, mi_row, mi_col + bs, subsize);
926
0
        break;
927
0
      default:
928
0
        assert(partition == PARTITION_SPLIT);
929
0
        copy_partitioning_helper(cpi, x, xd, subsize, mi_row, mi_col);
930
0
        copy_partitioning_helper(cpi, x, xd, subsize, mi_row + bs, mi_col);
931
0
        copy_partitioning_helper(cpi, x, xd, subsize, mi_row, mi_col + bs);
932
0
        copy_partitioning_helper(cpi, x, xd, subsize, mi_row + bs, mi_col + bs);
933
0
        break;
934
0
    }
935
0
  }
936
0
}
937
938
static int copy_partitioning(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
939
                             int mi_row, int mi_col, int segment_id,
940
0
                             int sb_offset) {
941
0
  int svc_copy_allowed = 1;
942
0
  int frames_since_key_thresh = 1;
943
0
  if (cpi->use_svc) {
944
    // For SVC, don't allow copy if base spatial layer is key frame, or if
945
    // frame is not a temporal enhancement layer frame.
946
0
    int layer = LAYER_IDS_TO_IDX(0, cpi->svc.temporal_layer_id,
947
0
                                 cpi->svc.number_temporal_layers);
948
0
    const LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
949
0
    if (lc->is_key_frame || !cpi->svc.non_reference_frame) svc_copy_allowed = 0;
950
0
    frames_since_key_thresh = cpi->svc.number_spatial_layers << 1;
951
0
  }
952
0
  if (cpi->rc.frames_since_key > frames_since_key_thresh && svc_copy_allowed &&
953
0
      !cpi->resize_pending && segment_id == CR_SEGMENT_ID_BASE &&
954
0
      cpi->prev_segment_id[sb_offset] == CR_SEGMENT_ID_BASE &&
955
0
      cpi->copied_frame_cnt[sb_offset] < cpi->max_copied_frame) {
956
0
    if (cpi->prev_partition != NULL) {
957
0
      copy_partitioning_helper(cpi, x, xd, BLOCK_64X64, mi_row, mi_col);
958
0
      cpi->copied_frame_cnt[sb_offset] += 1;
959
0
      memcpy(x->variance_low, &(cpi->prev_variance_low[sb_offset * 25]),
960
0
             sizeof(x->variance_low));
961
0
      return 1;
962
0
    }
963
0
  }
964
965
0
  return 0;
966
0
}
967
968
// Set the partition for mi_col/row_high (current resolution) based on
969
// the previous spatial layer (mi_col/row). Returns 0 if partition is set,
970
// returns 1 if no scale partitioning is done. Return 1 means the variance
971
// partitioning will be used.
972
static int scale_partitioning_svc(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
973
                                  BLOCK_SIZE bsize, int mi_row, int mi_col,
974
0
                                  int mi_row_high, int mi_col_high) {
975
0
  VP9_COMMON *const cm = &cpi->common;
976
0
  SVC *const svc = &cpi->svc;
977
0
  BLOCK_SIZE *prev_part = svc->prev_partition_svc;
978
  // Variables with _high are for higher resolution.
979
0
  int bsize_high = 0;
980
0
  int subsize_high = 0;
981
0
  const int bsl = b_width_log2_lookup[bsize];
982
0
  const int bs = (1 << bsl) >> 2;
983
0
  const int has_rows = (mi_row_high + bs) < cm->mi_rows;
984
0
  const int has_cols = (mi_col_high + bs) < cm->mi_cols;
985
986
0
  int start_pos;
987
0
  BLOCK_SIZE bsize_low;
988
0
  PARTITION_TYPE partition_high;
989
990
  // If the lower layer frame is outside the boundary (this can happen for
991
  // odd size resolutions) then do not scale partitioning from the lower
992
  // layer. Do variance based partitioning instead (return 1).
993
0
  if (mi_row >= svc->mi_rows[svc->spatial_layer_id - 1] ||
994
0
      mi_col >= svc->mi_cols[svc->spatial_layer_id - 1])
995
0
    return 1;
996
997
  // Do not scale partitioning from lower layers on the boundary. Do
998
  // variance based partitioning instead (return 1).
999
0
  if (!has_rows || !has_cols) return 1;
1000
1001
  // Find corresponding (mi_col/mi_row) block down-scaled by 2x2.
1002
0
  start_pos = mi_row * (svc->mi_stride[svc->spatial_layer_id - 1]) + mi_col;
1003
0
  bsize_low = prev_part[start_pos];
1004
1005
  // For reference frames: return 1 (do variance-based partitioning) if the
1006
  // superblock is not low source sad and lower-resoln bsize is below 32x32.
1007
0
  if (!cpi->svc.non_reference_frame && !x->skip_low_source_sad &&
1008
0
      bsize_low < BLOCK_32X32)
1009
0
    return 1;
1010
1011
  // Scale up block size by 2x2. Force 64x64 for size larger than 32x32.
1012
0
  if (bsize_low < BLOCK_32X32) {
1013
0
    bsize_high = bsize_low + 3;
1014
0
  } else if (bsize_low >= BLOCK_32X32) {
1015
0
    bsize_high = BLOCK_64X64;
1016
0
  }
1017
1018
0
  partition_high = partition_lookup[bsl][bsize_high];
1019
0
  subsize_high = get_subsize(bsize, partition_high);
1020
1021
0
  if (subsize_high < BLOCK_8X8) {
1022
0
    set_block_size(cpi, x, xd, mi_row_high, mi_col_high, bsize_high);
1023
0
  } else {
1024
0
    switch (partition_high) {
1025
0
      case PARTITION_NONE:
1026
0
        set_block_size(cpi, x, xd, mi_row_high, mi_col_high, bsize_high);
1027
0
        break;
1028
0
      case PARTITION_HORZ:
1029
0
        set_block_size(cpi, x, xd, mi_row_high, mi_col_high, subsize_high);
1030
0
        if (subsize_high < BLOCK_64X64)
1031
0
          set_block_size(cpi, x, xd, mi_row_high + bs, mi_col_high,
1032
0
                         subsize_high);
1033
0
        break;
1034
0
      case PARTITION_VERT:
1035
0
        set_block_size(cpi, x, xd, mi_row_high, mi_col_high, subsize_high);
1036
0
        if (subsize_high < BLOCK_64X64)
1037
0
          set_block_size(cpi, x, xd, mi_row_high, mi_col_high + bs,
1038
0
                         subsize_high);
1039
0
        break;
1040
0
      default:
1041
0
        assert(partition_high == PARTITION_SPLIT);
1042
0
        if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row, mi_col,
1043
0
                                   mi_row_high, mi_col_high))
1044
0
          return 1;
1045
0
        if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row + (bs >> 1),
1046
0
                                   mi_col, mi_row_high + bs, mi_col_high))
1047
0
          return 1;
1048
0
        if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row,
1049
0
                                   mi_col + (bs >> 1), mi_row_high,
1050
0
                                   mi_col_high + bs))
1051
0
          return 1;
1052
0
        if (scale_partitioning_svc(cpi, x, xd, subsize_high, mi_row + (bs >> 1),
1053
0
                                   mi_col + (bs >> 1), mi_row_high + bs,
1054
0
                                   mi_col_high + bs))
1055
0
          return 1;
1056
0
        break;
1057
0
    }
1058
0
  }
1059
1060
0
  return 0;
1061
0
}
1062
1063
static void update_partition_svc(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
1064
0
                                 int mi_col) {
1065
0
  VP9_COMMON *const cm = &cpi->common;
1066
0
  BLOCK_SIZE *prev_part = cpi->svc.prev_partition_svc;
1067
0
  int start_pos = mi_row * cm->mi_stride + mi_col;
1068
0
  const int bsl = b_width_log2_lookup[bsize];
1069
0
  const int bs = (1 << bsl) >> 2;
1070
0
  BLOCK_SIZE subsize;
1071
0
  PARTITION_TYPE partition;
1072
0
  const MODE_INFO *mi = NULL;
1073
0
  int xx, yy;
1074
1075
0
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1076
1077
0
  mi = cm->mi_grid_visible[start_pos];
1078
0
  partition = partition_lookup[bsl][mi->sb_type];
1079
0
  subsize = get_subsize(bsize, partition);
1080
0
  if (subsize < BLOCK_8X8) {
1081
0
    prev_part[start_pos] = bsize;
1082
0
  } else {
1083
0
    switch (partition) {
1084
0
      case PARTITION_NONE:
1085
0
        prev_part[start_pos] = bsize;
1086
0
        if (bsize == BLOCK_64X64) {
1087
0
          for (xx = 0; xx < 8; xx += 4)
1088
0
            for (yy = 0; yy < 8; yy += 4) {
1089
0
              if ((mi_row + xx < cm->mi_rows) && (mi_col + yy < cm->mi_cols))
1090
0
                prev_part[start_pos + xx * cm->mi_stride + yy] = bsize;
1091
0
            }
1092
0
        }
1093
0
        break;
1094
0
      case PARTITION_HORZ:
1095
0
        prev_part[start_pos] = subsize;
1096
0
        if (mi_row + bs < cm->mi_rows)
1097
0
          prev_part[start_pos + bs * cm->mi_stride] = subsize;
1098
0
        break;
1099
0
      case PARTITION_VERT:
1100
0
        prev_part[start_pos] = subsize;
1101
0
        if (mi_col + bs < cm->mi_cols) prev_part[start_pos + bs] = subsize;
1102
0
        break;
1103
0
      default:
1104
0
        assert(partition == PARTITION_SPLIT);
1105
0
        update_partition_svc(cpi, subsize, mi_row, mi_col);
1106
0
        update_partition_svc(cpi, subsize, mi_row + bs, mi_col);
1107
0
        update_partition_svc(cpi, subsize, mi_row, mi_col + bs);
1108
0
        update_partition_svc(cpi, subsize, mi_row + bs, mi_col + bs);
1109
0
        break;
1110
0
    }
1111
0
  }
1112
0
}
1113
1114
static void update_prev_partition_helper(VP9_COMP *cpi, BLOCK_SIZE bsize,
1115
0
                                         int mi_row, int mi_col) {
1116
0
  VP9_COMMON *const cm = &cpi->common;
1117
0
  BLOCK_SIZE *prev_part = cpi->prev_partition;
1118
0
  int start_pos = mi_row * cm->mi_stride + mi_col;
1119
0
  const int bsl = b_width_log2_lookup[bsize];
1120
0
  const int bs = (1 << bsl) >> 2;
1121
0
  BLOCK_SIZE subsize;
1122
0
  PARTITION_TYPE partition;
1123
0
  const MODE_INFO *mi = NULL;
1124
1125
0
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
1126
1127
0
  mi = cm->mi_grid_visible[start_pos];
1128
0
  partition = partition_lookup[bsl][mi->sb_type];
1129
0
  subsize = get_subsize(bsize, partition);
1130
0
  if (subsize < BLOCK_8X8) {
1131
0
    prev_part[start_pos] = bsize;
1132
0
  } else {
1133
0
    switch (partition) {
1134
0
      case PARTITION_NONE: prev_part[start_pos] = bsize; break;
1135
0
      case PARTITION_HORZ:
1136
0
        prev_part[start_pos] = subsize;
1137
0
        if (mi_row + bs < cm->mi_rows)
1138
0
          prev_part[start_pos + bs * cm->mi_stride] = subsize;
1139
0
        break;
1140
0
      case PARTITION_VERT:
1141
0
        prev_part[start_pos] = subsize;
1142
0
        if (mi_col + bs < cm->mi_cols) prev_part[start_pos + bs] = subsize;
1143
0
        break;
1144
0
      default:
1145
0
        assert(partition == PARTITION_SPLIT);
1146
0
        update_prev_partition_helper(cpi, subsize, mi_row, mi_col);
1147
0
        update_prev_partition_helper(cpi, subsize, mi_row + bs, mi_col);
1148
0
        update_prev_partition_helper(cpi, subsize, mi_row, mi_col + bs);
1149
0
        update_prev_partition_helper(cpi, subsize, mi_row + bs, mi_col + bs);
1150
0
        break;
1151
0
    }
1152
0
  }
1153
0
}
1154
1155
static void update_prev_partition(VP9_COMP *cpi, MACROBLOCK *x, int segment_id,
1156
0
                                  int mi_row, int mi_col, int sb_offset) {
1157
0
  update_prev_partition_helper(cpi, BLOCK_64X64, mi_row, mi_col);
1158
0
  cpi->prev_segment_id[sb_offset] = segment_id;
1159
0
  memcpy(&(cpi->prev_variance_low[sb_offset * 25]), x->variance_low,
1160
0
         sizeof(x->variance_low));
1161
  // Reset the counter for copy partitioning
1162
0
  cpi->copied_frame_cnt[sb_offset] = 0;
1163
0
}
1164
1165
static void chroma_check(VP9_COMP *cpi, MACROBLOCK *x, int bsize,
1166
                         unsigned int y_sad, int is_key_frame,
1167
247k
                         int scene_change_detected) {
1168
247k
  int i;
1169
247k
  MACROBLOCKD *xd = &x->e_mbd;
1170
247k
  int shift = 2;
1171
1172
247k
  if (is_key_frame) return;
1173
1174
  // For speed > 8, avoid the chroma check if y_sad is above threshold.
1175
229k
  if (cpi->oxcf.speed > 8) {
1176
0
    if (y_sad > cpi->vbp_thresholds[1] &&
1177
0
        (!cpi->noise_estimate.enabled ||
1178
0
         vp9_noise_estimate_extract_level(&cpi->noise_estimate) < kMedium))
1179
0
      return;
1180
0
  }
1181
1182
229k
  if (cpi->oxcf.content == VP9E_CONTENT_SCREEN && scene_change_detected)
1183
0
    shift = 5;
1184
1185
687k
  for (i = 1; i <= 2; ++i) {
1186
458k
    unsigned int uv_sad = UINT_MAX;
1187
458k
    struct macroblock_plane *p = &x->plane[i];
1188
458k
    struct macroblockd_plane *pd = &xd->plane[i];
1189
458k
    const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
1190
1191
458k
    if (bs != BLOCK_INVALID)
1192
458k
      uv_sad = cpi->fn_ptr[bs].sdf(p->src.buf, p->src.stride, pd->dst.buf,
1193
458k
                                   pd->dst.stride);
1194
1195
    // TODO(marpan): Investigate if we should lower this threshold if
1196
    // superblock is detected as skin.
1197
458k
    x->color_sensitivity[i - 1] = uv_sad > (y_sad >> shift);
1198
458k
  }
1199
229k
}
1200
1201
static uint64_t avg_source_sad(VP9_COMP *cpi, MACROBLOCK *x, int shift,
1202
254k
                               int sb_offset) {
1203
254k
  unsigned int tmp_sse;
1204
254k
  uint64_t tmp_sad;
1205
254k
  unsigned int tmp_variance;
1206
254k
  const BLOCK_SIZE bsize = BLOCK_64X64;
1207
254k
  uint8_t *src_y = cpi->Source->y_buffer;
1208
254k
  int src_ystride = cpi->Source->y_stride;
1209
254k
  uint8_t *last_src_y = cpi->Last_Source->y_buffer;
1210
254k
  int last_src_ystride = cpi->Last_Source->y_stride;
1211
254k
  uint64_t avg_source_sad_threshold = 10000;
1212
254k
  uint64_t avg_source_sad_threshold2 = 12000;
1213
254k
#if CONFIG_VP9_HIGHBITDEPTH
1214
254k
  if (cpi->common.use_highbitdepth) return 0;
1215
254k
#endif
1216
254k
  src_y += shift;
1217
254k
  last_src_y += shift;
1218
254k
  tmp_sad =
1219
254k
      cpi->fn_ptr[bsize].sdf(src_y, src_ystride, last_src_y, last_src_ystride);
1220
254k
  tmp_variance = vpx_variance64x64(src_y, src_ystride, last_src_y,
1221
254k
                                   last_src_ystride, &tmp_sse);
1222
  // Note: tmp_sse - tmp_variance = ((sum * sum) >> 12)
1223
254k
  if (tmp_sad < avg_source_sad_threshold)
1224
87.1k
    x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kLowSadLowSumdiff
1225
87.1k
                                                          : kLowSadHighSumdiff;
1226
166k
  else
1227
166k
    x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kHighSadLowSumdiff
1228
166k
                                                          : kHighSadHighSumdiff;
1229
1230
  // Detect large lighting change.
1231
254k
  if (cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
1232
254k
      cpi->oxcf.rc_mode == VPX_CBR && tmp_variance < (tmp_sse >> 3) &&
1233
0
      (tmp_sse - tmp_variance) > 10000)
1234
0
    x->content_state_sb = kLowVarHighSumdiff;
1235
254k
  else if (tmp_sad > (avg_source_sad_threshold << 1))
1236
150k
    x->content_state_sb = kVeryHighSad;
1237
1238
254k
  if (cpi->content_state_sb_fd != NULL) {
1239
0
    if (tmp_sad < avg_source_sad_threshold2) {
1240
      // Cap the increment to 255.
1241
0
      if (cpi->content_state_sb_fd[sb_offset] < 255)
1242
0
        cpi->content_state_sb_fd[sb_offset]++;
1243
0
    } else {
1244
0
      cpi->content_state_sb_fd[sb_offset] = 0;
1245
0
    }
1246
0
  }
1247
254k
  if (tmp_sad == 0) x->zero_temp_sad_source = 1;
1248
254k
  return tmp_sad;
1249
254k
}
1250
1251
// This function chooses partitioning based on the variance between source and
1252
// reconstructed last, where variance is computed for down-sampled inputs.
1253
static int choose_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
1254
247k
                               MACROBLOCK *x, int mi_row, int mi_col) {
1255
247k
  VP9_COMMON *const cm = &cpi->common;
1256
247k
  MACROBLOCKD *xd = &x->e_mbd;
1257
247k
  int i, j, k, m;
1258
247k
  v64x64 vt;
1259
247k
  v16x16 *vt2 = NULL;
1260
247k
  int force_split[21];
1261
247k
  int avg_32x32;
1262
247k
  int max_var_32x32 = 0;
1263
247k
  int min_var_32x32 = INT_MAX;
1264
247k
  int var_32x32;
1265
247k
  int avg_16x16[4];
1266
247k
  int maxvar_16x16[4];
1267
247k
  int minvar_16x16[4];
1268
247k
  int64_t threshold_4x4avg;
1269
247k
  NOISE_LEVEL noise_level = kLow;
1270
247k
  int content_state = 0;
1271
247k
  uint8_t *s;
1272
247k
  const uint8_t *d;
1273
247k
  int sp;
1274
247k
  int dp;
1275
247k
  int compute_minmax_variance = 1;
1276
247k
  unsigned int y_sad = UINT_MAX;
1277
247k
  BLOCK_SIZE bsize = BLOCK_64X64;
1278
  // Ref frame used in partitioning.
1279
247k
  MV_REFERENCE_FRAME ref_frame_partition = LAST_FRAME;
1280
247k
  int pixels_wide = 64, pixels_high = 64;
1281
247k
  int64_t thresholds[4] = { cpi->vbp_thresholds[0], cpi->vbp_thresholds[1],
1282
247k
                            cpi->vbp_thresholds[2], cpi->vbp_thresholds[3] };
1283
247k
  int scene_change_detected =
1284
247k
      cpi->rc.high_source_sad ||
1285
247k
      (cpi->use_svc && cpi->svc.high_source_sad_superframe);
1286
247k
  int force_64_split = scene_change_detected ||
1287
247k
                       (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1288
0
                        cpi->compute_source_sad_onepass &&
1289
0
                        cpi->sf.use_source_sad && !x->zero_temp_sad_source);
1290
1291
  // For the variance computation under SVC mode, we treat the frame as key if
1292
  // the reference (base layer frame) is key frame (i.e., is_key_frame == 1).
1293
247k
  int is_key_frame =
1294
247k
      (frame_is_intra_only(cm) ||
1295
229k
       (is_one_pass_svc(cpi) &&
1296
0
        cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame));
1297
1298
247k
  if (!is_key_frame) {
1299
229k
    if (cm->frame_refs[LAST_FRAME - 1].sf.x_scale_fp == REF_INVALID_SCALE ||
1300
229k
        cm->frame_refs[LAST_FRAME - 1].sf.y_scale_fp == REF_INVALID_SCALE)
1301
0
      is_key_frame = 1;
1302
229k
  }
1303
1304
  // Allow for sub8x8 (4x4) partition on key frames, but only for hybrid mode
1305
  // (i.e., sf->nonrd_keyframe = 0), where for small blocks rd intra pickmode
1306
  // (vp9_rd_pick_intra_mode_sb) is used. The nonrd intra pickmode
1307
  // (vp9_pick_intra_mode) does not currently support sub8x8 blocks. This causes
1308
  // the issue: 44166813. Assert is added in vp9_pick_intra_mode to check this.
1309
247k
  const int use_4x4_partition =
1310
247k
      frame_is_intra_only(cm) && !cpi->sf.nonrd_keyframe;
1311
247k
  const int low_res = (cm->width <= 352 && cm->height <= 288);
1312
247k
  int variance4x4downsample[16];
1313
247k
  int segment_id;
1314
247k
  int sb_offset = (cm->mi_stride >> 3) * (mi_row >> 3) + (mi_col >> 3);
1315
1316
  // For SVC: check if LAST frame is NULL or if the resolution of LAST is
1317
  // different than the current frame resolution, and if so, treat this frame
1318
  // as a key frame, for the purpose of the superblock partitioning.
1319
  // LAST == NULL can happen in some cases where enhancement spatial layers are
1320
  // enabled dyanmically in the stream and the only reference is the spatial
1321
  // reference (GOLDEN).
1322
247k
  if (cpi->use_svc) {
1323
0
    const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi, LAST_FRAME);
1324
0
    if (ref == NULL || ref->y_crop_height != cm->height ||
1325
0
        ref->y_crop_width != cm->width)
1326
0
      is_key_frame = 1;
1327
0
  }
1328
1329
247k
  set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
1330
247k
  set_segment_index(cpi, x, mi_row, mi_col, BLOCK_64X64, 0);
1331
247k
  segment_id = xd->mi[0]->segment_id;
1332
1333
247k
  if (cpi->oxcf.speed >= 8 || (cpi->use_svc && cpi->svc.non_reference_frame))
1334
0
    compute_minmax_variance = 0;
1335
1336
247k
  memset(x->variance_low, 0, sizeof(x->variance_low));
1337
1338
247k
  if (cpi->sf.use_source_sad && !is_key_frame) {
1339
229k
    int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
1340
229k
    content_state = x->content_state_sb;
1341
229k
    x->skip_low_source_sad = (content_state == kLowSadLowSumdiff ||
1342
169k
                              content_state == kLowSadHighSumdiff)
1343
229k
                                 ? 1
1344
229k
                                 : 0;
1345
229k
    x->lowvar_highsumdiff = (content_state == kLowVarHighSumdiff) ? 1 : 0;
1346
229k
    if (cpi->content_state_sb_fd != NULL)
1347
0
      x->last_sb_high_content = cpi->content_state_sb_fd[sb_offset2];
1348
1349
    // For SVC on top spatial layer: use/scale the partition from
1350
    // the lower spatial resolution if svc_use_lowres_part is enabled.
1351
229k
    if (cpi->sf.svc_use_lowres_part &&
1352
0
        cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1 &&
1353
0
        cpi->svc.prev_partition_svc != NULL && content_state != kVeryHighSad) {
1354
0
      if (!scale_partitioning_svc(cpi, x, xd, BLOCK_64X64, mi_row >> 1,
1355
0
                                  mi_col >> 1, mi_row, mi_col)) {
1356
0
        if (cpi->sf.copy_partition_flag) {
1357
0
          update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1358
0
        }
1359
0
        return 0;
1360
0
      }
1361
0
    }
1362
    // If source_sad is low copy the partition without computing the y_sad.
1363
229k
    if (x->skip_low_source_sad && cpi->sf.copy_partition_flag &&
1364
0
        !force_64_split &&
1365
0
        copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1366
0
      x->sb_use_mv_part = 1;
1367
0
      if (cpi->sf.svc_use_lowres_part &&
1368
0
          cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1369
0
        update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1370
0
      return 0;
1371
0
    }
1372
229k
  }
1373
1374
247k
  if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled &&
1375
0
      cyclic_refresh_segment_id_boosted(segment_id)) {
1376
0
    int q = vp9_get_qindex(&cm->seg, segment_id, cm->base_qindex);
1377
0
    set_vbp_thresholds(cpi, thresholds, q, content_state);
1378
247k
  } else {
1379
247k
    set_vbp_thresholds(cpi, thresholds, cm->base_qindex, content_state);
1380
247k
  }
1381
  // Decrease 32x32 split threshold for screen on base layer, for scene
1382
  // change/high motion frames.
1383
247k
  if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1384
0
      cpi->svc.spatial_layer_id == 0 && force_64_split)
1385
0
    thresholds[1] = 3 * thresholds[1] >> 2;
1386
1387
  // For non keyframes, disable 4x4 average for low resolution when speed = 8
1388
247k
  threshold_4x4avg = (cpi->oxcf.speed < 8) ? thresholds[1] << 1 : INT64_MAX;
1389
1390
247k
  if (xd->mb_to_right_edge < 0) pixels_wide += (xd->mb_to_right_edge >> 3);
1391
247k
  if (xd->mb_to_bottom_edge < 0) pixels_high += (xd->mb_to_bottom_edge >> 3);
1392
1393
247k
  s = x->plane[0].src.buf;
1394
247k
  sp = x->plane[0].src.stride;
1395
1396
  // Index for force_split: 0 for 64x64, 1-4 for 32x32 blocks,
1397
  // 5-20 for the 16x16 blocks.
1398
247k
  force_split[0] = force_64_split;
1399
1400
247k
  if (!is_key_frame) {
1401
    // In the case of spatial/temporal scalable coding, the assumption here is
1402
    // that the temporal reference frame will always be of type LAST_FRAME.
1403
    // TODO(marpan): If that assumption is broken, we need to revisit this code.
1404
229k
    MODE_INFO *mi = xd->mi[0];
1405
229k
    YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
1406
1407
229k
    const YV12_BUFFER_CONFIG *yv12_g = NULL;
1408
229k
    unsigned int y_sad_g, y_sad_thr, y_sad_last;
1409
229k
    bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
1410
229k
            (mi_row + 4 < cm->mi_rows);
1411
1412
229k
    assert(yv12 != NULL);
1413
1414
229k
    if (!(is_one_pass_svc(cpi) && cpi->svc.spatial_layer_id) ||
1415
229k
        cpi->svc.use_gf_temporal_ref_current_layer) {
1416
      // For now, GOLDEN will not be used for non-zero spatial layers, since
1417
      // it may not be a temporal reference.
1418
229k
      yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
1419
229k
    }
1420
1421
    // Only compute y_sad_g (sad for golden reference) for speed < 8.
1422
229k
    if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
1423
198k
        (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
1424
198k
      vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1425
198k
                           &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1426
198k
      y_sad_g = cpi->fn_ptr[bsize].sdf(
1427
198k
          x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1428
198k
          xd->plane[0].pre[0].stride);
1429
198k
    } else {
1430
31.0k
      y_sad_g = UINT_MAX;
1431
31.0k
    }
1432
1433
229k
    if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
1434
229k
        cpi->rc.is_src_frame_alt_ref) {
1435
0
      yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
1436
0
      vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1437
0
                           &cm->frame_refs[ALTREF_FRAME - 1].sf);
1438
0
      mi->ref_frame[0] = ALTREF_FRAME;
1439
0
      y_sad_g = UINT_MAX;
1440
229k
    } else {
1441
229k
      vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1442
229k
                           &cm->frame_refs[LAST_FRAME - 1].sf);
1443
229k
      mi->ref_frame[0] = LAST_FRAME;
1444
229k
    }
1445
229k
    mi->ref_frame[1] = NO_REF_FRAME;
1446
229k
    mi->sb_type = BLOCK_64X64;
1447
229k
    mi->mv[0].as_int = 0;
1448
229k
    mi->interp_filter = BILINEAR;
1449
1450
229k
    if (cpi->oxcf.speed >= 8 && !low_res &&
1451
0
        x->content_state_sb != kVeryHighSad) {
1452
0
      y_sad = cpi->fn_ptr[bsize].sdf(
1453
0
          x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1454
0
          xd->plane[0].pre[0].stride);
1455
229k
    } else {
1456
229k
      const MV dummy_mv = { 0, 0 };
1457
229k
      y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
1458
229k
                                            &dummy_mv);
1459
229k
      x->sb_use_mv_part = 1;
1460
229k
      x->sb_mvcol_part = mi->mv[0].as_mv.col;
1461
229k
      x->sb_mvrow_part = mi->mv[0].as_mv.row;
1462
229k
      if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1463
0
          cpi->svc.spatial_layer_id == cpi->svc.first_spatial_layer_to_encode &&
1464
0
          cpi->svc.high_num_blocks_with_motion && !x->zero_temp_sad_source &&
1465
0
          cm->width > 640 && cm->height > 480) {
1466
        // Disable split below 16x16 block size when scroll motion (horz or
1467
        // vert) is detected.
1468
        // TODO(marpan/jianj): Improve this condition: issue is that search
1469
        // range is hard-coded/limited in vp9_int_pro_motion_estimation() so
1470
        // scroll motion may not be detected here.
1471
0
        if (((abs(x->sb_mvrow_part) >= 48 && abs(x->sb_mvcol_part) <= 8) ||
1472
0
             (abs(x->sb_mvcol_part) >= 48 && abs(x->sb_mvrow_part) <= 8)) &&
1473
0
            y_sad < 100000) {
1474
0
          compute_minmax_variance = 0;
1475
0
          thresholds[2] = INT64_MAX;
1476
0
        }
1477
0
      }
1478
229k
    }
1479
1480
229k
    y_sad_last = y_sad;
1481
    // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
1482
    // are close if short_circuit_low_temp_var is on.
1483
229k
    y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
1484
229k
    if (y_sad_g < y_sad_thr) {
1485
50.9k
      vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1486
50.9k
                           &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1487
50.9k
      mi->ref_frame[0] = GOLDEN_FRAME;
1488
50.9k
      mi->mv[0].as_int = 0;
1489
50.9k
      y_sad = y_sad_g;
1490
50.9k
      ref_frame_partition = GOLDEN_FRAME;
1491
178k
    } else {
1492
178k
      x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
1493
178k
      ref_frame_partition = LAST_FRAME;
1494
178k
    }
1495
1496
229k
    set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
1497
229k
    vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
1498
1499
229k
    if (cpi->use_skin_detection)
1500
0
      x->sb_is_skin = skin_sb_split(cpi, low_res, mi_row, mi_col, force_split);
1501
1502
229k
    d = xd->plane[0].dst.buf;
1503
229k
    dp = xd->plane[0].dst.stride;
1504
1505
    // If the y_sad is very small, take 64x64 as partition and exit.
1506
    // Don't check on boosted segment for now, as 64x64 is suppressed there.
1507
229k
    if (segment_id == CR_SEGMENT_ID_BASE && y_sad < cpi->vbp_threshold_sad) {
1508
47.8k
      const int block_width = num_8x8_blocks_wide_lookup[BLOCK_64X64];
1509
47.8k
      const int block_height = num_8x8_blocks_high_lookup[BLOCK_64X64];
1510
47.8k
      if (mi_col + block_width / 2 < cm->mi_cols &&
1511
13.2k
          mi_row + block_height / 2 < cm->mi_rows) {
1512
9.09k
        set_block_size(cpi, x, xd, mi_row, mi_col, BLOCK_64X64);
1513
9.09k
        x->variance_low[0] = 1;
1514
9.09k
        chroma_check(cpi, x, bsize, y_sad, is_key_frame, scene_change_detected);
1515
9.09k
        if (cpi->sf.svc_use_lowres_part &&
1516
0
            cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1517
0
          update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1518
9.09k
        if (cpi->sf.copy_partition_flag) {
1519
0
          update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1520
0
        }
1521
9.09k
        return 0;
1522
9.09k
      }
1523
47.8k
    }
1524
1525
    // If the y_sad is small enough, copy the partition of the superblock in the
1526
    // last frame to current frame only if the last frame is not a keyframe.
1527
    // Stop the copy every cpi->max_copied_frame to refresh the partition.
1528
    // TODO(jianj) : tune the threshold.
1529
220k
    if (cpi->sf.copy_partition_flag && y_sad_last < cpi->vbp_threshold_copy &&
1530
0
        copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1531
0
      chroma_check(cpi, x, bsize, y_sad, is_key_frame, scene_change_detected);
1532
0
      if (cpi->sf.svc_use_lowres_part &&
1533
0
          cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1534
0
        update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1535
0
      return 0;
1536
0
    }
1537
220k
  } else {
1538
18.8k
    d = VP9_VAR_OFFS;
1539
18.8k
    dp = 0;
1540
18.8k
#if CONFIG_VP9_HIGHBITDEPTH
1541
18.8k
    if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1542
0
      switch (xd->bd) {
1543
0
        case 10: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10); break;
1544
0
        case 12: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12); break;
1545
0
        case 8:
1546
0
        default: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8); break;
1547
0
      }
1548
0
    }
1549
18.8k
#endif  // CONFIG_VP9_HIGHBITDEPTH
1550
18.8k
  }
1551
1552
238k
  if (low_res && threshold_4x4avg < INT64_MAX)
1553
238k
    CHECK_MEM_ERROR(&cm->error, vt2, vpx_calloc(16, sizeof(*vt2)));
1554
  // Fill in the entire tree of 8x8 (or 4x4 under some conditions) variances
1555
  // for splits.
1556
1.19M
  for (i = 0; i < 4; i++) {
1557
955k
    const int x32_idx = ((i & 1) << 5);
1558
955k
    const int y32_idx = ((i >> 1) << 5);
1559
955k
    const int i2 = i << 2;
1560
955k
    force_split[i + 1] = 0;
1561
955k
    avg_16x16[i] = 0;
1562
955k
    maxvar_16x16[i] = 0;
1563
955k
    minvar_16x16[i] = INT_MAX;
1564
4.77M
    for (j = 0; j < 4; j++) {
1565
3.82M
      const int x16_idx = x32_idx + ((j & 1) << 4);
1566
3.82M
      const int y16_idx = y32_idx + ((j >> 1) << 4);
1567
3.82M
      const int split_index = 5 + i2 + j;
1568
3.82M
      v16x16 *vst = &vt.split[i].split[j];
1569
3.82M
      force_split[split_index] = 0;
1570
3.82M
      variance4x4downsample[i2 + j] = 0;
1571
3.82M
      if (!is_key_frame) {
1572
3.52M
        fill_variance_8x8avg(s, sp, d, dp, x16_idx, y16_idx, vst,
1573
3.52M
#if CONFIG_VP9_HIGHBITDEPTH
1574
3.52M
                             xd->cur_buf->flags,
1575
3.52M
#endif
1576
3.52M
                             pixels_wide, pixels_high, is_key_frame);
1577
3.52M
        fill_variance_tree(&vt.split[i].split[j], BLOCK_16X16);
1578
3.52M
        get_variance(&vt.split[i].split[j].part_variances.none);
1579
3.52M
        avg_16x16[i] += vt.split[i].split[j].part_variances.none.variance;
1580
3.52M
        if (vt.split[i].split[j].part_variances.none.variance < minvar_16x16[i])
1581
1.24M
          minvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1582
3.52M
        if (vt.split[i].split[j].part_variances.none.variance > maxvar_16x16[i])
1583
489k
          maxvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1584
3.52M
        if (vt.split[i].split[j].part_variances.none.variance > thresholds[2]) {
1585
          // 16X16 variance is above threshold for split, so force split to 8x8
1586
          // for this 16x16 block (this also forces splits for upper levels).
1587
449k
          force_split[split_index] = 1;
1588
449k
          force_split[i + 1] = 1;
1589
449k
          force_split[0] = 1;
1590
3.07M
        } else if (compute_minmax_variance &&
1591
3.07M
                   vt.split[i].split[j].part_variances.none.variance >
1592
3.07M
                       thresholds[1] &&
1593
252k
                   !cyclic_refresh_segment_id_boosted(segment_id)) {
1594
          // We have some nominal amount of 16x16 variance (based on average),
1595
          // compute the minmax over the 8x8 sub-blocks, and if above threshold,
1596
          // force split to 8x8 block for this 16x16 block.
1597
252k
          int minmax = compute_minmax_8x8(s, sp, d, dp, x16_idx, y16_idx,
1598
252k
#if CONFIG_VP9_HIGHBITDEPTH
1599
252k
                                          xd->cur_buf->flags,
1600
252k
#endif
1601
252k
                                          pixels_wide, pixels_high);
1602
252k
          int thresh_minmax = (int)cpi->vbp_threshold_minmax;
1603
252k
          if (x->content_state_sb == kVeryHighSad)
1604
142k
            thresh_minmax = thresh_minmax << 1;
1605
252k
          if (minmax > thresh_minmax) {
1606
38.9k
            force_split[split_index] = 1;
1607
38.9k
            force_split[i + 1] = 1;
1608
38.9k
            force_split[0] = 1;
1609
38.9k
          }
1610
252k
        }
1611
3.52M
      }
1612
3.82M
      if (is_key_frame ||
1613
3.52M
          (low_res && vt.split[i].split[j].part_variances.none.variance >
1614
3.52M
                          threshold_4x4avg)) {
1615
972k
        force_split[split_index] = 0;
1616
        // Go down to 4x4 down-sampling for variance.
1617
972k
        variance4x4downsample[i2 + j] = 1;
1618
4.86M
        for (k = 0; k < 4; k++) {
1619
3.88M
          int x8_idx = x16_idx + ((k & 1) << 3);
1620
3.88M
          int y8_idx = y16_idx + ((k >> 1) << 3);
1621
3.88M
          v8x8 *vst2 = is_key_frame ? &vst->split[k] : &vt2[i2 + j].split[k];
1622
3.88M
          fill_variance_4x4avg(s, sp, d, dp, x8_idx, y8_idx, vst2,
1623
3.88M
#if CONFIG_VP9_HIGHBITDEPTH
1624
3.88M
                               xd->cur_buf->flags,
1625
3.88M
#endif
1626
3.88M
                               pixels_wide, pixels_high, is_key_frame);
1627
3.88M
        }
1628
972k
      }
1629
3.82M
    }
1630
955k
  }
1631
238k
  if (cpi->noise_estimate.enabled)
1632
0
    noise_level = vp9_noise_estimate_extract_level(&cpi->noise_estimate);
1633
  // Fill the rest of the variance tree by summing split partition values.
1634
238k
  avg_32x32 = 0;
1635
1.19M
  for (i = 0; i < 4; i++) {
1636
955k
    const int i2 = i << 2;
1637
4.77M
    for (j = 0; j < 4; j++) {
1638
3.82M
      if (variance4x4downsample[i2 + j] == 1) {
1639
972k
        v16x16 *vtemp = (!is_key_frame) ? &vt2[i2 + j] : &vt.split[i].split[j];
1640
4.86M
        for (m = 0; m < 4; m++) fill_variance_tree(&vtemp->split[m], BLOCK_8X8);
1641
972k
        fill_variance_tree(vtemp, BLOCK_16X16);
1642
        // If variance of this 16x16 block is above the threshold, force block
1643
        // to split. This also forces a split on the upper levels.
1644
972k
        get_variance(&vtemp->part_variances.none);
1645
972k
        if (vtemp->part_variances.none.variance > thresholds[2]) {
1646
640k
          force_split[5 + i2 + j] = 1;
1647
640k
          force_split[i + 1] = 1;
1648
640k
          force_split[0] = 1;
1649
640k
        }
1650
972k
      }
1651
3.82M
    }
1652
955k
    fill_variance_tree(&vt.split[i], BLOCK_32X32);
1653
    // If variance of this 32x32 block is above the threshold, or if its above
1654
    // (some threshold of) the average variance over the sub-16x16 blocks, then
1655
    // force this block to split. This also forces a split on the upper
1656
    // (64x64) level.
1657
955k
    if (!force_split[i + 1]) {
1658
626k
      get_variance(&vt.split[i].part_variances.none);
1659
626k
      var_32x32 = vt.split[i].part_variances.none.variance;
1660
626k
      max_var_32x32 = VPXMAX(var_32x32, max_var_32x32);
1661
626k
      min_var_32x32 = VPXMIN(var_32x32, min_var_32x32);
1662
626k
      if (vt.split[i].part_variances.none.variance > thresholds[1] ||
1663
583k
          (!is_key_frame &&
1664
544k
           vt.split[i].part_variances.none.variance > (thresholds[1] >> 1) &&
1665
43.6k
           vt.split[i].part_variances.none.variance > (avg_16x16[i] >> 1))) {
1666
43.6k
        force_split[i + 1] = 1;
1667
43.6k
        force_split[0] = 1;
1668
583k
      } else if (!is_key_frame && noise_level < kLow && cm->height <= 360 &&
1669
0
                 (maxvar_16x16[i] - minvar_16x16[i]) > (thresholds[1] >> 1) &&
1670
0
                 maxvar_16x16[i] > thresholds[1]) {
1671
0
        force_split[i + 1] = 1;
1672
0
        force_split[0] = 1;
1673
0
      }
1674
626k
      avg_32x32 += var_32x32;
1675
626k
    }
1676
955k
  }
1677
238k
  if (!force_split[0]) {
1678
56.8k
    fill_variance_tree(&vt, BLOCK_64X64);
1679
56.8k
    get_variance(&vt.part_variances.none);
1680
    // If variance of this 64x64 block is above (some threshold of) the average
1681
    // variance over the sub-32x32 blocks, then force this block to split.
1682
    // Only checking this for noise level >= medium for now.
1683
56.8k
    if (!is_key_frame && noise_level >= kMedium &&
1684
0
        vt.part_variances.none.variance > (9 * avg_32x32) >> 5)
1685
0
      force_split[0] = 1;
1686
    // Else if the maximum 32x32 variance minus the miniumum 32x32 variance in
1687
    // a 64x64 block is greater than threshold and the maximum 32x32 variance is
1688
    // above a miniumum threshold, then force the split of a 64x64 block
1689
    // Only check this for low noise.
1690
56.8k
    else if (!is_key_frame && noise_level < kMedium &&
1691
55.2k
             (max_var_32x32 - min_var_32x32) > 3 * (thresholds[0] >> 3) &&
1692
8.74k
             max_var_32x32 > thresholds[0] >> 1)
1693
8.44k
      force_split[0] = 1;
1694
56.8k
  }
1695
1696
  // Now go through the entire structure, splitting every block size until
1697
  // we get to one that's got a variance lower than our threshold.
1698
238k
  if (mi_col + 8 > cm->mi_cols || mi_row + 8 > cm->mi_rows ||
1699
0
      !set_vt_partitioning(cpi, x, xd, &vt, BLOCK_64X64, mi_row, mi_col,
1700
238k
                           thresholds[0], BLOCK_16X16, force_split[0])) {
1701
1.19M
    for (i = 0; i < 4; ++i) {
1702
955k
      const int x32_idx = ((i & 1) << 2);
1703
955k
      const int y32_idx = ((i >> 1) << 2);
1704
955k
      const int i2 = i << 2;
1705
955k
      if (!set_vt_partitioning(cpi, x, xd, &vt.split[i], BLOCK_32X32,
1706
955k
                               (mi_row + y32_idx), (mi_col + x32_idx),
1707
955k
                               thresholds[1], BLOCK_16X16,
1708
955k
                               force_split[i + 1])) {
1709
4.03M
        for (j = 0; j < 4; ++j) {
1710
3.23M
          const int x16_idx = ((j & 1) << 1);
1711
3.23M
          const int y16_idx = ((j >> 1) << 1);
1712
          // For inter frames: if variance4x4downsample[] == 1 for this 16x16
1713
          // block, then the variance is based on 4x4 down-sampling, so use vt2
1714
          // in set_vt_partitioning(), otherwise use vt.
1715
3.23M
          v16x16 *vtemp = (!is_key_frame && variance4x4downsample[i2 + j] == 1)
1716
3.23M
                              ? &vt2[i2 + j]
1717
3.23M
                              : &vt.split[i].split[j];
1718
3.23M
          if (!set_vt_partitioning(
1719
3.23M
                  cpi, x, xd, vtemp, BLOCK_16X16, mi_row + y32_idx + y16_idx,
1720
3.23M
                  mi_col + x32_idx + x16_idx, thresholds[2], cpi->vbp_bsize_min,
1721
3.23M
                  force_split[5 + i2 + j])) {
1722
14.8M
            for (k = 0; k < 4; ++k) {
1723
11.8M
              const int x8_idx = (k & 1);
1724
11.8M
              const int y8_idx = (k >> 1);
1725
11.8M
              if (use_4x4_partition) {
1726
801k
                if (!set_vt_partitioning(cpi, x, xd, &vtemp->split[k],
1727
801k
                                         BLOCK_8X8,
1728
801k
                                         mi_row + y32_idx + y16_idx + y8_idx,
1729
801k
                                         mi_col + x32_idx + x16_idx + x8_idx,
1730
801k
                                         thresholds[3], BLOCK_8X8, 0)) {
1731
743k
                  set_block_size(
1732
743k
                      cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1733
743k
                      (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_4X4);
1734
743k
                }
1735
11.0M
              } else {
1736
11.0M
                set_block_size(
1737
11.0M
                    cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1738
11.0M
                    (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_8X8);
1739
11.0M
              }
1740
11.8M
            }
1741
2.96M
          }
1742
3.23M
        }
1743
807k
      }
1744
955k
    }
1745
238k
  }
1746
1747
238k
  if (!frame_is_intra_only(cm) && cpi->sf.copy_partition_flag) {
1748
0
    update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1749
0
  }
1750
1751
238k
  if (!frame_is_intra_only(cm) && cpi->sf.svc_use_lowres_part &&
1752
0
      cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1753
0
    update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1754
1755
238k
  if (cpi->sf.short_circuit_low_temp_var) {
1756
0
    set_low_temp_var_flag(cpi, x, xd, &vt, thresholds, ref_frame_partition,
1757
0
                          mi_col, mi_row);
1758
0
  }
1759
1760
238k
  chroma_check(cpi, x, bsize, y_sad, is_key_frame, scene_change_detected);
1761
238k
  if (vt2) vpx_free(vt2);
1762
238k
  return 0;
1763
238k
}
1764
1765
#if !CONFIG_REALTIME_ONLY
1766
static void update_state(VP9_COMP *cpi, ThreadData *td, PICK_MODE_CONTEXT *ctx,
1767
                         int mi_row, int mi_col, BLOCK_SIZE bsize,
1768
4.90M
                         int output_enabled) {
1769
4.90M
  int i, x_idx, y;
1770
4.90M
  VP9_COMMON *const cm = &cpi->common;
1771
4.90M
  RD_COUNTS *const rdc = &td->rd_counts;
1772
4.90M
  MACROBLOCK *const x = &td->mb;
1773
4.90M
  MACROBLOCKD *const xd = &x->e_mbd;
1774
4.90M
  struct macroblock_plane *const p = x->plane;
1775
4.90M
  struct macroblockd_plane *const pd = xd->plane;
1776
4.90M
  MODE_INFO *mi = &ctx->mic;
1777
4.90M
  MODE_INFO *const xdmi = xd->mi[0];
1778
4.90M
  MODE_INFO *mi_addr = xd->mi[0];
1779
4.90M
  const struct segmentation *const seg = &cm->seg;
1780
4.90M
  const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
1781
4.90M
  const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
1782
4.90M
  const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
1783
4.90M
  const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
1784
4.90M
  MV_REF *const frame_mvs = cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
1785
4.90M
  int w, h;
1786
1787
4.90M
  const int mis = cm->mi_stride;
1788
4.90M
  const int mi_width = num_8x8_blocks_wide_lookup[bsize];
1789
4.90M
  const int mi_height = num_8x8_blocks_high_lookup[bsize];
1790
4.90M
  int max_plane;
1791
1792
4.90M
  assert(mi->sb_type == bsize);
1793
1794
4.90M
  *mi_addr = *mi;
1795
4.90M
  *x->mbmi_ext = ctx->mbmi_ext;
1796
1797
  // If segmentation in use
1798
4.90M
  if (seg->enabled) {
1799
    // For in frame complexity AQ copy the segment id from the segment map.
1800
0
    if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1801
0
      const uint8_t *const map =
1802
0
          seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1803
0
      mi_addr->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
1804
0
    }
1805
    // Else for cyclic refresh mode update the segment map, set the segment id
1806
    // and then update the quantizer.
1807
0
    if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
1808
0
        cpi->cyclic_refresh->content_mode) {
1809
0
      vp9_cyclic_refresh_update_segment(cpi, xd->mi[0], mi_row, mi_col, bsize,
1810
0
                                        ctx->rate, ctx->dist, x->skip, p);
1811
0
    }
1812
0
  }
1813
1814
4.90M
  max_plane = is_inter_block(xdmi) ? MAX_MB_PLANE : 1;
1815
15.1M
  for (i = 0; i < max_plane; ++i) {
1816
10.2M
    p[i].coeff = ctx->coeff_pbuf[i][1];
1817
10.2M
    p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
1818
10.2M
    pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
1819
10.2M
    p[i].eobs = ctx->eobs_pbuf[i][1];
1820
10.2M
  }
1821
1822
9.36M
  for (i = max_plane; i < MAX_MB_PLANE; ++i) {
1823
4.46M
    p[i].coeff = ctx->coeff_pbuf[i][2];
1824
4.46M
    p[i].qcoeff = ctx->qcoeff_pbuf[i][2];
1825
4.46M
    pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][2];
1826
4.46M
    p[i].eobs = ctx->eobs_pbuf[i][2];
1827
4.46M
  }
1828
1829
  // Restore the coding context of the MB to that that was in place
1830
  // when the mode was picked for it
1831
11.0M
  for (y = 0; y < mi_height; y++)
1832
15.5M
    for (x_idx = 0; x_idx < mi_width; x_idx++)
1833
9.47M
      if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > x_idx &&
1834
9.23M
          (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > y) {
1835
8.72M
        xd->mi[x_idx + y * mis] = mi_addr;
1836
8.72M
      }
1837
1838
4.90M
  if (cpi->oxcf.aq_mode != NO_AQ) vp9_init_plane_quantizers(cpi, x);
1839
1840
4.90M
  if (is_inter_block(xdmi) && xdmi->sb_type < BLOCK_8X8) {
1841
364k
    xdmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1842
364k
    xdmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1843
364k
  }
1844
1845
4.90M
  x->skip = ctx->skip;
1846
4.90M
  memcpy(x->zcoeff_blk[xdmi->tx_size], ctx->zcoeff_blk,
1847
4.90M
         sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
1848
1849
4.90M
  if (!output_enabled) return;
1850
1851
#if CONFIG_INTERNAL_STATS
1852
  if (frame_is_intra_only(cm)) {
1853
    static const int kf_mode_index[] = {
1854
      THR_DC /*DC_PRED*/,          THR_V_PRED /*V_PRED*/,
1855
      THR_H_PRED /*H_PRED*/,       THR_D45_PRED /*D45_PRED*/,
1856
      THR_D135_PRED /*D135_PRED*/, THR_D117_PRED /*D117_PRED*/,
1857
      THR_D153_PRED /*D153_PRED*/, THR_D207_PRED /*D207_PRED*/,
1858
      THR_D63_PRED /*D63_PRED*/,   THR_TM /*TM_PRED*/,
1859
    };
1860
    ++cpi->mode_chosen_counts[kf_mode_index[xdmi->mode]];
1861
  } else {
1862
    // Note how often each mode chosen as best
1863
    ++cpi->mode_chosen_counts[ctx->best_mode_index];
1864
  }
1865
#endif
1866
1.09M
  if (!frame_is_intra_only(cm)) {
1867
1.01M
    if (is_inter_block(xdmi)) {
1868
595k
      vp9_update_mv_count(td);
1869
1870
595k
      if (cm->interp_filter == SWITCHABLE) {
1871
262k
        const int ctx_interp = get_pred_context_switchable_interp(xd);
1872
262k
        ++td->counts->switchable_interp[ctx_interp][xdmi->interp_filter];
1873
262k
      }
1874
595k
    }
1875
1876
1.01M
    rdc->comp_pred_diff[SINGLE_REFERENCE] += ctx->single_pred_diff;
1877
1.01M
    rdc->comp_pred_diff[COMPOUND_REFERENCE] += ctx->comp_pred_diff;
1878
1.01M
    rdc->comp_pred_diff[REFERENCE_MODE_SELECT] += ctx->hybrid_pred_diff;
1879
1880
5.07M
    for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
1881
4.06M
      rdc->filter_diff[i] += ctx->best_filter_diff[i];
1882
1.01M
  }
1883
1884
2.51M
  for (h = 0; h < y_mis; ++h) {
1885
1.42M
    MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1886
3.81M
    for (w = 0; w < x_mis; ++w) {
1887
2.39M
      MV_REF *const mv = frame_mv + w;
1888
2.39M
      mv->ref_frame[0] = mi->ref_frame[0];
1889
2.39M
      mv->ref_frame[1] = mi->ref_frame[1];
1890
2.39M
      mv->mv[0].as_int = mi->mv[0].as_int;
1891
2.39M
      mv->mv[1].as_int = mi->mv[1].as_int;
1892
2.39M
    }
1893
1.42M
  }
1894
1.09M
}
1895
#endif  // !CONFIG_REALTIME_ONLY
1896
1897
void vp9_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src,
1898
26.6M
                          int mi_row, int mi_col) {
1899
26.6M
  uint8_t *const buffers[3] = { src->y_buffer, src->u_buffer, src->v_buffer };
1900
26.6M
  const int strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
1901
26.6M
  int i;
1902
1903
  // Set current frame pointer.
1904
26.6M
  x->e_mbd.cur_buf = src;
1905
1906
106M
  for (i = 0; i < MAX_MB_PLANE; i++)
1907
80.0M
    setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mi_row, mi_col,
1908
80.0M
                     NULL, x->e_mbd.plane[i].subsampling_x,
1909
80.0M
                     x->e_mbd.plane[i].subsampling_y);
1910
26.6M
}
1911
1912
static void set_mode_info_seg_skip(MACROBLOCK *x, TX_MODE tx_mode,
1913
                                   INTERP_FILTER interp_filter,
1914
0
                                   RD_COST *rd_cost, BLOCK_SIZE bsize) {
1915
0
  MACROBLOCKD *const xd = &x->e_mbd;
1916
0
  MODE_INFO *const mi = xd->mi[0];
1917
0
  INTERP_FILTER filter_ref;
1918
1919
0
  filter_ref = get_pred_context_switchable_interp(xd);
1920
0
  if (interp_filter == BILINEAR)
1921
0
    filter_ref = BILINEAR;
1922
0
  else if (filter_ref == SWITCHABLE_FILTERS)
1923
0
    filter_ref = EIGHTTAP;
1924
1925
0
  mi->sb_type = bsize;
1926
0
  mi->mode = ZEROMV;
1927
0
  mi->tx_size =
1928
0
      VPXMIN(max_txsize_lookup[bsize], tx_mode_to_biggest_tx_size[tx_mode]);
1929
0
  mi->skip = 1;
1930
0
  mi->uv_mode = DC_PRED;
1931
0
  mi->ref_frame[0] = LAST_FRAME;
1932
0
  mi->ref_frame[1] = NO_REF_FRAME;
1933
0
  mi->mv[0].as_int = 0;
1934
0
  mi->interp_filter = filter_ref;
1935
1936
0
  xd->mi[0]->bmi[0].as_mv[0].as_int = 0;
1937
0
  x->skip = 1;
1938
1939
0
  vp9_rd_cost_init(rd_cost);
1940
0
}
1941
1942
#if !CONFIG_REALTIME_ONLY
1943
static void set_segment_rdmult(VP9_COMP *const cpi, MACROBLOCK *const x,
1944
                               int mi_row, int mi_col, BLOCK_SIZE bsize,
1945
6.44M
                               AQ_MODE aq_mode) {
1946
6.44M
  VP9_COMMON *const cm = &cpi->common;
1947
6.44M
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1948
6.44M
  const uint8_t *const map =
1949
6.44M
      cm->seg.update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1950
1951
6.44M
  vp9_init_plane_quantizers(cpi, x);
1952
6.44M
  vpx_clear_system_state();
1953
1954
6.44M
  if (aq_mode == NO_AQ || aq_mode == PSNR_AQ) {
1955
6.44M
    if (cpi->sf.enable_tpl_model) x->rdmult = x->cb_rdmult;
1956
6.44M
  } else if (aq_mode == PERCEPTUAL_AQ) {
1957
0
    x->rdmult = x->cb_rdmult;
1958
0
  } else if (aq_mode == CYCLIC_REFRESH_AQ) {
1959
    // If segment is boosted, use rdmult for that segment.
1960
0
    if (cyclic_refresh_segment_id_boosted(
1961
0
            get_segment_id(cm, map, bsize, mi_row, mi_col)))
1962
0
      x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
1963
0
  } else {
1964
0
    x->rdmult = vp9_compute_rd_mult(cpi, cm->base_qindex + cm->y_dc_delta_q);
1965
0
  }
1966
1967
6.44M
  if (oxcf->tuning == VP8_TUNE_SSIM) {
1968
0
    set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &x->rdmult);
1969
0
  }
1970
6.44M
}
1971
1972
static void rd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
1973
                             MACROBLOCK *const x, int mi_row, int mi_col,
1974
                             RD_COST *rd_cost, BLOCK_SIZE bsize,
1975
                             PICK_MODE_CONTEXT *ctx, int rate_in_best_rd,
1976
6.44M
                             int64_t dist_in_best_rd) {
1977
6.44M
  VP9_COMMON *const cm = &cpi->common;
1978
6.44M
  TileInfo *const tile_info = &tile_data->tile_info;
1979
6.44M
  MACROBLOCKD *const xd = &x->e_mbd;
1980
6.44M
  MODE_INFO *mi;
1981
6.44M
  struct macroblock_plane *const p = x->plane;
1982
6.44M
  struct macroblockd_plane *const pd = xd->plane;
1983
6.44M
  const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
1984
6.44M
  int i, orig_rdmult;
1985
6.44M
  int64_t best_rd = INT64_MAX;
1986
1987
6.44M
  vpx_clear_system_state();
1988
#if CONFIG_COLLECT_COMPONENT_TIMING
1989
  start_timing(cpi, rd_pick_sb_modes_time);
1990
#endif
1991
1992
  // Use the lower precision, but faster, 32x32 fdct for mode selection.
1993
6.44M
  x->use_lp32x32fdct = 1;
1994
1995
6.44M
  set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1996
6.44M
  mi = xd->mi[0];
1997
6.44M
  mi->sb_type = bsize;
1998
1999
25.7M
  for (i = 0; i < MAX_MB_PLANE; ++i) {
2000
19.3M
    p[i].coeff = ctx->coeff_pbuf[i][0];
2001
19.3M
    p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
2002
19.3M
    pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
2003
19.3M
    p[i].eobs = ctx->eobs_pbuf[i][0];
2004
19.3M
  }
2005
6.44M
  ctx->is_coded = 0;
2006
6.44M
  ctx->skippable = 0;
2007
6.44M
  ctx->pred_pixel_ready = 0;
2008
6.44M
  x->skip_recode = 0;
2009
2010
  // Set to zero to make sure we do not use the previous encoded frame stats
2011
6.44M
  mi->skip = 0;
2012
2013
6.44M
#if CONFIG_VP9_HIGHBITDEPTH
2014
6.44M
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
2015
0
    x->source_variance = vp9_high_get_sby_perpixel_variance(
2016
0
        cpi, &x->plane[0].src, bsize, xd->bd);
2017
6.44M
  } else {
2018
6.44M
    x->source_variance =
2019
6.44M
        vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
2020
6.44M
  }
2021
#else
2022
  x->source_variance =
2023
      vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
2024
#endif  // CONFIG_VP9_HIGHBITDEPTH
2025
2026
  // Save rdmult before it might be changed, so it can be restored later.
2027
6.44M
  orig_rdmult = x->rdmult;
2028
2029
6.44M
  if ((cpi->sf.tx_domain_thresh > 0.0) ||
2030
6.44M
      (cpi->sf.trellis_opt_tx_rd.thresh > 0.0)) {
2031
6.44M
    double logvar = vp9_log_block_var(cpi, x, bsize);
2032
    // Check block complexity as part of decision on using pixel or transform
2033
    // domain distortion in rd tests.
2034
6.44M
    x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion &&
2035
0
                         (logvar >= cpi->sf.tx_domain_thresh);
2036
2037
    // Store block complexity to decide on using quantized coefficient
2038
    // optimization inside the rd loop.
2039
6.44M
    x->log_block_src_var = logvar;
2040
6.44M
  } else {
2041
0
    x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion;
2042
0
    x->log_block_src_var = 0.0;
2043
0
  }
2044
2045
6.44M
  set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
2046
6.44M
  set_segment_rdmult(cpi, x, mi_row, mi_col, bsize, aq_mode);
2047
6.44M
  if (rate_in_best_rd < INT_MAX && dist_in_best_rd < INT64_MAX) {
2048
5.73M
    best_rd = vp9_calculate_rd_cost(x->rdmult, x->rddiv, rate_in_best_rd,
2049
5.73M
                                    dist_in_best_rd);
2050
5.73M
  }
2051
2052
  // Find best coding mode & reconstruct the MB so it is available
2053
  // as a predictor for MBs that follow in the SB
2054
6.44M
  if (frame_is_intra_only(cm)) {
2055
598k
    vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, best_rd);
2056
5.84M
  } else {
2057
5.84M
    if (bsize >= BLOCK_8X8) {
2058
#if CONFIG_COLLECT_COMPONENT_TIMING
2059
      start_timing(cpi, vp9_rd_pick_inter_mode_sb_time);
2060
#endif
2061
2.95M
      if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
2062
0
        vp9_rd_pick_inter_mode_sb_seg_skip(cpi, tile_data, x, rd_cost, bsize,
2063
0
                                           ctx, best_rd);
2064
2.95M
      else
2065
2.95M
        vp9_rd_pick_inter_mode_sb(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2066
2.95M
                                  bsize, ctx, best_rd);
2067
#if CONFIG_COLLECT_COMPONENT_TIMING
2068
      end_timing(cpi, vp9_rd_pick_inter_mode_sb_time);
2069
#endif
2070
2.95M
    } else {
2071
#if CONFIG_COLLECT_COMPONENT_TIMING
2072
      start_timing(cpi, vp9_rd_pick_inter_mode_sub8x8_time);
2073
#endif
2074
2.88M
      vp9_rd_pick_inter_mode_sub8x8(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2075
2.88M
                                    bsize, ctx, best_rd);
2076
#if CONFIG_COLLECT_COMPONENT_TIMING
2077
      end_timing(cpi, vp9_rd_pick_inter_mode_sub8x8_time);
2078
#endif
2079
2.88M
    }
2080
5.84M
  }
2081
2082
  // Examine the resulting rate and for AQ mode 2 make a segment choice.
2083
6.44M
  if ((rd_cost->rate != INT_MAX) && (aq_mode == COMPLEXITY_AQ) &&
2084
0
      (bsize >= BLOCK_16X16) &&
2085
0
      (cm->frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame ||
2086
0
       (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref))) {
2087
0
    vp9_caq_select_segment(cpi, x, bsize, mi_row, mi_col, rd_cost->rate);
2088
0
  }
2089
2090
  // TODO(jingning) The rate-distortion optimization flow needs to be
2091
  // refactored to provide proper exit/return handle.
2092
6.44M
  if (rd_cost->rate == INT_MAX || rd_cost->dist == INT64_MAX)
2093
3.30M
    rd_cost->rdcost = INT64_MAX;
2094
3.13M
  else
2095
3.13M
    rd_cost->rdcost = RDCOST(x->rdmult, x->rddiv, rd_cost->rate, rd_cost->dist);
2096
2097
6.44M
  x->rdmult = orig_rdmult;
2098
2099
6.44M
  ctx->rate = rd_cost->rate;
2100
6.44M
  ctx->dist = rd_cost->dist;
2101
#if CONFIG_COLLECT_COMPONENT_TIMING
2102
  end_timing(cpi, rd_pick_sb_modes_time);
2103
#endif
2104
6.44M
}
2105
#endif  // !CONFIG_REALTIME_ONLY
2106
2107
3.32M
static void update_stats(VP9_COMMON *cm, ThreadData *td) {
2108
3.32M
  const MACROBLOCK *x = &td->mb;
2109
3.32M
  const MACROBLOCKD *const xd = &x->e_mbd;
2110
3.32M
  const MODE_INFO *const mi = xd->mi[0];
2111
3.32M
  const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2112
3.32M
  const BLOCK_SIZE bsize = mi->sb_type;
2113
2114
3.32M
  if (!frame_is_intra_only(cm)) {
2115
3.00M
    FRAME_COUNTS *const counts = td->counts;
2116
3.00M
    const int inter_block = is_inter_block(mi);
2117
3.00M
    const int seg_ref_active =
2118
3.00M
        segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_REF_FRAME);
2119
3.00M
    if (!seg_ref_active) {
2120
3.00M
      counts->intra_inter[get_intra_inter_context(xd)][inter_block]++;
2121
      // If the segment reference feature is enabled we have only a single
2122
      // reference frame allowed for the segment so exclude it from
2123
      // the reference frame counts used to work out probabilities.
2124
3.00M
      if (inter_block) {
2125
1.79M
        const MV_REFERENCE_FRAME ref0 = mi->ref_frame[0];
2126
1.79M
        if (cm->reference_mode == REFERENCE_MODE_SELECT)
2127
0
          counts->comp_inter[vp9_get_reference_mode_context(cm, xd)]
2128
0
                            [has_second_ref(mi)]++;
2129
2130
1.79M
        if (has_second_ref(mi)) {
2131
0
          const int idx = cm->ref_frame_sign_bias[cm->comp_fixed_ref];
2132
0
          const int ctx = vp9_get_pred_context_comp_ref_p(cm, xd);
2133
0
          const int bit = mi->ref_frame[!idx] == cm->comp_var_ref[1];
2134
0
          counts->comp_ref[ctx][bit]++;
2135
1.79M
        } else {
2136
1.79M
          counts->single_ref[vp9_get_pred_context_single_ref_p1(xd)][0]
2137
1.79M
                            [ref0 != LAST_FRAME]++;
2138
1.79M
          if (ref0 != LAST_FRAME)
2139
705k
            counts->single_ref[vp9_get_pred_context_single_ref_p2(xd)][1]
2140
705k
                              [ref0 != GOLDEN_FRAME]++;
2141
1.79M
        }
2142
1.79M
      }
2143
3.00M
    }
2144
3.00M
    if (inter_block &&
2145
1.79M
        !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP)) {
2146
1.79M
      const int mode_ctx = mbmi_ext->mode_context[mi->ref_frame[0]];
2147
1.79M
      if (bsize >= BLOCK_8X8) {
2148
1.70M
        const PREDICTION_MODE mode = mi->mode;
2149
1.70M
        ++counts->inter_mode[mode_ctx][INTER_OFFSET(mode)];
2150
1.70M
      } else {
2151
96.1k
        const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
2152
96.1k
        const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
2153
96.1k
        int idx, idy;
2154
270k
        for (idy = 0; idy < 2; idy += num_4x4_h) {
2155
450k
          for (idx = 0; idx < 2; idx += num_4x4_w) {
2156
276k
            const int j = idy * 2 + idx;
2157
276k
            const PREDICTION_MODE b_mode = mi->bmi[j].as_mode;
2158
276k
            ++counts->inter_mode[mode_ctx][INTER_OFFSET(b_mode)];
2159
276k
          }
2160
174k
        }
2161
96.1k
      }
2162
1.79M
    }
2163
3.00M
  }
2164
3.32M
}
2165
2166
#if !CONFIG_REALTIME_ONLY
2167
static void restore_context(MACROBLOCK *const x, int mi_row, int mi_col,
2168
                            ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2169
                            ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2170
                            PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2171
7.27M
                            BLOCK_SIZE bsize) {
2172
7.27M
  MACROBLOCKD *const xd = &x->e_mbd;
2173
7.27M
  int p;
2174
7.27M
  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2175
7.27M
  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2176
7.27M
  int mi_width = num_8x8_blocks_wide_lookup[bsize];
2177
7.27M
  int mi_height = num_8x8_blocks_high_lookup[bsize];
2178
29.1M
  for (p = 0; p < MAX_MB_PLANE; p++) {
2179
21.8M
    memcpy(xd->above_context[p] + ((mi_col * 2) >> xd->plane[p].subsampling_x),
2180
21.8M
           a + num_4x4_blocks_wide * p,
2181
21.8M
           (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2182
21.8M
               xd->plane[p].subsampling_x);
2183
21.8M
    memcpy(xd->left_context[p] +
2184
21.8M
               ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2185
21.8M
           l + num_4x4_blocks_high * p,
2186
21.8M
           (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2187
21.8M
               xd->plane[p].subsampling_y);
2188
21.8M
  }
2189
7.27M
  memcpy(xd->above_seg_context + mi_col, sa,
2190
7.27M
         sizeof(*xd->above_seg_context) * mi_width);
2191
7.27M
  memcpy(xd->left_seg_context + (mi_row & MI_MASK), sl,
2192
7.27M
         sizeof(xd->left_seg_context[0]) * mi_height);
2193
7.27M
}
2194
2195
static void save_context(MACROBLOCK *const x, int mi_row, int mi_col,
2196
                         ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2197
                         ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2198
                         PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2199
2.87M
                         BLOCK_SIZE bsize) {
2200
2.87M
  const MACROBLOCKD *const xd = &x->e_mbd;
2201
2.87M
  int p;
2202
2.87M
  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2203
2.87M
  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2204
2.87M
  int mi_width = num_8x8_blocks_wide_lookup[bsize];
2205
2.87M
  int mi_height = num_8x8_blocks_high_lookup[bsize];
2206
2207
  // buffer the above/left context information of the block in search.
2208
11.5M
  for (p = 0; p < MAX_MB_PLANE; ++p) {
2209
8.63M
    memcpy(a + num_4x4_blocks_wide * p,
2210
8.63M
           xd->above_context[p] + (mi_col * 2 >> xd->plane[p].subsampling_x),
2211
8.63M
           (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2212
8.63M
               xd->plane[p].subsampling_x);
2213
8.63M
    memcpy(l + num_4x4_blocks_high * p,
2214
8.63M
           xd->left_context[p] +
2215
8.63M
               ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2216
8.63M
           (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2217
8.63M
               xd->plane[p].subsampling_y);
2218
8.63M
  }
2219
2.87M
  memcpy(sa, xd->above_seg_context + mi_col,
2220
2.87M
         sizeof(*xd->above_seg_context) * mi_width);
2221
2.87M
  memcpy(sl, xd->left_seg_context + (mi_row & MI_MASK),
2222
2.87M
         sizeof(xd->left_seg_context[0]) * mi_height);
2223
2.87M
}
2224
2225
static void encode_b(VP9_COMP *cpi, const TileInfo *const tile, ThreadData *td,
2226
                     TOKENEXTRA **tp, int mi_row, int mi_col,
2227
                     int output_enabled, BLOCK_SIZE bsize,
2228
4.56M
                     PICK_MODE_CONTEXT *ctx) {
2229
4.56M
  MACROBLOCK *const x = &td->mb;
2230
4.56M
  set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2231
2232
4.56M
  if (cpi->sf.enable_tpl_model &&
2233
4.56M
      (cpi->oxcf.aq_mode == NO_AQ || cpi->oxcf.aq_mode == PERCEPTUAL_AQ)) {
2234
4.56M
    const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2235
4.56M
    x->rdmult = x->cb_rdmult;
2236
4.56M
    if (oxcf->tuning == VP8_TUNE_SSIM) {
2237
0
      set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &x->rdmult);
2238
0
    }
2239
4.56M
  }
2240
2241
4.56M
  update_state(cpi, td, ctx, mi_row, mi_col, bsize, output_enabled);
2242
4.56M
  encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2243
2244
4.56M
  if (output_enabled) {
2245
1.09M
    update_stats(&cpi->common, td);
2246
2247
1.09M
    (*tp)->token = EOSB_TOKEN;
2248
1.09M
    (*tp)++;
2249
1.09M
  }
2250
4.56M
}
2251
2252
static void encode_sb(VP9_COMP *cpi, ThreadData *td, const TileInfo *const tile,
2253
                      TOKENEXTRA **tp, int mi_row, int mi_col,
2254
9.00M
                      int output_enabled, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2255
9.00M
  VP9_COMMON *const cm = &cpi->common;
2256
9.00M
  MACROBLOCK *const x = &td->mb;
2257
9.00M
  MACROBLOCKD *const xd = &x->e_mbd;
2258
2259
9.00M
  const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2260
9.00M
  int ctx;
2261
9.00M
  PARTITION_TYPE partition;
2262
9.00M
  BLOCK_SIZE subsize = bsize;
2263
2264
9.00M
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2265
2266
6.10M
  if (bsize >= BLOCK_8X8) {
2267
6.10M
    ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2268
6.10M
    subsize = get_subsize(bsize, pc_tree->partitioning);
2269
6.10M
  } else {
2270
0
    ctx = 0;
2271
0
    subsize = BLOCK_4X4;
2272
0
  }
2273
2274
6.10M
  partition = partition_lookup[bsl][subsize];
2275
6.10M
  if (output_enabled && bsize != BLOCK_4X4)
2276
1.82M
    td->counts->partition[ctx][partition]++;
2277
2278
6.10M
  switch (partition) {
2279
2.94M
    case PARTITION_NONE:
2280
2.94M
      encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2281
2.94M
               &pc_tree->none);
2282
2.94M
      break;
2283
419k
    case PARTITION_VERT:
2284
419k
      encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2285
419k
               &pc_tree->vertical[0]);
2286
419k
      if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2287
23.4k
        encode_b(cpi, tile, td, tp, mi_row, mi_col + hbs, output_enabled,
2288
23.4k
                 subsize, &pc_tree->vertical[1]);
2289
23.4k
      }
2290
419k
      break;
2291
578k
    case PARTITION_HORZ:
2292
578k
      encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2293
578k
               &pc_tree->horizontal[0]);
2294
578k
      if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2295
51.5k
        encode_b(cpi, tile, td, tp, mi_row + hbs, mi_col, output_enabled,
2296
51.5k
                 subsize, &pc_tree->horizontal[1]);
2297
51.5k
      }
2298
578k
      break;
2299
2.17M
    default:
2300
2.17M
      assert(partition == PARTITION_SPLIT);
2301
2.17M
      if (bsize == BLOCK_8X8) {
2302
554k
        encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2303
554k
                 pc_tree->u.leaf_split[0]);
2304
1.61M
      } else {
2305
1.61M
        encode_sb(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2306
1.61M
                  pc_tree->u.split[0]);
2307
1.61M
        encode_sb(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2308
1.61M
                  subsize, pc_tree->u.split[1]);
2309
1.61M
        encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2310
1.61M
                  subsize, pc_tree->u.split[2]);
2311
1.61M
        encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs, output_enabled,
2312
1.61M
                  subsize, pc_tree->u.split[3]);
2313
1.61M
      }
2314
2.17M
      break;
2315
6.10M
  }
2316
2317
6.10M
  if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2318
4.49M
    update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2319
6.10M
}
2320
#endif  // !CONFIG_REALTIME_ONLY
2321
2322
// Check to see if the given partition size is allowed for a specified number
2323
// of 8x8 block rows and columns remaining in the image.
2324
// If not then return the largest allowed partition size
2325
static BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize, int rows_left,
2326
164k
                                      int cols_left, int *bh, int *bw) {
2327
164k
  if (rows_left <= 0 || cols_left <= 0) {
2328
125k
    return VPXMIN(bsize, BLOCK_8X8);
2329
125k
  } else {
2330
128k
    for (; bsize > 0; bsize -= 3) {
2331
128k
      *bh = num_8x8_blocks_high_lookup[bsize];
2332
128k
      *bw = num_8x8_blocks_wide_lookup[bsize];
2333
128k
      if ((*bh <= rows_left) && (*bw <= cols_left)) {
2334
39.1k
        break;
2335
39.1k
      }
2336
128k
    }
2337
39.1k
  }
2338
39.1k
  return bsize;
2339
164k
}
2340
2341
static void set_partial_b64x64_partition(MODE_INFO *mi, int mis, int bh_in,
2342
                                         int bw_in, int row8x8_remaining,
2343
                                         int col8x8_remaining, BLOCK_SIZE bsize,
2344
10.5k
                                         MODE_INFO **mi_8x8) {
2345
10.5k
  int bh = bh_in;
2346
10.5k
  int r, c;
2347
76.2k
  for (r = 0; r < MI_BLOCK_SIZE; r += bh) {
2348
65.6k
    int bw = bw_in;
2349
230k
    for (c = 0; c < MI_BLOCK_SIZE; c += bw) {
2350
164k
      const int index = r * mis + c;
2351
164k
      mi_8x8[index] = mi + index;
2352
164k
      mi_8x8[index]->sb_type = find_partition_size(
2353
164k
          bsize, row8x8_remaining - r, col8x8_remaining - c, &bh, &bw);
2354
164k
    }
2355
65.6k
  }
2356
10.5k
}
2357
2358
// This function attempts to set all mode info entries in a given SB64
2359
// to the same block partition size.
2360
// However, at the bottom and right borders of the image the requested size
2361
// may not be allowed in which case this code attempts to choose the largest
2362
// allowable partition.
2363
static void set_fixed_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
2364
                                   MODE_INFO **mi_8x8, int mi_row, int mi_col,
2365
10.5k
                                   BLOCK_SIZE bsize) {
2366
10.5k
  VP9_COMMON *const cm = &cpi->common;
2367
10.5k
  const int mis = cm->mi_stride;
2368
10.5k
  const int row8x8_remaining = tile->mi_row_end - mi_row;
2369
10.5k
  const int col8x8_remaining = tile->mi_col_end - mi_col;
2370
10.5k
  int block_row, block_col;
2371
10.5k
  MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
2372
10.5k
  int bh = num_8x8_blocks_high_lookup[bsize];
2373
10.5k
  int bw = num_8x8_blocks_wide_lookup[bsize];
2374
2375
10.5k
  assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
2376
2377
  // Apply the requested partition size to the SB64 if it is all "in image"
2378
10.5k
  if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
2379
4.34k
      (row8x8_remaining >= MI_BLOCK_SIZE)) {
2380
0
    for (block_row = 0; block_row < MI_BLOCK_SIZE; block_row += bh) {
2381
0
      for (block_col = 0; block_col < MI_BLOCK_SIZE; block_col += bw) {
2382
0
        int index = block_row * mis + block_col;
2383
0
        mi_8x8[index] = mi_upper_left + index;
2384
0
        mi_8x8[index]->sb_type = bsize;
2385
0
      }
2386
0
    }
2387
10.5k
  } else {
2388
    // Else this is a partial SB64.
2389
10.5k
    set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
2390
10.5k
                                 col8x8_remaining, bsize, mi_8x8);
2391
10.5k
  }
2392
10.5k
}
2393
2394
static void update_state_rt(VP9_COMP *cpi, ThreadData *td,
2395
                            PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
2396
2.22M
                            int bsize) {
2397
2.22M
  VP9_COMMON *const cm = &cpi->common;
2398
2.22M
  MACROBLOCK *const x = &td->mb;
2399
2.22M
  MACROBLOCKD *const xd = &x->e_mbd;
2400
2.22M
  MODE_INFO *const mi = xd->mi[0];
2401
2.22M
  struct macroblock_plane *const p = x->plane;
2402
2.22M
  const struct segmentation *const seg = &cm->seg;
2403
2.22M
  const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
2404
2.22M
  const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
2405
2.22M
  const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
2406
2.22M
  const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
2407
2408
2.22M
  *(xd->mi[0]) = ctx->mic;
2409
2.22M
  *(x->mbmi_ext) = ctx->mbmi_ext;
2410
2411
2.22M
  if (seg->enabled && (cpi->oxcf.aq_mode != NO_AQ || cpi->roi.enabled ||
2412
0
                       cpi->active_map.enabled)) {
2413
    // Setting segmentation map for cyclic_refresh.
2414
0
    if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
2415
0
        cpi->cyclic_refresh->content_mode) {
2416
0
      vp9_cyclic_refresh_update_segment(cpi, mi, mi_row, mi_col, bsize,
2417
0
                                        ctx->rate, ctx->dist, x->skip, p);
2418
0
    } else {
2419
0
      const uint8_t *const map =
2420
0
          seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
2421
0
      mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
2422
0
    }
2423
0
    vp9_init_plane_quantizers(cpi, x);
2424
0
  }
2425
2426
2.22M
  if (is_inter_block(mi)) {
2427
1.20M
    vp9_update_mv_count(td);
2428
1.20M
    if (cm->interp_filter == SWITCHABLE) {
2429
1.20M
      const int pred_ctx = get_pred_context_switchable_interp(xd);
2430
1.20M
      ++td->counts->switchable_interp[pred_ctx][mi->interp_filter];
2431
1.20M
    }
2432
2433
1.20M
    if (mi->sb_type < BLOCK_8X8) {
2434
0
      mi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
2435
0
      mi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
2436
0
    }
2437
1.20M
  }
2438
2439
2.22M
  if (cm->use_prev_frame_mvs || !cm->error_resilient_mode ||
2440
2.22M
      (cpi->svc.use_base_mv && cpi->svc.number_spatial_layers > 1 &&
2441
0
       cpi->svc.spatial_layer_id != cpi->svc.number_spatial_layers - 1)) {
2442
0
    MV_REF *const frame_mvs =
2443
0
        cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
2444
0
    int w, h;
2445
2446
0
    for (h = 0; h < y_mis; ++h) {
2447
0
      MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
2448
0
      for (w = 0; w < x_mis; ++w) {
2449
0
        MV_REF *const mv = frame_mv + w;
2450
0
        mv->ref_frame[0] = mi->ref_frame[0];
2451
0
        mv->ref_frame[1] = mi->ref_frame[1];
2452
0
        mv->mv[0].as_int = mi->mv[0].as_int;
2453
0
        mv->mv[1].as_int = mi->mv[1].as_int;
2454
0
      }
2455
0
    }
2456
0
  }
2457
2458
2.22M
  x->skip = ctx->skip;
2459
2.22M
  x->skip_txfm[0] = (mi->segment_id || xd->lossless) ? 0 : ctx->skip_txfm[0];
2460
2.22M
}
2461
2462
static void encode_b_rt(VP9_COMP *cpi, ThreadData *td,
2463
                        const TileInfo *const tile, TOKENEXTRA **tp, int mi_row,
2464
                        int mi_col, int output_enabled, BLOCK_SIZE bsize,
2465
2.22M
                        PICK_MODE_CONTEXT *ctx) {
2466
2.22M
  MACROBLOCK *const x = &td->mb;
2467
2.22M
  set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2468
2.22M
  update_state_rt(cpi, td, ctx, mi_row, mi_col, bsize);
2469
2470
2.22M
  encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2471
2.22M
  update_stats(&cpi->common, td);
2472
2473
2.22M
  (*tp)->token = EOSB_TOKEN;
2474
2.22M
  (*tp)++;
2475
2.22M
}
2476
2477
static void encode_sb_rt(VP9_COMP *cpi, ThreadData *td,
2478
                         const TileInfo *const tile, TOKENEXTRA **tp,
2479
                         int mi_row, int mi_col, int output_enabled,
2480
4.94M
                         BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2481
4.94M
  VP9_COMMON *const cm = &cpi->common;
2482
4.94M
  MACROBLOCK *const x = &td->mb;
2483
4.94M
  MACROBLOCKD *const xd = &x->e_mbd;
2484
2485
4.94M
  const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2486
4.94M
  int ctx;
2487
4.94M
  PARTITION_TYPE partition;
2488
4.94M
  BLOCK_SIZE subsize;
2489
2490
4.94M
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2491
2492
3.12M
  if (bsize >= BLOCK_8X8) {
2493
3.12M
    const int idx_str = xd->mi_stride * mi_row + mi_col;
2494
3.12M
    MODE_INFO **mi_8x8 = cm->mi_grid_visible + idx_str;
2495
3.12M
    ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2496
3.12M
    subsize = mi_8x8[0]->sb_type;
2497
3.12M
  } else {
2498
0
    ctx = 0;
2499
0
    subsize = BLOCK_4X4;
2500
0
  }
2501
2502
3.12M
  partition = partition_lookup[bsl][subsize];
2503
3.12M
  if (output_enabled && bsize != BLOCK_4X4)
2504
3.12M
    td->counts->partition[ctx][partition]++;
2505
2506
3.12M
  switch (partition) {
2507
1.94M
    case PARTITION_NONE:
2508
1.94M
      encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2509
1.94M
                  &pc_tree->none);
2510
1.94M
      break;
2511
0
    case PARTITION_VERT:
2512
0
      encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2513
0
                  &pc_tree->vertical[0]);
2514
0
      if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2515
0
        encode_b_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2516
0
                    subsize, &pc_tree->vertical[1]);
2517
0
      }
2518
0
      break;
2519
0
    case PARTITION_HORZ:
2520
0
      encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2521
0
                  &pc_tree->horizontal[0]);
2522
0
      if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2523
0
        encode_b_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2524
0
                    subsize, &pc_tree->horizontal[1]);
2525
0
      }
2526
0
      break;
2527
1.18M
    default:
2528
1.18M
      assert(partition == PARTITION_SPLIT);
2529
1.18M
      subsize = get_subsize(bsize, PARTITION_SPLIT);
2530
1.18M
      encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2531
1.18M
                   pc_tree->u.split[0]);
2532
1.18M
      encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2533
1.18M
                   subsize, pc_tree->u.split[1]);
2534
1.18M
      encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2535
1.18M
                   subsize, pc_tree->u.split[2]);
2536
1.18M
      encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs,
2537
1.18M
                   output_enabled, subsize, pc_tree->u.split[3]);
2538
1.18M
      break;
2539
3.12M
  }
2540
2541
3.12M
  if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2542
1.94M
    update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2543
3.12M
}
2544
2545
#if !CONFIG_REALTIME_ONLY
2546
static void rd_use_partition(VP9_COMP *cpi, ThreadData *td,
2547
                             TileDataEnc *tile_data, MODE_INFO **mi_8x8,
2548
                             TOKENEXTRA **tp, int mi_row, int mi_col,
2549
                             BLOCK_SIZE bsize, int *rate, int64_t *dist,
2550
0
                             int do_recon, PC_TREE *pc_tree) {
2551
0
  VP9_COMMON *const cm = &cpi->common;
2552
0
  TileInfo *const tile_info = &tile_data->tile_info;
2553
0
  MACROBLOCK *const x = &td->mb;
2554
0
  MACROBLOCKD *const xd = &x->e_mbd;
2555
0
  const int mis = cm->mi_stride;
2556
0
  const int bsl = b_width_log2_lookup[bsize];
2557
0
  const int mi_step = num_4x4_blocks_wide_lookup[bsize] / 2;
2558
0
  const int bss = (1 << bsl) / 4;
2559
0
  int i, pl;
2560
0
  PARTITION_TYPE partition = PARTITION_NONE;
2561
0
  BLOCK_SIZE subsize;
2562
0
  ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2563
0
  PARTITION_CONTEXT sl[8], sa[8];
2564
0
  RD_COST last_part_rdc, none_rdc, chosen_rdc;
2565
0
  BLOCK_SIZE sub_subsize = BLOCK_4X4;
2566
0
  int splits_below = 0;
2567
0
  BLOCK_SIZE bs_type = mi_8x8[0]->sb_type;
2568
0
  int do_partition_search = 1;
2569
0
  PICK_MODE_CONTEXT *ctx = &pc_tree->none;
2570
2571
0
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2572
2573
0
  assert(num_4x4_blocks_wide_lookup[bsize] ==
2574
0
         num_4x4_blocks_high_lookup[bsize]);
2575
2576
0
  vp9_rd_cost_reset(&last_part_rdc);
2577
0
  vp9_rd_cost_reset(&none_rdc);
2578
0
  vp9_rd_cost_reset(&chosen_rdc);
2579
2580
0
  partition = partition_lookup[bsl][bs_type];
2581
0
  subsize = get_subsize(bsize, partition);
2582
2583
0
  pc_tree->partitioning = partition;
2584
0
  save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2585
2586
0
  if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ) {
2587
0
    set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2588
0
    x->mb_energy = vp9_block_energy(cpi, x, bsize);
2589
0
  }
2590
2591
0
  if (do_partition_search &&
2592
0
      cpi->sf.partition_search_type == SEARCH_PARTITION &&
2593
0
      cpi->sf.adjust_partitioning_from_last_frame) {
2594
    // Check if any of the sub blocks are further split.
2595
0
    if (partition == PARTITION_SPLIT && subsize > BLOCK_8X8) {
2596
0
      sub_subsize = get_subsize(subsize, PARTITION_SPLIT);
2597
0
      splits_below = 1;
2598
0
      for (i = 0; i < 4; i++) {
2599
0
        int jj = i >> 1, ii = i & 0x01;
2600
0
        MODE_INFO *this_mi = mi_8x8[jj * bss * mis + ii * bss];
2601
0
        if (this_mi && this_mi->sb_type >= sub_subsize) {
2602
0
          splits_below = 0;
2603
0
        }
2604
0
      }
2605
0
    }
2606
2607
    // If partition is not none try none unless each of the 4 splits are split
2608
    // even further..
2609
0
    if (partition != PARTITION_NONE && !splits_below &&
2610
0
        mi_row + (mi_step >> 1) < cm->mi_rows &&
2611
0
        mi_col + (mi_step >> 1) < cm->mi_cols) {
2612
0
      pc_tree->partitioning = PARTITION_NONE;
2613
0
      rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &none_rdc, bsize, ctx,
2614
0
                       INT_MAX, INT64_MAX);
2615
2616
0
      pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2617
2618
0
      if (none_rdc.rate < INT_MAX) {
2619
0
        none_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2620
0
        none_rdc.rdcost =
2621
0
            RDCOST(x->rdmult, x->rddiv, none_rdc.rate, none_rdc.dist);
2622
0
      }
2623
2624
0
      restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2625
0
      mi_8x8[0]->sb_type = bs_type;
2626
0
      pc_tree->partitioning = partition;
2627
0
    }
2628
0
  }
2629
2630
0
  switch (partition) {
2631
0
    case PARTITION_NONE:
2632
0
      rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc, bsize,
2633
0
                       ctx, INT_MAX, INT64_MAX);
2634
0
      break;
2635
0
    case PARTITION_HORZ:
2636
0
      pc_tree->horizontal[0].skip_ref_frame_mask = 0;
2637
0
      rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2638
0
                       subsize, &pc_tree->horizontal[0], INT_MAX, INT64_MAX);
2639
0
      if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2640
0
          mi_row + (mi_step >> 1) < cm->mi_rows) {
2641
0
        RD_COST tmp_rdc;
2642
0
        PICK_MODE_CONTEXT *hctx = &pc_tree->horizontal[0];
2643
0
        vp9_rd_cost_init(&tmp_rdc);
2644
0
        update_state(cpi, td, hctx, mi_row, mi_col, subsize, 0);
2645
0
        encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, hctx);
2646
0
        pc_tree->horizontal[1].skip_ref_frame_mask = 0;
2647
0
        rd_pick_sb_modes(cpi, tile_data, x, mi_row + (mi_step >> 1), mi_col,
2648
0
                         &tmp_rdc, subsize, &pc_tree->horizontal[1], INT_MAX,
2649
0
                         INT64_MAX);
2650
0
        if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2651
0
          vp9_rd_cost_reset(&last_part_rdc);
2652
0
          break;
2653
0
        }
2654
0
        last_part_rdc.rate += tmp_rdc.rate;
2655
0
        last_part_rdc.dist += tmp_rdc.dist;
2656
0
        last_part_rdc.rdcost += tmp_rdc.rdcost;
2657
0
      }
2658
0
      break;
2659
0
    case PARTITION_VERT:
2660
0
      pc_tree->vertical[0].skip_ref_frame_mask = 0;
2661
0
      rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2662
0
                       subsize, &pc_tree->vertical[0], INT_MAX, INT64_MAX);
2663
0
      if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2664
0
          mi_col + (mi_step >> 1) < cm->mi_cols) {
2665
0
        RD_COST tmp_rdc;
2666
0
        PICK_MODE_CONTEXT *vctx = &pc_tree->vertical[0];
2667
0
        vp9_rd_cost_init(&tmp_rdc);
2668
0
        update_state(cpi, td, vctx, mi_row, mi_col, subsize, 0);
2669
0
        encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, vctx);
2670
0
        pc_tree->vertical[bsize > BLOCK_8X8].skip_ref_frame_mask = 0;
2671
0
        rd_pick_sb_modes(
2672
0
            cpi, tile_data, x, mi_row, mi_col + (mi_step >> 1), &tmp_rdc,
2673
0
            subsize, &pc_tree->vertical[bsize > BLOCK_8X8], INT_MAX, INT64_MAX);
2674
0
        if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2675
0
          vp9_rd_cost_reset(&last_part_rdc);
2676
0
          break;
2677
0
        }
2678
0
        last_part_rdc.rate += tmp_rdc.rate;
2679
0
        last_part_rdc.dist += tmp_rdc.dist;
2680
0
        last_part_rdc.rdcost += tmp_rdc.rdcost;
2681
0
      }
2682
0
      break;
2683
0
    default:
2684
0
      assert(partition == PARTITION_SPLIT);
2685
0
      if (bsize == BLOCK_8X8) {
2686
0
        rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2687
0
                         subsize, pc_tree->u.leaf_split[0], INT_MAX, INT64_MAX);
2688
0
        break;
2689
0
      }
2690
0
      last_part_rdc.rate = 0;
2691
0
      last_part_rdc.dist = 0;
2692
0
      last_part_rdc.rdcost = 0;
2693
0
      for (i = 0; i < 4; i++) {
2694
0
        int x_idx = (i & 1) * (mi_step >> 1);
2695
0
        int y_idx = (i >> 1) * (mi_step >> 1);
2696
0
        int jj = i >> 1, ii = i & 0x01;
2697
0
        RD_COST tmp_rdc;
2698
0
        if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2699
0
          continue;
2700
2701
0
        vp9_rd_cost_init(&tmp_rdc);
2702
0
        rd_use_partition(cpi, td, tile_data, mi_8x8 + jj * bss * mis + ii * bss,
2703
0
                         tp, mi_row + y_idx, mi_col + x_idx, subsize,
2704
0
                         &tmp_rdc.rate, &tmp_rdc.dist, i != 3,
2705
0
                         pc_tree->u.split[i]);
2706
0
        if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2707
0
          vp9_rd_cost_reset(&last_part_rdc);
2708
0
          break;
2709
0
        }
2710
0
        last_part_rdc.rate += tmp_rdc.rate;
2711
0
        last_part_rdc.dist += tmp_rdc.dist;
2712
0
      }
2713
0
      break;
2714
0
  }
2715
2716
0
  pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2717
0
  if (last_part_rdc.rate < INT_MAX) {
2718
0
    last_part_rdc.rate += cpi->partition_cost[pl][partition];
2719
0
    last_part_rdc.rdcost =
2720
0
        RDCOST(x->rdmult, x->rddiv, last_part_rdc.rate, last_part_rdc.dist);
2721
0
  }
2722
2723
0
  if (do_partition_search && cpi->sf.adjust_partitioning_from_last_frame &&
2724
0
      cpi->sf.partition_search_type == SEARCH_PARTITION &&
2725
0
      partition != PARTITION_SPLIT && bsize > BLOCK_8X8 &&
2726
0
      (mi_row + mi_step < cm->mi_rows ||
2727
0
       mi_row + (mi_step >> 1) == cm->mi_rows) &&
2728
0
      (mi_col + mi_step < cm->mi_cols ||
2729
0
       mi_col + (mi_step >> 1) == cm->mi_cols)) {
2730
0
    BLOCK_SIZE split_subsize = get_subsize(bsize, PARTITION_SPLIT);
2731
0
    chosen_rdc.rate = 0;
2732
0
    chosen_rdc.dist = 0;
2733
0
    restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2734
0
    pc_tree->partitioning = PARTITION_SPLIT;
2735
2736
    // Split partition.
2737
0
    for (i = 0; i < 4; i++) {
2738
0
      int x_idx = (i & 1) * (mi_step >> 1);
2739
0
      int y_idx = (i >> 1) * (mi_step >> 1);
2740
0
      RD_COST tmp_rdc;
2741
2742
0
      if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2743
0
        continue;
2744
2745
0
      save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2746
0
      pc_tree->u.split[i]->partitioning = PARTITION_NONE;
2747
0
      rd_pick_sb_modes(cpi, tile_data, x, mi_row + y_idx, mi_col + x_idx,
2748
0
                       &tmp_rdc, split_subsize, &pc_tree->u.split[i]->none,
2749
0
                       INT_MAX, INT64_MAX);
2750
2751
0
      restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2752
2753
0
      if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2754
0
        vp9_rd_cost_reset(&chosen_rdc);
2755
0
        break;
2756
0
      }
2757
2758
0
      chosen_rdc.rate += tmp_rdc.rate;
2759
0
      chosen_rdc.dist += tmp_rdc.dist;
2760
2761
0
      if (i != 3)
2762
0
        encode_sb(cpi, td, tile_info, tp, mi_row + y_idx, mi_col + x_idx, 0,
2763
0
                  split_subsize, pc_tree->u.split[i]);
2764
2765
0
      pl = partition_plane_context(xd, mi_row + y_idx, mi_col + x_idx,
2766
0
                                   split_subsize);
2767
0
      chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2768
0
    }
2769
0
    pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2770
0
    if (chosen_rdc.rate < INT_MAX) {
2771
0
      chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2772
0
      chosen_rdc.rdcost =
2773
0
          RDCOST(x->rdmult, x->rddiv, chosen_rdc.rate, chosen_rdc.dist);
2774
0
    }
2775
0
  }
2776
2777
  // If last_part is better set the partitioning to that.
2778
0
  if (last_part_rdc.rdcost < chosen_rdc.rdcost) {
2779
0
    mi_8x8[0]->sb_type = bsize;
2780
0
    if (bsize >= BLOCK_8X8) pc_tree->partitioning = partition;
2781
0
    chosen_rdc = last_part_rdc;
2782
0
  }
2783
  // If none was better set the partitioning to that.
2784
0
  if (none_rdc.rdcost < chosen_rdc.rdcost) {
2785
0
    if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
2786
0
    chosen_rdc = none_rdc;
2787
0
  }
2788
2789
0
  restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2790
2791
  // We must have chosen a partitioning and encoding or we'll fail later on.
2792
  // No other opportunities for success.
2793
0
  if (bsize == BLOCK_64X64)
2794
0
    assert(chosen_rdc.rate < INT_MAX && chosen_rdc.dist < INT64_MAX);
2795
2796
0
  if (do_recon) {
2797
0
    int output_enabled = (bsize == BLOCK_64X64);
2798
0
    encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
2799
0
              pc_tree);
2800
0
  }
2801
2802
0
  *rate = chosen_rdc.rate;
2803
0
  *dist = chosen_rdc.dist;
2804
0
}
2805
2806
static const BLOCK_SIZE min_partition_size[BLOCK_SIZES] = {
2807
  BLOCK_4X4,   BLOCK_4X4,   BLOCK_4X4,  BLOCK_4X4, BLOCK_4X4,
2808
  BLOCK_4X4,   BLOCK_8X8,   BLOCK_8X8,  BLOCK_8X8, BLOCK_16X16,
2809
  BLOCK_16X16, BLOCK_16X16, BLOCK_16X16
2810
};
2811
2812
static const BLOCK_SIZE max_partition_size[BLOCK_SIZES] = {
2813
  BLOCK_8X8,   BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2814
  BLOCK_32X32, BLOCK_32X32, BLOCK_64X64, BLOCK_64X64, BLOCK_64X64,
2815
  BLOCK_64X64, BLOCK_64X64, BLOCK_64X64
2816
};
2817
2818
// Look at all the mode_info entries for blocks that are part of this
2819
// partition and find the min and max values for sb_type.
2820
// At the moment this is designed to work on a 64x64 SB but could be
2821
// adjusted to use a size parameter.
2822
//
2823
// The min and max are assumed to have been initialized prior to calling this
2824
// function so repeat calls can accumulate a min and max of more than one sb64.
2825
static void get_sb_partition_size_range(MACROBLOCKD *xd, MODE_INFO **mi_8x8,
2826
                                        BLOCK_SIZE *min_block_size,
2827
                                        BLOCK_SIZE *max_block_size,
2828
0
                                        int bs_hist[BLOCK_SIZES]) {
2829
0
  int sb_width_in_blocks = MI_BLOCK_SIZE;
2830
0
  int sb_height_in_blocks = MI_BLOCK_SIZE;
2831
0
  int i, j;
2832
0
  int index = 0;
2833
2834
  // Check the sb_type for each block that belongs to this region.
2835
0
  for (i = 0; i < sb_height_in_blocks; ++i) {
2836
0
    for (j = 0; j < sb_width_in_blocks; ++j) {
2837
0
      MODE_INFO *mi = mi_8x8[index + j];
2838
0
      BLOCK_SIZE sb_type = mi ? mi->sb_type : 0;
2839
0
      bs_hist[sb_type]++;
2840
0
      *min_block_size = VPXMIN(*min_block_size, sb_type);
2841
0
      *max_block_size = VPXMAX(*max_block_size, sb_type);
2842
0
    }
2843
0
    index += xd->mi_stride;
2844
0
  }
2845
0
}
2846
2847
// Next square block size less or equal than current block size.
2848
static const BLOCK_SIZE next_square_size[BLOCK_SIZES] = {
2849
  BLOCK_4X4,   BLOCK_4X4,   BLOCK_4X4,   BLOCK_8X8,   BLOCK_8X8,
2850
  BLOCK_8X8,   BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2851
  BLOCK_32X32, BLOCK_32X32, BLOCK_64X64
2852
};
2853
2854
// Look at neighboring blocks and set a min and max partition size based on
2855
// what they chose.
2856
static void rd_auto_partition_range(VP9_COMP *cpi, const TileInfo *const tile,
2857
                                    MACROBLOCKD *const xd, int mi_row,
2858
                                    int mi_col, BLOCK_SIZE *min_block_size,
2859
0
                                    BLOCK_SIZE *max_block_size) {
2860
0
  VP9_COMMON *const cm = &cpi->common;
2861
0
  MODE_INFO **mi = xd->mi;
2862
0
  const int left_in_image = !!xd->left_mi;
2863
0
  const int above_in_image = !!xd->above_mi;
2864
0
  const int row8x8_remaining = tile->mi_row_end - mi_row;
2865
0
  const int col8x8_remaining = tile->mi_col_end - mi_col;
2866
0
  int bh, bw;
2867
0
  BLOCK_SIZE min_size = BLOCK_4X4;
2868
0
  BLOCK_SIZE max_size = BLOCK_64X64;
2869
0
  int bs_hist[BLOCK_SIZES] = { 0 };
2870
2871
  // Trap case where we do not have a prediction.
2872
0
  if (left_in_image || above_in_image || cm->frame_type != KEY_FRAME) {
2873
    // Default "min to max" and "max to min"
2874
0
    min_size = BLOCK_64X64;
2875
0
    max_size = BLOCK_4X4;
2876
2877
    // NOTE: each call to get_sb_partition_size_range() uses the previous
2878
    // passed in values for min and max as a starting point.
2879
    // Find the min and max partition used in previous frame at this location
2880
0
    if (cm->frame_type != KEY_FRAME &&
2881
0
        (cm->width == cm->last_width && cm->height == cm->last_height)) {
2882
0
      MODE_INFO **prev_mi =
2883
0
          &cm->prev_mi_grid_visible[mi_row * xd->mi_stride + mi_col];
2884
0
      get_sb_partition_size_range(xd, prev_mi, &min_size, &max_size, bs_hist);
2885
0
    }
2886
    // Find the min and max partition sizes used in the left SB64
2887
0
    if (left_in_image) {
2888
0
      MODE_INFO **left_sb64_mi = &mi[-MI_BLOCK_SIZE];
2889
0
      get_sb_partition_size_range(xd, left_sb64_mi, &min_size, &max_size,
2890
0
                                  bs_hist);
2891
0
    }
2892
    // Find the min and max partition sizes used in the above SB64.
2893
0
    if (above_in_image) {
2894
0
      MODE_INFO **above_sb64_mi = &mi[-xd->mi_stride * MI_BLOCK_SIZE];
2895
0
      get_sb_partition_size_range(xd, above_sb64_mi, &min_size, &max_size,
2896
0
                                  bs_hist);
2897
0
    }
2898
2899
    // Adjust observed min and max for "relaxed" auto partition case.
2900
0
    if (cpi->sf.auto_min_max_partition_size == RELAXED_NEIGHBORING_MIN_MAX) {
2901
0
      min_size = min_partition_size[min_size];
2902
0
      max_size = max_partition_size[max_size];
2903
0
    }
2904
0
  }
2905
2906
  // Check border cases where max and min from neighbors may not be legal.
2907
0
  max_size = find_partition_size(max_size, row8x8_remaining, col8x8_remaining,
2908
0
                                 &bh, &bw);
2909
  // Test for blocks at the edge of the active image.
2910
  // This may be the actual edge of the image or where there are formatting
2911
  // bars.
2912
0
  if (vp9_active_edge_sb(cpi, mi_row, mi_col)) {
2913
0
    min_size = BLOCK_4X4;
2914
0
  } else {
2915
0
    min_size =
2916
0
        VPXMIN(cpi->sf.rd_auto_partition_min_limit, VPXMIN(min_size, max_size));
2917
0
  }
2918
2919
  // When use_square_partition_only is true, make sure at least one square
2920
  // partition is allowed by selecting the next smaller square size as
2921
  // *min_block_size.
2922
0
  if (cpi->sf.use_square_partition_only &&
2923
0
      next_square_size[max_size] < min_size) {
2924
0
    min_size = next_square_size[max_size];
2925
0
  }
2926
2927
0
  *min_block_size = min_size;
2928
0
  *max_block_size = max_size;
2929
0
}
2930
2931
// TODO(jingning) refactor functions setting partition search range
2932
static void set_partition_range(VP9_COMMON *cm, MACROBLOCKD *xd, int mi_row,
2933
                                int mi_col, BLOCK_SIZE bsize,
2934
0
                                BLOCK_SIZE *min_bs, BLOCK_SIZE *max_bs) {
2935
0
  int mi_width = num_8x8_blocks_wide_lookup[bsize];
2936
0
  int mi_height = num_8x8_blocks_high_lookup[bsize];
2937
0
  int idx, idy;
2938
0
  BLOCK_SIZE bs, min_size, max_size;
2939
2940
0
  min_size = BLOCK_64X64;
2941
0
  max_size = BLOCK_4X4;
2942
2943
0
  if (cm->width != cm->last_width || cm->height != cm->last_height) {
2944
0
    *min_bs = min_size;
2945
0
    *max_bs = max_size;
2946
0
    return;
2947
0
  }
2948
2949
0
  MODE_INFO *mi;
2950
0
  const int idx_str = cm->mi_stride * mi_row + mi_col;
2951
0
  MODE_INFO **prev_mi = &cm->prev_mi_grid_visible[idx_str];
2952
2953
0
  for (idy = 0; idy < mi_height; ++idy) {
2954
0
    for (idx = 0; idx < mi_width; ++idx) {
2955
0
      mi = prev_mi[idy * cm->mi_stride + idx];
2956
0
      bs = mi ? mi->sb_type : bsize;
2957
0
      min_size = VPXMIN(min_size, bs);
2958
0
      max_size = VPXMAX(max_size, bs);
2959
0
    }
2960
0
  }
2961
2962
0
  if (xd->left_mi) {
2963
0
    for (idy = 0; idy < mi_height; ++idy) {
2964
0
      mi = xd->mi[idy * cm->mi_stride - 1];
2965
0
      bs = mi ? mi->sb_type : bsize;
2966
0
      min_size = VPXMIN(min_size, bs);
2967
0
      max_size = VPXMAX(max_size, bs);
2968
0
    }
2969
0
  }
2970
2971
0
  if (xd->above_mi) {
2972
0
    for (idx = 0; idx < mi_width; ++idx) {
2973
0
      mi = xd->mi[idx - cm->mi_stride];
2974
0
      bs = mi ? mi->sb_type : bsize;
2975
0
      min_size = VPXMIN(min_size, bs);
2976
0
      max_size = VPXMAX(max_size, bs);
2977
0
    }
2978
0
  }
2979
2980
0
  if (min_size == max_size) {
2981
0
    min_size = min_partition_size[min_size];
2982
0
    max_size = max_partition_size[max_size];
2983
0
  }
2984
2985
0
  *min_bs = min_size;
2986
0
  *max_bs = max_size;
2987
0
}
2988
#endif  // !CONFIG_REALTIME_ONLY
2989
2990
6.78M
static INLINE void store_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
2991
6.78M
  memcpy(ctx->pred_mv, x->pred_mv, sizeof(x->pred_mv));
2992
6.78M
}
2993
2994
8.44M
static INLINE void load_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
2995
8.44M
  memcpy(x->pred_mv, ctx->pred_mv, sizeof(x->pred_mv));
2996
8.44M
}
2997
2998
// Calculate prediction based on the given input features and neural net config.
2999
// Assume there are no more than NN_MAX_NODES_PER_LAYER nodes in each hidden
3000
// layer.
3001
static void nn_predict(const float *features, const NN_CONFIG *nn_config,
3002
1.54M
                       float *output) {
3003
1.54M
  int num_input_nodes = nn_config->num_inputs;
3004
1.54M
  int buf_index = 0;
3005
1.54M
  float buf[2][NN_MAX_NODES_PER_LAYER];
3006
1.54M
  const float *input_nodes = features;
3007
3008
  // Propagate hidden layers.
3009
1.54M
  const int num_layers = nn_config->num_hidden_layers;
3010
1.54M
  int layer, node, i;
3011
1.54M
  assert(num_layers <= NN_MAX_HIDDEN_LAYERS);
3012
3.09M
  for (layer = 0; layer < num_layers; ++layer) {
3013
1.54M
    const float *weights = nn_config->weights[layer];
3014
1.54M
    const float *bias = nn_config->bias[layer];
3015
1.54M
    float *output_nodes = buf[buf_index];
3016
1.54M
    const int num_output_nodes = nn_config->num_hidden_nodes[layer];
3017
1.54M
    assert(num_output_nodes < NN_MAX_NODES_PER_LAYER);
3018
15.6M
    for (node = 0; node < num_output_nodes; ++node) {
3019
14.1M
      float val = 0.0f;
3020
169M
      for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3021
14.1M
      val += bias[node];
3022
      // ReLU as activation function.
3023
14.1M
      val = VPXMAX(val, 0.0f);
3024
14.1M
      output_nodes[node] = val;
3025
14.1M
      weights += num_input_nodes;
3026
14.1M
    }
3027
1.54M
    num_input_nodes = num_output_nodes;
3028
1.54M
    input_nodes = output_nodes;
3029
1.54M
    buf_index = 1 - buf_index;
3030
1.54M
  }
3031
3032
  // Final output layer.
3033
1.54M
  {
3034
1.54M
    const float *weights = nn_config->weights[num_layers];
3035
3.74M
    for (node = 0; node < nn_config->num_outputs; ++node) {
3036
2.19M
      const float *bias = nn_config->bias[num_layers];
3037
2.19M
      float val = 0.0f;
3038
26.7M
      for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3039
2.19M
      output[node] = val + bias[node];
3040
2.19M
      weights += num_input_nodes;
3041
2.19M
    }
3042
1.54M
  }
3043
1.54M
}
3044
3045
#if !CONFIG_REALTIME_ONLY
3046
0
#define FEATURES 7
3047
// Machine-learning based partition search early termination.
3048
// Return 1 to skip split and rect partitions.
3049
static int ml_pruning_partition(VP9_COMMON *const cm, MACROBLOCKD *const xd,
3050
                                PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
3051
0
                                BLOCK_SIZE bsize) {
3052
0
  const int mag_mv =
3053
0
      abs(ctx->mic.mv[0].as_mv.col) + abs(ctx->mic.mv[0].as_mv.row);
3054
0
  const int left_in_image = !!xd->left_mi;
3055
0
  const int above_in_image = !!xd->above_mi;
3056
0
  int above_par = 0;  // above_partitioning
3057
0
  int left_par = 0;   // left_partitioning
3058
0
  int last_par = 0;   // last_partitioning
3059
0
  int offset = 0;
3060
0
  int i;
3061
0
  BLOCK_SIZE context_size;
3062
0
  const NN_CONFIG *nn_config = NULL;
3063
0
  const float *mean, *sd, *linear_weights;
3064
0
  float nn_score, linear_score;
3065
0
  float features[FEATURES];
3066
3067
0
  assert(b_width_log2_lookup[bsize] == b_height_log2_lookup[bsize]);
3068
0
  vpx_clear_system_state();
3069
3070
0
  switch (bsize) {
3071
0
    case BLOCK_64X64:
3072
0
      offset = 0;
3073
0
      nn_config = &vp9_partition_nnconfig_64x64;
3074
0
      break;
3075
0
    case BLOCK_32X32:
3076
0
      offset = 8;
3077
0
      nn_config = &vp9_partition_nnconfig_32x32;
3078
0
      break;
3079
0
    case BLOCK_16X16:
3080
0
      offset = 16;
3081
0
      nn_config = &vp9_partition_nnconfig_16x16;
3082
0
      break;
3083
0
    default: assert(0 && "Unexpected block size."); return 0;
3084
0
  }
3085
3086
0
  if (above_in_image) {
3087
0
    context_size = xd->above_mi->sb_type;
3088
0
    if (context_size < bsize)
3089
0
      above_par = 2;
3090
0
    else if (context_size == bsize)
3091
0
      above_par = 1;
3092
0
  }
3093
3094
0
  if (left_in_image) {
3095
0
    context_size = xd->left_mi->sb_type;
3096
0
    if (context_size < bsize)
3097
0
      left_par = 2;
3098
0
    else if (context_size == bsize)
3099
0
      left_par = 1;
3100
0
  }
3101
3102
0
  if (cm->width == cm->last_width && cm->height == cm->last_height) {
3103
0
    MODE_INFO **prev_mi =
3104
0
        &cm->prev_mi_grid_visible[mi_col + cm->mi_stride * mi_row];
3105
0
    if (prev_mi[0]) {
3106
0
      context_size = prev_mi[0]->sb_type;
3107
0
      if (context_size < bsize)
3108
0
        last_par = 2;
3109
0
      else if (context_size == bsize)
3110
0
        last_par = 1;
3111
0
    }
3112
0
  }
3113
3114
0
  mean = &vp9_partition_feature_mean[offset];
3115
0
  sd = &vp9_partition_feature_std[offset];
3116
0
  features[0] = ((float)ctx->rate - mean[0]) / sd[0];
3117
0
  features[1] = ((float)ctx->dist - mean[1]) / sd[1];
3118
0
  features[2] = ((float)mag_mv / 2 - mean[2]) * sd[2];
3119
0
  features[3] = ((float)(left_par + above_par) / 2 - mean[3]) * sd[3];
3120
0
  features[4] = ((float)ctx->sum_y_eobs - mean[4]) / sd[4];
3121
0
  features[5] = ((float)cm->base_qindex - mean[5]) * sd[5];
3122
0
  features[6] = ((float)last_par - mean[6]) * sd[6];
3123
3124
  // Predict using linear model.
3125
0
  linear_weights = &vp9_partition_linear_weights[offset];
3126
0
  linear_score = linear_weights[FEATURES];
3127
0
  for (i = 0; i < FEATURES; ++i)
3128
0
    linear_score += linear_weights[i] * features[i];
3129
0
  if (linear_score > 0.1f) return 0;
3130
3131
  // Predict using neural net model.
3132
0
  nn_predict(features, nn_config, &nn_score);
3133
3134
0
  if (linear_score < -0.0f && nn_score < 0.1f) return 1;
3135
0
  if (nn_score < -0.0f && linear_score < 0.1f) return 1;
3136
0
  return 0;
3137
0
}
3138
#undef FEATURES
3139
3140
196k
#define FEATURES 4
3141
// ML-based partition search breakout.
3142
static int ml_predict_breakout(VP9_COMP *const cpi, BLOCK_SIZE bsize,
3143
                               const MACROBLOCK *const x,
3144
32.7k
                               const RD_COST *const rd_cost) {
3145
32.7k
  DECLARE_ALIGNED(16, static const uint8_t, vp9_64_zeros[64]) = { 0 };
3146
32.7k
  const VP9_COMMON *const cm = &cpi->common;
3147
32.7k
  float features[FEATURES];
3148
32.7k
  const float *linear_weights = NULL;  // Linear model weights.
3149
32.7k
  float linear_score = 0.0f;
3150
32.7k
  const int qindex = cm->base_qindex;
3151
32.7k
  const int q_ctx = qindex >= 200 ? 0 : (qindex >= 150 ? 1 : 2);
3152
32.7k
  const int is_720p_or_larger = VPXMIN(cm->width, cm->height) >= 720;
3153
32.7k
  const int resolution_ctx = is_720p_or_larger ? 1 : 0;
3154
3155
32.7k
  switch (bsize) {
3156
169
    case BLOCK_64X64:
3157
169
      linear_weights = vp9_partition_breakout_weights_64[resolution_ctx][q_ctx];
3158
169
      break;
3159
470
    case BLOCK_32X32:
3160
470
      linear_weights = vp9_partition_breakout_weights_32[resolution_ctx][q_ctx];
3161
470
      break;
3162
4.10k
    case BLOCK_16X16:
3163
4.10k
      linear_weights = vp9_partition_breakout_weights_16[resolution_ctx][q_ctx];
3164
4.10k
      break;
3165
27.9k
    case BLOCK_8X8:
3166
27.9k
      linear_weights = vp9_partition_breakout_weights_8[resolution_ctx][q_ctx];
3167
27.9k
      break;
3168
0
    default: assert(0 && "Unexpected block size."); return 0;
3169
32.7k
  }
3170
32.7k
  if (!linear_weights) return 0;
3171
3172
32.7k
  {  // Generate feature values.
3173
32.7k
#if CONFIG_VP9_HIGHBITDEPTH
3174
32.7k
    const int ac_q =
3175
32.7k
        vp9_ac_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3176
#else
3177
    const int ac_q = vp9_ac_quant(qindex, 0, cm->bit_depth);
3178
#endif  // CONFIG_VP9_HIGHBITDEPTH
3179
32.7k
    const int num_pels_log2 = num_pels_log2_lookup[bsize];
3180
32.7k
    int feature_index = 0;
3181
32.7k
    unsigned int var, sse;
3182
32.7k
    float rate_f, dist_f;
3183
3184
32.7k
#if CONFIG_VP9_HIGHBITDEPTH
3185
32.7k
    if (x->e_mbd.cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
3186
0
      var =
3187
0
          vp9_high_get_sby_variance(cpi, &x->plane[0].src, bsize, x->e_mbd.bd);
3188
32.7k
    } else {
3189
32.7k
      var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3190
32.7k
                                  vp9_64_zeros, 0, &sse);
3191
32.7k
    }
3192
#else
3193
    var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3194
                                vp9_64_zeros, 0, &sse);
3195
#endif
3196
32.7k
    var = var >> num_pels_log2;
3197
3198
32.7k
    vpx_clear_system_state();
3199
3200
32.7k
    rate_f = (float)VPXMIN(rd_cost->rate, INT_MAX);
3201
32.7k
    dist_f = (float)(VPXMIN(rd_cost->dist, INT_MAX) >> num_pels_log2);
3202
32.7k
    rate_f =
3203
32.7k
        ((float)x->rdmult / 128.0f / 512.0f / (float)(1 << num_pels_log2)) *
3204
32.7k
        rate_f;
3205
3206
32.7k
    features[feature_index++] = rate_f;
3207
32.7k
    features[feature_index++] = dist_f;
3208
32.7k
    features[feature_index++] = (float)var;
3209
32.7k
    features[feature_index++] = (float)ac_q;
3210
32.7k
    assert(feature_index == FEATURES);
3211
32.7k
  }
3212
3213
32.7k
  {  // Calculate the output score.
3214
32.7k
    int i;
3215
32.7k
    linear_score = linear_weights[FEATURES];
3216
163k
    for (i = 0; i < FEATURES; ++i)
3217
130k
      linear_score += linear_weights[i] * features[i];
3218
32.7k
  }
3219
3220
32.7k
  return linear_score >= cpi->sf.rd_ml_partition.search_breakout_thresh[q_ctx];
3221
32.7k
}
3222
#undef FEATURES
3223
3224
#define FEATURES 8
3225
2.15M
#define LABELS 4
3226
static void ml_prune_rect_partition(VP9_COMP *const cpi, MACROBLOCK *const x,
3227
                                    BLOCK_SIZE bsize,
3228
                                    const PC_TREE *const pc_tree,
3229
                                    int *allow_horz, int *allow_vert,
3230
346k
                                    int64_t ref_rd) {
3231
346k
  const NN_CONFIG *nn_config = NULL;
3232
346k
  float score[LABELS] = {
3233
346k
    0.0f,
3234
346k
  };
3235
346k
  int thresh = -1;
3236
346k
  int i;
3237
346k
  (void)x;
3238
3239
346k
  if (ref_rd <= 0 || ref_rd > 1000000000) return;
3240
3241
303k
  switch (bsize) {
3242
0
    case BLOCK_8X8: break;
3243
249k
    case BLOCK_16X16:
3244
249k
      nn_config = &vp9_rect_part_nnconfig_16;
3245
249k
      thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[1];
3246
249k
      break;
3247
45.5k
    case BLOCK_32X32:
3248
45.5k
      nn_config = &vp9_rect_part_nnconfig_32;
3249
45.5k
      thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[2];
3250
45.5k
      break;
3251
8.47k
    case BLOCK_64X64:
3252
8.47k
      nn_config = &vp9_rect_part_nnconfig_64;
3253
8.47k
      thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[3];
3254
8.47k
      break;
3255
0
    default: assert(0 && "Unexpected block size."); return;
3256
303k
  }
3257
303k
  if (!nn_config || thresh < 0) return;
3258
3259
  // Feature extraction and model score calculation.
3260
215k
  {
3261
215k
    const VP9_COMMON *const cm = &cpi->common;
3262
215k
#if CONFIG_VP9_HIGHBITDEPTH
3263
215k
    const int dc_q =
3264
215k
        vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3265
#else
3266
    const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3267
#endif  // CONFIG_VP9_HIGHBITDEPTH
3268
215k
    const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3269
215k
    int feature_index = 0;
3270
215k
    float features[FEATURES];
3271
3272
215k
    features[feature_index++] = logf((float)dc_q + 1.0f);
3273
215k
    features[feature_index++] =
3274
215k
        (float)(pc_tree->partitioning == PARTITION_NONE);
3275
215k
    features[feature_index++] = logf((float)ref_rd / bs / bs + 1.0f);
3276
3277
215k
    {
3278
215k
      const float norm_factor = 1.0f / ((float)ref_rd + 1.0f);
3279
215k
      const int64_t none_rdcost = pc_tree->none.rdcost;
3280
215k
      float rd_ratio = 2.0f;
3281
215k
      if (none_rdcost > 0 && none_rdcost < 1000000000)
3282
196k
        rd_ratio = (float)none_rdcost * norm_factor;
3283
215k
      features[feature_index++] = VPXMIN(rd_ratio, 2.0f);
3284
3285
1.07M
      for (i = 0; i < 4; ++i) {
3286
860k
        const int64_t this_rd = pc_tree->u.split[i]->none.rdcost;
3287
860k
        const int rd_valid = this_rd > 0 && this_rd < 1000000000;
3288
        // Ratio between sub-block RD and whole block RD.
3289
860k
        features[feature_index++] =
3290
860k
            rd_valid ? (float)this_rd * norm_factor : 1.0f;
3291
860k
      }
3292
215k
    }
3293
3294
215k
    assert(feature_index == FEATURES);
3295
215k
    nn_predict(features, nn_config, score);
3296
215k
  }
3297
3298
  // Make decisions based on the model score.
3299
215k
  {
3300
215k
    int max_score = -1000;
3301
215k
    int horz = 0, vert = 0;
3302
215k
    int int_score[LABELS];
3303
1.07M
    for (i = 0; i < LABELS; ++i) {
3304
860k
      int_score[i] = (int)(100 * score[i]);
3305
860k
      max_score = VPXMAX(int_score[i], max_score);
3306
860k
    }
3307
215k
    thresh = max_score - thresh;
3308
1.07M
    for (i = 0; i < LABELS; ++i) {
3309
860k
      if (int_score[i] >= thresh) {
3310
374k
        if ((i >> 0) & 1) horz = 1;
3311
374k
        if ((i >> 1) & 1) vert = 1;
3312
374k
      }
3313
860k
    }
3314
215k
    *allow_horz = *allow_horz && horz;
3315
215k
    *allow_vert = *allow_vert && vert;
3316
215k
  }
3317
215k
}
3318
#undef FEATURES
3319
#undef LABELS
3320
3321
// Perform fast and coarse motion search for the given block. This is a
3322
// pre-processing step for the ML based partition search speedup.
3323
static void simple_motion_search(const VP9_COMP *const cpi, MACROBLOCK *const x,
3324
                                 BLOCK_SIZE bsize, int mi_row, int mi_col,
3325
                                 MV ref_mv, MV_REFERENCE_FRAME ref,
3326
1.33M
                                 uint8_t *const pred_buf) {
3327
1.33M
  const VP9_COMMON *const cm = &cpi->common;
3328
1.33M
  MACROBLOCKD *const xd = &x->e_mbd;
3329
1.33M
  MODE_INFO *const mi = xd->mi[0];
3330
1.33M
  YV12_BUFFER_CONFIG *yv12;
3331
1.33M
  YV12_BUFFER_CONFIG *scaled_ref_frame = vp9_get_scaled_ref_frame(cpi, ref);
3332
1.33M
  const int step_param = 1;
3333
1.33M
  const MvLimits tmp_mv_limits = x->mv_limits;
3334
1.33M
  const SEARCH_METHODS search_method = NSTEP;
3335
1.33M
  const int sadpb = x->sadperbit16;
3336
1.33M
  MV ref_mv_full = { ref_mv.row >> 3, ref_mv.col >> 3 };
3337
1.33M
  MV best_mv = { 0, 0 };
3338
1.33M
  int cost_list[5];
3339
1.33M
  struct buf_2d backup_pre[MAX_MB_PLANE] = { { 0, 0 } };
3340
3341
1.33M
  if (scaled_ref_frame) {
3342
0
    yv12 = scaled_ref_frame;
3343
    // As reported in b/311294795, the reference buffer pointer needs to be
3344
    // saved and restored after the search. Otherwise, it causes problems while
3345
    // the reference frame scaling happens.
3346
0
    for (int i = 0; i < MAX_MB_PLANE; i++) backup_pre[i] = xd->plane[i].pre[0];
3347
1.33M
  } else {
3348
1.33M
    yv12 = get_ref_frame_buffer(cpi, ref);
3349
1.33M
  }
3350
3351
1.33M
  assert(yv12 != NULL);
3352
1.33M
  if (!yv12) return;
3353
1.33M
  vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col, NULL);
3354
1.33M
  mi->ref_frame[0] = ref;
3355
1.33M
  mi->ref_frame[1] = NO_REF_FRAME;
3356
1.33M
  mi->sb_type = bsize;
3357
1.33M
  vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
3358
1.33M
  vp9_full_pixel_search(cpi, x, bsize, &ref_mv_full, step_param, search_method,
3359
1.33M
                        sadpb, cond_cost_list(cpi, cost_list), &ref_mv,
3360
1.33M
                        &best_mv, 0, 0);
3361
1.33M
  best_mv.row *= 8;
3362
1.33M
  best_mv.col *= 8;
3363
1.33M
  x->mv_limits = tmp_mv_limits;
3364
1.33M
  mi->mv[0].as_mv = best_mv;
3365
3366
  // Restore reference buffer pointer.
3367
1.33M
  if (scaled_ref_frame) {
3368
0
    for (int i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_pre[i];
3369
0
  }
3370
3371
1.33M
  set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
3372
1.33M
  xd->plane[0].dst.buf = pred_buf;
3373
1.33M
  xd->plane[0].dst.stride = 64;
3374
1.33M
  vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
3375
1.33M
}
3376
3377
// Use a neural net model to prune partition-none and partition-split search.
3378
// Features used: QP; spatial block size contexts; variance of prediction
3379
// residue after simple_motion_search.
3380
#define FEATURES 12
3381
static void ml_predict_var_rd_partitioning(const VP9_COMP *const cpi,
3382
                                           MACROBLOCK *const x,
3383
                                           PC_TREE *const pc_tree,
3384
                                           BLOCK_SIZE bsize, int mi_row,
3385
1.33M
                                           int mi_col, int *none, int *split) {
3386
1.33M
  const VP9_COMMON *const cm = &cpi->common;
3387
1.33M
  const NN_CONFIG *nn_config = NULL;
3388
1.33M
  const MACROBLOCKD *const xd = &x->e_mbd;
3389
1.33M
#if CONFIG_VP9_HIGHBITDEPTH
3390
1.33M
  DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64 * 2]);
3391
1.33M
  uint8_t *const pred_buf = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
3392
1.33M
                                ? (CONVERT_TO_BYTEPTR(pred_buffer))
3393
1.33M
                                : pred_buffer;
3394
#else
3395
  DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64]);
3396
  uint8_t *const pred_buf = pred_buffer;
3397
#endif  // CONFIG_VP9_HIGHBITDEPTH
3398
1.33M
  const int speed = cpi->oxcf.speed;
3399
1.33M
  float thresh = 0.0f;
3400
3401
1.33M
  switch (bsize) {
3402
0
    case BLOCK_64X64:
3403
0
      nn_config = &vp9_part_split_nnconfig_64;
3404
0
      thresh = speed > 0 ? 2.8f : 3.0f;
3405
0
      break;
3406
41.6k
    case BLOCK_32X32:
3407
41.6k
      nn_config = &vp9_part_split_nnconfig_32;
3408
41.6k
      thresh = speed > 0 ? 3.5f : 3.0f;
3409
41.6k
      break;
3410
195k
    case BLOCK_16X16:
3411
195k
      nn_config = &vp9_part_split_nnconfig_16;
3412
195k
      thresh = speed > 0 ? 3.8f : 4.0f;
3413
195k
      break;
3414
1.09M
    case BLOCK_8X8:
3415
1.09M
      nn_config = &vp9_part_split_nnconfig_8;
3416
1.09M
      if (cm->width >= 720 && cm->height >= 720)
3417
0
        thresh = speed > 0 ? 2.5f : 2.0f;
3418
1.09M
      else
3419
1.09M
        thresh = speed > 0 ? 3.8f : 2.0f;
3420
1.09M
      break;
3421
0
    default: assert(0 && "Unexpected block size."); return;
3422
1.33M
  }
3423
3424
1.33M
  if (!nn_config) return;
3425
3426
  // Do a simple single motion search to find a prediction for current block.
3427
  // The variance of the residue will be used as input features.
3428
1.33M
  {
3429
1.33M
    MV ref_mv;
3430
1.33M
    const MV_REFERENCE_FRAME ref =
3431
1.33M
        cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME : LAST_FRAME;
3432
    // If bsize is 64x64, use zero MV as reference; otherwise, use MV result
3433
    // of previous(larger) block as reference.
3434
1.33M
    if (bsize == BLOCK_64X64)
3435
0
      ref_mv.row = ref_mv.col = 0;
3436
1.33M
    else
3437
1.33M
      ref_mv = pc_tree->mv;
3438
1.33M
    vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
3439
1.33M
    simple_motion_search(cpi, x, bsize, mi_row, mi_col, ref_mv, ref, pred_buf);
3440
1.33M
    pc_tree->mv = x->e_mbd.mi[0]->mv[0].as_mv;
3441
1.33M
  }
3442
3443
1.33M
  vpx_clear_system_state();
3444
3445
1.33M
  {
3446
1.33M
    float features[FEATURES] = { 0.0f };
3447
1.33M
#if CONFIG_VP9_HIGHBITDEPTH
3448
1.33M
    const int dc_q =
3449
1.33M
        vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (xd->bd - 8);
3450
#else
3451
    const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3452
#endif  // CONFIG_VP9_HIGHBITDEPTH
3453
1.33M
    int feature_idx = 0;
3454
1.33M
    float score;
3455
3456
    // Generate model input features.
3457
1.33M
    features[feature_idx++] = logf((float)dc_q + 1.0f);
3458
3459
    // Get the variance of the residue as input features.
3460
1.33M
    {
3461
1.33M
      const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3462
1.33M
      const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
3463
1.33M
      const uint8_t *pred = pred_buf;
3464
1.33M
      const uint8_t *src = x->plane[0].src.buf;
3465
1.33M
      const int src_stride = x->plane[0].src.stride;
3466
1.33M
      const int pred_stride = 64;
3467
1.33M
      unsigned int sse;
3468
      // Variance of whole block.
3469
1.33M
      const unsigned int var =
3470
1.33M
          cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
3471
1.33M
      const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
3472
1.33M
      const int has_above = !!xd->above_mi;
3473
1.33M
      const int has_left = !!xd->left_mi;
3474
1.33M
      const BLOCK_SIZE above_bsize = has_above ? xd->above_mi->sb_type : bsize;
3475
1.33M
      const BLOCK_SIZE left_bsize = has_left ? xd->left_mi->sb_type : bsize;
3476
1.33M
      int i;
3477
3478
1.33M
      features[feature_idx++] = (float)has_above;
3479
1.33M
      features[feature_idx++] = (float)b_width_log2_lookup[above_bsize];
3480
1.33M
      features[feature_idx++] = (float)b_height_log2_lookup[above_bsize];
3481
1.33M
      features[feature_idx++] = (float)has_left;
3482
1.33M
      features[feature_idx++] = (float)b_width_log2_lookup[left_bsize];
3483
1.33M
      features[feature_idx++] = (float)b_height_log2_lookup[left_bsize];
3484
1.33M
      features[feature_idx++] = logf((float)var + 1.0f);
3485
6.67M
      for (i = 0; i < 4; ++i) {
3486
5.33M
        const int x_idx = (i & 1) * bs / 2;
3487
5.33M
        const int y_idx = (i >> 1) * bs / 2;
3488
5.33M
        const int src_offset = y_idx * src_stride + x_idx;
3489
5.33M
        const int pred_offset = y_idx * pred_stride + x_idx;
3490
        // Variance of quarter block.
3491
5.33M
        const unsigned int sub_var =
3492
5.33M
            cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
3493
5.33M
                                    pred + pred_offset, pred_stride, &sse);
3494
5.33M
        const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
3495
5.33M
        features[feature_idx++] = var_ratio;
3496
5.33M
      }
3497
1.33M
    }
3498
1.33M
    assert(feature_idx == FEATURES);
3499
3500
    // Feed the features into the model to get the confidence score.
3501
1.33M
    nn_predict(features, nn_config, &score);
3502
3503
    // Higher score means that the model has higher confidence that the split
3504
    // partition is better than the non-split partition. So if the score is
3505
    // high enough, we skip the none-split partition search; if the score is
3506
    // low enough, we skip the split partition search.
3507
1.33M
    if (score > thresh) *none = 0;
3508
1.33M
    if (score < -thresh) *split = 0;
3509
1.33M
  }
3510
1.33M
}
3511
#undef FEATURES
3512
#endif  // !CONFIG_REALTIME_ONLY
3513
3514
0
static double log_wiener_var(int64_t wiener_variance) {
3515
0
  return log(1.0 + wiener_variance) / log(2.0);
3516
0
}
3517
3518
0
static void build_kmeans_segmentation(VP9_COMP *cpi) {
3519
0
  VP9_COMMON *cm = &cpi->common;
3520
0
  BLOCK_SIZE bsize = BLOCK_64X64;
3521
0
  KMEANS_DATA *kmeans_data;
3522
3523
0
  vp9_disable_segmentation(&cm->seg);
3524
0
  if (cm->show_frame) {
3525
0
    int mi_row, mi_col;
3526
0
    cpi->kmeans_data_size = 0;
3527
0
    cpi->kmeans_ctr_num = 8;
3528
3529
0
    for (mi_row = 0; mi_row < cm->mi_rows; mi_row += MI_BLOCK_SIZE) {
3530
0
      for (mi_col = 0; mi_col < cm->mi_cols; mi_col += MI_BLOCK_SIZE) {
3531
0
        int mb_row_start = mi_row >> 1;
3532
0
        int mb_col_start = mi_col >> 1;
3533
0
        int mb_row_end = VPXMIN(
3534
0
            (mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3535
0
        int mb_col_end = VPXMIN(
3536
0
            (mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3537
0
        int row, col;
3538
0
        int64_t wiener_variance = 0;
3539
3540
0
        for (row = mb_row_start; row < mb_row_end; ++row)
3541
0
          for (col = mb_col_start; col < mb_col_end; ++col)
3542
0
            wiener_variance += cpi->mb_wiener_variance[row * cm->mb_cols + col];
3543
3544
0
        wiener_variance /=
3545
0
            (mb_row_end - mb_row_start) * (mb_col_end - mb_col_start);
3546
3547
0
#if CONFIG_MULTITHREAD
3548
0
        pthread_mutex_lock(&cpi->kmeans_mutex);
3549
0
#endif  // CONFIG_MULTITHREAD
3550
3551
0
        kmeans_data = &cpi->kmeans_data_arr[cpi->kmeans_data_size++];
3552
0
        kmeans_data->value = log_wiener_var(wiener_variance);
3553
0
        kmeans_data->pos = mi_row * cpi->kmeans_data_stride + mi_col;
3554
0
#if CONFIG_MULTITHREAD
3555
0
        pthread_mutex_unlock(&cpi->kmeans_mutex);
3556
0
#endif  // CONFIG_MULTITHREAD
3557
0
      }
3558
0
    }
3559
3560
0
    vp9_kmeans(cpi->kmeans_ctr_ls, cpi->kmeans_boundary_ls,
3561
0
               cpi->kmeans_count_ls, cpi->kmeans_ctr_num, cpi->kmeans_data_arr,
3562
0
               cpi->kmeans_data_size);
3563
3564
0
    vp9_perceptual_aq_mode_setup(cpi, &cm->seg);
3565
0
  }
3566
0
}
3567
3568
#if !CONFIG_REALTIME_ONLY
3569
static int wiener_var_segment(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3570
0
                              int mi_col) {
3571
0
  VP9_COMMON *cm = &cpi->common;
3572
0
  int mb_row_start = mi_row >> 1;
3573
0
  int mb_col_start = mi_col >> 1;
3574
0
  int mb_row_end =
3575
0
      VPXMIN((mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3576
0
  int mb_col_end =
3577
0
      VPXMIN((mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3578
0
  int row, col, idx;
3579
0
  int64_t wiener_variance = 0;
3580
0
  int segment_id;
3581
0
  int8_t seg_hist[MAX_SEGMENTS] = { 0 };
3582
0
  int8_t max_count = 0, max_index = -1;
3583
3584
0
  vpx_clear_system_state();
3585
3586
0
  assert(cpi->norm_wiener_variance > 0);
3587
3588
0
  for (row = mb_row_start; row < mb_row_end; ++row) {
3589
0
    for (col = mb_col_start; col < mb_col_end; ++col) {
3590
0
      wiener_variance = cpi->mb_wiener_variance[row * cm->mb_cols + col];
3591
0
      segment_id =
3592
0
          vp9_get_group_idx(log_wiener_var(wiener_variance),
3593
0
                            cpi->kmeans_boundary_ls, cpi->kmeans_ctr_num);
3594
0
      ++seg_hist[segment_id];
3595
0
    }
3596
0
  }
3597
3598
0
  for (idx = 0; idx < cpi->kmeans_ctr_num; ++idx) {
3599
0
    if (seg_hist[idx] > max_count) {
3600
0
      max_count = seg_hist[idx];
3601
0
      max_index = idx;
3602
0
    }
3603
0
  }
3604
3605
0
  assert(max_index >= 0);
3606
0
  segment_id = max_index;
3607
3608
0
  return segment_id;
3609
0
}
3610
3611
static int get_rdmult_delta(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3612
0
                            int mi_col, int orig_rdmult) {
3613
0
  const int gf_group_index = cpi->twopass.gf_group.index;
3614
0
  int64_t intra_cost = 0;
3615
0
  int64_t mc_dep_cost = 0;
3616
0
  int mi_wide = num_8x8_blocks_wide_lookup[bsize];
3617
0
  int mi_high = num_8x8_blocks_high_lookup[bsize];
3618
0
  int row, col;
3619
3620
0
  int dr = 0;
3621
0
  double r0, rk, beta;
3622
3623
0
  TplDepFrame *tpl_frame;
3624
0
  TplDepStats *tpl_stats;
3625
0
  int tpl_stride;
3626
3627
0
  if (gf_group_index >= MAX_ARF_GOP_SIZE) return orig_rdmult;
3628
0
  tpl_frame = &cpi->tpl_stats[gf_group_index];
3629
3630
0
  if (tpl_frame->is_valid == 0) return orig_rdmult;
3631
0
  tpl_stats = tpl_frame->tpl_stats_ptr;
3632
0
  tpl_stride = tpl_frame->stride;
3633
3634
0
  if (cpi->twopass.gf_group.layer_depth[gf_group_index] > 1) return orig_rdmult;
3635
3636
0
  if (cpi->ext_ratectrl.ready &&
3637
0
      (cpi->ext_ratectrl.funcs.rc_type & VPX_RC_QP) != 0 &&
3638
0
      cpi->ext_ratectrl.funcs.get_encodeframe_decision != NULL) {
3639
0
    int sb_size = num_8x8_blocks_wide_lookup[BLOCK_64X64] * MI_SIZE;
3640
0
    int sb_stride = (cpi->common.width + sb_size - 1) / sb_size;
3641
0
    int sby = mi_row / 8;
3642
0
    int sbx = mi_col / 8;
3643
0
    return (int)((cpi->sb_mul_scale[sby * sb_stride + sbx] * orig_rdmult) /
3644
0
                 256);
3645
0
  }
3646
3647
0
  for (row = mi_row; row < mi_row + mi_high; ++row) {
3648
0
    for (col = mi_col; col < mi_col + mi_wide; ++col) {
3649
0
      TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
3650
3651
0
      if (row >= cpi->common.mi_rows || col >= cpi->common.mi_cols) continue;
3652
3653
0
      intra_cost += this_stats->intra_cost;
3654
0
      mc_dep_cost += this_stats->mc_dep_cost;
3655
0
    }
3656
0
  }
3657
3658
0
  vpx_clear_system_state();
3659
3660
0
  r0 = cpi->rd.r0;
3661
0
  rk = (double)intra_cost / mc_dep_cost;
3662
0
  beta = r0 / rk;
3663
0
  dr = vp9_get_adaptive_rdmult(cpi, beta);
3664
3665
0
  dr = clamp(dr, orig_rdmult * 1 / 2, orig_rdmult * 3 / 2);
3666
0
  dr = VPXMAX(1, dr);
3667
3668
0
  return dr;
3669
0
}
3670
#endif  // !CONFIG_REALTIME_ONLY
3671
3672
#if !CONFIG_REALTIME_ONLY
3673
// TODO(jingning,jimbankoski,rbultje): properly skip partition types that are
3674
// unlikely to be selected depending on previous rate-distortion optimization
3675
// results, for encoding speed-up.
3676
static int rd_pick_partition(VP9_COMP *cpi, ThreadData *td,
3677
                             TileDataEnc *tile_data, TOKENEXTRA **tp,
3678
                             int mi_row, int mi_col, BLOCK_SIZE bsize,
3679
                             RD_COST *rd_cost, RD_COST best_rdc,
3680
2.87M
                             PC_TREE *pc_tree) {
3681
2.87M
  VP9_COMMON *const cm = &cpi->common;
3682
2.87M
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3683
2.87M
  TileInfo *const tile_info = &tile_data->tile_info;
3684
2.87M
  MACROBLOCK *const x = &td->mb;
3685
2.87M
  MACROBLOCKD *const xd = &x->e_mbd;
3686
2.87M
  const int mi_step = num_8x8_blocks_wide_lookup[bsize] / 2;
3687
2.87M
  ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
3688
2.87M
  PARTITION_CONTEXT sl[8], sa[8];
3689
2.87M
  TOKENEXTRA *tp_orig = *tp;
3690
2.87M
  PICK_MODE_CONTEXT *const ctx = &pc_tree->none;
3691
2.87M
  int i;
3692
2.87M
  const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3693
2.87M
  BLOCK_SIZE subsize;
3694
2.87M
  RD_COST this_rdc, sum_rdc;
3695
2.87M
  int do_split = bsize >= BLOCK_8X8;
3696
2.87M
  int do_rect = 1;
3697
2.87M
  INTERP_FILTER pred_interp_filter;
3698
3699
  // Override skipping rectangular partition operations for edge blocks
3700
2.87M
  const int force_horz_split = (mi_row + mi_step >= cm->mi_rows);
3701
2.87M
  const int force_vert_split = (mi_col + mi_step >= cm->mi_cols);
3702
2.87M
  const int xss = x->e_mbd.plane[1].subsampling_x;
3703
2.87M
  const int yss = x->e_mbd.plane[1].subsampling_y;
3704
3705
2.87M
  BLOCK_SIZE min_size = x->min_partition_size;
3706
2.87M
  BLOCK_SIZE max_size = x->max_partition_size;
3707
3708
2.87M
  int partition_none_allowed = !force_horz_split && !force_vert_split;
3709
2.87M
  int partition_horz_allowed =
3710
2.87M
      !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
3711
2.87M
  int partition_vert_allowed =
3712
2.87M
      !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
3713
3714
2.87M
  int64_t dist_breakout_thr = cpi->sf.partition_search_breakout_thr.dist;
3715
2.87M
  int rate_breakout_thr = cpi->sf.partition_search_breakout_thr.rate;
3716
2.87M
  int must_split = 0;
3717
2.87M
  int should_encode_sb = 0;
3718
3719
  // Ref frames picked in the [i_th] quarter subblock during square partition
3720
  // RD search. It may be used to prune ref frame selection of rect partitions.
3721
2.87M
  uint8_t ref_frames_used[4] = { 0, 0, 0, 0 };
3722
3723
2.87M
  int partition_mul = x->cb_rdmult;
3724
3725
2.87M
  (void)*tp_orig;
3726
3727
2.87M
  assert(num_8x8_blocks_wide_lookup[bsize] ==
3728
2.87M
         num_8x8_blocks_high_lookup[bsize]);
3729
3730
2.87M
  dist_breakout_thr >>=
3731
2.87M
      8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
3732
3733
2.87M
  rate_breakout_thr *= num_pels_log2_lookup[bsize];
3734
3735
2.87M
  vp9_rd_cost_init(&this_rdc);
3736
2.87M
  vp9_rd_cost_init(&sum_rdc);
3737
3738
2.87M
  set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
3739
3740
2.87M
  if (oxcf->tuning == VP8_TUNE_SSIM) {
3741
0
    set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &partition_mul);
3742
0
  }
3743
2.87M
  vp9_rd_cost_update(partition_mul, x->rddiv, &best_rdc);
3744
3745
2.87M
  if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ &&
3746
0
      cpi->oxcf.aq_mode != LOOKAHEAD_AQ)
3747
0
    x->mb_energy = vp9_block_energy(cpi, x, bsize);
3748
3749
2.87M
  if (cpi->sf.cb_partition_search && bsize == BLOCK_16X16) {
3750
0
    int cb_partition_search_ctrl =
3751
0
        ((pc_tree->index == 0 || pc_tree->index == 3) +
3752
0
         get_chessboard_index(cm->current_video_frame)) &
3753
0
        0x1;
3754
3755
0
    if (cb_partition_search_ctrl && bsize > min_size && bsize < max_size)
3756
0
      set_partition_range(cm, xd, mi_row, mi_col, bsize, &min_size, &max_size);
3757
0
  }
3758
3759
  // Get sub block energy range
3760
2.87M
  if (bsize >= BLOCK_16X16) {
3761
1.24M
    int min_energy, max_energy;
3762
1.24M
    vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
3763
1.24M
                             &max_energy);
3764
1.24M
    must_split = (min_energy < -3) && (max_energy - min_energy > 2);
3765
1.24M
  }
3766
3767
  // Determine partition types in search according to the speed features.
3768
  // The threshold set here has to be of square block size.
3769
2.87M
  if (cpi->sf.auto_min_max_partition_size) {
3770
0
    partition_none_allowed &= (bsize <= max_size);
3771
0
    partition_horz_allowed &=
3772
0
        ((bsize <= max_size && bsize > min_size) || force_horz_split);
3773
0
    partition_vert_allowed &=
3774
0
        ((bsize <= max_size && bsize > min_size) || force_vert_split);
3775
0
    do_split &= bsize > min_size;
3776
0
  }
3777
3778
2.87M
  if (cpi->sf.use_square_partition_only &&
3779
1.76M
      (bsize > cpi->sf.use_square_only_thresh_high ||
3780
1.64M
       bsize < cpi->sf.use_square_only_thresh_low)) {
3781
120k
    if (cpi->use_svc) {
3782
0
      if (!vp9_active_h_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
3783
0
        partition_horz_allowed &= force_horz_split;
3784
0
      if (!vp9_active_v_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
3785
0
        partition_vert_allowed &= force_vert_split;
3786
120k
    } else {
3787
120k
      partition_horz_allowed &= force_horz_split;
3788
120k
      partition_vert_allowed &= force_vert_split;
3789
120k
    }
3790
120k
  }
3791
3792
2.87M
  save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
3793
3794
2.87M
  pc_tree->partitioning = PARTITION_NONE;
3795
3796
2.87M
  if (cpi->sf.rd_ml_partition.var_pruning && !frame_is_intra_only(cm)) {
3797
1.96M
    const int do_rd_ml_partition_var_pruning =
3798
1.96M
        partition_none_allowed && do_split &&
3799
1.35M
        mi_row + num_8x8_blocks_high_lookup[bsize] <= cm->mi_rows &&
3800
1.33M
        mi_col + num_8x8_blocks_wide_lookup[bsize] <= cm->mi_cols;
3801
1.96M
    if (do_rd_ml_partition_var_pruning) {
3802
1.33M
      ml_predict_var_rd_partitioning(cpi, x, pc_tree, bsize, mi_row, mi_col,
3803
1.33M
                                     &partition_none_allowed, &do_split);
3804
      // ml_predict_var_rd_partitioning() may pruune out either
3805
      // partition_none_allowed or do_split, but we should keep the
3806
      // partition_none_allowed for 8x8 blocks unless disable_split_mask is
3807
      // off (0).
3808
1.33M
      if (bsize == BLOCK_8X8 && cpi->sf.disable_split_mask &&
3809
0
          partition_none_allowed == 0) {
3810
0
        partition_none_allowed = 1;
3811
0
      }
3812
1.33M
    } else {
3813
633k
      vp9_zero(pc_tree->mv);
3814
633k
    }
3815
1.96M
    if (bsize > BLOCK_8X8) {  // Store MV result as reference for subblocks.
3816
4.35M
      for (i = 0; i < 4; ++i) pc_tree->u.split[i]->mv = pc_tree->mv;
3817
871k
    }
3818
1.96M
  }
3819
3820
  // PARTITION_NONE
3821
2.87M
  if (partition_none_allowed) {
3822
1.98M
    rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize, ctx,
3823
1.98M
                     best_rdc.rate, best_rdc.dist);
3824
1.98M
    ctx->rdcost = this_rdc.rdcost;
3825
1.98M
    if (this_rdc.rate != INT_MAX) {
3826
1.86M
      if (cpi->sf.prune_ref_frame_for_rect_partitions) {
3827
1.33M
        const int ref1 = ctx->mic.ref_frame[0];
3828
1.33M
        const int ref2 = ctx->mic.ref_frame[1];
3829
6.65M
        for (i = 0; i < 4; ++i) {
3830
5.32M
          ref_frames_used[i] |= (1 << ref1);
3831
5.32M
          if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
3832
5.32M
        }
3833
1.33M
      }
3834
1.86M
      if (bsize >= BLOCK_8X8) {
3835
1.86M
        this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
3836
1.86M
        vp9_rd_cost_update(partition_mul, x->rddiv, &this_rdc);
3837
1.86M
      }
3838
3839
1.86M
      if (this_rdc.rdcost < best_rdc.rdcost) {
3840
1.84M
        MODE_INFO *mi = xd->mi[0];
3841
3842
1.84M
        best_rdc = this_rdc;
3843
1.84M
        should_encode_sb = 1;
3844
1.84M
        if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
3845
3846
1.84M
        if (cpi->sf.rd_ml_partition.search_early_termination) {
3847
          // Currently, the machine-learning based partition search early
3848
          // termination is only used while bsize is 16x16, 32x32 or 64x64,
3849
          // VPXMIN(cm->width, cm->height) >= 480, and speed = 0.
3850
0
          if (!x->e_mbd.lossless &&
3851
0
              !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP) &&
3852
0
              ctx->mic.mode >= INTRA_MODES && bsize >= BLOCK_16X16) {
3853
0
            if (ml_pruning_partition(cm, xd, ctx, mi_row, mi_col, bsize)) {
3854
0
              do_split = 0;
3855
0
              do_rect = 0;
3856
0
            }
3857
0
          }
3858
0
        }
3859
3860
1.84M
        if ((do_split || do_rect) && !x->e_mbd.lossless && ctx->skippable) {
3861
269k
          const int use_ml_based_breakout =
3862
269k
              cpi->sf.rd_ml_partition.search_breakout && cm->base_qindex >= 100;
3863
269k
          if (use_ml_based_breakout) {
3864
32.7k
            if (ml_predict_breakout(cpi, bsize, x, &this_rdc)) {
3865
23.9k
              do_split = 0;
3866
23.9k
              do_rect = 0;
3867
23.9k
            }
3868
237k
          } else {
3869
237k
            if (!cpi->sf.rd_ml_partition.search_early_termination) {
3870
237k
              if ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
3871
16.9k
                  (best_rdc.dist < dist_breakout_thr &&
3872
220k
                   best_rdc.rate < rate_breakout_thr)) {
3873
220k
                do_split = 0;
3874
220k
                do_rect = 0;
3875
220k
              }
3876
237k
            }
3877
237k
          }
3878
269k
        }
3879
1.84M
      }
3880
1.86M
    }
3881
1.98M
    restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
3882
1.98M
  } else {
3883
894k
    vp9_zero(ctx->pred_mv);
3884
894k
    ctx->mic.interp_filter = EIGHTTAP;
3885
894k
  }
3886
3887
  // store estimated motion vector
3888
2.87M
  store_pred_mv(x, ctx);
3889
3890
  // If the interp_filter is marked as SWITCHABLE_FILTERS, it was for an
3891
  // intra block and used for context purposes.
3892
2.87M
  if (ctx->mic.interp_filter == SWITCHABLE_FILTERS) {
3893
833k
    pred_interp_filter = EIGHTTAP;
3894
2.04M
  } else {
3895
2.04M
    pred_interp_filter = ctx->mic.interp_filter;
3896
2.04M
  }
3897
3898
  // PARTITION_SPLIT
3899
  // TODO(jingning): use the motion vectors given by the above search as
3900
  // the starting point of motion search in the following partition type check.
3901
2.87M
  pc_tree->u.split[0]->none.rdcost = 0;
3902
2.87M
  pc_tree->u.split[1]->none.rdcost = 0;
3903
2.87M
  pc_tree->u.split[2]->none.rdcost = 0;
3904
2.87M
  pc_tree->u.split[3]->none.rdcost = 0;
3905
2.87M
  if (do_split || must_split) {
3906
2.30M
    subsize = get_subsize(bsize, PARTITION_SPLIT);
3907
2.30M
    load_pred_mv(x, ctx);
3908
2.30M
    if (bsize == BLOCK_8X8) {
3909
1.12M
      i = 4;
3910
1.12M
      if (cpi->sf.adaptive_pred_interp_filter && partition_none_allowed)
3911
675k
        pc_tree->u.leaf_split[0]->pred_interp_filter = pred_interp_filter;
3912
1.12M
      rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
3913
1.12M
                       pc_tree->u.leaf_split[0], best_rdc.rate, best_rdc.dist);
3914
1.12M
      if (sum_rdc.rate == INT_MAX) {
3915
740k
        sum_rdc.rdcost = INT64_MAX;
3916
740k
      } else {
3917
387k
        if (cpi->sf.prune_ref_frame_for_rect_partitions) {
3918
260k
          const int ref1 = pc_tree->u.leaf_split[0]->mic.ref_frame[0];
3919
260k
          const int ref2 = pc_tree->u.leaf_split[0]->mic.ref_frame[1];
3920
1.30M
          for (i = 0; i < 4; ++i) {
3921
1.04M
            ref_frames_used[i] |= (1 << ref1);
3922
1.04M
            if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
3923
1.04M
          }
3924
260k
        }
3925
387k
      }
3926
1.17M
    } else {
3927
5.64M
      for (i = 0; (i < 4) && ((sum_rdc.rdcost < best_rdc.rdcost) || must_split);
3928
4.59M
           ++i) {
3929
4.59M
        const int x_idx = (i & 1) * mi_step;
3930
4.59M
        const int y_idx = (i >> 1) * mi_step;
3931
4.59M
        int found_best_rd = 0;
3932
4.59M
        RD_COST best_rdc_split;
3933
4.59M
        vp9_rd_cost_reset(&best_rdc_split);
3934
3935
4.59M
        if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX) {
3936
          // A must split test here increases the number of sub
3937
          // partitions but hurts metrics results quite a bit,
3938
          // so this extra test is commented out pending
3939
          // further tests on whether it adds much in terms of
3940
          // visual quality.
3941
          // (must_split) ? best_rdc.rate
3942
          //              : best_rdc.rate - sum_rdc.rate,
3943
          // (must_split) ? best_rdc.dist
3944
          //              : best_rdc.dist - sum_rdc.dist,
3945
1.50M
          best_rdc_split.rate = best_rdc.rate - sum_rdc.rate;
3946
1.50M
          best_rdc_split.dist = best_rdc.dist - sum_rdc.dist;
3947
1.50M
        }
3948
3949
4.59M
        if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
3950
1.91M
          continue;
3951
3952
2.68M
        pc_tree->u.split[i]->index = i;
3953
2.68M
        if (cpi->sf.prune_ref_frame_for_rect_partitions)
3954
1.95M
          pc_tree->u.split[i]->none.rate = INT_MAX;
3955
2.68M
        found_best_rd = rd_pick_partition(
3956
2.68M
            cpi, td, tile_data, tp, mi_row + y_idx, mi_col + x_idx, subsize,
3957
2.68M
            &this_rdc, best_rdc_split, pc_tree->u.split[i]);
3958
3959
2.68M
        if (found_best_rd == 0) {
3960
129k
          sum_rdc.rdcost = INT64_MAX;
3961
129k
          break;
3962
2.55M
        } else {
3963
2.55M
          if (cpi->sf.prune_ref_frame_for_rect_partitions &&
3964
1.87M
              pc_tree->u.split[i]->none.rate != INT_MAX) {
3965
1.29M
            const int ref1 = pc_tree->u.split[i]->none.mic.ref_frame[0];
3966
1.29M
            const int ref2 = pc_tree->u.split[i]->none.mic.ref_frame[1];
3967
1.29M
            ref_frames_used[i] |= (1 << ref1);
3968
1.29M
            if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
3969
1.29M
          }
3970
2.55M
          sum_rdc.rate += this_rdc.rate;
3971
2.55M
          sum_rdc.dist += this_rdc.dist;
3972
2.55M
          vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
3973
2.55M
        }
3974
2.68M
      }
3975
1.17M
    }
3976
3977
2.30M
    if (((sum_rdc.rdcost < best_rdc.rdcost) || must_split) && i == 4) {
3978
1.36M
      sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
3979
1.36M
      vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
3980
3981
1.36M
      if ((sum_rdc.rdcost < best_rdc.rdcost) ||
3982
1.31M
          (must_split && (sum_rdc.dist < best_rdc.dist))) {
3983
1.31M
        best_rdc = sum_rdc;
3984
1.31M
        should_encode_sb = 1;
3985
1.31M
        pc_tree->partitioning = PARTITION_SPLIT;
3986
3987
        // Rate and distortion based partition search termination clause.
3988
1.31M
        if (!cpi->sf.rd_ml_partition.search_early_termination &&
3989
1.31M
            !x->e_mbd.lossless &&
3990
1.18M
            ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
3991
478k
             (best_rdc.dist < dist_breakout_thr &&
3992
706k
              best_rdc.rate < rate_breakout_thr))) {
3993
706k
          do_rect = 0;
3994
706k
        }
3995
1.31M
      }
3996
1.36M
    } else {
3997
      // skip rectangular partition test when larger block size
3998
      // gives better rd cost
3999
934k
      if (cpi->sf.less_rectangular_check &&
4000
583k
          (bsize > cpi->sf.use_square_only_thresh_high ||
4001
580k
           best_rdc.dist < dist_breakout_thr))
4002
359k
        do_rect &= !partition_none_allowed;
4003
934k
    }
4004
2.30M
    restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4005
2.30M
  }
4006
4007
2.87M
  pc_tree->horizontal[0].skip_ref_frame_mask = 0;
4008
2.87M
  pc_tree->horizontal[1].skip_ref_frame_mask = 0;
4009
2.87M
  pc_tree->vertical[0].skip_ref_frame_mask = 0;
4010
2.87M
  pc_tree->vertical[1].skip_ref_frame_mask = 0;
4011
2.87M
  if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4012
2.09M
    uint8_t used_frames;
4013
2.09M
    used_frames = ref_frames_used[0] | ref_frames_used[1];
4014
2.09M
    if (used_frames) {
4015
1.73M
      pc_tree->horizontal[0].skip_ref_frame_mask = ~used_frames & 0xff;
4016
1.73M
    }
4017
2.09M
    used_frames = ref_frames_used[2] | ref_frames_used[3];
4018
2.09M
    if (used_frames) {
4019
1.48M
      pc_tree->horizontal[1].skip_ref_frame_mask = ~used_frames & 0xff;
4020
1.48M
    }
4021
2.09M
    used_frames = ref_frames_used[0] | ref_frames_used[2];
4022
2.09M
    if (used_frames) {
4023
1.73M
      pc_tree->vertical[0].skip_ref_frame_mask = ~used_frames & 0xff;
4024
1.73M
    }
4025
2.09M
    used_frames = ref_frames_used[1] | ref_frames_used[3];
4026
2.09M
    if (used_frames) {
4027
1.58M
      pc_tree->vertical[1].skip_ref_frame_mask = ~used_frames & 0xff;
4028
1.58M
    }
4029
2.09M
  }
4030
4031
2.87M
  {
4032
2.87M
    const int do_ml_rect_partition_pruning =
4033
2.87M
        !frame_is_intra_only(cm) && !force_horz_split && !force_vert_split &&
4034
1.84M
        (partition_horz_allowed || partition_vert_allowed) && bsize > BLOCK_8X8;
4035
2.87M
    if (do_ml_rect_partition_pruning) {
4036
346k
      ml_prune_rect_partition(cpi, x, bsize, pc_tree, &partition_horz_allowed,
4037
346k
                              &partition_vert_allowed, best_rdc.rdcost);
4038
346k
    }
4039
2.87M
  }
4040
4041
  // PARTITION_HORZ
4042
2.87M
  if (partition_horz_allowed &&
4043
2.23M
      (do_rect || vp9_active_h_edge(cpi, mi_row, mi_step))) {
4044
1.54M
    const int part_mode_rate = cpi->partition_cost[pl][PARTITION_HORZ];
4045
1.54M
    subsize = get_subsize(bsize, PARTITION_HORZ);
4046
1.54M
    load_pred_mv(x, ctx);
4047
1.54M
    if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4048
639k
        partition_none_allowed)
4049
610k
      pc_tree->horizontal[0].pred_interp_filter = pred_interp_filter;
4050
1.54M
    rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4051
1.54M
                     &pc_tree->horizontal[0], best_rdc.rate - part_mode_rate,
4052
1.54M
                     best_rdc.dist);
4053
1.54M
    if (sum_rdc.rdcost < INT64_MAX) {
4054
450k
      sum_rdc.rate += part_mode_rate;
4055
450k
      vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4056
450k
    }
4057
4058
1.54M
    if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + mi_step < cm->mi_rows &&
4059
277k
        bsize > BLOCK_8X8) {
4060
171k
      PICK_MODE_CONTEXT *hctx = &pc_tree->horizontal[0];
4061
171k
      update_state(cpi, td, hctx, mi_row, mi_col, subsize, 0);
4062
171k
      encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, hctx);
4063
171k
      if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4064
0
          partition_none_allowed)
4065
0
        pc_tree->horizontal[1].pred_interp_filter = pred_interp_filter;
4066
171k
      rd_pick_sb_modes(cpi, tile_data, x, mi_row + mi_step, mi_col, &this_rdc,
4067
171k
                       subsize, &pc_tree->horizontal[1],
4068
171k
                       best_rdc.rate - sum_rdc.rate,
4069
171k
                       best_rdc.dist - sum_rdc.dist);
4070
171k
      if (this_rdc.rate == INT_MAX) {
4071
134k
        sum_rdc.rdcost = INT64_MAX;
4072
134k
      } else {
4073
37.6k
        sum_rdc.rate += this_rdc.rate;
4074
37.6k
        sum_rdc.dist += this_rdc.dist;
4075
37.6k
        vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4076
37.6k
      }
4077
171k
    }
4078
4079
1.54M
    if (sum_rdc.rdcost < best_rdc.rdcost) {
4080
258k
      best_rdc = sum_rdc;
4081
258k
      should_encode_sb = 1;
4082
258k
      pc_tree->partitioning = PARTITION_HORZ;
4083
4084
258k
      if (cpi->sf.less_rectangular_check &&
4085
209k
          bsize > cpi->sf.use_square_only_thresh_high)
4086
6.63k
        do_rect = 0;
4087
258k
    }
4088
1.54M
    restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4089
1.54M
  }
4090
4091
  // PARTITION_VERT
4092
2.87M
  if (partition_vert_allowed &&
4093
2.11M
      (do_rect || vp9_active_v_edge(cpi, mi_col, mi_step))) {
4094
1.44M
    const int part_mode_rate = cpi->partition_cost[pl][PARTITION_VERT];
4095
1.44M
    subsize = get_subsize(bsize, PARTITION_VERT);
4096
1.44M
    load_pred_mv(x, ctx);
4097
1.44M
    if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4098
639k
        partition_none_allowed)
4099
610k
      pc_tree->vertical[0].pred_interp_filter = pred_interp_filter;
4100
1.44M
    rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4101
1.44M
                     &pc_tree->vertical[0], best_rdc.rate - part_mode_rate,
4102
1.44M
                     best_rdc.dist);
4103
1.44M
    if (sum_rdc.rdcost < INT64_MAX) {
4104
370k
      sum_rdc.rate += part_mode_rate;
4105
370k
      vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4106
370k
    }
4107
4108
1.44M
    if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + mi_step < cm->mi_cols &&
4109
225k
        bsize > BLOCK_8X8) {
4110
165k
      update_state(cpi, td, &pc_tree->vertical[0], mi_row, mi_col, subsize, 0);
4111
165k
      encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize,
4112
165k
                        &pc_tree->vertical[0]);
4113
165k
      if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4114
0
          partition_none_allowed)
4115
0
        pc_tree->vertical[1].pred_interp_filter = pred_interp_filter;
4116
165k
      rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + mi_step, &this_rdc,
4117
165k
                       subsize, &pc_tree->vertical[1],
4118
165k
                       best_rdc.rate - sum_rdc.rate,
4119
165k
                       best_rdc.dist - sum_rdc.dist);
4120
165k
      if (this_rdc.rate == INT_MAX) {
4121
142k
        sum_rdc.rdcost = INT64_MAX;
4122
142k
      } else {
4123
23.2k
        sum_rdc.rate += this_rdc.rate;
4124
23.2k
        sum_rdc.dist += this_rdc.dist;
4125
23.2k
        vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4126
23.2k
      }
4127
165k
    }
4128
4129
1.44M
    if (sum_rdc.rdcost < best_rdc.rdcost) {
4130
168k
      best_rdc = sum_rdc;
4131
168k
      should_encode_sb = 1;
4132
168k
      pc_tree->partitioning = PARTITION_VERT;
4133
168k
    }
4134
1.44M
    restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4135
1.44M
  }
4136
4137
2.87M
  if (bsize == BLOCK_64X64 && best_rdc.rdcost == INT64_MAX) {
4138
0
    vp9_rd_cost_reset(&this_rdc);
4139
0
    rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, BLOCK_64X64,
4140
0
                     ctx, INT_MAX, INT64_MAX);
4141
0
    ctx->rdcost = this_rdc.rdcost;
4142
0
    vp9_rd_cost_update(partition_mul, x->rddiv, &this_rdc);
4143
0
    if (this_rdc.rdcost < best_rdc.rdcost) {
4144
0
      best_rdc = this_rdc;
4145
0
      should_encode_sb = 1;
4146
0
      pc_tree->partitioning = PARTITION_NONE;
4147
0
    }
4148
0
  }
4149
4150
2.87M
  *rd_cost = best_rdc;
4151
4152
2.87M
  if (should_encode_sb && pc_tree->index != 3) {
4153
2.53M
    int output_enabled = (bsize == BLOCK_64X64);
4154
#if CONFIG_COLLECT_COMPONENT_TIMING
4155
    start_timing(cpi, encode_sb_time);
4156
#endif
4157
2.53M
    encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
4158
2.53M
              pc_tree);
4159
#if CONFIG_COLLECT_COMPONENT_TIMING
4160
    end_timing(cpi, encode_sb_time);
4161
#endif
4162
2.53M
  }
4163
4164
2.87M
  if (bsize == BLOCK_64X64) {
4165
193k
    assert(tp_orig < *tp);
4166
193k
    assert(best_rdc.rate < INT_MAX);
4167
193k
    assert(best_rdc.dist < INT64_MAX);
4168
2.68M
  } else {
4169
2.68M
    assert(tp_orig == *tp);
4170
2.68M
  }
4171
4172
2.87M
  return should_encode_sb;
4173
2.87M
}
4174
4175
static void encode_rd_sb_row(VP9_COMP *cpi, ThreadData *td,
4176
                             TileDataEnc *tile_data, int mi_row,
4177
193k
                             TOKENEXTRA **tp) {
4178
193k
  VP9_COMMON *const cm = &cpi->common;
4179
193k
  TileInfo *const tile_info = &tile_data->tile_info;
4180
193k
  MACROBLOCK *const x = &td->mb;
4181
193k
  MACROBLOCKD *const xd = &x->e_mbd;
4182
193k
  SPEED_FEATURES *const sf = &cpi->sf;
4183
193k
  const int mi_col_start = tile_info->mi_col_start;
4184
193k
  const int mi_col_end = tile_info->mi_col_end;
4185
193k
  int mi_col;
4186
193k
  const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
4187
193k
  const int num_sb_cols =
4188
193k
      get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
4189
193k
  int sb_col_in_tile;
4190
4191
  // Initialize the left context for the new SB row
4192
193k
  memset(&xd->left_context, 0, sizeof(xd->left_context));
4193
193k
  memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
4194
4195
  // Code each SB in the row
4196
387k
  for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
4197
193k
       mi_col += MI_BLOCK_SIZE, sb_col_in_tile++) {
4198
193k
    const struct segmentation *const seg = &cm->seg;
4199
193k
    int dummy_rate;
4200
193k
    int64_t dummy_dist;
4201
193k
    RD_COST dummy_rdc;
4202
193k
    int i;
4203
193k
    int seg_skip = 0;
4204
193k
    int orig_rdmult = cpi->rd.RDMULT;
4205
4206
193k
    const int idx_str = cm->mi_stride * mi_row + mi_col;
4207
193k
    MODE_INFO **mi = cm->mi_grid_visible + idx_str;
4208
4209
193k
    vp9_rd_cost_reset(&dummy_rdc);
4210
193k
    (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
4211
193k
                                   sb_col_in_tile);
4212
4213
193k
    if (sf->adaptive_pred_interp_filter) {
4214
9.14M
      for (i = 0; i < 64; ++i) td->leaf_tree[i].pred_interp_filter = SWITCHABLE;
4215
4216
9.14M
      for (i = 0; i < 64; ++i) {
4217
9.00M
        td->pc_tree[i].vertical[0].pred_interp_filter = SWITCHABLE;
4218
9.00M
        td->pc_tree[i].vertical[1].pred_interp_filter = SWITCHABLE;
4219
9.00M
        td->pc_tree[i].horizontal[0].pred_interp_filter = SWITCHABLE;
4220
9.00M
        td->pc_tree[i].horizontal[1].pred_interp_filter = SWITCHABLE;
4221
9.00M
      }
4222
140k
    }
4223
4224
969k
    for (i = 0; i < MAX_REF_FRAMES; ++i) {
4225
775k
      x->pred_mv[i].row = INT16_MAX;
4226
775k
      x->pred_mv[i].col = INT16_MAX;
4227
775k
    }
4228
193k
    td->pc_root->index = 0;
4229
4230
193k
    if (seg->enabled) {
4231
0
      const uint8_t *const map =
4232
0
          seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
4233
0
      int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
4234
0
      seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
4235
0
    }
4236
4237
193k
    x->source_variance = UINT_MAX;
4238
4239
193k
    x->cb_rdmult = orig_rdmult;
4240
4241
193k
    if (sf->partition_search_type == FIXED_PARTITION || seg_skip) {
4242
0
      const BLOCK_SIZE bsize =
4243
0
          seg_skip ? BLOCK_64X64 : sf->always_this_block_size;
4244
0
      set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4245
0
      set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
4246
0
      rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4247
0
                       &dummy_rate, &dummy_dist, 1, td->pc_root);
4248
193k
    } else if (sf->partition_search_type == VAR_BASED_PARTITION &&
4249
0
               cm->frame_type != KEY_FRAME) {
4250
0
      choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
4251
0
      rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4252
0
                       &dummy_rate, &dummy_dist, 1, td->pc_root);
4253
193k
    } else {
4254
193k
      if (cpi->twopass.gf_group.index > 0 && cpi->sf.enable_tpl_model) {
4255
0
        int dr =
4256
0
            get_rdmult_delta(cpi, BLOCK_64X64, mi_row, mi_col, orig_rdmult);
4257
0
        x->cb_rdmult = dr;
4258
0
      }
4259
4260
193k
      if (cpi->oxcf.aq_mode == PERCEPTUAL_AQ && cm->show_frame) {
4261
0
        x->segment_id = wiener_var_segment(cpi, BLOCK_64X64, mi_row, mi_col);
4262
0
        x->cb_rdmult = vp9_compute_rd_mult(
4263
0
            cpi, vp9_get_qindex(&cm->seg, x->segment_id, cm->base_qindex));
4264
0
      }
4265
4266
      // If required set upper and lower partition size limits
4267
193k
      if (sf->auto_min_max_partition_size) {
4268
0
        set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4269
0
        rd_auto_partition_range(cpi, tile_info, xd, mi_row, mi_col,
4270
0
                                &x->min_partition_size, &x->max_partition_size);
4271
0
      }
4272
193k
      td->pc_root->none.rdcost = 0;
4273
4274
#if CONFIG_COLLECT_COMPONENT_TIMING
4275
      start_timing(cpi, rd_pick_partition_time);
4276
#endif
4277
193k
      rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, BLOCK_64X64,
4278
193k
                        &dummy_rdc, dummy_rdc, td->pc_root);
4279
#if CONFIG_COLLECT_COMPONENT_TIMING
4280
      end_timing(cpi, rd_pick_partition_time);
4281
#endif
4282
193k
    }
4283
193k
    (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
4284
193k
                                    sb_col_in_tile, num_sb_cols);
4285
193k
  }
4286
193k
}
4287
#endif  // !CONFIG_REALTIME_ONLY
4288
4289
452k
static void init_encode_frame_mb_context(VP9_COMP *cpi) {
4290
452k
  MACROBLOCK *const x = &cpi->td.mb;
4291
452k
  VP9_COMMON *const cm = &cpi->common;
4292
452k
  MACROBLOCKD *const xd = &x->e_mbd;
4293
452k
  const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
4294
4295
  // Copy data over into macro block data structures.
4296
452k
  vp9_setup_src_planes(x, cpi->Source, 0, 0);
4297
4298
452k
  vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
4299
4300
  // Note: this memset assumes above_context[0], [1] and [2]
4301
  // are allocated as part of the same buffer.
4302
452k
  memset(xd->above_context[0], 0,
4303
452k
         sizeof(*xd->above_context[0]) * 2 * aligned_mi_cols * MAX_MB_PLANE);
4304
452k
  memset(xd->above_seg_context, 0,
4305
452k
         sizeof(*xd->above_seg_context) * aligned_mi_cols);
4306
452k
}
4307
4308
0
static int check_dual_ref_flags(VP9_COMP *cpi) {
4309
0
  const int ref_flags = cpi->ref_frame_flags;
4310
4311
0
  if (segfeature_active(&cpi->common.seg, 1, SEG_LVL_REF_FRAME)) {
4312
0
    return 0;
4313
0
  } else {
4314
0
    return (!!(ref_flags & VP9_GOLD_FLAG) + !!(ref_flags & VP9_LAST_FLAG) +
4315
0
            !!(ref_flags & VP9_ALT_FLAG)) >= 2;
4316
0
  }
4317
0
}
4318
4319
138k
static void reset_skip_tx_size(VP9_COMMON *cm, TX_SIZE max_tx_size) {
4320
138k
  int mi_row, mi_col;
4321
138k
  const int mis = cm->mi_stride;
4322
138k
  MODE_INFO **mi_ptr = cm->mi_grid_visible;
4323
4324
492k
  for (mi_row = 0; mi_row < cm->mi_rows; ++mi_row, mi_ptr += mis) {
4325
1.13M
    for (mi_col = 0; mi_col < cm->mi_cols; ++mi_col) {
4326
782k
      if (mi_ptr[mi_col]->tx_size > max_tx_size)
4327
23.5k
        mi_ptr[mi_col]->tx_size = max_tx_size;
4328
782k
    }
4329
354k
  }
4330
138k
}
4331
4332
193k
static MV_REFERENCE_FRAME get_frame_type(const VP9_COMP *cpi) {
4333
193k
  if (frame_is_intra_only(&cpi->common))
4334
9.47k
    return INTRA_FRAME;
4335
184k
  else if (cpi->rc.is_src_frame_alt_ref && cpi->refresh_golden_frame)
4336
0
    return ALTREF_FRAME;
4337
184k
  else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
4338
18.0k
    return GOLDEN_FRAME;
4339
166k
  else
4340
166k
    return LAST_FRAME;
4341
193k
}
4342
4343
452k
static TX_MODE select_tx_mode(const VP9_COMP *cpi, MACROBLOCKD *const xd) {
4344
452k
  if (xd->lossless) return ONLY_4X4;
4345
411k
  if (cpi->common.frame_type == KEY_FRAME && cpi->sf.use_nonrd_pick_mode)
4346
15.8k
    return ALLOW_16X16;
4347
395k
  if (cpi->sf.tx_size_search_method == USE_LARGESTALL)
4348
0
    return ALLOW_32X32;
4349
395k
  else if (cpi->sf.tx_size_search_method == USE_FULL_RD ||
4350
220k
           cpi->sf.tx_size_search_method == USE_TX_8X8)
4351
395k
    return TX_MODE_SELECT;
4352
0
  else
4353
0
    return cpi->common.tx_mode;
4354
395k
}
4355
4356
static void hybrid_intra_mode_search(VP9_COMP *cpi, MACROBLOCK *const x,
4357
                                     RD_COST *rd_cost, BLOCK_SIZE bsize,
4358
238k
                                     PICK_MODE_CONTEXT *ctx) {
4359
238k
  if (!cpi->sf.nonrd_keyframe && bsize < BLOCK_16X16)
4360
212k
    vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4361
25.4k
  else
4362
25.4k
    vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4363
238k
}
4364
4365
static void hybrid_search_svc_baseiskey(VP9_COMP *cpi, MACROBLOCK *const x,
4366
                                        RD_COST *rd_cost, BLOCK_SIZE bsize,
4367
                                        PICK_MODE_CONTEXT *ctx,
4368
                                        TileDataEnc *tile_data, int mi_row,
4369
0
                                        int mi_col) {
4370
0
  if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4371
0
    vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4372
0
  } else {
4373
0
    if (cpi->svc.disable_inter_layer_pred == INTER_LAYER_PRED_OFF)
4374
0
      vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4375
0
    else if (bsize >= BLOCK_8X8)
4376
0
      vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4377
0
                          ctx);
4378
0
    else
4379
0
      vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4380
0
  }
4381
0
}
4382
4383
static void hybrid_search_scene_change(VP9_COMP *cpi, MACROBLOCK *const x,
4384
                                       RD_COST *rd_cost, BLOCK_SIZE bsize,
4385
                                       PICK_MODE_CONTEXT *ctx,
4386
                                       TileDataEnc *tile_data, int mi_row,
4387
0
                                       int mi_col) {
4388
0
  if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4389
0
    vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4390
0
  } else {
4391
0
    vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize, ctx);
4392
0
  }
4393
0
}
4394
4395
static void nonrd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
4396
                                MACROBLOCK *const x, int mi_row, int mi_col,
4397
                                RD_COST *rd_cost, BLOCK_SIZE bsize,
4398
3.89M
                                PICK_MODE_CONTEXT *ctx) {
4399
3.89M
  VP9_COMMON *const cm = &cpi->common;
4400
3.89M
  TileInfo *const tile_info = &tile_data->tile_info;
4401
3.89M
  MACROBLOCKD *const xd = &x->e_mbd;
4402
3.89M
  MODE_INFO *mi;
4403
3.89M
  ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
4404
3.89M
  BLOCK_SIZE bs = VPXMAX(bsize, BLOCK_8X8);  // processing unit block size
4405
3.89M
  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bs];
4406
3.89M
  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bs];
4407
3.89M
  int plane;
4408
4409
3.89M
  set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4410
4411
3.89M
  set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
4412
4413
3.89M
  x->skip_recode = 0;
4414
4415
3.89M
  mi = xd->mi[0];
4416
3.89M
  mi->sb_type = bsize;
4417
4418
15.5M
  for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4419
11.6M
    struct macroblockd_plane *pd = &xd->plane[plane];
4420
11.6M
    memcpy(a + num_4x4_blocks_wide * plane, pd->above_context,
4421
11.6M
           (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4422
11.6M
    memcpy(l + num_4x4_blocks_high * plane, pd->left_context,
4423
11.6M
           (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4424
11.6M
  }
4425
4426
3.89M
  if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled)
4427
0
    if (cyclic_refresh_segment_id_boosted(mi->segment_id))
4428
0
      x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
4429
4430
3.89M
  if (frame_is_intra_only(cm))
4431
238k
    hybrid_intra_mode_search(cpi, x, rd_cost, bsize, ctx);
4432
3.66M
  else if (cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame)
4433
0
    hybrid_search_svc_baseiskey(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4434
0
                                mi_col);
4435
3.66M
  else if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
4436
0
    set_mode_info_seg_skip(x, cm->tx_mode, cm->interp_filter, rd_cost, bsize);
4437
3.66M
  else if (bsize >= BLOCK_8X8) {
4438
3.66M
    if (cpi->rc.hybrid_intra_scene_change)
4439
0
      hybrid_search_scene_change(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4440
0
                                 mi_col);
4441
3.66M
    else
4442
3.66M
      vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4443
3.66M
                          ctx);
4444
3.66M
  } else {
4445
0
    vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4446
0
  }
4447
4448
3.89M
  duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4449
4450
15.5M
  for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4451
11.6M
    struct macroblockd_plane *pd = &xd->plane[plane];
4452
11.6M
    memcpy(pd->above_context, a + num_4x4_blocks_wide * plane,
4453
11.6M
           (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4454
11.6M
    memcpy(pd->left_context, l + num_4x4_blocks_high * plane,
4455
11.6M
           (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4456
11.6M
  }
4457
4458
3.89M
  if (rd_cost->rate == INT_MAX) vp9_rd_cost_reset(rd_cost);
4459
4460
3.89M
  ctx->rate = rd_cost->rate;
4461
3.89M
  ctx->dist = rd_cost->dist;
4462
3.89M
}
4463
4464
static void fill_mode_info_sb(VP9_COMMON *cm, MACROBLOCK *x, int mi_row,
4465
6.64M
                              int mi_col, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
4466
6.64M
  MACROBLOCKD *xd = &x->e_mbd;
4467
6.64M
  int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
4468
6.64M
  PARTITION_TYPE partition = pc_tree->partitioning;
4469
6.64M
  BLOCK_SIZE subsize = get_subsize(bsize, partition);
4470
4471
6.64M
  assert(bsize >= BLOCK_8X8);
4472
4473
6.64M
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
4474
4475
5.78M
  switch (partition) {
4476
5.00M
    case PARTITION_NONE:
4477
5.00M
      set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4478
5.00M
      *(xd->mi[0]) = pc_tree->none.mic;
4479
5.00M
      *(x->mbmi_ext) = pc_tree->none.mbmi_ext;
4480
5.00M
      duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4481
5.00M
      break;
4482
0
    case PARTITION_VERT:
4483
0
      set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4484
0
      *(xd->mi[0]) = pc_tree->vertical[0].mic;
4485
0
      *(x->mbmi_ext) = pc_tree->vertical[0].mbmi_ext;
4486
0
      duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4487
4488
0
      if (mi_col + hbs < cm->mi_cols) {
4489
0
        set_mode_info_offsets(cm, x, xd, mi_row, mi_col + hbs);
4490
0
        *(xd->mi[0]) = pc_tree->vertical[1].mic;
4491
0
        *(x->mbmi_ext) = pc_tree->vertical[1].mbmi_ext;
4492
0
        duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col + hbs, subsize);
4493
0
      }
4494
0
      break;
4495
0
    case PARTITION_HORZ:
4496
0
      set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4497
0
      *(xd->mi[0]) = pc_tree->horizontal[0].mic;
4498
0
      *(x->mbmi_ext) = pc_tree->horizontal[0].mbmi_ext;
4499
0
      duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4500
0
      if (mi_row + hbs < cm->mi_rows) {
4501
0
        set_mode_info_offsets(cm, x, xd, mi_row + hbs, mi_col);
4502
0
        *(xd->mi[0]) = pc_tree->horizontal[1].mic;
4503
0
        *(x->mbmi_ext) = pc_tree->horizontal[1].mbmi_ext;
4504
0
        duplicate_mode_info_in_sb(cm, xd, mi_row + hbs, mi_col, subsize);
4505
0
      }
4506
0
      break;
4507
780k
    case PARTITION_SPLIT: {
4508
780k
      fill_mode_info_sb(cm, x, mi_row, mi_col, subsize, pc_tree->u.split[0]);
4509
780k
      fill_mode_info_sb(cm, x, mi_row, mi_col + hbs, subsize,
4510
780k
                        pc_tree->u.split[1]);
4511
780k
      fill_mode_info_sb(cm, x, mi_row + hbs, mi_col, subsize,
4512
780k
                        pc_tree->u.split[2]);
4513
780k
      fill_mode_info_sb(cm, x, mi_row + hbs, mi_col + hbs, subsize,
4514
780k
                        pc_tree->u.split[3]);
4515
780k
      break;
4516
0
    }
4517
0
    default: break;
4518
5.78M
  }
4519
5.78M
}
4520
4521
// Reset the prediction pixel ready flag recursively.
4522
0
static void pred_pixel_ready_reset(PC_TREE *pc_tree, BLOCK_SIZE bsize) {
4523
0
  pc_tree->none.pred_pixel_ready = 0;
4524
0
  pc_tree->horizontal[0].pred_pixel_ready = 0;
4525
0
  pc_tree->horizontal[1].pred_pixel_ready = 0;
4526
0
  pc_tree->vertical[0].pred_pixel_ready = 0;
4527
0
  pc_tree->vertical[1].pred_pixel_ready = 0;
4528
4529
0
  if (bsize > BLOCK_8X8) {
4530
0
    BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4531
0
    int i;
4532
0
    for (i = 0; i < 4; ++i)
4533
0
      pred_pixel_ready_reset(pc_tree->u.split[i], subsize);
4534
0
  }
4535
0
}
4536
4537
#define FEATURES 6
4538
#define LABELS 2
4539
static int ml_predict_var_partitioning(VP9_COMP *cpi, MACROBLOCK *x,
4540
                                       BLOCK_SIZE bsize, int mi_row,
4541
0
                                       int mi_col) {
4542
0
  VP9_COMMON *const cm = &cpi->common;
4543
0
  const NN_CONFIG *nn_config = NULL;
4544
4545
0
  switch (bsize) {
4546
0
    case BLOCK_64X64: nn_config = &vp9_var_part_nnconfig_64; break;
4547
0
    case BLOCK_32X32: nn_config = &vp9_var_part_nnconfig_32; break;
4548
0
    case BLOCK_16X16: nn_config = &vp9_var_part_nnconfig_16; break;
4549
0
    case BLOCK_8X8: break;
4550
0
    default: assert(0 && "Unexpected block size."); return -1;
4551
0
  }
4552
4553
0
  if (!nn_config) return -1;
4554
4555
0
  vpx_clear_system_state();
4556
4557
0
  {
4558
0
    const float thresh = cpi->oxcf.speed <= 5 ? 1.25f : 0.0f;
4559
0
    float features[FEATURES] = { 0.0f };
4560
0
    const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
4561
0
    int feature_idx = 0;
4562
0
    float score[LABELS];
4563
4564
0
    features[feature_idx++] = logf((float)(dc_q * dc_q) / 256.0f + 1.0f);
4565
0
    vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
4566
0
    {
4567
0
      const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
4568
0
      const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4569
0
      const int sb_offset_row = 8 * (mi_row & 7);
4570
0
      const int sb_offset_col = 8 * (mi_col & 7);
4571
0
      const uint8_t *pred = x->est_pred + sb_offset_row * 64 + sb_offset_col;
4572
0
      const uint8_t *src = x->plane[0].src.buf;
4573
0
      const int src_stride = x->plane[0].src.stride;
4574
0
      const int pred_stride = 64;
4575
0
      unsigned int sse;
4576
0
      int i;
4577
      // Variance of whole block.
4578
0
      const unsigned int var =
4579
0
          cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
4580
0
      const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
4581
4582
0
      features[feature_idx++] = logf((float)var + 1.0f);
4583
0
      for (i = 0; i < 4; ++i) {
4584
0
        const int x_idx = (i & 1) * bs / 2;
4585
0
        const int y_idx = (i >> 1) * bs / 2;
4586
0
        const int src_offset = y_idx * src_stride + x_idx;
4587
0
        const int pred_offset = y_idx * pred_stride + x_idx;
4588
        // Variance of quarter block.
4589
0
        const unsigned int sub_var =
4590
0
            cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
4591
0
                                    pred + pred_offset, pred_stride, &sse);
4592
0
        const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
4593
0
        features[feature_idx++] = var_ratio;
4594
0
      }
4595
0
    }
4596
4597
0
    assert(feature_idx == FEATURES);
4598
0
    nn_predict(features, nn_config, score);
4599
0
    if (score[0] > thresh) return PARTITION_SPLIT;
4600
0
    if (score[0] < -thresh) return PARTITION_NONE;
4601
0
    return -1;
4602
0
  }
4603
0
}
4604
#undef FEATURES
4605
#undef LABELS
4606
4607
static void nonrd_pick_partition(VP9_COMP *cpi, ThreadData *td,
4608
                                 TileDataEnc *tile_data, TOKENEXTRA **tp,
4609
                                 int mi_row, int mi_col, BLOCK_SIZE bsize,
4610
                                 RD_COST *rd_cost, int do_recon,
4611
3.90M
                                 int64_t best_rd, PC_TREE *pc_tree) {
4612
3.90M
  const SPEED_FEATURES *const sf = &cpi->sf;
4613
3.90M
  VP9_COMMON *const cm = &cpi->common;
4614
3.90M
  TileInfo *const tile_info = &tile_data->tile_info;
4615
3.90M
  MACROBLOCK *const x = &td->mb;
4616
3.90M
  MACROBLOCKD *const xd = &x->e_mbd;
4617
3.90M
  const int ms = num_8x8_blocks_wide_lookup[bsize] / 2;
4618
3.90M
  TOKENEXTRA *tp_orig = *tp;
4619
3.90M
  PICK_MODE_CONTEXT *ctx = &pc_tree->none;
4620
3.90M
  int i;
4621
3.90M
  BLOCK_SIZE subsize = bsize;
4622
3.90M
  RD_COST this_rdc, sum_rdc, best_rdc;
4623
3.90M
  int do_split = bsize >= BLOCK_8X8;
4624
3.90M
  int do_rect = 1;
4625
  // Override skipping rectangular partition operations for edge blocks
4626
3.90M
  const int force_horz_split = (mi_row + ms >= cm->mi_rows);
4627
3.90M
  const int force_vert_split = (mi_col + ms >= cm->mi_cols);
4628
3.90M
  const int xss = x->e_mbd.plane[1].subsampling_x;
4629
3.90M
  const int yss = x->e_mbd.plane[1].subsampling_y;
4630
4631
3.90M
  int partition_none_allowed = !force_horz_split && !force_vert_split;
4632
3.90M
  int partition_horz_allowed =
4633
3.90M
      !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
4634
3.90M
  int partition_vert_allowed =
4635
3.90M
      !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
4636
3.90M
  const int use_ml_based_partitioning =
4637
3.90M
      sf->partition_search_type == ML_BASED_PARTITION;
4638
4639
3.90M
  (void)*tp_orig;
4640
4641
  // Avoid checking for rectangular partitions for speed >= 5.
4642
3.90M
  if (cpi->oxcf.speed >= 5) do_rect = 0;
4643
4644
3.90M
  assert(num_8x8_blocks_wide_lookup[bsize] ==
4645
3.90M
         num_8x8_blocks_high_lookup[bsize]);
4646
4647
3.90M
  vp9_rd_cost_init(&sum_rdc);
4648
3.90M
  vp9_rd_cost_reset(&best_rdc);
4649
3.90M
  best_rdc.rdcost = best_rd;
4650
4651
  // Determine partition types in search according to the speed features.
4652
  // The threshold set here has to be of square block size.
4653
3.90M
  if (sf->auto_min_max_partition_size) {
4654
3.90M
    partition_none_allowed &=
4655
3.90M
        (bsize <= x->max_partition_size && bsize >= x->min_partition_size);
4656
3.90M
    partition_horz_allowed &=
4657
3.90M
        ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4658
2.84M
         force_horz_split);
4659
3.90M
    partition_vert_allowed &=
4660
3.90M
        ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4661
2.84M
         force_vert_split);
4662
3.90M
    do_split &= bsize > x->min_partition_size;
4663
3.90M
  }
4664
3.90M
  if (sf->use_square_partition_only) {
4665
3.90M
    partition_horz_allowed &= force_horz_split;
4666
3.90M
    partition_vert_allowed &= force_vert_split;
4667
3.90M
  }
4668
4669
3.90M
  if (use_ml_based_partitioning) {
4670
0
    if (partition_none_allowed || do_split) do_rect = 0;
4671
0
    if (partition_none_allowed && do_split) {
4672
0
      const int ml_predicted_partition =
4673
0
          ml_predict_var_partitioning(cpi, x, bsize, mi_row, mi_col);
4674
0
      if (ml_predicted_partition == PARTITION_NONE) do_split = 0;
4675
0
      if (ml_predicted_partition == PARTITION_SPLIT) partition_none_allowed = 0;
4676
0
    }
4677
0
  }
4678
4679
3.90M
  if (!partition_none_allowed && !do_split) do_rect = 1;
4680
4681
3.90M
  ctx->pred_pixel_ready =
4682
3.90M
      !(partition_vert_allowed || partition_horz_allowed || do_split);
4683
4684
  // PARTITION_NONE
4685
3.90M
  if (partition_none_allowed) {
4686
3.56M
    nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize,
4687
3.56M
                        ctx);
4688
3.56M
    ctx->mic = *xd->mi[0];
4689
3.56M
    ctx->mbmi_ext = *x->mbmi_ext;
4690
3.56M
    ctx->skip_txfm[0] = x->skip_txfm[0];
4691
3.56M
    ctx->skip = x->skip;
4692
4693
3.56M
    if (this_rdc.rate != INT_MAX) {
4694
3.56M
      const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4695
3.56M
      this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
4696
3.56M
      this_rdc.rdcost =
4697
3.56M
          RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist);
4698
3.56M
      if (this_rdc.rdcost < best_rdc.rdcost) {
4699
3.18M
        best_rdc = this_rdc;
4700
3.18M
        if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
4701
4702
3.18M
        if (!use_ml_based_partitioning) {
4703
3.18M
          int64_t dist_breakout_thr = sf->partition_search_breakout_thr.dist;
4704
3.18M
          int64_t rate_breakout_thr = sf->partition_search_breakout_thr.rate;
4705
3.18M
          dist_breakout_thr >>=
4706
3.18M
              8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
4707
3.18M
          rate_breakout_thr *= num_pels_log2_lookup[bsize];
4708
3.18M
          if (!x->e_mbd.lossless && this_rdc.rate < rate_breakout_thr &&
4709
144k
              this_rdc.dist < dist_breakout_thr) {
4710
144k
            do_split = 0;
4711
144k
            do_rect = 0;
4712
144k
          }
4713
3.18M
        }
4714
3.18M
      }
4715
3.56M
    }
4716
3.56M
  }
4717
4718
  // store estimated motion vector
4719
3.90M
  store_pred_mv(x, ctx);
4720
4721
  // PARTITION_SPLIT
4722
3.90M
  if (do_split) {
4723
1.02M
    int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4724
1.02M
    sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
4725
1.02M
    sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4726
1.02M
    subsize = get_subsize(bsize, PARTITION_SPLIT);
4727
4.95M
    for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
4728
3.92M
      const int x_idx = (i & 1) * ms;
4729
3.92M
      const int y_idx = (i >> 1) * ms;
4730
4731
3.92M
      if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
4732
777k
        continue;
4733
3.15M
      load_pred_mv(x, ctx);
4734
3.15M
      nonrd_pick_partition(
4735
3.15M
          cpi, td, tile_data, tp, mi_row + y_idx, mi_col + x_idx, subsize,
4736
3.15M
          &this_rdc, 0, best_rdc.rdcost - sum_rdc.rdcost, pc_tree->u.split[i]);
4737
4738
3.15M
      if (this_rdc.rate == INT_MAX) {
4739
382k
        vp9_rd_cost_reset(&sum_rdc);
4740
2.76M
      } else {
4741
2.76M
        sum_rdc.rate += this_rdc.rate;
4742
2.76M
        sum_rdc.dist += this_rdc.dist;
4743
2.76M
        sum_rdc.rdcost += this_rdc.rdcost;
4744
2.76M
      }
4745
3.15M
    }
4746
4747
1.02M
    if (sum_rdc.rdcost < best_rdc.rdcost) {
4748
642k
      best_rdc = sum_rdc;
4749
642k
      pc_tree->partitioning = PARTITION_SPLIT;
4750
642k
    } else {
4751
      // skip rectangular partition test when larger block size
4752
      // gives better rd cost
4753
386k
      if (sf->less_rectangular_check) do_rect &= !partition_none_allowed;
4754
386k
    }
4755
1.02M
  }
4756
4757
  // PARTITION_HORZ
4758
3.90M
  if (partition_horz_allowed && do_rect) {
4759
0
    subsize = get_subsize(bsize, PARTITION_HORZ);
4760
0
    load_pred_mv(x, ctx);
4761
0
    pc_tree->horizontal[0].pred_pixel_ready = 1;
4762
0
    nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4763
0
                        &pc_tree->horizontal[0]);
4764
4765
0
    pc_tree->horizontal[0].mic = *xd->mi[0];
4766
0
    pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
4767
0
    pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
4768
0
    pc_tree->horizontal[0].skip = x->skip;
4769
4770
0
    if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + ms < cm->mi_rows) {
4771
0
      load_pred_mv(x, ctx);
4772
0
      pc_tree->horizontal[1].pred_pixel_ready = 1;
4773
0
      nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + ms, mi_col, &this_rdc,
4774
0
                          subsize, &pc_tree->horizontal[1]);
4775
4776
0
      pc_tree->horizontal[1].mic = *xd->mi[0];
4777
0
      pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
4778
0
      pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
4779
0
      pc_tree->horizontal[1].skip = x->skip;
4780
4781
0
      if (this_rdc.rate == INT_MAX) {
4782
0
        vp9_rd_cost_reset(&sum_rdc);
4783
0
      } else {
4784
0
        int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4785
0
        this_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
4786
0
        sum_rdc.rate += this_rdc.rate;
4787
0
        sum_rdc.dist += this_rdc.dist;
4788
0
        sum_rdc.rdcost =
4789
0
            RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4790
0
      }
4791
0
    }
4792
4793
0
    if (sum_rdc.rdcost < best_rdc.rdcost) {
4794
0
      best_rdc = sum_rdc;
4795
0
      pc_tree->partitioning = PARTITION_HORZ;
4796
0
    } else {
4797
0
      pred_pixel_ready_reset(pc_tree, bsize);
4798
0
    }
4799
0
  }
4800
4801
  // PARTITION_VERT
4802
3.90M
  if (partition_vert_allowed && do_rect) {
4803
0
    subsize = get_subsize(bsize, PARTITION_VERT);
4804
0
    load_pred_mv(x, ctx);
4805
0
    pc_tree->vertical[0].pred_pixel_ready = 1;
4806
0
    nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4807
0
                        &pc_tree->vertical[0]);
4808
0
    pc_tree->vertical[0].mic = *xd->mi[0];
4809
0
    pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
4810
0
    pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
4811
0
    pc_tree->vertical[0].skip = x->skip;
4812
4813
0
    if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + ms < cm->mi_cols) {
4814
0
      load_pred_mv(x, ctx);
4815
0
      pc_tree->vertical[1].pred_pixel_ready = 1;
4816
0
      nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + ms, &this_rdc,
4817
0
                          subsize, &pc_tree->vertical[1]);
4818
0
      pc_tree->vertical[1].mic = *xd->mi[0];
4819
0
      pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
4820
0
      pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
4821
0
      pc_tree->vertical[1].skip = x->skip;
4822
4823
0
      if (this_rdc.rate == INT_MAX) {
4824
0
        vp9_rd_cost_reset(&sum_rdc);
4825
0
      } else {
4826
0
        int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4827
0
        sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
4828
0
        sum_rdc.rate += this_rdc.rate;
4829
0
        sum_rdc.dist += this_rdc.dist;
4830
0
        sum_rdc.rdcost =
4831
0
            RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4832
0
      }
4833
0
    }
4834
4835
0
    if (sum_rdc.rdcost < best_rdc.rdcost) {
4836
0
      best_rdc = sum_rdc;
4837
0
      pc_tree->partitioning = PARTITION_VERT;
4838
0
    } else {
4839
0
      pred_pixel_ready_reset(pc_tree, bsize);
4840
0
    }
4841
0
  }
4842
4843
3.90M
  *rd_cost = best_rdc;
4844
4845
3.90M
  if (best_rdc.rate == INT_MAX) {
4846
382k
    vp9_rd_cost_reset(rd_cost);
4847
382k
    return;
4848
382k
  }
4849
4850
  // update mode info array
4851
3.52M
  fill_mode_info_sb(cm, x, mi_row, mi_col, bsize, pc_tree);
4852
4853
3.52M
  if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX && do_recon) {
4854
0
    int output_enabled = (bsize == BLOCK_64X64);
4855
0
    encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
4856
0
                 pc_tree);
4857
0
  }
4858
4859
3.52M
  if (bsize == BLOCK_64X64 && do_recon) {
4860
0
    assert(tp_orig < *tp);
4861
0
    assert(best_rdc.rate < INT_MAX);
4862
0
    assert(best_rdc.dist < INT64_MAX);
4863
3.52M
  } else {
4864
3.52M
    assert(tp_orig == *tp);
4865
3.52M
  }
4866
3.52M
}
4867
4868
static void nonrd_select_partition(VP9_COMP *cpi, ThreadData *td,
4869
                                   TileDataEnc *tile_data, MODE_INFO **mi,
4870
                                   TOKENEXTRA **tp, int mi_row, int mi_col,
4871
                                   BLOCK_SIZE bsize, int output_enabled,
4872
2.38M
                                   RD_COST *rd_cost, PC_TREE *pc_tree) {
4873
2.38M
  VP9_COMMON *const cm = &cpi->common;
4874
2.38M
  TileInfo *const tile_info = &tile_data->tile_info;
4875
2.38M
  MACROBLOCK *const x = &td->mb;
4876
2.38M
  MACROBLOCKD *const xd = &x->e_mbd;
4877
2.38M
  const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
4878
2.38M
  const int mis = cm->mi_stride;
4879
2.38M
  PARTITION_TYPE partition;
4880
2.38M
  BLOCK_SIZE subsize;
4881
2.38M
  RD_COST this_rdc;
4882
2.38M
  BLOCK_SIZE subsize_ref =
4883
2.38M
      (cpi->sf.adapt_partition_source_sad) ? BLOCK_8X8 : BLOCK_16X16;
4884
4885
2.38M
  vp9_rd_cost_reset(&this_rdc);
4886
2.38M
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
4887
4888
1.34M
  subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
4889
1.34M
  partition = partition_lookup[bsl][subsize];
4890
4891
1.34M
  if (bsize == BLOCK_32X32 && subsize == BLOCK_32X32) {
4892
24.7k
    x->max_partition_size = BLOCK_32X32;
4893
24.7k
    x->min_partition_size = BLOCK_16X16;
4894
24.7k
    nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
4895
24.7k
                         0, INT64_MAX, pc_tree);
4896
1.32M
  } else if (bsize == BLOCK_32X32 && partition != PARTITION_NONE &&
4897
439k
             subsize >= subsize_ref) {
4898
118k
    x->max_partition_size = BLOCK_32X32;
4899
118k
    x->min_partition_size = BLOCK_8X8;
4900
118k
    nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
4901
118k
                         0, INT64_MAX, pc_tree);
4902
1.20M
  } else if (bsize == BLOCK_16X16 && partition != PARTITION_NONE) {
4903
609k
    x->max_partition_size = BLOCK_16X16;
4904
609k
    x->min_partition_size = BLOCK_8X8;
4905
609k
    nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
4906
609k
                         0, INT64_MAX, pc_tree);
4907
609k
  } else {
4908
594k
    switch (partition) {
4909
53.9k
      case PARTITION_NONE:
4910
53.9k
        pc_tree->none.pred_pixel_ready = 1;
4911
53.9k
        nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
4912
53.9k
                            &pc_tree->none);
4913
53.9k
        pc_tree->none.mic = *xd->mi[0];
4914
53.9k
        pc_tree->none.mbmi_ext = *x->mbmi_ext;
4915
53.9k
        pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
4916
53.9k
        pc_tree->none.skip = x->skip;
4917
53.9k
        break;
4918
0
      case PARTITION_VERT:
4919
0
        pc_tree->vertical[0].pred_pixel_ready = 1;
4920
0
        nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
4921
0
                            &pc_tree->vertical[0]);
4922
0
        pc_tree->vertical[0].mic = *xd->mi[0];
4923
0
        pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
4924
0
        pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
4925
0
        pc_tree->vertical[0].skip = x->skip;
4926
0
        if (mi_col + hbs < cm->mi_cols) {
4927
0
          pc_tree->vertical[1].pred_pixel_ready = 1;
4928
0
          nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs,
4929
0
                              &this_rdc, subsize, &pc_tree->vertical[1]);
4930
0
          pc_tree->vertical[1].mic = *xd->mi[0];
4931
0
          pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
4932
0
          pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
4933
0
          pc_tree->vertical[1].skip = x->skip;
4934
0
          if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
4935
0
              rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
4936
0
            rd_cost->rate += this_rdc.rate;
4937
0
            rd_cost->dist += this_rdc.dist;
4938
0
          }
4939
0
        }
4940
0
        break;
4941
0
      case PARTITION_HORZ:
4942
0
        pc_tree->horizontal[0].pred_pixel_ready = 1;
4943
0
        nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
4944
0
                            &pc_tree->horizontal[0]);
4945
0
        pc_tree->horizontal[0].mic = *xd->mi[0];
4946
0
        pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
4947
0
        pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
4948
0
        pc_tree->horizontal[0].skip = x->skip;
4949
0
        if (mi_row + hbs < cm->mi_rows) {
4950
0
          pc_tree->horizontal[1].pred_pixel_ready = 1;
4951
0
          nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col,
4952
0
                              &this_rdc, subsize, &pc_tree->horizontal[1]);
4953
0
          pc_tree->horizontal[1].mic = *xd->mi[0];
4954
0
          pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
4955
0
          pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
4956
0
          pc_tree->horizontal[1].skip = x->skip;
4957
0
          if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
4958
0
              rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
4959
0
            rd_cost->rate += this_rdc.rate;
4960
0
            rd_cost->dist += this_rdc.dist;
4961
0
          }
4962
0
        }
4963
0
        break;
4964
540k
      default:
4965
540k
        assert(partition == PARTITION_SPLIT);
4966
540k
        subsize = get_subsize(bsize, PARTITION_SPLIT);
4967
540k
        nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
4968
540k
                               subsize, output_enabled, rd_cost,
4969
540k
                               pc_tree->u.split[0]);
4970
540k
        nonrd_select_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
4971
540k
                               mi_col + hbs, subsize, output_enabled, &this_rdc,
4972
540k
                               pc_tree->u.split[1]);
4973
540k
        if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
4974
257k
            rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
4975
257k
          rd_cost->rate += this_rdc.rate;
4976
257k
          rd_cost->dist += this_rdc.dist;
4977
257k
        }
4978
540k
        nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis, tp,
4979
540k
                               mi_row + hbs, mi_col, subsize, output_enabled,
4980
540k
                               &this_rdc, pc_tree->u.split[2]);
4981
540k
        if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
4982
297k
            rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
4983
297k
          rd_cost->rate += this_rdc.rate;
4984
297k
          rd_cost->dist += this_rdc.dist;
4985
297k
        }
4986
540k
        nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
4987
540k
                               mi_row + hbs, mi_col + hbs, subsize,
4988
540k
                               output_enabled, &this_rdc, pc_tree->u.split[3]);
4989
540k
        if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
4990
297k
            rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
4991
297k
          rd_cost->rate += this_rdc.rate;
4992
297k
          rd_cost->dist += this_rdc.dist;
4993
297k
        }
4994
540k
        break;
4995
594k
    }
4996
594k
  }
4997
4998
1.34M
  if (bsize == BLOCK_64X64 && output_enabled)
4999
229k
    encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, 1, bsize, pc_tree);
5000
1.34M
}
5001
5002
static void nonrd_use_partition(VP9_COMP *cpi, ThreadData *td,
5003
                                TileDataEnc *tile_data, MODE_INFO **mi,
5004
                                TOKENEXTRA **tp, int mi_row, int mi_col,
5005
                                BLOCK_SIZE bsize, int output_enabled,
5006
660k
                                RD_COST *dummy_cost, PC_TREE *pc_tree) {
5007
660k
  VP9_COMMON *const cm = &cpi->common;
5008
660k
  TileInfo *tile_info = &tile_data->tile_info;
5009
660k
  MACROBLOCK *const x = &td->mb;
5010
660k
  MACROBLOCKD *const xd = &x->e_mbd;
5011
660k
  const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
5012
660k
  const int mis = cm->mi_stride;
5013
660k
  PARTITION_TYPE partition;
5014
660k
  BLOCK_SIZE subsize;
5015
5016
660k
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
5017
5018
435k
  subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
5019
435k
  partition = partition_lookup[bsl][subsize];
5020
5021
435k
  if (output_enabled && bsize != BLOCK_4X4) {
5022
435k
    int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
5023
435k
    td->counts->partition[ctx][partition]++;
5024
435k
  }
5025
5026
435k
  switch (partition) {
5027
121k
    case PARTITION_NONE:
5028
121k
      pc_tree->none.pred_pixel_ready = 1;
5029
121k
      nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5030
121k
                          subsize, &pc_tree->none);
5031
121k
      pc_tree->none.mic = *xd->mi[0];
5032
121k
      pc_tree->none.mbmi_ext = *x->mbmi_ext;
5033
121k
      pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
5034
121k
      pc_tree->none.skip = x->skip;
5035
121k
      encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5036
121k
                  subsize, &pc_tree->none);
5037
121k
      break;
5038
681
    case PARTITION_VERT:
5039
681
      pc_tree->vertical[0].pred_pixel_ready = 1;
5040
681
      nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5041
681
                          subsize, &pc_tree->vertical[0]);
5042
681
      pc_tree->vertical[0].mic = *xd->mi[0];
5043
681
      pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5044
681
      pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5045
681
      pc_tree->vertical[0].skip = x->skip;
5046
681
      encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5047
681
                  subsize, &pc_tree->vertical[0]);
5048
681
      if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
5049
4
        pc_tree->vertical[1].pred_pixel_ready = 1;
5050
4
        nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs, dummy_cost,
5051
4
                            subsize, &pc_tree->vertical[1]);
5052
4
        pc_tree->vertical[1].mic = *xd->mi[0];
5053
4
        pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5054
4
        pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5055
4
        pc_tree->vertical[1].skip = x->skip;
5056
4
        encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col + hbs,
5057
4
                    output_enabled, subsize, &pc_tree->vertical[1]);
5058
4
      }
5059
681
      break;
5060
1.01k
    case PARTITION_HORZ:
5061
1.01k
      pc_tree->horizontal[0].pred_pixel_ready = 1;
5062
1.01k
      nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5063
1.01k
                          subsize, &pc_tree->horizontal[0]);
5064
1.01k
      pc_tree->horizontal[0].mic = *xd->mi[0];
5065
1.01k
      pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5066
1.01k
      pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5067
1.01k
      pc_tree->horizontal[0].skip = x->skip;
5068
1.01k
      encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5069
1.01k
                  subsize, &pc_tree->horizontal[0]);
5070
5071
1.01k
      if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
5072
17
        pc_tree->horizontal[1].pred_pixel_ready = 1;
5073
17
        nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col, dummy_cost,
5074
17
                            subsize, &pc_tree->horizontal[1]);
5075
17
        pc_tree->horizontal[1].mic = *xd->mi[0];
5076
17
        pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5077
17
        pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5078
17
        pc_tree->horizontal[1].skip = x->skip;
5079
17
        encode_b_rt(cpi, td, tile_info, tp, mi_row + hbs, mi_col,
5080
17
                    output_enabled, subsize, &pc_tree->horizontal[1]);
5081
17
      }
5082
1.01k
      break;
5083
312k
    default:
5084
312k
      assert(partition == PARTITION_SPLIT);
5085
312k
      subsize = get_subsize(bsize, PARTITION_SPLIT);
5086
312k
      if (bsize == BLOCK_8X8) {
5087
154k
        nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5088
154k
                            subsize, pc_tree->u.leaf_split[0]);
5089
154k
        encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5090
154k
                    subsize, pc_tree->u.leaf_split[0]);
5091
157k
      } else {
5092
157k
        nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, subsize,
5093
157k
                            output_enabled, dummy_cost, pc_tree->u.split[0]);
5094
157k
        nonrd_use_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
5095
157k
                            mi_col + hbs, subsize, output_enabled, dummy_cost,
5096
157k
                            pc_tree->u.split[1]);
5097
157k
        nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis, tp,
5098
157k
                            mi_row + hbs, mi_col, subsize, output_enabled,
5099
157k
                            dummy_cost, pc_tree->u.split[2]);
5100
157k
        nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
5101
157k
                            mi_row + hbs, mi_col + hbs, subsize, output_enabled,
5102
157k
                            dummy_cost, pc_tree->u.split[3]);
5103
157k
      }
5104
312k
      break;
5105
435k
  }
5106
5107
435k
  if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
5108
277k
    update_partition_context(xd, mi_row, mi_col, subsize, bsize);
5109
435k
}
5110
5111
// Get a prediction(stored in x->est_pred) for the whole 64x64 superblock.
5112
static void get_estimated_pred(VP9_COMP *cpi, const TileInfo *const tile,
5113
0
                               MACROBLOCK *x, int mi_row, int mi_col) {
5114
0
  VP9_COMMON *const cm = &cpi->common;
5115
0
  const int is_key_frame = frame_is_intra_only(cm);
5116
0
  MACROBLOCKD *xd = &x->e_mbd;
5117
5118
0
  set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
5119
5120
0
  if (!is_key_frame) {
5121
0
    MODE_INFO *mi = xd->mi[0];
5122
0
    YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
5123
0
    const YV12_BUFFER_CONFIG *yv12_g = NULL;
5124
0
    const BLOCK_SIZE bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
5125
0
                             (mi_row + 4 < cm->mi_rows);
5126
0
    unsigned int y_sad_g, y_sad_thr;
5127
0
    unsigned int y_sad = UINT_MAX;
5128
5129
0
    assert(yv12 != NULL);
5130
5131
0
    if (!(is_one_pass_svc(cpi) && cpi->svc.spatial_layer_id) ||
5132
0
        cpi->svc.use_gf_temporal_ref_current_layer) {
5133
      // For now, GOLDEN will not be used for non-zero spatial layers, since
5134
      // it may not be a temporal reference.
5135
0
      yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
5136
0
    }
5137
5138
    // Only compute y_sad_g (sad for golden reference) for speed < 8.
5139
0
    if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
5140
0
        (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
5141
0
      vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
5142
0
                           &cm->frame_refs[GOLDEN_FRAME - 1].sf);
5143
0
      y_sad_g = cpi->fn_ptr[bsize].sdf(
5144
0
          x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
5145
0
          xd->plane[0].pre[0].stride);
5146
0
    } else {
5147
0
      y_sad_g = UINT_MAX;
5148
0
    }
5149
5150
0
    if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
5151
0
        cpi->rc.is_src_frame_alt_ref) {
5152
0
      yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
5153
0
      vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
5154
0
                           &cm->frame_refs[ALTREF_FRAME - 1].sf);
5155
0
      mi->ref_frame[0] = ALTREF_FRAME;
5156
0
      y_sad_g = UINT_MAX;
5157
0
    } else {
5158
0
      vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
5159
0
                           &cm->frame_refs[LAST_FRAME - 1].sf);
5160
0
      mi->ref_frame[0] = LAST_FRAME;
5161
0
    }
5162
0
    mi->ref_frame[1] = NO_REF_FRAME;
5163
0
    mi->sb_type = BLOCK_64X64;
5164
0
    mi->mv[0].as_int = 0;
5165
0
    mi->interp_filter = BILINEAR;
5166
5167
0
    {
5168
0
      const MV dummy_mv = { 0, 0 };
5169
0
      y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
5170
0
                                            &dummy_mv);
5171
0
      x->sb_use_mv_part = 1;
5172
0
      x->sb_mvcol_part = mi->mv[0].as_mv.col;
5173
0
      x->sb_mvrow_part = mi->mv[0].as_mv.row;
5174
0
    }
5175
5176
    // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
5177
    // are close if short_circuit_low_temp_var is on.
5178
0
    y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
5179
0
    if (y_sad_g < y_sad_thr) {
5180
0
      vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
5181
0
                           &cm->frame_refs[GOLDEN_FRAME - 1].sf);
5182
0
      mi->ref_frame[0] = GOLDEN_FRAME;
5183
0
      mi->mv[0].as_int = 0;
5184
0
    } else {
5185
0
      x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
5186
0
    }
5187
5188
0
    set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
5189
0
    xd->plane[0].dst.buf = x->est_pred;
5190
0
    xd->plane[0].dst.stride = 64;
5191
0
    vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
5192
0
  } else {
5193
0
#if CONFIG_VP9_HIGHBITDEPTH
5194
0
    switch (xd->bd) {
5195
0
      case 8: memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0])); break;
5196
0
      case 10:
5197
0
        memset(x->est_pred, 128 * 4, 64 * 64 * sizeof(x->est_pred[0]));
5198
0
        break;
5199
0
      case 12:
5200
0
        memset(x->est_pred, 128 * 16, 64 * 64 * sizeof(x->est_pred[0]));
5201
0
        break;
5202
0
    }
5203
#else
5204
    memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0]));
5205
#endif  // CONFIG_VP9_HIGHBITDEPTH
5206
0
  }
5207
0
}
5208
5209
static void encode_nonrd_sb_row(VP9_COMP *cpi, ThreadData *td,
5210
                                TileDataEnc *tile_data, int mi_row,
5211
258k
                                TOKENEXTRA **tp) {
5212
258k
  SPEED_FEATURES *const sf = &cpi->sf;
5213
258k
  VP9_COMMON *const cm = &cpi->common;
5214
258k
  TileInfo *const tile_info = &tile_data->tile_info;
5215
258k
  MACROBLOCK *const x = &td->mb;
5216
258k
  MACROBLOCKD *const xd = &x->e_mbd;
5217
258k
  const int mi_col_start = tile_info->mi_col_start;
5218
258k
  const int mi_col_end = tile_info->mi_col_end;
5219
258k
  int mi_col;
5220
258k
  const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
5221
258k
  const int num_sb_cols =
5222
258k
      get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
5223
258k
  int sb_col_in_tile;
5224
5225
  // Initialize the left context for the new SB row
5226
258k
  memset(&xd->left_context, 0, sizeof(xd->left_context));
5227
258k
  memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
5228
5229
  // Code each SB in the row
5230
516k
  for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
5231
258k
       mi_col += MI_BLOCK_SIZE, ++sb_col_in_tile) {
5232
258k
    const struct segmentation *const seg = &cm->seg;
5233
258k
    RD_COST dummy_rdc;
5234
258k
    const int idx_str = cm->mi_stride * mi_row + mi_col;
5235
258k
    MODE_INFO **mi = cm->mi_grid_visible + idx_str;
5236
258k
    PARTITION_SEARCH_TYPE partition_search_type = sf->partition_search_type;
5237
258k
    BLOCK_SIZE bsize = BLOCK_64X64;
5238
258k
    int seg_skip = 0;
5239
258k
    int i;
5240
5241
258k
    (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
5242
258k
                                   sb_col_in_tile);
5243
5244
258k
    if (cpi->use_skin_detection) {
5245
0
      vp9_compute_skin_sb(cpi, BLOCK_16X16, mi_row, mi_col);
5246
0
    }
5247
5248
258k
    x->source_variance = UINT_MAX;
5249
1.29M
    for (i = 0; i < MAX_REF_FRAMES; ++i) {
5250
1.03M
      x->pred_mv[i].row = INT16_MAX;
5251
1.03M
      x->pred_mv[i].col = INT16_MAX;
5252
1.03M
    }
5253
258k
    vp9_rd_cost_init(&dummy_rdc);
5254
258k
    x->color_sensitivity[0] = 0;
5255
258k
    x->color_sensitivity[1] = 0;
5256
258k
    x->sb_is_skin = 0;
5257
258k
    x->skip_low_source_sad = 0;
5258
258k
    x->lowvar_highsumdiff = 0;
5259
258k
    x->content_state_sb = 0;
5260
258k
    x->zero_temp_sad_source = 0;
5261
258k
    x->sb_use_mv_part = 0;
5262
258k
    x->sb_mvcol_part = 0;
5263
258k
    x->sb_mvrow_part = 0;
5264
258k
    x->sb_pickmode_part = 0;
5265
258k
    x->arf_frame_usage = 0;
5266
258k
    x->lastgolden_frame_usage = 0;
5267
5268
258k
    if (cpi->compute_source_sad_onepass && cpi->sf.use_source_sad) {
5269
254k
      int shift = cpi->Source->y_stride * (mi_row << 3) + (mi_col << 3);
5270
254k
      int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5271
254k
      int64_t source_sad = avg_source_sad(cpi, x, shift, sb_offset2);
5272
254k
      if (sf->adapt_partition_source_sad &&
5273
0
          (cpi->oxcf.rc_mode == VPX_VBR && !cpi->rc.is_src_frame_alt_ref &&
5274
0
           source_sad > sf->adapt_partition_thresh &&
5275
0
           (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)))
5276
0
        partition_search_type = REFERENCE_PARTITION;
5277
254k
    }
5278
5279
258k
    if (seg->enabled) {
5280
0
      const uint8_t *const map =
5281
0
          seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
5282
0
      int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
5283
0
      seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
5284
5285
0
      if (cpi->roi.enabled && cpi->roi.skip[BACKGROUND_SEG_SKIP_ID] &&
5286
0
          cpi->rc.frames_since_key > FRAMES_NO_SKIPPING_AFTER_KEY &&
5287
0
          x->content_state_sb > kLowSadLowSumdiff) {
5288
        // For ROI with skip, force segment = 0 (no skip) over whole
5289
        // superblock to avoid artifacts if temporal change in source_sad is
5290
        // not 0.
5291
0
        int xi, yi;
5292
0
        const int bw = num_8x8_blocks_wide_lookup[BLOCK_64X64];
5293
0
        const int bh = num_8x8_blocks_high_lookup[BLOCK_64X64];
5294
0
        const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
5295
0
        const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
5296
0
        const int block_index = mi_row * cm->mi_cols + mi_col;
5297
0
        set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
5298
0
        for (yi = 0; yi < ymis; yi++)
5299
0
          for (xi = 0; xi < xmis; xi++) {
5300
0
            int map_offset = block_index + yi * cm->mi_cols + xi;
5301
0
            cpi->segmentation_map[map_offset] = 0;
5302
0
          }
5303
0
        set_segment_index(cpi, x, mi_row, mi_col, BLOCK_64X64, 0);
5304
0
        seg_skip = 0;
5305
0
      }
5306
0
      if (seg_skip) {
5307
0
        partition_search_type = FIXED_PARTITION;
5308
0
      }
5309
0
    }
5310
5311
    // Set the partition type of the 64X64 block
5312
258k
    switch (partition_search_type) {
5313
148
      case VAR_BASED_PARTITION:
5314
        // TODO(jingning, marpan): The mode decision and encoding process
5315
        // support both intra and inter sub8x8 block coding for RTC mode.
5316
        // Tune the thresholds accordingly to use sub8x8 block coding for
5317
        // coding performance improvement.
5318
148
        choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5319
148
        nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5320
148
                            BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5321
148
        break;
5322
0
      case ML_BASED_PARTITION:
5323
0
        get_estimated_pred(cpi, tile_info, x, mi_row, mi_col);
5324
0
        x->max_partition_size = BLOCK_64X64;
5325
0
        x->min_partition_size = BLOCK_8X8;
5326
0
        x->sb_pickmode_part = 1;
5327
0
        nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
5328
0
                             BLOCK_64X64, &dummy_rdc, 1, INT64_MAX,
5329
0
                             td->pc_root);
5330
0
        break;
5331
10.5k
      case FIXED_PARTITION:
5332
10.5k
        if (!seg_skip) bsize = sf->always_this_block_size;
5333
10.5k
        set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
5334
10.5k
        nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5335
10.5k
                            BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5336
10.5k
        break;
5337
247k
      default:
5338
247k
        assert(partition_search_type == REFERENCE_PARTITION);
5339
247k
        x->sb_pickmode_part = 1;
5340
247k
        set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
5341
        // Use nonrd_pick_partition on scene-cut for VBR mode.
5342
        // nonrd_pick_partition does not support 4x4 partition, so avoid it
5343
        // on key frame for now.
5344
247k
        if ((cpi->oxcf.rc_mode == VPX_VBR && cpi->rc.high_source_sad &&
5345
0
             cpi->oxcf.speed < 6 && !frame_is_intra_only(cm) &&
5346
0
             (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
5347
          // Use lower max_partition_size for low resolutions.
5348
0
          if (cm->width <= 352 && cm->height <= 288)
5349
0
            x->max_partition_size = BLOCK_32X32;
5350
0
          else
5351
0
            x->max_partition_size = BLOCK_64X64;
5352
0
          x->min_partition_size = BLOCK_8X8;
5353
0
          nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col,
5354
0
                               BLOCK_64X64, &dummy_rdc, 1, INT64_MAX,
5355
0
                               td->pc_root);
5356
247k
        } else {
5357
247k
          choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5358
          // TODO(marpan): Seems like nonrd_select_partition does not support
5359
          // 4x4 partition. Since 4x4 is used on key frame, use this switch
5360
          // for now.
5361
247k
          if (frame_is_intra_only(cm))
5362
18.6k
            nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5363
18.6k
                                BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5364
229k
          else
5365
229k
            nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5366
229k
                                   BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5367
247k
        }
5368
5369
247k
        break;
5370
258k
    }
5371
5372
    // Update ref_frame usage for inter frame if this group is ARF group.
5373
258k
    if (!cpi->rc.is_src_frame_alt_ref && !cpi->refresh_golden_frame &&
5374
221k
        !cpi->refresh_alt_ref_frame && cpi->rc.alt_ref_gf_group &&
5375
116k
        cpi->sf.use_altref_onepass) {
5376
116k
      int sboffset = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5377
116k
      if (cpi->count_arf_frame_usage != NULL)
5378
116k
        cpi->count_arf_frame_usage[sboffset] = x->arf_frame_usage;
5379
116k
      if (cpi->count_lastgolden_frame_usage != NULL)
5380
116k
        cpi->count_lastgolden_frame_usage[sboffset] = x->lastgolden_frame_usage;
5381
116k
    }
5382
5383
258k
    (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
5384
258k
                                    sb_col_in_tile, num_sb_cols);
5385
258k
  }
5386
258k
}
5387
// end RTC play code
5388
5389
258k
static int get_skip_encode_frame(const VP9_COMMON *cm, ThreadData *const td) {
5390
258k
  unsigned int intra_count = 0, inter_count = 0;
5391
258k
  int j;
5392
5393
1.29M
  for (j = 0; j < INTRA_INTER_CONTEXTS; ++j) {
5394
1.03M
    intra_count += td->counts->intra_inter[j][0];
5395
1.03M
    inter_count += td->counts->intra_inter[j][1];
5396
1.03M
  }
5397
5398
258k
  return (intra_count << 2) < inter_count && cm->frame_type != KEY_FRAME &&
5399
143k
         cm->show_frame;
5400
258k
}
5401
5402
452k
void vp9_init_tile_data(VP9_COMP *cpi) {
5403
452k
  VP9_COMMON *const cm = &cpi->common;
5404
452k
  const int tile_cols = 1 << cm->log2_tile_cols;
5405
452k
  const int tile_rows = 1 << cm->log2_tile_rows;
5406
452k
  int tile_col, tile_row;
5407
452k
  TOKENEXTRA *pre_tok = cpi->tile_tok[0][0];
5408
452k
  TOKENLIST *tplist = cpi->tplist[0][0];
5409
452k
  int64_t tile_tok = 0;
5410
452k
  int tplist_count = 0;
5411
5412
452k
  if (cpi->tile_data == NULL || cpi->allocated_tiles < tile_cols * tile_rows) {
5413
10.6k
    if (cpi->tile_data != NULL) {
5414
      // Free the row mt memory in cpi->tile_data first.
5415
0
      vp9_row_mt_mem_dealloc(cpi);
5416
0
      vpx_free(cpi->tile_data);
5417
0
    }
5418
10.6k
    cpi->allocated_tiles = 0;
5419
10.6k
    CHECK_MEM_ERROR(
5420
10.6k
        &cm->error, cpi->tile_data,
5421
10.6k
        vpx_malloc(tile_cols * tile_rows * sizeof(*cpi->tile_data)));
5422
10.6k
    cpi->allocated_tiles = tile_cols * tile_rows;
5423
5424
21.2k
    for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5425
21.2k
      for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5426
10.6k
        TileDataEnc *tile_data =
5427
10.6k
            &cpi->tile_data[tile_row * tile_cols + tile_col];
5428
10.6k
        int i, j;
5429
10.6k
        const MV zero_mv = { 0, 0 };
5430
148k
        for (i = 0; i < BLOCK_SIZES; ++i) {
5431
4.28M
          for (j = 0; j < MAX_MODES; ++j) {
5432
4.14M
            tile_data->thresh_freq_fact[i][j] = RD_THRESH_INIT_FACT;
5433
4.14M
            tile_data->thresh_freq_fact_prev[i][j] = RD_THRESH_INIT_FACT;
5434
4.14M
            tile_data->mode_map[i][j] = j;
5435
4.14M
          }
5436
138k
        }
5437
10.6k
        tile_data->firstpass_top_mv = zero_mv;
5438
10.6k
#if CONFIG_MULTITHREAD
5439
10.6k
        tile_data->row_base_thresh_freq_fact = NULL;
5440
10.6k
#endif
5441
10.6k
      }
5442
10.6k
  }
5443
5444
904k
  for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
5445
904k
    for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5446
452k
      TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5447
452k
      TileInfo *tile_info = &this_tile->tile_info;
5448
452k
      if (cpi->sf.adaptive_rd_thresh_row_mt) {
5449
0
        vp9_row_mt_alloc_rd_thresh(cpi, this_tile);
5450
0
      }
5451
452k
      vp9_tile_init(tile_info, cm, tile_row, tile_col);
5452
5453
452k
      cpi->tile_tok[tile_row][tile_col] = pre_tok + tile_tok;
5454
452k
      pre_tok = cpi->tile_tok[tile_row][tile_col];
5455
452k
      tile_tok = allocated_tokens(*tile_info);
5456
5457
452k
      cpi->tplist[tile_row][tile_col] = tplist + tplist_count;
5458
452k
      tplist = cpi->tplist[tile_row][tile_col];
5459
452k
      tplist_count = get_num_vert_units(*tile_info, MI_BLOCK_SIZE_LOG2);
5460
452k
    }
5461
452k
  }
5462
452k
}
5463
5464
void vp9_encode_sb_row(VP9_COMP *cpi, ThreadData *td, int tile_row,
5465
452k
                       int tile_col, int mi_row) {
5466
452k
  VP9_COMMON *const cm = &cpi->common;
5467
452k
  const int tile_cols = 1 << cm->log2_tile_cols;
5468
452k
  TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5469
452k
  const TileInfo *const tile_info = &this_tile->tile_info;
5470
452k
  TOKENEXTRA *tok = NULL;
5471
452k
  int tile_sb_row;
5472
452k
  int tile_mb_cols = (tile_info->mi_col_end - tile_info->mi_col_start + 1) >> 1;
5473
5474
452k
  tile_sb_row = mi_cols_aligned_to_sb(mi_row - tile_info->mi_row_start) >>
5475
452k
                MI_BLOCK_SIZE_LOG2;
5476
452k
  get_start_tok(cpi, tile_row, tile_col, mi_row, &tok);
5477
452k
  cpi->tplist[tile_row][tile_col][tile_sb_row].start = tok;
5478
5479
#if CONFIG_REALTIME_ONLY
5480
  assert(cpi->sf.use_nonrd_pick_mode);
5481
  encode_nonrd_sb_row(cpi, td, this_tile, mi_row, &tok);
5482
#else
5483
452k
  if (cpi->sf.use_nonrd_pick_mode)
5484
258k
    encode_nonrd_sb_row(cpi, td, this_tile, mi_row, &tok);
5485
193k
  else
5486
193k
    encode_rd_sb_row(cpi, td, this_tile, mi_row, &tok);
5487
452k
#endif
5488
5489
452k
  cpi->tplist[tile_row][tile_col][tile_sb_row].stop = tok;
5490
452k
  cpi->tplist[tile_row][tile_col][tile_sb_row].count =
5491
452k
      (unsigned int)(cpi->tplist[tile_row][tile_col][tile_sb_row].stop -
5492
452k
                     cpi->tplist[tile_row][tile_col][tile_sb_row].start);
5493
452k
  assert(tok - cpi->tplist[tile_row][tile_col][tile_sb_row].start <=
5494
452k
         get_token_alloc(MI_BLOCK_SIZE >> 1, tile_mb_cols));
5495
5496
452k
  (void)tile_mb_cols;
5497
452k
}
5498
5499
void vp9_encode_tile(VP9_COMP *cpi, ThreadData *td, int tile_row,
5500
452k
                     int tile_col) {
5501
452k
  VP9_COMMON *const cm = &cpi->common;
5502
452k
  const int tile_cols = 1 << cm->log2_tile_cols;
5503
452k
  TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5504
452k
  const TileInfo *const tile_info = &this_tile->tile_info;
5505
452k
  const int mi_row_start = tile_info->mi_row_start;
5506
452k
  const int mi_row_end = tile_info->mi_row_end;
5507
452k
  int mi_row;
5508
5509
904k
  for (mi_row = mi_row_start; mi_row < mi_row_end; mi_row += MI_BLOCK_SIZE)
5510
452k
    vp9_encode_sb_row(cpi, td, tile_row, tile_col, mi_row);
5511
452k
}
5512
5513
452k
static void encode_tiles(VP9_COMP *cpi) {
5514
452k
  VP9_COMMON *const cm = &cpi->common;
5515
452k
  const int tile_cols = 1 << cm->log2_tile_cols;
5516
452k
  const int tile_rows = 1 << cm->log2_tile_rows;
5517
452k
  int tile_col, tile_row;
5518
5519
452k
  vp9_init_tile_data(cpi);
5520
5521
904k
  for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5522
904k
    for (tile_col = 0; tile_col < tile_cols; ++tile_col)
5523
452k
      vp9_encode_tile(cpi, &cpi->td, tile_row, tile_col);
5524
452k
}
5525
5526
0
static int compare_kmeans_data(const void *a, const void *b) {
5527
0
  if (((const KMEANS_DATA *)a)->value > ((const KMEANS_DATA *)b)->value) {
5528
0
    return 1;
5529
0
  } else if (((const KMEANS_DATA *)a)->value <
5530
0
             ((const KMEANS_DATA *)b)->value) {
5531
0
    return -1;
5532
0
  } else {
5533
0
    return 0;
5534
0
  }
5535
0
}
5536
5537
static void compute_boundary_ls(const double *ctr_ls, int k,
5538
0
                                double *boundary_ls) {
5539
  // boundary_ls[j] is the upper bound of data centered at ctr_ls[j]
5540
0
  int j;
5541
0
  for (j = 0; j < k - 1; ++j) {
5542
0
    boundary_ls[j] = (ctr_ls[j] + ctr_ls[j + 1]) / 2.;
5543
0
  }
5544
0
  boundary_ls[k - 1] = DBL_MAX;
5545
0
}
5546
5547
0
int vp9_get_group_idx(double value, double *boundary_ls, int k) {
5548
0
  int group_idx = 0;
5549
0
  while (value >= boundary_ls[group_idx]) {
5550
0
    ++group_idx;
5551
0
    if (group_idx == k - 1) {
5552
0
      break;
5553
0
    }
5554
0
  }
5555
0
  return group_idx;
5556
0
}
5557
5558
void vp9_kmeans(double *ctr_ls, double *boundary_ls, int *count_ls, int k,
5559
0
                KMEANS_DATA *arr, int size) {
5560
0
  int i, j;
5561
0
  int itr;
5562
0
  int group_idx;
5563
0
  double sum[MAX_KMEANS_GROUPS];
5564
0
  int count[MAX_KMEANS_GROUPS];
5565
5566
0
  vpx_clear_system_state();
5567
5568
0
  assert(k >= 2 && k <= MAX_KMEANS_GROUPS);
5569
5570
0
  qsort(arr, size, sizeof(*arr), compare_kmeans_data);
5571
5572
  // initialize the center points
5573
0
  for (j = 0; j < k; ++j) {
5574
0
    ctr_ls[j] = arr[(size * (2 * j + 1)) / (2 * k)].value;
5575
0
  }
5576
5577
0
  for (itr = 0; itr < 10; ++itr) {
5578
0
    compute_boundary_ls(ctr_ls, k, boundary_ls);
5579
0
    for (i = 0; i < MAX_KMEANS_GROUPS; ++i) {
5580
0
      sum[i] = 0;
5581
0
      count[i] = 0;
5582
0
    }
5583
5584
    // Both the data and centers are sorted in ascending order.
5585
    // As each data point is processed in order, its corresponding group index
5586
    // can only increase. So we only need to reset the group index to zero here.
5587
0
    group_idx = 0;
5588
0
    for (i = 0; i < size; ++i) {
5589
0
      while (arr[i].value >= boundary_ls[group_idx]) {
5590
        // place samples into clusters
5591
0
        ++group_idx;
5592
0
        if (group_idx == k - 1) {
5593
0
          break;
5594
0
        }
5595
0
      }
5596
0
      sum[group_idx] += arr[i].value;
5597
0
      ++count[group_idx];
5598
0
    }
5599
5600
0
    for (group_idx = 0; group_idx < k; ++group_idx) {
5601
0
      if (count[group_idx] > 0)
5602
0
        ctr_ls[group_idx] = sum[group_idx] / count[group_idx];
5603
5604
0
      sum[group_idx] = 0;
5605
0
      count[group_idx] = 0;
5606
0
    }
5607
0
  }
5608
5609
  // compute group_idx, boundary_ls and count_ls
5610
0
  for (j = 0; j < k; ++j) {
5611
0
    count_ls[j] = 0;
5612
0
  }
5613
0
  compute_boundary_ls(ctr_ls, k, boundary_ls);
5614
0
  group_idx = 0;
5615
0
  for (i = 0; i < size; ++i) {
5616
0
    while (arr[i].value >= boundary_ls[group_idx]) {
5617
0
      ++group_idx;
5618
0
      if (group_idx == k - 1) {
5619
0
        break;
5620
0
      }
5621
0
    }
5622
0
    arr[i].group_idx = group_idx;
5623
0
    ++count_ls[group_idx];
5624
0
  }
5625
0
}
5626
5627
452k
static void encode_frame_internal(VP9_COMP *cpi) {
5628
452k
  SPEED_FEATURES *const sf = &cpi->sf;
5629
452k
  ThreadData *const td = &cpi->td;
5630
452k
  MACROBLOCK *const x = &td->mb;
5631
452k
  VP9_COMMON *const cm = &cpi->common;
5632
452k
  MACROBLOCKD *const xd = &x->e_mbd;
5633
452k
  const int gf_group_index = cpi->twopass.gf_group.index;
5634
5635
452k
  xd->mi = cm->mi_grid_visible;
5636
452k
  xd->mi[0] = cm->mi;
5637
452k
  vp9_zero(*td->counts);
5638
452k
  vp9_zero(cpi->td.rd_counts);
5639
5640
452k
  xd->lossless = cm->base_qindex == 0 && cm->y_dc_delta_q == 0 &&
5641
41.1k
                 cm->uv_dc_delta_q == 0 && cm->uv_ac_delta_q == 0;
5642
5643
452k
#if CONFIG_VP9_HIGHBITDEPTH
5644
452k
  if (cm->use_highbitdepth)
5645
0
    x->fwd_txfm4x4 = xd->lossless ? vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
5646
452k
  else
5647
452k
    x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
5648
452k
  x->highbd_inv_txfm_add =
5649
452k
      xd->lossless ? vp9_highbd_iwht4x4_add : vp9_highbd_idct4x4_add;
5650
#else
5651
  x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
5652
#endif  // CONFIG_VP9_HIGHBITDEPTH
5653
452k
  x->inv_txfm_add = xd->lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
5654
452k
  x->optimize = sf->optimize_coefficients == 1 && cpi->oxcf.pass != 1;
5655
452k
  if (xd->lossless) x->optimize = 0;
5656
452k
  x->sharpness = cpi->oxcf.sharpness;
5657
452k
  x->adjust_rdmult_by_segment = (cpi->oxcf.aq_mode == VARIANCE_AQ);
5658
5659
452k
  cm->tx_mode = select_tx_mode(cpi, xd);
5660
5661
452k
  vp9_frame_init_quantizer(cpi);
5662
5663
452k
  vp9_initialize_rd_consts(cpi);
5664
452k
  vp9_initialize_me_consts(cpi, x, cm->base_qindex);
5665
452k
  init_encode_frame_mb_context(cpi);
5666
452k
  cm->use_prev_frame_mvs =
5667
452k
      !cm->error_resilient_mode && cm->width == cm->last_width &&
5668
0
      cm->height == cm->last_height && !cm->intra_only && cm->last_show_frame;
5669
  // Special case: set prev_mi to NULL when the previous mode info
5670
  // context cannot be used.
5671
452k
  cm->prev_mi =
5672
452k
      cm->use_prev_frame_mvs ? cm->prev_mip + cm->mi_stride + 1 : NULL;
5673
5674
452k
  x->quant_fp = cpi->sf.use_quant_fp;
5675
452k
  vp9_zero(x->skip_txfm);
5676
452k
  if (sf->use_nonrd_pick_mode) {
5677
    // Initialize internal buffer pointers for rtc coding, where non-RD
5678
    // mode decision is used and hence no buffer pointer swap needed.
5679
258k
    int i;
5680
258k
    struct macroblock_plane *const p = x->plane;
5681
258k
    struct macroblockd_plane *const pd = xd->plane;
5682
258k
    PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
5683
5684
1.03M
    for (i = 0; i < MAX_MB_PLANE; ++i) {
5685
775k
      p[i].coeff = ctx->coeff_pbuf[i][0];
5686
775k
      p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
5687
775k
      pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
5688
775k
      p[i].eobs = ctx->eobs_pbuf[i][0];
5689
775k
    }
5690
258k
    vp9_zero(x->zcoeff_blk);
5691
5692
258k
    if (cm->frame_type != KEY_FRAME && cpi->rc.frames_since_golden == 0 &&
5693
46.8k
        !(cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR) &&
5694
0
        !cpi->use_svc)
5695
0
      cpi->ref_frame_flags &= (~VP9_GOLD_FLAG);
5696
258k
  } else if (gf_group_index && gf_group_index < MAX_ARF_GOP_SIZE &&
5697
0
             cpi->sf.enable_tpl_model) {
5698
0
    TplDepFrame *tpl_frame = &cpi->tpl_stats[cpi->twopass.gf_group.index];
5699
0
    TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr;
5700
5701
0
    int tpl_stride = tpl_frame->stride;
5702
0
    int64_t intra_cost_base = 0;
5703
0
    int64_t mc_dep_cost_base = 0;
5704
0
    int row, col;
5705
5706
0
    for (row = 0; row < cm->mi_rows && tpl_frame->is_valid; ++row) {
5707
0
      for (col = 0; col < cm->mi_cols; ++col) {
5708
0
        TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
5709
0
        intra_cost_base += this_stats->intra_cost;
5710
0
        mc_dep_cost_base += this_stats->mc_dep_cost;
5711
0
      }
5712
0
    }
5713
5714
0
    vpx_clear_system_state();
5715
5716
0
    if (tpl_frame->is_valid)
5717
0
      cpi->rd.r0 = (double)intra_cost_base / mc_dep_cost_base;
5718
0
  }
5719
5720
1.80M
  for (MV_REFERENCE_FRAME ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME;
5721
1.35M
       ++ref_frame) {
5722
1.35M
    if (cpi->ref_frame_flags & ref_frame_to_flag(ref_frame)) {
5723
1.12M
      if (cm->frame_refs[ref_frame - 1].sf.x_scale_fp == REF_INVALID_SCALE ||
5724
1.12M
          cm->frame_refs[ref_frame - 1].sf.y_scale_fp == REF_INVALID_SCALE)
5725
0
        cpi->ref_frame_flags &= ~ref_frame_to_flag(ref_frame);
5726
1.12M
    }
5727
1.35M
  }
5728
5729
  // Frame segmentation
5730
452k
  if (cpi->oxcf.aq_mode == PERCEPTUAL_AQ) build_kmeans_segmentation(cpi);
5731
5732
452k
  {
5733
#if CONFIG_INTERNAL_STATS
5734
    struct vpx_usec_timer emr_timer;
5735
    vpx_usec_timer_start(&emr_timer);
5736
#endif
5737
5738
452k
    if (!cpi->row_mt) {
5739
452k
      cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read_dummy;
5740
452k
      cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write_dummy;
5741
      // If allowed, encoding tiles in parallel with one thread handling one
5742
      // tile when row based multi-threading is disabled.
5743
452k
      if (VPXMIN(cpi->oxcf.max_threads, 1 << cm->log2_tile_cols) > 1)
5744
0
        vp9_encode_tiles_mt(cpi);
5745
452k
      else
5746
452k
        encode_tiles(cpi);
5747
452k
    } else {
5748
0
      cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read;
5749
0
      cpi->row_mt_sync_write_ptr = vp9_row_mt_sync_write;
5750
0
      vp9_encode_tiles_row_mt(cpi);
5751
0
    }
5752
5753
#if CONFIG_INTERNAL_STATS
5754
    vpx_usec_timer_mark(&emr_timer);
5755
    cpi->time_encode_sb_row += vpx_usec_timer_elapsed(&emr_timer);
5756
#endif
5757
452k
  }
5758
5759
452k
  sf->skip_encode_frame =
5760
452k
      sf->skip_encode_sb ? get_skip_encode_frame(cm, td) : 0;
5761
5762
#if 0
5763
  // Keep record of the total distortion this time around for future use
5764
  cpi->last_frame_distortion = cpi->frame_distortion;
5765
#endif
5766
452k
}
5767
5768
static INTERP_FILTER get_interp_filter(
5769
193k
    const int64_t threshes[SWITCHABLE_FILTER_CONTEXTS], int is_alt_ref) {
5770
193k
  if (!is_alt_ref && threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP] &&
5771
38.3k
      threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP_SHARP] &&
5772
37.1k
      threshes[EIGHTTAP_SMOOTH] > threshes[SWITCHABLE - 1]) {
5773
26.4k
    return EIGHTTAP_SMOOTH;
5774
167k
  } else if (threshes[EIGHTTAP_SHARP] > threshes[EIGHTTAP] &&
5775
17.0k
             threshes[EIGHTTAP_SHARP] > threshes[SWITCHABLE - 1]) {
5776
12.2k
    return EIGHTTAP_SHARP;
5777
155k
  } else if (threshes[EIGHTTAP] > threshes[SWITCHABLE - 1]) {
5778
92.5k
    return EIGHTTAP;
5779
92.5k
  } else {
5780
62.6k
    return SWITCHABLE;
5781
62.6k
  }
5782
193k
}
5783
5784
0
static int compute_frame_aq_offset(struct VP9_COMP *cpi) {
5785
0
  VP9_COMMON *const cm = &cpi->common;
5786
0
  MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
5787
0
  struct segmentation *const seg = &cm->seg;
5788
5789
0
  int mi_row, mi_col;
5790
0
  int sum_delta = 0;
5791
0
  int qdelta_index;
5792
0
  int segment_id;
5793
5794
0
  for (mi_row = 0; mi_row < cm->mi_rows; mi_row++) {
5795
0
    MODE_INFO **mi_8x8 = mi_8x8_ptr;
5796
0
    for (mi_col = 0; mi_col < cm->mi_cols; mi_col++, mi_8x8++) {
5797
0
      segment_id = mi_8x8[0]->segment_id;
5798
0
      qdelta_index = get_segdata(seg, segment_id, SEG_LVL_ALT_Q);
5799
0
      sum_delta += qdelta_index;
5800
0
    }
5801
0
    mi_8x8_ptr += cm->mi_stride;
5802
0
  }
5803
5804
0
  return sum_delta / (cm->mi_rows * cm->mi_cols);
5805
0
}
5806
5807
452k
static void restore_encode_params(VP9_COMP *cpi) {
5808
452k
  VP9_COMMON *const cm = &cpi->common;
5809
452k
  int tile_idx;
5810
452k
  int i, j;
5811
452k
  TileDataEnc *tile_data;
5812
452k
  RD_OPT *rd_opt = &cpi->rd;
5813
2.26M
  for (i = 0; i < MAX_REF_FRAMES; i++) {
5814
7.23M
    for (j = 0; j < REFERENCE_MODES; j++)
5815
5.42M
      rd_opt->prediction_type_threshes[i][j] =
5816
5.42M
          rd_opt->prediction_type_threshes_prev[i][j];
5817
5818
9.04M
    for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; j++)
5819
7.23M
      rd_opt->filter_threshes[i][j] = rd_opt->filter_threshes_prev[i][j];
5820
1.80M
  }
5821
5822
894k
  for (tile_idx = 0; tile_idx < cpi->allocated_tiles; tile_idx++) {
5823
441k
    assert(cpi->tile_data);
5824
441k
    tile_data = &cpi->tile_data[tile_idx];
5825
441k
    vp9_copy(tile_data->thresh_freq_fact, tile_data->thresh_freq_fact_prev);
5826
441k
  }
5827
5828
452k
  cm->interp_filter = cpi->sf.default_interp_filter;
5829
452k
}
5830
5831
452k
void vp9_encode_frame(VP9_COMP *cpi) {
5832
452k
  VP9_COMMON *const cm = &cpi->common;
5833
5834
452k
  restore_encode_params(cpi);
5835
5836
#if CONFIG_MISMATCH_DEBUG
5837
  mismatch_reset_frame(MAX_MB_PLANE);
5838
#endif
5839
5840
  // In the longer term the encoder should be generalized to match the
5841
  // decoder such that we allow compound where one of the 3 buffers has a
5842
  // different sign bias and that buffer is then the fixed ref. However, this
5843
  // requires further work in the rd loop. For now the only supported encoder
5844
  // side behavior is where the ALT ref buffer has opposite sign bias to
5845
  // the other two.
5846
452k
  if (!frame_is_intra_only(cm)) {
5847
424k
    if (vp9_compound_reference_allowed(cm)) {
5848
0
      cpi->allow_comp_inter_inter = 1;
5849
0
      vp9_setup_compound_reference_mode(cm);
5850
424k
    } else {
5851
424k
      cpi->allow_comp_inter_inter = 0;
5852
424k
    }
5853
424k
  }
5854
5855
452k
  if (cpi->sf.frame_parameter_update) {
5856
193k
    int i;
5857
193k
    RD_OPT *const rd_opt = &cpi->rd;
5858
193k
    FRAME_COUNTS *counts = cpi->td.counts;
5859
193k
    RD_COUNTS *const rdc = &cpi->td.rd_counts;
5860
5861
    // This code does a single RD pass over the whole frame assuming
5862
    // either compound, single or hybrid prediction as per whatever has
5863
    // worked best for that type of frame in the past.
5864
    // It also predicts whether another coding mode would have worked
5865
    // better than this coding mode. If that is the case, it remembers
5866
    // that for subsequent frames.
5867
    // It also does the same analysis for transform size selection.
5868
193k
    const MV_REFERENCE_FRAME frame_type = get_frame_type(cpi);
5869
193k
    int64_t *const mode_thrs = rd_opt->prediction_type_threshes[frame_type];
5870
193k
    int64_t *const filter_thrs = rd_opt->filter_threshes[frame_type];
5871
193k
    const int is_alt_ref = frame_type == ALTREF_FRAME;
5872
5873
    /* prediction (compound, single or hybrid) mode selection */
5874
193k
    if (is_alt_ref || !cpi->allow_comp_inter_inter)
5875
193k
      cm->reference_mode = SINGLE_REFERENCE;
5876
0
    else if (mode_thrs[COMPOUND_REFERENCE] > mode_thrs[SINGLE_REFERENCE] &&
5877
0
             mode_thrs[COMPOUND_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT] &&
5878
0
             check_dual_ref_flags(cpi) && cpi->static_mb_pct == 100)
5879
0
      cm->reference_mode = COMPOUND_REFERENCE;
5880
0
    else if (mode_thrs[SINGLE_REFERENCE] > mode_thrs[REFERENCE_MODE_SELECT])
5881
0
      cm->reference_mode = SINGLE_REFERENCE;
5882
0
    else
5883
0
      cm->reference_mode = REFERENCE_MODE_SELECT;
5884
5885
193k
    if (cm->interp_filter == SWITCHABLE)
5886
193k
      cm->interp_filter = get_interp_filter(filter_thrs, is_alt_ref);
5887
5888
#if CONFIG_COLLECT_COMPONENT_TIMING
5889
    start_timing(cpi, encode_frame_internal_time);
5890
#endif
5891
193k
    encode_frame_internal(cpi);
5892
#if CONFIG_COLLECT_COMPONENT_TIMING
5893
    end_timing(cpi, encode_frame_internal_time);
5894
#endif
5895
5896
775k
    for (i = 0; i < REFERENCE_MODES; ++i)
5897
581k
      mode_thrs[i] = (mode_thrs[i] + rdc->comp_pred_diff[i] / cm->MBs) / 2;
5898
5899
969k
    for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
5900
775k
      filter_thrs[i] = (filter_thrs[i] + rdc->filter_diff[i] / cm->MBs) / 2;
5901
5902
193k
    if (cm->reference_mode == REFERENCE_MODE_SELECT) {
5903
0
      int single_count_zero = 0;
5904
0
      int comp_count_zero = 0;
5905
5906
0
      for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
5907
0
        single_count_zero += counts->comp_inter[i][0];
5908
0
        comp_count_zero += counts->comp_inter[i][1];
5909
0
      }
5910
5911
0
      if (comp_count_zero == 0) {
5912
0
        cm->reference_mode = SINGLE_REFERENCE;
5913
0
        vp9_zero(counts->comp_inter);
5914
0
      } else if (single_count_zero == 0) {
5915
0
        cm->reference_mode = COMPOUND_REFERENCE;
5916
0
        vp9_zero(counts->comp_inter);
5917
0
      }
5918
0
    }
5919
5920
193k
    if (cm->tx_mode == TX_MODE_SELECT) {
5921
174k
      int count4x4 = 0;
5922
174k
      int count8x8_lp = 0, count8x8_8x8p = 0;
5923
174k
      int count16x16_16x16p = 0, count16x16_lp = 0;
5924
174k
      int count32x32 = 0;
5925
5926
523k
      for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
5927
349k
        count4x4 += counts->tx.p32x32[i][TX_4X4];
5928
349k
        count4x4 += counts->tx.p16x16[i][TX_4X4];
5929
349k
        count4x4 += counts->tx.p8x8[i][TX_4X4];
5930
5931
349k
        count8x8_lp += counts->tx.p32x32[i][TX_8X8];
5932
349k
        count8x8_lp += counts->tx.p16x16[i][TX_8X8];
5933
349k
        count8x8_8x8p += counts->tx.p8x8[i][TX_8X8];
5934
5935
349k
        count16x16_16x16p += counts->tx.p16x16[i][TX_16X16];
5936
349k
        count16x16_lp += counts->tx.p32x32[i][TX_16X16];
5937
349k
        count32x32 += counts->tx.p32x32[i][TX_32X32];
5938
349k
      }
5939
174k
      if (count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0 &&
5940
123k
          count32x32 == 0) {
5941
120k
        cm->tx_mode = ALLOW_8X8;
5942
120k
        reset_skip_tx_size(cm, TX_8X8);
5943
120k
      } else if (count8x8_8x8p == 0 && count16x16_16x16p == 0 &&
5944
20.9k
                 count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0) {
5945
17.4k
        cm->tx_mode = ONLY_4X4;
5946
17.4k
        reset_skip_tx_size(cm, TX_4X4);
5947
36.9k
      } else if (count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0) {
5948
16.4k
        cm->tx_mode = ALLOW_32X32;
5949
20.5k
      } else if (count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0) {
5950
505
        cm->tx_mode = ALLOW_16X16;
5951
505
        reset_skip_tx_size(cm, TX_16X16);
5952
505
      }
5953
174k
    }
5954
258k
  } else {
5955
258k
    FRAME_COUNTS *counts = cpi->td.counts;
5956
258k
    cm->reference_mode = SINGLE_REFERENCE;
5957
258k
    if (cpi->allow_comp_inter_inter && cpi->sf.use_compound_nonrd_pickmode &&
5958
0
        cpi->rc.alt_ref_gf_group && !cpi->rc.is_src_frame_alt_ref &&
5959
0
        cm->frame_type != KEY_FRAME)
5960
0
      cm->reference_mode = REFERENCE_MODE_SELECT;
5961
5962
258k
    encode_frame_internal(cpi);
5963
5964
258k
    if (cm->reference_mode == REFERENCE_MODE_SELECT) {
5965
0
      int single_count_zero = 0;
5966
0
      int comp_count_zero = 0;
5967
0
      int i;
5968
0
      for (i = 0; i < COMP_INTER_CONTEXTS; i++) {
5969
0
        single_count_zero += counts->comp_inter[i][0];
5970
0
        comp_count_zero += counts->comp_inter[i][1];
5971
0
      }
5972
0
      if (comp_count_zero == 0) {
5973
0
        cm->reference_mode = SINGLE_REFERENCE;
5974
0
        vp9_zero(counts->comp_inter);
5975
0
      } else if (single_count_zero == 0) {
5976
0
        cm->reference_mode = COMPOUND_REFERENCE;
5977
0
        vp9_zero(counts->comp_inter);
5978
0
      }
5979
0
    }
5980
258k
  }
5981
5982
  // If segmented AQ is enabled compute the average AQ weighting.
5983
452k
  if (cm->seg.enabled && (cpi->oxcf.aq_mode != NO_AQ) &&
5984
0
      (cm->seg.update_map || cm->seg.update_data)) {
5985
0
    cm->seg.aq_av_offset = compute_frame_aq_offset(cpi);
5986
0
  }
5987
452k
}
5988
5989
1.52M
static void sum_intra_stats(FRAME_COUNTS *counts, const MODE_INFO *mi) {
5990
1.52M
  const PREDICTION_MODE y_mode = mi->mode;
5991
1.52M
  const PREDICTION_MODE uv_mode = mi->uv_mode;
5992
1.52M
  const BLOCK_SIZE bsize = mi->sb_type;
5993
5994
1.52M
  if (bsize < BLOCK_8X8) {
5995
321k
    int idx, idy;
5996
321k
    const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
5997
321k
    const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
5998
935k
    for (idy = 0; idy < 2; idy += num_4x4_h)
5999
1.76M
      for (idx = 0; idx < 2; idx += num_4x4_w)
6000
1.15M
        ++counts->y_mode[0][mi->bmi[idy * 2 + idx].as_mode];
6001
1.20M
  } else {
6002
1.20M
    ++counts->y_mode[size_group_lookup[bsize]][y_mode];
6003
1.20M
  }
6004
6005
1.52M
  ++counts->uv_mode[y_mode][uv_mode];
6006
1.52M
}
6007
6008
static void update_zeromv_cnt(VP9_COMP *const cpi, const MODE_INFO *const mi,
6009
3.32M
                              int mi_row, int mi_col, BLOCK_SIZE bsize) {
6010
3.32M
  const VP9_COMMON *const cm = &cpi->common;
6011
3.32M
  MV mv = mi->mv[0].as_mv;
6012
3.32M
  const int bw = num_8x8_blocks_wide_lookup[bsize];
6013
3.32M
  const int bh = num_8x8_blocks_high_lookup[bsize];
6014
3.32M
  const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
6015
3.32M
  const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
6016
3.32M
  const int block_index = mi_row * cm->mi_cols + mi_col;
6017
3.32M
  int x, y;
6018
7.60M
  for (y = 0; y < ymis; y++)
6019
11.3M
    for (x = 0; x < xmis; x++) {
6020
7.01M
      int map_offset = block_index + y * cm->mi_cols + x;
6021
7.01M
      if (mi->ref_frame[0] == LAST_FRAME && is_inter_block(mi) &&
6022
2.72M
          mi->segment_id <= CR_SEGMENT_ID_BOOST2) {
6023
2.72M
        if (abs(mv.row) < 8 && abs(mv.col) < 8) {
6024
1.34M
          if (cpi->consec_zero_mv[map_offset] < 255)
6025
1.34M
            cpi->consec_zero_mv[map_offset]++;
6026
1.38M
        } else {
6027
1.38M
          cpi->consec_zero_mv[map_offset] = 0;
6028
1.38M
        }
6029
2.72M
      }
6030
7.01M
    }
6031
3.32M
}
6032
6033
static void encode_superblock(VP9_COMP *cpi, ThreadData *td, TOKENEXTRA **t,
6034
                              int output_enabled, int mi_row, int mi_col,
6035
7.13M
                              BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
6036
7.13M
  VP9_COMMON *const cm = &cpi->common;
6037
7.13M
  MACROBLOCK *const x = &td->mb;
6038
7.13M
  MACROBLOCKD *const xd = &x->e_mbd;
6039
7.13M
  MODE_INFO *mi = xd->mi[0];
6040
7.13M
  const int seg_skip =
6041
7.13M
      segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP);
6042
7.13M
  x->skip_recode = !x->select_tx_size && mi->sb_type >= BLOCK_8X8 &&
6043
0
                   cpi->oxcf.aq_mode != COMPLEXITY_AQ &&
6044
0
                   cpi->oxcf.aq_mode != CYCLIC_REFRESH_AQ &&
6045
0
                   cpi->sf.allow_skip_recode;
6046
6047
7.13M
  if (!x->skip_recode && !cpi->sf.use_nonrd_pick_mode)
6048
4.90M
    memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
6049
6050
7.13M
  x->skip_optimize = ctx->is_coded;
6051
7.13M
  ctx->is_coded = 1;
6052
7.13M
  x->use_lp32x32fdct = cpi->sf.use_lp32x32fdct;
6053
7.13M
  x->skip_encode = (!output_enabled && cpi->sf.skip_encode_frame &&
6054
0
                    x->q_index < QIDX_SKIP_THRESH);
6055
6056
7.13M
  if (x->skip_encode) return;
6057
6058
7.13M
  if (!is_inter_block(mi)) {
6059
3.25M
    int plane;
6060
#if CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
6061
    if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) &&
6062
        (xd->above_mi == NULL || xd->left_mi == NULL) &&
6063
        need_top_left[mi->uv_mode])
6064
      assert(0);
6065
#endif  // CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
6066
3.25M
    mi->skip = 1;
6067
13.0M
    for (plane = 0; plane < MAX_MB_PLANE; ++plane)
6068
9.76M
      vp9_encode_intra_block_plane(x, VPXMAX(bsize, BLOCK_8X8), plane, 1);
6069
3.25M
    if (output_enabled) sum_intra_stats(td->counts, mi);
6070
3.25M
    vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6071
3.25M
                    VPXMAX(bsize, BLOCK_8X8));
6072
3.87M
  } else {
6073
3.87M
    int ref;
6074
3.87M
    const int is_compound = has_second_ref(mi);
6075
3.87M
    set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
6076
7.75M
    for (ref = 0; ref < 1 + is_compound; ++ref) {
6077
3.87M
      YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi, mi->ref_frame[ref]);
6078
3.87M
      assert(cfg != NULL);
6079
3.87M
      vp9_setup_pre_planes(xd, ref, cfg, mi_row, mi_col,
6080
3.87M
                           &xd->block_refs[ref]->sf);
6081
3.87M
    }
6082
3.87M
    if (!(cpi->sf.reuse_inter_pred_sby && ctx->pred_pixel_ready) || seg_skip)
6083
2.85M
      vp9_build_inter_predictors_sby(xd, mi_row, mi_col,
6084
2.85M
                                     VPXMAX(bsize, BLOCK_8X8));
6085
6086
3.87M
    vp9_build_inter_predictors_sbuv(xd, mi_row, mi_col,
6087
3.87M
                                    VPXMAX(bsize, BLOCK_8X8));
6088
6089
#if CONFIG_MISMATCH_DEBUG
6090
    if (output_enabled) {
6091
      int plane;
6092
      for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
6093
        const struct macroblockd_plane *pd = &xd->plane[plane];
6094
        int pixel_c, pixel_r;
6095
        const BLOCK_SIZE plane_bsize =
6096
            get_plane_block_size(VPXMAX(bsize, BLOCK_8X8), &xd->plane[plane]);
6097
        const int bw = get_block_width(plane_bsize);
6098
        const int bh = get_block_height(plane_bsize);
6099
        mi_to_pixel_loc(&pixel_c, &pixel_r, mi_col, mi_row, 0, 0,
6100
                        pd->subsampling_x, pd->subsampling_y);
6101
6102
        mismatch_record_block_pre(pd->dst.buf, pd->dst.stride, plane, pixel_c,
6103
                                  pixel_r, bw, bh,
6104
                                  xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH);
6105
      }
6106
    }
6107
#endif
6108
6109
3.87M
    vp9_encode_sb(x, VPXMAX(bsize, BLOCK_8X8), mi_row, mi_col, output_enabled);
6110
3.87M
    vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6111
3.87M
                    VPXMAX(bsize, BLOCK_8X8));
6112
3.87M
  }
6113
6114
7.13M
  if (seg_skip) {
6115
0
    assert(mi->skip);
6116
0
  }
6117
6118
7.13M
  if (output_enabled) {
6119
3.32M
    if (cm->tx_mode == TX_MODE_SELECT && mi->sb_type >= BLOCK_8X8 &&
6120
2.58M
        !(is_inter_block(mi) && mi->skip)) {
6121
2.23M
      ++get_tx_counts(max_txsize_lookup[bsize], get_tx_size_context(xd),
6122
2.23M
                      &td->counts->tx)[mi->tx_size];
6123
2.23M
    } else {
6124
      // The new intra coding scheme requires no change of transform size
6125
1.08M
      if (is_inter_block(mi)) {
6126
621k
        mi->tx_size = VPXMIN(tx_mode_to_biggest_tx_size[cm->tx_mode],
6127
621k
                             max_txsize_lookup[bsize]);
6128
621k
      } else {
6129
460k
        mi->tx_size = (bsize >= BLOCK_8X8) ? mi->tx_size : TX_4X4;
6130
460k
      }
6131
1.08M
    }
6132
6133
3.32M
    ++td->counts->tx.tx_totals[mi->tx_size];
6134
3.32M
    ++td->counts->tx.tx_totals[get_uv_tx_size(mi, &xd->plane[1])];
6135
3.32M
    if (cm->seg.enabled && cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
6136
0
        cpi->cyclic_refresh->content_mode)
6137
0
      vp9_cyclic_refresh_update_sb_postencode(cpi, mi, mi_row, mi_col, bsize);
6138
3.32M
    if (cpi->oxcf.pass == 0 && cpi->svc.temporal_layer_id == 0 &&
6139
3.32M
        (!cpi->use_svc ||
6140
0
         (cpi->use_svc &&
6141
0
          !cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame &&
6142
0
          cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1)))
6143
3.32M
      update_zeromv_cnt(cpi, mi, mi_row, mi_col, bsize);
6144
3.32M
  }
6145
7.13M
}