Coverage Report

Created: 2026-10-28 08:13

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
8.95M
                                  BLOCK_SIZE bs) {
114
8.95M
  unsigned int sse;
115
8.95M
  const unsigned int var =
116
8.95M
      cpi->fn_ptr[bs].vf(ref->buf, ref->stride, VP9_VAR_OFFS, 0, &sse);
117
8.95M
  return var;
118
8.95M
}
119
120
#if CONFIG_VP9_HIGHBITDEPTH
121
unsigned int vp9_high_get_sby_variance(VP9_COMP *cpi, const struct buf_2d *ref,
122
146k
                                       BLOCK_SIZE bs, int bd) {
123
146k
  unsigned int var, sse;
124
146k
  switch (bd) {
125
44.4k
    case 10:
126
44.4k
      var =
127
44.4k
          cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
128
44.4k
                             CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10), 0, &sse);
129
44.4k
      break;
130
101k
    case 12:
131
101k
      var =
132
101k
          cpi->fn_ptr[bs].vf(ref->buf, ref->stride,
133
101k
                             CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12), 0, &sse);
134
101k
      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
146k
  }
142
146k
  return var;
143
146k
}
144
#endif  // CONFIG_VP9_HIGHBITDEPTH
145
146
unsigned int vp9_get_sby_perpixel_variance(VP9_COMP *cpi,
147
                                           const struct buf_2d *ref,
148
8.95M
                                           BLOCK_SIZE bs) {
149
8.95M
  return ROUND_POWER_OF_TWO(vp9_get_sby_variance(cpi, ref, bs),
150
8.95M
                            num_pels_log2_lookup[bs]);
151
8.95M
}
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
144k
                                                BLOCK_SIZE bs, int bd) {
157
144k
  return (unsigned int)ROUND64_POWER_OF_TWO(
158
144k
      (int64_t)vp9_high_get_sby_variance(cpi, ref, bs, bd),
159
144k
      num_pels_log2_lookup[bs]);
160
144k
}
161
#endif  // CONFIG_VP9_HIGHBITDEPTH
162
163
static void set_segment_index(VP9_COMP *cpi, MACROBLOCK *const x, int mi_row,
164
9.09M
                              int mi_col, BLOCK_SIZE bsize, int segment_index) {
165
9.09M
  VP9_COMMON *const cm = &cpi->common;
166
9.09M
  const struct segmentation *const seg = &cm->seg;
167
9.09M
  MACROBLOCKD *const xd = &x->e_mbd;
168
9.09M
  MODE_INFO *mi = xd->mi[0];
169
170
9.09M
  const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
171
9.09M
  const uint8_t *const map =
172
9.09M
      seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
173
174
  // Initialize the segmentation index as 0.
175
9.09M
  mi->segment_id = 0;
176
177
  // Skip the rest if AQ mode is disabled.
178
9.09M
  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
19.2M
                                         int mi_col) {
234
19.2M
  const int idx_str = xd->mi_stride * mi_row + mi_col;
235
19.2M
  xd->mi = cm->mi_grid_visible + idx_str;
236
19.2M
  xd->mi[0] = cm->mi + idx_str;
237
19.2M
  x->mbmi_ext = x->mbmi_ext_base + (mi_row * cm->mi_cols + mi_col);
238
19.2M
}
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
19.2M
                        BLOCK_SIZE bsize) {
280
19.2M
  VP9_COMMON *const cm = &cpi->common;
281
19.2M
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
282
19.2M
  MACROBLOCKD *const xd = &x->e_mbd;
283
19.2M
  const int mi_width = num_8x8_blocks_wide_lookup[bsize];
284
19.2M
  const int mi_height = num_8x8_blocks_high_lookup[bsize];
285
19.2M
  MvLimits *const mv_limits = &x->mv_limits;
286
287
19.2M
  set_skip_context(xd, mi_row, mi_col);
288
289
19.2M
  set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
290
291
  // Set up destination pointers.
292
19.2M
  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
19.2M
  mv_limits->row_min = -(((mi_row + mi_height) * MI_SIZE) + VP9_INTERP_EXTEND);
297
19.2M
  mv_limits->col_min = -(((mi_col + mi_width) * MI_SIZE) + VP9_INTERP_EXTEND);
298
19.2M
  mv_limits->row_max = (cm->mi_rows - mi_row) * MI_SIZE + VP9_INTERP_EXTEND;
299
19.2M
  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
19.2M
  assert(!(mi_col & (mi_width - 1)) && !(mi_row & (mi_height - 1)));
303
19.2M
  set_mi_row_col(xd, tile, mi_row, mi_height, mi_col, mi_width, cm->mi_rows,
304
19.2M
                 cm->mi_cols);
305
306
  // Set up source buffers.
307
19.2M
  vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
308
309
  // R/D setup.
310
19.2M
  x->rddiv = cpi->rd.RDDIV;
311
19.2M
  x->rdmult = cpi->rd.RDMULT;
312
19.2M
  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
19.2M
  xd->tile = *tile;
318
19.2M
}
319
320
static void duplicate_mode_info_in_sb(VP9_COMMON *cm, MACROBLOCKD *xd,
321
                                      int mi_row, int mi_col,
322
0
                                      BLOCK_SIZE bsize) {
323
0
  const int block_width =
324
0
      VPXMIN(num_8x8_blocks_wide_lookup[bsize], cm->mi_cols - mi_col);
325
0
  const int block_height =
326
0
      VPXMIN(num_8x8_blocks_high_lookup[bsize], cm->mi_rows - mi_row);
327
0
  const int mi_stride = xd->mi_stride;
328
0
  MODE_INFO *const src_mi = xd->mi[0];
329
0
  int i, j;
330
331
0
  for (j = 0; j < block_height; ++j)
332
0
    for (i = 0; i < block_width; ++i) xd->mi[j * mi_stride + i] = src_mi;
333
0
}
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
0
                           BLOCK_SIZE bsize) {
338
0
  if (cpi->common.mi_cols > mi_col && cpi->common.mi_rows > mi_row) {
339
0
    set_mode_info_offsets(&cpi->common, x, xd, mi_row, mi_col);
340
0
    xd->mi[0]->sb_type = bsize;
341
0
  }
342
0
}
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
0
static void tree_to_node(void *data, BLOCK_SIZE bsize, variance_node *node) {
398
0
  int i;
399
0
  node->part_variances = NULL;
400
0
  switch (bsize) {
401
0
    case BLOCK_64X64: {
402
0
      v64x64 *vt = (v64x64 *)data;
403
0
      node->part_variances = &vt->part_variances;
404
0
      for (i = 0; i < 4; i++)
405
0
        node->split[i] = &vt->split[i].part_variances.none;
406
0
      break;
407
0
    }
408
0
    case BLOCK_32X32: {
409
0
      v32x32 *vt = (v32x32 *)data;
410
0
      node->part_variances = &vt->part_variances;
411
0
      for (i = 0; i < 4; i++)
412
0
        node->split[i] = &vt->split[i].part_variances.none;
413
0
      break;
414
0
    }
415
0
    case BLOCK_16X16: {
416
0
      v16x16 *vt = (v16x16 *)data;
417
0
      node->part_variances = &vt->part_variances;
418
0
      for (i = 0; i < 4; i++)
419
0
        node->split[i] = &vt->split[i].part_variances.none;
420
0
      break;
421
0
    }
422
0
    case BLOCK_8X8: {
423
0
      v8x8 *vt = (v8x8 *)data;
424
0
      node->part_variances = &vt->part_variances;
425
0
      for (i = 0; i < 4; i++)
426
0
        node->split[i] = &vt->split[i].part_variances.none;
427
0
      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
0
  }
437
0
}
438
439
// Set variance values given sum square error, sum error, count.
440
0
static void fill_variance(uint32_t s2, int32_t s, int c, Var *v) {
441
0
  v->sum_square_error = s2;
442
0
  v->sum_error = s;
443
0
  v->log2_count = c;
444
0
}
445
446
0
static void get_variance(Var *v) {
447
0
  v->variance =
448
0
      (int)(256 * (v->sum_square_error -
449
0
                   (uint32_t)(((int64_t)v->sum_error * v->sum_error) >>
450
0
                              v->log2_count)) >>
451
0
            v->log2_count);
452
0
}
453
454
0
static void sum_2_variances(const Var *a, const Var *b, Var *r) {
455
0
  assert(a->log2_count == b->log2_count);
456
0
  fill_variance(a->sum_square_error + b->sum_square_error,
457
0
                a->sum_error + b->sum_error, a->log2_count + 1, r);
458
0
}
459
460
0
static void fill_variance_tree(void *data, BLOCK_SIZE bsize) {
461
0
  variance_node node;
462
0
  memset(&node, 0, sizeof(node));
463
0
  tree_to_node(data, bsize, &node);
464
0
  sum_2_variances(node.split[0], node.split[1], &node.part_variances->horz[0]);
465
0
  sum_2_variances(node.split[2], node.split[3], &node.part_variances->horz[1]);
466
0
  sum_2_variances(node.split[0], node.split[2], &node.part_variances->vert[0]);
467
0
  sum_2_variances(node.split[1], node.split[3], &node.part_variances->vert[1]);
468
0
  sum_2_variances(&node.part_variances->vert[0], &node.part_variances->vert[1],
469
0
                  &node.part_variances->none);
470
0
}
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
0
                               int force_split) {
477
0
  VP9_COMMON *const cm = &cpi->common;
478
0
  variance_node vt;
479
0
  const int block_width = num_8x8_blocks_wide_lookup[bsize];
480
0
  const int block_height = num_8x8_blocks_high_lookup[bsize];
481
482
0
  assert(block_height == block_width);
483
0
  tree_to_node(data, bsize, &vt);
484
485
0
  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
0
  if (bsize == bsize_min) {
491
    // Variance already computed to set the force_split.
492
0
    if (frame_is_intra_only(cm)) get_variance(&vt.part_variances->none);
493
0
    if (mi_col + block_width / 2 < cm->mi_cols &&
494
0
        mi_row + block_height / 2 < cm->mi_rows &&
495
0
        vt.part_variances->none.variance < threshold) {
496
0
      set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
497
0
      return 1;
498
0
    }
499
0
    return 0;
500
0
  } else if (bsize > bsize_min) {
501
    // Variance already computed to set the force_split.
502
0
    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
0
    if (frame_is_intra_only(cm) &&
505
0
        (bsize > BLOCK_32X32 ||
506
0
         vt.part_variances->none.variance > (threshold << 4))) {
507
0
      return 0;
508
0
    }
509
    // If variance is low, take the bsize (no split).
510
0
    if (mi_col + block_width / 2 < cm->mi_cols &&
511
0
        mi_row + block_height / 2 < cm->mi_rows &&
512
0
        vt.part_variances->none.variance < threshold) {
513
0
      set_block_size(cpi, x, xd, mi_row, mi_col, bsize);
514
0
      return 1;
515
0
    }
516
517
    // Check vertical split.
518
0
    if (mi_row + block_height / 2 < cm->mi_rows) {
519
0
      BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_VERT);
520
0
      get_variance(&vt.part_variances->vert[0]);
521
0
      get_variance(&vt.part_variances->vert[1]);
522
0
      if (vt.part_variances->vert[0].variance < threshold &&
523
0
          vt.part_variances->vert[1].variance < threshold &&
524
0
          get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
525
0
        set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
526
0
        set_block_size(cpi, x, xd, mi_row, mi_col + block_width / 2, subsize);
527
0
        return 1;
528
0
      }
529
0
    }
530
    // Check horizontal split.
531
0
    if (mi_col + block_width / 2 < cm->mi_cols) {
532
0
      BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_HORZ);
533
0
      get_variance(&vt.part_variances->horz[0]);
534
0
      get_variance(&vt.part_variances->horz[1]);
535
0
      if (vt.part_variances->horz[0].variance < threshold &&
536
0
          vt.part_variances->horz[1].variance < threshold &&
537
0
          get_plane_block_size(subsize, &xd->plane[1]) < BLOCK_INVALID) {
538
0
        set_block_size(cpi, x, xd, mi_row, mi_col, subsize);
539
0
        set_block_size(cpi, x, xd, mi_row + block_height / 2, mi_col, subsize);
540
0
        return 1;
541
0
      }
542
0
    }
543
544
0
    return 0;
545
0
  }
546
0
  return 0;
547
0
}
548
549
static int64_t scale_part_thresh_sumdiff(int64_t threshold_base, int speed,
550
                                         int width, int height,
551
0
                                         int content_state) {
552
0
  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
0
  } 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
0
  return threshold_base;
567
0
}
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
0
                               int content_state) {
575
0
  VP9_COMMON *const cm = &cpi->common;
576
0
  const int is_key_frame = frame_is_intra_only(cm);
577
0
  const int threshold_multiplier =
578
0
      is_key_frame ? 20 : cpi->sf.variance_part_thresh_mult;
579
0
  int64_t threshold_base =
580
0
      (int64_t)(threshold_multiplier * cpi->y_dequant[q][1]);
581
582
0
  if (is_key_frame) {
583
0
    thresholds[0] = threshold_base;
584
0
    thresholds[1] = threshold_base >> 2;
585
0
    thresholds[2] = threshold_base >> 2;
586
0
    thresholds[3] = threshold_base << 2;
587
0
  } else {
588
    // Increase base variance threshold based on estimated noise level.
589
0
    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
0
    threshold_base = scale_part_thresh_sumdiff(
612
0
        threshold_base, cpi->oxcf.speed, cm->width, cm->height, content_state);
613
0
#endif
614
0
    thresholds[0] = threshold_base;
615
0
    thresholds[2] = threshold_base << cpi->oxcf.speed;
616
0
    if (cm->width >= 1280 && cm->height >= 720 && cpi->oxcf.speed < 7)
617
0
      thresholds[2] = thresholds[2] << 1;
618
0
    if (cm->width <= 352 && cm->height <= 288) {
619
0
      thresholds[0] = threshold_base >> 3;
620
0
      thresholds[1] = threshold_base >> 1;
621
0
      thresholds[2] = threshold_base << 3;
622
0
      if (cpi->rc.avg_frame_qindex[INTER_FRAME] > 220)
623
0
        thresholds[2] = thresholds[2] << 2;
624
0
      else if (cpi->rc.avg_frame_qindex[INTER_FRAME] > 200)
625
0
        thresholds[2] = thresholds[2] << 1;
626
0
    } 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
0
    if (cpi->sf.disable_16x16part_nonkey) thresholds[2] = INT64_MAX;
634
0
  }
635
0
}
636
637
void vp9_set_variance_partition_thresholds(VP9_COMP *cpi, int q,
638
74.0k
                                           int content_state) {
639
74.0k
  VP9_COMMON *const cm = &cpi->common;
640
74.0k
  SPEED_FEATURES *const sf = &cpi->sf;
641
74.0k
  const int is_key_frame = frame_is_intra_only(cm);
642
74.0k
  if (sf->partition_search_type != VAR_BASED_PARTITION &&
643
74.0k
      sf->partition_search_type != REFERENCE_PARTITION) {
644
74.0k
    return;
645
74.0k
  } else {
646
0
    set_vbp_thresholds(cpi, cpi->vbp_thresholds, q, content_state);
647
    // The thresholds below are not changed locally.
648
0
    if (is_key_frame) {
649
0
      cpi->vbp_threshold_sad = 0;
650
0
      cpi->vbp_threshold_copy = 0;
651
0
      cpi->vbp_bsize_min = BLOCK_8X8;
652
0
    } else {
653
0
      if (cm->width <= 352 && cm->height <= 288)
654
0
        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
0
      cpi->vbp_bsize_min = BLOCK_16X16;
660
0
      if (cm->width <= 352 && cm->height <= 288)
661
0
        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
0
      if (cpi->rc.high_source_sad ||
669
0
          (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
0
    }
674
0
    cpi->vbp_threshold_minmax = 15 + (q >> 3);
675
0
  }
676
74.0k
}
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
0
                              int pixels_wide, int pixels_high) {
685
0
  int k;
686
0
  int minmax_max = 0;
687
0
  int minmax_min = 255;
688
  // Loop over the 4 8x8 subblocks.
689
0
  for (k = 0; k < 4; k++) {
690
0
    int x8_idx = x16_idx + ((k & 1) << 3);
691
0
    int y8_idx = y16_idx + ((k >> 1) << 3);
692
0
    int min = 0;
693
0
    int max = 0;
694
0
    if (x8_idx < pixels_wide && y8_idx < pixels_high) {
695
0
#if CONFIG_VP9_HIGHBITDEPTH
696
0
      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
0
      } else {
700
0
        vpx_minmax_8x8(s + y8_idx * sp + x8_idx, sp, d + y8_idx * dp + x8_idx,
701
0
                       dp, &min, &max);
702
0
      }
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
0
      if ((max - min) > minmax_max) minmax_max = (max - min);
708
0
      if ((max - min) < minmax_min) minmax_min = (max - min);
709
0
    }
710
0
  }
711
0
  return (minmax_max - minmax_min);
712
0
}
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
0
                                 int is_key_frame) {
721
0
  int k;
722
0
  for (k = 0; k < 4; k++) {
723
0
    int x4_idx = x8_idx + ((k & 1) << 2);
724
0
    int y4_idx = y8_idx + ((k >> 1) << 2);
725
0
    unsigned int sse = 0;
726
0
    int sum = 0;
727
0
    if (x4_idx < pixels_wide && y4_idx < pixels_high) {
728
0
      int s_avg;
729
0
      int d_avg = 128;
730
0
#if CONFIG_VP9_HIGHBITDEPTH
731
0
      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
0
      } else {
736
0
        s_avg = vpx_avg_4x4(s + y4_idx * sp + x4_idx, sp);
737
0
        if (!is_key_frame) d_avg = vpx_avg_4x4(d + y4_idx * dp + x4_idx, dp);
738
0
      }
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
0
      sum = s_avg - d_avg;
744
0
      sse = sum * sum;
745
0
    }
746
0
    fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
747
0
  }
748
0
}
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
0
                                 int is_key_frame) {
757
0
  int k;
758
0
  for (k = 0; k < 4; k++) {
759
0
    int x8_idx = x16_idx + ((k & 1) << 3);
760
0
    int y8_idx = y16_idx + ((k >> 1) << 3);
761
0
    unsigned int sse = 0;
762
0
    int sum = 0;
763
0
    if (x8_idx < pixels_wide && y8_idx < pixels_high) {
764
0
      int s_avg;
765
0
      int d_avg = 128;
766
0
#if CONFIG_VP9_HIGHBITDEPTH
767
0
      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
0
      } else {
772
0
        s_avg = vpx_avg_8x8(s + y8_idx * sp + x8_idx, sp);
773
0
        if (!is_key_frame) d_avg = vpx_avg_8x8(d + y8_idx * dp + x8_idx, dp);
774
0
      }
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
0
      sum = s_avg - d_avg;
780
0
      sse = sum * sum;
781
0
    }
782
0
    fill_variance(sse, sum, 0, &vst->split[k].part_variances.none);
783
0
  }
784
0
}
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
0
                         int scene_change_detected) {
1168
0
  int i;
1169
0
  MACROBLOCKD *xd = &x->e_mbd;
1170
0
  int shift = 2;
1171
1172
0
  if (is_key_frame) return;
1173
1174
  // For speed > 8, avoid the chroma check if y_sad is above threshold.
1175
0
  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
0
  if (cpi->oxcf.content == VP9E_CONTENT_SCREEN && scene_change_detected)
1183
0
    shift = 5;
1184
1185
0
  for (i = 1; i <= 2; ++i) {
1186
0
    unsigned int uv_sad = UINT_MAX;
1187
0
    struct macroblock_plane *p = &x->plane[i];
1188
0
    struct macroblockd_plane *pd = &xd->plane[i];
1189
0
    const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
1190
1191
0
    if (bs != BLOCK_INVALID)
1192
0
      uv_sad = cpi->fn_ptr[bs].sdf(p->src.buf, p->src.stride, pd->dst.buf,
1193
0
                                   pd->dst.stride);
1194
1195
    // TODO(marpan): Investigate if we should lower this threshold if
1196
    // superblock is detected as skin.
1197
0
    x->color_sensitivity[i - 1] = uv_sad > (y_sad >> shift);
1198
0
  }
1199
0
}
1200
1201
static uint64_t avg_source_sad(VP9_COMP *cpi, MACROBLOCK *x, int shift,
1202
0
                               int sb_offset) {
1203
0
  unsigned int tmp_sse;
1204
0
  uint64_t tmp_sad;
1205
0
  unsigned int tmp_variance;
1206
0
  const BLOCK_SIZE bsize = BLOCK_64X64;
1207
0
  uint8_t *src_y = cpi->Source->y_buffer;
1208
0
  int src_ystride = cpi->Source->y_stride;
1209
0
  uint8_t *last_src_y = cpi->Last_Source->y_buffer;
1210
0
  int last_src_ystride = cpi->Last_Source->y_stride;
1211
0
  uint64_t avg_source_sad_threshold = 10000;
1212
0
  uint64_t avg_source_sad_threshold2 = 12000;
1213
0
#if CONFIG_VP9_HIGHBITDEPTH
1214
0
  if (cpi->common.use_highbitdepth) return 0;
1215
0
#endif
1216
0
  src_y += shift;
1217
0
  last_src_y += shift;
1218
0
  tmp_sad =
1219
0
      cpi->fn_ptr[bsize].sdf(src_y, src_ystride, last_src_y, last_src_ystride);
1220
0
  tmp_variance = vpx_variance64x64(src_y, src_ystride, last_src_y,
1221
0
                                   last_src_ystride, &tmp_sse);
1222
  // Note: tmp_sse - tmp_variance = ((sum * sum) >> 12)
1223
0
  if (tmp_sad < avg_source_sad_threshold)
1224
0
    x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kLowSadLowSumdiff
1225
0
                                                          : kLowSadHighSumdiff;
1226
0
  else
1227
0
    x->content_state_sb = ((tmp_sse - tmp_variance) < 25) ? kHighSadLowSumdiff
1228
0
                                                          : kHighSadHighSumdiff;
1229
1230
  // Detect large lighting change.
1231
0
  if (cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
1232
0
      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
0
  else if (tmp_sad > (avg_source_sad_threshold << 1))
1236
0
    x->content_state_sb = kVeryHighSad;
1237
1238
0
  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
0
  if (tmp_sad == 0) x->zero_temp_sad_source = 1;
1248
0
  return tmp_sad;
1249
0
}
1250
1251
// Check whether the current frame should be treated as a key frame for the
1252
// purpose of superblock partitioning. Under SVC mode, treat the frame as key if
1253
// the base layer frame is a key frame, or if LAST_FRAME is NULL or has a
1254
// different resolution than the current frame (e.g., when enhancement spatial
1255
// layers are enabled dynamically and the only reference is GOLDEN).
1256
0
static INLINE int is_key_frame_for_partition(const VP9_COMP *const cpi) {
1257
0
  const VP9_COMMON *const cm = &cpi->common;
1258
0
  const YV12_BUFFER_CONFIG *ref;
1259
0
  if (frame_is_intra_only(cm) ||
1260
0
      (is_one_pass_svc(cpi) &&
1261
0
       cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame)) {
1262
0
    return 1;
1263
0
  }
1264
0
  ref = get_ref_frame_buffer(cpi, LAST_FRAME);
1265
0
  if (ref == NULL ||
1266
0
      cm->frame_refs[LAST_FRAME - 1].sf.x_scale_fp == REF_INVALID_SCALE ||
1267
0
      cm->frame_refs[LAST_FRAME - 1].sf.y_scale_fp == REF_INVALID_SCALE ||
1268
0
      (cpi->use_svc &&
1269
0
       (ref->y_crop_height != cm->height || ref->y_crop_width != cm->width))) {
1270
0
    return 1;
1271
0
  }
1272
0
  return 0;
1273
0
}
1274
1275
// This function chooses partitioning based on the variance between source and
1276
// reconstructed last, where variance is computed for down-sampled inputs.
1277
static int choose_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
1278
0
                               MACROBLOCK *x, int mi_row, int mi_col) {
1279
0
  VP9_COMMON *const cm = &cpi->common;
1280
0
  MACROBLOCKD *xd = &x->e_mbd;
1281
0
  int i, j, k, m;
1282
0
  v64x64 vt;
1283
0
  v16x16 *vt2 = NULL;
1284
0
  int force_split[21];
1285
0
  int avg_32x32;
1286
0
  int max_var_32x32 = 0;
1287
0
  int min_var_32x32 = INT_MAX;
1288
0
  int var_32x32;
1289
0
  int avg_16x16[4];
1290
0
  int maxvar_16x16[4];
1291
0
  int minvar_16x16[4];
1292
0
  int64_t threshold_4x4avg;
1293
0
  NOISE_LEVEL noise_level = kLow;
1294
0
  int content_state = 0;
1295
0
  uint8_t *s;
1296
0
  const uint8_t *d;
1297
0
  int sp;
1298
0
  int dp;
1299
0
  int compute_minmax_variance = 1;
1300
0
  unsigned int y_sad = UINT_MAX;
1301
0
  BLOCK_SIZE bsize = BLOCK_64X64;
1302
  // Ref frame used in partitioning.
1303
0
  MV_REFERENCE_FRAME ref_frame_partition = LAST_FRAME;
1304
0
  int pixels_wide = 64, pixels_high = 64;
1305
0
  int64_t thresholds[4] = { cpi->vbp_thresholds[0], cpi->vbp_thresholds[1],
1306
0
                            cpi->vbp_thresholds[2], cpi->vbp_thresholds[3] };
1307
0
  int scene_change_detected =
1308
0
      cpi->rc.high_source_sad ||
1309
0
      (cpi->use_svc && cpi->svc.high_source_sad_superframe);
1310
0
  int force_64_split = scene_change_detected ||
1311
0
                       (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1312
0
                        cpi->compute_source_sad_onepass &&
1313
0
                        cpi->sf.use_source_sad && !x->zero_temp_sad_source);
1314
0
  const int is_key_frame = is_key_frame_for_partition(cpi);
1315
1316
  // Allow for sub8x8 (4x4) partition on key frames, but only for hybrid mode
1317
  // (i.e., sf->nonrd_keyframe = 0), where for small blocks rd intra pickmode
1318
  // (vp9_rd_pick_intra_mode_sb) is used. The nonrd intra pickmode
1319
  // (vp9_pick_intra_mode) does not currently support sub8x8 blocks. This causes
1320
  // the issue: 44166813. Assert is added in vp9_pick_intra_mode to check this.
1321
0
  const int use_4x4_partition =
1322
0
      frame_is_intra_only(cm) && !cpi->sf.nonrd_keyframe;
1323
0
  const int low_res = (cm->width <= 352 && cm->height <= 288);
1324
0
  int variance4x4downsample[16];
1325
0
  int segment_id;
1326
0
  int sb_offset = (cm->mi_stride >> 3) * (mi_row >> 3) + (mi_col >> 3);
1327
1328
0
  set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64);
1329
0
  set_segment_index(cpi, x, mi_row, mi_col, BLOCK_64X64, 0);
1330
0
  segment_id = xd->mi[0]->segment_id;
1331
1332
0
  if (cpi->oxcf.speed >= 8 || (cpi->use_svc && cpi->svc.non_reference_frame))
1333
0
    compute_minmax_variance = 0;
1334
1335
0
  memset(x->variance_low, 0, sizeof(x->variance_low));
1336
1337
0
  if (cpi->sf.use_source_sad && !is_key_frame) {
1338
0
    int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
1339
0
    content_state = x->content_state_sb;
1340
0
    x->skip_low_source_sad = (content_state == kLowSadLowSumdiff ||
1341
0
                              content_state == kLowSadHighSumdiff)
1342
0
                                 ? 1
1343
0
                                 : 0;
1344
0
    x->lowvar_highsumdiff = (content_state == kLowVarHighSumdiff) ? 1 : 0;
1345
0
    if (cpi->content_state_sb_fd != NULL)
1346
0
      x->last_sb_high_content = cpi->content_state_sb_fd[sb_offset2];
1347
1348
    // For SVC on top spatial layer: use/scale the partition from
1349
    // the lower spatial resolution if svc_use_lowres_part is enabled.
1350
0
    if (cpi->sf.svc_use_lowres_part &&
1351
0
        cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1 &&
1352
0
        cpi->svc.prev_partition_svc != NULL && content_state != kVeryHighSad) {
1353
0
      if (!scale_partitioning_svc(cpi, x, xd, BLOCK_64X64, mi_row >> 1,
1354
0
                                  mi_col >> 1, mi_row, mi_col)) {
1355
0
        if (cpi->sf.copy_partition_flag) {
1356
0
          update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1357
0
        }
1358
0
        return 0;
1359
0
      }
1360
0
    }
1361
    // If source_sad is low copy the partition without computing the y_sad.
1362
0
    if (x->skip_low_source_sad && cpi->sf.copy_partition_flag &&
1363
0
        !force_64_split &&
1364
0
        copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1365
0
      x->sb_use_mv_part = 1;
1366
0
      if (cpi->sf.svc_use_lowres_part &&
1367
0
          cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1368
0
        update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1369
0
      return 0;
1370
0
    }
1371
0
  }
1372
1373
0
  if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled &&
1374
0
      cyclic_refresh_segment_id_boosted(segment_id)) {
1375
0
    int q = vp9_get_qindex(&cm->seg, segment_id, cm->base_qindex);
1376
0
    set_vbp_thresholds(cpi, thresholds, q, content_state);
1377
0
  } else {
1378
0
    set_vbp_thresholds(cpi, thresholds, cm->base_qindex, content_state);
1379
0
  }
1380
  // Decrease 32x32 split threshold for screen on base layer, for scene
1381
  // change/high motion frames.
1382
0
  if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1383
0
      cpi->svc.spatial_layer_id == 0 && force_64_split)
1384
0
    thresholds[1] = 3 * thresholds[1] >> 2;
1385
1386
  // For non keyframes, disable 4x4 average for low resolution when speed = 8
1387
0
  threshold_4x4avg = (cpi->oxcf.speed < 8) ? thresholds[1] << 1 : INT64_MAX;
1388
1389
0
  if (xd->mb_to_right_edge < 0) pixels_wide += (xd->mb_to_right_edge >> 3);
1390
0
  if (xd->mb_to_bottom_edge < 0) pixels_high += (xd->mb_to_bottom_edge >> 3);
1391
1392
0
  s = x->plane[0].src.buf;
1393
0
  sp = x->plane[0].src.stride;
1394
1395
  // Index for force_split: 0 for 64x64, 1-4 for 32x32 blocks,
1396
  // 5-20 for the 16x16 blocks.
1397
0
  force_split[0] = force_64_split;
1398
1399
0
  if (!is_key_frame) {
1400
    // In the case of spatial/temporal scalable coding, the assumption here is
1401
    // that the temporal reference frame will always be of type LAST_FRAME.
1402
    // TODO(marpan): If that assumption is broken, we need to revisit this code.
1403
0
    MODE_INFO *mi = xd->mi[0];
1404
0
    YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
1405
1406
0
    const YV12_BUFFER_CONFIG *yv12_g = NULL;
1407
0
    unsigned int y_sad_g, y_sad_thr, y_sad_last;
1408
0
    bsize = BLOCK_32X32 + (mi_col + 4 < cm->mi_cols) * 2 +
1409
0
            (mi_row + 4 < cm->mi_rows);
1410
1411
0
    assert(yv12 != NULL);
1412
1413
0
    if (!(is_one_pass_svc(cpi) && cpi->svc.spatial_layer_id) ||
1414
0
        cpi->svc.use_gf_temporal_ref_current_layer) {
1415
      // For now, GOLDEN will not be used for non-zero spatial layers, since
1416
      // it may not be a temporal reference.
1417
0
      yv12_g = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
1418
0
    }
1419
1420
    // Only compute y_sad_g (sad for golden reference) for speed < 8.
1421
0
    if (cpi->oxcf.speed < 8 && yv12_g && yv12_g != yv12 &&
1422
0
        (cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
1423
0
      vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1424
0
                           &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1425
0
      y_sad_g = cpi->fn_ptr[bsize].sdf(
1426
0
          x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1427
0
          xd->plane[0].pre[0].stride);
1428
0
    } else {
1429
0
      y_sad_g = UINT_MAX;
1430
0
    }
1431
1432
0
    if (cpi->oxcf.lag_in_frames > 0 && cpi->oxcf.rc_mode == VPX_VBR &&
1433
0
        cpi->rc.is_src_frame_alt_ref) {
1434
0
      yv12 = get_ref_frame_buffer(cpi, ALTREF_FRAME);
1435
0
      vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1436
0
                           &cm->frame_refs[ALTREF_FRAME - 1].sf);
1437
0
      mi->ref_frame[0] = ALTREF_FRAME;
1438
0
      y_sad_g = UINT_MAX;
1439
0
    } else {
1440
0
      vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col,
1441
0
                           &cm->frame_refs[LAST_FRAME - 1].sf);
1442
0
      mi->ref_frame[0] = LAST_FRAME;
1443
0
    }
