1 /*
2 * Copyright (c) 2016, Alliance for Open Media. All rights reserved
3 *
4 * This source code is subject to the terms of the BSD 2 Clause License and
5 * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6 * was not distributed with this source code in the LICENSE file, you can
7 * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8 * Media Patent License 1.0 was not distributed with this source code in the
9 * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10 */
11
12 #include <limits.h>
13 #include <math.h>
14 #include <stdio.h>
15
16 #include "config/aom_dsp_rtcd.h"
17 #include "config/aom_scale_rtcd.h"
18
19 #include "aom_dsp/aom_dsp_common.h"
20 #include "aom_dsp/variance.h"
21 #include "aom_mem/aom_mem.h"
22 #include "aom_ports/mem.h"
23 #include "aom_scale/aom_scale.h"
24 #include "aom_scale/yv12config.h"
25 #include "aom_util/aom_pthread.h"
26
27 #include "av1/common/entropymv.h"
28 #include "av1/common/quant_common.h"
29 #include "av1/common/reconinter.h" // av1_setup_dst_planes()
30 #include "av1/common/reconintra.h"
31 #include "av1/common/txb_common.h"
32 #include "av1/encoder/aq_variance.h"
33 #include "av1/encoder/av1_quantize.h"
34 #include "av1/encoder/block.h"
35 #include "av1/encoder/dwt.h"
36 #include "av1/encoder/encodeframe.h"
37 #include "av1/encoder/encodeframe_utils.h"
38 #include "av1/encoder/encodemb.h"
39 #include "av1/encoder/encodemv.h"
40 #include "av1/encoder/encoder.h"
41 #include "av1/encoder/encoder_utils.h"
42 #include "av1/encoder/encode_strategy.h"
43 #include "av1/encoder/ethread.h"
44 #include "av1/encoder/extend.h"
45 #include "av1/encoder/firstpass.h"
46 #include "av1/encoder/mcomp.h"
47 #include "av1/encoder/rd.h"
48 #include "av1/encoder/reconinter_enc.h"
49
50 #define OUTPUT_FPF 0
51
52 #define FIRST_PASS_Q 10.0
53 #define INTRA_MODE_PENALTY 1024
54 #define NEW_MV_MODE_PENALTY 32
55 #define DARK_THRESH 64
56
57 #define NCOUNT_INTRA_THRESH 8192
58 #define NCOUNT_INTRA_FACTOR 3
59
60 #define INVALID_FP_STATS_TO_PREDICT_FLAT_GOP -1
61
output_stats(FIRSTPASS_STATS * stats,struct aom_codec_pkt_list * pktlist)62 static AOM_INLINE void output_stats(FIRSTPASS_STATS *stats,
63 struct aom_codec_pkt_list *pktlist) {
64 struct aom_codec_cx_pkt pkt;
65 pkt.kind = AOM_CODEC_STATS_PKT;
66 pkt.data.twopass_stats.buf = stats;
67 pkt.data.twopass_stats.sz = sizeof(FIRSTPASS_STATS);
68 if (pktlist != NULL) aom_codec_pkt_list_add(pktlist, &pkt);
69
70 // TEMP debug code
71 #if OUTPUT_FPF
72 {
73 FILE *fpfile;
74 fpfile = fopen("firstpass.stt", "a");
75
76 fprintf(fpfile,
77 "%12.0lf %12.4lf %12.0lf %12.0lf %12.0lf %12.4lf %12.4lf"
78 "%12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf"
79 "%12.4lf %12.4lf %12.0lf %12.0lf %12.0lf %12.4lf %12.4lf\n",
80 stats->frame, stats->weight, stats->intra_error, stats->coded_error,
81 stats->sr_coded_error, stats->pcnt_inter, stats->pcnt_motion,
82 stats->pcnt_second_ref, stats->pcnt_neutral, stats->intra_skip_pct,
83 stats->inactive_zone_rows, stats->inactive_zone_cols, stats->MVr,
84 stats->mvr_abs, stats->MVc, stats->mvc_abs, stats->MVrv,
85 stats->MVcv, stats->mv_in_out_count, stats->new_mv_count,
86 stats->count, stats->duration);
87 fclose(fpfile);
88 }
89 #endif
90 }
91
av1_twopass_zero_stats(FIRSTPASS_STATS * section)92 void av1_twopass_zero_stats(FIRSTPASS_STATS *section) {
93 section->frame = 0.0;
94 section->weight = 0.0;
95 section->intra_error = 0.0;
96 section->frame_avg_wavelet_energy = 0.0;
97 section->coded_error = 0.0;
98 section->log_intra_error = 0.0;
99 section->log_coded_error = 0.0;
100 section->sr_coded_error = 0.0;
101 section->pcnt_inter = 0.0;
102 section->pcnt_motion = 0.0;
103 section->pcnt_second_ref = 0.0;
104 section->pcnt_neutral = 0.0;
105 section->intra_skip_pct = 0.0;
106 section->inactive_zone_rows = 0.0;
107 section->inactive_zone_cols = 0.0;
108 section->MVr = 0.0;
109 section->mvr_abs = 0.0;
110 section->MVc = 0.0;
111 section->mvc_abs = 0.0;
112 section->MVrv = 0.0;
113 section->MVcv = 0.0;
114 section->mv_in_out_count = 0.0;
115 section->new_mv_count = 0.0;
116 section->count = 0.0;
117 section->duration = 1.0;
118 section->is_flash = 0;
119 section->noise_var = 0;
120 section->cor_coeff = 1.0;
121 }
122
av1_accumulate_stats(FIRSTPASS_STATS * section,const FIRSTPASS_STATS * frame)123 void av1_accumulate_stats(FIRSTPASS_STATS *section,
124 const FIRSTPASS_STATS *frame) {
125 section->frame += frame->frame;
126 section->weight += frame->weight;
127 section->intra_error += frame->intra_error;
128 section->log_intra_error += log1p(frame->intra_error);
129 section->log_coded_error += log1p(frame->coded_error);
130 section->frame_avg_wavelet_energy += frame->frame_avg_wavelet_energy;
131 section->coded_error += frame->coded_error;
132 section->sr_coded_error += frame->sr_coded_error;
133 section->pcnt_inter += frame->pcnt_inter;
134 section->pcnt_motion += frame->pcnt_motion;
135 section->pcnt_second_ref += frame->pcnt_second_ref;
136 section->pcnt_neutral += frame->pcnt_neutral;
137 section->intra_skip_pct += frame->intra_skip_pct;
138 section->inactive_zone_rows += frame->inactive_zone_rows;
139 section->inactive_zone_cols += frame->inactive_zone_cols;
140 section->MVr += frame->MVr;
141 section->mvr_abs += frame->mvr_abs;
142 section->MVc += frame->MVc;
143 section->mvc_abs += frame->mvc_abs;
144 section->MVrv += frame->MVrv;
145 section->MVcv += frame->MVcv;
146 section->mv_in_out_count += frame->mv_in_out_count;
147 section->new_mv_count += frame->new_mv_count;
148 section->count += frame->count;
149 section->duration += frame->duration;
150 }
151
get_unit_rows(const BLOCK_SIZE fp_block_size,const int mb_rows)152 static int get_unit_rows(const BLOCK_SIZE fp_block_size, const int mb_rows) {
153 const int height_mi_log2 = mi_size_high_log2[fp_block_size];
154 const int mb_height_mi_log2 = mi_size_high_log2[BLOCK_16X16];
155 if (height_mi_log2 > mb_height_mi_log2) {
156 return mb_rows >> (height_mi_log2 - mb_height_mi_log2);
157 }
158
159 return mb_rows << (mb_height_mi_log2 - height_mi_log2);
160 }
161
get_unit_cols(const BLOCK_SIZE fp_block_size,const int mb_cols)162 static int get_unit_cols(const BLOCK_SIZE fp_block_size, const int mb_cols) {
163 const int width_mi_log2 = mi_size_wide_log2[fp_block_size];
164 const int mb_width_mi_log2 = mi_size_wide_log2[BLOCK_16X16];
165 if (width_mi_log2 > mb_width_mi_log2) {
166 return mb_cols >> (width_mi_log2 - mb_width_mi_log2);
167 }
168
169 return mb_cols << (mb_width_mi_log2 - width_mi_log2);
170 }
171
172 // TODO(chengchen): can we simplify it even if resize has to be considered?
get_num_mbs(const BLOCK_SIZE fp_block_size,const int num_mbs_16X16)173 static int get_num_mbs(const BLOCK_SIZE fp_block_size,
174 const int num_mbs_16X16) {
175 const int width_mi_log2 = mi_size_wide_log2[fp_block_size];
176 const int height_mi_log2 = mi_size_high_log2[fp_block_size];
177 const int mb_width_mi_log2 = mi_size_wide_log2[BLOCK_16X16];
178 const int mb_height_mi_log2 = mi_size_high_log2[BLOCK_16X16];
179 // TODO(chengchen): Now this function assumes a square block is used.
180 // It does not support rectangular block sizes.
181 assert(width_mi_log2 == height_mi_log2);
182 if (width_mi_log2 > mb_width_mi_log2) {
183 return num_mbs_16X16 >> ((width_mi_log2 - mb_width_mi_log2) +
184 (height_mi_log2 - mb_height_mi_log2));
185 }
186
187 return num_mbs_16X16 << ((mb_width_mi_log2 - width_mi_log2) +
188 (mb_height_mi_log2 - height_mi_log2));
189 }
190
av1_end_first_pass(AV1_COMP * cpi)191 void av1_end_first_pass(AV1_COMP *cpi) {
192 if (cpi->ppi->twopass.stats_buf_ctx->total_stats && !cpi->ppi->lap_enabled)
193 output_stats(cpi->ppi->twopass.stats_buf_ctx->total_stats,
194 cpi->ppi->output_pkt_list);
195 }
196
get_block_variance_fn(BLOCK_SIZE bsize)197 static aom_variance_fn_t get_block_variance_fn(BLOCK_SIZE bsize) {
198 switch (bsize) {
199 case BLOCK_8X8: return aom_mse8x8;
200 case BLOCK_16X8: return aom_mse16x8;
201 case BLOCK_8X16: return aom_mse8x16;
202 default: return aom_mse16x16;
203 }
204 }
205
get_prediction_error(BLOCK_SIZE bsize,const struct buf_2d * src,const struct buf_2d * ref)206 static unsigned int get_prediction_error(BLOCK_SIZE bsize,
207 const struct buf_2d *src,
208 const struct buf_2d *ref) {
209 unsigned int sse;
210 const aom_variance_fn_t fn = get_block_variance_fn(bsize);
211 fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
212 return sse;
213 }
214
215 #if CONFIG_AV1_HIGHBITDEPTH
highbd_get_block_variance_fn(BLOCK_SIZE bsize,int bd)216 static aom_variance_fn_t highbd_get_block_variance_fn(BLOCK_SIZE bsize,
217 int bd) {
218 switch (bd) {
219 default:
220 switch (bsize) {
221 case BLOCK_8X8: return aom_highbd_8_mse8x8;
222 case BLOCK_16X8: return aom_highbd_8_mse16x8;
223 case BLOCK_8X16: return aom_highbd_8_mse8x16;
224 default: return aom_highbd_8_mse16x16;
225 }
226 case 10:
227 switch (bsize) {
228 case BLOCK_8X8: return aom_highbd_10_mse8x8;
229 case BLOCK_16X8: return aom_highbd_10_mse16x8;
230 case BLOCK_8X16: return aom_highbd_10_mse8x16;
231 default: return aom_highbd_10_mse16x16;
232 }
233 case 12:
234 switch (bsize) {
235 case BLOCK_8X8: return aom_highbd_12_mse8x8;
236 case BLOCK_16X8: return aom_highbd_12_mse16x8;
237 case BLOCK_8X16: return aom_highbd_12_mse8x16;
238 default: return aom_highbd_12_mse16x16;
239 }
240 }
241 }
242
highbd_get_prediction_error(BLOCK_SIZE bsize,const struct buf_2d * src,const struct buf_2d * ref,int bd)243 static unsigned int highbd_get_prediction_error(BLOCK_SIZE bsize,
244 const struct buf_2d *src,
245 const struct buf_2d *ref,
246 int bd) {
247 unsigned int sse;
248 const aom_variance_fn_t fn = highbd_get_block_variance_fn(bsize, bd);
249 fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
250 return sse;
251 }
252 #endif // CONFIG_AV1_HIGHBITDEPTH
253
254 // Refine the motion search range according to the frame dimension
255 // for first pass test.
get_search_range(int width,int height)256 static int get_search_range(int width, int height) {
257 int sr = 0;
258 const int dim = AOMMIN(width, height);
259
260 while ((dim << sr) < MAX_FULL_PEL_VAL) ++sr;
261 return sr;
262 }
263
264 static AOM_INLINE const search_site_config *
av1_get_first_pass_search_site_config(const AV1_COMP * cpi,MACROBLOCK * x,SEARCH_METHODS search_method)265 av1_get_first_pass_search_site_config(const AV1_COMP *cpi, MACROBLOCK *x,
266 SEARCH_METHODS search_method) {
267 const int ref_stride = x->e_mbd.plane[0].pre[0].stride;
268
269 // For AVIF applications, even the source frames can have changing resolution,
270 // so we need to manually check for the strides :(
271 // AV1_COMP::mv_search_params.search_site_config is a compressor level cache
272 // that's shared by multiple threads. In most cases where all frames have the
273 // same resolution, the cache contains the search site config that we need.
274 const MotionVectorSearchParams *mv_search_params = &cpi->mv_search_params;
275 if (ref_stride == mv_search_params->search_site_cfg[SS_CFG_FPF]->stride) {
276 return mv_search_params->search_site_cfg[SS_CFG_FPF];
277 }
278
279 // If the cache does not contain the correct stride, then we will need to rely
280 // on the thread level config MACROBLOCK::search_site_cfg_buf. If even the
281 // thread level config doesn't match, then we need to update it.
282 search_method = search_method_lookup[search_method];
283 assert(search_method_lookup[search_method] == search_method &&
284 "The search_method_lookup table should be idempotent.");
285 if (ref_stride != x->search_site_cfg_buf[search_method].stride) {
286 av1_refresh_search_site_config(x->search_site_cfg_buf, search_method,
287 ref_stride);
288 }
289
290 return x->search_site_cfg_buf;
291 }
292
first_pass_motion_search(AV1_COMP * cpi,MACROBLOCK * x,const MV * ref_mv,FULLPEL_MV * best_mv,int * best_motion_err)293 static AOM_INLINE void first_pass_motion_search(AV1_COMP *cpi, MACROBLOCK *x,
294 const MV *ref_mv,
295 FULLPEL_MV *best_mv,
296 int *best_motion_err) {
297 AV1_COMMON *const cm = &cpi->common;
298 MACROBLOCKD *const xd = &x->e_mbd;
299 FULLPEL_MV start_mv = get_fullmv_from_mv(ref_mv);
300 int tmp_err;
301 const BLOCK_SIZE bsize = xd->mi[0]->bsize;
302 const int new_mv_mode_penalty = NEW_MV_MODE_PENALTY;
303 const int sr = get_search_range(cm->width, cm->height);
304 const int step_param = cpi->sf.fp_sf.reduce_mv_step_param + sr;
305
306 const search_site_config *first_pass_search_sites =
307 av1_get_first_pass_search_site_config(cpi, x, NSTEP);
308 const int fine_search_interval =
309 cpi->is_screen_content_type && cm->features.allow_intrabc;
310 FULLPEL_MOTION_SEARCH_PARAMS ms_params;
311 av1_make_default_fullpel_ms_params(&ms_params, cpi, x, bsize, ref_mv,
312 start_mv, first_pass_search_sites, NSTEP,
313 fine_search_interval);
314
315 FULLPEL_MV this_best_mv;
316 FULLPEL_MV_STATS best_mv_stats;
317 tmp_err = av1_full_pixel_search(start_mv, &ms_params, step_param, NULL,
318 &this_best_mv, &best_mv_stats, NULL);
319
320 if (tmp_err < INT_MAX) {
321 aom_variance_fn_ptr_t v_fn_ptr = cpi->ppi->fn_ptr[bsize];
322 const MSBuffers *ms_buffers = &ms_params.ms_buffers;
323 tmp_err = av1_get_mvpred_sse(&ms_params.mv_cost_params, this_best_mv,
324 &v_fn_ptr, ms_buffers->src, ms_buffers->ref) +
325 new_mv_mode_penalty;
326 }
327
328 if (tmp_err < *best_motion_err) {
329 *best_motion_err = tmp_err;
330 *best_mv = this_best_mv;
331 }
332 }
333
get_bsize(const CommonModeInfoParams * const mi_params,const BLOCK_SIZE fp_block_size,const int unit_row,const int unit_col)334 static BLOCK_SIZE get_bsize(const CommonModeInfoParams *const mi_params,
335 const BLOCK_SIZE fp_block_size, const int unit_row,
336 const int unit_col) {
337 const int unit_width = mi_size_wide[fp_block_size];
338 const int unit_height = mi_size_high[fp_block_size];
339 const int is_half_width =
340 unit_width * unit_col + unit_width / 2 >= mi_params->mi_cols;
341 const int is_half_height =
342 unit_height * unit_row + unit_height / 2 >= mi_params->mi_rows;
343 const int max_dimension =
344 AOMMAX(block_size_wide[fp_block_size], block_size_high[fp_block_size]);
345 int square_block_size = 0;
346 // 4X4, 8X8, 16X16, 32X32, 64X64, 128X128
347 switch (max_dimension) {
348 case 4: square_block_size = 0; break;
349 case 8: square_block_size = 1; break;
350 case 16: square_block_size = 2; break;
351 case 32: square_block_size = 3; break;
352 case 64: square_block_size = 4; break;
353 case 128: square_block_size = 5; break;
354 default: assert(0 && "First pass block size is not supported!"); break;
355 }
356 if (is_half_width && is_half_height) {
357 return subsize_lookup[PARTITION_SPLIT][square_block_size];
358 } else if (is_half_width) {
359 return subsize_lookup[PARTITION_VERT][square_block_size];
360 } else if (is_half_height) {
361 return subsize_lookup[PARTITION_HORZ][square_block_size];
362 } else {
363 return fp_block_size;
364 }
365 }
366
find_fp_qindex(aom_bit_depth_t bit_depth)367 static int find_fp_qindex(aom_bit_depth_t bit_depth) {
368 return av1_find_qindex(FIRST_PASS_Q, bit_depth, 0, QINDEX_RANGE - 1);
369 }
370
raw_motion_error_stdev(int * raw_motion_err_list,int raw_motion_err_counts)371 static double raw_motion_error_stdev(int *raw_motion_err_list,
372 int raw_motion_err_counts) {
373 int64_t sum_raw_err = 0;
374 double raw_err_avg = 0;
375 double raw_err_stdev = 0;
376 if (raw_motion_err_counts == 0) return 0;
377
378 int i;
379 for (i = 0; i < raw_motion_err_counts; i++) {
380 sum_raw_err += raw_motion_err_list[i];
381 }
382 raw_err_avg = (double)sum_raw_err / raw_motion_err_counts;
383 for (i = 0; i < raw_motion_err_counts; i++) {
384 raw_err_stdev += (raw_motion_err_list[i] - raw_err_avg) *
385 (raw_motion_err_list[i] - raw_err_avg);
386 }
387 // Calculate the standard deviation for the motion error of all the inter
388 // blocks of the 0,0 motion using the last source
389 // frame as the reference.
390 raw_err_stdev = sqrt(raw_err_stdev / raw_motion_err_counts);
391 return raw_err_stdev;
392 }
393
calc_wavelet_energy(const AV1EncoderConfig * oxcf)394 static AOM_INLINE int calc_wavelet_energy(const AV1EncoderConfig *oxcf) {
395 return oxcf->q_cfg.deltaq_mode == DELTA_Q_PERCEPTUAL;
396 }
397 typedef struct intra_pred_block_pass1_args {
398 const SequenceHeader *seq_params;
399 MACROBLOCK *x;
400 } intra_pred_block_pass1_args;
401
copy_rect(uint8_t * dst,int dstride,const uint8_t * src,int sstride,int width,int height,int use_hbd)402 static INLINE void copy_rect(uint8_t *dst, int dstride, const uint8_t *src,
403 int sstride, int width, int height, int use_hbd) {
404 #if CONFIG_AV1_HIGHBITDEPTH
405 if (use_hbd) {
406 aom_highbd_convolve_copy(CONVERT_TO_SHORTPTR(src), sstride,
407 CONVERT_TO_SHORTPTR(dst), dstride, width, height);
408 } else {
409 aom_convolve_copy(src, sstride, dst, dstride, width, height);
410 }
411 #else
412 (void)use_hbd;
413 aom_convolve_copy(src, sstride, dst, dstride, width, height);
414 #endif
415 }
416
first_pass_intra_pred_and_calc_diff(int plane,int block,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,void * arg)417 static void first_pass_intra_pred_and_calc_diff(int plane, int block,
418 int blk_row, int blk_col,
419 BLOCK_SIZE plane_bsize,
420 TX_SIZE tx_size, void *arg) {
421 (void)block;
422 struct intra_pred_block_pass1_args *const args = arg;
423 MACROBLOCK *const x = args->x;
424 MACROBLOCKD *const xd = &x->e_mbd;
425 MACROBLOCKD_PLANE *const pd = &xd->plane[plane];
426 MACROBLOCK_PLANE *const p = &x->plane[plane];
427 const int dst_stride = pd->dst.stride;
428 uint8_t *dst = &pd->dst.buf[(blk_row * dst_stride + blk_col) << MI_SIZE_LOG2];
429 const MB_MODE_INFO *const mbmi = xd->mi[0];
430 const SequenceHeader *seq_params = args->seq_params;
431 const int src_stride = p->src.stride;
432 uint8_t *src = &p->src.buf[(blk_row * src_stride + blk_col) << MI_SIZE_LOG2];
433
434 av1_predict_intra_block(
435 xd, seq_params->sb_size, seq_params->enable_intra_edge_filter, pd->width,
436 pd->height, tx_size, mbmi->mode, 0, 0, FILTER_INTRA_MODES, src,
437 src_stride, dst, dst_stride, blk_col, blk_row, plane);
438
439 av1_subtract_txb(x, plane, plane_bsize, blk_col, blk_row, tx_size);
440 }
441
first_pass_predict_intra_block_for_luma_plane(const SequenceHeader * seq_params,MACROBLOCK * x,BLOCK_SIZE bsize)442 static void first_pass_predict_intra_block_for_luma_plane(
443 const SequenceHeader *seq_params, MACROBLOCK *x, BLOCK_SIZE bsize) {
444 assert(bsize < BLOCK_SIZES_ALL);
445 const MACROBLOCKD *const xd = &x->e_mbd;
446 const int plane = AOM_PLANE_Y;
447 const MACROBLOCKD_PLANE *const pd = &xd->plane[plane];
448 const int ss_x = pd->subsampling_x;
449 const int ss_y = pd->subsampling_y;
450 const BLOCK_SIZE plane_bsize = get_plane_block_size(bsize, ss_x, ss_y);
451 const int dst_stride = pd->dst.stride;
452 uint8_t *dst = pd->dst.buf;
453 const MACROBLOCK_PLANE *const p = &x->plane[plane];
454 const int src_stride = p->src.stride;
455 const uint8_t *src = p->src.buf;
456
457 intra_pred_block_pass1_args args = { seq_params, x };
458 av1_foreach_transformed_block_in_plane(
459 xd, plane_bsize, plane, first_pass_intra_pred_and_calc_diff, &args);
460
461 // copy source data to recon buffer, as the recon buffer will be used as a
462 // reference frame subsequently.
463 copy_rect(dst, dst_stride, src, src_stride, block_size_wide[bsize],
464 block_size_high[bsize], seq_params->use_highbitdepth);
465 }
466
467 #define UL_INTRA_THRESH 50
468 #define INVALID_ROW -1
469 // Computes and returns the intra pred error of a block.
470 // intra pred error: sum of squared error of the intra predicted residual.
471 // Inputs:
472 // cpi: the encoder setting. Only a few params in it will be used.
473 // this_frame: the current frame buffer.
474 // tile: tile information (not used in first pass, already init to zero)
475 // unit_row: row index in the unit of first pass block size.
476 // unit_col: column index in the unit of first pass block size.
477 // y_offset: the offset of y frame buffer, indicating the starting point of
478 // the current block.
479 // uv_offset: the offset of u and v frame buffer, indicating the starting
480 // point of the current block.
481 // fp_block_size: first pass block size.
482 // qindex: quantization step size to encode the frame.
483 // stats: frame encoding stats.
484 // Modifies:
485 // stats->intra_skip_count
486 // stats->image_data_start_row
487 // stats->intra_factor
488 // stats->brightness_factor
489 // stats->intra_error
490 // stats->frame_avg_wavelet_energy
491 // Returns:
492 // this_intra_error.
firstpass_intra_prediction(AV1_COMP * cpi,ThreadData * td,YV12_BUFFER_CONFIG * const this_frame,const TileInfo * const tile,const int unit_row,const int unit_col,const int y_offset,const int uv_offset,const BLOCK_SIZE fp_block_size,const int qindex,FRAME_STATS * const stats)493 static int firstpass_intra_prediction(
494 AV1_COMP *cpi, ThreadData *td, YV12_BUFFER_CONFIG *const this_frame,
495 const TileInfo *const tile, const int unit_row, const int unit_col,
496 const int y_offset, const int uv_offset, const BLOCK_SIZE fp_block_size,
497 const int qindex, FRAME_STATS *const stats) {
498 const AV1_COMMON *const cm = &cpi->common;
499 const CommonModeInfoParams *const mi_params = &cm->mi_params;
500 const SequenceHeader *const seq_params = cm->seq_params;
501 MACROBLOCK *const x = &td->mb;
502 MACROBLOCKD *const xd = &x->e_mbd;
503 const int unit_scale = mi_size_wide[fp_block_size];
504 const int num_planes = av1_num_planes(cm);
505 const BLOCK_SIZE bsize =
506 get_bsize(mi_params, fp_block_size, unit_row, unit_col);
507
508 set_mi_offsets(mi_params, xd, unit_row * unit_scale, unit_col * unit_scale);
509 xd->plane[0].dst.buf = this_frame->y_buffer + y_offset;
510 if (num_planes > 1) {
511 xd->plane[1].dst.buf = this_frame->u_buffer + uv_offset;
512 xd->plane[2].dst.buf = this_frame->v_buffer + uv_offset;
513 }
514 xd->left_available = (unit_col != 0);
515 xd->mi[0]->bsize = bsize;
516 xd->mi[0]->ref_frame[0] = INTRA_FRAME;
517 set_mi_row_col(xd, tile, unit_row * unit_scale, mi_size_high[bsize],
518 unit_col * unit_scale, mi_size_wide[bsize], mi_params->mi_rows,
519 mi_params->mi_cols);
520 set_plane_n4(xd, mi_size_wide[bsize], mi_size_high[bsize], num_planes);
521 xd->mi[0]->segment_id = 0;
522 xd->lossless[xd->mi[0]->segment_id] = (qindex == 0);
523 xd->mi[0]->mode = DC_PRED;
524 xd->mi[0]->tx_size = TX_4X4;
525
526 if (cpi->sf.fp_sf.disable_recon)
527 first_pass_predict_intra_block_for_luma_plane(seq_params, x, bsize);
528 else
529 av1_encode_intra_block_plane(cpi, x, bsize, 0, DRY_RUN_NORMAL, 0);
530 int this_intra_error = aom_get_mb_ss(x->plane[0].src_diff);
531 if (seq_params->use_highbitdepth) {
532 switch (seq_params->bit_depth) {
533 case AOM_BITS_8: break;
534 case AOM_BITS_10: this_intra_error >>= 4; break;
535 case AOM_BITS_12: this_intra_error >>= 8; break;
536 default:
537 assert(0 &&
538 "seq_params->bit_depth should be AOM_BITS_8, "
539 "AOM_BITS_10 or AOM_BITS_12");
540 return -1;
541 }
542 }
543
544 if (this_intra_error < UL_INTRA_THRESH) {
545 ++stats->intra_skip_count;
546 } else if ((unit_col > 0) && (stats->image_data_start_row == INVALID_ROW)) {
547 stats->image_data_start_row = unit_row;
548 }
549
550 double log_intra = log1p(this_intra_error);
551 if (log_intra < 10.0) {
552 stats->intra_factor += 1.0 + ((10.0 - log_intra) * 0.05);
553 } else {
554 stats->intra_factor += 1.0;
555 }
556
557 int level_sample;
558 if (seq_params->use_highbitdepth) {
559 level_sample = CONVERT_TO_SHORTPTR(x->plane[0].src.buf)[0];
560 } else {
561 level_sample = x->plane[0].src.buf[0];
562 }
563
564 if (seq_params->use_highbitdepth) {
565 switch (seq_params->bit_depth) {
566 case AOM_BITS_8: break;
567 case AOM_BITS_10: level_sample >>= 2; break;
568 case AOM_BITS_12: level_sample >>= 4; break;
569 default:
570 assert(0 &&
571 "seq_params->bit_depth should be AOM_BITS_8, "
572 "AOM_BITS_10 or AOM_BITS_12");
573 return -1;
574 }
575 }
576 if ((level_sample < DARK_THRESH) && (log_intra < 9.0)) {
577 stats->brightness_factor += 1.0 + (0.01 * (DARK_THRESH - level_sample));
578 } else {
579 stats->brightness_factor += 1.0;
580 }
581
582 // Intrapenalty below deals with situations where the intra and inter
583 // error scores are very low (e.g. a plain black frame).
584 // We do not have special cases in first pass for 0,0 and nearest etc so
585 // all inter modes carry an overhead cost estimate for the mv.
586 // When the error score is very low this causes us to pick all or lots of
587 // INTRA modes and throw lots of key frames.
588 // This penalty adds a cost matching that of a 0,0 mv to the intra case.
589 this_intra_error += INTRA_MODE_PENALTY;
590
591 // Accumulate the intra error.
592 stats->intra_error += (int64_t)this_intra_error;
593
594 // Stats based on wavelet energy is used in the following cases :
595 // 1. ML model which predicts if a flat structure (golden-frame only structure
596 // without ALT-REF and Internal-ARFs) is better. This ML model is enabled in
597 // constant quality mode under certain conditions.
598 // 2. Delta qindex mode is set as DELTA_Q_PERCEPTUAL.
599 // Thus, wavelet energy calculation is enabled for the above cases.
600 if (calc_wavelet_energy(&cpi->oxcf)) {
601 const int hbd = is_cur_buf_hbd(xd);
602 const int stride = x->plane[0].src.stride;
603 const int num_8x8_rows = block_size_high[fp_block_size] / 8;
604 const int num_8x8_cols = block_size_wide[fp_block_size] / 8;
605 const uint8_t *buf = x->plane[0].src.buf;
606 stats->frame_avg_wavelet_energy += av1_haar_ac_sad_mxn_uint8_input(
607 buf, stride, hbd, num_8x8_rows, num_8x8_cols);
608 } else {
609 stats->frame_avg_wavelet_energy = INVALID_FP_STATS_TO_PREDICT_FLAT_GOP;
610 }
611
612 return this_intra_error;
613 }
614
615 // Returns the sum of square error between source and reference blocks.
get_prediction_error_bitdepth(const int is_high_bitdepth,const int bitdepth,const BLOCK_SIZE block_size,const struct buf_2d * src,const struct buf_2d * ref)616 static int get_prediction_error_bitdepth(const int is_high_bitdepth,
617 const int bitdepth,
618 const BLOCK_SIZE block_size,
619 const struct buf_2d *src,
620 const struct buf_2d *ref) {
621 (void)is_high_bitdepth;
622 (void)bitdepth;
623 #if CONFIG_AV1_HIGHBITDEPTH
624 if (is_high_bitdepth) {
625 return highbd_get_prediction_error(block_size, src, ref, bitdepth);
626 }
627 #endif // CONFIG_AV1_HIGHBITDEPTH
628 return get_prediction_error(block_size, src, ref);
629 }
630
631 // Accumulates motion vector stats.
632 // Modifies member variables of "stats".
accumulate_mv_stats(const MV best_mv,const FULLPEL_MV mv,const int mb_row,const int mb_col,const int mb_rows,const int mb_cols,MV * last_non_zero_mv,FRAME_STATS * stats)633 static void accumulate_mv_stats(const MV best_mv, const FULLPEL_MV mv,
634 const int mb_row, const int mb_col,
635 const int mb_rows, const int mb_cols,
636 MV *last_non_zero_mv, FRAME_STATS *stats) {
637 if (is_zero_mv(&best_mv)) return;
638
639 ++stats->mv_count;
640 // Non-zero vector, was it different from the last non zero vector?
641 if (!is_equal_mv(&best_mv, last_non_zero_mv)) ++stats->new_mv_count;
642 *last_non_zero_mv = best_mv;
643
644 // Does the row vector point inwards or outwards?
645 if (mb_row < mb_rows / 2) {
646 if (mv.row > 0) {
647 --stats->sum_in_vectors;
648 } else if (mv.row < 0) {
649 ++stats->sum_in_vectors;
650 }
651 } else if (mb_row > mb_rows / 2) {
652 if (mv.row > 0) {
653 ++stats->sum_in_vectors;
654 } else if (mv.row < 0) {
655 --stats->sum_in_vectors;
656 }
657 }
658
659 // Does the col vector point inwards or outwards?
660 if (mb_col < mb_cols / 2) {
661 if (mv.col > 0) {
662 --stats->sum_in_vectors;
663 } else if (mv.col < 0) {
664 ++stats->sum_in_vectors;
665 }
666 } else if (mb_col > mb_cols / 2) {
667 if (mv.col > 0) {
668 ++stats->sum_in_vectors;
669 } else if (mv.col < 0) {
670 --stats->sum_in_vectors;
671 }
672 }
673 }
674
675 // Computes and returns the inter prediction error from the last frame.
676 // Computes inter prediction errors from the golden and alt ref frams and
677 // Updates stats accordingly.
678 // Inputs:
679 // cpi: the encoder setting. Only a few params in it will be used.
680 // last_frame: the frame buffer of the last frame.
681 // golden_frame: the frame buffer of the golden frame.
682 // unit_row: row index in the unit of first pass block size.
683 // unit_col: column index in the unit of first pass block size.
684 // recon_yoffset: the y offset of the reconstructed frame buffer,
685 // indicating the starting point of the current block.
686 // recont_uvoffset: the u/v offset of the reconstructed frame buffer,
687 // indicating the starting point of the current block.
688 // src_yoffset: the y offset of the source frame buffer.
689 // fp_block_size: first pass block size.
690 // this_intra_error: the intra prediction error of this block.
691 // raw_motion_err_counts: the count of raw motion vectors.
692 // raw_motion_err_list: the array that records the raw motion error.
693 // ref_mv: the reference used to start the motion search
694 // best_mv: the best mv found
695 // last_non_zero_mv: the last non zero mv found in this tile row.
696 // stats: frame encoding stats.
697 // Modifies:
698 // raw_motion_err_list
699 // best_ref_mv
700 // last_mv
701 // stats: many member params in it.
702 // Returns:
703 // this_inter_error
firstpass_inter_prediction(AV1_COMP * cpi,ThreadData * td,const YV12_BUFFER_CONFIG * const last_frame,const YV12_BUFFER_CONFIG * const golden_frame,const int unit_row,const int unit_col,const int recon_yoffset,const int recon_uvoffset,const int src_yoffset,const BLOCK_SIZE fp_block_size,const int this_intra_error,const int raw_motion_err_counts,int * raw_motion_err_list,const MV ref_mv,MV * best_mv,MV * last_non_zero_mv,FRAME_STATS * stats)704 static int firstpass_inter_prediction(
705 AV1_COMP *cpi, ThreadData *td, const YV12_BUFFER_CONFIG *const last_frame,
706 const YV12_BUFFER_CONFIG *const golden_frame, const int unit_row,
707 const int unit_col, const int recon_yoffset, const int recon_uvoffset,
708 const int src_yoffset, const BLOCK_SIZE fp_block_size,
709 const int this_intra_error, const int raw_motion_err_counts,
710 int *raw_motion_err_list, const MV ref_mv, MV *best_mv,
711 MV *last_non_zero_mv, FRAME_STATS *stats) {
712 int this_inter_error = this_intra_error;
713 AV1_COMMON *const cm = &cpi->common;
714 const CommonModeInfoParams *const mi_params = &cm->mi_params;
715 CurrentFrame *const current_frame = &cm->current_frame;
716 MACROBLOCK *const x = &td->mb;
717 MACROBLOCKD *const xd = &x->e_mbd;
718 const int is_high_bitdepth = is_cur_buf_hbd(xd);
719 const int bitdepth = xd->bd;
720 const int unit_scale = mi_size_wide[fp_block_size];
721 const BLOCK_SIZE bsize =
722 get_bsize(mi_params, fp_block_size, unit_row, unit_col);
723 const int fp_block_size_height = block_size_wide[fp_block_size];
724 const int unit_width = mi_size_wide[fp_block_size];
725 const int unit_rows = get_unit_rows(fp_block_size, mi_params->mb_rows);
726 const int unit_cols = get_unit_cols(fp_block_size, mi_params->mb_cols);
727 // Assume 0,0 motion with no mv overhead.
728 FULLPEL_MV mv = kZeroFullMv;
729 xd->plane[0].pre[0].buf = last_frame->y_buffer + recon_yoffset;
730 // Set up limit values for motion vectors to prevent them extending
731 // outside the UMV borders.
732 av1_set_mv_col_limits(mi_params, &x->mv_limits, unit_col * unit_width,
733 fp_block_size_height >> MI_SIZE_LOG2,
734 cpi->oxcf.border_in_pixels);
735
736 int motion_error =
737 get_prediction_error_bitdepth(is_high_bitdepth, bitdepth, bsize,
738 &x->plane[0].src, &xd->plane[0].pre[0]);
739
740 // Compute the motion error of the 0,0 motion using the last source
741 // frame as the reference. Skip the further motion search on
742 // reconstructed frame if this error is small.
743 // TODO(chiyotsai): The unscaled last source might be different dimension
744 // as the current source. See BUG=aomedia:3413
745 struct buf_2d unscaled_last_source_buf_2d;
746 unscaled_last_source_buf_2d.buf =
747 cpi->unscaled_last_source->y_buffer + src_yoffset;
748 unscaled_last_source_buf_2d.stride = cpi->unscaled_last_source->y_stride;
749 const int raw_motion_error = get_prediction_error_bitdepth(
750 is_high_bitdepth, bitdepth, bsize, &x->plane[0].src,
751 &unscaled_last_source_buf_2d);
752 raw_motion_err_list[raw_motion_err_counts] = raw_motion_error;
753 const FIRST_PASS_SPEED_FEATURES *const fp_sf = &cpi->sf.fp_sf;
754
755 if (raw_motion_error > fp_sf->skip_motion_search_threshold) {
756 // Test last reference frame using the previous best mv as the
757 // starting point (best reference) for the search.
758 first_pass_motion_search(cpi, x, &ref_mv, &mv, &motion_error);
759
760 // If the current best reference mv is not centered on 0,0 then do a
761 // 0,0 based search as well.
762 if ((fp_sf->skip_zeromv_motion_search == 0) && !is_zero_mv(&ref_mv)) {
763 FULLPEL_MV tmp_mv = kZeroFullMv;
764 int tmp_err = INT_MAX;
765 first_pass_motion_search(cpi, x, &kZeroMv, &tmp_mv, &tmp_err);
766
767 if (tmp_err < motion_error) {
768 motion_error = tmp_err;
769 mv = tmp_mv;
770 }
771 }
772 }
773
774 // Motion search in 2nd reference frame.
775 int gf_motion_error = motion_error;
776 if ((current_frame->frame_number > 1) && golden_frame != NULL) {
777 FULLPEL_MV tmp_mv = kZeroFullMv;
778 // Assume 0,0 motion with no mv overhead.
779 av1_setup_pre_planes(xd, 0, golden_frame, 0, 0, NULL, 1);
780 xd->plane[0].pre[0].buf += recon_yoffset;
781 gf_motion_error =
782 get_prediction_error_bitdepth(is_high_bitdepth, bitdepth, bsize,
783 &x->plane[0].src, &xd->plane[0].pre[0]);
784 first_pass_motion_search(cpi, x, &kZeroMv, &tmp_mv, &gf_motion_error);
785 }
786 if (gf_motion_error < motion_error && gf_motion_error < this_intra_error) {
787 ++stats->second_ref_count;
788 }
789 // In accumulating a score for the 2nd reference frame take the
790 // best of the motion predicted score and the intra coded error
791 // (just as will be done for) accumulation of "coded_error" for
792 // the last frame.
793 if ((current_frame->frame_number > 1) && golden_frame != NULL) {
794 stats->sr_coded_error += AOMMIN(gf_motion_error, this_intra_error);
795 } else {
796 // TODO(chengchen): I believe logically this should also be changed to
797 // stats->sr_coded_error += AOMMIN(gf_motion_error, this_intra_error).
798 stats->sr_coded_error += motion_error;
799 }
800
801 // Reset to last frame as reference buffer.
802 xd->plane[0].pre[0].buf = last_frame->y_buffer + recon_yoffset;
803 if (av1_num_planes(&cpi->common) > 1) {
804 xd->plane[1].pre[0].buf = last_frame->u_buffer + recon_uvoffset;
805 xd->plane[2].pre[0].buf = last_frame->v_buffer + recon_uvoffset;
806 }
807
808 // Start by assuming that intra mode is best.
809 *best_mv = kZeroMv;
810
811 if (motion_error <= this_intra_error) {
812 // Keep a count of cases where the inter and intra were very close
813 // and very low. This helps with scene cut detection for example in
814 // cropped clips with black bars at the sides or top and bottom.
815 if (((this_intra_error - INTRA_MODE_PENALTY) * 9 <= motion_error * 10) &&
816 (this_intra_error < (2 * INTRA_MODE_PENALTY))) {
817 stats->neutral_count += 1.0;
818 // Also track cases where the intra is not much worse than the inter
819 // and use this in limiting the GF/arf group length.
820 } else if ((this_intra_error > NCOUNT_INTRA_THRESH) &&
821 (this_intra_error < (NCOUNT_INTRA_FACTOR * motion_error))) {
822 stats->neutral_count +=
823 (double)motion_error / DOUBLE_DIVIDE_CHECK((double)this_intra_error);
824 }
825
826 *best_mv = get_mv_from_fullmv(&mv);
827 this_inter_error = motion_error;
828 xd->mi[0]->mode = NEWMV;
829 xd->mi[0]->mv[0].as_mv = *best_mv;
830 xd->mi[0]->tx_size = TX_4X4;
831 xd->mi[0]->ref_frame[0] = LAST_FRAME;
832 xd->mi[0]->ref_frame[1] = NONE_FRAME;
833
834 if (fp_sf->disable_recon == 0) {
835 av1_enc_build_inter_predictor(cm, xd, unit_row * unit_scale,
836 unit_col * unit_scale, NULL, bsize,
837 AOM_PLANE_Y, AOM_PLANE_Y);
838 av1_encode_sby_pass1(cpi, x, bsize);
839 }
840 stats->sum_mvr += best_mv->row;
841 stats->sum_mvr_abs += abs(best_mv->row);
842 stats->sum_mvc += best_mv->col;
843 stats->sum_mvc_abs += abs(best_mv->col);
844 stats->sum_mvrs += best_mv->row * best_mv->row;
845 stats->sum_mvcs += best_mv->col * best_mv->col;
846 ++stats->inter_count;
847
848 accumulate_mv_stats(*best_mv, mv, unit_row, unit_col, unit_rows, unit_cols,
849 last_non_zero_mv, stats);
850 }
851
852 return this_inter_error;
853 }
854
855 // Normalize the first pass stats.
856 // Error / counters are normalized to each MB.
857 // MVs are normalized to the width/height of the frame.
normalize_firstpass_stats(FIRSTPASS_STATS * fps,double num_mbs_16x16,double f_w,double f_h)858 static void normalize_firstpass_stats(FIRSTPASS_STATS *fps,
859 double num_mbs_16x16, double f_w,
860 double f_h) {
861 fps->coded_error /= num_mbs_16x16;
862 fps->sr_coded_error /= num_mbs_16x16;
863 fps->intra_error /= num_mbs_16x16;
864 fps->frame_avg_wavelet_energy /= num_mbs_16x16;
865 fps->log_coded_error = log1p(fps->coded_error);
866 fps->log_intra_error = log1p(fps->intra_error);
867 fps->MVr /= f_h;
868 fps->mvr_abs /= f_h;
869 fps->MVc /= f_w;
870 fps->mvc_abs /= f_w;
871 fps->MVrv /= (f_h * f_h);
872 fps->MVcv /= (f_w * f_w);
873 fps->new_mv_count /= num_mbs_16x16;
874 }
875
876 // Updates the first pass stats of this frame.
877 // Input:
878 // cpi: the encoder setting. Only a few params in it will be used.
879 // stats: stats accumulated for this frame.
880 // raw_err_stdev: the statndard deviation for the motion error of all the
881 // inter blocks of the (0,0) motion using the last source
882 // frame as the reference.
883 // frame_number: current frame number.
884 // ts_duration: Duration of the frame / collection of frames.
885 // Updates:
886 // twopass->total_stats: the accumulated stats.
887 // twopass->stats_buf_ctx->stats_in_end: the pointer to the current stats,
888 // update its value and its position
889 // in the buffer.
update_firstpass_stats(AV1_COMP * cpi,const FRAME_STATS * const stats,const double raw_err_stdev,const int frame_number,const int64_t ts_duration,const BLOCK_SIZE fp_block_size)890 static void update_firstpass_stats(AV1_COMP *cpi,
891 const FRAME_STATS *const stats,
892 const double raw_err_stdev,
893 const int frame_number,
894 const int64_t ts_duration,
895 const BLOCK_SIZE fp_block_size) {
896 TWO_PASS *twopass = &cpi->ppi->twopass;
897 AV1_COMMON *const cm = &cpi->common;
898 const CommonModeInfoParams *const mi_params = &cm->mi_params;
899 FIRSTPASS_STATS *this_frame_stats = twopass->stats_buf_ctx->stats_in_end;
900 FIRSTPASS_STATS fps;
901 // The minimum error here insures some bit allocation to frames even
902 // in static regions. The allocation per MB declines for larger formats
903 // where the typical "real" energy per MB also falls.
904 // Initial estimate here uses sqrt(mbs) to define the min_err, where the
905 // number of mbs is proportional to the image area.
906 const int num_mbs_16X16 = (cpi->oxcf.resize_cfg.resize_mode != RESIZE_NONE)
907 ? cpi->initial_mbs
908 : mi_params->MBs;
909 // Number of actual units used in the first pass, it can be other square
910 // block sizes than 16X16.
911 const int num_mbs = get_num_mbs(fp_block_size, num_mbs_16X16);
912 const double min_err = 200 * sqrt(num_mbs);
913
914 fps.weight = stats->intra_factor * stats->brightness_factor;
915 fps.frame = frame_number;
916 fps.coded_error = (double)(stats->coded_error >> 8) + min_err;
917 fps.sr_coded_error = (double)(stats->sr_coded_error >> 8) + min_err;
918 fps.intra_error = (double)(stats->intra_error >> 8) + min_err;
919 fps.frame_avg_wavelet_energy = (double)stats->frame_avg_wavelet_energy;
920 fps.count = 1.0;
921 fps.pcnt_inter = (double)stats->inter_count / num_mbs;
922 fps.pcnt_second_ref = (double)stats->second_ref_count / num_mbs;
923 fps.pcnt_neutral = (double)stats->neutral_count / num_mbs;
924 fps.intra_skip_pct = (double)stats->intra_skip_count / num_mbs;
925 fps.inactive_zone_rows = (double)stats->image_data_start_row;
926 fps.inactive_zone_cols = 0.0; // Placeholder: not currently supported.
927 fps.raw_error_stdev = raw_err_stdev;
928 fps.is_flash = 0;
929 fps.noise_var = 0.0;
930 fps.cor_coeff = 1.0;
931 fps.log_coded_error = 0.0;
932 fps.log_intra_error = 0.0;
933
934 if (stats->mv_count > 0) {
935 fps.MVr = (double)stats->sum_mvr / stats->mv_count;
936 fps.mvr_abs = (double)stats->sum_mvr_abs / stats->mv_count;
937 fps.MVc = (double)stats->sum_mvc / stats->mv_count;
938 fps.mvc_abs = (double)stats->sum_mvc_abs / stats->mv_count;
939 fps.MVrv = ((double)stats->sum_mvrs -
940 ((double)stats->sum_mvr * stats->sum_mvr / stats->mv_count)) /
941 stats->mv_count;
942 fps.MVcv = ((double)stats->sum_mvcs -
943 ((double)stats->sum_mvc * stats->sum_mvc / stats->mv_count)) /
944 stats->mv_count;
945 fps.mv_in_out_count = (double)stats->sum_in_vectors / (stats->mv_count * 2);
946 fps.new_mv_count = stats->new_mv_count;
947 fps.pcnt_motion = (double)stats->mv_count / num_mbs;
948 } else {
949 fps.MVr = 0.0;
950 fps.mvr_abs = 0.0;
951 fps.MVc = 0.0;
952 fps.mvc_abs = 0.0;
953 fps.MVrv = 0.0;
954 fps.MVcv = 0.0;
955 fps.mv_in_out_count = 0.0;
956 fps.new_mv_count = 0.0;
957 fps.pcnt_motion = 0.0;
958 }
959
960 // TODO(paulwilkins): Handle the case when duration is set to 0, or
961 // something less than the full time between subsequent values of
962 // cpi->source_time_stamp.
963 fps.duration = (double)ts_duration;
964
965 normalize_firstpass_stats(&fps, num_mbs_16X16, cm->width, cm->height);
966
967 // We will store the stats inside the persistent twopass struct (and NOT the
968 // local variable 'fps'), and then cpi->output_pkt_list will point to it.
969 *this_frame_stats = fps;
970 if (!cpi->ppi->lap_enabled) {
971 output_stats(this_frame_stats, cpi->ppi->output_pkt_list);
972 } else {
973 av1_firstpass_info_push(&twopass->firstpass_info, this_frame_stats);
974 }
975 if (cpi->ppi->twopass.stats_buf_ctx->total_stats != NULL) {
976 av1_accumulate_stats(cpi->ppi->twopass.stats_buf_ctx->total_stats, &fps);
977 }
978 twopass->stats_buf_ctx->stats_in_end++;
979 // When ducky encode is on, we always use linear buffer for stats_buf_ctx.
980 if (cpi->use_ducky_encode == 0) {
981 // TODO(angiebird): Figure out why first pass uses circular buffer.
982 /* In the case of two pass, first pass uses it as a circular buffer,
983 * when LAP is enabled it is used as a linear buffer*/
984 if ((cpi->oxcf.pass == AOM_RC_FIRST_PASS) &&
985 (twopass->stats_buf_ctx->stats_in_end >=
986 twopass->stats_buf_ctx->stats_in_buf_end)) {
987 twopass->stats_buf_ctx->stats_in_end =
988 twopass->stats_buf_ctx->stats_in_start;
989 }
990 }
991 }
992
print_reconstruction_frame(const YV12_BUFFER_CONFIG * const last_frame,int frame_number,int do_print)993 static void print_reconstruction_frame(
994 const YV12_BUFFER_CONFIG *const last_frame, int frame_number,
995 int do_print) {
996 if (!do_print) return;
997
998 char filename[512];
999 FILE *recon_file;
1000 snprintf(filename, sizeof(filename), "enc%04d.yuv", frame_number);
1001
1002 if (frame_number == 0) {
1003 recon_file = fopen(filename, "wb");
1004 } else {
1005 recon_file = fopen(filename, "ab");
1006 }
1007
1008 fwrite(last_frame->buffer_alloc, last_frame->frame_size, 1, recon_file);
1009 fclose(recon_file);
1010 }
1011
accumulate_frame_stats(FRAME_STATS * mb_stats,int mb_rows,int mb_cols)1012 static FRAME_STATS accumulate_frame_stats(FRAME_STATS *mb_stats, int mb_rows,
1013 int mb_cols) {
1014 FRAME_STATS stats = { 0 };
1015 int i, j;
1016
1017 stats.image_data_start_row = INVALID_ROW;
1018 for (j = 0; j < mb_rows; j++) {
1019 for (i = 0; i < mb_cols; i++) {
1020 FRAME_STATS mb_stat = mb_stats[j * mb_cols + i];
1021 stats.brightness_factor += mb_stat.brightness_factor;
1022 stats.coded_error += mb_stat.coded_error;
1023 stats.frame_avg_wavelet_energy += mb_stat.frame_avg_wavelet_energy;
1024 if (stats.image_data_start_row == INVALID_ROW &&
1025 mb_stat.image_data_start_row != INVALID_ROW) {
1026 stats.image_data_start_row = mb_stat.image_data_start_row;
1027 }
1028 stats.inter_count += mb_stat.inter_count;
1029 stats.intra_error += mb_stat.intra_error;
1030 stats.intra_factor += mb_stat.intra_factor;
1031 stats.intra_skip_count += mb_stat.intra_skip_count;
1032 stats.mv_count += mb_stat.mv_count;
1033 stats.neutral_count += mb_stat.neutral_count;
1034 stats.new_mv_count += mb_stat.new_mv_count;
1035 stats.second_ref_count += mb_stat.second_ref_count;
1036 stats.sr_coded_error += mb_stat.sr_coded_error;
1037 stats.sum_in_vectors += mb_stat.sum_in_vectors;
1038 stats.sum_mvc += mb_stat.sum_mvc;
1039 stats.sum_mvc_abs += mb_stat.sum_mvc_abs;
1040 stats.sum_mvcs += mb_stat.sum_mvcs;
1041 stats.sum_mvr += mb_stat.sum_mvr;
1042 stats.sum_mvr_abs += mb_stat.sum_mvr_abs;
1043 stats.sum_mvrs += mb_stat.sum_mvrs;
1044 }
1045 }
1046 return stats;
1047 }
1048
setup_firstpass_data(AV1_COMMON * const cm,FirstPassData * firstpass_data,const int unit_rows,const int unit_cols)1049 static void setup_firstpass_data(AV1_COMMON *const cm,
1050 FirstPassData *firstpass_data,
1051 const int unit_rows, const int unit_cols) {
1052 CHECK_MEM_ERROR(cm, firstpass_data->raw_motion_err_list,
1053 aom_calloc(unit_rows * unit_cols,
1054 sizeof(*firstpass_data->raw_motion_err_list)));
1055 CHECK_MEM_ERROR(
1056 cm, firstpass_data->mb_stats,
1057 aom_calloc(unit_rows * unit_cols, sizeof(*firstpass_data->mb_stats)));
1058 for (int j = 0; j < unit_rows; j++) {
1059 for (int i = 0; i < unit_cols; i++) {
1060 firstpass_data->mb_stats[j * unit_cols + i].image_data_start_row =
1061 INVALID_ROW;
1062 }
1063 }
1064 }
1065
av1_free_firstpass_data(FirstPassData * firstpass_data)1066 void av1_free_firstpass_data(FirstPassData *firstpass_data) {
1067 aom_free(firstpass_data->raw_motion_err_list);
1068 firstpass_data->raw_motion_err_list = NULL;
1069 aom_free(firstpass_data->mb_stats);
1070 firstpass_data->mb_stats = NULL;
1071 }
1072
av1_get_unit_rows_in_tile(const TileInfo * tile,const BLOCK_SIZE fp_block_size)1073 int av1_get_unit_rows_in_tile(const TileInfo *tile,
1074 const BLOCK_SIZE fp_block_size) {
1075 const int unit_height_log2 = mi_size_high_log2[fp_block_size];
1076 const int mi_rows = tile->mi_row_end - tile->mi_row_start;
1077 const int unit_rows = CEIL_POWER_OF_TWO(mi_rows, unit_height_log2);
1078
1079 return unit_rows;
1080 }
1081
av1_get_unit_cols_in_tile(const TileInfo * tile,const BLOCK_SIZE fp_block_size)1082 int av1_get_unit_cols_in_tile(const TileInfo *tile,
1083 const BLOCK_SIZE fp_block_size) {
1084 const int unit_width_log2 = mi_size_wide_log2[fp_block_size];
1085 const int mi_cols = tile->mi_col_end - tile->mi_col_start;
1086 const int unit_cols = CEIL_POWER_OF_TWO(mi_cols, unit_width_log2);
1087
1088 return unit_cols;
1089 }
1090
1091 #define FIRST_PASS_ALT_REF_DISTANCE 16
first_pass_tile(AV1_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,const BLOCK_SIZE fp_block_size)1092 static void first_pass_tile(AV1_COMP *cpi, ThreadData *td,
1093 TileDataEnc *tile_data,
1094 const BLOCK_SIZE fp_block_size) {
1095 TileInfo *tile = &tile_data->tile_info;
1096 const int unit_height = mi_size_high[fp_block_size];
1097 const int unit_height_log2 = mi_size_high_log2[fp_block_size];
1098 for (int mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
1099 mi_row += unit_height) {
1100 av1_first_pass_row(cpi, td, tile_data, mi_row >> unit_height_log2,
1101 fp_block_size);
1102 }
1103 }
1104
first_pass_tiles(AV1_COMP * cpi,const BLOCK_SIZE fp_block_size)1105 static void first_pass_tiles(AV1_COMP *cpi, const BLOCK_SIZE fp_block_size) {
1106 AV1_COMMON *const cm = &cpi->common;
1107 const int tile_cols = cm->tiles.cols;
1108 const int tile_rows = cm->tiles.rows;
1109
1110 av1_alloc_src_diff_buf(cm, &cpi->td.mb);
1111 for (int tile_row = 0; tile_row < tile_rows; ++tile_row) {
1112 for (int tile_col = 0; tile_col < tile_cols; ++tile_col) {
1113 TileDataEnc *const tile_data =
1114 &cpi->tile_data[tile_row * tile_cols + tile_col];
1115 first_pass_tile(cpi, &cpi->td, tile_data, fp_block_size);
1116 }
1117 }
1118 }
1119
av1_first_pass_row(AV1_COMP * cpi,ThreadData * td,TileDataEnc * tile_data,const int unit_row,const BLOCK_SIZE fp_block_size)1120 void av1_first_pass_row(AV1_COMP *cpi, ThreadData *td, TileDataEnc *tile_data,
1121 const int unit_row, const BLOCK_SIZE fp_block_size) {
1122 MACROBLOCK *const x = &td->mb;
1123 AV1_COMMON *const cm = &cpi->common;
1124 const CommonModeInfoParams *const mi_params = &cm->mi_params;
1125 const SequenceHeader *const seq_params = cm->seq_params;
1126 const int num_planes = av1_num_planes(cm);
1127 MACROBLOCKD *const xd = &x->e_mbd;
1128 TileInfo *tile = &tile_data->tile_info;
1129 const int qindex = find_fp_qindex(seq_params->bit_depth);
1130 const int fp_block_size_width = block_size_high[fp_block_size];
1131 const int fp_block_size_height = block_size_wide[fp_block_size];
1132 const int unit_width = mi_size_wide[fp_block_size];
1133 const int unit_width_log2 = mi_size_wide_log2[fp_block_size];
1134 const int unit_height_log2 = mi_size_high_log2[fp_block_size];
1135 const int unit_cols = mi_params->mb_cols * 4 / unit_width;
1136 int raw_motion_err_counts = 0;
1137 int unit_row_in_tile = unit_row - (tile->mi_row_start >> unit_height_log2);
1138 int unit_col_start = tile->mi_col_start >> unit_width_log2;
1139 int unit_cols_in_tile = av1_get_unit_cols_in_tile(tile, fp_block_size);
1140 MultiThreadInfo *const mt_info = &cpi->mt_info;
1141 AV1EncRowMultiThreadInfo *const enc_row_mt = &mt_info->enc_row_mt;
1142 AV1EncRowMultiThreadSync *const row_mt_sync = &tile_data->row_mt_sync;
1143
1144 const YV12_BUFFER_CONFIG *last_frame =
1145 av1_get_scaled_ref_frame(cpi, LAST_FRAME);
1146 if (!last_frame) {
1147 last_frame = get_ref_frame_yv12_buf(cm, LAST_FRAME);
1148 }
1149 const YV12_BUFFER_CONFIG *golden_frame =
1150 av1_get_scaled_ref_frame(cpi, GOLDEN_FRAME);
1151 if (!golden_frame) {
1152 golden_frame = get_ref_frame_yv12_buf(cm, GOLDEN_FRAME);
1153 }
1154 YV12_BUFFER_CONFIG *const this_frame = &cm->cur_frame->buf;
1155
1156 PICK_MODE_CONTEXT *ctx = td->firstpass_ctx;
1157 FRAME_STATS *mb_stats =
1158 cpi->firstpass_data.mb_stats + unit_row * unit_cols + unit_col_start;
1159 int *raw_motion_err_list = cpi->firstpass_data.raw_motion_err_list +
1160 unit_row * unit_cols + unit_col_start;
1161 MV *first_top_mv = &tile_data->firstpass_top_mv;
1162
1163 for (int i = 0; i < num_planes; ++i) {
1164 x->plane[i].coeff = ctx->coeff[i];
1165 x->plane[i].qcoeff = ctx->qcoeff[i];
1166 x->plane[i].eobs = ctx->eobs[i];
1167 x->plane[i].txb_entropy_ctx = ctx->txb_entropy_ctx[i];
1168 x->plane[i].dqcoeff = ctx->dqcoeff[i];
1169 }
1170
1171 const int src_y_stride = cpi->source->y_stride;
1172 const int recon_y_stride = this_frame->y_stride;
1173 const int recon_uv_stride = this_frame->uv_stride;
1174 const int uv_mb_height =
1175 fp_block_size_height >> (this_frame->y_height > this_frame->uv_height);
1176
1177 MV best_ref_mv = kZeroMv;
1178 MV last_mv;
1179
1180 // Reset above block coeffs.
1181 xd->up_available = (unit_row_in_tile != 0);
1182 int recon_yoffset = (unit_row * recon_y_stride * fp_block_size_height) +
1183 (unit_col_start * fp_block_size_width);
1184 int src_yoffset = (unit_row * src_y_stride * fp_block_size_height) +
1185 (unit_col_start * fp_block_size_width);
1186 int recon_uvoffset = (unit_row * recon_uv_stride * uv_mb_height) +
1187 (unit_col_start * uv_mb_height);
1188
1189 // Set up limit values for motion vectors to prevent them extending
1190 // outside the UMV borders.
1191 av1_set_mv_row_limits(
1192 mi_params, &x->mv_limits, (unit_row << unit_height_log2),
1193 (fp_block_size_height >> MI_SIZE_LOG2), cpi->oxcf.border_in_pixels);
1194
1195 av1_setup_src_planes(x, cpi->source, unit_row << unit_height_log2,
1196 tile->mi_col_start, num_planes, fp_block_size);
1197
1198 // Fix - zero the 16x16 block first. This ensures correct this_intra_error for
1199 // block sizes smaller than 16x16.
1200 av1_zero_array(x->plane[0].src_diff, 256);
1201
1202 for (int unit_col_in_tile = 0; unit_col_in_tile < unit_cols_in_tile;
1203 unit_col_in_tile++) {
1204 const int unit_col = unit_col_start + unit_col_in_tile;
1205
1206 enc_row_mt->sync_read_ptr(row_mt_sync, unit_row_in_tile, unit_col_in_tile);
1207
1208 #if CONFIG_MULTITHREAD
1209 if (cpi->ppi->p_mt_info.num_workers > 1) {
1210 pthread_mutex_lock(enc_row_mt->mutex_);
1211 bool firstpass_mt_exit = enc_row_mt->firstpass_mt_exit;
1212 pthread_mutex_unlock(enc_row_mt->mutex_);
1213 // Exit in case any worker has encountered an error.
1214 if (firstpass_mt_exit) return;
1215 }
1216 #endif
1217
1218 if (unit_col_in_tile == 0) {
1219 last_mv = *first_top_mv;
1220 }
1221 int this_intra_error = firstpass_intra_prediction(
1222 cpi, td, this_frame, tile, unit_row, unit_col, recon_yoffset,
1223 recon_uvoffset, fp_block_size, qindex, mb_stats);
1224
1225 if (!frame_is_intra_only(cm)) {
1226 const int this_inter_error = firstpass_inter_prediction(
1227 cpi, td, last_frame, golden_frame, unit_row, unit_col, recon_yoffset,
1228 recon_uvoffset, src_yoffset, fp_block_size, this_intra_error,
1229 raw_motion_err_counts, raw_motion_err_list, best_ref_mv, &best_ref_mv,
1230 &last_mv, mb_stats);
1231 if (unit_col_in_tile == 0) {
1232 *first_top_mv = last_mv;
1233 }
1234 mb_stats->coded_error += this_inter_error;
1235 ++raw_motion_err_counts;
1236 } else {
1237 mb_stats->sr_coded_error += this_intra_error;
1238 mb_stats->coded_error += this_intra_error;
1239 }
1240
1241 // Adjust to the next column of MBs.
1242 x->plane[0].src.buf += fp_block_size_width;
1243 if (num_planes > 1) {
1244 x->plane[1].src.buf += uv_mb_height;
1245 x->plane[2].src.buf += uv_mb_height;
1246 }
1247
1248 recon_yoffset += fp_block_size_width;
1249 src_yoffset += fp_block_size_width;
1250 recon_uvoffset += uv_mb_height;
1251 mb_stats++;
1252
1253 enc_row_mt->sync_write_ptr(row_mt_sync, unit_row_in_tile, unit_col_in_tile,
1254 unit_cols_in_tile);
1255 }
1256 }
1257
av1_noop_first_pass_frame(AV1_COMP * cpi,const int64_t ts_duration)1258 void av1_noop_first_pass_frame(AV1_COMP *cpi, const int64_t ts_duration) {
1259 AV1_COMMON *const cm = &cpi->common;
1260 CurrentFrame *const current_frame = &cm->current_frame;
1261 const CommonModeInfoParams *const mi_params = &cm->mi_params;
1262 int max_mb_rows = mi_params->mb_rows;
1263 int max_mb_cols = mi_params->mb_cols;
1264 if (cpi->oxcf.frm_dim_cfg.forced_max_frame_width) {
1265 int max_mi_cols = size_in_mi(cpi->oxcf.frm_dim_cfg.forced_max_frame_width);
1266 max_mb_cols = ROUND_POWER_OF_TWO(max_mi_cols, 2);
1267 }
1268 if (cpi->oxcf.frm_dim_cfg.forced_max_frame_height) {
1269 int max_mi_rows = size_in_mi(cpi->oxcf.frm_dim_cfg.forced_max_frame_height);
1270 max_mb_rows = ROUND_POWER_OF_TWO(max_mi_rows, 2);
1271 }
1272 const int unit_rows = get_unit_rows(BLOCK_16X16, max_mb_rows);
1273 const int unit_cols = get_unit_cols(BLOCK_16X16, max_mb_cols);
1274 setup_firstpass_data(cm, &cpi->firstpass_data, unit_rows, unit_cols);
1275 FRAME_STATS *mb_stats = cpi->firstpass_data.mb_stats;
1276 FRAME_STATS stats = accumulate_frame_stats(mb_stats, unit_rows, unit_cols);
1277 av1_free_firstpass_data(&cpi->firstpass_data);
1278 update_firstpass_stats(cpi, &stats, 1.0, current_frame->frame_number,
1279 ts_duration, BLOCK_16X16);
1280 }
1281
av1_first_pass(AV1_COMP * cpi,const int64_t ts_duration)1282 void av1_first_pass(AV1_COMP *cpi, const int64_t ts_duration) {
1283 MACROBLOCK *const x = &cpi->td.mb;
1284 AV1_COMMON *const cm = &cpi->common;
1285 const CommonModeInfoParams *const mi_params = &cm->mi_params;
1286 CurrentFrame *const current_frame = &cm->current_frame;
1287 const SequenceHeader *const seq_params = cm->seq_params;
1288 const int num_planes = av1_num_planes(cm);
1289 MACROBLOCKD *const xd = &x->e_mbd;
1290 const int qindex = find_fp_qindex(seq_params->bit_depth);
1291 const int ref_frame_flags_backup = cpi->ref_frame_flags;
1292 cpi->ref_frame_flags = av1_ref_frame_flag_list[LAST_FRAME] |
1293 av1_ref_frame_flag_list[GOLDEN_FRAME];
1294
1295 // Detect if the key frame is screen content type.
1296 if (frame_is_intra_only(cm)) {
1297 FeatureFlags *const features = &cm->features;
1298 assert(cpi->source != NULL);
1299 xd->cur_buf = cpi->source;
1300 av1_set_screen_content_options(cpi, features);
1301 }
1302
1303 // Prepare the speed features
1304 av1_set_speed_features_framesize_independent(cpi, cpi->oxcf.speed);
1305
1306 // Unit size for the first pass encoding.
1307 const BLOCK_SIZE fp_block_size =
1308 get_fp_block_size(cpi->is_screen_content_type);
1309
1310 int max_mb_rows = mi_params->mb_rows;
1311 int max_mb_cols = mi_params->mb_cols;
1312 if (cpi->oxcf.frm_dim_cfg.forced_max_frame_width) {
1313 int max_mi_cols = size_in_mi(cpi->oxcf.frm_dim_cfg.forced_max_frame_width);
1314 max_mb_cols = ROUND_POWER_OF_TWO(max_mi_cols, 2);
1315 }
1316 if (cpi->oxcf.frm_dim_cfg.forced_max_frame_height) {
1317 int max_mi_rows = size_in_mi(cpi->oxcf.frm_dim_cfg.forced_max_frame_height);
1318 max_mb_rows = ROUND_POWER_OF_TWO(max_mi_rows, 2);
1319 }
1320
1321 // Number of rows in the unit size.
1322 // Note max_mb_rows and max_mb_cols are in the unit of 16x16.
1323 const int unit_rows = get_unit_rows(fp_block_size, max_mb_rows);
1324 const int unit_cols = get_unit_cols(fp_block_size, max_mb_cols);
1325
1326 // Set fp_block_size, for the convenience of multi-thread usage.
1327 cpi->fp_block_size = fp_block_size;
1328
1329 setup_firstpass_data(cm, &cpi->firstpass_data, unit_rows, unit_cols);
1330 int *raw_motion_err_list = cpi->firstpass_data.raw_motion_err_list;
1331 FRAME_STATS *mb_stats = cpi->firstpass_data.mb_stats;
1332
1333 // multi threading info
1334 MultiThreadInfo *const mt_info = &cpi->mt_info;
1335 AV1EncRowMultiThreadInfo *const enc_row_mt = &mt_info->enc_row_mt;
1336
1337 const int tile_cols = cm->tiles.cols;
1338 const int tile_rows = cm->tiles.rows;
1339 if (cpi->allocated_tiles < tile_cols * tile_rows) {
1340 av1_alloc_tile_data(cpi);
1341 }
1342
1343 av1_init_tile_data(cpi);
1344
1345 const YV12_BUFFER_CONFIG *last_frame = NULL;
1346 const YV12_BUFFER_CONFIG *golden_frame = NULL;
1347 if (!frame_is_intra_only(cm)) {
1348 av1_scale_references(cpi, EIGHTTAP_REGULAR, 0, 0);
1349 last_frame = av1_is_scaled(get_ref_scale_factors_const(cm, LAST_FRAME))
1350 ? av1_get_scaled_ref_frame(cpi, LAST_FRAME)
1351 : get_ref_frame_yv12_buf(cm, LAST_FRAME);
1352 golden_frame = av1_is_scaled(get_ref_scale_factors_const(cm, GOLDEN_FRAME))
1353 ? av1_get_scaled_ref_frame(cpi, GOLDEN_FRAME)
1354 : get_ref_frame_yv12_buf(cm, GOLDEN_FRAME);
1355 }
1356
1357 YV12_BUFFER_CONFIG *const this_frame = &cm->cur_frame->buf;
1358 // First pass code requires valid last and new frame buffers.
1359 assert(this_frame != NULL);
1360 assert(frame_is_intra_only(cm) || (last_frame != NULL));
1361
1362 av1_setup_frame_size(cpi);
1363 av1_set_mv_search_params(cpi);
1364
1365 set_mi_offsets(mi_params, xd, 0, 0);
1366 xd->mi[0]->bsize = fp_block_size;
1367
1368 // Do not use periodic key frames.
1369 cpi->rc.frames_to_key = INT_MAX;
1370
1371 av1_set_quantizer(
1372 cm, cpi->oxcf.q_cfg.qm_minlevel, cpi->oxcf.q_cfg.qm_maxlevel, qindex,
1373 cpi->oxcf.q_cfg.enable_chroma_deltaq, cpi->oxcf.q_cfg.enable_hdr_deltaq);
1374
1375 av1_setup_block_planes(xd, seq_params->subsampling_x,
1376 seq_params->subsampling_y, num_planes);
1377
1378 av1_setup_src_planes(x, cpi->source, 0, 0, num_planes, fp_block_size);
1379 av1_setup_dst_planes(xd->plane, seq_params->sb_size, this_frame, 0, 0, 0,
1380 num_planes);
1381
1382 if (!frame_is_intra_only(cm)) {
1383 av1_setup_pre_planes(xd, 0, last_frame, 0, 0, NULL, num_planes);
1384 }
1385
1386 set_mi_offsets(mi_params, xd, 0, 0);
1387
1388 // Don't store luma on the fist pass since chroma is not computed
1389 xd->cfl.store_y = 0;
1390 av1_frame_init_quantizer(cpi);
1391
1392 av1_default_coef_probs(cm);
1393 av1_init_mode_probs(cm->fc);
1394 av1_init_mv_probs(cm);
1395 av1_initialize_rd_consts(cpi);
1396
1397 enc_row_mt->sync_read_ptr = av1_row_mt_sync_read_dummy;
1398 enc_row_mt->sync_write_ptr = av1_row_mt_sync_write_dummy;
1399
1400 if (mt_info->num_workers > 1) {
1401 enc_row_mt->sync_read_ptr = av1_row_mt_sync_read;
1402 enc_row_mt->sync_write_ptr = av1_row_mt_sync_write;
1403 av1_fp_encode_tiles_row_mt(cpi);
1404 } else {
1405 first_pass_tiles(cpi, fp_block_size);
1406 }
1407
1408 FRAME_STATS stats = accumulate_frame_stats(mb_stats, unit_rows, unit_cols);
1409 int total_raw_motion_err_count =
1410 frame_is_intra_only(cm) ? 0 : unit_rows * unit_cols;
1411 const double raw_err_stdev =
1412 raw_motion_error_stdev(raw_motion_err_list, total_raw_motion_err_count);
1413 av1_free_firstpass_data(&cpi->firstpass_data);
1414 av1_dealloc_src_diff_buf(&cpi->td.mb, av1_num_planes(cm));
1415
1416 // Clamp the image start to rows/2. This number of rows is discarded top
1417 // and bottom as dead data so rows / 2 means the frame is blank.
1418 if ((stats.image_data_start_row > unit_rows / 2) ||
1419 (stats.image_data_start_row == INVALID_ROW)) {
1420 stats.image_data_start_row = unit_rows / 2;
1421 }
1422 // Exclude any image dead zone
1423 if (stats.image_data_start_row > 0) {
1424 stats.intra_skip_count =
1425 AOMMAX(0, stats.intra_skip_count -
1426 (stats.image_data_start_row * unit_cols * 2));
1427 }
1428
1429 TWO_PASS *twopass = &cpi->ppi->twopass;
1430 const int num_mbs_16X16 = (cpi->oxcf.resize_cfg.resize_mode != RESIZE_NONE)
1431 ? cpi->initial_mbs
1432 : mi_params->MBs;
1433 // Number of actual units used in the first pass, it can be other square
1434 // block sizes than 16X16.
1435 const int num_mbs = get_num_mbs(fp_block_size, num_mbs_16X16);
1436 stats.intra_factor = stats.intra_factor / (double)num_mbs;
1437 stats.brightness_factor = stats.brightness_factor / (double)num_mbs;
1438 FIRSTPASS_STATS *this_frame_stats = twopass->stats_buf_ctx->stats_in_end;
1439 update_firstpass_stats(cpi, &stats, raw_err_stdev,
1440 current_frame->frame_number, ts_duration,
1441 fp_block_size);
1442
1443 // Copy the previous Last Frame back into gf buffer if the prediction is good
1444 // enough... but also don't allow it to lag too far.
1445 if ((twopass->sr_update_lag > 3) ||
1446 ((current_frame->frame_number > 0) &&
1447 (this_frame_stats->pcnt_inter > 0.20) &&
1448 ((this_frame_stats->intra_error /
1449 DOUBLE_DIVIDE_CHECK(this_frame_stats->coded_error)) > 2.0))) {
1450 if (golden_frame != NULL) {
1451 assign_frame_buffer_p(
1452 &cm->ref_frame_map[get_ref_frame_map_idx(cm, GOLDEN_FRAME)],
1453 cm->ref_frame_map[get_ref_frame_map_idx(cm, LAST_FRAME)]);
1454 }
1455 twopass->sr_update_lag = 1;
1456 } else {
1457 ++twopass->sr_update_lag;
1458 }
1459
1460 aom_extend_frame_borders(this_frame, num_planes);
1461
1462 // The frame we just compressed now becomes the last frame.
1463 assign_frame_buffer_p(
1464 &cm->ref_frame_map[get_ref_frame_map_idx(cm, LAST_FRAME)], cm->cur_frame);
1465
1466 // Special case for the first frame. Copy into the GF buffer as a second
1467 // reference.
1468 if (current_frame->frame_number == 0 &&
1469 get_ref_frame_map_idx(cm, GOLDEN_FRAME) != INVALID_IDX) {
1470 assign_frame_buffer_p(
1471 &cm->ref_frame_map[get_ref_frame_map_idx(cm, GOLDEN_FRAME)],
1472 cm->ref_frame_map[get_ref_frame_map_idx(cm, LAST_FRAME)]);
1473 }
1474
1475 print_reconstruction_frame(last_frame, current_frame->frame_number,
1476 /*do_print=*/0);
1477
1478 ++current_frame->frame_number;
1479 cpi->ref_frame_flags = ref_frame_flags_backup;
1480 if (!frame_is_intra_only(cm)) {
1481 release_scaled_references(cpi);
1482 }
1483 }
1484
av1_firstpass_info_init(FIRSTPASS_INFO * firstpass_info,FIRSTPASS_STATS * ext_stats_buf,int ext_stats_buf_size)1485 aom_codec_err_t av1_firstpass_info_init(FIRSTPASS_INFO *firstpass_info,
1486 FIRSTPASS_STATS *ext_stats_buf,
1487 int ext_stats_buf_size) {
1488 assert(IMPLIES(ext_stats_buf == NULL, ext_stats_buf_size == 0));
1489 if (ext_stats_buf == NULL) {
1490 firstpass_info->stats_buf = firstpass_info->static_stats_buf;
1491 firstpass_info->stats_buf_size =
1492 sizeof(firstpass_info->static_stats_buf) /
1493 sizeof(firstpass_info->static_stats_buf[0]);
1494 firstpass_info->start_index = 0;
1495 firstpass_info->cur_index = 0;
1496 firstpass_info->stats_count = 0;
1497 firstpass_info->future_stats_count = 0;
1498 firstpass_info->past_stats_count = 0;
1499 av1_zero(firstpass_info->total_stats);
1500 if (ext_stats_buf_size == 0) {
1501 return AOM_CODEC_OK;
1502 } else {
1503 return AOM_CODEC_ERROR;
1504 }
1505 } else {
1506 firstpass_info->stats_buf = ext_stats_buf;
1507 firstpass_info->stats_buf_size = ext_stats_buf_size;
1508 firstpass_info->start_index = 0;
1509 firstpass_info->cur_index = 0;
1510 firstpass_info->stats_count = firstpass_info->stats_buf_size;
1511 firstpass_info->future_stats_count = firstpass_info->stats_count;
1512 firstpass_info->past_stats_count = 0;
1513 av1_zero(firstpass_info->total_stats);
1514 for (int i = 0; i < firstpass_info->stats_count; ++i) {
1515 av1_accumulate_stats(&firstpass_info->total_stats,
1516 &firstpass_info->stats_buf[i]);
1517 }
1518 }
1519 return AOM_CODEC_OK;
1520 }
1521
av1_firstpass_info_move_cur_index(FIRSTPASS_INFO * firstpass_info)1522 aom_codec_err_t av1_firstpass_info_move_cur_index(
1523 FIRSTPASS_INFO *firstpass_info) {
1524 assert(firstpass_info->future_stats_count +
1525 firstpass_info->past_stats_count ==
1526 firstpass_info->stats_count);
1527 if (firstpass_info->future_stats_count > 1) {
1528 firstpass_info->cur_index =
1529 (firstpass_info->cur_index + 1) % firstpass_info->stats_buf_size;
1530 --firstpass_info->future_stats_count;
1531 ++firstpass_info->past_stats_count;
1532 return AOM_CODEC_OK;
1533 } else {
1534 return AOM_CODEC_ERROR;
1535 }
1536 }
1537
av1_firstpass_info_pop(FIRSTPASS_INFO * firstpass_info)1538 aom_codec_err_t av1_firstpass_info_pop(FIRSTPASS_INFO *firstpass_info) {
1539 if (firstpass_info->stats_count > 0 && firstpass_info->past_stats_count > 0) {
1540 const int next_start =
1541 (firstpass_info->start_index + 1) % firstpass_info->stats_buf_size;
1542 firstpass_info->start_index = next_start;
1543 --firstpass_info->stats_count;
1544 --firstpass_info->past_stats_count;
1545 return AOM_CODEC_OK;
1546 } else {
1547 return AOM_CODEC_ERROR;
1548 }
1549 }
1550
av1_firstpass_info_move_cur_index_and_pop(FIRSTPASS_INFO * firstpass_info)1551 aom_codec_err_t av1_firstpass_info_move_cur_index_and_pop(
1552 FIRSTPASS_INFO *firstpass_info) {
1553 aom_codec_err_t ret = av1_firstpass_info_move_cur_index(firstpass_info);
1554 if (ret != AOM_CODEC_OK) return ret;
1555 ret = av1_firstpass_info_pop(firstpass_info);
1556 return ret;
1557 }
1558
av1_firstpass_info_push(FIRSTPASS_INFO * firstpass_info,const FIRSTPASS_STATS * input_stats)1559 aom_codec_err_t av1_firstpass_info_push(FIRSTPASS_INFO *firstpass_info,
1560 const FIRSTPASS_STATS *input_stats) {
1561 if (firstpass_info->stats_count < firstpass_info->stats_buf_size) {
1562 const int next_index =
1563 (firstpass_info->start_index + firstpass_info->stats_count) %
1564 firstpass_info->stats_buf_size;
1565 firstpass_info->stats_buf[next_index] = *input_stats;
1566 ++firstpass_info->stats_count;
1567 ++firstpass_info->future_stats_count;
1568 av1_accumulate_stats(&firstpass_info->total_stats, input_stats);
1569 return AOM_CODEC_OK;
1570 } else {
1571 return AOM_CODEC_ERROR;
1572 }
1573 }
1574
av1_firstpass_info_peek(const FIRSTPASS_INFO * firstpass_info,int offset_from_cur)1575 const FIRSTPASS_STATS *av1_firstpass_info_peek(
1576 const FIRSTPASS_INFO *firstpass_info, int offset_from_cur) {
1577 if (offset_from_cur >= -firstpass_info->past_stats_count &&
1578 offset_from_cur < firstpass_info->future_stats_count) {
1579 const int index = (firstpass_info->cur_index + offset_from_cur) %
1580 firstpass_info->stats_buf_size;
1581 return &firstpass_info->stats_buf[index];
1582 } else {
1583 return NULL;
1584 }
1585 }
1586
av1_firstpass_info_future_count(const FIRSTPASS_INFO * firstpass_info,int offset_from_cur)1587 int av1_firstpass_info_future_count(const FIRSTPASS_INFO *firstpass_info,
1588 int offset_from_cur) {
1589 if (offset_from_cur < firstpass_info->future_stats_count) {
1590 return firstpass_info->future_stats_count - offset_from_cur;
1591 }
1592 return 0;
1593 }
1594
av1_firstpass_info_past_count(const FIRSTPASS_INFO * firstpass_info,int offset_from_cur)1595 int av1_firstpass_info_past_count(const FIRSTPASS_INFO *firstpass_info,
1596 int offset_from_cur) {
1597 if (offset_from_cur >= -firstpass_info->past_stats_count) {
1598 return offset_from_cur + firstpass_info->past_stats_count;
1599 }
1600 return 0;
1601 }
1602