Coverage Report

Created: 2025-08-28 07:12

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