1444
0
    mi->ref_frame[1] = NO_REF_FRAME;
1445
0
    mi->sb_type = BLOCK_64X64;
1446
0
    mi->mv[0].as_int = 0;
1447
0
    mi->interp_filter = BILINEAR;
1448
1449
0
    if (cpi->oxcf.speed >= 8 && !low_res &&
1450
0
        x->content_state_sb != kVeryHighSad) {
1451
0
      y_sad = cpi->fn_ptr[bsize].sdf(
1452
0
          x->plane[0].src.buf, x->plane[0].src.stride, xd->plane[0].pre[0].buf,
1453
0
          xd->plane[0].pre[0].stride);
1454
0
    } else {
1455
0
      const MV dummy_mv = { 0, 0 };
1456
0
      y_sad = vp9_int_pro_motion_estimation(cpi, x, bsize, mi_row, mi_col,
1457
0
                                            &dummy_mv);
1458
0
      x->sb_use_mv_part = 1;
1459
0
      x->sb_mvcol_part = mi->mv[0].as_mv.col;
1460
0
      x->sb_mvrow_part = mi->mv[0].as_mv.row;
1461
0
      if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
1462
0
          cpi->svc.spatial_layer_id == cpi->svc.first_spatial_layer_to_encode &&
1463
0
          cpi->svc.high_num_blocks_with_motion && !x->zero_temp_sad_source &&
1464
0
          cm->width > 640 && cm->height > 480) {
1465
        // Disable split below 16x16 block size when scroll motion (horz or
1466
        // vert) is detected.
1467
        // TODO(marpan/jianj): Improve this condition: issue is that search
1468
        // range is hard-coded/limited in vp9_int_pro_motion_estimation() so
1469
        // scroll motion may not be detected here.
1470
0
        if (((abs(x->sb_mvrow_part) >= 48 && abs(x->sb_mvcol_part) <= 8) ||
1471
0
             (abs(x->sb_mvcol_part) >= 48 && abs(x->sb_mvrow_part) <= 8)) &&
1472
0
            y_sad < 100000) {
1473
0
          compute_minmax_variance = 0;
1474
0
          thresholds[2] = INT64_MAX;
1475
0
        }
1476
0
      }
1477
0
    }
1478
1479
0
    y_sad_last = y_sad;
1480
    // Pick ref frame for partitioning, bias last frame when y_sad_g and y_sad
1481
    // are close if short_circuit_low_temp_var is on.
1482
0
    y_sad_thr = cpi->sf.short_circuit_low_temp_var ? (y_sad * 7) >> 3 : y_sad;
1483
0
    if (y_sad_g < y_sad_thr) {
1484
0
      vp9_setup_pre_planes(xd, 0, yv12_g, mi_row, mi_col,
1485
0
                           &cm->frame_refs[GOLDEN_FRAME - 1].sf);
1486
0
      mi->ref_frame[0] = GOLDEN_FRAME;
1487
0
      mi->mv[0].as_int = 0;
1488
0
      y_sad = y_sad_g;
1489
0
      ref_frame_partition = GOLDEN_FRAME;
1490
0
    } else {
1491
0
      x->pred_mv[LAST_FRAME] = mi->mv[0].as_mv;
1492
0
      ref_frame_partition = LAST_FRAME;
1493
0
    }
1494
1495
0
    set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
1496
0
    vp9_build_inter_predictors_sb(xd, mi_row, mi_col, BLOCK_64X64);
1497
1498
0
    if (cpi->use_skin_detection)
1499
0
      x->sb_is_skin = skin_sb_split(cpi, low_res, mi_row, mi_col, force_split);
1500
1501
0
    d = xd->plane[0].dst.buf;
1502
0
    dp = xd->plane[0].dst.stride;
1503
1504
    // If the y_sad is very small, take 64x64 as partition and exit.
1505
    // Don't check on boosted segment for now, as 64x64 is suppressed there.
1506
0
    if (segment_id == CR_SEGMENT_ID_BASE && y_sad < cpi->vbp_threshold_sad) {
1507
0
      const int block_width = num_8x8_blocks_wide_lookup[BLOCK_64X64];
1508
0
      const int block_height = num_8x8_blocks_high_lookup[BLOCK_64X64];
1509
0
      if (mi_col + block_width / 2 < cm->mi_cols &&
1510
0
          mi_row + block_height / 2 < cm->mi_rows) {
1511
0
        set_block_size(cpi, x, xd, mi_row, mi_col, BLOCK_64X64);
1512
0
        x->variance_low[0] = 1;
1513
0
        chroma_check(cpi, x, bsize, y_sad, is_key_frame, scene_change_detected);
1514
0
        if (cpi->sf.svc_use_lowres_part &&
1515
0
            cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1516
0
          update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1517
0
        if (cpi->sf.copy_partition_flag) {
1518
0
          update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1519
0
        }
1520
0
        return 0;
1521
0
      }
1522
0
    }
1523
1524
    // If the y_sad is small enough, copy the partition of the superblock in the
1525
    // last frame to current frame only if the last frame is not a keyframe.
1526
    // Stop the copy every cpi->max_copied_frame to refresh the partition.
1527
    // TODO(jianj) : tune the threshold.
1528
0
    if (cpi->sf.copy_partition_flag && y_sad_last < cpi->vbp_threshold_copy &&
1529
0
        copy_partitioning(cpi, x, xd, mi_row, mi_col, segment_id, sb_offset)) {
1530
0
      chroma_check(cpi, x, bsize, y_sad, is_key_frame, scene_change_detected);
1531
0
      if (cpi->sf.svc_use_lowres_part &&
1532
0
          cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1533
0
        update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1534
0
      return 0;
1535
0
    }
1536
0
  } else {
1537
0
    d = VP9_VAR_OFFS;
1538
0
    dp = 0;
1539
0
#if CONFIG_VP9_HIGHBITDEPTH
1540
0
    if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
1541
0
      switch (xd->bd) {
1542
0
        case 10: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_10); break;
1543
0
        case 12: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_12); break;
1544
0
        case 8:
1545
0
        default: d = CONVERT_TO_BYTEPTR(VP9_HIGH_VAR_OFFS_8); break;
1546
0
      }
1547
0
    }
1548
0
#endif  // CONFIG_VP9_HIGHBITDEPTH
1549
0
  }
1550
1551
0
  if (low_res && threshold_4x4avg < INT64_MAX)
1552
0
    CHECK_MEM_ERROR(&cm->error, vt2, vpx_calloc(16, sizeof(*vt2)));
1553
  // Fill in the entire tree of 8x8 (or 4x4 under some conditions) variances
1554
  // for splits.
1555
0
  for (i = 0; i < 4; i++) {
1556
0
    const int x32_idx = ((i & 1) << 5);
1557
0
    const int y32_idx = ((i >> 1) << 5);
1558
0
    const int i2 = i << 2;
1559
0
    force_split[i + 1] = 0;
1560
0
    avg_16x16[i] = 0;
1561
0
    maxvar_16x16[i] = 0;
1562
0
    minvar_16x16[i] = INT_MAX;
1563
0
    for (j = 0; j < 4; j++) {
1564
0
      const int x16_idx = x32_idx + ((j & 1) << 4);
1565
0
      const int y16_idx = y32_idx + ((j >> 1) << 4);
1566
0
      const int split_index = 5 + i2 + j;
1567
0
      v16x16 *vst = &vt.split[i].split[j];
1568
0
      force_split[split_index] = 0;
1569
0
      variance4x4downsample[i2 + j] = 0;
1570
0
      if (!is_key_frame) {
1571
0
        fill_variance_8x8avg(s, sp, d, dp, x16_idx, y16_idx, vst,
1572
0
#if CONFIG_VP9_HIGHBITDEPTH
1573
0
                             xd->cur_buf->flags,
1574
0
#endif
1575
0
                             pixels_wide, pixels_high, is_key_frame);
1576
0
        fill_variance_tree(&vt.split[i].split[j], BLOCK_16X16);
1577
0
        get_variance(&vt.split[i].split[j].part_variances.none);
1578
0
        avg_16x16[i] += vt.split[i].split[j].part_variances.none.variance;
1579
0
        if (vt.split[i].split[j].part_variances.none.variance < minvar_16x16[i])
1580
0
          minvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1581
0
        if (vt.split[i].split[j].part_variances.none.variance > maxvar_16x16[i])
1582
0
          maxvar_16x16[i] = vt.split[i].split[j].part_variances.none.variance;
1583
0
        if (vt.split[i].split[j].part_variances.none.variance > thresholds[2]) {
1584
          // 16X16 variance is above threshold for split, so force split to 8x8
1585
          // for this 16x16 block (this also forces splits for upper levels).
1586
0
          force_split[split_index] = 1;
1587
0
          force_split[i + 1] = 1;
1588
0
          force_split[0] = 1;
1589
0
        } else if (compute_minmax_variance &&
1590
0
                   vt.split[i].split[j].part_variances.none.variance >
1591
0
                       thresholds[1] &&
1592
0
                   !cyclic_refresh_segment_id_boosted(segment_id)) {
1593
          // We have some nominal amount of 16x16 variance (based on average),
1594
          // compute the minmax over the 8x8 sub-blocks, and if above threshold,
1595
          // force split to 8x8 block for this 16x16 block.
1596
0
          int minmax = compute_minmax_8x8(s, sp, d, dp, x16_idx, y16_idx,
1597
0
#if CONFIG_VP9_HIGHBITDEPTH
1598
0
                                          xd->cur_buf->flags,
1599
0
#endif
1600
0
                                          pixels_wide, pixels_high);
1601
0
          int thresh_minmax = (int)cpi->vbp_threshold_minmax;
1602
0
          if (x->content_state_sb == kVeryHighSad)
1603
0
            thresh_minmax = thresh_minmax << 1;
1604
0
          if (minmax > thresh_minmax) {
1605
0
            force_split[split_index] = 1;
1606
0
            force_split[i + 1] = 1;
1607
0
            force_split[0] = 1;
1608
0
          }
1609
0
        }
1610
0
      }
1611
0
      if (is_key_frame ||
1612
0
          (low_res && vt.split[i].split[j].part_variances.none.variance >
1613
0
                          threshold_4x4avg)) {
1614
0
        force_split[split_index] = 0;
1615
        // Go down to 4x4 down-sampling for variance.
1616
0
        variance4x4downsample[i2 + j] = 1;
1617
0
        for (k = 0; k < 4; k++) {
1618
0
          int x8_idx = x16_idx + ((k & 1) << 3);
1619
0
          int y8_idx = y16_idx + ((k >> 1) << 3);
1620
0
          v8x8 *vst2 = is_key_frame ? &vst->split[k] : &vt2[i2 + j].split[k];
1621
0
          fill_variance_4x4avg(s, sp, d, dp, x8_idx, y8_idx, vst2,
1622
0
#if CONFIG_VP9_HIGHBITDEPTH
1623
0
                               xd->cur_buf->flags,
1624
0
#endif
1625
0
                               pixels_wide, pixels_high, is_key_frame);
1626
0
        }
1627
0
      }
1628
0
    }
1629
0
  }
1630
0
  if (cpi->noise_estimate.enabled)
1631
0
    noise_level = vp9_noise_estimate_extract_level(&cpi->noise_estimate);
1632
  // Fill the rest of the variance tree by summing split partition values.
1633
0
  avg_32x32 = 0;
1634
0
  for (i = 0; i < 4; i++) {
1635
0
    const int i2 = i << 2;
1636
0
    for (j = 0; j < 4; j++) {
1637
0
      if (variance4x4downsample[i2 + j] == 1) {
1638
0
        v16x16 *vtemp = (!is_key_frame) ? &vt2[i2 + j] : &vt.split[i].split[j];
1639
0
        for (m = 0; m < 4; m++) fill_variance_tree(&vtemp->split[m], BLOCK_8X8);
1640
0
        fill_variance_tree(vtemp, BLOCK_16X16);
1641
        // If variance of this 16x16 block is above the threshold, force block
1642
        // to split. This also forces a split on the upper levels.
1643
0
        get_variance(&vtemp->part_variances.none);
1644
0
        if (vtemp->part_variances.none.variance > thresholds[2]) {
1645
0
          force_split[5 + i2 + j] = 1;
1646
0
          force_split[i + 1] = 1;
1647
0
          force_split[0] = 1;
1648
0
        }
1649
0
      }
1650
0
    }
1651
0
    fill_variance_tree(&vt.split[i], BLOCK_32X32);
1652
    // If variance of this 32x32 block is above the threshold, or if its above
1653
    // (some threshold of) the average variance over the sub-16x16 blocks, then
1654
    // force this block to split. This also forces a split on the upper
1655
    // (64x64) level.
1656
0
    if (!force_split[i + 1]) {
1657
0
      get_variance(&vt.split[i].part_variances.none);
1658
0
      var_32x32 = vt.split[i].part_variances.none.variance;
1659
0
      max_var_32x32 = VPXMAX(var_32x32, max_var_32x32);
1660
0
      min_var_32x32 = VPXMIN(var_32x32, min_var_32x32);
1661
0
      if (vt.split[i].part_variances.none.variance > thresholds[1] ||
1662
0
          (!is_key_frame &&
1663
0
           vt.split[i].part_variances.none.variance > (thresholds[1] >> 1) &&
1664
0
           vt.split[i].part_variances.none.variance > (avg_16x16[i] >> 1))) {
1665
0
        force_split[i + 1] = 1;
1666
0
        force_split[0] = 1;
1667
0
      } else if (!is_key_frame && noise_level < kLow && cm->height <= 360 &&
1668
0
                 (maxvar_16x16[i] - minvar_16x16[i]) > (thresholds[1] >> 1) &&
1669
0
                 maxvar_16x16[i] > thresholds[1]) {
1670
0
        force_split[i + 1] = 1;
1671
0
        force_split[0] = 1;
1672
0
      }
1673
0
      avg_32x32 += var_32x32;
1674
0
    }
1675
0
  }
1676
0
  if (!force_split[0]) {
1677
0
    fill_variance_tree(&vt, BLOCK_64X64);
1678
0
    get_variance(&vt.part_variances.none);
1679
    // If variance of this 64x64 block is above (some threshold of) the average
1680
    // variance over the sub-32x32 blocks, then force this block to split.
1681
    // Only checking this for noise level >= medium for now.
1682
0
    if (!is_key_frame && noise_level >= kMedium &&
1683
0
        vt.part_variances.none.variance > (9 * avg_32x32) >> 5)
1684
0
      force_split[0] = 1;
1685
    // Else if the maximum 32x32 variance minus the miniumum 32x32 variance in
1686
    // a 64x64 block is greater than threshold and the maximum 32x32 variance is
1687
    // above a miniumum threshold, then force the split of a 64x64 block
1688
    // Only check this for low noise.
1689
0
    else if (!is_key_frame && noise_level < kMedium &&
1690
0
             (max_var_32x32 - min_var_32x32) > 3 * (thresholds[0] >> 3) &&
1691
0
             max_var_32x32 > thresholds[0] >> 1)
1692
0
      force_split[0] = 1;
1693
0
  }
1694
1695
  // Now go through the entire structure, splitting every block size until
1696
  // we get to one that's got a variance lower than our threshold.
1697
0
  if (mi_col + 8 > cm->mi_cols || mi_row + 8 > cm->mi_rows ||
1698
0
      !set_vt_partitioning(cpi, x, xd, &vt, BLOCK_64X64, mi_row, mi_col,
1699
0
                           thresholds[0], BLOCK_16X16, force_split[0])) {
1700
0
    for (i = 0; i < 4; ++i) {
1701
0
      const int x32_idx = ((i & 1) << 2);
1702
0
      const int y32_idx = ((i >> 1) << 2);
1703
0
      const int i2 = i << 2;
1704
0
      if (!set_vt_partitioning(cpi, x, xd, &vt.split[i], BLOCK_32X32,
1705
0
                               (mi_row + y32_idx), (mi_col + x32_idx),
1706
0
                               thresholds[1], BLOCK_16X16,
1707
0
                               force_split[i + 1])) {
1708
0
        for (j = 0; j < 4; ++j) {
1709
0
          const int x16_idx = ((j & 1) << 1);
1710
0
          const int y16_idx = ((j >> 1) << 1);
1711
          // For inter frames: if variance4x4downsample[] == 1 for this 16x16
1712
          // block, then the variance is based on 4x4 down-sampling, so use vt2
1713
          // in set_vt_partitioning(), otherwise use vt.
1714
0
          v16x16 *vtemp = (!is_key_frame && variance4x4downsample[i2 + j] == 1)
1715
0
                              ? &vt2[i2 + j]
1716
0
                              : &vt.split[i].split[j];
1717
0
          if (!set_vt_partitioning(
1718
0
                  cpi, x, xd, vtemp, BLOCK_16X16, mi_row + y32_idx + y16_idx,
1719
0
                  mi_col + x32_idx + x16_idx, thresholds[2], cpi->vbp_bsize_min,
1720
0
                  force_split[5 + i2 + j])) {
1721
0
            for (k = 0; k < 4; ++k) {
1722
0
              const int x8_idx = (k & 1);
1723
0
              const int y8_idx = (k >> 1);
1724
0
              if (use_4x4_partition) {
1725
0
                if (!set_vt_partitioning(cpi, x, xd, &vtemp->split[k],
1726
0
                                         BLOCK_8X8,
1727
0
                                         mi_row + y32_idx + y16_idx + y8_idx,
1728
0
                                         mi_col + x32_idx + x16_idx + x8_idx,
1729
0
                                         thresholds[3], BLOCK_8X8, 0)) {
1730
0
                  set_block_size(
1731
0
                      cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1732
0
                      (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_4X4);
1733
0
                }
1734
0
              } else {
1735
0
                set_block_size(
1736
0
                    cpi, x, xd, (mi_row + y32_idx + y16_idx + y8_idx),
1737
0
                    (mi_col + x32_idx + x16_idx + x8_idx), BLOCK_8X8);
1738
0
              }
1739
0
            }
1740
0
          }
1741
0
        }
1742
0
      }
1743
0
    }
1744
0
  }
1745
1746
0
  if (!frame_is_intra_only(cm) && cpi->sf.copy_partition_flag) {
1747
0
    update_prev_partition(cpi, x, segment_id, mi_row, mi_col, sb_offset);
1748
0
  }
1749
1750
0
  if (!frame_is_intra_only(cm) && cpi->sf.svc_use_lowres_part &&
1751
0
      cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 2)
1752
0
    update_partition_svc(cpi, BLOCK_64X64, mi_row, mi_col);
1753
1754
0
  if (cpi->sf.short_circuit_low_temp_var) {
1755
0
    set_low_temp_var_flag(cpi, x, xd, &vt, thresholds, ref_frame_partition,
1756
0
                          mi_col, mi_row);
1757
0
  }
1758
1759
0
  chroma_check(cpi, x, bsize, y_sad, is_key_frame, scene_change_detected);
1760
0
  if (vt2) vpx_free(vt2);
1761
0
  return 0;
1762
0
}
1763
1764
#if !CONFIG_REALTIME_ONLY
1765
static void update_state(VP9_COMP *cpi, ThreadData *td, PICK_MODE_CONTEXT *ctx,
1766
                         int mi_row, int mi_col, BLOCK_SIZE bsize,
1767
7.27M
                         int output_enabled) {
1768
7.27M
  int i, x_idx, y;
1769
7.27M
  VP9_COMMON *const cm = &cpi->common;
1770
7.27M
  RD_COUNTS *const rdc = &td->rd_counts;
1771
7.27M
  MACROBLOCK *const x = &td->mb;
1772
7.27M
  MACROBLOCKD *const xd = &x->e_mbd;
1773
7.27M
  struct macroblock_plane *const p = x->plane;
1774
7.27M
  struct macroblockd_plane *const pd = xd->plane;
1775
7.27M
  MODE_INFO *mi = &ctx->mic;
1776
7.27M
  MODE_INFO *const xdmi = xd->mi[0];
1777
7.27M
  MODE_INFO *mi_addr = xd->mi[0];
1778
7.27M
  const struct segmentation *const seg = &cm->seg;
1779
7.27M
  const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
1780
7.27M
  const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
1781
7.27M
  const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
1782
7.27M
  const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
1783
7.27M
  MV_REF *const frame_mvs = cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
1784
7.27M
  int w, h;
1785
1786
7.27M
  const int mis = cm->mi_stride;
1787
7.27M
  const int mi_width = num_8x8_blocks_wide_lookup[bsize];
1788
7.27M
  const int mi_height = num_8x8_blocks_high_lookup[bsize];
1789
7.27M
  int max_plane;
1790
1791
7.27M
  assert(mi->sb_type == bsize);
1792
1793
7.27M
  *mi_addr = *mi;
1794
7.27M
  *x->mbmi_ext = ctx->mbmi_ext;
1795
1796
  // If segmentation in use
1797
7.27M
  if (seg->enabled) {
1798
    // For in frame complexity AQ copy the segment id from the segment map.
1799
0
    if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1800
0
      const uint8_t *const map =
1801
0
          seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1802
0
      mi_addr->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
1803
0
    }
1804
    // Else for cyclic refresh mode update the segment map, set the segment id
1805
    // and then update the quantizer.
1806
0
    if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
1807
0
        cpi->cyclic_refresh->content_mode) {
1808
0
      vp9_cyclic_refresh_update_segment(cpi, xd->mi[0], mi_row, mi_col, bsize,
1809
0
                                        ctx->rate, ctx->dist, x->skip, p);
1810
0
    }
1811
0
  }
1812
1813
7.27M
  max_plane = is_inter_block(xdmi) ? MAX_MB_PLANE : 1;
1814
18.4M
  for (i = 0; i < max_plane; ++i) {
1815
11.1M
    p[i].coeff = ctx->coeff_pbuf[i][1];
1816
11.1M
    p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
1817
11.1M
    pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
1818
11.1M
    p[i].eobs = ctx->eobs_pbuf[i][1];
1819
11.1M
  }
1820
1821
17.9M
  for (i = max_plane; i < MAX_MB_PLANE; ++i) {
1822
10.6M
    p[i].coeff = ctx->coeff_pbuf[i][2];
1823
10.6M
    p[i].qcoeff = ctx->qcoeff_pbuf[i][2];
1824
10.6M
    pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][2];
1825
10.6M
    p[i].eobs = ctx->eobs_pbuf[i][2];
1826
10.6M
  }
1827
1828
  // Restore the coding context of the MB to that that was in place
1829
  // when the mode was picked for it
1830
16.1M
  for (y = 0; y < mi_height; y++)
1831
22.7M
    for (x_idx = 0; x_idx < mi_width; x_idx++)
1832
13.8M
      if ((xd->mb_to_right_edge >> (3 + MI_SIZE_LOG2)) + mi_width > x_idx &&
1833
13.6M
          (xd->mb_to_bottom_edge >> (3 + MI_SIZE_LOG2)) + mi_height > y) {
1834
13.3M
        xd->mi[x_idx + y * mis] = mi_addr;
1835
13.3M
      }
1836
1837
7.27M
  if (cpi->oxcf.aq_mode != NO_AQ) vp9_init_plane_quantizers(cpi, x);
1838
1839
7.27M
  if (is_inter_block(xdmi) && xdmi->sb_type < BLOCK_8X8) {
1840
687k
    xdmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
1841
687k
    xdmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
1842
687k
  }
1843
1844
7.27M
  x->skip = ctx->skip;
1845
7.27M
  memcpy(x->zcoeff_blk[xdmi->tx_size], ctx->zcoeff_blk,
1846
7.27M
         sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
1847
1848
7.27M
  if (!output_enabled) return;
1849
1850
#if CONFIG_INTERNAL_STATS
1851
  if (frame_is_intra_only(cm)) {
1852
    static const int kf_mode_index[] = {
1853
      THR_DC /*DC_PRED*/,          THR_V_PRED /*V_PRED*/,
1854
      THR_H_PRED /*H_PRED*/,       THR_D45_PRED /*D45_PRED*/,
1855
      THR_D135_PRED /*D135_PRED*/, THR_D117_PRED /*D117_PRED*/,
1856
      THR_D153_PRED /*D153_PRED*/, THR_D207_PRED /*D207_PRED*/,
1857
      THR_D63_PRED /*D63_PRED*/,   THR_TM /*TM_PRED*/,
1858
    };
1859
    ++cpi->mode_chosen_counts[kf_mode_index[xdmi->mode]];
1860
  } else {
1861
    // Note how often each mode chosen as best
1862
    ++cpi->mode_chosen_counts[ctx->best_mode_index];
1863
  }
1864
#endif
1865
1.72M
  if (!frame_is_intra_only(cm)) {
1866
1.12M
    if (is_inter_block(xdmi)) {
1867
449k
      vp9_update_mv_count(td);
1868
1869
449k
      if (cm->interp_filter == SWITCHABLE) {
1870
194k
        const int ctx_interp = get_pred_context_switchable_interp(xd);
1871
194k
        ++td->counts->switchable_interp[ctx_interp][xdmi->interp_filter];
1872
194k
      }
1873
449k
    }
1874
1875
1.12M
    rdc->comp_pred_diff[SINGLE_REFERENCE] += ctx->single_pred_diff;
1876
1.12M
    rdc->comp_pred_diff[COMPOUND_REFERENCE] += ctx->comp_pred_diff;
1877
1.12M
    rdc->comp_pred_diff[REFERENCE_MODE_SELECT] += ctx->hybrid_pred_diff;
1878
1879
5.63M
    for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
1880
4.51M
      rdc->filter_diff[i] += ctx->best_filter_diff[i];
1881
1.12M
  }
1882
1883
3.86M
  for (h = 0; h < y_mis; ++h) {
1884
2.13M
    MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
1885
5.90M
    for (w = 0; w < x_mis; ++w) {
1886
3.76M
      MV_REF *const mv = frame_mv + w;
1887
3.76M
      mv->ref_frame[0] = mi->ref_frame[0];
1888
3.76M
      mv->ref_frame[1] = mi->ref_frame[1];
1889
3.76M
      mv->mv[0].as_int = mi->mv[0].as_int;
1890
3.76M
      mv->mv[1].as_int = mi->mv[1].as_int;
1891
3.76M
    }
1892
2.13M
  }
1893
1.72M
}
1894
#endif  // !CONFIG_REALTIME_ONLY
1895
1896
void vp9_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src,
1897
29.2M
                          int mi_row, int mi_col) {
1898
29.2M
  uint8_t *const buffers[3] = { src->y_buffer, src->u_buffer, src->v_buffer };
1899
29.2M
  const int strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
1900
29.2M
  int i;
1901
1902
  // Set current frame pointer.
1903
29.2M
  x->e_mbd.cur_buf = src;
1904
1905
116M
  for (i = 0; i < MAX_MB_PLANE; i++)
1906
87.7M
    setup_pred_plane(&x->plane[i].src, buffers[i], strides[i], mi_row, mi_col,
1907
87.7M
                     NULL, x->e_mbd.plane[i].subsampling_x,
1908
87.7M
                     x->e_mbd.plane[i].subsampling_y);
1909
29.2M
}
1910
1911
static void set_mode_info_seg_skip(MACROBLOCK *x, TX_MODE tx_mode,
1912
                                   INTERP_FILTER interp_filter,
1913
0
                                   RD_COST *rd_cost, BLOCK_SIZE bsize) {
1914
0
  MACROBLOCKD *const xd = &x->e_mbd;
1915
0
  MODE_INFO *const mi = xd->mi[0];
1916
0
  INTERP_FILTER filter_ref;
1917
1918
0
  filter_ref = get_pred_context_switchable_interp(xd);
1919
0
  if (interp_filter == BILINEAR)
1920
0
    filter_ref = BILINEAR;
1921
0
  else if (filter_ref == SWITCHABLE_FILTERS)
1922
0
    filter_ref = EIGHTTAP;
1923
1924
0
  mi->sb_type = bsize;
1925
0
  mi->mode = ZEROMV;
1926
0
  mi->tx_size =
1927
0
      VPXMIN(max_txsize_lookup[bsize], tx_mode_to_biggest_tx_size[tx_mode]);
1928
0
  mi->skip = 1;
1929
0
  mi->uv_mode = DC_PRED;
1930
0
  mi->ref_frame[0] = LAST_FRAME;
1931
0
  mi->ref_frame[1] = NO_REF_FRAME;
1932
0
  mi->mv[0].as_int = 0;
1933
0
  mi->interp_filter = filter_ref;
1934
1935
0
  xd->mi[0]->bmi[0].as_mv[0].as_int = 0;
1936
0
  x->skip = 1;
1937
1938
0
  vp9_rd_cost_init(rd_cost);
1939
0
}
1940
1941
#if !CONFIG_REALTIME_ONLY
1942
static void set_segment_rdmult(VP9_COMP *const cpi, MACROBLOCK *const x,
1943
                               int mi_row, int mi_col, BLOCK_SIZE bsize,
1944
9.09M
                               AQ_MODE aq_mode) {
1945
9.09M
  VP9_COMMON *const cm = &cpi->common;
1946
9.09M
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1947
9.09M
  const uint8_t *const map =
1948
9.09M
      cm->seg.update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
1949
1950
9.09M
  vp9_init_plane_quantizers(cpi, x);
1951
9.09M
  vpx_clear_system_state();
1952
1953
9.09M
  if (aq_mode == NO_AQ || aq_mode == PSNR_AQ) {
1954
9.09M
    if (cpi->sf.enable_tpl_model) x->rdmult = x->cb_rdmult;
1955
9.09M
  } else if (aq_mode == PERCEPTUAL_AQ) {
1956
0
    x->rdmult = x->cb_rdmult;
1957
0
  } else if (aq_mode == CYCLIC_REFRESH_AQ) {
1958
    // If segment is boosted, use rdmult for that segment.
1959
0
    if (cyclic_refresh_segment_id_boosted(
1960
0
            get_segment_id(cm, map, bsize, mi_row, mi_col)))
1961
0
      x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
1962
0
  } else {
1963
0
    x->rdmult = vp9_compute_rd_mult(cpi, cm->base_qindex + cm->y_dc_delta_q);
1964
0
  }
1965
1966
9.09M
  if (oxcf->tuning == VP8_TUNE_SSIM) {
1967
0
    set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &x->rdmult);
1968
0
  }
1969
9.09M
}
1970
1971
static void rd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
1972
                             MACROBLOCK *const x, int mi_row, int mi_col,
1973
                             RD_COST *rd_cost, BLOCK_SIZE bsize,
1974
                             PICK_MODE_CONTEXT *ctx, int rate_in_best_rd,
1975
9.09M
                             int64_t dist_in_best_rd) {
1976
9.09M
  VP9_COMMON *const cm = &cpi->common;
1977
9.09M
  TileInfo *const tile_info = &tile_data->tile_info;
1978
9.09M
  MACROBLOCKD *const xd = &x->e_mbd;
1979
9.09M
  MODE_INFO *mi;
1980
9.09M
  struct macroblock_plane *const p = x->plane;
1981
9.09M
  struct macroblockd_plane *const pd = xd->plane;
1982
9.09M
  const AQ_MODE aq_mode = cpi->oxcf.aq_mode;
1983
9.09M
  int i, orig_rdmult;
1984
9.09M
  int64_t best_rd = INT64_MAX;
1985
1986
9.09M
  vpx_clear_system_state();
1987
#if CONFIG_COLLECT_COMPONENT_TIMING
1988
  start_timing(cpi, rd_pick_sb_modes_time);
1989
#endif
1990
1991
  // Use the lower precision, but faster, 32x32 fdct for mode selection.
1992
9.09M
  x->use_lp32x32fdct = 1;
1993
1994
9.09M
  set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
1995
9.09M
  mi = xd->mi[0];
1996
9.09M
  mi->sb_type = bsize;
1997
1998
36.3M
  for (i = 0; i < MAX_MB_PLANE; ++i) {
1999
27.2M
    p[i].coeff = ctx->coeff_pbuf[i][0];
2000
27.2M
    p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
2001
27.2M
    pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
2002
27.2M
    p[i].eobs = ctx->eobs_pbuf[i][0];
2003
27.2M
  }
2004
9.09M
  ctx->is_coded = 0;
2005
9.09M
  ctx->skippable = 0;
2006
9.09M
  ctx->pred_pixel_ready = 0;
2007
9.09M
  x->skip_recode = 0;
2008
2009
  // Set to zero to make sure we do not use the previous encoded frame stats
2010
9.09M
  mi->skip = 0;
2011
2012
9.09M
#if CONFIG_VP9_HIGHBITDEPTH
2013
9.09M
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
2014
144k
    x->source_variance = vp9_high_get_sby_perpixel_variance(
2015
144k
        cpi, &x->plane[0].src, bsize, xd->bd);
2016
8.95M
  } else {
2017
8.95M
    x->source_variance =
2018
8.95M
        vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
2019
8.95M
  }
2020
#else
2021
  x->source_variance =
2022
      vp9_get_sby_perpixel_variance(cpi, &x->plane[0].src, bsize);
