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