2023
#endif  // CONFIG_VP9_HIGHBITDEPTH
2024
2025
  // Save rdmult before it might be changed, so it can be restored later.
2026
9.09M
  orig_rdmult = x->rdmult;
2027
2028
9.09M
  if ((cpi->sf.tx_domain_thresh > 0.0) ||
2029
6.35M
      (cpi->sf.trellis_opt_tx_rd.thresh > 0.0)) {
2030
2.74M
    double logvar = vp9_log_block_var(cpi, x, bsize);
2031
    // Check block complexity as part of decision on using pixel or transform
2032
    // domain distortion in rd tests.
2033
2.74M
    x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion &&
2034
2.74M
                         (logvar >= cpi->sf.tx_domain_thresh);
2035
2036
    // Store block complexity to decide on using quantized coefficient
2037
    // optimization inside the rd loop.
2038
2.74M
    x->log_block_src_var = logvar;
2039
6.35M
  } else {
2040
6.35M
    x->block_tx_domain = cpi->sf.allow_txfm_domain_distortion;
2041
6.35M
    x->log_block_src_var = 0.0;
2042
6.35M
  }
2043
2044
9.09M
  set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
2045
9.09M
  set_segment_rdmult(cpi, x, mi_row, mi_col, bsize, aq_mode);
2046
9.09M
  if (rate_in_best_rd < INT_MAX && dist_in_best_rd < INT64_MAX) {
2047
8.68M
    best_rd = vp9_calculate_rd_cost(x->rdmult, x->rddiv, rate_in_best_rd,
2048
8.68M
                                    dist_in_best_rd);
2049
8.68M
  }
2050
2051
  // Find best coding mode & reconstruct the MB so it is available
2052
  // as a predictor for MBs that follow in the SB
2053
9.09M
  if (frame_is_intra_only(cm)) {
2054
3.63M
    vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, best_rd);
2055
5.45M
  } else {
2056
5.45M
    if (bsize >= BLOCK_8X8) {
2057
#if CONFIG_COLLECT_COMPONENT_TIMING
2058
      start_timing(cpi, vp9_rd_pick_inter_mode_sb_time);
2059
#endif
2060
3.05M
      if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
2061
0
        vp9_rd_pick_inter_mode_sb_seg_skip(cpi, tile_data, x, rd_cost, bsize,
2062
0
                                           ctx, best_rd);
2063
3.05M
      else
2064
3.05M
        vp9_rd_pick_inter_mode_sb(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2065
3.05M
                                  bsize, ctx, best_rd);
2066
#if CONFIG_COLLECT_COMPONENT_TIMING
2067
      end_timing(cpi, vp9_rd_pick_inter_mode_sb_time);
2068
#endif
2069
3.05M
    } else {
2070
#if CONFIG_COLLECT_COMPONENT_TIMING
2071
      start_timing(cpi, vp9_rd_pick_inter_mode_sub8x8_time);
2072
#endif
2073
2.40M
      vp9_rd_pick_inter_mode_sub8x8(cpi, tile_data, x, mi_row, mi_col, rd_cost,
2074
2.40M
                                    bsize, ctx, best_rd);
2075
#if CONFIG_COLLECT_COMPONENT_TIMING
2076
      end_timing(cpi, vp9_rd_pick_inter_mode_sub8x8_time);
2077
#endif
2078
2.40M
    }
2079
5.45M
  }
2080
2081
  // Examine the resulting rate and for AQ mode 2 make a segment choice.
2082
9.09M
  if ((rd_cost->rate != INT_MAX) && (aq_mode == COMPLEXITY_AQ) &&
2083
0
      (bsize >= BLOCK_16X16) &&
2084
0
      (cm->frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame ||
2085
0
       (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref))) {
2086
0
    vp9_caq_select_segment(cpi, x, bsize, mi_row, mi_col, rd_cost->rate);
2087
0
  }
2088
2089
  // TODO(jingning) The rate-distortion optimization flow needs to be
2090
  // refactored to provide proper exit/return handle.
2091
9.09M
  if (rd_cost->rate == INT_MAX || rd_cost->dist == INT64_MAX)
2092
3.03M
    rd_cost->rdcost = INT64_MAX;
2093
6.05M
  else
2094
6.05M
    rd_cost->rdcost = RDCOST(x->rdmult, x->rddiv, rd_cost->rate, rd_cost->dist);
2095
2096
9.09M
  x->rdmult = orig_rdmult;
2097
2098
9.09M
  ctx->rate = rd_cost->rate;
2099
9.09M
  ctx->dist = rd_cost->dist;
2100
#if CONFIG_COLLECT_COMPONENT_TIMING
2101
  end_timing(cpi, rd_pick_sb_modes_time);
2102
#endif
2103
9.09M
}
2104
#endif  // !CONFIG_REALTIME_ONLY
2105
2106
1.72M
static void update_stats(VP9_COMMON *cm, ThreadData *td) {
2107
1.72M
  const MACROBLOCK *x = &td->mb;
2108
1.72M
  const MACROBLOCKD *const xd = &x->e_mbd;
2109
1.72M
  const MODE_INFO *const mi = xd->mi[0];
2110
1.72M
  const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
2111
1.72M
  const BLOCK_SIZE bsize = mi->sb_type;
2112
2113
1.72M
  if (!frame_is_intra_only(cm)) {
2114
1.12M
    FRAME_COUNTS *const counts = td->counts;
2115
1.12M
    const int inter_block = is_inter_block(mi);
2116
1.12M
    const int seg_ref_active =
2117
1.12M
        segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_REF_FRAME);
2118
1.12M
    if (!seg_ref_active) {
2119
1.12M
      counts->intra_inter[get_intra_inter_context(xd)][inter_block]++;
2120
      // If the segment reference feature is enabled we have only a single
2121
      // reference frame allowed for the segment so exclude it from
2122
      // the reference frame counts used to work out probabilities.
2123
1.12M
      if (inter_block) {
2124
449k
        const MV_REFERENCE_FRAME ref0 = mi->ref_frame[0];
2125
449k
        if (cm->reference_mode == REFERENCE_MODE_SELECT)
2126
0
          counts->comp_inter[vp9_get_reference_mode_context(cm, xd)]
2127
0
                            [has_second_ref(mi)]++;
2128
2129
449k
        if (has_second_ref(mi)) {
2130
0
          const int idx = cm->ref_frame_sign_bias[cm->comp_fixed_ref];
2131
0
          const int ctx = vp9_get_pred_context_comp_ref_p(cm, xd);
2132
0
          const int bit = mi->ref_frame[!idx] == cm->comp_var_ref[1];
2133
0
          counts->comp_ref[ctx][bit]++;
2134
449k
        } else {
2135
449k
          counts->single_ref[vp9_get_pred_context_single_ref_p1(xd)][0]
2136
449k
                            [ref0 != LAST_FRAME]++;
2137
449k
          if (ref0 != LAST_FRAME)
2138
149k
            counts->single_ref[vp9_get_pred_context_single_ref_p2(xd)][1]
2139
149k
                              [ref0 != GOLDEN_FRAME]++;
2140
449k
        }
2141
449k
      }
2142
1.12M
    }
2143
1.12M
    if (inter_block &&
2144
449k
        !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP)) {
2145
449k
      const int mode_ctx = mbmi_ext->mode_context[mi->ref_frame[0]];
2146
449k
      if (bsize >= BLOCK_8X8) {
2147
262k
        const PREDICTION_MODE mode = mi->mode;
2148
262k
        ++counts->inter_mode[mode_ctx][INTER_OFFSET(mode)];
2149
262k
      } else {
2150
186k
        const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
2151
186k
        const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
2152
186k
        int idx, idy;
2153
542k
        for (idy = 0; idy < 2; idy += num_4x4_h) {
2154
984k
          for (idx = 0; idx < 2; idx += num_4x4_w) {
2155
628k
            const int j = idy * 2 + idx;
2156
628k
            const PREDICTION_MODE b_mode = mi->bmi[j].as_mode;
2157
628k
            ++counts->inter_mode[mode_ctx][INTER_OFFSET(b_mode)];
2158
628k
          }
2159
355k
        }
2160
186k
      }
2161
449k
    }
2162
1.12M
  }
2163
1.72M
}
2164
2165
#if !CONFIG_REALTIME_ONLY
2166
static void restore_context(MACROBLOCK *const x, int mi_row, int mi_col,
2167
                            ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2168
                            ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2169
                            PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2170
9.50M
                            BLOCK_SIZE bsize) {
2171
9.50M
  MACROBLOCKD *const xd = &x->e_mbd;
2172
9.50M
  int p;
2173
9.50M
  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2174
9.50M
  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2175
9.50M
  int mi_width = num_8x8_blocks_wide_lookup[bsize];
2176
9.50M
  int mi_height = num_8x8_blocks_high_lookup[bsize];
2177
38.0M
  for (p = 0; p < MAX_MB_PLANE; p++) {
2178
28.5M
    memcpy(xd->above_context[p] + ((mi_col * 2) >> xd->plane[p].subsampling_x),
2179
28.5M
           a + num_4x4_blocks_wide * p,
2180
28.5M
           (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2181
28.5M
               xd->plane[p].subsampling_x);
2182
28.5M
    memcpy(xd->left_context[p] +
2183
28.5M
               ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2184
28.5M
           l + num_4x4_blocks_high * p,
2185
28.5M
           (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2186
28.5M
               xd->plane[p].subsampling_y);
2187
28.5M
  }
2188
9.50M
  memcpy(xd->above_seg_context + mi_col, sa,
2189
9.50M
         sizeof(*xd->above_seg_context) * mi_width);
2190
9.50M
  memcpy(xd->left_seg_context + (mi_row & MI_MASK), sl,
2191
9.50M
         sizeof(xd->left_seg_context[0]) * mi_height);
2192
9.50M
}
2193
2194
static void save_context(MACROBLOCK *const x, int mi_row, int mi_col,
2195
                         ENTROPY_CONTEXT a[16 * MAX_MB_PLANE],
2196
                         ENTROPY_CONTEXT l[16 * MAX_MB_PLANE],
2197
                         PARTITION_CONTEXT sa[8], PARTITION_CONTEXT sl[8],
2198
3.58M
                         BLOCK_SIZE bsize) {
2199
3.58M
  const MACROBLOCKD *const xd = &x->e_mbd;
2200
3.58M
  int p;
2201
3.58M
  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
2202
3.58M
  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
2203
3.58M
  int mi_width = num_8x8_blocks_wide_lookup[bsize];
2204
3.58M
  int mi_height = num_8x8_blocks_high_lookup[bsize];
2205
2206
  // buffer the above/left context information of the block in search.
2207
14.3M
  for (p = 0; p < MAX_MB_PLANE; ++p) {
2208
10.7M
    memcpy(a + num_4x4_blocks_wide * p,
2209
10.7M
           xd->above_context[p] + (mi_col * 2 >> xd->plane[p].subsampling_x),
2210
10.7M
           (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_wide) >>
2211
10.7M
               xd->plane[p].subsampling_x);
2212
10.7M
    memcpy(l + num_4x4_blocks_high * p,
2213
10.7M
           xd->left_context[p] +
2214
10.7M
               ((mi_row & MI_MASK) * 2 >> xd->plane[p].subsampling_y),
2215
10.7M
           (sizeof(ENTROPY_CONTEXT) * num_4x4_blocks_high) >>
2216
10.7M
               xd->plane[p].subsampling_y);
2217
10.7M
  }
2218
3.58M
  memcpy(sa, xd->above_seg_context + mi_col,
2219
3.58M
         sizeof(*xd->above_seg_context) * mi_width);
2220
3.58M
  memcpy(sl, xd->left_seg_context + (mi_row & MI_MASK),
2221
3.58M
         sizeof(xd->left_seg_context[0]) * mi_height);
2222
3.58M
}
2223
2224
static void encode_b(VP9_COMP *cpi, const TileInfo *const tile, ThreadData *td,
2225
                     TOKENEXTRA **tp, int mi_row, int mi_col,
2226
                     int output_enabled, BLOCK_SIZE bsize,
2227
6.54M
                     PICK_MODE_CONTEXT *ctx) {
2228
6.54M
  MACROBLOCK *const x = &td->mb;
2229
6.54M
  set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2230
2231
6.54M
  if (cpi->sf.enable_tpl_model &&
2232
2.65M
      (cpi->oxcf.aq_mode == NO_AQ || cpi->oxcf.aq_mode == PERCEPTUAL_AQ)) {
2233
2.65M
    const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2234
2.65M
    x->rdmult = x->cb_rdmult;
2235
2.65M
    if (oxcf->tuning == VP8_TUNE_SSIM) {
2236
0
      set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &x->rdmult);
2237
0
    }
2238
2.65M
  }
2239
2240
6.54M
  update_state(cpi, td, ctx, mi_row, mi_col, bsize, output_enabled);
2241
6.54M
  encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2242
2243
6.54M
  if (output_enabled) {
2244
1.72M
    update_stats(&cpi->common, td);
2245
2246
1.72M
    (*tp)->token = EOSB_TOKEN;
2247
1.72M
    (*tp)++;
2248
1.72M
  }
2249
6.54M
}
2250
2251
static void encode_sb(VP9_COMP *cpi, ThreadData *td, const TileInfo *const tile,
2252
                      TOKENEXTRA **tp, int mi_row, int mi_col,
2253
9.10M
                      int output_enabled, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2254
9.10M
  VP9_COMMON *const cm = &cpi->common;
2255
9.10M
  MACROBLOCK *const x = &td->mb;
2256
9.10M
  MACROBLOCKD *const xd = &x->e_mbd;
2257
2258
9.10M
  const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2259
9.10M
  int ctx;
2260
9.10M
  PARTITION_TYPE partition;
2261
9.10M
  BLOCK_SIZE subsize = bsize;
2262
2263
9.10M
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2264
2265
8.01M
  if (bsize >= BLOCK_8X8) {
2266
8.01M
    ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2267
8.01M
    subsize = get_subsize(bsize, pc_tree->partitioning);
2268
8.01M
  } else {
2269
0
    ctx = 0;
2270
0
    subsize = BLOCK_4X4;
2271
0
  }
2272
2273
8.01M
  partition = partition_lookup[bsl][subsize];
2274
8.01M
  if (output_enabled && bsize != BLOCK_4X4)
2275
2.38M
    td->counts->partition[ctx][partition]++;
2276
2277
8.01M
  switch (partition) {
2278
2.94M
    case PARTITION_NONE:
2279
2.94M
      encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2280
2.94M
               &pc_tree->none);
2281
2.94M
      break;
2282
437k
    case PARTITION_VERT:
2283
437k
      encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2284
437k
               &pc_tree->vertical[0]);
2285
437k
      if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2286
42.3k
        encode_b(cpi, tile, td, tp, mi_row, mi_col + hbs, output_enabled,
2287
42.3k
                 subsize, &pc_tree->vertical[1]);
2288
42.3k
      }
2289
437k
      break;
2290
730k
    case PARTITION_HORZ:
2291
730k
      encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2292
730k
               &pc_tree->horizontal[0]);
2293
730k
      if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2294
69.9k
        encode_b(cpi, tile, td, tp, mi_row + hbs, mi_col, output_enabled,
2295
69.9k
                 subsize, &pc_tree->horizontal[1]);
2296
69.9k
      }
2297
730k
      break;
2298
3.90M
    default:
2299
3.90M
      assert(partition == PARTITION_SPLIT);
2300
3.90M
      if (bsize == BLOCK_8X8) {
2301
2.32M
        encode_b(cpi, tile, td, tp, mi_row, mi_col, output_enabled, subsize,
2302
2.32M
                 pc_tree->u.leaf_split[0]);
2303
2.32M
      } else {
2304
1.58M
        encode_sb(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2305
1.58M
                  pc_tree->u.split[0]);
2306
1.58M
        encode_sb(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2307
1.58M
                  subsize, pc_tree->u.split[1]);
2308
1.58M
        encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2309
1.58M
                  subsize, pc_tree->u.split[2]);
2310
1.58M
        encode_sb(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs, output_enabled,
2311
1.58M
                  subsize, pc_tree->u.split[3]);
2312
1.58M
      }
2313
3.90M
      break;
2314
8.01M
  }
2315
2316
8.01M
  if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2317
6.43M
    update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2318
8.01M
}
2319
#endif  // !CONFIG_REALTIME_ONLY
2320
2321
// Check to see if the given partition size is allowed for a specified number
2322
// of 8x8 block rows and columns remaining in the image.
2323
// If not then return the largest allowed partition size
2324
static BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize, int rows_left,
2325
0
                                      int cols_left, int *bh, int *bw) {
2326
0
  if (rows_left <= 0 || cols_left <= 0) {
2327
0
    return VPXMIN(bsize, BLOCK_8X8);
2328
0
  } else {
2329
0
    for (; bsize > 0; bsize -= 3) {
2330
0
      *bh = num_8x8_blocks_high_lookup[bsize];
2331
0
      *bw = num_8x8_blocks_wide_lookup[bsize];
2332
0
      if ((*bh <= rows_left) && (*bw <= cols_left)) {
2333
0
        break;
2334
0
      }
2335
0
    }
2336
0
  }
2337
0
  return bsize;
2338
0
}
2339
2340
static void set_partial_b64x64_partition(MODE_INFO *mi, int mis, int bh_in,
2341
                                         int bw_in, int row8x8_remaining,
2342
                                         int col8x8_remaining, BLOCK_SIZE bsize,
2343
0
                                         MODE_INFO **mi_8x8) {
2344
0
  int bh = bh_in;
2345
0
  int r, c;
2346
0
  for (r = 0; r < MI_BLOCK_SIZE; r += bh) {
2347
0
    int bw = bw_in;
2348
0
    for (c = 0; c < MI_BLOCK_SIZE; c += bw) {
2349
0
      const int index = r * mis + c;
2350
0
      mi_8x8[index] = mi + index;
2351
0
      mi_8x8[index]->sb_type = find_partition_size(
2352
0
          bsize, row8x8_remaining - r, col8x8_remaining - c, &bh, &bw);
2353
0
    }
2354
0
  }
2355
0
}
2356
2357
// This function attempts to set all mode info entries in a given SB64
2358
// to the same block partition size.
2359
// However, at the bottom and right borders of the image the requested size
2360
// may not be allowed in which case this code attempts to choose the largest
2361
// allowable partition.
2362
static void set_fixed_partitioning(VP9_COMP *cpi, const TileInfo *const tile,
2363
                                   MODE_INFO **mi_8x8, int mi_row, int mi_col,
2364
0
                                   BLOCK_SIZE bsize) {
2365
0
  VP9_COMMON *const cm = &cpi->common;
2366
0
  const int mis = cm->mi_stride;
2367
0
  const int row8x8_remaining = tile->mi_row_end - mi_row;
2368
0
  const int col8x8_remaining = tile->mi_col_end - mi_col;
2369
0
  int block_row, block_col;
2370
0
  MODE_INFO *mi_upper_left = cm->mi + mi_row * mis + mi_col;
2371
0
  int bh = num_8x8_blocks_high_lookup[bsize];
2372
0
  int bw = num_8x8_blocks_wide_lookup[bsize];
2373
2374
0
  assert((row8x8_remaining > 0) && (col8x8_remaining > 0));
2375
2376
  // Apply the requested partition size to the SB64 if it is all "in image"
2377
0
  if ((col8x8_remaining >= MI_BLOCK_SIZE) &&
2378
0
      (row8x8_remaining >= MI_BLOCK_SIZE)) {
2379
0
    for (block_row = 0; block_row < MI_BLOCK_SIZE; block_row += bh) {
2380
0
      for (block_col = 0; block_col < MI_BLOCK_SIZE; block_col += bw) {
2381
0
        int index = block_row * mis + block_col;
2382
0
        mi_8x8[index] = mi_upper_left + index;
2383
0
        mi_8x8[index]->sb_type = bsize;
2384
0
      }
2385
0
    }
2386
0
  } else {
2387
    // Else this is a partial SB64.
2388
0
    set_partial_b64x64_partition(mi_upper_left, mis, bh, bw, row8x8_remaining,
2389
0
                                 col8x8_remaining, bsize, mi_8x8);
2390
0
  }
2391
0
}
2392
2393
static void update_state_rt(VP9_COMP *cpi, ThreadData *td,
2394
                            PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
2395
0
                            int bsize) {
2396
0
  VP9_COMMON *const cm = &cpi->common;
2397
0
  MACROBLOCK *const x = &td->mb;
2398
0
  MACROBLOCKD *const xd = &x->e_mbd;
2399
0
  MODE_INFO *const mi = xd->mi[0];
2400
0
  struct macroblock_plane *const p = x->plane;
2401
0
  const struct segmentation *const seg = &cm->seg;
2402
0
  const int bw = num_8x8_blocks_wide_lookup[mi->sb_type];
2403
0
  const int bh = num_8x8_blocks_high_lookup[mi->sb_type];
2404
0
  const int x_mis = VPXMIN(bw, cm->mi_cols - mi_col);
2405
0
  const int y_mis = VPXMIN(bh, cm->mi_rows - mi_row);
2406
2407
0
  *(xd->mi[0]) = ctx->mic;
2408
0
  *(x->mbmi_ext) = ctx->mbmi_ext;
2409
2410
0
  if (seg->enabled && (cpi->oxcf.aq_mode != NO_AQ || cpi->roi.enabled ||
2411
0
                       cpi->active_map.enabled)) {
2412
    // Setting segmentation map for cyclic_refresh.
2413
0
    if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
2414
0
        cpi->cyclic_refresh->content_mode) {
2415
0
      vp9_cyclic_refresh_update_segment(cpi, mi, mi_row, mi_col, bsize,
2416
0
                                        ctx->rate, ctx->dist, x->skip, p);
2417
0
    } else {
2418
0
      const uint8_t *const map =
2419
0
          seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
2420
0
      mi->segment_id = get_segment_id(cm, map, bsize, mi_row, mi_col);
2421
0
    }
2422
0
    vp9_init_plane_quantizers(cpi, x);
2423
0
  }
2424
2425
0
  if (is_inter_block(mi)) {
2426
0
    vp9_update_mv_count(td);
2427
0
    if (cm->interp_filter == SWITCHABLE) {
2428
0
      const int pred_ctx = get_pred_context_switchable_interp(xd);
2429
0
      ++td->counts->switchable_interp[pred_ctx][mi->interp_filter];
2430
0
    }
2431
2432
0
    if (mi->sb_type < BLOCK_8X8) {
2433
0
      mi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int;
2434
0
      mi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int;
2435
0
    }
2436
0
  }
2437
2438
0
  if (cm->use_prev_frame_mvs || !cm->error_resilient_mode ||
2439
0
      (cpi->svc.use_base_mv && cpi->svc.number_spatial_layers > 1 &&
2440
0
       cpi->svc.spatial_layer_id != cpi->svc.number_spatial_layers - 1)) {
2441
0
    MV_REF *const frame_mvs =
2442
0
        cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col;
2443
0
    int w, h;
2444
2445
0
    for (h = 0; h < y_mis; ++h) {
2446
0
      MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols;
2447
0
      for (w = 0; w < x_mis; ++w) {
2448
0
        MV_REF *const mv = frame_mv + w;
2449
0
        mv->ref_frame[0] = mi->ref_frame[0];
2450
0
        mv->ref_frame[1] = mi->ref_frame[1];
2451
0
        mv->mv[0].as_int = mi->mv[0].as_int;
2452
0
        mv->mv[1].as_int = mi->mv[1].as_int;
2453
0
      }
2454
0
    }
2455
0
  }
2456
2457
0
  x->skip = ctx->skip;
2458
0
  x->skip_txfm[0] = (mi->segment_id || xd->lossless) ? 0 : ctx->skip_txfm[0];
2459
0
}
2460
2461
static void encode_b_rt(VP9_COMP *cpi, ThreadData *td,
2462
                        const TileInfo *const tile, TOKENEXTRA **tp, int mi_row,
2463
                        int mi_col, int output_enabled, BLOCK_SIZE bsize,
2464
0
                        PICK_MODE_CONTEXT *ctx) {
2465
0
  MACROBLOCK *const x = &td->mb;
2466
0
  set_offsets(cpi, tile, x, mi_row, mi_col, bsize);
2467
0
  update_state_rt(cpi, td, ctx, mi_row, mi_col, bsize);
2468
2469
0
  encode_superblock(cpi, td, tp, output_enabled, mi_row, mi_col, bsize, ctx);
2470
0
  update_stats(&cpi->common, td);
2471
2472
0
  (*tp)->token = EOSB_TOKEN;
2473
0
  (*tp)++;
2474
0
}
2475
2476
static void encode_sb_rt(VP9_COMP *cpi, ThreadData *td,
2477
                         const TileInfo *const tile, TOKENEXTRA **tp,
2478
                         int mi_row, int mi_col, int output_enabled,
2479
0
                         BLOCK_SIZE bsize, PC_TREE *pc_tree) {
2480
0
  VP9_COMMON *const cm = &cpi->common;
2481
0
  MACROBLOCK *const x = &td->mb;
2482
0
  MACROBLOCKD *const xd = &x->e_mbd;
2483
2484
0
  const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
2485
0
  int ctx;
2486
0
  PARTITION_TYPE partition;
2487
0
  BLOCK_SIZE subsize;
2488
2489
0
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2490
2491
0
  if (bsize >= BLOCK_8X8) {
2492
0
    const int idx_str = xd->mi_stride * mi_row + mi_col;
2493
0
    MODE_INFO **mi_8x8 = cm->mi_grid_visible + idx_str;
2494
0
    ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
2495
0
    subsize = mi_8x8[0]->sb_type;
2496
0
  } else {
2497
0
    ctx = 0;
2498
0
    subsize = BLOCK_4X4;
2499
0
  }
2500
2501
0
  partition = partition_lookup[bsl][subsize];
2502
0
  if (output_enabled && bsize != BLOCK_4X4)
2503
0
    td->counts->partition[ctx][partition]++;
2504
2505
0
  switch (partition) {
2506
0
    case PARTITION_NONE:
2507
0
      encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2508
0
                  &pc_tree->none);
2509
0
      break;
2510
0
    case PARTITION_VERT:
2511
0
      encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2512
0
                  &pc_tree->vertical[0]);
2513
0
      if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
2514
0
        encode_b_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2515
0
                    subsize, &pc_tree->vertical[1]);
2516
0
      }
2517
0
      break;
2518
0
    case PARTITION_HORZ:
2519
0
      encode_b_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2520
0
                  &pc_tree->horizontal[0]);
2521
0
      if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
2522
0
        encode_b_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2523
0
                    subsize, &pc_tree->horizontal[1]);
2524
0
      }
2525
0
      break;
2526
0
    default:
2527
0
      assert(partition == PARTITION_SPLIT);
2528
0
      subsize = get_subsize(bsize, PARTITION_SPLIT);
2529
0
      encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col, output_enabled, subsize,
2530
0
                   pc_tree->u.split[0]);
2531
0
      encode_sb_rt(cpi, td, tile, tp, mi_row, mi_col + hbs, output_enabled,
2532
0
                   subsize, pc_tree->u.split[1]);
2533
0
      encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col, output_enabled,
2534
0
                   subsize, pc_tree->u.split[2]);
2535
0
      encode_sb_rt(cpi, td, tile, tp, mi_row + hbs, mi_col + hbs,
2536
0
                   output_enabled, subsize, pc_tree->u.split[3]);
2537
0
      break;
2538
0
  }
2539
2540
0
  if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
2541
0
    update_partition_context(xd, mi_row, mi_col, subsize, bsize);
2542
0
}
2543
2544
#if !CONFIG_REALTIME_ONLY
2545
static void rd_use_partition(VP9_COMP *cpi, ThreadData *td,
2546
                             TileDataEnc *tile_data, MODE_INFO **mi_8x8,
2547
                             TOKENEXTRA **tp, int mi_row, int mi_col,
2548
                             BLOCK_SIZE bsize, int *rate, int64_t *dist,
2549
0
                             int do_recon, PC_TREE *pc_tree) {
2550
0
  VP9_COMMON *const cm = &cpi->common;
2551
0
  TileInfo *const tile_info = &tile_data->tile_info;
2552
0
  MACROBLOCK *const x = &td->mb;
2553
0
  MACROBLOCKD *const xd = &x->e_mbd;
2554
0
  const int mis = cm->mi_stride;
2555
0
  const int bsl = b_width_log2_lookup[bsize];
2556
0
  const int mi_step = num_4x4_blocks_wide_lookup[bsize] / 2;
2557
0
  const int bss = (1 << bsl) / 4;
2558
0
  int i, pl;
2559
0
  PARTITION_TYPE partition = PARTITION_NONE;
2560
0
  BLOCK_SIZE subsize;
2561
0
  ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
2562
0
  PARTITION_CONTEXT sl[8], sa[8];
2563
0
  RD_COST last_part_rdc, none_rdc, chosen_rdc;
2564
0
  BLOCK_SIZE sub_subsize = BLOCK_4X4;
2565
0
  int splits_below = 0;
2566
0
  BLOCK_SIZE bs_type = mi_8x8[0]->sb_type;
2567
0
  int do_partition_search = 1;
2568
0
  PICK_MODE_CONTEXT *ctx = &pc_tree->none;
2569
2570
0
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
2571
2572
0
  assert(num_4x4_blocks_wide_lookup[bsize] ==
2573
0
         num_4x4_blocks_high_lookup[bsize]);
2574
2575
0
  vp9_rd_cost_reset(&last_part_rdc);
2576
0
  vp9_rd_cost_reset(&none_rdc);
2577
0
  vp9_rd_cost_reset(&chosen_rdc);
2578
2579
0
  partition = partition_lookup[bsl][bs_type];
2580
0
  subsize = get_subsize(bsize, partition);
2581
2582
0
  pc_tree->partitioning = partition;
2583
0
  save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2584
2585
0
  if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ) {
2586
0
    set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
2587
0
    x->mb_energy = vp9_block_energy(cpi, x, bsize);
2588
0
  }
2589
2590
0
  if (do_partition_search &&
2591
0
      cpi->sf.partition_search_type == SEARCH_PARTITION &&
2592
0
      cpi->sf.adjust_partitioning_from_last_frame) {
2593
    // Check if any of the sub blocks are further split.
2594
0
    if (partition == PARTITION_SPLIT && subsize > BLOCK_8X8) {
2595
0
      sub_subsize = get_subsize(subsize, PARTITION_SPLIT);
2596
0
      splits_below = 1;
2597
0
      for (i = 0; i < 4; i++) {
2598
0
        int jj = i >> 1, ii = i & 0x01;
2599
0
        MODE_INFO *this_mi = mi_8x8[jj * bss * mis + ii * bss];
2600
0
        if (this_mi && this_mi->sb_type >= sub_subsize) {
2601
0
          splits_below = 0;
2602
0
        }
2603
0
      }
2604
0
    }
2605
2606
    // If partition is not none try none unless each of the 4 splits are split
2607
    // even further..
2608
0
    if (partition != PARTITION_NONE && !splits_below &&
2609
0
        mi_row + (mi_step >> 1) < cm->mi_rows &&
2610
0
        mi_col + (mi_step >> 1) < cm->mi_cols) {
2611
0
      pc_tree->partitioning = PARTITION_NONE;
2612
0
      rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &none_rdc, bsize, ctx,
2613
0
                       INT_MAX, INT64_MAX);
2614
2615
0
      pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2616
2617
0
      if (none_rdc.rate < INT_MAX) {
2618
0
        none_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2619
0
        none_rdc.rdcost =
2620
0
            RDCOST(x->rdmult, x->rddiv, none_rdc.rate, none_rdc.dist);
2621
0
      }
2622
2623
0
      restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2624
0
      mi_8x8[0]->sb_type = bs_type;
2625
0
      pc_tree->partitioning = partition;
2626
0
    }
2627
0
  }
2628
2629
0
  switch (partition) {
2630
0
    case PARTITION_NONE:
2631
0
      rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc, bsize,
2632
0
                       ctx, INT_MAX, INT64_MAX);
2633
0
      break;
2634
0
    case PARTITION_HORZ:
2635
0
      pc_tree->horizontal[0].skip_ref_frame_mask = 0;
2636
0
      rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2637
0
                       subsize, &pc_tree->horizontal[0], INT_MAX, INT64_MAX);
2638
0
      if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2639
0
          mi_row + (mi_step >> 1) < cm->mi_rows) {
2640
0
        RD_COST tmp_rdc;
2641
0
        PICK_MODE_CONTEXT *hctx = &pc_tree->horizontal[0];
2642
0
        vp9_rd_cost_init(&tmp_rdc);
2643
0
        update_state(cpi, td, hctx, mi_row, mi_col, subsize, 0);
2644
0
        encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, hctx);
2645
0
        pc_tree->horizontal[1].skip_ref_frame_mask = 0;
2646
0
        rd_pick_sb_modes(cpi, tile_data, x, mi_row + (mi_step >> 1), mi_col,
2647
0
                         &tmp_rdc, subsize, &pc_tree->horizontal[1], INT_MAX,
2648
0
                         INT64_MAX);
2649
0
        if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2650
0
          vp9_rd_cost_reset(&last_part_rdc);
2651
0
          break;
2652
0
        }
2653
0
        last_part_rdc.rate += tmp_rdc.rate;
2654
0
        last_part_rdc.dist += tmp_rdc.dist;
2655
0
        last_part_rdc.rdcost += tmp_rdc.rdcost;
2656
0
      }
2657
0
      break;
2658
0
    case PARTITION_VERT:
2659
0
      pc_tree->vertical[0].skip_ref_frame_mask = 0;
2660
0
      rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2661
0
                       subsize, &pc_tree->vertical[0], INT_MAX, INT64_MAX);
2662
0
      if (last_part_rdc.rate != INT_MAX && bsize >= BLOCK_8X8 &&
2663
0
          mi_col + (mi_step >> 1) < cm->mi_cols) {
2664
0
        RD_COST tmp_rdc;
2665
0
        PICK_MODE_CONTEXT *vctx = &pc_tree->vertical[0];
2666
0
        vp9_rd_cost_init(&tmp_rdc);
2667
0
        update_state(cpi, td, vctx, mi_row, mi_col, subsize, 0);
2668
0
        encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, vctx);
2669
0
        pc_tree->vertical[bsize > BLOCK_8X8].skip_ref_frame_mask = 0;
2670
0
        rd_pick_sb_modes(
2671
0
            cpi, tile_data, x, mi_row, mi_col + (mi_step >> 1), &tmp_rdc,
2672
0
            subsize, &pc_tree->vertical[bsize > BLOCK_8X8], INT_MAX, INT64_MAX);
2673
0
        if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2674
0
          vp9_rd_cost_reset(&last_part_rdc);
2675
0
          break;
2676
0
        }
2677
0
        last_part_rdc.rate += tmp_rdc.rate;
2678
0
        last_part_rdc.dist += tmp_rdc.dist;
2679
0
        last_part_rdc.rdcost += tmp_rdc.rdcost;
2680
0
      }
2681
0
      break;
2682
0
    default:
2683
0
      assert(partition == PARTITION_SPLIT);
2684
0
      if (bsize == BLOCK_8X8) {
2685
0
        rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &last_part_rdc,
2686
0
                         subsize, pc_tree->u.leaf_split[0], INT_MAX, INT64_MAX);
2687
0
        break;
2688
0
      }
2689
0
      last_part_rdc.rate = 0;
2690
0
      last_part_rdc.dist = 0;
2691
0
      last_part_rdc.rdcost = 0;
2692
0
      for (i = 0; i < 4; i++) {
2693
0
        int x_idx = (i & 1) * (mi_step >> 1);
2694
0
        int y_idx = (i >> 1) * (mi_step >> 1);
2695
0
        int jj = i >> 1, ii = i & 0x01;
2696
0
        RD_COST tmp_rdc;
2697
0
        if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2698
0
          continue;
2699
2700
0
        vp9_rd_cost_init(&tmp_rdc);
2701
0
        rd_use_partition(cpi, td, tile_data, mi_8x8 + jj * bss * mis + ii * bss,
2702
0
                         tp, mi_row + y_idx, mi_col + x_idx, subsize,
2703
0
                         &tmp_rdc.rate, &tmp_rdc.dist, i != 3,
2704
0
                         pc_tree->u.split[i]);
2705
0
        if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2706
0
          vp9_rd_cost_reset(&last_part_rdc);
2707
0
          break;
2708
0
        }
2709
0
        last_part_rdc.rate += tmp_rdc.rate;
2710
0
        last_part_rdc.dist += tmp_rdc.dist;
2711
0
      }
2712
0
      break;
2713
0
  }
2714
2715
0
  pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2716
0
  if (last_part_rdc.rate < INT_MAX) {
2717
0
    last_part_rdc.rate += cpi->partition_cost[pl][partition];
2718
0
    last_part_rdc.rdcost =
2719
0
        RDCOST(x->rdmult, x->rddiv, last_part_rdc.rate, last_part_rdc.dist);
2720
0
  }
2721
2722
0
  if (do_partition_search && cpi->sf.adjust_partitioning_from_last_frame &&
2723
0
      cpi->sf.partition_search_type == SEARCH_PARTITION &&
2724
0
      partition != PARTITION_SPLIT && bsize > BLOCK_8X8 &&
2725
0
      (mi_row + mi_step < cm->mi_rows ||
2726
0
       mi_row + (mi_step >> 1) == cm->mi_rows) &&
2727
0
      (mi_col + mi_step < cm->mi_cols ||
2728
0
       mi_col + (mi_step >> 1) == cm->mi_cols)) {
2729
0
    BLOCK_SIZE split_subsize = get_subsize(bsize, PARTITION_SPLIT);
2730
0
    chosen_rdc.rate = 0;
2731
0
    chosen_rdc.dist = 0;
2732
0
    restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2733
0
    pc_tree->partitioning = PARTITION_SPLIT;
2734
2735
    // Split partition.
2736
0
    for (i = 0; i < 4; i++) {
2737
0
      int x_idx = (i & 1) * (mi_step >> 1);
2738
0
      int y_idx = (i >> 1) * (mi_step >> 1);
2739
0
      RD_COST tmp_rdc;
2740
2741
0
      if ((mi_row + y_idx >= cm->mi_rows) || (mi_col + x_idx >= cm->mi_cols))
2742
0
        continue;
2743
2744
0
      save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2745
0
      pc_tree->u.split[i]->partitioning = PARTITION_NONE;
2746
0
      rd_pick_sb_modes(cpi, tile_data, x, mi_row + y_idx, mi_col + x_idx,
2747
0
                       &tmp_rdc, split_subsize, &pc_tree->u.split[i]->none,
2748
0
                       INT_MAX, INT64_MAX);
2749
2750
0
      restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2751
2752
0
      if (tmp_rdc.rate == INT_MAX || tmp_rdc.dist == INT64_MAX) {
2753
0
        vp9_rd_cost_reset(&chosen_rdc);
2754
0
        break;
2755
0
      }
2756
2757
0
      chosen_rdc.rate += tmp_rdc.rate;
2758
0
      chosen_rdc.dist += tmp_rdc.dist;
2759
2760
0
      if (i != 3)
2761
0
        encode_sb(cpi, td, tile_info, tp, mi_row + y_idx, mi_col + x_idx, 0,
2762
0
                  split_subsize, pc_tree->u.split[i]);
2763
2764
0
      pl = partition_plane_context(xd, mi_row + y_idx, mi_col + x_idx,
2765
0
                                   split_subsize);
2766
0
      chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
2767
0
    }
2768
0
    pl = partition_plane_context(xd, mi_row, mi_col, bsize);
2769
0
    if (chosen_rdc.rate < INT_MAX) {
2770
0
      chosen_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
2771
0
      chosen_rdc.rdcost =
2772
0
          RDCOST(x->rdmult, x->rddiv, chosen_rdc.rate, chosen_rdc.dist);
2773
0
    }
2774
0
  }
2775
2776
  // If last_part is better set the partitioning to that.
2777
0
  if (last_part_rdc.rdcost < chosen_rdc.rdcost) {
2778
0
    mi_8x8[0]->sb_type = bsize;
2779
0
    if (bsize >= BLOCK_8X8) pc_tree->partitioning = partition;
2780
0
    chosen_rdc = last_part_rdc;
2781
0
  }
2782
  // If none was better set the partitioning to that.
2783
0
  if (none_rdc.rdcost < chosen_rdc.rdcost) {
2784
0
    if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
2785
0
    chosen_rdc = none_rdc;
2786
0
  }
2787
2788
0
  restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
2789
2790
  // We must have chosen a partitioning and encoding or we'll fail later on.
2791
  // No other opportunities for success.
2792
0
  if (bsize == BLOCK_64X64)
2793
0
    assert(chosen_rdc.rate < INT_MAX && chosen_rdc.dist < INT64_MAX);
2794
2795
0
  if (do_recon) {
2796
0
    int output_enabled = (bsize == BLOCK_64X64);
2797
0
    encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
2798
0
              pc_tree);
2799
0
  }
2800
2801
0
  *rate = chosen_rdc.rate;
2802
0
  *dist = chosen_rdc.dist;
2803
0
}
2804
2805
static const BLOCK_SIZE min_partition_size[BLOCK_SIZES] = {
2806
  BLOCK_4X4,   BLOCK_4X4,   BLOCK_4X4,  BLOCK_4X4, BLOCK_4X4,
2807
  BLOCK_4X4,   BLOCK_8X8,   BLOCK_8X8,  BLOCK_8X8, BLOCK_16X16,
2808
  BLOCK_16X16, BLOCK_16X16, BLOCK_16X16
2809
};
2810
2811
static const BLOCK_SIZE max_partition_size[BLOCK_SIZES] = {
2812
  BLOCK_8X8,   BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2813
  BLOCK_32X32, BLOCK_32X32, BLOCK_64X64, BLOCK_64X64, BLOCK_64X64,
2814
  BLOCK_64X64, BLOCK_64X64, BLOCK_64X64
2815
};
2816
2817
// Look at all the mode_info entries for blocks that are part of this
2818
// partition and find the min and max values for sb_type.
2819
// At the moment this is designed to work on a 64x64 SB but could be
2820
// adjusted to use a size parameter.
2821
//
2822
// The min and max are assumed to have been initialized prior to calling this
2823
// function so repeat calls can accumulate a min and max of more than one sb64.
2824
static void get_sb_partition_size_range(MACROBLOCKD *xd, MODE_INFO **mi_8x8,
2825
                                        BLOCK_SIZE *min_block_size,
2826
                                        BLOCK_SIZE *max_block_size,
2827
0
                                        int bs_hist[BLOCK_SIZES]) {
2828
0
  int sb_width_in_blocks = MI_BLOCK_SIZE;
2829
0
  int sb_height_in_blocks = MI_BLOCK_SIZE;
2830
0
  int i, j;
2831
0
  int index = 0;
2832
2833
  // Check the sb_type for each block that belongs to this region.
2834
0
  for (i = 0; i < sb_height_in_blocks; ++i) {
2835
0
    for (j = 0; j < sb_width_in_blocks; ++j) {
2836
0
      MODE_INFO *mi = mi_8x8[index + j];
2837
0
      BLOCK_SIZE sb_type = mi ? mi->sb_type : 0;
2838
0
      bs_hist[sb_type]++;
2839
0
      *min_block_size = VPXMIN(*min_block_size, sb_type);
2840
0
      *max_block_size = VPXMAX(*max_block_size, sb_type);
2841
0
    }
2842
0
    index += xd->mi_stride;
2843
0
  }
2844
0
}
2845
2846
// Next square block size less or equal than current block size.
2847
static const BLOCK_SIZE next_square_size[BLOCK_SIZES] = {
2848
  BLOCK_4X4,   BLOCK_4X4,   BLOCK_4X4,   BLOCK_8X8,   BLOCK_8X8,
2849
  BLOCK_8X8,   BLOCK_16X16, BLOCK_16X16, BLOCK_16X16, BLOCK_32X32,
2850
  BLOCK_32X32, BLOCK_32X32, BLOCK_64X64
2851
};
2852
2853
// Look at neighboring blocks and set a min and max partition size based on
2854
// what they chose.
2855
static void rd_auto_partition_range(VP9_COMP *cpi, const TileInfo *const tile,
2856
                                    MACROBLOCKD *const xd, int mi_row,
2857
                                    int mi_col, BLOCK_SIZE *min_block_size,
2858
0
                                    BLOCK_SIZE *max_block_size) {
2859
0
  VP9_COMMON *const cm = &cpi->common;
2860
0
  MODE_INFO **mi = xd->mi;
2861
0
  const int left_in_image = !!xd->left_mi;
2862
0
  const int above_in_image = !!xd->above_mi;
2863
0
  const int row8x8_remaining = tile->mi_row_end - mi_row;
2864
0
  const int col8x8_remaining = tile->mi_col_end - mi_col;
2865
0
  int bh, bw;
2866
0
  BLOCK_SIZE min_size = BLOCK_4X4;
2867
0
  BLOCK_SIZE max_size = BLOCK_64X64;
2868
0
  int bs_hist[BLOCK_SIZES] = { 0 };
2869
2870
  // Trap case where we do not have a prediction.
2871
0
  if (left_in_image || above_in_image || cm->frame_type != KEY_FRAME) {
2872
    // Default "min to max" and "max to min"
2873
0
    min_size = BLOCK_64X64;
2874
0
    max_size = BLOCK_4X4;
2875
2876
    // NOTE: each call to get_sb_partition_size_range() uses the previous
2877
    // passed in values for min and max as a starting point.
2878
    // Find the min and max partition used in previous frame at this location
2879
0
    if (cm->frame_type != KEY_FRAME &&
2880
0
        (cm->width == cm->last_width && cm->height == cm->last_height)) {
2881
0
      MODE_INFO **prev_mi =
2882
0
          &cm->prev_mi_grid_visible[mi_row * xd->mi_stride + mi_col];
2883
0
      get_sb_partition_size_range(xd, prev_mi, &min_size, &max_size, bs_hist);
2884
0
    }
2885
    // Find the min and max partition sizes used in the left SB64
2886
0
    if (left_in_image) {
2887
0
      MODE_INFO **left_sb64_mi = &mi[-MI_BLOCK_SIZE];
2888
0
      get_sb_partition_size_range(xd, left_sb64_mi, &min_size, &max_size,
2889
0
                                  bs_hist);
2890
0
    }
2891
    // Find the min and max partition sizes used in the above SB64.
2892
0
    if (above_in_image) {
2893
0
      MODE_INFO **above_sb64_mi = &mi[-xd->mi_stride * MI_BLOCK_SIZE];
2894
0
      get_sb_partition_size_range(xd, above_sb64_mi, &min_size, &max_size,
2895
0
                                  bs_hist);
2896
0
    }
2897
2898
    // Adjust observed min and max for "relaxed" auto partition case.
2899
0
    if (cpi->sf.auto_min_max_partition_size == RELAXED_NEIGHBORING_MIN_MAX) {
2900
0
      min_size = min_partition_size[min_size];
2901
0
      max_size = max_partition_size[max_size];
2902
0
    }
2903
0
  }
2904
2905
  // Check border cases where max and min from neighbors may not be legal.
2906
0
  max_size = find_partition_size(max_size, row8x8_remaining, col8x8_remaining,
2907
0
                                 &bh, &bw);
2908
  // Test for blocks at the edge of the active image.
2909
  // This may be the actual edge of the image or where there are formatting
2910
  // bars.
2911
0
  if (vp9_active_edge_sb(cpi, mi_row, mi_col)) {
2912
0
    min_size = BLOCK_4X4;
2913
0
  } else {
2914
0
    min_size =
2915
0
        VPXMIN(cpi->sf.rd_auto_partition_min_limit, VPXMIN(min_size, max_size));
2916
0
  }
2917
2918
  // When use_square_partition_only is true, make sure at least one square
2919
  // partition is allowed by selecting the next smaller square size as
2920
  // *min_block_size.
2921
0
  if (cpi->sf.use_square_partition_only &&
2922
0
      next_square_size[max_size] < min_size) {
2923
0
    min_size = next_square_size[max_size];
2924
0
  }
2925
2926
0
  *min_block_size = min_size;
2927
0
  *max_block_size = max_size;
2928
0
}
2929
2930
// TODO(jingning) refactor functions setting partition search range
2931
static void set_partition_range(VP9_COMMON *cm, MACROBLOCKD *xd, int mi_row,
2932
                                int mi_col, BLOCK_SIZE bsize,
2933
0
                                BLOCK_SIZE *min_bs, BLOCK_SIZE *max_bs) {
2934
0
  int mi_width = num_8x8_blocks_wide_lookup[bsize];
2935
0
  int mi_height = num_8x8_blocks_high_lookup[bsize];
2936
0
  int idx, idy;
2937
0
  BLOCK_SIZE bs, min_size, max_size;
2938
2939
0
  min_size = BLOCK_64X64;
2940
0
  max_size = BLOCK_4X4;
2941
2942
0
  if (cm->width != cm->last_width || cm->height != cm->last_height) {
2943
0
    *min_bs = min_size;
2944
0
    *max_bs = max_size;
2945
0
    return;
2946
0
  }
2947
2948
0
  MODE_INFO *mi;
2949
0
  const int idx_str = cm->mi_stride * mi_row + mi_col;
2950
0
  MODE_INFO **prev_mi = &cm->prev_mi_grid_visible[idx_str];
2951
2952
0
  for (idy = 0; idy < mi_height; ++idy) {
2953
0
    for (idx = 0; idx < mi_width; ++idx) {
2954
0
      mi = prev_mi[idy * cm->mi_stride + idx];
2955
0
      bs = mi ? mi->sb_type : bsize;
2956
0
      min_size = VPXMIN(min_size, bs);
2957
0
      max_size = VPXMAX(max_size, bs);
2958
0
    }
2959
0
  }
2960
2961
0
  if (xd->left_mi) {
2962
0
    for (idy = 0; idy < mi_height; ++idy) {
2963
0
      mi = xd->mi[idy * cm->mi_stride - 1];
2964
0
      bs = mi ? mi->sb_type : bsize;
2965
0
      min_size = VPXMIN(min_size, bs);
2966
0
      max_size = VPXMAX(max_size, bs);
2967
0
    }
2968
0
  }
2969
2970
0
  if (xd->above_mi) {
2971
0
    for (idx = 0; idx < mi_width; ++idx) {
2972
0
      mi = xd->mi[idx - cm->mi_stride];
2973
0
      bs = mi ? mi->sb_type : bsize;
2974
0
      min_size = VPXMIN(min_size, bs);
2975
0
      max_size = VPXMAX(max_size, bs);
2976
0
    }
2977
0
  }
2978
2979
0
  if (min_size == max_size) {
2980
0
    min_size = min_partition_size[min_size];
2981
0
    max_size = max_partition_size[max_size];
2982
0
  }
2983
2984
0
  *min_bs = min_size;
2985
0
  *max_bs = max_size;
2986
0
}
2987
#endif  // !CONFIG_REALTIME_ONLY
2988
2989
3.58M
static INLINE void store_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
2990
3.58M
  memcpy(ctx->pred_mv, x->pred_mv, sizeof(x->pred_mv));
2991
3.58M
}
2992
2993
6.28M
static INLINE void load_pred_mv(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx) {
2994
6.28M
  memcpy(x->pred_mv, ctx->pred_mv, sizeof(x->pred_mv));
2995
6.28M
}
2996
2997
// Calculate prediction based on the given input features and neural net config.
2998
// Assume there are no more than NN_MAX_NODES_PER_LAYER nodes in each hidden
2999
// layer.
3000
static void nn_predict(const float *features, const NN_CONFIG *nn_config,
3001
1.07M
                       float *output) {
3002
1.07M
  int num_input_nodes = nn_config->num_inputs;
3003
1.07M
  int buf_index = 0;
3004
1.07M
  float buf[2][NN_MAX_NODES_PER_LAYER];
3005
1.07M
  const float *input_nodes = features;
3006
3007
  // Propagate hidden layers.
3008
1.07M
  const int num_layers = nn_config->num_hidden_layers;
3009
1.07M
  int layer, node, i;
3010
1.07M
  assert(num_layers <= NN_MAX_HIDDEN_LAYERS);
3011
2.15M
  for (layer = 0; layer < num_layers; ++layer) {
3012
1.07M
    const float *weights = nn_config->weights[layer];
3013
1.07M
    const float *bias = nn_config->bias[layer];
3014
1.07M
    float *output_nodes = buf[buf_index];
3015
1.07M
    const int num_output_nodes = nn_config->num_hidden_nodes[layer];
3016
1.07M
    assert(num_output_nodes < NN_MAX_NODES_PER_LAYER);
3017
11.2M
    for (node = 0; node < num_output_nodes; ++node) {
3018
10.1M
      float val = 0.0f;
3019
119M
      for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3020
10.1M
      val += bias[node];
3021
      // ReLU as activation function.
3022
10.1M
      val = VPXMAX(val, 0.0f);
3023
10.1M
      output_nodes[node] = val;
3024
10.1M
      weights += num_input_nodes;
3025
10.1M
    }
3026
1.07M
    num_input_nodes = num_output_nodes;
3027
1.07M
    input_nodes = output_nodes;
3028
1.07M
    buf_index = 1 - buf_index;
3029
1.07M
  }
3030
3031
  // Final output layer.
3032
1.07M
  {
3033
1.07M
    const float *weights = nn_config->weights[num_layers];
3034
2.73M
    for (node = 0; node < nn_config->num_outputs; ++node) {
3035
1.66M
      const float *bias = nn_config->bias[num_layers];
3036
1.66M
      float val = 0.0f;
3037
21.2M
      for (i = 0; i < num_input_nodes; ++i) val += weights[i] * input_nodes[i];
3038
1.66M
      output[node] = val + bias[node];
3039
1.66M
      weights += num_input_nodes;
3040
1.66M
    }
3041
1.07M
  }
3042
1.07M
}
3043
3044
#if !CONFIG_REALTIME_ONLY
3045
0
#define FEATURES 7
3046
// Machine-learning based partition search early termination.
3047
// Return 1 to skip split and rect partitions.
3048
static int ml_pruning_partition(VP9_COMMON *const cm, MACROBLOCKD *const xd,
3049
                                PICK_MODE_CONTEXT *ctx, int mi_row, int mi_col,
3050
0
                                BLOCK_SIZE bsize) {
3051
0
  const int mag_mv =
3052
0
      abs(ctx->mic.mv[0].as_mv.col) + abs(ctx->mic.mv[0].as_mv.row);
3053
0
  const int left_in_image = !!xd->left_mi;
3054
0
  const int above_in_image = !!xd->above_mi;
3055
0
  int above_par = 0;  // above_partitioning
3056
0
  int left_par = 0;   // left_partitioning
3057
0
  int last_par = 0;   // last_partitioning
3058
0
  int offset = 0;
3059
0
  int i;
3060
0
  BLOCK_SIZE context_size;
3061
0
  const NN_CONFIG *nn_config = NULL;
3062
0
  const float *mean, *sd, *linear_weights;
3063
0
  float nn_score, linear_score;
3064
0
  float features[FEATURES];
3065
3066
0
  assert(b_width_log2_lookup[bsize] == b_height_log2_lookup[bsize]);
3067
0
  vpx_clear_system_state();
3068
3069
0
  switch (bsize) {
3070
0
    case BLOCK_64X64:
3071
0
      offset = 0;
3072
0
      nn_config = &vp9_partition_nnconfig_64x64;
3073
0
      break;
3074
0
    case BLOCK_32X32:
3075
0
      offset = 8;
3076
0
      nn_config = &vp9_partition_nnconfig_32x32;
3077
0
      break;
3078
0
    case BLOCK_16X16:
3079
0
      offset = 16;
3080
0
      nn_config = &vp9_partition_nnconfig_16x16;
3081
0
      break;
3082
0
    default: assert(0 && "Unexpected block size."); return 0;
3083
0
  }
3084
3085
0
  if (above_in_image) {
3086
0
    context_size = xd->above_mi->sb_type;
3087
0
    if (context_size < bsize)
3088
0
      above_par = 2;
3089
0
    else if (context_size == bsize)
3090
0
      above_par = 1;
3091
0
  }
3092
3093
0
  if (left_in_image) {
3094
0
    context_size = xd->left_mi->sb_type;
3095
0
    if (context_size < bsize)
3096
0
      left_par = 2;
3097
0
    else if (context_size == bsize)
3098
0
      left_par = 1;
3099
0
  }
3100
3101
0
  if (cm->width == cm->last_width && cm->height == cm->last_height) {
3102
0
    MODE_INFO **prev_mi =
3103
0
        &cm->prev_mi_grid_visible[mi_col + cm->mi_stride * mi_row];
3104
0
    if (prev_mi[0]) {
3105
0
      context_size = prev_mi[0]->sb_type;
3106
0
      if (context_size < bsize)
3107
0
        last_par = 2;
3108
0
      else if (context_size == bsize)
3109
0
        last_par = 1;
3110
0
    }
3111
0
  }
3112
3113
0
  mean = &vp9_partition_feature_mean[offset];
3114
0
  sd = &vp9_partition_feature_std[offset];
3115
0
  features[0] = ((float)ctx->rate - mean[0]) / sd[0];
3116
0
  features[1] = ((float)ctx->dist - mean[1]) / sd[1];
3117
0
  features[2] = ((float)mag_mv / 2 - mean[2]) * sd[2];
3118
0
  features[3] = ((float)(left_par + above_par) / 2 - mean[3]) * sd[3];
3119
0
  features[4] = ((float)ctx->sum_y_eobs - mean[4]) / sd[4];
3120
0
  features[5] = ((float)cm->base_qindex - mean[5]) * sd[5];
3121
0
  features[6] = ((float)last_par - mean[6]) * sd[6];
3122
3123
  // Predict using linear model.
3124
0
  linear_weights = &vp9_partition_linear_weights[offset];
3125
0
  linear_score = linear_weights[FEATURES];
3126
0
  for (i = 0; i < FEATURES; ++i)
3127
0
    linear_score += linear_weights[i] * features[i];
3128
0
  if (linear_score > 0.1f) return 0;
3129
3130
  // Predict using neural net model.
3131
0
  nn_predict(features, nn_config, &nn_score);
3132
3133
0
  if (linear_score < -0.0f && nn_score < 0.1f) return 1;
3134
0
  if (nn_score < -0.0f && linear_score < 0.1f) return 1;
3135
0
  return 0;
3136
0
}
3137
#undef FEATURES
3138
3139
399k
#define FEATURES 4
3140
// ML-based partition search breakout.
3141
static int ml_predict_breakout(VP9_COMP *const cpi, BLOCK_SIZE bsize,
3142
                               const MACROBLOCK *const x,
3143
66.6k
                               const RD_COST *const rd_cost) {
3144
66.6k
  DECLARE_ALIGNED(16, static const uint8_t, vp9_64_zeros[64]) = { 0 };
3145
66.6k
  const VP9_COMMON *const cm = &cpi->common;
3146
66.6k
  float features[FEATURES];
3147
66.6k
  const float *linear_weights = NULL;  // Linear model weights.
3148
66.6k
  float linear_score = 0.0f;
3149
66.6k
  const int qindex = cm->base_qindex;
3150
66.6k
  const int q_ctx = qindex >= 200 ? 0 : (qindex >= 150 ? 1 : 2);
3151
66.6k
  const int is_720p_or_larger = VPXMIN(cm->width, cm->height) >= 720;
3152
66.6k
  const int resolution_ctx = is_720p_or_larger ? 1 : 0;
3153
3154
66.6k
  switch (bsize) {
3155
448
    case BLOCK_64X64:
3156
448
      linear_weights = vp9_partition_breakout_weights_64[resolution_ctx][q_ctx];
3157
448
      break;
3158
1.98k
    case BLOCK_32X32:
3159
1.98k
      linear_weights = vp9_partition_breakout_weights_32[resolution_ctx][q_ctx];
3160
1.98k
      break;
3161
10.1k
    case BLOCK_16X16:
3162
10.1k
      linear_weights = vp9_partition_breakout_weights_16[resolution_ctx][q_ctx];
3163
10.1k
      break;
3164
54.1k
    case BLOCK_8X8:
3165
54.1k
      linear_weights = vp9_partition_breakout_weights_8[resolution_ctx][q_ctx];
3166
54.1k
      break;
3167
0
    default: assert(0 && "Unexpected block size."); return 0;
3168
66.6k
  }
3169
66.6k
  if (!linear_weights) return 0;
3170
3171
66.6k
  {  // Generate feature values.
3172
66.6k
#if CONFIG_VP9_HIGHBITDEPTH
3173
66.6k
    const int ac_q =
3174
66.6k
        vp9_ac_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3175
#else
3176
    const int ac_q = vp9_ac_quant(qindex, 0, cm->bit_depth);
3177
#endif  // CONFIG_VP9_HIGHBITDEPTH
3178
66.6k
    const int num_pels_log2 = num_pels_log2_lookup[bsize];
3179
66.6k
    int feature_index = 0;
3180
66.6k
    unsigned int var, sse;
3181
66.6k
    float rate_f, dist_f;
3182
3183
66.6k
#if CONFIG_VP9_HIGHBITDEPTH
3184
66.6k
    if (x->e_mbd.cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
3185
1.24k
      var =
3186
1.24k
          vp9_high_get_sby_variance(cpi, &x->plane[0].src, bsize, x->e_mbd.bd);
3187
65.4k
    } else {
3188
65.4k
      var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3189
65.4k
                                  vp9_64_zeros, 0, &sse);
3190
65.4k
    }
3191
#else
3192
    var = cpi->fn_ptr[bsize].vf(x->plane[0].src.buf, x->plane[0].src.stride,
3193
                                vp9_64_zeros, 0, &sse);
3194
#endif
3195
66.6k
    var = var >> num_pels_log2;
3196
3197
66.6k
    vpx_clear_system_state();
3198
3199
66.6k
    rate_f = (float)VPXMIN(rd_cost->rate, INT_MAX);
3200
66.6k
    dist_f = (float)(VPXMIN(rd_cost->dist, INT_MAX) >> num_pels_log2);
3201
66.6k
    rate_f =
3202
66.6k
        ((float)x->rdmult / 128.0f / 512.0f / (float)(1 << num_pels_log2)) *
3203
66.6k
        rate_f;
3204
3205
66.6k
    features[feature_index++] = rate_f;
3206
66.6k
    features[feature_index++] = dist_f;
3207
66.6k
    features[feature_index++] = (float)var;
3208
66.6k
    features[feature_index++] = (float)ac_q;
3209
66.6k
    assert(feature_index == FEATURES);
3210
66.6k
  }
3211
3212
66.6k
  {  // Calculate the output score.
3213
66.6k
    int i;
3214
66.6k
    linear_score = linear_weights[FEATURES];
3215
333k
    for (i = 0; i < FEATURES; ++i)
3216
266k
      linear_score += linear_weights[i] * features[i];
3217
66.6k
  }
3218
3219
66.6k
  return linear_score >= cpi->sf.rd_ml_partition.search_breakout_thresh[q_ctx];
3220
66.6k
}
3221
#undef FEATURES
3222
3223
#define FEATURES 8
3224
1.95M
#define LABELS 4
3225
static void ml_prune_rect_partition(VP9_COMP *const cpi, MACROBLOCK *const x,
3226
                                    BLOCK_SIZE bsize,
3227
                                    const PC_TREE *const pc_tree,
3228
                                    int *allow_horz, int *allow_vert,
3229
504k
                                    int64_t ref_rd) {
3230
504k
  const NN_CONFIG *nn_config = NULL;
3231
504k
  float score[LABELS] = {
3232
504k
    0.0f,
3233
504k
  };
3234
504k
  int thresh = -1;
3235
504k
  int i;
3236
504k
  (void)x;
3237
3238
504k
  if (ref_rd <= 0 || ref_rd > 1000000000) return;
3239
3240
393k
  switch (bsize) {
3241
0
    case BLOCK_8X8: break;
3242
302k
    case BLOCK_16X16:
3243
302k
      nn_config = &vp9_rect_part_nnconfig_16;
3244
302k
      thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[1];
3245
302k
      break;
3246
82.2k
    case BLOCK_32X32:
3247
82.2k
      nn_config = &vp9_rect_part_nnconfig_32;
3248
82.2k
      thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[2];
3249
82.2k
      break;
3250
9.04k
    case BLOCK_64X64:
3251
9.04k
      nn_config = &vp9_rect_part_nnconfig_64;
3252
9.04k
      thresh = cpi->sf.rd_ml_partition.prune_rect_thresh[3];
3253
9.04k
      break;
3254
0
    default: assert(0 && "Unexpected block size."); return;
3255
393k
  }
3256
393k
  if (!nn_config || thresh < 0) return;
3257
3258
  // Feature extraction and model score calculation.
3259
195k
  {
3260
195k
    const VP9_COMMON *const cm = &cpi->common;
3261
195k
#if CONFIG_VP9_HIGHBITDEPTH
3262
195k
    const int dc_q =
3263
195k
        vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (x->e_mbd.bd - 8);
3264
#else
3265
    const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3266
#endif  // CONFIG_VP9_HIGHBITDEPTH
3267
195k
    const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3268
195k
    int feature_index = 0;
3269
195k
    float features[FEATURES];
3270
3271
195k
    features[feature_index++] = logf((float)dc_q + 1.0f);
3272
195k
    features[feature_index++] =
3273
195k
        (float)(pc_tree->partitioning == PARTITION_NONE);
3274
195k
    features[feature_index++] = logf((float)ref_rd / bs / bs + 1.0f);
3275
3276
195k
    {
3277
195k
      const float norm_factor = 1.0f / ((float)ref_rd + 1.0f);
3278
195k
      const int64_t none_rdcost = pc_tree->none.rdcost;
3279
195k
      float rd_ratio = 2.0f;
3280
195k
      if (none_rdcost > 0 && none_rdcost < 1000000000)
3281
145k
        rd_ratio = (float)none_rdcost * norm_factor;
3282
195k
      features[feature_index++] = VPXMIN(rd_ratio, 2.0f);
3283
3284
978k
      for (i = 0; i < 4; ++i) {
3285
782k
        const int64_t this_rd = pc_tree->u.split[i]->none.rdcost;
3286
782k
        const int rd_valid = this_rd > 0 && this_rd < 1000000000;
3287
        // Ratio between sub-block RD and whole block RD.
3288
782k
        features[feature_index++] =
3289
782k
            rd_valid ? (float)this_rd * norm_factor : 1.0f;
3290
782k
      }
3291
195k
    }
3292
3293
195k
    assert(feature_index == FEATURES);
3294
195k
    nn_predict(features, nn_config, score);
3295
195k
  }
3296
3297
  // Make decisions based on the model score.
3298
195k
  {
3299
195k
    int max_score = -1000;
3300
195k
    int horz = 0, vert = 0;
3301
195k
    int int_score[LABELS];
3302
978k
    for (i = 0; i < LABELS; ++i) {
3303
782k
      int_score[i] = (int)(100 * score[i]);
3304
782k
      max_score = VPXMAX(int_score[i], max_score);
3305
782k
    }
3306
195k
    thresh = max_score - thresh;
3307
978k
    for (i = 0; i < LABELS; ++i) {
3308
782k
      if (int_score[i] >= thresh) {
3309
242k
        if ((i >> 0) & 1) horz = 1;
3310
242k
        if ((i >> 1) & 1) vert = 1;
3311
242k
      }
3312
782k
    }
3313
195k
    *allow_horz = *allow_horz && horz;
3314
195k
    *allow_vert = *allow_vert && vert;
3315
195k
  }
3316
195k
}
3317
#undef FEATURES
3318
#undef LABELS
3319
3320
// Perform fast and coarse motion search for the given block. This is a
3321
// pre-processing step for the ML based partition search speedup.
3322
static void simple_motion_search(const VP9_COMP *const cpi, MACROBLOCK *const x,
3323
                                 BLOCK_SIZE bsize, int mi_row, int mi_col,
3324
                                 MV ref_mv, MV_REFERENCE_FRAME ref,
3325
880k
                                 uint8_t *const pred_buf) {
3326
880k
  const VP9_COMMON *const cm = &cpi->common;
3327
880k
  MACROBLOCKD *const xd = &x->e_mbd;
3328
880k
  MODE_INFO *const mi = xd->mi[0];
3329
880k
  YV12_BUFFER_CONFIG *yv12;
3330
880k
  YV12_BUFFER_CONFIG *scaled_ref_frame = vp9_get_scaled_ref_frame(cpi, ref);
3331
880k
  const int step_param = 1;
3332
880k
  const MvLimits tmp_mv_limits = x->mv_limits;
3333
880k
  const SEARCH_METHODS search_method = NSTEP;
3334
880k
  const int sadpb = x->sadperbit16;
3335
880k
  MV ref_mv_full = { ref_mv.row >> 3, ref_mv.col >> 3 };
3336
880k
  MV best_mv = { 0, 0 };
3337
880k
  int cost_list[5];
3338
880k
  struct buf_2d backup_pre[MAX_MB_PLANE] = { { 0, 0 } };
3339
3340
880k
  if (scaled_ref_frame) {
3341
0
    yv12 = scaled_ref_frame;
3342
    // As reported in b/311294795, the reference buffer pointer needs to be
3343
    // saved and restored after the search. Otherwise, it causes problems while
3344
    // the reference frame scaling happens.
3345
0
    for (int i = 0; i < MAX_MB_PLANE; i++) backup_pre[i] = xd->plane[i].pre[0];
3346
880k
  } else {
3347
880k
    yv12 = get_ref_frame_buffer(cpi, ref);
3348
880k
  }
3349
3350
880k
  assert(yv12 != NULL);
3351
880k
  if (!yv12) return;
3352
880k
  vp9_setup_pre_planes(xd, 0, yv12, mi_row, mi_col, NULL);
3353
880k
  mi->ref_frame[0] = ref;
3354
880k
  mi->ref_frame[1] = NO_REF_FRAME;
3355
880k
  mi->sb_type = bsize;
3356
880k
  vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
3357
880k
  vp9_full_pixel_search(cpi, x, bsize, &ref_mv_full, step_param, search_method,
3358
880k
                        sadpb, cond_cost_list(cpi, cost_list), &ref_mv,
3359
880k
                        &best_mv, 0, 0);
3360
880k
  best_mv.row *= 8;
3361
880k
  best_mv.col *= 8;
3362
880k
  x->mv_limits = tmp_mv_limits;
3363
880k
  mi->mv[0].as_mv = best_mv;
3364
3365
  // Restore reference buffer pointer.
3366
880k
  if (scaled_ref_frame) {
3367
0
    for (int i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_pre[i];
3368
0
  }
3369
3370
880k
  set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
3371
880k
  xd->plane[0].dst.buf = pred_buf;
3372
880k
  xd->plane[0].dst.stride = 64;
3373
880k
  vp9_build_inter_predictors_sby(xd, mi_row, mi_col, bsize);
3374
880k
}
3375
3376
// Use a neural net model to prune partition-none and partition-split search.
3377
// Features used: QP; spatial block size contexts; variance of prediction
3378
// residue after simple_motion_search.
3379
#define FEATURES 12
3380
static void ml_predict_var_rd_partitioning(const VP9_COMP *const cpi,
3381
                                           MACROBLOCK *const x,
3382
                                           PC_TREE *const pc_tree,
3383
                                           BLOCK_SIZE bsize, int mi_row,
3384
880k
                                           int mi_col, int *none, int *split) {
3385
880k
  const VP9_COMMON *const cm = &cpi->common;
3386
880k
  const NN_CONFIG *nn_config = NULL;
3387
880k
  const MACROBLOCKD *const xd = &x->e_mbd;
3388
880k
#if CONFIG_VP9_HIGHBITDEPTH
3389
880k
  DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64 * 2]);
3390
880k
  uint8_t *const pred_buf = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
3391
880k
                                ? (CONVERT_TO_BYTEPTR(pred_buffer))
3392
880k
                                : pred_buffer;
3393
#else
3394
  DECLARE_ALIGNED(16, uint8_t, pred_buffer[64 * 64]);
3395
  uint8_t *const pred_buf = pred_buffer;
3396
#endif  // CONFIG_VP9_HIGHBITDEPTH
3397
880k
  const int speed = cpi->oxcf.speed;
3398
880k
  float thresh = 0.0f;
3399
3400
880k
  switch (bsize) {
3401
10.3k
    case BLOCK_64X64:
3402
10.3k
      nn_config = &vp9_part_split_nnconfig_64;
3403
10.3k
      thresh = speed > 0 ? 2.8f : 3.0f;
3404
10.3k
      break;
3405
42.1k
    case BLOCK_32X32:
3406
42.1k
      nn_config = &vp9_part_split_nnconfig_32;
3407
42.1k
      thresh = speed > 0 ? 3.5f : 3.0f;
3408
42.1k
      break;
3409
169k
    case BLOCK_16X16:
3410
169k
      nn_config = &vp9_part_split_nnconfig_16;
3411
169k
      thresh = speed > 0 ? 3.8f : 4.0f;
3412
169k
      break;
3413
658k
    case BLOCK_8X8:
3414
658k
      nn_config = &vp9_part_split_nnconfig_8;
3415
658k
      if (cm->width >= 720 && cm->height >= 720)
3416
0
        thresh = speed > 0 ? 2.5f : 2.0f;
3417
658k
      else
3418
658k
        thresh = speed > 0 ? 3.8f : 2.0f;
3419
658k
      break;
3420
0
    default: assert(0 && "Unexpected block size."); return;
3421
880k
  }
3422
3423
880k
  if (!nn_config) return;
3424
3425
  // Do a simple single motion search to find a prediction for current block.
3426
  // The variance of the residue will be used as input features.
3427
880k
  {
3428
880k
    MV ref_mv;
3429
880k
    const MV_REFERENCE_FRAME ref =
3430
880k
        cpi->rc.is_src_frame_alt_ref ? ALTREF_FRAME : LAST_FRAME;
3431
    // If bsize is 64x64, use zero MV as reference; otherwise, use MV result
3432
    // of previous(larger) block as reference.
3433
880k
    if (bsize == BLOCK_64X64)
3434
10.3k
      ref_mv.row = ref_mv.col = 0;
3435
869k
    else
3436
869k
      ref_mv = pc_tree->mv;
3437
880k
    vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
3438
880k
    simple_motion_search(cpi, x, bsize, mi_row, mi_col, ref_mv, ref, pred_buf);
3439
880k
    pc_tree->mv = x->e_mbd.mi[0]->mv[0].as_mv;
3440
880k
  }
3441
3442
880k
  vpx_clear_system_state();
3443
3444
880k
  {
3445
880k
    float features[FEATURES] = { 0.0f };
3446
880k
#if CONFIG_VP9_HIGHBITDEPTH
3447
880k
    const int dc_q =
3448
880k
        vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) >> (xd->bd - 8);
3449
#else
3450
    const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
3451
#endif  // CONFIG_VP9_HIGHBITDEPTH
3452
880k
    int feature_idx = 0;
3453
880k
    float score;
3454
3455
    // Generate model input features.
3456
880k
    features[feature_idx++] = logf((float)dc_q + 1.0f);
3457
3458
    // Get the variance of the residue as input features.
3459
880k
    {
3460
880k
      const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
3461
880k
      const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
3462
880k
      const uint8_t *pred = pred_buf;
3463
880k
      const uint8_t *src = x->plane[0].src.buf;
3464
880k
      const int src_stride = x->plane[0].src.stride;
3465
880k
      const int pred_stride = 64;
3466
880k
      unsigned int sse;
3467
      // Variance of whole block.
3468
880k
      const unsigned int var =
3469
880k
          cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
3470
880k
      const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
3471
880k
      const int has_above = !!xd->above_mi;
3472
880k
      const int has_left = !!xd->left_mi;
3473
880k
      const BLOCK_SIZE above_bsize = has_above ? xd->above_mi->sb_type : bsize;
3474
880k
      const BLOCK_SIZE left_bsize = has_left ? xd->left_mi->sb_type : bsize;
3475
880k
      int i;
3476
3477
880k
      features[feature_idx++] = (float)has_above;
3478
880k
      features[feature_idx++] = (float)b_width_log2_lookup[above_bsize];
3479
880k
      features[feature_idx++] = (float)b_height_log2_lookup[above_bsize];
3480
880k
      features[feature_idx++] = (float)has_left;
3481
880k
      features[feature_idx++] = (float)b_width_log2_lookup[left_bsize];
3482
880k
      features[feature_idx++] = (float)b_height_log2_lookup[left_bsize];
3483
880k
      features[feature_idx++] = logf((float)var + 1.0f);
3484
4.40M
      for (i = 0; i < 4; ++i) {
3485
3.52M
        const int x_idx = (i & 1) * bs / 2;
3486
3.52M
        const int y_idx = (i >> 1) * bs / 2;
3487
3.52M
        const int src_offset = y_idx * src_stride + x_idx;
3488
3.52M
        const int pred_offset = y_idx * pred_stride + x_idx;
3489
        // Variance of quarter block.
3490
3.52M
        const unsigned int sub_var =
3491
3.52M
            cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
3492
3.52M
                                    pred + pred_offset, pred_stride, &sse);
3493
3.52M
        const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
3494
3.52M
        features[feature_idx++] = var_ratio;
3495
3.52M
      }
3496
880k
    }
3497
880k
    assert(feature_idx == FEATURES);
3498
3499
    // Feed the features into the model to get the confidence score.
3500
880k
    nn_predict(features, nn_config, &score);
3501
3502
    // Higher score means that the model has higher confidence that the split
3503
    // partition is better than the non-split partition. So if the score is
3504
    // high enough, we skip the none-split partition search; if the score is
3505
    // low enough, we skip the split partition search.
3506
880k
    if (score > thresh) *none = 0;
3507
880k
    if (score < -thresh) *split = 0;
3508
880k
  }
3509
880k
}
3510
#undef FEATURES
3511
#endif  // !CONFIG_REALTIME_ONLY
3512
3513
0
static double log_wiener_var(int64_t wiener_variance) {
3514
0
  return log(1.0 + wiener_variance) / log(2.0);
3515
0
}
3516
3517
0
static void build_kmeans_segmentation(VP9_COMP *cpi) {
3518
0
  VP9_COMMON *cm = &cpi->common;
3519
0
  BLOCK_SIZE bsize = BLOCK_64X64;
3520
0
  KMEANS_DATA *kmeans_data;
3521
3522
0
  vp9_disable_segmentation(&cm->seg);
3523
0
  if (cm->show_frame) {
3524
0
    int mi_row, mi_col;
3525
0
    cpi->kmeans_data_size = 0;
3526
0
    cpi->kmeans_ctr_num = 8;
3527
3528
0
    for (mi_row = 0; mi_row < cm->mi_rows; mi_row += MI_BLOCK_SIZE) {
3529
0
      for (mi_col = 0; mi_col < cm->mi_cols; mi_col += MI_BLOCK_SIZE) {
3530
0
        int mb_row_start = mi_row >> 1;
3531
0
        int mb_col_start = mi_col >> 1;
3532
0
        int mb_row_end = VPXMIN(
3533
0
            (mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3534
0
        int mb_col_end = VPXMIN(
3535
0
            (mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3536
0
        int row, col;
3537
0
        int64_t wiener_variance = 0;
3538
3539
0
        for (row = mb_row_start; row < mb_row_end; ++row)
3540
0
          for (col = mb_col_start; col < mb_col_end; ++col)
3541
0
            wiener_variance += cpi->mb_wiener_variance[row * cm->mb_cols + col];
3542
3543
0
        wiener_variance /=
3544
0
            (mb_row_end - mb_row_start) * (mb_col_end - mb_col_start);
3545
3546
0
#if CONFIG_MULTITHREAD
3547
0
        pthread_mutex_lock(&cpi->kmeans_mutex);
3548
0
#endif  // CONFIG_MULTITHREAD
3549
3550
0
        kmeans_data = &cpi->kmeans_data_arr[cpi->kmeans_data_size++];
3551
0
        kmeans_data->value = log_wiener_var(wiener_variance);
3552
0
        kmeans_data->pos = mi_row * cpi->kmeans_data_stride + mi_col;
3553
0
#if CONFIG_MULTITHREAD
3554
0
        pthread_mutex_unlock(&cpi->kmeans_mutex);
3555
0
#endif  // CONFIG_MULTITHREAD
3556
0
      }
3557
0
    }
3558
3559
0
    vp9_kmeans(cpi->kmeans_ctr_ls, cpi->kmeans_boundary_ls,
3560
0
               cpi->kmeans_count_ls, cpi->kmeans_ctr_num, cpi->kmeans_data_arr,
3561
0
               cpi->kmeans_data_size);
3562
3563
0
    vp9_perceptual_aq_mode_setup(cpi, &cm->seg);
3564
0
  }
3565
0
}
3566
3567
#if !CONFIG_REALTIME_ONLY
3568
static int wiener_var_segment(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3569
0
                              int mi_col) {
3570
0
  VP9_COMMON *cm = &cpi->common;
3571
0
  int mb_row_start = mi_row >> 1;
3572
0
  int mb_col_start = mi_col >> 1;
3573
0
  int mb_row_end =
3574
0
      VPXMIN((mi_row + num_8x8_blocks_high_lookup[bsize]) >> 1, cm->mb_rows);
3575
0
  int mb_col_end =
3576
0
      VPXMIN((mi_col + num_8x8_blocks_wide_lookup[bsize]) >> 1, cm->mb_cols);
3577
0
  int row, col, idx;
3578
0
  int64_t wiener_variance = 0;
3579
0
  int segment_id;
3580
0
  int8_t seg_hist[MAX_SEGMENTS] = { 0 };
3581
0
  int8_t max_count = 0, max_index = -1;
3582
3583
0
  vpx_clear_system_state();
3584
3585
0
  assert(cpi->norm_wiener_variance > 0);
3586
3587
0
  for (row = mb_row_start; row < mb_row_end; ++row) {
3588
0
    for (col = mb_col_start; col < mb_col_end; ++col) {
3589
0
      wiener_variance = cpi->mb_wiener_variance[row * cm->mb_cols + col];
3590
0
      segment_id =
3591
0
          vp9_get_group_idx(log_wiener_var(wiener_variance),
3592
0
                            cpi->kmeans_boundary_ls, cpi->kmeans_ctr_num);
3593
0
      ++seg_hist[segment_id];
3594
0
    }
3595
0
  }
3596
3597
0
  for (idx = 0; idx < cpi->kmeans_ctr_num; ++idx) {
3598
0
    if (seg_hist[idx] > max_count) {
3599
0
      max_count = seg_hist[idx];
3600
0
      max_index = idx;
3601
0
    }
3602
0
  }
3603
3604
0
  assert(max_index >= 0);
3605
0
  segment_id = max_index;
3606
3607
0
  return segment_id;
3608
0
}
3609
3610
static int get_rdmult_delta(VP9_COMP *cpi, BLOCK_SIZE bsize, int mi_row,
3611
0
                            int mi_col, int orig_rdmult) {
3612
0
  const int gf_group_index = cpi->twopass.gf_group.index;
3613
0
  int64_t intra_cost = 0;
3614
0
  int64_t mc_dep_cost = 0;
3615
0
  int mi_wide = num_8x8_blocks_wide_lookup[bsize];
3616
0
  int mi_high = num_8x8_blocks_high_lookup[bsize];
3617
0
  int row, col;
3618
3619
0
  int dr = 0;
3620
0
  double r0, rk, beta;
3621
3622
0
  TplDepFrame *tpl_frame;
3623
0
  TplDepStats *tpl_stats;
3624
0
  int tpl_stride;
3625
3626
0
  if (gf_group_index >= MAX_ARF_GOP_SIZE) return orig_rdmult;
3627
0
  tpl_frame = &cpi->tpl_stats[gf_group_index];
3628
3629
0
  if (tpl_frame->is_valid == 0) return orig_rdmult;
3630
0
  tpl_stats = tpl_frame->tpl_stats_ptr;
3631
0
  tpl_stride = tpl_frame->stride;
3632
3633
0
  if (cpi->twopass.gf_group.layer_depth[gf_group_index] > 1) return orig_rdmult;
3634
3635
0
  if (cpi->ext_ratectrl.ready &&
3636
0
      (cpi->ext_ratectrl.funcs.rc_type & VPX_RC_QP) != 0 &&
3637
0
      cpi->ext_ratectrl.funcs.get_encodeframe_decision != NULL) {
3638
0
    int sb_size = num_8x8_blocks_wide_lookup[BLOCK_64X64] * MI_SIZE;
3639
0
    int sb_stride = (cpi->common.width + sb_size - 1) / sb_size;
3640
0
    int sby = mi_row / 8;
3641
0
    int sbx = mi_col / 8;
3642
0
    return (int)((cpi->sb_mul_scale[sby * sb_stride + sbx] * orig_rdmult) /
3643
0
                 256);
3644
0
  }
3645
3646
0
  for (row = mi_row; row < mi_row + mi_high; ++row) {
3647
0
    for (col = mi_col; col < mi_col + mi_wide; ++col) {
3648
0
      TplDepStats *this_stats = &tpl_stats[row * tpl_stride + col];
3649
3650
0
      if (row >= cpi->common.mi_rows || col >= cpi->common.mi_cols) continue;
3651
3652
0
      intra_cost += this_stats->intra_cost;
3653
0
      mc_dep_cost += this_stats->mc_dep_cost;
3654
0
    }
3655
0
  }
3656
3657
0
  vpx_clear_system_state();
3658
3659
0
  r0 = cpi->rd.r0;
3660
0
  rk = (double)intra_cost / mc_dep_cost;
3661
0
  beta = r0 / rk;
3662
0
  dr = vp9_get_adaptive_rdmult(cpi, beta);
3663
3664
0
  dr = clamp(dr, orig_rdmult * 1 / 2, orig_rdmult * 3 / 2);
3665
0
  dr = VPXMAX(1, dr);
3666
3667
0
  return dr;
3668
0
}
3669
#endif  // !CONFIG_REALTIME_ONLY
3670
3671
#if !CONFIG_REALTIME_ONLY
3672
// TODO(jingning,jimbankoski,rbultje): properly skip partition types that are
3673
// unlikely to be selected depending on previous rate-distortion optimization
3674
// results, for encoding speed-up.
3675
static int rd_pick_partition(VP9_COMP *cpi, ThreadData *td,
3676
                             TileDataEnc *tile_data, TOKENEXTRA **tp,
3677
                             int mi_row, int mi_col, BLOCK_SIZE bsize,
3678
                             RD_COST *rd_cost, RD_COST best_rdc,
3679
3.58M
                             PC_TREE *pc_tree) {
3680
3.58M
  VP9_COMMON *const cm = &cpi->common;
3681
3.58M
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3682
3.58M
  TileInfo *const tile_info = &tile_data->tile_info;
3683
3.58M
  MACROBLOCK *const x = &td->mb;
3684
3.58M
  MACROBLOCKD *const xd = &x->e_mbd;
3685
3.58M
  const int mi_step = num_8x8_blocks_wide_lookup[bsize] / 2;
3686
3.58M
  ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
3687
3.58M
  PARTITION_CONTEXT sl[8], sa[8];
3688
3.58M
  TOKENEXTRA *tp_orig = *tp;
3689
3.58M
  PICK_MODE_CONTEXT *const ctx = &pc_tree->none;
3690
3.58M
  int i;
3691
3.58M
  const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
3692
3.58M
  BLOCK_SIZE subsize;
3693
3.58M
  RD_COST this_rdc, sum_rdc;
3694
3.58M
  int do_split = bsize >= BLOCK_8X8;
3695
3.58M
  int do_rect = 1;
3696
3.58M
  INTERP_FILTER pred_interp_filter;
3697
3698
  // Override skipping rectangular partition operations for edge blocks
3699
3.58M
  const int force_horz_split = (mi_row + mi_step >= cm->mi_rows);
3700
3.58M
  const int force_vert_split = (mi_col + mi_step >= cm->mi_cols);
3701
3.58M
  const int xss = x->e_mbd.plane[1].subsampling_x;
3702
3.58M
  const int yss = x->e_mbd.plane[1].subsampling_y;
3703
3704
3.58M
  BLOCK_SIZE min_size = x->min_partition_size;
3705
3.58M
  BLOCK_SIZE max_size = x->max_partition_size;
3706
3707
3.58M
  int partition_none_allowed = !force_horz_split && !force_vert_split;
3708
3.58M
  int partition_horz_allowed =
3709
3.58M
      !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
3710
3.58M
  int partition_vert_allowed =
3711
3.58M
      !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
3712
3713
3.58M
  int64_t dist_breakout_thr = cpi->sf.partition_search_breakout_thr.dist;
3714
3.58M
  int rate_breakout_thr = cpi->sf.partition_search_breakout_thr.rate;
3715
3.58M
  int must_split = 0;
3716
3.58M
  int should_encode_sb = 0;
3717
3718
  // Ref frames picked in the [i_th] quarter subblock during square partition
3719
  // RD search. It may be used to prune ref frame selection of rect partitions.
3720
3.58M
  uint8_t ref_frames_used[4] = { 0, 0, 0, 0 };
3721
3722
3.58M
  int partition_mul = x->cb_rdmult;
3723
3724
3.58M
  (void)*tp_orig;
3725
3726
3.58M
  assert(num_8x8_blocks_wide_lookup[bsize] ==
3727
3.58M
         num_8x8_blocks_high_lookup[bsize]);
3728
3729
3.58M
  dist_breakout_thr >>=
3730
3.58M
      8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
3731
3732
3.58M
  rate_breakout_thr *= num_pels_log2_lookup[bsize];
3733
3734
3.58M
  vp9_rd_cost_init(&this_rdc);
3735
3.58M
  vp9_rd_cost_init(&sum_rdc);
3736
3737
3.58M
  set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
3738
3739
3.58M
  if (oxcf->tuning == VP8_TUNE_SSIM) {
3740
0
    set_ssim_rdmult(cpi, x, bsize, mi_row, mi_col, &partition_mul);
3741
0
  }
3742
3.58M
  vp9_rd_cost_update(partition_mul, x->rddiv, &best_rdc);
3743
3744
3.58M
  if (bsize == BLOCK_16X16 && cpi->oxcf.aq_mode != NO_AQ &&
3745
0
      cpi->oxcf.aq_mode != LOOKAHEAD_AQ)
3746
0
    x->mb_energy = vp9_block_energy(cpi, x, bsize);
3747
3748
3.58M
  if (cpi->sf.cb_partition_search && bsize == BLOCK_16X16) {
3749
0
    int cb_partition_search_ctrl =
3750
0
        ((pc_tree->index == 0 || pc_tree->index == 3) +
3751
0
         get_chessboard_index(cm->current_video_frame)) &
3752
0
        0x1;
3753
3754
0
    if (cb_partition_search_ctrl && bsize > min_size && bsize < max_size)
3755
0
      set_partition_range(cm, xd, mi_row, mi_col, bsize, &min_size, &max_size);
3756
0
  }
3757
3758
  // Get sub block energy range
3759
3.58M
  if (bsize >= BLOCK_16X16) {
3760
1.16M
    int min_energy, max_energy;
3761
1.16M
    vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
3762
1.16M
                             &max_energy);
3763
1.16M
    must_split = (min_energy < -3) && (max_energy - min_energy > 2);
3764
1.16M
  }
3765
3766
  // Determine partition types in search according to the speed features.
3767
  // The threshold set here has to be of square block size.
3768
3.58M
  if (cpi->sf.auto_min_max_partition_size) {
3769
0
    partition_none_allowed &= (bsize <= max_size);
3770
0
    partition_horz_allowed &=
3771
0
        ((bsize <= max_size && bsize > min_size) || force_horz_split);
3772
0
    partition_vert_allowed &=
3773
0
        ((bsize <= max_size && bsize > min_size) || force_vert_split);
3774
0
    do_split &= bsize > min_size;
3775
0
  }
3776
3777
3.58M
  if (cpi->sf.use_square_partition_only &&
3778
2.18M
      (bsize > cpi->sf.use_square_only_thresh_high ||
3779
2.15M
       bsize < cpi->sf.use_square_only_thresh_low)) {
3780
743k
    if (cpi->use_svc) {
3781
0
      if (!vp9_active_h_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
3782
0
        partition_horz_allowed &= force_horz_split;
3783
0
      if (!vp9_active_v_edge(cpi, mi_row, mi_step) || x->e_mbd.lossless)
3784
0
        partition_vert_allowed &= force_vert_split;
3785
743k
    } else {
3786
743k
      partition_horz_allowed &= force_horz_split;
3787
743k
      partition_vert_allowed &= force_vert_split;
3788
743k
    }
3789
743k
  }
3790
3791
3.58M
  save_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
3792
3793
3.58M
  pc_tree->partitioning = PARTITION_NONE;
3794
3795
3.58M
  if (cpi->sf.rd_ml_partition.var_pruning && !frame_is_intra_only(cm)) {
3796
957k
    const int do_rd_ml_partition_var_pruning =
3797
957k
        partition_none_allowed && do_split &&
3798
891k
        mi_row + num_8x8_blocks_high_lookup[bsize] <= cm->mi_rows &&
3799
884k
        mi_col + num_8x8_blocks_wide_lookup[bsize] <= cm->mi_cols;
3800
957k
    if (do_rd_ml_partition_var_pruning) {
3801
880k
      ml_predict_var_rd_partitioning(cpi, x, pc_tree, bsize, mi_row, mi_col,
3802
880k
                                     &partition_none_allowed, &do_split);
3803
      // ml_predict_var_rd_partitioning() may pruune out either
3804
      // partition_none_allowed or do_split, but we should keep the
3805
      // partition_none_allowed for 8x8 blocks unless disable_split_mask is
3806
      // off (0).
3807
880k
      if (bsize == BLOCK_8X8 && cpi->sf.disable_split_mask &&
3808
658k
          partition_none_allowed == 0) {
3809
45.8k
        partition_none_allowed = 1;
3810
45.8k
      }
3811
880k
    } else {
3812
77.4k
      vp9_zero(pc_tree->mv);
3813
77.4k
    }
3814
957k
    if (bsize > BLOCK_8X8) {  // Store MV result as reference for subblocks.
3815
1.49M
      for (i = 0; i < 4; ++i) pc_tree->u.split[i]->mv = pc_tree->mv;
3816
299k
    }
3817
957k
  }
3818
3819
  // PARTITION_NONE
3820
3.58M
  if (partition_none_allowed) {
3821
3.22M
    rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize, ctx,
3822
3.22M
                     best_rdc.rate, best_rdc.dist);
3823
3.22M
    ctx->rdcost = this_rdc.rdcost;
3824
3.22M
    if (this_rdc.rate != INT_MAX) {
3825
2.95M
      if (cpi->sf.prune_ref_frame_for_rect_partitions) {
3826
1.19M
        const int ref1 = ctx->mic.ref_frame[0];
3827
1.19M
        const int ref2 = ctx->mic.ref_frame[1];
3828
5.96M
        for (i = 0; i < 4; ++i) {
3829
4.77M
          ref_frames_used[i] |= (1 << ref1);
3830
4.77M
          if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
3831
4.77M
        }
3832
1.19M
      }
3833
2.95M
      if (bsize >= BLOCK_8X8) {
3834
2.95M
        this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
3835
2.95M
        vp9_rd_cost_update(partition_mul, x->rddiv, &this_rdc);
3836
2.95M
      }
3837
3838
2.95M
      if (this_rdc.rdcost < best_rdc.rdcost) {
3839
2.90M
        MODE_INFO *mi = xd->mi[0];
3840
3841
2.90M
        best_rdc = this_rdc;
3842
2.90M
        should_encode_sb = 1;
3843
2.90M
        if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
3844
3845
2.90M
        if (cpi->sf.rd_ml_partition.search_early_termination) {
3846
          // Currently, the machine-learning based partition search early
3847
          // termination is only used while bsize is 16x16, 32x32 or 64x64,
3848
          // VPXMIN(cm->width, cm->height) >= 480, and speed = 0.
3849
0
          if (!x->e_mbd.lossless &&
3850
0
              !segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP) &&
3851
0
              ctx->mic.mode >= INTRA_MODES && bsize >= BLOCK_16X16) {
3852
0
            if (ml_pruning_partition(cm, xd, ctx, mi_row, mi_col, bsize)) {
3853
0
              do_split = 0;
3854
0
              do_rect = 0;
3855
0
            }
3856
0
          }
3857
0
        }
3858
3859
2.90M
        if ((do_split || do_rect) && !x->e_mbd.lossless && ctx->skippable) {
3860
235k
          const int use_ml_based_breakout =
3861
235k
              cpi->sf.rd_ml_partition.search_breakout && cm->base_qindex >= 100;
3862
235k
          if (use_ml_based_breakout) {
3863
66.6k
            if (ml_predict_breakout(cpi, bsize, x, &this_rdc)) {
3864
21.5k
              do_split = 0;
3865
21.5k
              do_rect = 0;
3866
21.5k
            }
3867
168k
          } else {
3868
168k
            if (!cpi->sf.rd_ml_partition.search_early_termination) {
3869
168k
              if ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
3870
93.5k
                  (best_rdc.dist < dist_breakout_thr &&
3871
75.3k
                   best_rdc.rate < rate_breakout_thr)) {
3872
75.3k
                do_split = 0;
3873
75.3k
                do_rect = 0;
3874
75.3k
              }
3875
168k
            }
3876
168k
          }
3877
235k
        }
3878
2.90M
      }
3879
2.95M
    }
3880
3.22M
    restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
3881
3.22M
  } else {
3882
365k
    vp9_zero(ctx->pred_mv);
3883
365k
    ctx->mic.interp_filter = EIGHTTAP;
3884
365k
  }
3885
3886
  // store estimated motion vector
3887
3.58M
  store_pred_mv(x, ctx);
3888
3889
  // If the interp_filter is marked as SWITCHABLE_FILTERS, it was for an
3890
  // intra block and used for context purposes.
3891
3.58M
  if (ctx->mic.interp_filter == SWITCHABLE_FILTERS) {
3892
2.28M
    pred_interp_filter = EIGHTTAP;
3893
2.28M
  } else {
3894
1.30M
    pred_interp_filter = ctx->mic.interp_filter;
3895
1.30M
  }
3896
3897
  // PARTITION_SPLIT
3898
  // TODO(jingning): use the motion vectors given by the above search as
3899
  // the starting point of motion search in the following partition type check.
3900
3.58M
  pc_tree->u.split[0]->none.rdcost = 0;
3901
3.58M
  pc_tree->u.split[1]->none.rdcost = 0;
3902
3.58M
  pc_tree->u.split[2]->none.rdcost = 0;
3903
3.58M
  pc_tree->u.split[3]->none.rdcost = 0;
3904
3.58M
  if (do_split || must_split) {
3905
3.37M
    subsize = get_subsize(bsize, PARTITION_SPLIT);
3906
3.37M
    load_pred_mv(x, ctx);
3907
3.37M
    if (bsize == BLOCK_8X8) {
3908
2.24M
      i = 4;
3909
2.24M
      if (cpi->sf.adaptive_pred_interp_filter && partition_none_allowed)
3910
2.24M
        pc_tree->u.leaf_split[0]->pred_interp_filter = pred_interp_filter;
3911
2.24M
      rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
3912
2.24M
                       pc_tree->u.leaf_split[0], best_rdc.rate, best_rdc.dist);
3913
2.24M
      if (sum_rdc.rate == INT_MAX) {
3914
962k
        sum_rdc.rdcost = INT64_MAX;
3915
1.28M
      } else {
3916
1.28M
        if (cpi->sf.prune_ref_frame_for_rect_partitions) {
3917
474k
          const int ref1 = pc_tree->u.leaf_split[0]->mic.ref_frame[0];
3918
474k
          const int ref2 = pc_tree->u.leaf_split[0]->mic.ref_frame[1];
3919
2.37M
          for (i = 0; i < 4; ++i) {
3920
1.89M
            ref_frames_used[i] |= (1 << ref1);
3921
1.89M
            if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
3922
1.89M
          }
3923
474k
        }
3924
1.28M
      }
3925
2.24M
    } else {
3926
5.03M
      for (i = 0; (i < 4) && ((sum_rdc.rdcost < best_rdc.rdcost) || must_split);
3927
4.18M
           ++i) {
3928
4.18M
        const int x_idx = (i & 1) * mi_step;
3929
4.18M
        const int y_idx = (i >> 1) * mi_step;
3930
4.18M
        int found_best_rd = 0;
3931
4.18M
        RD_COST best_rdc_split;
3932
4.18M
        vp9_rd_cost_reset(&best_rdc_split);
3933
3934
4.18M
        if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX) {
3935
          // A must split test here increases the number of sub
3936
          // partitions but hurts metrics results quite a bit,
3937
          // so this extra test is commented out pending
3938
          // further tests on whether it adds much in terms of
3939
          // visual quality.
3940
          // (must_split) ? best_rdc.rate
3941
          //              : best_rdc.rate - sum_rdc.rate,
3942
          // (must_split) ? best_rdc.dist
3943
          //              : best_rdc.dist - sum_rdc.dist,
3944
3.04M
          best_rdc_split.rate = best_rdc.rate - sum_rdc.rate;
3945
3.04M
          best_rdc_split.dist = best_rdc.dist - sum_rdc.dist;
3946
3.04M
        }
3947
3948
4.18M
        if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
3949
724k
          continue;
3950
3951
3.46M
        pc_tree->u.split[i]->index = i;
3952
3.46M
        if (cpi->sf.prune_ref_frame_for_rect_partitions)
3953
1.44M
          pc_tree->u.split[i]->none.rate = INT_MAX;
3954
3.46M
        found_best_rd = rd_pick_partition(
3955
3.46M
            cpi, td, tile_data, tp, mi_row + y_idx, mi_col + x_idx, subsize,
3956
3.46M
            &this_rdc, best_rdc_split, pc_tree->u.split[i]);
3957
3958
3.46M
        if (found_best_rd == 0) {
3959
279k
          sum_rdc.rdcost = INT64_MAX;
3960
279k
          break;
3961
3.18M
        } else {
3962
3.18M
          if (cpi->sf.prune_ref_frame_for_rect_partitions &&
3963
1.32M
              pc_tree->u.split[i]->none.rate != INT_MAX) {
3964
1.16M
            const int ref1 = pc_tree->u.split[i]->none.mic.ref_frame[0];
3965
1.16M
            const int ref2 = pc_tree->u.split[i]->none.mic.ref_frame[1];
3966
1.16M
            ref_frames_used[i] |= (1 << ref1);
3967
1.16M
            if (ref2 > 0) ref_frames_used[i] |= (1 << ref2);
3968
1.16M
          }
3969
3.18M
          sum_rdc.rate += this_rdc.rate;
3970
3.18M
          sum_rdc.dist += this_rdc.dist;
3971
3.18M
          vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
3972
3.18M
        }
3973
3.46M
      }
3974
1.13M
    }
3975
3976
3.37M
    if (((sum_rdc.rdcost < best_rdc.rdcost) || must_split) && i == 4) {
3977
1.94M
      sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
3978
1.94M
      vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
3979
3980
1.94M
      if ((sum_rdc.rdcost < best_rdc.rdcost) ||
3981
1.85M
          (must_split && (sum_rdc.dist < best_rdc.dist))) {
3982
1.85M
        best_rdc = sum_rdc;
3983
1.85M
        should_encode_sb = 1;
3984
1.85M
        pc_tree->partitioning = PARTITION_SPLIT;
3985
3986
        // Rate and distortion based partition search termination clause.
3987
1.85M
        if (!cpi->sf.rd_ml_partition.search_early_termination &&
3988
1.85M
            !x->e_mbd.lossless &&
3989
1.61M
            ((best_rdc.dist < (dist_breakout_thr >> 2)) ||
3990
899k
             (best_rdc.dist < dist_breakout_thr &&
3991
718k
              best_rdc.rate < rate_breakout_thr))) {
3992
718k
          do_rect = 0;
3993
718k
        }
3994
1.85M
      }
3995
1.94M
    } else {
3996
      // skip rectangular partition test when larger block size
3997
      // gives better rd cost
3998
1.43M
      if (cpi->sf.less_rectangular_check &&
3999
1.43M
          (bsize > cpi->sf.use_square_only_thresh_high ||
4000
1.42M
           best_rdc.dist < dist_breakout_thr))
4001
891k
        do_rect &= !partition_none_allowed;
4002
1.43M
    }
4003
3.37M
    restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4004
3.37M
  }
4005
4006
3.58M
  pc_tree->horizontal[0].skip_ref_frame_mask = 0;
4007
3.58M
  pc_tree->horizontal[1].skip_ref_frame_mask = 0;
4008
3.58M
  pc_tree->vertical[0].skip_ref_frame_mask = 0;
4009
3.58M
  pc_tree->vertical[1].skip_ref_frame_mask = 0;
4010
3.58M
  if (cpi->sf.prune_ref_frame_for_rect_partitions) {
4011
1.49M
    uint8_t used_frames;
4012
1.49M
    used_frames = ref_frames_used[0] | ref_frames_used[1];
4013
1.49M
    if (used_frames) {
4014
1.36M
      pc_tree->horizontal[0].skip_ref_frame_mask = ~used_frames & 0xff;
4015
1.36M
    }
4016
1.49M
    used_frames = ref_frames_used[2] | ref_frames_used[3];
4017
1.49M
    if (used_frames) {
4018
1.28M
      pc_tree->horizontal[1].skip_ref_frame_mask = ~used_frames & 0xff;
4019
1.28M
    }
4020
1.49M
    used_frames = ref_frames_used[0] | ref_frames_used[2];
4021
1.49M
    if (used_frames) {
4022
1.36M
      pc_tree->vertical[0].skip_ref_frame_mask = ~used_frames & 0xff;
4023
1.36M
    }
4024
1.49M
    used_frames = ref_frames_used[1] | ref_frames_used[3];
4025
1.49M
    if (used_frames) {
4026
1.31M
      pc_tree->vertical[1].skip_ref_frame_mask = ~used_frames & 0xff;
4027
1.31M
    }
4028
1.49M
  }
4029
4030
3.58M
  {
4031
3.58M
    const int do_ml_rect_partition_pruning =
4032
3.58M
        !frame_is_intra_only(cm) && !force_horz_split && !force_vert_split &&
4033
2.01M
        (partition_horz_allowed || partition_vert_allowed) && bsize > BLOCK_8X8;
4034
3.58M
    if (do_ml_rect_partition_pruning) {
4035
504k
      ml_prune_rect_partition(cpi, x, bsize, pc_tree, &partition_horz_allowed,
4036
504k
                              &partition_vert_allowed, best_rdc.rdcost);
4037
504k
    }
4038
3.58M
  }
4039
4040
  // PARTITION_HORZ
4041
3.58M
  if (partition_horz_allowed &&
4042
2.42M
      (do_rect || vp9_active_h_edge(cpi, mi_row, mi_step))) {
4043
1.48M
    const int part_mode_rate = cpi->partition_cost[pl][PARTITION_HORZ];
4044
1.48M
    subsize = get_subsize(bsize, PARTITION_HORZ);
4045
1.48M
    load_pred_mv(x, ctx);
4046
1.48M
    if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4047
903k
        partition_none_allowed)
4048
903k
      pc_tree->horizontal[0].pred_interp_filter = pred_interp_filter;
4049
1.48M
    rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4050
1.48M
                     &pc_tree->horizontal[0], best_rdc.rate - part_mode_rate,
4051
1.48M
                     best_rdc.dist);
4052
1.48M
    if (sum_rdc.rdcost < INT64_MAX) {
4053
853k
      sum_rdc.rate += part_mode_rate;
4054
853k
      vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4055
853k
    }
4056
4057
1.48M
    if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + mi_step < cm->mi_rows &&
4058
579k
        bsize > BLOCK_8X8) {
4059
356k
      PICK_MODE_CONTEXT *hctx = &pc_tree->horizontal[0];
4060
356k
      update_state(cpi, td, hctx, mi_row, mi_col, subsize, 0);
4061
356k
      encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize, hctx);
4062
356k
      if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4063
0
          partition_none_allowed)
4064
0
        pc_tree->horizontal[1].pred_interp_filter = pred_interp_filter;
4065
356k
      rd_pick_sb_modes(cpi, tile_data, x, mi_row + mi_step, mi_col, &this_rdc,
4066
356k
                       subsize, &pc_tree->horizontal[1],
4067
356k
                       best_rdc.rate - sum_rdc.rate,
4068
356k
                       best_rdc.dist - sum_rdc.dist);
4069
356k
      if (this_rdc.rate == INT_MAX) {
4070
242k
        sum_rdc.rdcost = INT64_MAX;
4071
242k
      } else {
4072
113k
        sum_rdc.rate += this_rdc.rate;
4073
113k
        sum_rdc.dist += this_rdc.dist;
4074
113k
        vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4075
113k
      }
4076
356k
    }
4077
4078
1.48M
    if (sum_rdc.rdcost < best_rdc.rdcost) {
4079
301k
      best_rdc = sum_rdc;
4080
301k
      should_encode_sb = 1;
4081
301k
      pc_tree->partitioning = PARTITION_HORZ;
4082
4083
301k
      if (cpi->sf.less_rectangular_check &&
4084
301k
          bsize > cpi->sf.use_square_only_thresh_high)
4085
3.14k
        do_rect = 0;
4086
301k
    }
4087
1.48M
    restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4088
1.48M
  }
4089
4090
  // PARTITION_VERT
4091
3.58M
  if (partition_vert_allowed &&
4092
2.32M
      (do_rect || vp9_active_v_edge(cpi, mi_col, mi_step))) {
4093
1.41M
    const int part_mode_rate = cpi->partition_cost[pl][PARTITION_VERT];
4094
1.41M
    subsize = get_subsize(bsize, PARTITION_VERT);
4095
1.41M
    load_pred_mv(x, ctx);
4096
1.41M
    if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4097
904k
        partition_none_allowed)
4098
904k
      pc_tree->vertical[0].pred_interp_filter = pred_interp_filter;
4099
1.41M
    rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4100
1.41M
                     &pc_tree->vertical[0], best_rdc.rate - part_mode_rate,
4101
1.41M
                     best_rdc.dist);
4102
1.41M
    if (sum_rdc.rdcost < INT64_MAX) {
4103
754k
      sum_rdc.rate += part_mode_rate;
4104
754k
      vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4105
754k
    }
4106
4107
1.41M
    if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + mi_step < cm->mi_cols &&
4108
481k
        bsize > BLOCK_8X8) {
4109
370k
      update_state(cpi, td, &pc_tree->vertical[0], mi_row, mi_col, subsize, 0);
4110
370k
      encode_superblock(cpi, td, tp, 0, mi_row, mi_col, subsize,
4111
370k
                        &pc_tree->vertical[0]);
4112
370k
      if (cpi->sf.adaptive_pred_interp_filter && bsize == BLOCK_8X8 &&
4113
0
          partition_none_allowed)
4114
0
        pc_tree->vertical[1].pred_interp_filter = pred_interp_filter;
4115
370k
      rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + mi_step, &this_rdc,
4116
370k
                       subsize, &pc_tree->vertical[1],
4117
370k
                       best_rdc.rate - sum_rdc.rate,
4118
370k
                       best_rdc.dist - sum_rdc.dist);
4119
370k
      if (this_rdc.rate == INT_MAX) {
4120
270k
        sum_rdc.rdcost = INT64_MAX;
4121
270k
      } else {
4122
100k
        sum_rdc.rate += this_rdc.rate;
4123
100k
        sum_rdc.dist += this_rdc.dist;
4124
100k
        vp9_rd_cost_update(partition_mul, x->rddiv, &sum_rdc);
4125
100k
      }
4126
370k
    }
4127
4128
1.41M
    if (sum_rdc.rdcost < best_rdc.rdcost) {
4129
156k
      best_rdc = sum_rdc;
4130
156k
      should_encode_sb = 1;
4131
156k
      pc_tree->partitioning = PARTITION_VERT;
4132
156k
    }
4133
1.41M
    restore_context(x, mi_row, mi_col, a, l, sa, sl, bsize);
4134
1.41M
  }
4135
4136
3.58M
  if (bsize == BLOCK_64X64 && best_rdc.rdcost == INT64_MAX) {
4137
0
    vp9_rd_cost_reset(&this_rdc);
4138
0
    rd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, BLOCK_64X64,
4139
0
                     ctx, INT_MAX, INT64_MAX);
4140
0
    ctx->rdcost = this_rdc.rdcost;
4141
0
    vp9_rd_cost_update(partition_mul, x->rddiv, &this_rdc);
4142
0
    if (this_rdc.rdcost < best_rdc.rdcost) {
4143
0
      best_rdc = this_rdc;
4144
0
      should_encode_sb = 1;
4145
0
      pc_tree->partitioning = PARTITION_NONE;
4146
0
    }
4147
0
  }
4148
4149
3.58M
  *rd_cost = best_rdc;
4150
4151
3.58M
  if (should_encode_sb && pc_tree->index != 3) {
4152
2.77M
    int output_enabled = (bsize == BLOCK_64X64);
4153
#if CONFIG_COLLECT_COMPONENT_TIMING
4154
    start_timing(cpi, encode_sb_time);
4155
#endif
4156
2.77M
    encode_sb(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
4157
2.77M
              pc_tree);
4158
#if CONFIG_COLLECT_COMPONENT_TIMING
4159
    end_timing(cpi, encode_sb_time);
4160
#endif
4161
2.77M
  }
4162
4163
3.58M
  if (bsize == BLOCK_64X64) {
4164
127k
    assert(tp_orig < *tp);
4165
127k
    assert(best_rdc.rate < INT_MAX);
4166
127k
    assert(best_rdc.dist < INT64_MAX);
4167
3.46M
  } else {
4168
3.46M
    assert(tp_orig == *tp);
4169
3.46M
  }
4170
4171
3.58M
  return should_encode_sb;
4172
3.58M
}
4173
4174
static void encode_rd_sb_row(VP9_COMP *cpi, ThreadData *td,
4175
                             TileDataEnc *tile_data, int mi_row,
4176
95.2k
                             TOKENEXTRA **tp) {
4177
95.2k
  VP9_COMMON *const cm = &cpi->common;
4178
95.2k
  TileInfo *const tile_info = &tile_data->tile_info;
4179
95.2k
  MACROBLOCK *const x = &td->mb;
4180
95.2k
  MACROBLOCKD *const xd = &x->e_mbd;
4181
95.2k
  SPEED_FEATURES *const sf = &cpi->sf;
4182
95.2k
  const int mi_col_start = tile_info->mi_col_start;
4183
95.2k
  const int mi_col_end = tile_info->mi_col_end;
4184
95.2k
  int mi_col;
4185
95.2k
  const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
4186
95.2k
  const int num_sb_cols =
4187
95.2k
      get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
4188
95.2k
  int sb_col_in_tile;
4189
4190
  // Initialize the left context for the new SB row
4191
95.2k
  memset(&xd->left_context, 0, sizeof(xd->left_context));
4192
95.2k
  memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
4193
4194
  // Code each SB in the row
4195
223k
  for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
4196
127k
       mi_col += MI_BLOCK_SIZE, sb_col_in_tile++) {
4197
127k
    const struct segmentation *const seg = &cm->seg;
4198
127k
    int dummy_rate;
4199
127k
    int64_t dummy_dist;
4200
127k
    RD_COST dummy_rdc;
4201
127k
    int i;
4202
127k
    int seg_skip = 0;
4203
127k
    int orig_rdmult = cpi->rd.RDMULT;
4204
4205
127k
    const int idx_str = cm->mi_stride * mi_row + mi_col;
4206
127k
    MODE_INFO **mi = cm->mi_grid_visible + idx_str;
4207
4208
127k
    vp9_rd_cost_reset(&dummy_rdc);
4209
127k
    (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
4210
127k
                                   sb_col_in_tile);
4211
4212
127k
    if (sf->adaptive_pred_interp_filter) {
4213
8.31M
      for (i = 0; i < 64; ++i) td->leaf_tree[i].pred_interp_filter = SWITCHABLE;
4214
4215
8.31M
      for (i = 0; i < 64; ++i) {
4216
8.19M
        td->pc_tree[i].vertical[0].pred_interp_filter = SWITCHABLE;
4217
8.19M
        td->pc_tree[i].vertical[1].pred_interp_filter = SWITCHABLE;
4218
8.19M
        td->pc_tree[i].horizontal[0].pred_interp_filter = SWITCHABLE;
4219
8.19M
        td->pc_tree[i].horizontal[1].pred_interp_filter = SWITCHABLE;
4220
8.19M
      }
4221
127k
    }
4222
4223
639k
    for (i = 0; i < MAX_REF_FRAMES; ++i) {
4224
511k
      x->pred_mv[i].row = INT16_MAX;
4225
511k
      x->pred_mv[i].col = INT16_MAX;
4226
511k
    }
4227
127k
    td->pc_root->index = 0;
4228
4229
127k
    if (seg->enabled) {
4230
0
      const uint8_t *const map =
4231
0
          seg->update_map ? cpi->segmentation_map : cm->last_frame_seg_map;
4232
0
      int segment_id = get_segment_id(cm, map, BLOCK_64X64, mi_row, mi_col);
4233
0
      seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP);
4234
0
    }
4235
4236
127k
    x->source_variance = UINT_MAX;
4237
4238
127k
    x->cb_rdmult = orig_rdmult;
4239
4240
127k
    if (sf->partition_search_type == FIXED_PARTITION || seg_skip) {
4241
0
      const BLOCK_SIZE bsize =
4242
0
          seg_skip ? BLOCK_64X64 : sf->always_this_block_size;
4243
0
      set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4244
0
      set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
4245
0
      rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4246
0
                       &dummy_rate, &dummy_dist, 1, td->pc_root);
4247
127k
    } else if (sf->partition_search_type == VAR_BASED_PARTITION &&
4248
0
               cm->frame_type != KEY_FRAME) {
4249
0
      choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
4250
0
      rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, BLOCK_64X64,
4251
0
                       &dummy_rate, &dummy_dist, 1, td->pc_root);
4252
127k
    } else {
4253
127k
      if (cpi->twopass.gf_group.index > 0 && cpi->sf.enable_tpl_model) {
4254
0
        int dr =
4255
0
            get_rdmult_delta(cpi, BLOCK_64X64, mi_row, mi_col, orig_rdmult);
4256
0
        x->cb_rdmult = dr;
4257
0
      }
4258
4259
127k
      if (cpi->oxcf.aq_mode == PERCEPTUAL_AQ && cm->show_frame) {
4260
0
        x->segment_id = wiener_var_segment(cpi, BLOCK_64X64, mi_row, mi_col);
4261
0
        x->cb_rdmult = vp9_compute_rd_mult(
4262
0
            cpi, vp9_get_qindex(&cm->seg, x->segment_id, cm->base_qindex));
4263
0
      }
4264
4265
      // If required set upper and lower partition size limits
4266
127k
      if (sf->auto_min_max_partition_size) {
4267
0
        set_offsets(cpi, tile_info, x, mi_row, mi_col, BLOCK_64X64);
4268
0
        rd_auto_partition_range(cpi, tile_info, xd, mi_row, mi_col,
4269
0
                                &x->min_partition_size, &x->max_partition_size);
4270
0
      }
4271
127k
      td->pc_root->none.rdcost = 0;
4272
4273
#if CONFIG_COLLECT_COMPONENT_TIMING
4274
      start_timing(cpi, rd_pick_partition_time);
4275
#endif
4276
127k
      rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, BLOCK_64X64,
4277
127k
                        &dummy_rdc, dummy_rdc, td->pc_root);
4278
#if CONFIG_COLLECT_COMPONENT_TIMING
4279
      end_timing(cpi, rd_pick_partition_time);
4280
#endif
4281
127k
    }
4282
127k
    (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
4283
127k
                                    sb_col_in_tile, num_sb_cols);
4284
127k
  }
4285
95.2k
}
4286
#endif  // !CONFIG_REALTIME_ONLY
4287
4288
74.0k
static void init_encode_frame_mb_context(VP9_COMP *cpi) {
4289
74.0k
  MACROBLOCK *const x = &cpi->td.mb;
4290
74.0k
  VP9_COMMON *const cm = &cpi->common;
4291
74.0k
  MACROBLOCKD *const xd = &x->e_mbd;
4292
74.0k
  const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
4293
4294
  // Copy data over into macro block data structures.
4295
74.0k
  vp9_setup_src_planes(x, cpi->Source, 0, 0);
4296
4297
74.0k
  vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
4298
4299
  // Note: this memset assumes above_context[0], [1] and [2]
4300
  // are allocated as part of the same buffer.
4301
74.0k
  memset(xd->above_context[0], 0,
4302
74.0k
         sizeof(*xd->above_context[0]) * 2 * aligned_mi_cols * MAX_MB_PLANE);
4303
74.0k
  memset(xd->above_seg_context, 0,
4304
74.0k
         sizeof(*xd->above_seg_context) * aligned_mi_cols);
4305
74.0k
}
4306
4307
0
static int check_dual_ref_flags(VP9_COMP *cpi) {
4308
0
  const int ref_flags = cpi->ref_frame_flags;
4309
4310
0
  if (segfeature_active(&cpi->common.seg, 1, SEG_LVL_REF_FRAME)) {
4311
0
    return 0;
4312
0
  } else {
4313
0
    return (!!(ref_flags & VP9_GOLD_FLAG) + !!(ref_flags & VP9_LAST_FLAG) +
4314
0
            !!(ref_flags & VP9_ALT_FLAG)) >= 2;
4315
0
  }
4316
0
}
4317
4318
15.7k
static void reset_skip_tx_size(VP9_COMMON *cm, TX_SIZE max_tx_size) {
4319
15.7k
  int mi_row, mi_col;
4320
15.7k
  const int mis = cm->mi_stride;
4321
15.7k
  MODE_INFO **mi_ptr = cm->mi_grid_visible;
4322
4323
61.3k
  for (mi_row = 0; mi_row < cm->mi_rows; ++mi_row, mi_ptr += mis) {
4324
274k
    for (mi_col = 0; mi_col < cm->mi_cols; ++mi_col) {
4325
228k
      if (mi_ptr[mi_col]->tx_size > max_tx_size)
4326
5.18k
        mi_ptr[mi_col]->tx_size = max_tx_size;
4327
228k
    }
4328
45.5k
  }
4329
15.7k
}
4330
4331
74.0k
static MV_REFERENCE_FRAME get_frame_type(const VP9_COMP *cpi) {
4332
74.0k
  if (frame_is_intra_only(&cpi->common))
4333
15.7k
    return INTRA_FRAME;
4334
58.2k
  else if (cpi->rc.is_src_frame_alt_ref && cpi->refresh_golden_frame)
4335
0
    return ALTREF_FRAME;
4336
58.2k
  else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
4337
4.21k
    return GOLDEN_FRAME;
4338
54.0k
  else
4339
54.0k
    return LAST_FRAME;
4340
74.0k
}
4341
4342
74.0k
static TX_MODE select_tx_mode(const VP9_COMP *cpi, MACROBLOCKD *const xd) {
4343
74.0k
  if (xd->lossless) return ONLY_4X4;
4344
59.3k
  if (cpi->common.frame_type == KEY_FRAME && cpi->sf.use_nonrd_pick_mode)
4345
0
    return ALLOW_16X16;
4346
59.3k
  if (cpi->sf.tx_size_search_method == USE_LARGESTALL)
4347
25.9k
    return ALLOW_32X32;
4348
33.4k
  else if (cpi->sf.tx_size_search_method == USE_FULL_RD ||
4349
0
           cpi->sf.tx_size_search_method == USE_TX_8X8)
4350
33.4k
    return TX_MODE_SELECT;
4351
0
  else
4352
0
    return cpi->common.tx_mode;
4353
59.3k
}
4354
4355
static void hybrid_intra_mode_search(VP9_COMP *cpi, MACROBLOCK *const x,
4356
                                     RD_COST *rd_cost, BLOCK_SIZE bsize,
4357
0
                                     PICK_MODE_CONTEXT *ctx) {
4358
0
  if (!cpi->sf.nonrd_keyframe && bsize < BLOCK_16X16)
4359
0
    vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4360
0
  else
4361
0
    vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4362
0
}
4363
4364
static void hybrid_search_svc_baseiskey(VP9_COMP *cpi, MACROBLOCK *const x,
4365
                                        RD_COST *rd_cost, BLOCK_SIZE bsize,
4366
                                        PICK_MODE_CONTEXT *ctx,
4367
                                        TileDataEnc *tile_data, int mi_row,
4368
0
                                        int mi_col) {
4369
0
  if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4370
0
    vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4371
0
  } else {
4372
0
    if (cpi->svc.disable_inter_layer_pred == INTER_LAYER_PRED_OFF)
4373
0
      vp9_pick_intra_mode(cpi, x, rd_cost, bsize, ctx);
4374
0
    else if (bsize >= BLOCK_8X8)
4375
0
      vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4376
0
                          ctx);
4377
0
    else
4378
0
      vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4379
0
  }
4380
0
}
4381
4382
static void hybrid_search_scene_change(VP9_COMP *cpi, MACROBLOCK *const x,
4383
                                       RD_COST *rd_cost, BLOCK_SIZE bsize,
4384
                                       PICK_MODE_CONTEXT *ctx,
4385
                                       TileDataEnc *tile_data, int mi_row,
4386
0
                                       int mi_col) {
4387
0
  if (!cpi->sf.nonrd_keyframe && bsize <= BLOCK_8X8) {
4388
0
    vp9_rd_pick_intra_mode_sb(cpi, x, rd_cost, bsize, ctx, INT64_MAX);
4389
0
  } else {
4390
0
    vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize, ctx);
4391
0
  }
4392
0
}
4393
4394
static void nonrd_pick_sb_modes(VP9_COMP *cpi, TileDataEnc *tile_data,
4395
                                MACROBLOCK *const x, int mi_row, int mi_col,
4396
                                RD_COST *rd_cost, BLOCK_SIZE bsize,
4397
0
                                PICK_MODE_CONTEXT *ctx) {
4398
0
  VP9_COMMON *const cm = &cpi->common;
4399
0
  TileInfo *const tile_info = &tile_data->tile_info;
4400
0
  MACROBLOCKD *const xd = &x->e_mbd;
4401
0
  MODE_INFO *mi;
4402
0
  ENTROPY_CONTEXT l[16 * MAX_MB_PLANE], a[16 * MAX_MB_PLANE];
4403
0
  BLOCK_SIZE bs = VPXMAX(bsize, BLOCK_8X8);  // processing unit block size
4404
0
  const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bs];
4405
0
  const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bs];
4406
0
  int plane;
4407
4408
0
  set_offsets(cpi, tile_info, x, mi_row, mi_col, bsize);
4409
4410
0
  set_segment_index(cpi, x, mi_row, mi_col, bsize, 0);
4411
4412
0
  x->skip_recode = 0;
4413
4414
0
  mi = xd->mi[0];
4415
0
  mi->sb_type = bsize;
4416
4417
0
  for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4418
0
    struct macroblockd_plane *pd = &xd->plane[plane];
4419
0
    memcpy(a + num_4x4_blocks_wide * plane, pd->above_context,
4420
0
           (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4421
0
    memcpy(l + num_4x4_blocks_high * plane, pd->left_context,
4422
0
           (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4423
0
  }
4424
4425
0
  if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled)
4426
0
    if (cyclic_refresh_segment_id_boosted(mi->segment_id))
4427
0
      x->rdmult = vp9_cyclic_refresh_get_rdmult(cpi->cyclic_refresh);
4428
4429
0
  if (frame_is_intra_only(cm))
4430
0
    hybrid_intra_mode_search(cpi, x, rd_cost, bsize, ctx);
4431
0
  else if (cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame)
4432
0
    hybrid_search_svc_baseiskey(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4433
0
                                mi_col);
4434
0
  else if (segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP))
4435
0
    set_mode_info_seg_skip(x, cm->tx_mode, cm->interp_filter, rd_cost, bsize);
4436
0
  else if (bsize >= BLOCK_8X8) {
4437
0
    if (cpi->rc.hybrid_intra_scene_change)
4438
0
      hybrid_search_scene_change(cpi, x, rd_cost, bsize, ctx, tile_data, mi_row,
4439
0
                                 mi_col);
4440
0
    else
4441
0
      vp9_pick_inter_mode(cpi, x, tile_data, mi_row, mi_col, rd_cost, bsize,
4442
0
                          ctx);
4443
0
  } else {
4444
0
    vp9_pick_inter_mode_sub8x8(cpi, x, mi_row, mi_col, rd_cost, bsize, ctx);
4445
0
  }
4446
4447
0
  duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4448
4449
0
  for (plane = 0; plane < MAX_MB_PLANE; ++plane) {
4450
0
    struct macroblockd_plane *pd = &xd->plane[plane];
4451
0
    memcpy(pd->above_context, a + num_4x4_blocks_wide * plane,
4452
0
           (sizeof(a[0]) * num_4x4_blocks_wide) >> pd->subsampling_x);
4453
0
    memcpy(pd->left_context, l + num_4x4_blocks_high * plane,
4454
0
           (sizeof(l[0]) * num_4x4_blocks_high) >> pd->subsampling_y);
4455
0
  }
4456
4457
0
  if (rd_cost->rate == INT_MAX) vp9_rd_cost_reset(rd_cost);
4458
4459
0
  ctx->rate = rd_cost->rate;
4460
0
  ctx->dist = rd_cost->dist;
4461
0
}
4462
4463
static void fill_mode_info_sb(VP9_COMMON *cm, MACROBLOCK *x, int mi_row,
4464
0
                              int mi_col, BLOCK_SIZE bsize, PC_TREE *pc_tree) {
4465
0
  MACROBLOCKD *xd = &x->e_mbd;
4466
0
  int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
4467
0
  PARTITION_TYPE partition = pc_tree->partitioning;
4468
0
  BLOCK_SIZE subsize = get_subsize(bsize, partition);
4469
4470
0
  assert(bsize >= BLOCK_8X8);
4471
4472
0
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
4473
4474
0
  switch (partition) {
4475
0
    case PARTITION_NONE:
4476
0
      set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4477
0
      *(xd->mi[0]) = pc_tree->none.mic;
4478
0
      *(x->mbmi_ext) = pc_tree->none.mbmi_ext;
4479
0
      duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, bsize);
4480
0
      break;
4481
0
    case PARTITION_VERT:
4482
0
      set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4483
0
      *(xd->mi[0]) = pc_tree->vertical[0].mic;
4484
0
      *(x->mbmi_ext) = pc_tree->vertical[0].mbmi_ext;
4485
0
      duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4486
4487
0
      if (mi_col + hbs < cm->mi_cols) {
4488
0
        set_mode_info_offsets(cm, x, xd, mi_row, mi_col + hbs);
4489
0
        *(xd->mi[0]) = pc_tree->vertical[1].mic;
4490
0
        *(x->mbmi_ext) = pc_tree->vertical[1].mbmi_ext;
4491
0
        duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col + hbs, subsize);
4492
0
      }
4493
0
      break;
4494
0
    case PARTITION_HORZ:
4495
0
      set_mode_info_offsets(cm, x, xd, mi_row, mi_col);
4496
0
      *(xd->mi[0]) = pc_tree->horizontal[0].mic;
4497
0
      *(x->mbmi_ext) = pc_tree->horizontal[0].mbmi_ext;
4498
0
      duplicate_mode_info_in_sb(cm, xd, mi_row, mi_col, subsize);
4499
0
      if (mi_row + hbs < cm->mi_rows) {
4500
0
        set_mode_info_offsets(cm, x, xd, mi_row + hbs, mi_col);
4501
0
        *(xd->mi[0]) = pc_tree->horizontal[1].mic;
4502
0
        *(x->mbmi_ext) = pc_tree->horizontal[1].mbmi_ext;
4503
0
        duplicate_mode_info_in_sb(cm, xd, mi_row + hbs, mi_col, subsize);
4504
0
      }
4505
0
      break;
4506
0
    case PARTITION_SPLIT: {
4507
0
      fill_mode_info_sb(cm, x, mi_row, mi_col, subsize, pc_tree->u.split[0]);
4508
0
      fill_mode_info_sb(cm, x, mi_row, mi_col + hbs, subsize,
4509
0
                        pc_tree->u.split[1]);
4510
0
      fill_mode_info_sb(cm, x, mi_row + hbs, mi_col, subsize,
4511
0
                        pc_tree->u.split[2]);
4512
0
      fill_mode_info_sb(cm, x, mi_row + hbs, mi_col + hbs, subsize,
4513
0
                        pc_tree->u.split[3]);
4514
0
      break;
4515
0
    }
4516
0
    default: break;
4517
0
  }
4518
0
}
4519
4520
// Reset the prediction pixel ready flag recursively.
4521
0
static void pred_pixel_ready_reset(PC_TREE *pc_tree, BLOCK_SIZE bsize) {
4522
0
  pc_tree->none.pred_pixel_ready = 0;
4523
0
  pc_tree->horizontal[0].pred_pixel_ready = 0;
4524
0
  pc_tree->horizontal[1].pred_pixel_ready = 0;
4525
0
  pc_tree->vertical[0].pred_pixel_ready = 0;
4526
0
  pc_tree->vertical[1].pred_pixel_ready = 0;
4527
4528
0
  if (bsize > BLOCK_8X8) {
4529
0
    BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4530
0
    int i;
4531
0
    for (i = 0; i < 4; ++i)
4532
0
      pred_pixel_ready_reset(pc_tree->u.split[i], subsize);
4533
0
  }
4534
0
}
4535
4536
#define FEATURES 6
4537
#define LABELS 2
4538
static int ml_predict_var_partitioning(VP9_COMP *cpi, MACROBLOCK *x,
4539
                                       BLOCK_SIZE bsize, int mi_row,
4540
0
                                       int mi_col) {
4541
0
  VP9_COMMON *const cm = &cpi->common;
4542
0
  const NN_CONFIG *nn_config = NULL;
4543
4544
0
  switch (bsize) {
4545
0
    case BLOCK_64X64: nn_config = &vp9_var_part_nnconfig_64; break;
4546
0
    case BLOCK_32X32: nn_config = &vp9_var_part_nnconfig_32; break;
4547
0
    case BLOCK_16X16: nn_config = &vp9_var_part_nnconfig_16; break;
4548
0
    case BLOCK_8X8: break;
4549
0
    default: assert(0 && "Unexpected block size."); return -1;
4550
0
  }
4551
4552
0
  if (!nn_config) return -1;
4553
4554
0
  vpx_clear_system_state();
4555
4556
0
  {
4557
0
    const float thresh = cpi->oxcf.speed <= 5 ? 1.25f : 0.0f;
4558
0
    float features[FEATURES] = { 0.0f };
4559
0
    const int dc_q = vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth);
4560
0
    int feature_idx = 0;
4561
0
    float score[LABELS];
4562
4563
0
    features[feature_idx++] = logf((float)(dc_q * dc_q) / 256.0f + 1.0f);
4564
0
    vp9_setup_src_planes(x, cpi->Source, mi_row, mi_col);
4565
0
    {
4566
0
      const int bs = 4 * num_4x4_blocks_wide_lookup[bsize];
4567
0
      const BLOCK_SIZE subsize = get_subsize(bsize, PARTITION_SPLIT);
4568
0
      const int sb_offset_row = 8 * (mi_row & 7);
4569
0
      const int sb_offset_col = 8 * (mi_col & 7);
4570
0
      const uint8_t *pred = x->est_pred + sb_offset_row * 64 + sb_offset_col;
4571
0
      const uint8_t *src = x->plane[0].src.buf;
4572
0
      const int src_stride = x->plane[0].src.stride;
4573
0
      const int pred_stride = 64;
4574
0
      unsigned int sse;
4575
0
      int i;
4576
      // Variance of whole block.
4577
0
      const unsigned int var =
4578
0
          cpi->fn_ptr[bsize].vf(src, src_stride, pred, pred_stride, &sse);
4579
0
      const float factor = (var == 0) ? 1.0f : (1.0f / (float)var);
4580
4581
0
      features[feature_idx++] = logf((float)var + 1.0f);
4582
0
      for (i = 0; i < 4; ++i) {
4583
0
        const int x_idx = (i & 1) * bs / 2;
4584
0
        const int y_idx = (i >> 1) * bs / 2;
4585
0
        const int src_offset = y_idx * src_stride + x_idx;
4586
0
        const int pred_offset = y_idx * pred_stride + x_idx;
4587
        // Variance of quarter block.
4588
0
        const unsigned int sub_var =
4589
0
            cpi->fn_ptr[subsize].vf(src + src_offset, src_stride,
4590
0
                                    pred + pred_offset, pred_stride, &sse);
4591
0
        const float var_ratio = (var == 0) ? 1.0f : factor * (float)sub_var;
4592
0
        features[feature_idx++] = var_ratio;
4593
0
      }
4594
0
    }
4595
4596
0
    assert(feature_idx == FEATURES);
4597
0
    nn_predict(features, nn_config, score);
4598
0
    if (score[0] > thresh) return PARTITION_SPLIT;
4599
0
    if (score[0] < -thresh) return PARTITION_NONE;
4600
0
    return -1;
4601
0
  }
4602
0
}
4603
#undef FEATURES
4604
#undef LABELS
4605
4606
static void nonrd_pick_partition(VP9_COMP *cpi, ThreadData *td,
4607
                                 TileDataEnc *tile_data, TOKENEXTRA **tp,
4608
                                 int mi_row, int mi_col, BLOCK_SIZE bsize,
4609
                                 RD_COST *rd_cost, int do_recon,
4610
0
                                 int64_t best_rd, PC_TREE *pc_tree) {
4611
0
  const SPEED_FEATURES *const sf = &cpi->sf;
4612
0
  VP9_COMMON *const cm = &cpi->common;
4613
0
  TileInfo *const tile_info = &tile_data->tile_info;
4614
0
  MACROBLOCK *const x = &td->mb;
4615
0
  MACROBLOCKD *const xd = &x->e_mbd;
4616
0
  const int ms = num_8x8_blocks_wide_lookup[bsize] / 2;
4617
0
  TOKENEXTRA *tp_orig = *tp;
4618
0
  PICK_MODE_CONTEXT *ctx = &pc_tree->none;
4619
0
  int i;
4620
0
  BLOCK_SIZE subsize = bsize;
4621
0
  RD_COST this_rdc, sum_rdc, best_rdc;
4622
0
  int do_split = bsize >= BLOCK_8X8;
4623
0
  int do_rect = 1;
4624
  // Override skipping rectangular partition operations for edge blocks
4625
0
  const int force_horz_split = (mi_row + ms >= cm->mi_rows);
4626
0
  const int force_vert_split = (mi_col + ms >= cm->mi_cols);
4627
0
  const int xss = x->e_mbd.plane[1].subsampling_x;
4628
0
  const int yss = x->e_mbd.plane[1].subsampling_y;
4629
4630
0
  int partition_none_allowed = !force_horz_split && !force_vert_split;
4631
0
  int partition_horz_allowed =
4632
0
      !force_vert_split && yss <= xss && bsize >= BLOCK_8X8;
4633
0
  int partition_vert_allowed =
4634
0
      !force_horz_split && xss <= yss && bsize >= BLOCK_8X8;
4635
0
  const int use_ml_based_partitioning =
4636
0
      sf->partition_search_type == ML_BASED_PARTITION;
4637
4638
0
  (void)*tp_orig;
4639
4640
  // Avoid checking for rectangular partitions for speed >= 5.
4641
0
  if (cpi->oxcf.speed >= 5) do_rect = 0;
4642
4643
0
  assert(num_8x8_blocks_wide_lookup[bsize] ==
4644
0
         num_8x8_blocks_high_lookup[bsize]);
4645
4646
0
  vp9_rd_cost_init(&sum_rdc);
4647
0
  vp9_rd_cost_reset(&best_rdc);
4648
0
  best_rdc.rdcost = best_rd;
4649
4650
  // Determine partition types in search according to the speed features.
4651
  // The threshold set here has to be of square block size.
4652
0
  if (sf->auto_min_max_partition_size) {
4653
0
    partition_none_allowed &=
4654
0
        (bsize <= x->max_partition_size && bsize >= x->min_partition_size);
4655
0
    partition_horz_allowed &=
4656
0
        ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4657
0
         force_horz_split);
4658
0
    partition_vert_allowed &=
4659
0
        ((bsize <= x->max_partition_size && bsize > x->min_partition_size) ||
4660
0
         force_vert_split);
4661
0
    do_split &= bsize > x->min_partition_size;
4662
0
  }
4663
0
  if (sf->use_square_partition_only) {
4664
0
    partition_horz_allowed &= force_horz_split;
4665
0
    partition_vert_allowed &= force_vert_split;
4666
0
  }
4667
4668
0
  if (use_ml_based_partitioning) {
4669
0
    if (partition_none_allowed || do_split) do_rect = 0;
4670
0
    if (partition_none_allowed && do_split) {
4671
0
      const int ml_predicted_partition =
4672
0
          ml_predict_var_partitioning(cpi, x, bsize, mi_row, mi_col);
4673
0
      if (ml_predicted_partition == PARTITION_NONE) do_split = 0;
4674
0
      if (ml_predicted_partition == PARTITION_SPLIT) partition_none_allowed = 0;
4675
0
    }
4676
0
  }
4677
4678
0
  if (!partition_none_allowed && !do_split) do_rect = 1;
4679
4680
0
  ctx->pred_pixel_ready =
4681
0
      !(partition_vert_allowed || partition_horz_allowed || do_split);
4682
4683
  // PARTITION_NONE
4684
0
  if (partition_none_allowed) {
4685
0
    nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &this_rdc, bsize,
4686
0
                        ctx);
4687
0
    ctx->mic = *xd->mi[0];
4688
0
    ctx->mbmi_ext = *x->mbmi_ext;
4689
0
    ctx->skip_txfm[0] = x->skip_txfm[0];
4690
0
    ctx->skip = x->skip;
4691
4692
0
    if (this_rdc.rate != INT_MAX) {
4693
0
      const int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4694
0
      this_rdc.rate += cpi->partition_cost[pl][PARTITION_NONE];
4695
0
      this_rdc.rdcost =
4696
0
          RDCOST(x->rdmult, x->rddiv, this_rdc.rate, this_rdc.dist);
4697
0
      if (this_rdc.rdcost < best_rdc.rdcost) {
4698
0
        best_rdc = this_rdc;
4699
0
        if (bsize >= BLOCK_8X8) pc_tree->partitioning = PARTITION_NONE;
4700
4701
0
        if (!use_ml_based_partitioning) {
4702
0
          int64_t dist_breakout_thr = sf->partition_search_breakout_thr.dist;
4703
0
          int64_t rate_breakout_thr = sf->partition_search_breakout_thr.rate;
4704
0
          dist_breakout_thr >>=
4705
0
              8 - (b_width_log2_lookup[bsize] + b_height_log2_lookup[bsize]);
4706
0
          rate_breakout_thr *= num_pels_log2_lookup[bsize];
4707
0
          if (!x->e_mbd.lossless && this_rdc.rate < rate_breakout_thr &&
4708
0
              this_rdc.dist < dist_breakout_thr) {
4709
0
            do_split = 0;
4710
0
            do_rect = 0;
4711
0
          }
4712
0
        }
4713
0
      }
4714
0
    }
4715
0
  }
4716
4717
  // store estimated motion vector
4718
0
  store_pred_mv(x, ctx);
4719
4720
  // PARTITION_SPLIT
4721
0
  if (do_split) {
4722
0
    int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4723
0
    sum_rdc.rate += cpi->partition_cost[pl][PARTITION_SPLIT];
4724
0
    sum_rdc.rdcost = RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4725
0
    subsize = get_subsize(bsize, PARTITION_SPLIT);
4726
0
    for (i = 0; i < 4 && sum_rdc.rdcost < best_rdc.rdcost; ++i) {
4727
0
      const int x_idx = (i & 1) * ms;
4728
0
      const int y_idx = (i >> 1) * ms;
4729
4730
0
      if (mi_row + y_idx >= cm->mi_rows || mi_col + x_idx >= cm->mi_cols)
4731
0
        continue;
4732
0
      load_pred_mv(x, ctx);
4733
0
      nonrd_pick_partition(
4734
0
          cpi, td, tile_data, tp, mi_row + y_idx, mi_col + x_idx, subsize,
4735
0
          &this_rdc, 0, best_rdc.rdcost - sum_rdc.rdcost, pc_tree->u.split[i]);
4736
4737
0
      if (this_rdc.rate == INT_MAX) {
4738
0
        vp9_rd_cost_reset(&sum_rdc);
4739
0
      } else {
4740
0
        sum_rdc.rate += this_rdc.rate;
4741
0
        sum_rdc.dist += this_rdc.dist;
4742
0
        sum_rdc.rdcost += this_rdc.rdcost;
4743
0
      }
4744
0
    }
4745
4746
0
    if (sum_rdc.rdcost < best_rdc.rdcost) {
4747
0
      best_rdc = sum_rdc;
4748
0
      pc_tree->partitioning = PARTITION_SPLIT;
4749
0
    } else {
4750
      // skip rectangular partition test when larger block size
4751
      // gives better rd cost
4752
0
      if (sf->less_rectangular_check) do_rect &= !partition_none_allowed;
4753
0
    }
4754
0
  }
4755
4756
  // PARTITION_HORZ
4757
0
  if (partition_horz_allowed && do_rect) {
4758
0
    subsize = get_subsize(bsize, PARTITION_HORZ);
4759
0
    load_pred_mv(x, ctx);
4760
0
    pc_tree->horizontal[0].pred_pixel_ready = 1;
4761
0
    nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4762
0
                        &pc_tree->horizontal[0]);
4763
4764
0
    pc_tree->horizontal[0].mic = *xd->mi[0];
4765
0
    pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
4766
0
    pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
4767
0
    pc_tree->horizontal[0].skip = x->skip;
4768
4769
0
    if (sum_rdc.rdcost < best_rdc.rdcost && mi_row + ms < cm->mi_rows) {
4770
0
      load_pred_mv(x, ctx);
4771
0
      pc_tree->horizontal[1].pred_pixel_ready = 1;
4772
0
      nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + ms, mi_col, &this_rdc,
4773
0
                          subsize, &pc_tree->horizontal[1]);
4774
4775
0
      pc_tree->horizontal[1].mic = *xd->mi[0];
4776
0
      pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
4777
0
      pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
4778
0
      pc_tree->horizontal[1].skip = x->skip;
4779
4780
0
      if (this_rdc.rate == INT_MAX) {
4781
0
        vp9_rd_cost_reset(&sum_rdc);
4782
0
      } else {
4783
0
        int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4784
0
        this_rdc.rate += cpi->partition_cost[pl][PARTITION_HORZ];
4785
0
        sum_rdc.rate += this_rdc.rate;
4786
0
        sum_rdc.dist += this_rdc.dist;
4787
0
        sum_rdc.rdcost =
4788
0
            RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4789
0
      }
4790
0
    }
4791
4792
0
    if (sum_rdc.rdcost < best_rdc.rdcost) {
4793
0
      best_rdc = sum_rdc;
4794
0
      pc_tree->partitioning = PARTITION_HORZ;
4795
0
    } else {
4796
0
      pred_pixel_ready_reset(pc_tree, bsize);
4797
0
    }
4798
0
  }
4799
4800
  // PARTITION_VERT
4801
0
  if (partition_vert_allowed && do_rect) {
4802
0
    subsize = get_subsize(bsize, PARTITION_VERT);
4803
0
    load_pred_mv(x, ctx);
4804
0
    pc_tree->vertical[0].pred_pixel_ready = 1;
4805
0
    nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, &sum_rdc, subsize,
4806
0
                        &pc_tree->vertical[0]);
4807
0
    pc_tree->vertical[0].mic = *xd->mi[0];
4808
0
    pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
4809
0
    pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
4810
0
    pc_tree->vertical[0].skip = x->skip;
4811
4812
0
    if (sum_rdc.rdcost < best_rdc.rdcost && mi_col + ms < cm->mi_cols) {
4813
0
      load_pred_mv(x, ctx);
4814
0
      pc_tree->vertical[1].pred_pixel_ready = 1;
4815
0
      nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + ms, &this_rdc,
4816
0
                          subsize, &pc_tree->vertical[1]);
4817
0
      pc_tree->vertical[1].mic = *xd->mi[0];
4818
0
      pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
4819
0
      pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
4820
0
      pc_tree->vertical[1].skip = x->skip;
4821
4822
0
      if (this_rdc.rate == INT_MAX) {
4823
0
        vp9_rd_cost_reset(&sum_rdc);
4824
0
      } else {
4825
0
        int pl = partition_plane_context(xd, mi_row, mi_col, bsize);
4826
0
        sum_rdc.rate += cpi->partition_cost[pl][PARTITION_VERT];
4827
0
        sum_rdc.rate += this_rdc.rate;
4828
0
        sum_rdc.dist += this_rdc.dist;
4829
0
        sum_rdc.rdcost =
4830
0
            RDCOST(x->rdmult, x->rddiv, sum_rdc.rate, sum_rdc.dist);
4831
0
      }
4832
0
    }
4833
4834
0
    if (sum_rdc.rdcost < best_rdc.rdcost) {
4835
0
      best_rdc = sum_rdc;
4836
0
      pc_tree->partitioning = PARTITION_VERT;
4837
0
    } else {
4838
0
      pred_pixel_ready_reset(pc_tree, bsize);
4839
0
    }
4840
0
  }
4841
4842
0
  *rd_cost = best_rdc;
4843
4844
0
  if (best_rdc.rate == INT_MAX) {
4845
0
    vp9_rd_cost_reset(rd_cost);
4846
0
    return;
4847
0
  }
4848
4849
  // update mode info array
4850
0
  fill_mode_info_sb(cm, x, mi_row, mi_col, bsize, pc_tree);
4851
4852
0
  if (best_rdc.rate < INT_MAX && best_rdc.dist < INT64_MAX && do_recon) {
4853
0
    int output_enabled = (bsize == BLOCK_64X64);
4854
0
    encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled, bsize,
4855
0
                 pc_tree);
4856
0
  }
4857
4858
0
  if (bsize == BLOCK_64X64 && do_recon) {
4859
0
    assert(tp_orig < *tp);
4860
0
    assert(best_rdc.rate < INT_MAX);
4861
0
    assert(best_rdc.dist < INT64_MAX);
4862
0
  } else {
4863
0
    assert(tp_orig == *tp);
4864
0
  }
4865
0
}
4866
4867
static void nonrd_select_partition(VP9_COMP *cpi, ThreadData *td,
4868
                                   TileDataEnc *tile_data, MODE_INFO **mi,
4869
                                   TOKENEXTRA **tp, int mi_row, int mi_col,
4870
                                   BLOCK_SIZE bsize, int output_enabled,
4871
0
                                   RD_COST *rd_cost, PC_TREE *pc_tree) {
4872
0
  VP9_COMMON *const cm = &cpi->common;
4873
0
  TileInfo *const tile_info = &tile_data->tile_info;
4874
0
  MACROBLOCK *const x = &td->mb;
4875
0
  MACROBLOCKD *const xd = &x->e_mbd;
4876
0
  const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
4877
0
  const int mis = cm->mi_stride;
4878
0
  PARTITION_TYPE partition;
4879
0
  BLOCK_SIZE subsize;
4880
0
  RD_COST this_rdc;
4881
0
  BLOCK_SIZE subsize_ref =
4882
0
      (cpi->sf.adapt_partition_source_sad) ? BLOCK_8X8 : BLOCK_16X16;
4883
4884
0
  vp9_rd_cost_reset(&this_rdc);
4885
0
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
4886
4887
0
  subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
4888
0
  partition = partition_lookup[bsl][subsize];
4889
4890
0
  if (bsize == BLOCK_32X32 && subsize == BLOCK_32X32) {
4891
0
    x->max_partition_size = BLOCK_32X32;
4892
0
    x->min_partition_size = BLOCK_16X16;
4893
0
    nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
4894
0
                         0, INT64_MAX, pc_tree);
4895
0
  } else if (bsize == BLOCK_32X32 && partition != PARTITION_NONE &&
4896
0
             subsize >= subsize_ref) {
4897
0
    x->max_partition_size = BLOCK_32X32;
4898
0
    x->min_partition_size = BLOCK_8X8;
4899
0
    nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
4900
0
                         0, INT64_MAX, pc_tree);
4901
0
  } else if (bsize == BLOCK_16X16 && partition != PARTITION_NONE) {
4902
0
    x->max_partition_size = BLOCK_16X16;
4903
0
    x->min_partition_size = BLOCK_8X8;
4904
0
    nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, bsize, rd_cost,
4905
0
                         0, INT64_MAX, pc_tree);
4906
0
  } else {
4907
0
    switch (partition) {
4908
0
      case PARTITION_NONE:
4909
0
        pc_tree->none.pred_pixel_ready = 1;
4910
0
        nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
4911
0
                            &pc_tree->none);
4912
0
        pc_tree->none.mic = *xd->mi[0];
4913
0
        pc_tree->none.mbmi_ext = *x->mbmi_ext;
4914
0
        pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
4915
0
        pc_tree->none.skip = x->skip;
4916
0
        break;
4917
0
      case PARTITION_VERT:
4918
0
        pc_tree->vertical[0].pred_pixel_ready = 1;
4919
0
        nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
4920
0
                            &pc_tree->vertical[0]);
4921
0
        pc_tree->vertical[0].mic = *xd->mi[0];
4922
0
        pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
4923
0
        pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
4924
0
        pc_tree->vertical[0].skip = x->skip;
4925
0
        if (mi_col + hbs < cm->mi_cols) {
4926
0
          pc_tree->vertical[1].pred_pixel_ready = 1;
4927
0
          nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs,
4928
0
                              &this_rdc, subsize, &pc_tree->vertical[1]);
4929
0
          pc_tree->vertical[1].mic = *xd->mi[0];
4930
0
          pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
4931
0
          pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
4932
0
          pc_tree->vertical[1].skip = x->skip;
4933
0
          if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
4934
0
              rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
4935
0
            rd_cost->rate += this_rdc.rate;
4936
0
            rd_cost->dist += this_rdc.dist;
4937
0
          }
4938
0
        }
4939
0
        break;
4940
0
      case PARTITION_HORZ:
4941
0
        pc_tree->horizontal[0].pred_pixel_ready = 1;
4942
0
        nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, rd_cost, subsize,
4943
0
                            &pc_tree->horizontal[0]);
4944
0
        pc_tree->horizontal[0].mic = *xd->mi[0];
4945
0
        pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
4946
0
        pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
4947
0
        pc_tree->horizontal[0].skip = x->skip;
4948
0
        if (mi_row + hbs < cm->mi_rows) {
4949
0
          pc_tree->horizontal[1].pred_pixel_ready = 1;
4950
0
          nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col,
4951
0
                              &this_rdc, subsize, &pc_tree->horizontal[1]);
4952
0
          pc_tree->horizontal[1].mic = *xd->mi[0];
4953
0
          pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
4954
0
          pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
4955
0
          pc_tree->horizontal[1].skip = x->skip;
4956
0
          if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
4957
0
              rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
4958
0
            rd_cost->rate += this_rdc.rate;
4959
0
            rd_cost->dist += this_rdc.dist;
4960
0
          }
4961
0
        }
4962
0
        break;
4963
0
      default:
4964
0
        assert(partition == PARTITION_SPLIT);
4965
0
        subsize = get_subsize(bsize, PARTITION_SPLIT);
4966
0
        nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
4967
0
                               subsize, output_enabled, rd_cost,
4968
0
                               pc_tree->u.split[0]);
4969
0
        nonrd_select_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
4970
0
                               mi_col + hbs, subsize, output_enabled, &this_rdc,
4971
0
                               pc_tree->u.split[1]);
4972
0
        if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
4973
0
            rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
4974
0
          rd_cost->rate += this_rdc.rate;
4975
0
          rd_cost->dist += this_rdc.dist;
4976
0
        }
4977
0
        nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis, tp,
4978
0
                               mi_row + hbs, mi_col, subsize, output_enabled,
4979
0
                               &this_rdc, pc_tree->u.split[2]);
4980
0
        if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
4981
0
            rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
4982
0
          rd_cost->rate += this_rdc.rate;
4983
0
          rd_cost->dist += this_rdc.dist;
4984
0
        }
4985
0
        nonrd_select_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
4986
0
                               mi_row + hbs, mi_col + hbs, subsize,
4987
0
                               output_enabled, &this_rdc, pc_tree->u.split[3]);
4988
0
        if (this_rdc.rate != INT_MAX && this_rdc.dist != INT64_MAX &&
4989
0
            rd_cost->rate != INT_MAX && rd_cost->dist != INT64_MAX) {
4990
0
          rd_cost->rate += this_rdc.rate;
4991
0
          rd_cost->dist += this_rdc.dist;
4992
0
        }
4993
0
        break;
4994
0
    }
4995
0
  }
4996
4997
0
  if (bsize == BLOCK_64X64 && output_enabled)
4998
0
    encode_sb_rt(cpi, td, tile_info, tp, mi_row, mi_col, 1, bsize, pc_tree);
4999
0
}
5000
5001
static void nonrd_use_partition(VP9_COMP *cpi, ThreadData *td,
5002
                                TileDataEnc *tile_data, MODE_INFO **mi,
5003
                                TOKENEXTRA **tp, int mi_row, int mi_col,
5004
                                BLOCK_SIZE bsize, int output_enabled,
5005
0
                                RD_COST *dummy_cost, PC_TREE *pc_tree) {
5006
0
  VP9_COMMON *const cm = &cpi->common;
5007
0
  TileInfo *tile_info = &tile_data->tile_info;
5008
0
  MACROBLOCK *const x = &td->mb;
5009
0
  MACROBLOCKD *const xd = &x->e_mbd;
5010
0
  const int bsl = b_width_log2_lookup[bsize], hbs = (1 << bsl) / 4;
5011
0
  const int mis = cm->mi_stride;
5012
0
  PARTITION_TYPE partition;
5013
0
  BLOCK_SIZE subsize;
5014
5015
0
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
5016
5017
0
  subsize = (bsize >= BLOCK_8X8) ? mi[0]->sb_type : BLOCK_4X4;
5018
0
  partition = partition_lookup[bsl][subsize];
5019
5020
0
  if (output_enabled && bsize != BLOCK_4X4) {
5021
0
    int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
5022
0
    td->counts->partition[ctx][partition]++;
5023
0
  }
5024
5025
0
  switch (partition) {
5026
0
    case PARTITION_NONE:
5027
0
      pc_tree->none.pred_pixel_ready = 1;
5028
0
      nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5029
0
                          subsize, &pc_tree->none);
5030
0
      pc_tree->none.mic = *xd->mi[0];
5031
0
      pc_tree->none.mbmi_ext = *x->mbmi_ext;
5032
0
      pc_tree->none.skip_txfm[0] = x->skip_txfm[0];
5033
0
      pc_tree->none.skip = x->skip;
5034
0
      encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5035
0
                  subsize, &pc_tree->none);
5036
0
      break;
5037
0
    case PARTITION_VERT:
5038
0
      pc_tree->vertical[0].pred_pixel_ready = 1;
5039
0
      nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5040
0
                          subsize, &pc_tree->vertical[0]);
5041
0
      pc_tree->vertical[0].mic = *xd->mi[0];
5042
0
      pc_tree->vertical[0].mbmi_ext = *x->mbmi_ext;
5043
0
      pc_tree->vertical[0].skip_txfm[0] = x->skip_txfm[0];
5044
0
      pc_tree->vertical[0].skip = x->skip;
5045
0
      encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5046
0
                  subsize, &pc_tree->vertical[0]);
5047
0
      if (mi_col + hbs < cm->mi_cols && bsize > BLOCK_8X8) {
5048
0
        pc_tree->vertical[1].pred_pixel_ready = 1;
5049
0
        nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col + hbs, dummy_cost,
5050
0
                            subsize, &pc_tree->vertical[1]);
5051
0
        pc_tree->vertical[1].mic = *xd->mi[0];
5052
0
        pc_tree->vertical[1].mbmi_ext = *x->mbmi_ext;
5053
0
        pc_tree->vertical[1].skip_txfm[0] = x->skip_txfm[0];
5054
0
        pc_tree->vertical[1].skip = x->skip;
5055
0
        encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col + hbs,
5056
0
                    output_enabled, subsize, &pc_tree->vertical[1]);
5057
0
      }
5058
0
      break;
5059
0
    case PARTITION_HORZ:
5060
0
      pc_tree->horizontal[0].pred_pixel_ready = 1;
5061
0
      nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5062
0
                          subsize, &pc_tree->horizontal[0]);
5063
0
      pc_tree->horizontal[0].mic = *xd->mi[0];
5064
0
      pc_tree->horizontal[0].mbmi_ext = *x->mbmi_ext;
5065
0
      pc_tree->horizontal[0].skip_txfm[0] = x->skip_txfm[0];
5066
0
      pc_tree->horizontal[0].skip = x->skip;
5067
0
      encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5068
0
                  subsize, &pc_tree->horizontal[0]);
5069
5070
0
      if (mi_row + hbs < cm->mi_rows && bsize > BLOCK_8X8) {
5071
0
        pc_tree->horizontal[1].pred_pixel_ready = 1;
5072
0
        nonrd_pick_sb_modes(cpi, tile_data, x, mi_row + hbs, mi_col, dummy_cost,
5073
0
                            subsize, &pc_tree->horizontal[1]);
5074
0
        pc_tree->horizontal[1].mic = *xd->mi[0];
5075
0
        pc_tree->horizontal[1].mbmi_ext = *x->mbmi_ext;
5076
0
        pc_tree->horizontal[1].skip_txfm[0] = x->skip_txfm[0];
5077
0
        pc_tree->horizontal[1].skip = x->skip;
5078
0
        encode_b_rt(cpi, td, tile_info, tp, mi_row + hbs, mi_col,
5079
0
                    output_enabled, subsize, &pc_tree->horizontal[1]);
5080
0
      }
5081
0
      break;
5082
0
    default:
5083
0
      assert(partition == PARTITION_SPLIT);
5084
0
      subsize = get_subsize(bsize, PARTITION_SPLIT);
5085
0
      if (bsize == BLOCK_8X8) {
5086
0
        nonrd_pick_sb_modes(cpi, tile_data, x, mi_row, mi_col, dummy_cost,
5087
0
                            subsize, pc_tree->u.leaf_split[0]);
5088
0
        encode_b_rt(cpi, td, tile_info, tp, mi_row, mi_col, output_enabled,
5089
0
                    subsize, pc_tree->u.leaf_split[0]);
5090
0
      } else {
5091
0
        nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, subsize,
5092
0
                            output_enabled, dummy_cost, pc_tree->u.split[0]);
5093
0
        nonrd_use_partition(cpi, td, tile_data, mi + hbs, tp, mi_row,
5094
0
                            mi_col + hbs, subsize, output_enabled, dummy_cost,
5095
0
                            pc_tree->u.split[1]);
5096
0
        nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis, tp,
5097
0
                            mi_row + hbs, mi_col, subsize, output_enabled,
5098
0
                            dummy_cost, pc_tree->u.split[2]);
5099
0
        nonrd_use_partition(cpi, td, tile_data, mi + hbs * mis + hbs, tp,
5100
0
                            mi_row + hbs, mi_col + hbs, subsize, output_enabled,
5101
0
                            dummy_cost, pc_tree->u.split[3]);
5102
0
      }
5103
0
      break;
5104
0
  }
5105
5106
0
  if (partition != PARTITION_SPLIT || bsize == BLOCK_8X8)
5107
0
    update_partition_context(xd, mi_row, mi_col, subsize, bsize);
5108
0
}
5109
5110
// Get a prediction(stored in x->est_pred) for the whole 64x64 superblock.
5111
static void get_estimated_pred(VP9_COMP *cpi, const TileInfo *const tile,
5112
0
                               MACROBLOCK *x, int mi_row, int mi_col) {
5113
0
  VP9_COMMON *const cm = &cpi->common;
5114
0
  const int is_key_frame = is_key_frame_for_partition(cpi) ||
5115
0
                           !(cpi->ref_frame_flags & VP9_LAST_FLAG);
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
0
                                TOKENEXTRA **tp) {
5212
0
  SPEED_FEATURES *const sf = &cpi->sf;
5213
0
  VP9_COMMON *const cm = &cpi->common;
5214
0
  TileInfo *const tile_info = &tile_data->tile_info;
5215
0
  MACROBLOCK *const x = &td->mb;
5216
0
  MACROBLOCKD *const xd = &x->e_mbd;
5217
0
  const int mi_col_start = tile_info->mi_col_start;
5218
0
  const int mi_col_end = tile_info->mi_col_end;
5219
0
  int mi_col;
5220
0
  const int sb_row = mi_row >> MI_BLOCK_SIZE_LOG2;
5221
0
  const int num_sb_cols =
5222
0
      get_num_cols(tile_data->tile_info, MI_BLOCK_SIZE_LOG2);
5223
0
  int sb_col_in_tile;
5224
5225
  // Initialize the left context for the new SB row
5226
0
  memset(&xd->left_context, 0, sizeof(xd->left_context));
5227
0
  memset(xd->left_seg_context, 0, sizeof(xd->left_seg_context));
5228
5229
  // Code each SB in the row
5230
0
  for (mi_col = mi_col_start, sb_col_in_tile = 0; mi_col < mi_col_end;
5231
0
       mi_col += MI_BLOCK_SIZE, ++sb_col_in_tile) {
5232
0
    const struct segmentation *const seg = &cm->seg;
5233
0
    RD_COST dummy_rdc;
5234
0
    const int idx_str = cm->mi_stride * mi_row + mi_col;
5235
0
    MODE_INFO **mi = cm->mi_grid_visible + idx_str;
5236
0
    PARTITION_SEARCH_TYPE partition_search_type = sf->partition_search_type;
5237
0
    BLOCK_SIZE bsize = BLOCK_64X64;
5238
0
    int seg_skip = 0;
5239
0
    int i;
5240
5241
0
    (*(cpi->row_mt_sync_read_ptr))(&tile_data->row_mt_sync, sb_row,
5242
0
                                   sb_col_in_tile);
5243
5244
0
    if (cpi->use_skin_detection) {
5245
0
      vp9_compute_skin_sb(cpi, BLOCK_16X16, mi_row, mi_col);
5246
0
    }
5247
5248
0
    x->source_variance = UINT_MAX;
5249
0
    for (i = 0; i < MAX_REF_FRAMES; ++i) {
5250
0
      x->pred_mv[i].row = INT16_MAX;
5251
0
      x->pred_mv[i].col = INT16_MAX;
5252
0
    }
5253
0
    vp9_rd_cost_init(&dummy_rdc);
5254
0
    x->color_sensitivity[0] = 0;
5255
0
    x->color_sensitivity[1] = 0;
5256
0
    x->sb_is_skin = 0;
5257
0
    x->skip_low_source_sad = 0;
5258
0
    x->lowvar_highsumdiff = 0;
5259
0
    x->content_state_sb = 0;
5260
0
    x->zero_temp_sad_source = 0;
5261
0
    x->sb_use_mv_part = 0;
5262
0
    x->sb_mvcol_part = 0;
5263
0
    x->sb_mvrow_part = 0;
5264
0
    x->sb_pickmode_part = 0;
5265
0
    x->arf_frame_usage = 0;
5266
0
    x->lastgolden_frame_usage = 0;
5267
5268
0
    if (cpi->compute_source_sad_onepass && cpi->sf.use_source_sad) {
5269
0
      int shift = cpi->Source->y_stride * (mi_row << 3) + (mi_col << 3);
5270
0
      int sb_offset2 = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5271
0
      int64_t source_sad = avg_source_sad(cpi, x, shift, sb_offset2);
5272
0
      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
0
    }
5278
5279
0
    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
0
    switch (partition_search_type) {
5313
0
      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
0
        choose_partitioning(cpi, tile_info, x, mi_row, mi_col);
5319
0
        nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5320
0
                            BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5321
0
        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
0
      case FIXED_PARTITION:
5332
0
        if (!seg_skip) bsize = sf->always_this_block_size;
5333
0
        set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize);
5334
0
        nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5335
0
                            BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5336
0
        break;
5337
0
      default:
5338
0
        assert(partition_search_type == REFERENCE_PARTITION);
5339
0
        x->sb_pickmode_part = 1;
5340
0
        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
0
        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
0
        } else {
5357
0
          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
0
          if (frame_is_intra_only(cm))
5362
0
            nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5363
0
                                BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5364
0
          else
5365
0
            nonrd_select_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col,
5366
0
                                   BLOCK_64X64, 1, &dummy_rdc, td->pc_root);
5367
0
        }
5368
5369
0
        break;
5370
0
    }
5371
5372
    // Update ref_frame usage for inter frame if this group is ARF group.
5373
0
    if (!cpi->rc.is_src_frame_alt_ref && !cpi->refresh_golden_frame &&
5374
0
        !cpi->refresh_alt_ref_frame && cpi->rc.alt_ref_gf_group &&
5375
0
        cpi->sf.use_altref_onepass) {
5376
0
      int sboffset = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
5377
0
      if (cpi->count_arf_frame_usage != NULL)
5378
0
        cpi->count_arf_frame_usage[sboffset] = x->arf_frame_usage;
5379
0
      if (cpi->count_lastgolden_frame_usage != NULL)
5380
0
        cpi->count_lastgolden_frame_usage[sboffset] = x->lastgolden_frame_usage;
5381
0
    }
5382
5383
0
    (*(cpi->row_mt_sync_write_ptr))(&tile_data->row_mt_sync, sb_row,
5384
0
                                    sb_col_in_tile, num_sb_cols);
5385
0
  }
5386
0
}
5387
// end RTC play code
5388
5389
0
static int get_skip_encode_frame(const VP9_COMMON *cm, ThreadData *const td) {
5390
0
  unsigned int intra_count = 0, inter_count = 0;
5391
0
  int j;
5392
5393
0
  for (j = 0; j < INTRA_INTER_CONTEXTS; ++j) {
5394
0
    intra_count += td->counts->intra_inter[j][0];
5395
0
    inter_count += td->counts->intra_inter[j][1];
5396
0
  }
5397
5398
0
  return (intra_count << 2) < inter_count && cm->frame_type != KEY_FRAME &&
5399
0
         cm->show_frame;
5400
0
}
5401
5402
74.0k
void vp9_init_tile_data(VP9_COMP *cpi) {
5403
74.0k
  VP9_COMMON *const cm = &cpi->common;
5404
74.0k
  const int tile_cols = 1 << cm->log2_tile_cols;
5405
74.0k
  const int tile_rows = 1 << cm->log2_tile_rows;
5406
74.0k
  int tile_col, tile_row;
5407
74.0k
  TOKENEXTRA *pre_tok = cpi->tile_tok[0][0];
5408
74.0k
  TOKENLIST *tplist = cpi->tplist[0][0];
5409
74.0k
  int64_t tile_tok = 0;
5410
74.0k
  int tplist_count = 0;
5411
5412
74.0k
  if (cpi->tile_data == NULL || cpi->allocated_tiles < tile_cols * tile_rows) {
5413
4.53k
    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
4.53k
    cpi->allocated_tiles = 0;
5419
4.53k
    CHECK_MEM_ERROR(
5420
4.53k
        &cm->error, cpi->tile_data,
5421
4.53k
        vpx_malloc(tile_cols * tile_rows * sizeof(*cpi->tile_data)));
5422
4.53k
    cpi->allocated_tiles = tile_cols * tile_rows;
5423
5424
9.06k
    for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5425
12.2k
      for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5426
7.71k
        TileDataEnc *tile_data =
5427
7.71k
            &cpi->tile_data[tile_row * tile_cols + tile_col];
5428
7.71k
        int i, j;
5429
7.71k
        const MV zero_mv = { 0, 0 };
5430
108k
        for (i = 0; i < BLOCK_SIZES; ++i) {
5431
3.10M
          for (j = 0; j < MAX_MODES; ++j) {
5432
3.00M
            tile_data->thresh_freq_fact[i][j] = RD_THRESH_INIT_FACT;
5433
3.00M
            tile_data->thresh_freq_fact_prev[i][j] = RD_THRESH_INIT_FACT;
5434
3.00M
            tile_data->mode_map[i][j] = j;
5435
3.00M
          }
5436
100k
        }
5437
7.71k
        tile_data->firstpass_top_mv = zero_mv;
5438
7.71k
#if CONFIG_MULTITHREAD
5439
7.71k
        tile_data->row_base_thresh_freq_fact = NULL;
5440
7.71k
#endif
5441
7.71k
      }
5442
4.53k
  }
5443
5444
148k
  for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
5445
151k
    for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
5446
77.8k
      TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5447
77.8k
      TileInfo *tile_info = &this_tile->tile_info;
5448
77.8k
      if (cpi->sf.adaptive_rd_thresh_row_mt) {
5449
0
        vp9_row_mt_alloc_rd_thresh(cpi, this_tile);
5450
0
      }
5451
77.8k
      vp9_tile_init(tile_info, cm, tile_row, tile_col);
5452
5453
77.8k
      cpi->tile_tok[tile_row][tile_col] = pre_tok + tile_tok;
5454
77.8k
      pre_tok = cpi->tile_tok[tile_row][tile_col];
5455
77.8k
      tile_tok = allocated_tokens(*tile_info);
5456
5457
77.8k
      cpi->tplist[tile_row][tile_col] = tplist + tplist_count;
5458
77.8k
      tplist = cpi->tplist[tile_row][tile_col];
5459
77.8k
      tplist_count = get_num_vert_units(*tile_info, MI_BLOCK_SIZE_LOG2);
5460
77.8k
    }
5461
74.0k
  }
5462
74.0k
}
5463
5464
void vp9_encode_sb_row(VP9_COMP *cpi, ThreadData *td, int tile_row,
5465
95.2k
                       int tile_col, int mi_row) {
5466
95.2k
  VP9_COMMON *const cm = &cpi->common;
5467
95.2k
  const int tile_cols = 1 << cm->log2_tile_cols;
5468
95.2k
  TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5469
95.2k
  const TileInfo *const tile_info = &this_tile->tile_info;
5470
95.2k
  TOKENEXTRA *tok = NULL;
5471
95.2k
  int tile_sb_row;
5472
95.2k
  int tile_mb_cols = (tile_info->mi_col_end - tile_info->mi_col_start + 1) >> 1;
5473
5474
95.2k
  tile_sb_row = mi_cols_aligned_to_sb(mi_row - tile_info->mi_row_start) >>
5475
95.2k
                MI_BLOCK_SIZE_LOG2;
5476
95.2k
  get_start_tok(cpi, tile_row, tile_col, mi_row, &tok);
5477
95.2k
  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
95.2k
  if (cpi->sf.use_nonrd_pick_mode)
5484
0
    encode_nonrd_sb_row(cpi, td, this_tile, mi_row, &tok);
5485
95.2k
  else
5486
95.2k
    encode_rd_sb_row(cpi, td, this_tile, mi_row, &tok);
5487
95.2k
#endif
5488
5489
95.2k
  cpi->tplist[tile_row][tile_col][tile_sb_row].stop = tok;
5490
95.2k
  cpi->tplist[tile_row][tile_col][tile_sb_row].count =
5491
95.2k
      (unsigned int)(cpi->tplist[tile_row][tile_col][tile_sb_row].stop -
5492
95.2k
                     cpi->tplist[tile_row][tile_col][tile_sb_row].start);
5493
95.2k
  assert(tok - cpi->tplist[tile_row][tile_col][tile_sb_row].start <=
5494
95.2k
         get_token_alloc(MI_BLOCK_SIZE >> 1, tile_mb_cols));
5495
5496
95.2k
  (void)tile_mb_cols;
5497
95.2k
}
5498
5499
void vp9_encode_tile(VP9_COMP *cpi, ThreadData *td, int tile_row,
5500
77.8k
                     int tile_col) {
5501
77.8k
  VP9_COMMON *const cm = &cpi->common;
5502
77.8k
  const int tile_cols = 1 << cm->log2_tile_cols;
5503
77.8k
  TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
5504
77.8k
  const TileInfo *const tile_info = &this_tile->tile_info;
5505
77.8k
  const int mi_row_start = tile_info->mi_row_start;
5506
77.8k
  const int mi_row_end = tile_info->mi_row_end;
5507
77.8k
  int mi_row;
5508
5509
173k
  for (mi_row = mi_row_start; mi_row < mi_row_end; mi_row += MI_BLOCK_SIZE)
5510
95.2k
    vp9_encode_sb_row(cpi, td, tile_row, tile_col, mi_row);
5511
77.8k
}
5512
5513
74.0k
static void encode_tiles(VP9_COMP *cpi) {
5514
74.0k
  VP9_COMMON *const cm = &cpi->common;
5515
74.0k
  const int tile_cols = 1 << cm->log2_tile_cols;
5516
74.0k
  const int tile_rows = 1 << cm->log2_tile_rows;
5517
74.0k
  int tile_col, tile_row;
5518
5519
74.0k
  vp9_init_tile_data(cpi);
5520
5521
148k
  for (tile_row = 0; tile_row < tile_rows; ++tile_row)
5522
151k
    for (tile_col = 0; tile_col < tile_cols; ++tile_col)
5523
77.8k
      vp9_encode_tile(cpi, &cpi->td, tile_row, tile_col);
5524
74.0k
}
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
74.0k
static void encode_frame_internal(VP9_COMP *cpi) {
5628
74.0k
  SPEED_FEATURES *const sf = &cpi->sf;
5629
74.0k
  ThreadData *const td = &cpi->td;
5630
74.0k
  MACROBLOCK *const x = &td->mb;
5631
74.0k
  VP9_COMMON *const cm = &cpi->common;
5632
74.0k
  MACROBLOCKD *const xd = &x->e_mbd;
5633
74.0k
  const int gf_group_index = cpi->twopass.gf_group.index;
5634
5635
74.0k
  xd->mi = cm->mi_grid_visible;
5636
74.0k
  xd->mi[0] = cm->mi;
5637
74.0k
  vp9_zero(*td->counts);
5638
74.0k
  vp9_zero(cpi->td.rd_counts);
5639
5640
74.0k
  xd->lossless = cm->base_qindex == 0 && cm->y_dc_delta_q == 0 &&
5641
14.6k
                 cm->uv_dc_delta_q == 0 && cm->uv_ac_delta_q == 0;
5642
5643
74.0k
#if CONFIG_VP9_HIGHBITDEPTH
5644
74.0k
  if (cm->use_highbitdepth)
5645
5.97k
    x->fwd_txfm4x4 = xd->lossless ? vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
5646
68.0k
  else
5647
68.0k
    x->fwd_txfm4x4 = xd->lossless ? vp9_fwht4x4 : vpx_fdct4x4;
5648
74.0k
  x->highbd_inv_txfm_add =
5649
74.0k
      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
74.0k
  x->inv_txfm_add = xd->lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
5654
74.0k
  x->optimize = sf->optimize_coefficients == 1 && cpi->oxcf.pass != 1;
5655
74.0k
  if (xd->lossless) x->optimize = 0;
5656
74.0k
  x->sharpness = cpi->oxcf.sharpness;
5657
74.0k
  x->adjust_rdmult_by_segment = (cpi->oxcf.aq_mode == VARIANCE_AQ);
5658
5659
74.0k
  cm->tx_mode = select_tx_mode(cpi, xd);
5660
5661
74.0k
  vp9_frame_init_quantizer(cpi);
5662
5663
74.0k
  vp9_initialize_rd_consts(cpi);
5664
74.0k
  vp9_initialize_me_consts(cpi, x, cm->base_qindex);
5665
74.0k
  init_encode_frame_mb_context(cpi);
5666
74.0k
  cm->use_prev_frame_mvs =
5667
74.0k
      !cm->error_resilient_mode && cm->width == cm->last_width &&
5668
69.4k
      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
74.0k
  cm->prev_mi =
5672
74.0k
      cm->use_prev_frame_mvs ? cm->prev_mip + cm->mi_stride + 1 : NULL;
5673
5674
74.0k
  x->quant_fp = cpi->sf.use_quant_fp;
5675
74.0k
  vp9_zero(x->skip_txfm);
5676
74.0k
  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
0
    int i;
5680
0
    struct macroblock_plane *const p = x->plane;
5681
0
    struct macroblockd_plane *const pd = xd->plane;
5682
0
    PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
5683
5684
0
    for (i = 0; i < MAX_MB_PLANE; ++i) {
5685
0
      p[i].coeff = ctx->coeff_pbuf[i][0];
5686
0
      p[i].qcoeff = ctx->qcoeff_pbuf[i][0];
5687
0
      pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][0];
5688
0
      p[i].eobs = ctx->eobs_pbuf[i][0];
5689
0
    }
5690
0
    vp9_zero(x->zcoeff_blk);
5691
5692
0
    if (cm->frame_type != KEY_FRAME && cpi->rc.frames_since_golden == 0 &&
5693
0
        !(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
74.0k
  } 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
296k
  for (MV_REFERENCE_FRAME ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME;
5721
222k
       ++ref_frame) {
5722
222k
    if (cpi->ref_frame_flags & ref_frame_to_flag(ref_frame)) {
5723
157k
      if (cm->frame_refs[ref_frame - 1].sf.x_scale_fp == REF_INVALID_SCALE ||
5724
157k
          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
157k
    }
5727
222k
  }
5728
5729
  // Frame segmentation
5730
74.0k
  if (cpi->oxcf.aq_mode == PERCEPTUAL_AQ) build_kmeans_segmentation(cpi);
5731
5732
74.0k
  {
5733
#if CONFIG_INTERNAL_STATS
5734
    struct vpx_usec_timer emr_timer;
5735
    vpx_usec_timer_start(&emr_timer);
5736
#endif
5737
5738
74.0k
    if (!cpi->row_mt) {
5739
74.0k
      cpi->row_mt_sync_read_ptr = vp9_row_mt_sync_read_dummy;
5740
74.0k
      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
74.0k
      if (VPXMIN(cpi->oxcf.max_threads, 1 << cm->log2_tile_cols) > 1)
5744
0
        vp9_encode_tiles_mt(cpi);
5745
74.0k
      else
5746
74.0k
        encode_tiles(cpi);
5747
74.0k
    } 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
74.0k
  }
5758
5759
74.0k
  sf->skip_encode_frame =
5760
74.0k
      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
74.0k
}
5767
5768
static INTERP_FILTER get_interp_filter(
5769
74.0k
    const int64_t threshes[SWITCHABLE_FILTER_CONTEXTS], int is_alt_ref) {
5770
74.0k
  if (!is_alt_ref && threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP] &&
5771
14.2k
      threshes[EIGHTTAP_SMOOTH] > threshes[EIGHTTAP_SHARP] &&
5772
14.0k
      threshes[EIGHTTAP_SMOOTH] > threshes[SWITCHABLE - 1]) {
5773
11.3k
    return EIGHTTAP_SMOOTH;
5774
62.7k
  } else if (threshes[EIGHTTAP_SHARP] > threshes[EIGHTTAP] &&
5775
2.02k
             threshes[EIGHTTAP_SHARP] > threshes[SWITCHABLE - 1]) {
5776
1.67k
    return EIGHTTAP_SHARP;
5777
61.0k
  } else if (threshes[EIGHTTAP] > threshes[SWITCHABLE - 1]) {
5778
24.8k
    return EIGHTTAP;
5779
36.1k
  } else {
5780
36.1k
    return SWITCHABLE;
5781
36.1k
  }
5782
74.0k
}
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
74.0k
static void restore_encode_params(VP9_COMP *cpi) {
5808
74.0k
  VP9_COMMON *const cm = &cpi->common;
5809
74.0k
  int tile_idx;
5810
74.0k
  int i, j;
5811
74.0k
  TileDataEnc *tile_data;
5812
74.0k
  RD_OPT *rd_opt = &cpi->rd;
5813
370k
  for (i = 0; i < MAX_REF_FRAMES; i++) {
5814
1.18M
    for (j = 0; j < REFERENCE_MODES; j++)
5815
888k
      rd_opt->prediction_type_threshes[i][j] =
5816
888k
          rd_opt->prediction_type_threshes_prev[i][j];
5817
5818
1.48M
    for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; j++)
5819
1.18M
      rd_opt->filter_threshes[i][j] = rd_opt->filter_threshes_prev[i][j];
5820
296k
  }
5821
5822
144k
  for (tile_idx = 0; tile_idx < cpi->allocated_tiles; tile_idx++) {
5823
70.1k
    assert(cpi->tile_data);
5824
70.1k
    tile_data = &cpi->tile_data[tile_idx];
5825
70.1k
    vp9_copy(tile_data->thresh_freq_fact, tile_data->thresh_freq_fact_prev);
5826
70.1k
  }
5827
5828
74.0k
  cm->interp_filter = cpi->sf.default_interp_filter;
5829
74.0k
}
5830
5831
74.0k
void vp9_encode_frame(VP9_COMP *cpi) {
5832
74.0k
  VP9_COMMON *const cm = &cpi->common;
5833
5834
74.0k
  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
74.0k
  if (!frame_is_intra_only(cm)) {
5847
58.2k
    if (vp9_compound_reference_allowed(cm)) {
5848
0
      cpi->allow_comp_inter_inter = 1;
5849
0
      vp9_setup_compound_reference_mode(cm);
5850
58.2k
    } else {
5851
58.2k
      cpi->allow_comp_inter_inter = 0;
5852
58.2k
    }
5853
58.2k
  }
5854
5855
74.0k
  if (cpi->sf.frame_parameter_update) {
5856
74.0k
    int i;
5857
74.0k
    RD_OPT *const rd_opt = &cpi->rd;
5858
74.0k
    FRAME_COUNTS *counts = cpi->td.counts;
5859
74.0k
    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
74.0k
    const MV_REFERENCE_FRAME frame_type = get_frame_type(cpi);
5869
74.0k
    int64_t *const mode_thrs = rd_opt->prediction_type_threshes[frame_type];
5870
74.0k
    int64_t *const filter_thrs = rd_opt->filter_threshes[frame_type];
5871
74.0k
    const int is_alt_ref = frame_type == ALTREF_FRAME;
5872
5873
    /* prediction (compound, single or hybrid) mode selection */
5874
74.0k
    if (is_alt_ref || !cpi->allow_comp_inter_inter)
5875
74.0k
      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
74.0k
    if (cm->interp_filter == SWITCHABLE)
5886
74.0k
      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
74.0k
    encode_frame_internal(cpi);
5892
#if CONFIG_COLLECT_COMPONENT_TIMING
5893
    end_timing(cpi, encode_frame_internal_time);
5894
#endif
5895
5896
296k
    for (i = 0; i < REFERENCE_MODES; ++i)
5897
222k
      mode_thrs[i] = (mode_thrs[i] + rdc->comp_pred_diff[i] / cm->MBs) / 2;
5898
5899
370k
    for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
5900
296k
      filter_thrs[i] = (filter_thrs[i] + rdc->filter_diff[i] / cm->MBs) / 2;
5901
5902
74.0k
    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
74.0k
    if (cm->tx_mode == TX_MODE_SELECT) {
5921
33.4k
      int count4x4 = 0;
5922
33.4k
      int count8x8_lp = 0, count8x8_8x8p = 0;
5923
33.4k
      int count16x16_16x16p = 0, count16x16_lp = 0;
5924
33.4k
      int count32x32 = 0;
5925
5926
100k
      for (i = 0; i < TX_SIZE_CONTEXTS; ++i) {
5927
66.8k
        count4x4 += counts->tx.p32x32[i][TX_4X4];
5928
66.8k
        count4x4 += counts->tx.p16x16[i][TX_4X4];
5929
66.8k
        count4x4 += counts->tx.p8x8[i][TX_4X4];
5930
5931
66.8k
        count8x8_lp += counts->tx.p32x32[i][TX_8X8];
5932
66.8k
        count8x8_lp += counts->tx.p16x16[i][TX_8X8];
5933
66.8k
        count8x8_8x8p += counts->tx.p8x8[i][TX_8X8];
5934
5935
66.8k
        count16x16_16x16p += counts->tx.p16x16[i][TX_16X16];
5936
66.8k
        count16x16_lp += counts->tx.p32x32[i][TX_16X16];
5937
66.8k
        count32x32 += counts->tx.p32x32[i][TX_32X32];
5938
66.8k
      }
5939
33.4k
      if (count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0 &&
5940
15.2k
          count32x32 == 0) {
5941
12.3k
        cm->tx_mode = ALLOW_8X8;
5942
12.3k
        reset_skip_tx_size(cm, TX_8X8);
5943
21.0k
      } else if (count8x8_8x8p == 0 && count16x16_16x16p == 0 &&
5944
6.38k
                 count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0) {
5945
3.32k
        cm->tx_mode = ONLY_4X4;
5946
3.32k
        reset_skip_tx_size(cm, TX_4X4);
5947
17.6k
      } else if (count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0) {
5948
4.90k
        cm->tx_mode = ALLOW_32X32;
5949
12.7k
      } else if (count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0) {
5950
73
        cm->tx_mode = ALLOW_16X16;
5951
73
        reset_skip_tx_size(cm, TX_16X16);
5952
73
      }
5953
33.4k
    }
5954
74.0k
  } else {
5955
0
    FRAME_COUNTS *counts = cpi->td.counts;
5956
0
    cm->reference_mode = SINGLE_REFERENCE;
5957
0
    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
0
    encode_frame_internal(cpi);
5963
5964
0
    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
0
  }
5981
5982
  // If segmented AQ is enabled compute the average AQ weighting.
5983
74.0k
  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
74.0k
}
5988
5989
1.27M
static void sum_intra_stats(FRAME_COUNTS *counts, const MODE_INFO *mi) {
5990
1.27M
  const PREDICTION_MODE y_mode = mi->mode;
5991
1.27M
  const PREDICTION_MODE uv_mode = mi->uv_mode;
5992
1.27M
  const BLOCK_SIZE bsize = mi->sb_type;
5993
5994
1.27M
  if (bsize < BLOCK_8X8) {
5995
714k
    int idx, idy;
5996
714k
    const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
5997
714k
    const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
5998
2.06M
    for (idy = 0; idy < 2; idy += num_4x4_h)
5999
3.82M
      for (idx = 0; idx < 2; idx += num_4x4_w)
6000
2.47M
        ++counts->y_mode[0][mi->bmi[idy * 2 + idx].as_mode];
6001
714k
  } else {
6002
563k
    ++counts->y_mode[size_group_lookup[bsize]][y_mode];
6003
563k
  }
6004
6005
1.27M
  ++counts->uv_mode[y_mode][uv_mode];
6006
1.27M
}
6007
6008
static void update_zeromv_cnt(VP9_COMP *const cpi, const MODE_INFO *const mi,
6009
1.72M
                              int mi_row, int mi_col, BLOCK_SIZE bsize) {
6010
1.72M
  const VP9_COMMON *const cm = &cpi->common;
6011
1.72M
  MV mv = mi->mv[0].as_mv;
6012
1.72M
  const int bw = num_8x8_blocks_wide_lookup[bsize];
6013
1.72M
  const int bh = num_8x8_blocks_high_lookup[bsize];
6014
1.72M
  const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
6015
1.72M
  const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
6016
1.72M
  const int block_index = mi_row * cm->mi_cols + mi_col;
6017
1.72M
  int x, y;
6018
3.86M
  for (y = 0; y < ymis; y++)
6019
5.90M
    for (x = 0; x < xmis; x++) {
6020
3.76M
      int map_offset = block_index + y * cm->mi_cols + x;
6021
3.76M
      if (mi->ref_frame[0] == LAST_FRAME && is_inter_block(mi) &&
6022
691k
          mi->segment_id <= CR_SEGMENT_ID_BOOST2) {
6023
691k
        if (abs(mv.row) < 8 && abs(mv.col) < 8) {
6024
130k
          if (cpi->consec_zero_mv[map_offset] < 255)
6025
129k
            cpi->consec_zero_mv[map_offset]++;
6026
561k
        } else {
6027
561k
          cpi->consec_zero_mv[map_offset] = 0;
6028
561k
        }
6029
691k
      }
6030
3.76M
    }
6031
1.72M
}
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.27M
                              BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx) {
6036
7.27M
  VP9_COMMON *const cm = &cpi->common;
6037
7.27M
  MACROBLOCK *const x = &td->mb;
6038
7.27M
  MACROBLOCKD *const xd = &x->e_mbd;
6039
7.27M
  MODE_INFO *mi = xd->mi[0];
6040
7.27M
  const int seg_skip =
6041
7.27M
      segfeature_active(&cm->seg, mi->segment_id, SEG_LVL_SKIP);
6042
7.27M
  x->skip_recode = !x->select_tx_size && mi->sb_type >= BLOCK_8X8 &&
6043
1.35M
                   cpi->oxcf.aq_mode != COMPLEXITY_AQ &&
6044
1.35M
                   cpi->oxcf.aq_mode != CYCLIC_REFRESH_AQ &&
6045
1.35M
                   cpi->sf.allow_skip_recode;
6046
6047
7.27M
  if (!x->skip_recode && !cpi->sf.use_nonrd_pick_mode)
6048
7.27M
    memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
6049
6050
7.27M
  x->skip_optimize = ctx->is_coded;
6051
7.27M
  ctx->is_coded = 1;
6052
7.27M
  x->use_lp32x32fdct = cpi->sf.use_lp32x32fdct;
6053
7.27M
  x->skip_encode = (!output_enabled && cpi->sf.skip_encode_frame &&
6054
0
                    x->q_index < QIDX_SKIP_THRESH);
6055
6056
7.27M
  if (x->skip_encode) return;
6057
6058
7.27M
  if (!is_inter_block(mi)) {
6059
5.32M
    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
5.32M
    mi->skip = 1;
6067
21.2M
    for (plane = 0; plane < MAX_MB_PLANE; ++plane)
6068
15.9M
      vp9_encode_intra_block_plane(x, VPXMAX(bsize, BLOCK_8X8), plane, 1);
6069
5.32M
    if (output_enabled) sum_intra_stats(td->counts, mi);
6070
5.32M
    vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6071
5.32M
                    VPXMAX(bsize, BLOCK_8X8));
6072
5.32M
  } else {
6073
1.95M
    int ref;
6074
1.95M
    const int is_compound = has_second_ref(mi);
6075
1.95M
    set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]);
6076
3.90M
    for (ref = 0; ref < 1 + is_compound; ++ref) {
6077
1.95M
      YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi, mi->ref_frame[ref]);
6078
1.95M
      assert(cfg != NULL);
6079
1.95M
      vp9_setup_pre_planes(xd, ref, cfg, mi_row, mi_col,
6080
1.95M
                           &xd->block_refs[ref]->sf);
6081
1.95M
    }
6082
1.95M
    if (!(cpi->sf.reuse_inter_pred_sby && ctx->pred_pixel_ready) || seg_skip)
6083
1.95M
      vp9_build_inter_predictors_sby(xd, mi_row, mi_col,
6084
1.95M
                                     VPXMAX(bsize, BLOCK_8X8));
6085
6086
1.95M
    vp9_build_inter_predictors_sbuv(xd, mi_row, mi_col,
6087
1.95M
                                    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
1.95M
    vp9_encode_sb(x, VPXMAX(bsize, BLOCK_8X8), mi_row, mi_col, output_enabled);
6110
1.95M
    vp9_tokenize_sb(cpi, td, t, !output_enabled, seg_skip,
6111
1.95M
                    VPXMAX(bsize, BLOCK_8X8));
6112
1.95M
  }
6113
6114
7.27M
  if (seg_skip) {
6115
0
    assert(mi->skip);
6116
0
  }
6117
6118
7.27M
  if (output_enabled) {
6119
1.72M
    if (cm->tx_mode == TX_MODE_SELECT && mi->sb_type >= BLOCK_8X8 &&
6120
491k
        !(is_inter_block(mi) && mi->skip)) {
6121
459k
      ++get_tx_counts(max_txsize_lookup[bsize], get_tx_size_context(xd),
6122
459k
                      &td->counts->tx)[mi->tx_size];
6123
1.26M
    } else {
6124
      // The new intra coding scheme requires no change of transform size
6125
1.26M
      if (is_inter_block(mi)) {
6126
360k
        mi->tx_size = VPXMIN(tx_mode_to_biggest_tx_size[cm->tx_mode],
6127
360k
                             max_txsize_lookup[bsize]);
6128
906k
      } else {
6129
906k
        mi->tx_size = (bsize >= BLOCK_8X8) ? mi->tx_size : TX_4X4;
6130
906k
      }
6131
1.26M
    }
6132
6133
1.72M
    ++td->counts->tx.tx_totals[mi->tx_size];
6134
1.72M
    ++td->counts->tx.tx_totals[get_uv_tx_size(mi, &xd->plane[1])];
6135
1.72M
    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
1.72M
    if (cpi->oxcf.pass == 0 && cpi->svc.temporal_layer_id == 0 &&
6139
1.72M
        (!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
1.72M
      update_zeromv_cnt(cpi, mi, mi_row, mi_col, bsize);
6144
1.72M
  }
6145
7.27M
}