2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
15 #include "./vp9_rtcd.h"
16 #include "./vpx_config.h"
17 #include "./vpx_dsp_rtcd.h"
18 #include "./vpx_scale_rtcd.h"
19 #include "vpx_dsp/psnr.h"
20 #include "vpx_dsp/vpx_dsp_common.h"
21 #include "vpx_dsp/vpx_filter.h"
22 #if CONFIG_INTERNAL_STATS
23 #include "vpx_dsp/ssim.h"
25 #include "vpx_ports/mem.h"
26 #include "vpx_ports/system_state.h"
27 #include "vpx_ports/vpx_timer.h"
29 #include "vp9/common/vp9_alloccommon.h"
30 #include "vp9/common/vp9_filter.h"
31 #include "vp9/common/vp9_idct.h"
32 #if CONFIG_VP9_POSTPROC
33 #include "vp9/common/vp9_postproc.h"
35 #include "vp9/common/vp9_reconinter.h"
36 #include "vp9/common/vp9_reconintra.h"
37 #include "vp9/common/vp9_tile_common.h"
39 #include "vp9/encoder/vp9_aq_360.h"
40 #include "vp9/encoder/vp9_aq_complexity.h"
41 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
42 #include "vp9/encoder/vp9_aq_variance.h"
43 #include "vp9/encoder/vp9_bitstream.h"
44 #include "vp9/encoder/vp9_context_tree.h"
45 #include "vp9/encoder/vp9_encodeframe.h"
46 #include "vp9/encoder/vp9_encodemv.h"
47 #include "vp9/encoder/vp9_encoder.h"
48 #include "vp9/encoder/vp9_extend.h"
49 #include "vp9/encoder/vp9_ethread.h"
50 #include "vp9/encoder/vp9_firstpass.h"
51 #include "vp9/encoder/vp9_mbgraph.h"
52 #include "vp9/encoder/vp9_noise_estimate.h"
53 #include "vp9/encoder/vp9_picklpf.h"
54 #include "vp9/encoder/vp9_ratectrl.h"
55 #include "vp9/encoder/vp9_rd.h"
56 #include "vp9/encoder/vp9_resize.h"
57 #include "vp9/encoder/vp9_segmentation.h"
58 #include "vp9/encoder/vp9_skin_detection.h"
59 #include "vp9/encoder/vp9_speed_features.h"
60 #include "vp9/encoder/vp9_svc_layercontext.h"
61 #include "vp9/encoder/vp9_temporal_filter.h"
63 #define AM_SEGMENT_ID_INACTIVE 7
64 #define AM_SEGMENT_ID_ACTIVE 0
66 #define ALTREF_HIGH_PRECISION_MV 1 // Whether to use high precision mv
67 // for altref computation.
68 #define HIGH_PRECISION_MV_QTHRESH 200 // Q threshold for high precision
69 // mv. Choose a very high value for
70 // now so that HIGH_PRECISION is always
72 // #define OUTPUT_YUV_REC
74 #ifdef OUTPUT_YUV_DENOISED
75 FILE *yuv_denoised_file = NULL;
77 #ifdef OUTPUT_YUV_SKINMAP
78 FILE *yuv_skinmap_file = NULL;
90 #ifdef ENABLE_KF_DENOISE
91 // Test condition for spatial denoise of source.
92 static int is_spatial_denoise_enabled(VP9_COMP *cpi) {
93 VP9_COMMON *const cm = &cpi->common;
94 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
96 return (oxcf->pass != 1) && !is_lossless_requested(&cpi->oxcf) &&
97 frame_is_intra_only(cm);
101 // Test for whether to calculate metrics for the frame.
102 static int is_psnr_calc_enabled(VP9_COMP *cpi) {
103 VP9_COMMON *const cm = &cpi->common;
104 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
106 return cpi->b_calculate_psnr && (oxcf->pass != 1) && cm->show_frame;
109 /* clang-format off */
110 static const Vp9LevelSpec vp9_level_defs[VP9_LEVELS] = {
111 { LEVEL_1, 829440, 36864, 200, 400, 2, 1, 4, 8 },
112 { LEVEL_1_1, 2764800, 73728, 800, 1000, 2, 1, 4, 8 },
113 { LEVEL_2, 4608000, 122880, 1800, 1500, 2, 1, 4, 8 },
114 { LEVEL_2_1, 9216000, 245760, 3600, 2800, 2, 2, 4, 8 },
115 { LEVEL_3, 20736000, 552960, 7200, 6000, 2, 4, 4, 8 },
116 { LEVEL_3_1, 36864000, 983040, 12000, 10000, 2, 4, 4, 8 },
117 { LEVEL_4, 83558400, 2228224, 18000, 16000, 4, 4, 4, 8 },
118 { LEVEL_4_1, 160432128, 2228224, 30000, 18000, 4, 4, 5, 6 },
119 { LEVEL_5, 311951360, 8912896, 60000, 36000, 6, 8, 6, 4 },
120 { LEVEL_5_1, 588251136, 8912896, 120000, 46000, 8, 8, 10, 4 },
121 // TODO(huisu): update max_cpb_size for level 5_2 ~ 6_2 when
122 // they are finalized (currently TBD).
123 { LEVEL_5_2, 1176502272, 8912896, 180000, 0, 8, 8, 10, 4 },
124 { LEVEL_6, 1176502272, 35651584, 180000, 0, 8, 16, 10, 4 },
125 { LEVEL_6_1, 2353004544u, 35651584, 240000, 0, 8, 16, 10, 4 },
126 { LEVEL_6_2, 4706009088u, 35651584, 480000, 0, 8, 16, 10, 4 },
128 /* clang-format on */
130 static INLINE void Scale2Ratio(VPX_SCALING mode, int *hr, int *hs) {
156 // Mark all inactive blocks as active. Other segmentation features may be set
157 // so memset cannot be used, instead only inactive blocks should be reset.
158 static void suppress_active_map(VP9_COMP *cpi) {
159 unsigned char *const seg_map = cpi->segmentation_map;
161 if (cpi->active_map.enabled || cpi->active_map.update) {
162 const int rows = cpi->common.mi_rows;
163 const int cols = cpi->common.mi_cols;
166 for (i = 0; i < rows * cols; ++i)
167 if (seg_map[i] == AM_SEGMENT_ID_INACTIVE)
168 seg_map[i] = AM_SEGMENT_ID_ACTIVE;
172 static void apply_active_map(VP9_COMP *cpi) {
173 struct segmentation *const seg = &cpi->common.seg;
174 unsigned char *const seg_map = cpi->segmentation_map;
175 const unsigned char *const active_map = cpi->active_map.map;
178 assert(AM_SEGMENT_ID_ACTIVE == CR_SEGMENT_ID_BASE);
180 if (frame_is_intra_only(&cpi->common)) {
181 cpi->active_map.enabled = 0;
182 cpi->active_map.update = 1;
185 if (cpi->active_map.update) {
186 if (cpi->active_map.enabled) {
187 for (i = 0; i < cpi->common.mi_rows * cpi->common.mi_cols; ++i)
188 if (seg_map[i] == AM_SEGMENT_ID_ACTIVE) seg_map[i] = active_map[i];
189 vp9_enable_segmentation(seg);
190 vp9_enable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
191 vp9_enable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
192 // Setting the data to -MAX_LOOP_FILTER will result in the computed loop
193 // filter level being zero regardless of the value of seg->abs_delta.
194 vp9_set_segdata(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF,
197 vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
198 vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
200 seg->update_data = 1;
204 cpi->active_map.update = 0;
208 static void init_level_info(Vp9LevelInfo *level_info) {
209 Vp9LevelStats *const level_stats = &level_info->level_stats;
210 Vp9LevelSpec *const level_spec = &level_info->level_spec;
212 memset(level_stats, 0, sizeof(*level_stats));
213 memset(level_spec, 0, sizeof(*level_spec));
214 level_spec->level = LEVEL_UNKNOWN;
215 level_spec->min_altref_distance = INT_MAX;
218 VP9_LEVEL vp9_get_level(const Vp9LevelSpec *const level_spec) {
220 const Vp9LevelSpec *this_level;
222 vpx_clear_system_state();
224 for (i = 0; i < VP9_LEVELS; ++i) {
225 this_level = &vp9_level_defs[i];
226 if ((double)level_spec->max_luma_sample_rate * (1 + SAMPLE_RATE_GRACE_P) >
227 (double)this_level->max_luma_sample_rate ||
228 level_spec->max_luma_picture_size > this_level->max_luma_picture_size ||
229 level_spec->average_bitrate > this_level->average_bitrate ||
230 level_spec->max_cpb_size > this_level->max_cpb_size ||
231 level_spec->compression_ratio < this_level->compression_ratio ||
232 level_spec->max_col_tiles > this_level->max_col_tiles ||
233 level_spec->min_altref_distance < this_level->min_altref_distance ||
234 level_spec->max_ref_frame_buffers > this_level->max_ref_frame_buffers)
238 return (i == VP9_LEVELS) ? LEVEL_UNKNOWN : vp9_level_defs[i].level;
241 int vp9_set_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
243 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
244 unsigned char *const active_map_8x8 = cpi->active_map.map;
245 const int mi_rows = cpi->common.mi_rows;
246 const int mi_cols = cpi->common.mi_cols;
247 cpi->active_map.update = 1;
250 for (r = 0; r < mi_rows; ++r) {
251 for (c = 0; c < mi_cols; ++c) {
252 active_map_8x8[r * mi_cols + c] =
253 new_map_16x16[(r >> 1) * cols + (c >> 1)]
254 ? AM_SEGMENT_ID_ACTIVE
255 : AM_SEGMENT_ID_INACTIVE;
258 cpi->active_map.enabled = 1;
260 cpi->active_map.enabled = 0;
268 int vp9_get_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
270 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols &&
272 unsigned char *const seg_map_8x8 = cpi->segmentation_map;
273 const int mi_rows = cpi->common.mi_rows;
274 const int mi_cols = cpi->common.mi_cols;
275 memset(new_map_16x16, !cpi->active_map.enabled, rows * cols);
276 if (cpi->active_map.enabled) {
278 for (r = 0; r < mi_rows; ++r) {
279 for (c = 0; c < mi_cols; ++c) {
280 // Cyclic refresh segments are considered active despite not having
281 // AM_SEGMENT_ID_ACTIVE
282 new_map_16x16[(r >> 1) * cols + (c >> 1)] |=
283 seg_map_8x8[r * mi_cols + c] != AM_SEGMENT_ID_INACTIVE;
293 void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv) {
294 MACROBLOCK *const mb = &cpi->td.mb;
295 cpi->common.allow_high_precision_mv = allow_high_precision_mv;
296 if (cpi->common.allow_high_precision_mv) {
297 mb->mvcost = mb->nmvcost_hp;
298 mb->mvsadcost = mb->nmvsadcost_hp;
300 mb->mvcost = mb->nmvcost;
301 mb->mvsadcost = mb->nmvsadcost;
305 static void setup_frame(VP9_COMP *cpi) {
306 VP9_COMMON *const cm = &cpi->common;
307 // Set up entropy context depending on frame type. The decoder mandates
308 // the use of the default context, index 0, for keyframes and inter
309 // frames where the error_resilient_mode or intra_only flag is set. For
310 // other inter-frames the encoder currently uses only two contexts;
311 // context 1 for ALTREF frames and context 0 for the others.
312 if (frame_is_intra_only(cm) || cm->error_resilient_mode) {
313 vp9_setup_past_independence(cm);
315 if (!cpi->use_svc) cm->frame_context_idx = cpi->refresh_alt_ref_frame;
318 if (cm->frame_type == KEY_FRAME) {
319 if (!is_two_pass_svc(cpi)) cpi->refresh_golden_frame = 1;
320 cpi->refresh_alt_ref_frame = 1;
321 vp9_zero(cpi->interp_filter_selected);
323 *cm->fc = cm->frame_contexts[cm->frame_context_idx];
324 vp9_zero(cpi->interp_filter_selected[0]);
328 static void vp9_enc_setup_mi(VP9_COMMON *cm) {
330 cm->mi = cm->mip + cm->mi_stride + 1;
331 memset(cm->mip, 0, cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mip));
332 cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
333 // Clear top border row
334 memset(cm->prev_mip, 0, sizeof(*cm->prev_mip) * cm->mi_stride);
335 // Clear left border column
336 for (i = 1; i < cm->mi_rows + 1; ++i)
337 memset(&cm->prev_mip[i * cm->mi_stride], 0, sizeof(*cm->prev_mip));
339 cm->mi_grid_visible = cm->mi_grid_base + cm->mi_stride + 1;
340 cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mi_stride + 1;
342 memset(cm->mi_grid_base, 0,
343 cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mi_grid_base));
346 static int vp9_enc_alloc_mi(VP9_COMMON *cm, int mi_size) {
347 cm->mip = vpx_calloc(mi_size, sizeof(*cm->mip));
348 if (!cm->mip) return 1;
349 cm->prev_mip = vpx_calloc(mi_size, sizeof(*cm->prev_mip));
350 if (!cm->prev_mip) return 1;
351 cm->mi_alloc_size = mi_size;
353 cm->mi_grid_base = (MODE_INFO **)vpx_calloc(mi_size, sizeof(MODE_INFO *));
354 if (!cm->mi_grid_base) return 1;
355 cm->prev_mi_grid_base =
356 (MODE_INFO **)vpx_calloc(mi_size, sizeof(MODE_INFO *));
357 if (!cm->prev_mi_grid_base) return 1;
362 static void vp9_enc_free_mi(VP9_COMMON *cm) {
365 vpx_free(cm->prev_mip);
367 vpx_free(cm->mi_grid_base);
368 cm->mi_grid_base = NULL;
369 vpx_free(cm->prev_mi_grid_base);
370 cm->prev_mi_grid_base = NULL;
373 static void vp9_swap_mi_and_prev_mi(VP9_COMMON *cm) {
374 // Current mip will be the prev_mip for the next frame.
375 MODE_INFO **temp_base = cm->prev_mi_grid_base;
376 MODE_INFO *temp = cm->prev_mip;
377 cm->prev_mip = cm->mip;
380 // Update the upper left visible macroblock ptrs.
381 cm->mi = cm->mip + cm->mi_stride + 1;
382 cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
384 cm->prev_mi_grid_base = cm->mi_grid_base;
385 cm->mi_grid_base = temp_base;
386 cm->mi_grid_visible = cm->mi_grid_base + cm->mi_stride + 1;
387 cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mi_stride + 1;
390 void vp9_initialize_enc(void) {
391 static volatile int init_done = 0;
397 vp9_init_intra_predictors();
399 vp9_rc_init_minq_luts();
400 vp9_entropy_mv_init();
401 vp9_temporal_filter_init();
406 static void dealloc_compressor_data(VP9_COMP *cpi) {
407 VP9_COMMON *const cm = &cpi->common;
410 vpx_free(cpi->mbmi_ext_base);
411 cpi->mbmi_ext_base = NULL;
413 vpx_free(cpi->tile_data);
414 cpi->tile_data = NULL;
416 vpx_free(cpi->segmentation_map);
417 cpi->segmentation_map = NULL;
418 vpx_free(cpi->coding_context.last_frame_seg_map_copy);
419 cpi->coding_context.last_frame_seg_map_copy = NULL;
421 vpx_free(cpi->nmvcosts[0]);
422 vpx_free(cpi->nmvcosts[1]);
423 cpi->nmvcosts[0] = NULL;
424 cpi->nmvcosts[1] = NULL;
426 vpx_free(cpi->nmvcosts_hp[0]);
427 vpx_free(cpi->nmvcosts_hp[1]);
428 cpi->nmvcosts_hp[0] = NULL;
429 cpi->nmvcosts_hp[1] = NULL;
431 vpx_free(cpi->nmvsadcosts[0]);
432 vpx_free(cpi->nmvsadcosts[1]);
433 cpi->nmvsadcosts[0] = NULL;
434 cpi->nmvsadcosts[1] = NULL;
436 vpx_free(cpi->nmvsadcosts_hp[0]);
437 vpx_free(cpi->nmvsadcosts_hp[1]);
438 cpi->nmvsadcosts_hp[0] = NULL;
439 cpi->nmvsadcosts_hp[1] = NULL;
441 vp9_cyclic_refresh_free(cpi->cyclic_refresh);
442 cpi->cyclic_refresh = NULL;
444 vpx_free(cpi->active_map.map);
445 cpi->active_map.map = NULL;
447 vpx_free(cpi->consec_zero_mv);
448 cpi->consec_zero_mv = NULL;
450 vp9_free_ref_frame_buffers(cm->buffer_pool);
451 #if CONFIG_VP9_POSTPROC
452 vp9_free_postproc_buffers(cm);
454 vp9_free_context_buffers(cm);
456 vpx_free_frame_buffer(&cpi->last_frame_uf);
457 vpx_free_frame_buffer(&cpi->scaled_source);
458 vpx_free_frame_buffer(&cpi->scaled_last_source);
459 vpx_free_frame_buffer(&cpi->alt_ref_buffer);
460 #ifdef ENABLE_KF_DENOISE
461 vpx_free_frame_buffer(&cpi->raw_unscaled_source);
462 vpx_free_frame_buffer(&cpi->raw_scaled_source);
465 vp9_lookahead_destroy(cpi->lookahead);
467 vpx_free(cpi->tile_tok[0][0]);
468 cpi->tile_tok[0][0] = 0;
470 vp9_free_pc_tree(&cpi->td);
472 for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
473 LAYER_CONTEXT *const lc = &cpi->svc.layer_context[i];
474 vpx_free(lc->rc_twopass_stats_in.buf);
475 lc->rc_twopass_stats_in.buf = NULL;
476 lc->rc_twopass_stats_in.sz = 0;
479 if (cpi->source_diff_var != NULL) {
480 vpx_free(cpi->source_diff_var);
481 cpi->source_diff_var = NULL;
484 for (i = 0; i < MAX_LAG_BUFFERS; ++i) {
485 vpx_free_frame_buffer(&cpi->svc.scaled_frames[i]);
487 memset(&cpi->svc.scaled_frames[0], 0,
488 MAX_LAG_BUFFERS * sizeof(cpi->svc.scaled_frames[0]));
490 vpx_free_frame_buffer(&cpi->svc.scaled_temp);
491 memset(&cpi->svc.scaled_temp, 0, sizeof(cpi->svc.scaled_temp));
493 vpx_free_frame_buffer(&cpi->svc.empty_frame.img);
494 memset(&cpi->svc.empty_frame, 0, sizeof(cpi->svc.empty_frame));
496 vp9_free_svc_cyclic_refresh(cpi);
499 static void save_coding_context(VP9_COMP *cpi) {
500 CODING_CONTEXT *const cc = &cpi->coding_context;
501 VP9_COMMON *cm = &cpi->common;
503 // Stores a snapshot of key state variables which can subsequently be
504 // restored with a call to vp9_restore_coding_context. These functions are
505 // intended for use in a re-code loop in vp9_compress_frame where the
506 // quantizer value is adjusted between loop iterations.
507 vp9_copy(cc->nmvjointcost, cpi->td.mb.nmvjointcost);
509 memcpy(cc->nmvcosts[0], cpi->nmvcosts[0],
510 MV_VALS * sizeof(*cpi->nmvcosts[0]));
511 memcpy(cc->nmvcosts[1], cpi->nmvcosts[1],
512 MV_VALS * sizeof(*cpi->nmvcosts[1]));
513 memcpy(cc->nmvcosts_hp[0], cpi->nmvcosts_hp[0],
514 MV_VALS * sizeof(*cpi->nmvcosts_hp[0]));
515 memcpy(cc->nmvcosts_hp[1], cpi->nmvcosts_hp[1],
516 MV_VALS * sizeof(*cpi->nmvcosts_hp[1]));
518 vp9_copy(cc->segment_pred_probs, cm->seg.pred_probs);
520 memcpy(cpi->coding_context.last_frame_seg_map_copy, cm->last_frame_seg_map,
521 (cm->mi_rows * cm->mi_cols));
523 vp9_copy(cc->last_ref_lf_deltas, cm->lf.last_ref_deltas);
524 vp9_copy(cc->last_mode_lf_deltas, cm->lf.last_mode_deltas);
529 static void restore_coding_context(VP9_COMP *cpi) {
530 CODING_CONTEXT *const cc = &cpi->coding_context;
531 VP9_COMMON *cm = &cpi->common;
533 // Restore key state variables to the snapshot state stored in the
534 // previous call to vp9_save_coding_context.
535 vp9_copy(cpi->td.mb.nmvjointcost, cc->nmvjointcost);
537 memcpy(cpi->nmvcosts[0], cc->nmvcosts[0], MV_VALS * sizeof(*cc->nmvcosts[0]));
538 memcpy(cpi->nmvcosts[1], cc->nmvcosts[1], MV_VALS * sizeof(*cc->nmvcosts[1]));
539 memcpy(cpi->nmvcosts_hp[0], cc->nmvcosts_hp[0],
540 MV_VALS * sizeof(*cc->nmvcosts_hp[0]));
541 memcpy(cpi->nmvcosts_hp[1], cc->nmvcosts_hp[1],
542 MV_VALS * sizeof(*cc->nmvcosts_hp[1]));
544 vp9_copy(cm->seg.pred_probs, cc->segment_pred_probs);
546 memcpy(cm->last_frame_seg_map, cpi->coding_context.last_frame_seg_map_copy,
547 (cm->mi_rows * cm->mi_cols));
549 vp9_copy(cm->lf.last_ref_deltas, cc->last_ref_lf_deltas);
550 vp9_copy(cm->lf.last_mode_deltas, cc->last_mode_lf_deltas);
555 static void configure_static_seg_features(VP9_COMP *cpi) {
556 VP9_COMMON *const cm = &cpi->common;
557 const RATE_CONTROL *const rc = &cpi->rc;
558 struct segmentation *const seg = &cm->seg;
560 int high_q = (int)(rc->avg_q > 48.0);
563 // Disable and clear down for KF
564 if (cm->frame_type == KEY_FRAME) {
565 // Clear down the global segmentation map
566 memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
568 seg->update_data = 0;
569 cpi->static_mb_pct = 0;
571 // Disable segmentation
572 vp9_disable_segmentation(seg);
574 // Clear down the segment features.
575 vp9_clearall_segfeatures(seg);
576 } else if (cpi->refresh_alt_ref_frame) {
577 // If this is an alt ref frame
578 // Clear down the global segmentation map
579 memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
581 seg->update_data = 0;
582 cpi->static_mb_pct = 0;
584 // Disable segmentation and individual segment features by default
585 vp9_disable_segmentation(seg);
586 vp9_clearall_segfeatures(seg);
588 // Scan frames from current to arf frame.
589 // This function re-enables segmentation if appropriate.
590 vp9_update_mbgraph_stats(cpi);
592 // If segmentation was enabled set those features needed for the
596 seg->update_data = 1;
599 vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 0.875, cm->bit_depth);
600 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta - 2);
601 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
603 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
604 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
606 // Where relevant assume segment data is delta data
607 seg->abs_delta = SEGMENT_DELTADATA;
609 } else if (seg->enabled) {
610 // All other frames if segmentation has been enabled
612 // First normal frame in a valid gf or alt ref group
613 if (rc->frames_since_golden == 0) {
614 // Set up segment features for normal frames in an arf group
615 if (rc->source_alt_ref_active) {
617 seg->update_data = 1;
618 seg->abs_delta = SEGMENT_DELTADATA;
621 vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 1.125, cm->bit_depth);
622 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta + 2);
623 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
625 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
626 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
628 // Segment coding disabled for compred testing
629 if (high_q || (cpi->static_mb_pct == 100)) {
630 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
631 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
632 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
635 // Disable segmentation and clear down features if alt ref
636 // is not active for this group
638 vp9_disable_segmentation(seg);
640 memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
643 seg->update_data = 0;
645 vp9_clearall_segfeatures(seg);
647 } else if (rc->is_src_frame_alt_ref) {
648 // Special case where we are coding over the top of a previous
650 // Segment coding disabled for compred testing
652 // Enable ref frame features for segment 0 as well
653 vp9_enable_segfeature(seg, 0, SEG_LVL_REF_FRAME);
654 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
656 // All mbs should use ALTREF_FRAME
657 vp9_clear_segdata(seg, 0, SEG_LVL_REF_FRAME);
658 vp9_set_segdata(seg, 0, SEG_LVL_REF_FRAME, ALTREF_FRAME);
659 vp9_clear_segdata(seg, 1, SEG_LVL_REF_FRAME);
660 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
662 // Skip all MBs if high Q (0,0 mv and skip coeffs)
664 vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
665 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
667 // Enable data update
668 seg->update_data = 1;
672 // No updates.. leave things as they are.
674 seg->update_data = 0;
679 static void update_reference_segmentation_map(VP9_COMP *cpi) {
680 VP9_COMMON *const cm = &cpi->common;
681 MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
682 uint8_t *cache_ptr = cm->last_frame_seg_map;
685 for (row = 0; row < cm->mi_rows; row++) {
686 MODE_INFO **mi_8x8 = mi_8x8_ptr;
687 uint8_t *cache = cache_ptr;
688 for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
689 cache[0] = mi_8x8[0]->segment_id;
690 mi_8x8_ptr += cm->mi_stride;
691 cache_ptr += cm->mi_cols;
695 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
696 VP9_COMMON *cm = &cpi->common;
697 const VP9EncoderConfig *oxcf = &cpi->oxcf;
700 cpi->lookahead = vp9_lookahead_init(oxcf->width, oxcf->height,
701 cm->subsampling_x, cm->subsampling_y,
702 #if CONFIG_VP9_HIGHBITDEPTH
703 cm->use_highbitdepth,
705 oxcf->lag_in_frames);
707 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
708 "Failed to allocate lag buffers");
710 // TODO(agrange) Check if ARF is enabled and skip allocation if not.
711 if (vpx_realloc_frame_buffer(&cpi->alt_ref_buffer, oxcf->width, oxcf->height,
712 cm->subsampling_x, cm->subsampling_y,
713 #if CONFIG_VP9_HIGHBITDEPTH
714 cm->use_highbitdepth,
716 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
718 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
719 "Failed to allocate altref buffer");
722 static void alloc_util_frame_buffers(VP9_COMP *cpi) {
723 VP9_COMMON *const cm = &cpi->common;
724 if (vpx_realloc_frame_buffer(&cpi->last_frame_uf, cm->width, cm->height,
725 cm->subsampling_x, cm->subsampling_y,
726 #if CONFIG_VP9_HIGHBITDEPTH
727 cm->use_highbitdepth,
729 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
731 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
732 "Failed to allocate last frame buffer");
734 if (vpx_realloc_frame_buffer(&cpi->scaled_source, cm->width, cm->height,
735 cm->subsampling_x, cm->subsampling_y,
736 #if CONFIG_VP9_HIGHBITDEPTH
737 cm->use_highbitdepth,
739 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
741 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
742 "Failed to allocate scaled source buffer");
744 // For 1 pass cbr: allocate scaled_frame that may be used as an intermediate
745 // buffer for a 2 stage down-sampling: two stages of 1:2 down-sampling for a
746 // target of 1/4x1/4.
747 if (is_one_pass_cbr_svc(cpi) && !cpi->svc.scaled_temp_is_alloc) {
748 cpi->svc.scaled_temp_is_alloc = 1;
749 if (vpx_realloc_frame_buffer(
750 &cpi->svc.scaled_temp, cm->width >> 1, cm->height >> 1,
751 cm->subsampling_x, cm->subsampling_y,
752 #if CONFIG_VP9_HIGHBITDEPTH
753 cm->use_highbitdepth,
755 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment, NULL, NULL, NULL))
756 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
757 "Failed to allocate scaled_frame for svc ");
760 if (vpx_realloc_frame_buffer(&cpi->scaled_last_source, cm->width, cm->height,
761 cm->subsampling_x, cm->subsampling_y,
762 #if CONFIG_VP9_HIGHBITDEPTH
763 cm->use_highbitdepth,
765 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
767 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
768 "Failed to allocate scaled last source buffer");
769 #ifdef ENABLE_KF_DENOISE
770 if (vpx_realloc_frame_buffer(&cpi->raw_unscaled_source, cm->width, cm->height,
771 cm->subsampling_x, cm->subsampling_y,
772 #if CONFIG_VP9_HIGHBITDEPTH
773 cm->use_highbitdepth,
775 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
777 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
778 "Failed to allocate unscaled raw source frame buffer");
780 if (vpx_realloc_frame_buffer(&cpi->raw_scaled_source, cm->width, cm->height,
781 cm->subsampling_x, cm->subsampling_y,
782 #if CONFIG_VP9_HIGHBITDEPTH
783 cm->use_highbitdepth,
785 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
787 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
788 "Failed to allocate scaled raw source frame buffer");
792 static int alloc_context_buffers_ext(VP9_COMP *cpi) {
793 VP9_COMMON *cm = &cpi->common;
794 int mi_size = cm->mi_cols * cm->mi_rows;
796 cpi->mbmi_ext_base = vpx_calloc(mi_size, sizeof(*cpi->mbmi_ext_base));
797 if (!cpi->mbmi_ext_base) return 1;
802 static void alloc_compressor_data(VP9_COMP *cpi) {
803 VP9_COMMON *cm = &cpi->common;
805 vp9_alloc_context_buffers(cm, cm->width, cm->height);
807 alloc_context_buffers_ext(cpi);
809 vpx_free(cpi->tile_tok[0][0]);
812 unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
813 CHECK_MEM_ERROR(cm, cpi->tile_tok[0][0],
814 vpx_calloc(tokens, sizeof(*cpi->tile_tok[0][0])));
817 vp9_setup_pc_tree(&cpi->common, &cpi->td);
820 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
821 cpi->framerate = framerate < 0.1 ? 30 : framerate;
822 vp9_rc_update_framerate(cpi);
825 static void set_tile_limits(VP9_COMP *cpi) {
826 VP9_COMMON *const cm = &cpi->common;
828 int min_log2_tile_cols, max_log2_tile_cols;
829 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
831 if (is_two_pass_svc(cpi) && (cpi->svc.encode_empty_frame_state == ENCODING ||
832 cpi->svc.number_spatial_layers > 1)) {
833 cm->log2_tile_cols = 0;
834 cm->log2_tile_rows = 0;
837 clamp(cpi->oxcf.tile_columns, min_log2_tile_cols, max_log2_tile_cols);
838 cm->log2_tile_rows = cpi->oxcf.tile_rows;
842 static void update_frame_size(VP9_COMP *cpi) {
843 VP9_COMMON *const cm = &cpi->common;
844 MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
846 vp9_set_mb_mi(cm, cm->width, cm->height);
847 vp9_init_context_buffers(cm);
848 vp9_init_macroblockd(cm, xd, NULL);
849 cpi->td.mb.mbmi_ext_base = cpi->mbmi_ext_base;
850 memset(cpi->mbmi_ext_base, 0,
851 cm->mi_rows * cm->mi_cols * sizeof(*cpi->mbmi_ext_base));
853 set_tile_limits(cpi);
855 if (is_two_pass_svc(cpi)) {
856 if (vpx_realloc_frame_buffer(&cpi->alt_ref_buffer, cm->width, cm->height,
857 cm->subsampling_x, cm->subsampling_y,
858 #if CONFIG_VP9_HIGHBITDEPTH
859 cm->use_highbitdepth,
861 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
863 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
864 "Failed to reallocate alt_ref_buffer");
868 static void init_buffer_indices(VP9_COMP *cpi) {
874 static void init_config(struct VP9_COMP *cpi, VP9EncoderConfig *oxcf) {
875 VP9_COMMON *const cm = &cpi->common;
878 cpi->framerate = oxcf->init_framerate;
879 cm->profile = oxcf->profile;
880 cm->bit_depth = oxcf->bit_depth;
881 #if CONFIG_VP9_HIGHBITDEPTH
882 cm->use_highbitdepth = oxcf->use_highbitdepth;
884 cm->color_space = oxcf->color_space;
885 cm->color_range = oxcf->color_range;
887 cpi->target_level = oxcf->target_level;
888 cpi->keep_level_stats = oxcf->target_level != LEVEL_MAX;
890 cm->width = oxcf->width;
891 cm->height = oxcf->height;
892 alloc_compressor_data(cpi);
894 cpi->svc.temporal_layering_mode = oxcf->temporal_layering_mode;
896 // Single thread case: use counts in common.
897 cpi->td.counts = &cm->counts;
899 // Spatial scalability.
900 cpi->svc.number_spatial_layers = oxcf->ss_number_layers;
901 // Temporal scalability.
902 cpi->svc.number_temporal_layers = oxcf->ts_number_layers;
904 if ((cpi->svc.number_temporal_layers > 1 && cpi->oxcf.rc_mode == VPX_CBR) ||
905 ((cpi->svc.number_temporal_layers > 1 ||
906 cpi->svc.number_spatial_layers > 1) &&
907 cpi->oxcf.pass != 1)) {
908 vp9_init_layer_context(cpi);
911 // change includes all joint functionality
912 vp9_change_config(cpi, oxcf);
914 cpi->static_mb_pct = 0;
915 cpi->ref_frame_flags = 0;
917 init_buffer_indices(cpi);
919 vp9_noise_estimate_init(&cpi->noise_estimate, cm->width, cm->height);
922 static void set_rc_buffer_sizes(RATE_CONTROL *rc,
923 const VP9EncoderConfig *oxcf) {
924 const int64_t bandwidth = oxcf->target_bandwidth;
925 const int64_t starting = oxcf->starting_buffer_level_ms;
926 const int64_t optimal = oxcf->optimal_buffer_level_ms;
927 const int64_t maximum = oxcf->maximum_buffer_size_ms;
929 rc->starting_buffer_level = starting * bandwidth / 1000;
930 rc->optimal_buffer_level =
931 (optimal == 0) ? bandwidth / 8 : optimal * bandwidth / 1000;
932 rc->maximum_buffer_size =
933 (maximum == 0) ? bandwidth / 8 : maximum * bandwidth / 1000;
936 #if CONFIG_VP9_HIGHBITDEPTH
937 #define HIGHBD_BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF) \
938 cpi->fn_ptr[BT].sdf = SDF; \
939 cpi->fn_ptr[BT].sdaf = SDAF; \
940 cpi->fn_ptr[BT].vf = VF; \
941 cpi->fn_ptr[BT].svf = SVF; \
942 cpi->fn_ptr[BT].svaf = SVAF; \
943 cpi->fn_ptr[BT].sdx3f = SDX3F; \
944 cpi->fn_ptr[BT].sdx8f = SDX8F; \
945 cpi->fn_ptr[BT].sdx4df = SDX4DF;
947 #define MAKE_BFP_SAD_WRAPPER(fnname) \
948 static unsigned int fnname##_bits8(const uint8_t *src_ptr, \
950 const uint8_t *ref_ptr, int ref_stride) { \
951 return fnname(src_ptr, source_stride, ref_ptr, ref_stride); \
953 static unsigned int fnname##_bits10( \
954 const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr, \
956 return fnname(src_ptr, source_stride, ref_ptr, ref_stride) >> 2; \
958 static unsigned int fnname##_bits12( \
959 const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr, \
961 return fnname(src_ptr, source_stride, ref_ptr, ref_stride) >> 4; \
964 #define MAKE_BFP_SADAVG_WRAPPER(fnname) \
965 static unsigned int fnname##_bits8( \
966 const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr, \
967 int ref_stride, const uint8_t *second_pred) { \
968 return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred); \
970 static unsigned int fnname##_bits10( \
971 const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr, \
972 int ref_stride, const uint8_t *second_pred) { \
973 return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred) >> \
976 static unsigned int fnname##_bits12( \
977 const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr, \
978 int ref_stride, const uint8_t *second_pred) { \
979 return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred) >> \
983 #define MAKE_BFP_SAD3_WRAPPER(fnname) \
984 static void fnname##_bits8(const uint8_t *src_ptr, int source_stride, \
985 const uint8_t *ref_ptr, int ref_stride, \
986 unsigned int *sad_array) { \
987 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
989 static void fnname##_bits10(const uint8_t *src_ptr, int source_stride, \
990 const uint8_t *ref_ptr, int ref_stride, \
991 unsigned int *sad_array) { \
993 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
994 for (i = 0; i < 3; i++) sad_array[i] >>= 2; \
996 static void fnname##_bits12(const uint8_t *src_ptr, int source_stride, \
997 const uint8_t *ref_ptr, int ref_stride, \
998 unsigned int *sad_array) { \
1000 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1001 for (i = 0; i < 3; i++) sad_array[i] >>= 4; \
1004 #define MAKE_BFP_SAD8_WRAPPER(fnname) \
1005 static void fnname##_bits8(const uint8_t *src_ptr, int source_stride, \
1006 const uint8_t *ref_ptr, int ref_stride, \
1007 unsigned int *sad_array) { \
1008 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1010 static void fnname##_bits10(const uint8_t *src_ptr, int source_stride, \
1011 const uint8_t *ref_ptr, int ref_stride, \
1012 unsigned int *sad_array) { \
1014 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1015 for (i = 0; i < 8; i++) sad_array[i] >>= 2; \
1017 static void fnname##_bits12(const uint8_t *src_ptr, int source_stride, \
1018 const uint8_t *ref_ptr, int ref_stride, \
1019 unsigned int *sad_array) { \
1021 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1022 for (i = 0; i < 8; i++) sad_array[i] >>= 4; \
1024 #define MAKE_BFP_SAD4D_WRAPPER(fnname) \
1025 static void fnname##_bits8(const uint8_t *src_ptr, int source_stride, \
1026 const uint8_t *const ref_ptr[], int ref_stride, \
1027 unsigned int *sad_array) { \
1028 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1030 static void fnname##_bits10(const uint8_t *src_ptr, int source_stride, \
1031 const uint8_t *const ref_ptr[], int ref_stride, \
1032 unsigned int *sad_array) { \
1034 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1035 for (i = 0; i < 4; i++) sad_array[i] >>= 2; \
1037 static void fnname##_bits12(const uint8_t *src_ptr, int source_stride, \
1038 const uint8_t *const ref_ptr[], int ref_stride, \
1039 unsigned int *sad_array) { \
1041 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1042 for (i = 0; i < 4; i++) sad_array[i] >>= 4; \
1045 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x16)
1046 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x16_avg)
1047 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x16x4d)
1048 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x32)
1049 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x32_avg)
1050 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x32x4d)
1051 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad64x32)
1052 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad64x32_avg)
1053 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad64x32x4d)
1054 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x64)
1055 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x64_avg)
1056 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x64x4d)
1057 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x32)
1058 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x32_avg)
1059 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad32x32x3)
1060 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad32x32x8)
1061 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x32x4d)
1062 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad64x64)
1063 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad64x64_avg)
1064 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad64x64x3)
1065 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad64x64x8)
1066 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad64x64x4d)
1067 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x16)
1068 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x16_avg)
1069 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad16x16x3)
1070 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad16x16x8)
1071 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x16x4d)
1072 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x8)
1073 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x8_avg)
1074 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad16x8x3)
1075 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad16x8x8)
1076 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x8x4d)
1077 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x16)
1078 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x16_avg)
1079 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad8x16x3)
1080 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x16x8)
1081 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x16x4d)
1082 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x8)
1083 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x8_avg)
1084 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad8x8x3)
1085 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x8x8)
1086 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x8x4d)
1087 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x4)
1088 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x4_avg)
1089 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x4x8)
1090 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x4x4d)
1091 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad4x8)
1092 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad4x8_avg)
1093 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad4x8x8)
1094 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad4x8x4d)
1095 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad4x4)
1096 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad4x4_avg)
1097 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad4x4x3)
1098 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad4x4x8)
1099 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad4x4x4d)
1101 static void highbd_set_var_fns(VP9_COMP *const cpi) {
1102 VP9_COMMON *const cm = &cpi->common;
1103 if (cm->use_highbitdepth) {
1104 switch (cm->bit_depth) {
1106 HIGHBD_BFP(BLOCK_32X16, vpx_highbd_sad32x16_bits8,
1107 vpx_highbd_sad32x16_avg_bits8, vpx_highbd_8_variance32x16,
1108 vpx_highbd_8_sub_pixel_variance32x16,
1109 vpx_highbd_8_sub_pixel_avg_variance32x16, NULL, NULL,
1110 vpx_highbd_sad32x16x4d_bits8)
1112 HIGHBD_BFP(BLOCK_16X32, vpx_highbd_sad16x32_bits8,
1113 vpx_highbd_sad16x32_avg_bits8, vpx_highbd_8_variance16x32,
1114 vpx_highbd_8_sub_pixel_variance16x32,
1115 vpx_highbd_8_sub_pixel_avg_variance16x32, NULL, NULL,
1116 vpx_highbd_sad16x32x4d_bits8)
1118 HIGHBD_BFP(BLOCK_64X32, vpx_highbd_sad64x32_bits8,
1119 vpx_highbd_sad64x32_avg_bits8, vpx_highbd_8_variance64x32,
1120 vpx_highbd_8_sub_pixel_variance64x32,
1121 vpx_highbd_8_sub_pixel_avg_variance64x32, NULL, NULL,
1122 vpx_highbd_sad64x32x4d_bits8)
1124 HIGHBD_BFP(BLOCK_32X64, vpx_highbd_sad32x64_bits8,
1125 vpx_highbd_sad32x64_avg_bits8, vpx_highbd_8_variance32x64,
1126 vpx_highbd_8_sub_pixel_variance32x64,
1127 vpx_highbd_8_sub_pixel_avg_variance32x64, NULL, NULL,
1128 vpx_highbd_sad32x64x4d_bits8)
1130 HIGHBD_BFP(BLOCK_32X32, vpx_highbd_sad32x32_bits8,
1131 vpx_highbd_sad32x32_avg_bits8, vpx_highbd_8_variance32x32,
1132 vpx_highbd_8_sub_pixel_variance32x32,
1133 vpx_highbd_8_sub_pixel_avg_variance32x32,
1134 vpx_highbd_sad32x32x3_bits8, vpx_highbd_sad32x32x8_bits8,
1135 vpx_highbd_sad32x32x4d_bits8)
1137 HIGHBD_BFP(BLOCK_64X64, vpx_highbd_sad64x64_bits8,
1138 vpx_highbd_sad64x64_avg_bits8, vpx_highbd_8_variance64x64,
1139 vpx_highbd_8_sub_pixel_variance64x64,
1140 vpx_highbd_8_sub_pixel_avg_variance64x64,
1141 vpx_highbd_sad64x64x3_bits8, vpx_highbd_sad64x64x8_bits8,
1142 vpx_highbd_sad64x64x4d_bits8)
1144 HIGHBD_BFP(BLOCK_16X16, vpx_highbd_sad16x16_bits8,
1145 vpx_highbd_sad16x16_avg_bits8, vpx_highbd_8_variance16x16,
1146 vpx_highbd_8_sub_pixel_variance16x16,
1147 vpx_highbd_8_sub_pixel_avg_variance16x16,
1148 vpx_highbd_sad16x16x3_bits8, vpx_highbd_sad16x16x8_bits8,
1149 vpx_highbd_sad16x16x4d_bits8)
1152 BLOCK_16X8, vpx_highbd_sad16x8_bits8, vpx_highbd_sad16x8_avg_bits8,
1153 vpx_highbd_8_variance16x8, vpx_highbd_8_sub_pixel_variance16x8,
1154 vpx_highbd_8_sub_pixel_avg_variance16x8, vpx_highbd_sad16x8x3_bits8,
1155 vpx_highbd_sad16x8x8_bits8, vpx_highbd_sad16x8x4d_bits8)
1158 BLOCK_8X16, vpx_highbd_sad8x16_bits8, vpx_highbd_sad8x16_avg_bits8,
1159 vpx_highbd_8_variance8x16, vpx_highbd_8_sub_pixel_variance8x16,
1160 vpx_highbd_8_sub_pixel_avg_variance8x16, vpx_highbd_sad8x16x3_bits8,
1161 vpx_highbd_sad8x16x8_bits8, vpx_highbd_sad8x16x4d_bits8)
1164 BLOCK_8X8, vpx_highbd_sad8x8_bits8, vpx_highbd_sad8x8_avg_bits8,
1165 vpx_highbd_8_variance8x8, vpx_highbd_8_sub_pixel_variance8x8,
1166 vpx_highbd_8_sub_pixel_avg_variance8x8, vpx_highbd_sad8x8x3_bits8,
1167 vpx_highbd_sad8x8x8_bits8, vpx_highbd_sad8x8x4d_bits8)
1169 HIGHBD_BFP(BLOCK_8X4, vpx_highbd_sad8x4_bits8,
1170 vpx_highbd_sad8x4_avg_bits8, vpx_highbd_8_variance8x4,
1171 vpx_highbd_8_sub_pixel_variance8x4,
1172 vpx_highbd_8_sub_pixel_avg_variance8x4, NULL,
1173 vpx_highbd_sad8x4x8_bits8, vpx_highbd_sad8x4x4d_bits8)
1175 HIGHBD_BFP(BLOCK_4X8, vpx_highbd_sad4x8_bits8,
1176 vpx_highbd_sad4x8_avg_bits8, vpx_highbd_8_variance4x8,
1177 vpx_highbd_8_sub_pixel_variance4x8,
1178 vpx_highbd_8_sub_pixel_avg_variance4x8, NULL,
1179 vpx_highbd_sad4x8x8_bits8, vpx_highbd_sad4x8x4d_bits8)
1182 BLOCK_4X4, vpx_highbd_sad4x4_bits8, vpx_highbd_sad4x4_avg_bits8,
1183 vpx_highbd_8_variance4x4, vpx_highbd_8_sub_pixel_variance4x4,
1184 vpx_highbd_8_sub_pixel_avg_variance4x4, vpx_highbd_sad4x4x3_bits8,
1185 vpx_highbd_sad4x4x8_bits8, vpx_highbd_sad4x4x4d_bits8)
1189 HIGHBD_BFP(BLOCK_32X16, vpx_highbd_sad32x16_bits10,
1190 vpx_highbd_sad32x16_avg_bits10, vpx_highbd_10_variance32x16,
1191 vpx_highbd_10_sub_pixel_variance32x16,
1192 vpx_highbd_10_sub_pixel_avg_variance32x16, NULL, NULL,
1193 vpx_highbd_sad32x16x4d_bits10)
1195 HIGHBD_BFP(BLOCK_16X32, vpx_highbd_sad16x32_bits10,
1196 vpx_highbd_sad16x32_avg_bits10, vpx_highbd_10_variance16x32,
1197 vpx_highbd_10_sub_pixel_variance16x32,
1198 vpx_highbd_10_sub_pixel_avg_variance16x32, NULL, NULL,
1199 vpx_highbd_sad16x32x4d_bits10)
1201 HIGHBD_BFP(BLOCK_64X32, vpx_highbd_sad64x32_bits10,
1202 vpx_highbd_sad64x32_avg_bits10, vpx_highbd_10_variance64x32,
1203 vpx_highbd_10_sub_pixel_variance64x32,
1204 vpx_highbd_10_sub_pixel_avg_variance64x32, NULL, NULL,
1205 vpx_highbd_sad64x32x4d_bits10)
1207 HIGHBD_BFP(BLOCK_32X64, vpx_highbd_sad32x64_bits10,
1208 vpx_highbd_sad32x64_avg_bits10, vpx_highbd_10_variance32x64,
1209 vpx_highbd_10_sub_pixel_variance32x64,
1210 vpx_highbd_10_sub_pixel_avg_variance32x64, NULL, NULL,
1211 vpx_highbd_sad32x64x4d_bits10)
1213 HIGHBD_BFP(BLOCK_32X32, vpx_highbd_sad32x32_bits10,
1214 vpx_highbd_sad32x32_avg_bits10, vpx_highbd_10_variance32x32,
1215 vpx_highbd_10_sub_pixel_variance32x32,
1216 vpx_highbd_10_sub_pixel_avg_variance32x32,
1217 vpx_highbd_sad32x32x3_bits10, vpx_highbd_sad32x32x8_bits10,
1218 vpx_highbd_sad32x32x4d_bits10)
1220 HIGHBD_BFP(BLOCK_64X64, vpx_highbd_sad64x64_bits10,
1221 vpx_highbd_sad64x64_avg_bits10, vpx_highbd_10_variance64x64,
1222 vpx_highbd_10_sub_pixel_variance64x64,
1223 vpx_highbd_10_sub_pixel_avg_variance64x64,
1224 vpx_highbd_sad64x64x3_bits10, vpx_highbd_sad64x64x8_bits10,
1225 vpx_highbd_sad64x64x4d_bits10)
1227 HIGHBD_BFP(BLOCK_16X16, vpx_highbd_sad16x16_bits10,
1228 vpx_highbd_sad16x16_avg_bits10, vpx_highbd_10_variance16x16,
1229 vpx_highbd_10_sub_pixel_variance16x16,
1230 vpx_highbd_10_sub_pixel_avg_variance16x16,
1231 vpx_highbd_sad16x16x3_bits10, vpx_highbd_sad16x16x8_bits10,
1232 vpx_highbd_sad16x16x4d_bits10)
1234 HIGHBD_BFP(BLOCK_16X8, vpx_highbd_sad16x8_bits10,
1235 vpx_highbd_sad16x8_avg_bits10, vpx_highbd_10_variance16x8,
1236 vpx_highbd_10_sub_pixel_variance16x8,
1237 vpx_highbd_10_sub_pixel_avg_variance16x8,
1238 vpx_highbd_sad16x8x3_bits10, vpx_highbd_sad16x8x8_bits10,
1239 vpx_highbd_sad16x8x4d_bits10)
1241 HIGHBD_BFP(BLOCK_8X16, vpx_highbd_sad8x16_bits10,
1242 vpx_highbd_sad8x16_avg_bits10, vpx_highbd_10_variance8x16,
1243 vpx_highbd_10_sub_pixel_variance8x16,
1244 vpx_highbd_10_sub_pixel_avg_variance8x16,
1245 vpx_highbd_sad8x16x3_bits10, vpx_highbd_sad8x16x8_bits10,
1246 vpx_highbd_sad8x16x4d_bits10)
1249 BLOCK_8X8, vpx_highbd_sad8x8_bits10, vpx_highbd_sad8x8_avg_bits10,
1250 vpx_highbd_10_variance8x8, vpx_highbd_10_sub_pixel_variance8x8,
1251 vpx_highbd_10_sub_pixel_avg_variance8x8, vpx_highbd_sad8x8x3_bits10,
1252 vpx_highbd_sad8x8x8_bits10, vpx_highbd_sad8x8x4d_bits10)
1254 HIGHBD_BFP(BLOCK_8X4, vpx_highbd_sad8x4_bits10,
1255 vpx_highbd_sad8x4_avg_bits10, vpx_highbd_10_variance8x4,
1256 vpx_highbd_10_sub_pixel_variance8x4,
1257 vpx_highbd_10_sub_pixel_avg_variance8x4, NULL,
1258 vpx_highbd_sad8x4x8_bits10, vpx_highbd_sad8x4x4d_bits10)
1260 HIGHBD_BFP(BLOCK_4X8, vpx_highbd_sad4x8_bits10,
1261 vpx_highbd_sad4x8_avg_bits10, vpx_highbd_10_variance4x8,
1262 vpx_highbd_10_sub_pixel_variance4x8,
1263 vpx_highbd_10_sub_pixel_avg_variance4x8, NULL,
1264 vpx_highbd_sad4x8x8_bits10, vpx_highbd_sad4x8x4d_bits10)
1267 BLOCK_4X4, vpx_highbd_sad4x4_bits10, vpx_highbd_sad4x4_avg_bits10,
1268 vpx_highbd_10_variance4x4, vpx_highbd_10_sub_pixel_variance4x4,
1269 vpx_highbd_10_sub_pixel_avg_variance4x4, vpx_highbd_sad4x4x3_bits10,
1270 vpx_highbd_sad4x4x8_bits10, vpx_highbd_sad4x4x4d_bits10)
1274 HIGHBD_BFP(BLOCK_32X16, vpx_highbd_sad32x16_bits12,
1275 vpx_highbd_sad32x16_avg_bits12, vpx_highbd_12_variance32x16,
1276 vpx_highbd_12_sub_pixel_variance32x16,
1277 vpx_highbd_12_sub_pixel_avg_variance32x16, NULL, NULL,
1278 vpx_highbd_sad32x16x4d_bits12)
1280 HIGHBD_BFP(BLOCK_16X32, vpx_highbd_sad16x32_bits12,
1281 vpx_highbd_sad16x32_avg_bits12, vpx_highbd_12_variance16x32,
1282 vpx_highbd_12_sub_pixel_variance16x32,
1283 vpx_highbd_12_sub_pixel_avg_variance16x32, NULL, NULL,
1284 vpx_highbd_sad16x32x4d_bits12)
1286 HIGHBD_BFP(BLOCK_64X32, vpx_highbd_sad64x32_bits12,
1287 vpx_highbd_sad64x32_avg_bits12, vpx_highbd_12_variance64x32,
1288 vpx_highbd_12_sub_pixel_variance64x32,
1289 vpx_highbd_12_sub_pixel_avg_variance64x32, NULL, NULL,
1290 vpx_highbd_sad64x32x4d_bits12)
1292 HIGHBD_BFP(BLOCK_32X64, vpx_highbd_sad32x64_bits12,
1293 vpx_highbd_sad32x64_avg_bits12, vpx_highbd_12_variance32x64,
1294 vpx_highbd_12_sub_pixel_variance32x64,
1295 vpx_highbd_12_sub_pixel_avg_variance32x64, NULL, NULL,
1296 vpx_highbd_sad32x64x4d_bits12)
1298 HIGHBD_BFP(BLOCK_32X32, vpx_highbd_sad32x32_bits12,
1299 vpx_highbd_sad32x32_avg_bits12, vpx_highbd_12_variance32x32,
1300 vpx_highbd_12_sub_pixel_variance32x32,
1301 vpx_highbd_12_sub_pixel_avg_variance32x32,
1302 vpx_highbd_sad32x32x3_bits12, vpx_highbd_sad32x32x8_bits12,
1303 vpx_highbd_sad32x32x4d_bits12)
1305 HIGHBD_BFP(BLOCK_64X64, vpx_highbd_sad64x64_bits12,
1306 vpx_highbd_sad64x64_avg_bits12, vpx_highbd_12_variance64x64,
1307 vpx_highbd_12_sub_pixel_variance64x64,
1308 vpx_highbd_12_sub_pixel_avg_variance64x64,
1309 vpx_highbd_sad64x64x3_bits12, vpx_highbd_sad64x64x8_bits12,
1310 vpx_highbd_sad64x64x4d_bits12)
1312 HIGHBD_BFP(BLOCK_16X16, vpx_highbd_sad16x16_bits12,
1313 vpx_highbd_sad16x16_avg_bits12, vpx_highbd_12_variance16x16,
1314 vpx_highbd_12_sub_pixel_variance16x16,
1315 vpx_highbd_12_sub_pixel_avg_variance16x16,
1316 vpx_highbd_sad16x16x3_bits12, vpx_highbd_sad16x16x8_bits12,
1317 vpx_highbd_sad16x16x4d_bits12)
1319 HIGHBD_BFP(BLOCK_16X8, vpx_highbd_sad16x8_bits12,
1320 vpx_highbd_sad16x8_avg_bits12, vpx_highbd_12_variance16x8,
1321 vpx_highbd_12_sub_pixel_variance16x8,
1322 vpx_highbd_12_sub_pixel_avg_variance16x8,
1323 vpx_highbd_sad16x8x3_bits12, vpx_highbd_sad16x8x8_bits12,
1324 vpx_highbd_sad16x8x4d_bits12)
1326 HIGHBD_BFP(BLOCK_8X16, vpx_highbd_sad8x16_bits12,
1327 vpx_highbd_sad8x16_avg_bits12, vpx_highbd_12_variance8x16,
1328 vpx_highbd_12_sub_pixel_variance8x16,
1329 vpx_highbd_12_sub_pixel_avg_variance8x16,
1330 vpx_highbd_sad8x16x3_bits12, vpx_highbd_sad8x16x8_bits12,
1331 vpx_highbd_sad8x16x4d_bits12)
1334 BLOCK_8X8, vpx_highbd_sad8x8_bits12, vpx_highbd_sad8x8_avg_bits12,
1335 vpx_highbd_12_variance8x8, vpx_highbd_12_sub_pixel_variance8x8,
1336 vpx_highbd_12_sub_pixel_avg_variance8x8, vpx_highbd_sad8x8x3_bits12,
1337 vpx_highbd_sad8x8x8_bits12, vpx_highbd_sad8x8x4d_bits12)
1339 HIGHBD_BFP(BLOCK_8X4, vpx_highbd_sad8x4_bits12,
1340 vpx_highbd_sad8x4_avg_bits12, vpx_highbd_12_variance8x4,
1341 vpx_highbd_12_sub_pixel_variance8x4,
1342 vpx_highbd_12_sub_pixel_avg_variance8x4, NULL,
1343 vpx_highbd_sad8x4x8_bits12, vpx_highbd_sad8x4x4d_bits12)
1345 HIGHBD_BFP(BLOCK_4X8, vpx_highbd_sad4x8_bits12,
1346 vpx_highbd_sad4x8_avg_bits12, vpx_highbd_12_variance4x8,
1347 vpx_highbd_12_sub_pixel_variance4x8,
1348 vpx_highbd_12_sub_pixel_avg_variance4x8, NULL,
1349 vpx_highbd_sad4x8x8_bits12, vpx_highbd_sad4x8x4d_bits12)
1352 BLOCK_4X4, vpx_highbd_sad4x4_bits12, vpx_highbd_sad4x4_avg_bits12,
1353 vpx_highbd_12_variance4x4, vpx_highbd_12_sub_pixel_variance4x4,
1354 vpx_highbd_12_sub_pixel_avg_variance4x4, vpx_highbd_sad4x4x3_bits12,
1355 vpx_highbd_sad4x4x8_bits12, vpx_highbd_sad4x4x4d_bits12)
1360 "cm->bit_depth should be VPX_BITS_8, "
1361 "VPX_BITS_10 or VPX_BITS_12");
1365 #endif // CONFIG_VP9_HIGHBITDEPTH
1367 static void realloc_segmentation_maps(VP9_COMP *cpi) {
1368 VP9_COMMON *const cm = &cpi->common;
1370 // Create the encoder segmentation map and set all entries to 0
1371 vpx_free(cpi->segmentation_map);
1372 CHECK_MEM_ERROR(cm, cpi->segmentation_map,
1373 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1375 // Create a map used for cyclic background refresh.
1376 if (cpi->cyclic_refresh) vp9_cyclic_refresh_free(cpi->cyclic_refresh);
1377 CHECK_MEM_ERROR(cm, cpi->cyclic_refresh,
1378 vp9_cyclic_refresh_alloc(cm->mi_rows, cm->mi_cols));
1380 // Create a map used to mark inactive areas.
1381 vpx_free(cpi->active_map.map);
1382 CHECK_MEM_ERROR(cm, cpi->active_map.map,
1383 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1385 // And a place holder structure is the coding context
1386 // for use if we want to save and restore it
1387 vpx_free(cpi->coding_context.last_frame_seg_map_copy);
1388 CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
1389 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1392 void vp9_change_config(struct VP9_COMP *cpi, const VP9EncoderConfig *oxcf) {
1393 VP9_COMMON *const cm = &cpi->common;
1394 RATE_CONTROL *const rc = &cpi->rc;
1395 int last_w = cpi->oxcf.width;
1396 int last_h = cpi->oxcf.height;
1398 if (cm->profile != oxcf->profile) cm->profile = oxcf->profile;
1399 cm->bit_depth = oxcf->bit_depth;
1400 cm->color_space = oxcf->color_space;
1401 cm->color_range = oxcf->color_range;
1403 cpi->target_level = oxcf->target_level;
1404 cpi->keep_level_stats = oxcf->target_level != LEVEL_MAX;
1406 if (cm->profile <= PROFILE_1)
1407 assert(cm->bit_depth == VPX_BITS_8);
1409 assert(cm->bit_depth > VPX_BITS_8);
1412 #if CONFIG_VP9_HIGHBITDEPTH
1413 cpi->td.mb.e_mbd.bd = (int)cm->bit_depth;
1414 #endif // CONFIG_VP9_HIGHBITDEPTH
1416 if ((oxcf->pass == 0) && (oxcf->rc_mode == VPX_Q)) {
1417 rc->baseline_gf_interval = FIXED_GF_INTERVAL;
1419 rc->baseline_gf_interval = (MIN_GF_INTERVAL + MAX_GF_INTERVAL) / 2;
1422 cpi->refresh_golden_frame = 0;
1423 cpi->refresh_last_frame = 1;
1424 cm->refresh_frame_context = 1;
1425 cm->reset_frame_context = 0;
1427 vp9_reset_segment_features(&cm->seg);
1428 vp9_set_high_precision_mv(cpi, 0);
1433 for (i = 0; i < MAX_SEGMENTS; i++)
1434 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1436 cpi->encode_breakout = cpi->oxcf.encode_breakout;
1438 set_rc_buffer_sizes(rc, &cpi->oxcf);
1440 // Under a configuration change, where maximum_buffer_size may change,
1441 // keep buffer level clipped to the maximum allowed buffer size.
1442 rc->bits_off_target = VPXMIN(rc->bits_off_target, rc->maximum_buffer_size);
1443 rc->buffer_level = VPXMIN(rc->buffer_level, rc->maximum_buffer_size);
1445 // Set up frame rate and related parameters rate control values.
1446 vp9_new_framerate(cpi, cpi->framerate);
1448 // Set absolute upper and lower quality limits
1449 rc->worst_quality = cpi->oxcf.worst_allowed_q;
1450 rc->best_quality = cpi->oxcf.best_allowed_q;
1452 cm->interp_filter = cpi->sf.default_interp_filter;
1454 if (cpi->oxcf.render_width > 0 && cpi->oxcf.render_height > 0) {
1455 cm->render_width = cpi->oxcf.render_width;
1456 cm->render_height = cpi->oxcf.render_height;
1458 cm->render_width = cpi->oxcf.width;
1459 cm->render_height = cpi->oxcf.height;
1461 if (last_w != cpi->oxcf.width || last_h != cpi->oxcf.height) {
1462 cm->width = cpi->oxcf.width;
1463 cm->height = cpi->oxcf.height;
1464 cpi->external_resize = 1;
1467 if (cpi->initial_width) {
1468 int new_mi_size = 0;
1469 vp9_set_mb_mi(cm, cm->width, cm->height);
1470 new_mi_size = cm->mi_stride * calc_mi_size(cm->mi_rows);
1471 if (cm->mi_alloc_size < new_mi_size) {
1472 vp9_free_context_buffers(cm);
1473 alloc_compressor_data(cpi);
1474 realloc_segmentation_maps(cpi);
1475 cpi->initial_width = cpi->initial_height = 0;
1476 cpi->external_resize = 0;
1477 } else if (cm->mi_alloc_size == new_mi_size &&
1478 (cpi->oxcf.width > last_w || cpi->oxcf.height > last_h)) {
1479 vp9_alloc_loop_filter(cm);
1483 update_frame_size(cpi);
1485 if (last_w != cpi->oxcf.width || last_h != cpi->oxcf.height) {
1486 memset(cpi->consec_zero_mv, 0,
1487 cm->mi_rows * cm->mi_cols * sizeof(*cpi->consec_zero_mv));
1488 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1489 vp9_cyclic_refresh_reset_resize(cpi);
1492 if ((cpi->svc.number_temporal_layers > 1 && cpi->oxcf.rc_mode == VPX_CBR) ||
1493 ((cpi->svc.number_temporal_layers > 1 ||
1494 cpi->svc.number_spatial_layers > 1) &&
1495 cpi->oxcf.pass != 1)) {
1496 vp9_update_layer_context_change_config(cpi,
1497 (int)cpi->oxcf.target_bandwidth);
1500 cpi->alt_ref_source = NULL;
1501 rc->is_src_frame_alt_ref = 0;
1504 // Experimental RD Code
1505 cpi->frame_distortion = 0;
1506 cpi->last_frame_distortion = 0;
1509 set_tile_limits(cpi);
1511 cpi->ext_refresh_frame_flags_pending = 0;
1512 cpi->ext_refresh_frame_context_pending = 0;
1514 #if CONFIG_VP9_HIGHBITDEPTH
1515 highbd_set_var_fns(cpi);
1520 #define M_LOG2_E 0.693147180559945309417
1522 #define log2f(x) (log(x) / (float)M_LOG2_E)
1524 /***********************************************************************
1525 * Read before modifying 'cal_nmvjointsadcost' or 'cal_nmvsadcosts' *
1526 ***********************************************************************
1527 * The following 2 functions ('cal_nmvjointsadcost' and *
1528 * 'cal_nmvsadcosts') are used to calculate cost lookup tables *
1529 * used by 'vp9_diamond_search_sad'. The C implementation of the *
1530 * function is generic, but the AVX intrinsics optimised version *
1531 * relies on the following properties of the computed tables: *
1532 * For cal_nmvjointsadcost: *
1533 * - mvjointsadcost[1] == mvjointsadcost[2] == mvjointsadcost[3] *
1534 * For cal_nmvsadcosts: *
1535 * - For all i: mvsadcost[0][i] == mvsadcost[1][i] *
1536 * (Equal costs for both components) *
1537 * - For all i: mvsadcost[0][i] == mvsadcost[0][-i] *
1538 * (Cost function is even) *
1539 * If these do not hold, then the AVX optimised version of the *
1540 * 'vp9_diamond_search_sad' function cannot be used as it is, in which *
1541 * case you can revert to using the C function instead. *
1542 ***********************************************************************/
1544 static void cal_nmvjointsadcost(int *mvjointsadcost) {
1545 /*********************************************************************
1546 * Warning: Read the comments above before modifying this function *
1547 *********************************************************************/
1548 mvjointsadcost[0] = 600;
1549 mvjointsadcost[1] = 300;
1550 mvjointsadcost[2] = 300;
1551 mvjointsadcost[3] = 300;
1554 static void cal_nmvsadcosts(int *mvsadcost[2]) {
1555 /*********************************************************************
1556 * Warning: Read the comments above before modifying this function *
1557 *********************************************************************/
1560 mvsadcost[0][0] = 0;
1561 mvsadcost[1][0] = 0;
1564 double z = 256 * (2 * (log2f(8 * i) + .6));
1565 mvsadcost[0][i] = (int)z;
1566 mvsadcost[1][i] = (int)z;
1567 mvsadcost[0][-i] = (int)z;
1568 mvsadcost[1][-i] = (int)z;
1569 } while (++i <= MV_MAX);
1572 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
1575 mvsadcost[0][0] = 0;
1576 mvsadcost[1][0] = 0;
1579 double z = 256 * (2 * (log2f(8 * i) + .6));
1580 mvsadcost[0][i] = (int)z;
1581 mvsadcost[1][i] = (int)z;
1582 mvsadcost[0][-i] = (int)z;
1583 mvsadcost[1][-i] = (int)z;
1584 } while (++i <= MV_MAX);
1587 VP9_COMP *vp9_create_compressor(VP9EncoderConfig *oxcf,
1588 BufferPool *const pool) {
1590 VP9_COMP *volatile const cpi = vpx_memalign(32, sizeof(VP9_COMP));
1591 VP9_COMMON *volatile const cm = cpi != NULL ? &cpi->common : NULL;
1593 if (!cm) return NULL;
1597 if (setjmp(cm->error.jmp)) {
1598 cm->error.setjmp = 0;
1599 vp9_remove_compressor(cpi);
1603 cm->error.setjmp = 1;
1604 cm->alloc_mi = vp9_enc_alloc_mi;
1605 cm->free_mi = vp9_enc_free_mi;
1606 cm->setup_mi = vp9_enc_setup_mi;
1608 CHECK_MEM_ERROR(cm, cm->fc, (FRAME_CONTEXT *)vpx_calloc(1, sizeof(*cm->fc)));
1610 cm, cm->frame_contexts,
1611 (FRAME_CONTEXT *)vpx_calloc(FRAME_CONTEXTS, sizeof(*cm->frame_contexts)));
1614 cpi->resize_state = 0;
1615 cpi->external_resize = 0;
1616 cpi->resize_avg_qp = 0;
1617 cpi->resize_buffer_underflow = 0;
1618 cpi->use_skin_detection = 0;
1619 cpi->common.buffer_pool = pool;
1621 init_config(cpi, oxcf);
1622 vp9_rc_init(&cpi->oxcf, oxcf->pass, &cpi->rc);
1624 cm->current_video_frame = 0;
1625 cpi->partition_search_skippable_frame = 0;
1626 cpi->tile_data = NULL;
1628 realloc_segmentation_maps(cpi);
1631 cm, cpi->consec_zero_mv,
1632 vpx_calloc(cm->mi_rows * cm->mi_cols, sizeof(*cpi->consec_zero_mv)));
1634 CHECK_MEM_ERROR(cm, cpi->nmvcosts[0],
1635 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts[0])));
1636 CHECK_MEM_ERROR(cm, cpi->nmvcosts[1],
1637 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts[1])));
1638 CHECK_MEM_ERROR(cm, cpi->nmvcosts_hp[0],
1639 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts_hp[0])));
1640 CHECK_MEM_ERROR(cm, cpi->nmvcosts_hp[1],
1641 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts_hp[1])));
1642 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts[0],
1643 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts[0])));
1644 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts[1],
1645 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts[1])));
1646 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts_hp[0],
1647 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts_hp[0])));
1648 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts_hp[1],
1649 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts_hp[1])));
1651 for (i = 0; i < (sizeof(cpi->mbgraph_stats) / sizeof(cpi->mbgraph_stats[0]));
1654 cm, cpi->mbgraph_stats[i].mb_stats,
1655 vpx_calloc(cm->MBs * sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
1658 #if CONFIG_FP_MB_STATS
1659 cpi->use_fp_mb_stats = 0;
1660 if (cpi->use_fp_mb_stats) {
1661 // a place holder used to store the first pass mb stats in the first pass
1662 CHECK_MEM_ERROR(cm, cpi->twopass.frame_mb_stats_buf,
1663 vpx_calloc(cm->MBs * sizeof(uint8_t), 1));
1665 cpi->twopass.frame_mb_stats_buf = NULL;
1669 cpi->refresh_alt_ref_frame = 0;
1670 cpi->multi_arf_last_grp_enabled = 0;
1672 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1674 init_level_info(&cpi->level_info);
1676 #if CONFIG_INTERNAL_STATS
1677 cpi->b_calculate_blockiness = 1;
1678 cpi->b_calculate_consistency = 1;
1679 cpi->total_inconsistency = 0;
1680 cpi->psnr.worst = 100.0;
1681 cpi->worst_ssim = 100.0;
1686 if (cpi->b_calculate_psnr) {
1687 cpi->total_sq_error = 0;
1688 cpi->total_samples = 0;
1690 cpi->totalp_sq_error = 0;
1691 cpi->totalp_samples = 0;
1693 cpi->tot_recode_hits = 0;
1694 cpi->summed_quality = 0;
1695 cpi->summed_weights = 0;
1696 cpi->summedp_quality = 0;
1697 cpi->summedp_weights = 0;
1700 cpi->fastssim.worst = 100.0;
1702 cpi->psnrhvs.worst = 100.0;
1704 if (cpi->b_calculate_blockiness) {
1705 cpi->total_blockiness = 0;
1706 cpi->worst_blockiness = 0.0;
1709 if (cpi->b_calculate_consistency) {
1710 CHECK_MEM_ERROR(cm, cpi->ssim_vars,
1711 vpx_malloc(sizeof(*cpi->ssim_vars) * 4 *
1712 cpi->common.mi_rows * cpi->common.mi_cols));
1713 cpi->worst_consistency = 100.0;
1718 cpi->first_time_stamp_ever = INT64_MAX;
1720 /*********************************************************************
1721 * Warning: Read the comments around 'cal_nmvjointsadcost' and *
1722 * 'cal_nmvsadcosts' before modifying how these tables are computed. *
1723 *********************************************************************/
1724 cal_nmvjointsadcost(cpi->td.mb.nmvjointsadcost);
1725 cpi->td.mb.nmvcost[0] = &cpi->nmvcosts[0][MV_MAX];
1726 cpi->td.mb.nmvcost[1] = &cpi->nmvcosts[1][MV_MAX];
1727 cpi->td.mb.nmvsadcost[0] = &cpi->nmvsadcosts[0][MV_MAX];
1728 cpi->td.mb.nmvsadcost[1] = &cpi->nmvsadcosts[1][MV_MAX];
1729 cal_nmvsadcosts(cpi->td.mb.nmvsadcost);
1731 cpi->td.mb.nmvcost_hp[0] = &cpi->nmvcosts_hp[0][MV_MAX];
1732 cpi->td.mb.nmvcost_hp[1] = &cpi->nmvcosts_hp[1][MV_MAX];
1733 cpi->td.mb.nmvsadcost_hp[0] = &cpi->nmvsadcosts_hp[0][MV_MAX];
1734 cpi->td.mb.nmvsadcost_hp[1] = &cpi->nmvsadcosts_hp[1][MV_MAX];
1735 cal_nmvsadcosts_hp(cpi->td.mb.nmvsadcost_hp);
1737 #if CONFIG_VP9_TEMPORAL_DENOISING
1738 #ifdef OUTPUT_YUV_DENOISED
1739 yuv_denoised_file = fopen("denoised.yuv", "ab");
1742 #ifdef OUTPUT_YUV_SKINMAP
1743 yuv_skinmap_file = fopen("skinmap.yuv", "ab");
1745 #ifdef OUTPUT_YUV_REC
1746 yuv_rec_file = fopen("rec.yuv", "wb");
1750 framepsnr = fopen("framepsnr.stt", "a");
1751 kf_list = fopen("kf_list.stt", "w");
1754 cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
1756 if (oxcf->pass == 1) {
1757 vp9_init_first_pass(cpi);
1758 } else if (oxcf->pass == 2) {
1759 const size_t packet_sz = sizeof(FIRSTPASS_STATS);
1760 const int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
1762 if (cpi->svc.number_spatial_layers > 1 ||
1763 cpi->svc.number_temporal_layers > 1) {
1764 FIRSTPASS_STATS *const stats = oxcf->two_pass_stats_in.buf;
1765 FIRSTPASS_STATS *stats_copy[VPX_SS_MAX_LAYERS] = { 0 };
1768 for (i = 0; i < oxcf->ss_number_layers; ++i) {
1769 FIRSTPASS_STATS *const last_packet_for_layer =
1770 &stats[packets - oxcf->ss_number_layers + i];
1771 const int layer_id = (int)last_packet_for_layer->spatial_layer_id;
1772 const int packets_in_layer = (int)last_packet_for_layer->count + 1;
1773 if (layer_id >= 0 && layer_id < oxcf->ss_number_layers) {
1774 LAYER_CONTEXT *const lc = &cpi->svc.layer_context[layer_id];
1776 vpx_free(lc->rc_twopass_stats_in.buf);
1778 lc->rc_twopass_stats_in.sz = packets_in_layer * packet_sz;
1779 CHECK_MEM_ERROR(cm, lc->rc_twopass_stats_in.buf,
1780 vpx_malloc(lc->rc_twopass_stats_in.sz));
1781 lc->twopass.stats_in_start = lc->rc_twopass_stats_in.buf;
1782 lc->twopass.stats_in = lc->twopass.stats_in_start;
1783 lc->twopass.stats_in_end =
1784 lc->twopass.stats_in_start + packets_in_layer - 1;
1785 stats_copy[layer_id] = lc->rc_twopass_stats_in.buf;
1789 for (i = 0; i < packets; ++i) {
1790 const int layer_id = (int)stats[i].spatial_layer_id;
1791 if (layer_id >= 0 && layer_id < oxcf->ss_number_layers &&
1792 stats_copy[layer_id] != NULL) {
1793 *stats_copy[layer_id] = stats[i];
1794 ++stats_copy[layer_id];
1798 vp9_init_second_pass_spatial_svc(cpi);
1800 #if CONFIG_FP_MB_STATS
1801 if (cpi->use_fp_mb_stats) {
1802 const size_t psz = cpi->common.MBs * sizeof(uint8_t);
1803 const int ps = (int)(oxcf->firstpass_mb_stats_in.sz / psz);
1805 cpi->twopass.firstpass_mb_stats.mb_stats_start =
1806 oxcf->firstpass_mb_stats_in.buf;
1807 cpi->twopass.firstpass_mb_stats.mb_stats_end =
1808 cpi->twopass.firstpass_mb_stats.mb_stats_start +
1809 (ps - 1) * cpi->common.MBs * sizeof(uint8_t);
1813 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1814 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1815 cpi->twopass.stats_in_end = &cpi->twopass.stats_in[packets - 1];
1817 vp9_init_second_pass(cpi);
1821 vp9_set_speed_features_framesize_independent(cpi);
1822 vp9_set_speed_features_framesize_dependent(cpi);
1824 // Allocate memory to store variances for a frame.
1825 CHECK_MEM_ERROR(cm, cpi->source_diff_var, vpx_calloc(cm->MBs, sizeof(diff)));
1826 cpi->source_var_thresh = 0;
1827 cpi->frames_till_next_var_check = 0;
1829 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF) \
1830 cpi->fn_ptr[BT].sdf = SDF; \
1831 cpi->fn_ptr[BT].sdaf = SDAF; \
1832 cpi->fn_ptr[BT].vf = VF; \
1833 cpi->fn_ptr[BT].svf = SVF; \
1834 cpi->fn_ptr[BT].svaf = SVAF; \
1835 cpi->fn_ptr[BT].sdx3f = SDX3F; \
1836 cpi->fn_ptr[BT].sdx8f = SDX8F; \
1837 cpi->fn_ptr[BT].sdx4df = SDX4DF;
1839 BFP(BLOCK_32X16, vpx_sad32x16, vpx_sad32x16_avg, vpx_variance32x16,
1840 vpx_sub_pixel_variance32x16, vpx_sub_pixel_avg_variance32x16, NULL, NULL,
1843 BFP(BLOCK_16X32, vpx_sad16x32, vpx_sad16x32_avg, vpx_variance16x32,
1844 vpx_sub_pixel_variance16x32, vpx_sub_pixel_avg_variance16x32, NULL, NULL,
1847 BFP(BLOCK_64X32, vpx_sad64x32, vpx_sad64x32_avg, vpx_variance64x32,
1848 vpx_sub_pixel_variance64x32, vpx_sub_pixel_avg_variance64x32, NULL, NULL,
1851 BFP(BLOCK_32X64, vpx_sad32x64, vpx_sad32x64_avg, vpx_variance32x64,
1852 vpx_sub_pixel_variance32x64, vpx_sub_pixel_avg_variance32x64, NULL, NULL,
1855 BFP(BLOCK_32X32, vpx_sad32x32, vpx_sad32x32_avg, vpx_variance32x32,
1856 vpx_sub_pixel_variance32x32, vpx_sub_pixel_avg_variance32x32,
1857 vpx_sad32x32x3, vpx_sad32x32x8, vpx_sad32x32x4d)
1859 BFP(BLOCK_64X64, vpx_sad64x64, vpx_sad64x64_avg, vpx_variance64x64,
1860 vpx_sub_pixel_variance64x64, vpx_sub_pixel_avg_variance64x64,
1861 vpx_sad64x64x3, vpx_sad64x64x8, vpx_sad64x64x4d)
1863 BFP(BLOCK_16X16, vpx_sad16x16, vpx_sad16x16_avg, vpx_variance16x16,
1864 vpx_sub_pixel_variance16x16, vpx_sub_pixel_avg_variance16x16,
1865 vpx_sad16x16x3, vpx_sad16x16x8, vpx_sad16x16x4d)
1867 BFP(BLOCK_16X8, vpx_sad16x8, vpx_sad16x8_avg, vpx_variance16x8,
1868 vpx_sub_pixel_variance16x8, vpx_sub_pixel_avg_variance16x8, vpx_sad16x8x3,
1869 vpx_sad16x8x8, vpx_sad16x8x4d)
1871 BFP(BLOCK_8X16, vpx_sad8x16, vpx_sad8x16_avg, vpx_variance8x16,
1872 vpx_sub_pixel_variance8x16, vpx_sub_pixel_avg_variance8x16, vpx_sad8x16x3,
1873 vpx_sad8x16x8, vpx_sad8x16x4d)
1875 BFP(BLOCK_8X8, vpx_sad8x8, vpx_sad8x8_avg, vpx_variance8x8,
1876 vpx_sub_pixel_variance8x8, vpx_sub_pixel_avg_variance8x8, vpx_sad8x8x3,
1877 vpx_sad8x8x8, vpx_sad8x8x4d)
1879 BFP(BLOCK_8X4, vpx_sad8x4, vpx_sad8x4_avg, vpx_variance8x4,
1880 vpx_sub_pixel_variance8x4, vpx_sub_pixel_avg_variance8x4, NULL,
1881 vpx_sad8x4x8, vpx_sad8x4x4d)
1883 BFP(BLOCK_4X8, vpx_sad4x8, vpx_sad4x8_avg, vpx_variance4x8,
1884 vpx_sub_pixel_variance4x8, vpx_sub_pixel_avg_variance4x8, NULL,
1885 vpx_sad4x8x8, vpx_sad4x8x4d)
1887 BFP(BLOCK_4X4, vpx_sad4x4, vpx_sad4x4_avg, vpx_variance4x4,
1888 vpx_sub_pixel_variance4x4, vpx_sub_pixel_avg_variance4x4, vpx_sad4x4x3,
1889 vpx_sad4x4x8, vpx_sad4x4x4d)
1891 #if CONFIG_VP9_HIGHBITDEPTH
1892 highbd_set_var_fns(cpi);
1895 /* vp9_init_quantizer() is first called here. Add check in
1896 * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
1897 * called later when needed. This will avoid unnecessary calls of
1898 * vp9_init_quantizer() for every frame.
1900 vp9_init_quantizer(cpi);
1902 vp9_loop_filter_init(cm);
1904 cm->error.setjmp = 0;
1909 #if CONFIG_INTERNAL_STATS
1910 #define SNPRINT(H, T) snprintf((H) + strlen(H), sizeof(H) - strlen(H), (T))
1912 #define SNPRINT2(H, T, V) \
1913 snprintf((H) + strlen(H), sizeof(H) - strlen(H), (T), (V))
1914 #endif // CONFIG_INTERNAL_STATS
1916 void vp9_remove_compressor(VP9_COMP *cpi) {
1924 if (cm->current_video_frame > 0) {
1925 #if CONFIG_INTERNAL_STATS
1926 vpx_clear_system_state();
1928 if (cpi->oxcf.pass != 1) {
1929 char headings[512] = { 0 };
1930 char results[512] = { 0 };
1931 FILE *f = fopen("opsnr.stt", "a");
1932 double time_encoded =
1933 (cpi->last_end_time_stamp_seen - cpi->first_time_stamp_ever) /
1935 double total_encode_time =
1936 (cpi->time_receive_data + cpi->time_compress_data) / 1000.000;
1938 (double)cpi->bytes * (double)8 / (double)1000 / time_encoded;
1939 const double peak = (double)((1 << cpi->oxcf.input_bit_depth) - 1);
1940 const double target_rate = (double)cpi->oxcf.target_bandwidth / 1000;
1941 const double rate_err = ((100.0 * (dr - target_rate)) / target_rate);
1943 if (cpi->b_calculate_psnr) {
1944 const double total_psnr = vpx_sse_to_psnr(
1945 (double)cpi->total_samples, peak, (double)cpi->total_sq_error);
1946 const double totalp_psnr = vpx_sse_to_psnr(
1947 (double)cpi->totalp_samples, peak, (double)cpi->totalp_sq_error);
1948 const double total_ssim =
1949 100 * pow(cpi->summed_quality / cpi->summed_weights, 8.0);
1950 const double totalp_ssim =
1951 100 * pow(cpi->summedp_quality / cpi->summedp_weights, 8.0);
1953 snprintf(headings, sizeof(headings),
1954 "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
1955 "VPXSSIM\tVPSSIMP\tFASTSIM\tPSNRHVS\t"
1956 "WstPsnr\tWstSsim\tWstFast\tWstHVS");
1957 snprintf(results, sizeof(results),
1958 "%7.2f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
1959 "%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
1960 "%7.3f\t%7.3f\t%7.3f\t%7.3f",
1961 dr, cpi->psnr.stat[ALL] / cpi->count, total_psnr,
1962 cpi->psnrp.stat[ALL] / cpi->count, totalp_psnr, total_ssim,
1963 totalp_ssim, cpi->fastssim.stat[ALL] / cpi->count,
1964 cpi->psnrhvs.stat[ALL] / cpi->count, cpi->psnr.worst,
1965 cpi->worst_ssim, cpi->fastssim.worst, cpi->psnrhvs.worst);
1967 if (cpi->b_calculate_blockiness) {
1968 SNPRINT(headings, "\t Block\tWstBlck");
1969 SNPRINT2(results, "\t%7.3f", cpi->total_blockiness / cpi->count);
1970 SNPRINT2(results, "\t%7.3f", cpi->worst_blockiness);
1973 if (cpi->b_calculate_consistency) {
1974 double consistency =
1975 vpx_sse_to_psnr((double)cpi->totalp_samples, peak,
1976 (double)cpi->total_inconsistency);
1978 SNPRINT(headings, "\tConsist\tWstCons");
1979 SNPRINT2(results, "\t%7.3f", consistency);
1980 SNPRINT2(results, "\t%7.3f", cpi->worst_consistency);
1982 fprintf(f, "%s\t Time Rc-Err Abs Err\n", headings);
1983 fprintf(f, "%s\t%8.0f %7.2f %7.2f\n", results, total_encode_time,
1984 rate_err, fabs(rate_err));
1994 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
1995 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
1996 printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
1997 cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
1998 cpi->time_compress_data / 1000,
1999 (cpi->time_receive_data + cpi->time_compress_data) / 1000);
2004 #if CONFIG_VP9_TEMPORAL_DENOISING
2005 vp9_denoiser_free(&(cpi->denoiser));
2008 for (t = 0; t < cpi->num_workers; ++t) {
2009 VPxWorker *const worker = &cpi->workers[t];
2010 EncWorkerData *const thread_data = &cpi->tile_thr_data[t];
2012 // Deallocate allocated threads.
2013 vpx_get_worker_interface()->end(worker);
2015 // Deallocate allocated thread data.
2016 if (t < cpi->num_workers - 1) {
2017 vpx_free(thread_data->td->counts);
2018 vp9_free_pc_tree(thread_data->td);
2019 vpx_free(thread_data->td);
2022 vpx_free(cpi->tile_thr_data);
2023 vpx_free(cpi->workers);
2025 if (cpi->num_workers > 1) vp9_loop_filter_dealloc(&cpi->lf_row_sync);
2027 dealloc_compressor_data(cpi);
2029 for (i = 0; i < sizeof(cpi->mbgraph_stats) / sizeof(cpi->mbgraph_stats[0]);
2031 vpx_free(cpi->mbgraph_stats[i].mb_stats);
2034 #if CONFIG_FP_MB_STATS
2035 if (cpi->use_fp_mb_stats) {
2036 vpx_free(cpi->twopass.frame_mb_stats_buf);
2037 cpi->twopass.frame_mb_stats_buf = NULL;
2041 vp9_remove_common(cm);
2042 vp9_free_ref_frame_buffers(cm->buffer_pool);
2043 #if CONFIG_VP9_POSTPROC
2044 vp9_free_postproc_buffers(cm);
2048 #if CONFIG_VP9_TEMPORAL_DENOISING
2049 #ifdef OUTPUT_YUV_DENOISED
2050 fclose(yuv_denoised_file);
2053 #ifdef OUTPUT_YUV_SKINMAP
2054 fclose(yuv_skinmap_file);
2056 #ifdef OUTPUT_YUV_REC
2057 fclose(yuv_rec_file);
2074 static void generate_psnr_packet(VP9_COMP *cpi) {
2075 struct vpx_codec_cx_pkt pkt;
2078 #if CONFIG_VP9_HIGHBITDEPTH
2079 vpx_calc_highbd_psnr(cpi->raw_source_frame, cpi->common.frame_to_show, &psnr,
2080 cpi->td.mb.e_mbd.bd, cpi->oxcf.input_bit_depth);
2082 vpx_calc_psnr(cpi->raw_source_frame, cpi->common.frame_to_show, &psnr);
2085 for (i = 0; i < 4; ++i) {
2086 pkt.data.psnr.samples[i] = psnr.samples[i];
2087 pkt.data.psnr.sse[i] = psnr.sse[i];
2088 pkt.data.psnr.psnr[i] = psnr.psnr[i];
2090 pkt.kind = VPX_CODEC_PSNR_PKT;
2092 cpi->svc.layer_context[cpi->svc.spatial_layer_id *
2093 cpi->svc.number_temporal_layers]
2094 .psnr_pkt = pkt.data.psnr;
2096 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2099 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags) {
2100 if (ref_frame_flags > 7) return -1;
2102 cpi->ref_frame_flags = ref_frame_flags;
2106 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags) {
2107 cpi->ext_refresh_golden_frame = (ref_frame_flags & VP9_GOLD_FLAG) != 0;
2108 cpi->ext_refresh_alt_ref_frame = (ref_frame_flags & VP9_ALT_FLAG) != 0;
2109 cpi->ext_refresh_last_frame = (ref_frame_flags & VP9_LAST_FLAG) != 0;
2110 cpi->ext_refresh_frame_flags_pending = 1;
2113 static YV12_BUFFER_CONFIG *get_vp9_ref_frame_buffer(
2114 VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag) {
2115 MV_REFERENCE_FRAME ref_frame = NONE;
2116 if (ref_frame_flag == VP9_LAST_FLAG)
2117 ref_frame = LAST_FRAME;
2118 else if (ref_frame_flag == VP9_GOLD_FLAG)
2119 ref_frame = GOLDEN_FRAME;
2120 else if (ref_frame_flag == VP9_ALT_FLAG)
2121 ref_frame = ALTREF_FRAME;
2123 return ref_frame == NONE ? NULL : get_ref_frame_buffer(cpi, ref_frame);
2126 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
2127 YV12_BUFFER_CONFIG *sd) {
2128 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2130 vp8_yv12_copy_frame(cfg, sd);
2137 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
2138 YV12_BUFFER_CONFIG *sd) {
2139 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2141 vp8_yv12_copy_frame(sd, cfg);
2148 int vp9_update_entropy(VP9_COMP *cpi, int update) {
2149 cpi->ext_refresh_frame_context = update;
2150 cpi->ext_refresh_frame_context_pending = 1;
2154 #if defined(OUTPUT_YUV_DENOISED) || defined(OUTPUT_YUV_SKINMAP)
2155 // The denoiser buffer is allocated as a YUV 440 buffer. This function writes it
2156 // as YUV 420. We simply use the top-left pixels of the UV buffers, since we do
2157 // not denoise the UV channels at this time. If ever we implement UV channel
2158 // denoising we will have to modify this.
2159 void vp9_write_yuv_frame_420(YV12_BUFFER_CONFIG *s, FILE *f) {
2160 uint8_t *src = s->y_buffer;
2161 int h = s->y_height;
2164 fwrite(src, s->y_width, 1, f);
2172 fwrite(src, s->uv_width, 1, f);
2173 src += s->uv_stride;
2180 fwrite(src, s->uv_width, 1, f);
2181 src += s->uv_stride;
2186 #ifdef OUTPUT_YUV_REC
2187 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
2188 YV12_BUFFER_CONFIG *s = cm->frame_to_show;
2189 uint8_t *src = s->y_buffer;
2192 #if CONFIG_VP9_HIGHBITDEPTH
2193 if (s->flags & YV12_FLAG_HIGHBITDEPTH) {
2194 uint16_t *src16 = CONVERT_TO_SHORTPTR(s->y_buffer);
2197 fwrite(src16, s->y_width, 2, yuv_rec_file);
2198 src16 += s->y_stride;
2201 src16 = CONVERT_TO_SHORTPTR(s->u_buffer);
2205 fwrite(src16, s->uv_width, 2, yuv_rec_file);
2206 src16 += s->uv_stride;
2209 src16 = CONVERT_TO_SHORTPTR(s->v_buffer);
2213 fwrite(src16, s->uv_width, 2, yuv_rec_file);
2214 src16 += s->uv_stride;
2217 fflush(yuv_rec_file);
2220 #endif // CONFIG_VP9_HIGHBITDEPTH
2223 fwrite(src, s->y_width, 1, yuv_rec_file);
2231 fwrite(src, s->uv_width, 1, yuv_rec_file);
2232 src += s->uv_stride;
2239 fwrite(src, s->uv_width, 1, yuv_rec_file);
2240 src += s->uv_stride;
2243 fflush(yuv_rec_file);
2247 #if CONFIG_VP9_HIGHBITDEPTH
2248 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
2249 YV12_BUFFER_CONFIG *dst,
2252 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
2253 YV12_BUFFER_CONFIG *dst) {
2254 #endif // CONFIG_VP9_HIGHBITDEPTH
2255 // TODO(dkovalev): replace YV12_BUFFER_CONFIG with vpx_image_t
2257 const uint8_t *const srcs[3] = { src->y_buffer, src->u_buffer,
2259 const int src_strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
2260 const int src_widths[3] = { src->y_crop_width, src->uv_crop_width,
2261 src->uv_crop_width };
2262 const int src_heights[3] = { src->y_crop_height, src->uv_crop_height,
2263 src->uv_crop_height };
2264 uint8_t *const dsts[3] = { dst->y_buffer, dst->u_buffer, dst->v_buffer };
2265 const int dst_strides[3] = { dst->y_stride, dst->uv_stride, dst->uv_stride };
2266 const int dst_widths[3] = { dst->y_crop_width, dst->uv_crop_width,
2267 dst->uv_crop_width };
2268 const int dst_heights[3] = { dst->y_crop_height, dst->uv_crop_height,
2269 dst->uv_crop_height };
2271 for (i = 0; i < MAX_MB_PLANE; ++i) {
2272 #if CONFIG_VP9_HIGHBITDEPTH
2273 if (src->flags & YV12_FLAG_HIGHBITDEPTH) {
2274 vp9_highbd_resize_plane(srcs[i], src_heights[i], src_widths[i],
2275 src_strides[i], dsts[i], dst_heights[i],
2276 dst_widths[i], dst_strides[i], bd);
2278 vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
2279 dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
2282 vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
2283 dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
2284 #endif // CONFIG_VP9_HIGHBITDEPTH
2286 vpx_extend_frame_borders(dst);
2289 #if CONFIG_VP9_HIGHBITDEPTH
2290 static void scale_and_extend_frame(const YV12_BUFFER_CONFIG *src,
2291 YV12_BUFFER_CONFIG *dst, int bd) {
2292 const int src_w = src->y_crop_width;
2293 const int src_h = src->y_crop_height;
2294 const int dst_w = dst->y_crop_width;
2295 const int dst_h = dst->y_crop_height;
2296 const uint8_t *const srcs[3] = { src->y_buffer, src->u_buffer,
2298 const int src_strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
2299 uint8_t *const dsts[3] = { dst->y_buffer, dst->u_buffer, dst->v_buffer };
2300 const int dst_strides[3] = { dst->y_stride, dst->uv_stride, dst->uv_stride };
2301 const InterpKernel *const kernel = vp9_filter_kernels[EIGHTTAP];
2304 for (i = 0; i < MAX_MB_PLANE; ++i) {
2305 const int factor = (i == 0 || i == 3 ? 1 : 2);
2306 const int src_stride = src_strides[i];
2307 const int dst_stride = dst_strides[i];
2308 for (y = 0; y < dst_h; y += 16) {
2309 const int y_q4 = y * (16 / factor) * src_h / dst_h;
2310 for (x = 0; x < dst_w; x += 16) {
2311 const int x_q4 = x * (16 / factor) * src_w / dst_w;
2312 const uint8_t *src_ptr = srcs[i] +
2313 (y / factor) * src_h / dst_h * src_stride +
2314 (x / factor) * src_w / dst_w;
2315 uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
2317 if (src->flags & YV12_FLAG_HIGHBITDEPTH) {
2318 vpx_highbd_convolve8(src_ptr, src_stride, dst_ptr, dst_stride,
2319 kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2320 kernel[y_q4 & 0xf], 16 * src_h / dst_h,
2321 16 / factor, 16 / factor, bd);
2323 vpx_scaled_2d(src_ptr, src_stride, dst_ptr, dst_stride,
2324 kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2325 kernel[y_q4 & 0xf], 16 * src_h / dst_h, 16 / factor,
2332 vpx_extend_frame_borders(dst);
2335 void vp9_scale_and_extend_frame_c(const YV12_BUFFER_CONFIG *src,
2336 YV12_BUFFER_CONFIG *dst) {
2337 const int src_w = src->y_crop_width;
2338 const int src_h = src->y_crop_height;
2339 const int dst_w = dst->y_crop_width;
2340 const int dst_h = dst->y_crop_height;
2341 const uint8_t *const srcs[3] = { src->y_buffer, src->u_buffer,
2343 const int src_strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
2344 uint8_t *const dsts[3] = { dst->y_buffer, dst->u_buffer, dst->v_buffer };
2345 const int dst_strides[3] = { dst->y_stride, dst->uv_stride, dst->uv_stride };
2346 const InterpKernel *const kernel = vp9_filter_kernels[EIGHTTAP];
2349 for (i = 0; i < MAX_MB_PLANE; ++i) {
2350 const int factor = (i == 0 || i == 3 ? 1 : 2);
2351 const int src_stride = src_strides[i];
2352 const int dst_stride = dst_strides[i];
2353 for (y = 0; y < dst_h; y += 16) {
2354 const int y_q4 = y * (16 / factor) * src_h / dst_h;
2355 for (x = 0; x < dst_w; x += 16) {
2356 const int x_q4 = x * (16 / factor) * src_w / dst_w;
2357 const uint8_t *src_ptr = srcs[i] +
2358 (y / factor) * src_h / dst_h * src_stride +
2359 (x / factor) * src_w / dst_w;
2360 uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
2362 vpx_scaled_2d(src_ptr, src_stride, dst_ptr, dst_stride,
2363 kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2364 kernel[y_q4 & 0xf], 16 * src_h / dst_h, 16 / factor,
2370 vpx_extend_frame_borders(dst);
2372 #endif // CONFIG_VP9_HIGHBITDEPTH
2374 static int scale_down(VP9_COMP *cpi, int q) {
2375 RATE_CONTROL *const rc = &cpi->rc;
2376 GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2378 assert(frame_is_kf_gf_arf(cpi));
2380 if (rc->frame_size_selector == UNSCALED &&
2381 q >= rc->rf_level_maxq[gf_group->rf_level[gf_group->index]]) {
2382 const int max_size_thresh =
2383 (int)(rate_thresh_mult[SCALE_STEP1] *
2384 VPXMAX(rc->this_frame_target, rc->avg_frame_bandwidth));
2385 scale = rc->projected_frame_size > max_size_thresh ? 1 : 0;
2390 static int big_rate_miss(VP9_COMP *cpi, int high_limit, int low_limit) {
2391 const RATE_CONTROL *const rc = &cpi->rc;
2393 return (rc->projected_frame_size > ((high_limit * 3) / 2)) ||
2394 (rc->projected_frame_size < (low_limit / 2));
2397 // Function to test for conditions that indicate we should loop
2398 // back and recode a frame.
2399 static int recode_loop_test(VP9_COMP *cpi, int high_limit, int low_limit, int q,
2400 int maxq, int minq) {
2401 const RATE_CONTROL *const rc = &cpi->rc;
2402 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2403 const int frame_is_kfgfarf = frame_is_kf_gf_arf(cpi);
2404 int force_recode = 0;
2406 if ((rc->projected_frame_size >= rc->max_frame_bandwidth) ||
2407 big_rate_miss(cpi, high_limit, low_limit) ||
2408 (cpi->sf.recode_loop == ALLOW_RECODE) ||
2409 (frame_is_kfgfarf && (cpi->sf.recode_loop == ALLOW_RECODE_KFARFGF))) {
2410 if (frame_is_kfgfarf && (oxcf->resize_mode == RESIZE_DYNAMIC) &&
2411 scale_down(cpi, q)) {
2412 // Code this group at a lower resolution.
2413 cpi->resize_pending = 1;
2417 // TODO(agrange) high_limit could be greater than the scale-down threshold.
2418 if ((rc->projected_frame_size > high_limit && q < maxq) ||
2419 (rc->projected_frame_size < low_limit && q > minq)) {
2421 } else if (cpi->oxcf.rc_mode == VPX_CQ) {
2422 // Deal with frame undershoot and whether or not we are
2423 // below the automatically set cq level.
2424 if (q > oxcf->cq_level &&
2425 rc->projected_frame_size < ((rc->this_frame_target * 7) >> 3)) {
2430 return force_recode;
2433 void vp9_update_reference_frames(VP9_COMP *cpi) {
2434 VP9_COMMON *const cm = &cpi->common;
2435 BufferPool *const pool = cm->buffer_pool;
2437 // At this point the new frame has been encoded.
2438 // If any buffer copy / swapping is signaled it should be done here.
2439 if (cm->frame_type == KEY_FRAME) {
2440 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
2442 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->alt_fb_idx],
2444 } else if (vp9_preserve_existing_gf(cpi)) {
2445 // We have decided to preserve the previously existing golden frame as our
2446 // new ARF frame. However, in the short term in function
2447 // vp9_get_refresh_mask() we left it in the GF slot and, if
2448 // we're updating the GF with the current decoded frame, we save it to the
2449 // ARF slot instead.
2450 // We now have to update the ARF with the current frame and swap gld_fb_idx
2451 // and alt_fb_idx so that, overall, we've stored the old GF in the new ARF
2452 // slot and, if we're updating the GF, the current frame becomes the new GF.
2455 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->alt_fb_idx],
2458 tmp = cpi->alt_fb_idx;
2459 cpi->alt_fb_idx = cpi->gld_fb_idx;
2460 cpi->gld_fb_idx = tmp;
2462 if (is_two_pass_svc(cpi)) {
2463 cpi->svc.layer_context[0].gold_ref_idx = cpi->gld_fb_idx;
2464 cpi->svc.layer_context[0].alt_ref_idx = cpi->alt_fb_idx;
2466 } else { /* For non key/golden frames */
2467 if (cpi->refresh_alt_ref_frame) {
2468 int arf_idx = cpi->alt_fb_idx;
2469 if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
2470 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2471 arf_idx = gf_group->arf_update_idx[gf_group->index];
2474 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
2475 memcpy(cpi->interp_filter_selected[ALTREF_FRAME],
2476 cpi->interp_filter_selected[0],
2477 sizeof(cpi->interp_filter_selected[0]));
2480 if (cpi->refresh_golden_frame) {
2481 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
2483 if (!cpi->rc.is_src_frame_alt_ref)
2484 memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
2485 cpi->interp_filter_selected[0],
2486 sizeof(cpi->interp_filter_selected[0]));
2488 memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
2489 cpi->interp_filter_selected[ALTREF_FRAME],
2490 sizeof(cpi->interp_filter_selected[ALTREF_FRAME]));
2494 if (cpi->refresh_last_frame) {
2495 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->lst_fb_idx],
2497 if (!cpi->rc.is_src_frame_alt_ref)
2498 memcpy(cpi->interp_filter_selected[LAST_FRAME],
2499 cpi->interp_filter_selected[0],
2500 sizeof(cpi->interp_filter_selected[0]));
2502 #if CONFIG_VP9_TEMPORAL_DENOISING
2503 if (cpi->oxcf.noise_sensitivity > 0 &&
2504 cpi->denoiser.denoising_level > kDenLowLow) {
2505 vp9_denoiser_update_frame_info(
2506 &cpi->denoiser, *cpi->Source, cpi->common.frame_type,
2507 cpi->refresh_alt_ref_frame, cpi->refresh_golden_frame,
2508 cpi->refresh_last_frame, cpi->resize_pending);
2511 if (is_one_pass_cbr_svc(cpi)) {
2512 // Keep track of frame index for each reference frame.
2513 SVC *const svc = &cpi->svc;
2514 if (cm->frame_type == KEY_FRAME) {
2515 svc->ref_frame_index[cpi->lst_fb_idx] = svc->current_superframe;
2516 svc->ref_frame_index[cpi->gld_fb_idx] = svc->current_superframe;
2517 svc->ref_frame_index[cpi->alt_fb_idx] = svc->current_superframe;
2519 if (cpi->refresh_last_frame)
2520 svc->ref_frame_index[cpi->lst_fb_idx] = svc->current_superframe;
2521 if (cpi->refresh_golden_frame)
2522 svc->ref_frame_index[cpi->gld_fb_idx] = svc->current_superframe;
2523 if (cpi->refresh_alt_ref_frame)
2524 svc->ref_frame_index[cpi->alt_fb_idx] = svc->current_superframe;
2529 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
2530 MACROBLOCKD *xd = &cpi->td.mb.e_mbd;
2531 struct loopfilter *lf = &cm->lf;
2534 lf->filter_level = 0;
2535 lf->last_filt_level = 0;
2537 struct vpx_usec_timer timer;
2539 vpx_clear_system_state();
2541 vpx_usec_timer_start(&timer);
2543 if (!cpi->rc.is_src_frame_alt_ref) {
2544 if ((cpi->common.frame_type == KEY_FRAME) &&
2545 (!cpi->rc.this_key_frame_forced)) {
2546 lf->last_filt_level = 0;
2548 vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.lpf_pick);
2549 lf->last_filt_level = lf->filter_level;
2551 lf->filter_level = 0;
2554 vpx_usec_timer_mark(&timer);
2555 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
2558 if (lf->filter_level > 0) {
2559 vp9_build_mask_frame(cm, lf->filter_level, 0);
2561 if (cpi->num_workers > 1)
2562 vp9_loop_filter_frame_mt(cm->frame_to_show, cm, xd->plane,
2563 lf->filter_level, 0, 0, cpi->workers,
2564 cpi->num_workers, &cpi->lf_row_sync);
2566 vp9_loop_filter_frame(cm->frame_to_show, cm, xd, lf->filter_level, 0, 0);
2569 vpx_extend_frame_inner_borders(cm->frame_to_show);
2572 static INLINE void alloc_frame_mvs(VP9_COMMON *const cm, int buffer_idx) {
2573 RefCntBuffer *const new_fb_ptr = &cm->buffer_pool->frame_bufs[buffer_idx];
2574 if (new_fb_ptr->mvs == NULL || new_fb_ptr->mi_rows < cm->mi_rows ||
2575 new_fb_ptr->mi_cols < cm->mi_cols) {
2576 vpx_free(new_fb_ptr->mvs);
2577 CHECK_MEM_ERROR(cm, new_fb_ptr->mvs,
2578 (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
2579 sizeof(*new_fb_ptr->mvs)));
2580 new_fb_ptr->mi_rows = cm->mi_rows;
2581 new_fb_ptr->mi_cols = cm->mi_cols;
2585 void vp9_scale_references(VP9_COMP *cpi) {
2586 VP9_COMMON *cm = &cpi->common;
2587 MV_REFERENCE_FRAME ref_frame;
2588 const VP9_REFFRAME ref_mask[3] = { VP9_LAST_FLAG, VP9_GOLD_FLAG,
2591 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2592 // Need to convert from VP9_REFFRAME to index into ref_mask (subtract 1).
2593 if (cpi->ref_frame_flags & ref_mask[ref_frame - 1]) {
2594 BufferPool *const pool = cm->buffer_pool;
2595 const YV12_BUFFER_CONFIG *const ref =
2596 get_ref_frame_buffer(cpi, ref_frame);
2599 cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2603 #if CONFIG_VP9_HIGHBITDEPTH
2604 if (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height) {
2605 RefCntBuffer *new_fb_ptr = NULL;
2606 int force_scaling = 0;
2607 int new_fb = cpi->scaled_ref_idx[ref_frame - 1];
2608 if (new_fb == INVALID_IDX) {
2609 new_fb = get_free_fb(cm);
2612 if (new_fb == INVALID_IDX) return;
2613 new_fb_ptr = &pool->frame_bufs[new_fb];
2614 if (force_scaling || new_fb_ptr->buf.y_crop_width != cm->width ||
2615 new_fb_ptr->buf.y_crop_height != cm->height) {
2616 if (vpx_realloc_frame_buffer(&new_fb_ptr->buf, cm->width, cm->height,
2617 cm->subsampling_x, cm->subsampling_y,
2618 cm->use_highbitdepth,
2619 VP9_ENC_BORDER_IN_PIXELS,
2620 cm->byte_alignment, NULL, NULL, NULL))
2621 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2622 "Failed to allocate frame buffer");
2623 scale_and_extend_frame(ref, &new_fb_ptr->buf, (int)cm->bit_depth);
2624 cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
2625 alloc_frame_mvs(cm, new_fb);
2628 if (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height) {
2629 RefCntBuffer *new_fb_ptr = NULL;
2630 int force_scaling = 0;
2631 int new_fb = cpi->scaled_ref_idx[ref_frame - 1];
2632 if (new_fb == INVALID_IDX) {
2633 new_fb = get_free_fb(cm);
2636 if (new_fb == INVALID_IDX) return;
2637 new_fb_ptr = &pool->frame_bufs[new_fb];
2638 if (force_scaling || new_fb_ptr->buf.y_crop_width != cm->width ||
2639 new_fb_ptr->buf.y_crop_height != cm->height) {
2640 if (vpx_realloc_frame_buffer(&new_fb_ptr->buf, cm->width, cm->height,
2641 cm->subsampling_x, cm->subsampling_y,
2642 VP9_ENC_BORDER_IN_PIXELS,
2643 cm->byte_alignment, NULL, NULL, NULL))
2644 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2645 "Failed to allocate frame buffer");
2646 vp9_scale_and_extend_frame(ref, &new_fb_ptr->buf);
2647 cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
2648 alloc_frame_mvs(cm, new_fb);
2650 #endif // CONFIG_VP9_HIGHBITDEPTH
2653 RefCntBuffer *buf = NULL;
2654 if (cpi->oxcf.pass == 0 && !cpi->use_svc) {
2655 // Check for release of scaled reference.
2656 buf_idx = cpi->scaled_ref_idx[ref_frame - 1];
2657 buf = (buf_idx != INVALID_IDX) ? &pool->frame_bufs[buf_idx] : NULL;
2660 cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2663 buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
2664 buf = &pool->frame_bufs[buf_idx];
2665 buf->buf.y_crop_width = ref->y_crop_width;
2666 buf->buf.y_crop_height = ref->y_crop_height;
2667 cpi->scaled_ref_idx[ref_frame - 1] = buf_idx;
2671 if (cpi->oxcf.pass != 0 || cpi->use_svc)
2672 cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2677 static void release_scaled_references(VP9_COMP *cpi) {
2678 VP9_COMMON *cm = &cpi->common;
2680 if (cpi->oxcf.pass == 0 && !cpi->use_svc) {
2681 // Only release scaled references under certain conditions:
2682 // if reference will be updated, or if scaled reference has same resolution.
2684 refresh[0] = (cpi->refresh_last_frame) ? 1 : 0;
2685 refresh[1] = (cpi->refresh_golden_frame) ? 1 : 0;
2686 refresh[2] = (cpi->refresh_alt_ref_frame) ? 1 : 0;
2687 for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
2688 const int idx = cpi->scaled_ref_idx[i - 1];
2689 RefCntBuffer *const buf =
2690 idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[idx] : NULL;
2691 const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi, i);
2693 (refresh[i - 1] || (buf->buf.y_crop_width == ref->y_crop_width &&
2694 buf->buf.y_crop_height == ref->y_crop_height))) {
2696 cpi->scaled_ref_idx[i - 1] = INVALID_IDX;
2700 for (i = 0; i < MAX_REF_FRAMES; ++i) {
2701 const int idx = cpi->scaled_ref_idx[i];
2702 RefCntBuffer *const buf =
2703 idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[idx] : NULL;
2706 cpi->scaled_ref_idx[i] = INVALID_IDX;
2712 static void full_to_model_count(unsigned int *model_count,
2713 unsigned int *full_count) {
2715 model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
2716 model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
2717 model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
2718 for (n = THREE_TOKEN; n < EOB_TOKEN; ++n)
2719 model_count[TWO_TOKEN] += full_count[n];
2720 model_count[EOB_MODEL_TOKEN] = full_count[EOB_TOKEN];
2723 static void full_to_model_counts(vp9_coeff_count_model *model_count,
2724 vp9_coeff_count *full_count) {
2727 for (i = 0; i < PLANE_TYPES; ++i)
2728 for (j = 0; j < REF_TYPES; ++j)
2729 for (k = 0; k < COEF_BANDS; ++k)
2730 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
2731 full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
2734 #if 0 && CONFIG_INTERNAL_STATS
2735 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
2736 VP9_COMMON *const cm = &cpi->common;
2737 FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
2740 vpx_clear_system_state();
2742 #if CONFIG_VP9_HIGHBITDEPTH
2743 if (cm->use_highbitdepth) {
2744 recon_err = vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2746 recon_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2749 recon_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2750 #endif // CONFIG_VP9_HIGHBITDEPTH
2753 if (cpi->twopass.total_left_stats.coded_error != 0.0) {
2754 double dc_quant_devisor;
2755 #if CONFIG_VP9_HIGHBITDEPTH
2756 switch (cm->bit_depth) {
2758 dc_quant_devisor = 4.0;
2761 dc_quant_devisor = 16.0;
2764 dc_quant_devisor = 64.0;
2767 assert(0 && "bit_depth must be VPX_BITS_8, VPX_BITS_10 or VPX_BITS_12");
2771 dc_quant_devisor = 4.0;
2774 fprintf(f, "%10u %dx%d %10d %10d %d %d %10d %10d %10d %10d"
2775 "%10"PRId64" %10"PRId64" %5d %5d %10"PRId64" "
2776 "%10"PRId64" %10"PRId64" %10d "
2777 "%7.2lf %7.2lf %7.2lf %7.2lf %7.2lf"
2778 "%6d %6d %5d %5d %5d "
2779 "%10"PRId64" %10.3lf"
2780 "%10lf %8u %10"PRId64" %10d %10d %10d %10d %10d\n",
2781 cpi->common.current_video_frame,
2782 cm->width, cm->height,
2783 cpi->td.rd_counts.m_search_count,
2784 cpi->td.rd_counts.ex_search_count,
2785 cpi->rc.source_alt_ref_pending,
2786 cpi->rc.source_alt_ref_active,
2787 cpi->rc.this_frame_target,
2788 cpi->rc.projected_frame_size,
2789 cpi->rc.projected_frame_size / cpi->common.MBs,
2790 (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
2791 cpi->rc.vbr_bits_off_target,
2792 cpi->rc.vbr_bits_off_target_fast,
2793 cpi->twopass.extend_minq,
2794 cpi->twopass.extend_minq_fast,
2795 cpi->rc.total_target_vs_actual,
2796 (cpi->rc.starting_buffer_level - cpi->rc.bits_off_target),
2797 cpi->rc.total_actual_bits, cm->base_qindex,
2798 vp9_convert_qindex_to_q(cm->base_qindex, cm->bit_depth),
2799 (double)vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) /
2801 vp9_convert_qindex_to_q(cpi->twopass.active_worst_quality,
2804 vp9_convert_qindex_to_q(cpi->oxcf.cq_level, cm->bit_depth),
2805 cpi->refresh_last_frame, cpi->refresh_golden_frame,
2806 cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
2807 cpi->twopass.bits_left,
2808 cpi->twopass.total_left_stats.coded_error,
2809 cpi->twopass.bits_left /
2810 (1 + cpi->twopass.total_left_stats.coded_error),
2811 cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
2812 cpi->twopass.kf_zeromotion_pct,
2813 cpi->twopass.fr_content_type,
2814 cm->lf.filter_level,
2815 cm->seg.aq_av_offset);
2820 FILE *const fmodes = fopen("Modes.stt", "a");
2823 fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
2824 cm->frame_type, cpi->refresh_golden_frame,
2825 cpi->refresh_alt_ref_frame);
2827 for (i = 0; i < MAX_MODES; ++i)
2828 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
2830 fprintf(fmodes, "\n");
2837 static void set_mv_search_params(VP9_COMP *cpi) {
2838 const VP9_COMMON *const cm = &cpi->common;
2839 const unsigned int max_mv_def = VPXMIN(cm->width, cm->height);
2841 // Default based on max resolution.
2842 cpi->mv_step_param = vp9_init_search_range(max_mv_def);
2844 if (cpi->sf.mv.auto_mv_step_size) {
2845 if (frame_is_intra_only(cm)) {
2846 // Initialize max_mv_magnitude for use in the first INTER frame
2847 // after a key/intra-only frame.
2848 cpi->max_mv_magnitude = max_mv_def;
2850 if (cm->show_frame) {
2851 // Allow mv_steps to correspond to twice the max mv magnitude found
2852 // in the previous frame, capped by the default max_mv_magnitude based
2854 cpi->mv_step_param = vp9_init_search_range(
2855 VPXMIN(max_mv_def, 2 * cpi->max_mv_magnitude));
2857 cpi->max_mv_magnitude = 0;
2862 static void set_size_independent_vars(VP9_COMP *cpi) {
2863 vp9_set_speed_features_framesize_independent(cpi);
2864 vp9_set_rd_speed_thresholds(cpi);
2865 vp9_set_rd_speed_thresholds_sub8x8(cpi);
2866 cpi->common.interp_filter = cpi->sf.default_interp_filter;
2869 static void set_size_dependent_vars(VP9_COMP *cpi, int *q, int *bottom_index,
2871 VP9_COMMON *const cm = &cpi->common;
2872 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2874 // Setup variables that depend on the dimensions of the frame.
2875 vp9_set_speed_features_framesize_dependent(cpi);
2877 // Decide q and q bounds.
2878 *q = vp9_rc_pick_q_and_bounds(cpi, bottom_index, top_index);
2880 if (!frame_is_intra_only(cm)) {
2881 vp9_set_high_precision_mv(cpi, (*q) < HIGH_PRECISION_MV_QTHRESH);
2884 // Configure experimental use of segmentation for enhanced coding of
2885 // static regions if indicated.
2886 // Only allowed in the second pass of a two pass encode, as it requires
2887 // lagged coding, and if the relevant speed feature flag is set.
2888 if (oxcf->pass == 2 && cpi->sf.static_segmentation)
2889 configure_static_seg_features(cpi);
2891 #if CONFIG_VP9_POSTPROC && !(CONFIG_VP9_TEMPORAL_DENOISING)
2892 if (oxcf->noise_sensitivity > 0) {
2894 switch (oxcf->noise_sensitivity) {
2895 case 1: l = 20; break;
2896 case 2: l = 40; break;
2897 case 3: l = 60; break;
2899 case 5: l = 100; break;
2900 case 6: l = 150; break;
2902 if (!cpi->common.postproc_state.limits) {
2903 cpi->common.postproc_state.limits = vpx_calloc(
2904 cpi->common.width, sizeof(*cpi->common.postproc_state.limits));
2906 vp9_denoise(cpi->Source, cpi->Source, l, cpi->common.postproc_state.limits);
2908 #endif // CONFIG_VP9_POSTPROC
2911 #if CONFIG_VP9_TEMPORAL_DENOISING
2912 static void setup_denoiser_buffer(VP9_COMP *cpi) {
2913 VP9_COMMON *const cm = &cpi->common;
2914 if (cpi->oxcf.noise_sensitivity > 0 &&
2915 !cpi->denoiser.frame_buffer_initialized) {
2916 if (vp9_denoiser_alloc(&cpi->denoiser, cm->width, cm->height,
2917 cm->subsampling_x, cm->subsampling_y,
2918 #if CONFIG_VP9_HIGHBITDEPTH
2919 cm->use_highbitdepth,
2921 VP9_ENC_BORDER_IN_PIXELS))
2922 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2923 "Failed to allocate denoiser");
2928 static void init_motion_estimation(VP9_COMP *cpi) {
2929 int y_stride = cpi->scaled_source.y_stride;
2931 if (cpi->sf.mv.search_method == NSTEP) {
2932 vp9_init3smotion_compensation(&cpi->ss_cfg, y_stride);
2933 } else if (cpi->sf.mv.search_method == DIAMOND) {
2934 vp9_init_dsmotion_compensation(&cpi->ss_cfg, y_stride);
2938 static void set_frame_size(VP9_COMP *cpi) {
2940 VP9_COMMON *const cm = &cpi->common;
2941 VP9EncoderConfig *const oxcf = &cpi->oxcf;
2942 MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
2944 if (oxcf->pass == 2 && oxcf->rc_mode == VPX_VBR &&
2945 ((oxcf->resize_mode == RESIZE_FIXED && cm->current_video_frame == 0) ||
2946 (oxcf->resize_mode == RESIZE_DYNAMIC && cpi->resize_pending))) {
2947 calculate_coded_size(cpi, &oxcf->scaled_frame_width,
2948 &oxcf->scaled_frame_height);
2950 // There has been a change in frame size.
2951 vp9_set_size_literal(cpi, oxcf->scaled_frame_width,
2952 oxcf->scaled_frame_height);
2955 if (oxcf->pass == 0 && oxcf->rc_mode == VPX_CBR && !cpi->use_svc &&
2956 oxcf->resize_mode == RESIZE_DYNAMIC && cpi->resize_pending != 0) {
2957 oxcf->scaled_frame_width =
2958 (oxcf->width * cpi->resize_scale_num) / cpi->resize_scale_den;
2959 oxcf->scaled_frame_height =
2960 (oxcf->height * cpi->resize_scale_num) / cpi->resize_scale_den;
2961 // There has been a change in frame size.
2962 vp9_set_size_literal(cpi, oxcf->scaled_frame_width,
2963 oxcf->scaled_frame_height);
2965 // TODO(agrange) Scale cpi->max_mv_magnitude if frame-size has changed.
2966 set_mv_search_params(cpi);
2968 vp9_noise_estimate_init(&cpi->noise_estimate, cm->width, cm->height);
2969 #if CONFIG_VP9_TEMPORAL_DENOISING
2970 // Reset the denoiser on the resized frame.
2971 if (cpi->oxcf.noise_sensitivity > 0) {
2972 vp9_denoiser_free(&(cpi->denoiser));
2973 setup_denoiser_buffer(cpi);
2974 // Dynamic resize is only triggered for non-SVC, so we can force
2975 // golden frame update here as temporary fix to denoiser.
2976 cpi->refresh_golden_frame = 1;
2981 if ((oxcf->pass == 2) &&
2982 (!cpi->use_svc || (is_two_pass_svc(cpi) &&
2983 cpi->svc.encode_empty_frame_state != ENCODING))) {
2984 vp9_set_target_rate(cpi);
2987 alloc_frame_mvs(cm, cm->new_fb_idx);
2989 // Reset the frame pointers to the current frame size.
2990 if (vpx_realloc_frame_buffer(get_frame_new_buffer(cm), cm->width, cm->height,
2991 cm->subsampling_x, cm->subsampling_y,
2992 #if CONFIG_VP9_HIGHBITDEPTH
2993 cm->use_highbitdepth,
2995 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
2997 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2998 "Failed to allocate frame buffer");
3000 alloc_util_frame_buffers(cpi);
3001 init_motion_estimation(cpi);
3003 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3004 RefBuffer *const ref_buf = &cm->frame_refs[ref_frame - 1];
3005 const int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
3007 ref_buf->idx = buf_idx;
3009 if (buf_idx != INVALID_IDX) {
3010 YV12_BUFFER_CONFIG *const buf = &cm->buffer_pool->frame_bufs[buf_idx].buf;
3012 #if CONFIG_VP9_HIGHBITDEPTH
3013 vp9_setup_scale_factors_for_frame(
3014 &ref_buf->sf, buf->y_crop_width, buf->y_crop_height, cm->width,
3015 cm->height, (buf->flags & YV12_FLAG_HIGHBITDEPTH) ? 1 : 0);
3017 vp9_setup_scale_factors_for_frame(&ref_buf->sf, buf->y_crop_width,
3018 buf->y_crop_height, cm->width,
3020 #endif // CONFIG_VP9_HIGHBITDEPTH
3021 if (vp9_is_scaled(&ref_buf->sf)) vpx_extend_frame_borders(buf);
3023 ref_buf->buf = NULL;
3027 set_ref_ptrs(cm, xd, LAST_FRAME, LAST_FRAME);
3030 static void encode_without_recode_loop(VP9_COMP *cpi, size_t *size,
3032 VP9_COMMON *const cm = &cpi->common;
3033 int q = 0, bottom_index = 0, top_index = 0; // Dummy variables.
3035 vpx_clear_system_state();
3037 set_frame_size(cpi);
3039 if (is_one_pass_cbr_svc(cpi) &&
3040 cpi->un_scaled_source->y_width == cm->width << 2 &&
3041 cpi->un_scaled_source->y_height == cm->height << 2 &&
3042 cpi->svc.scaled_temp.y_width == cm->width << 1 &&
3043 cpi->svc.scaled_temp.y_height == cm->height << 1) {
3044 // For svc, if it is a 1/4x1/4 downscaling, do a two-stage scaling to take
3045 // advantage of the 1:2 optimized scaler. In the process, the 1/2x1/2
3046 // result will be saved in scaled_temp and might be used later.
3047 cpi->Source = vp9_svc_twostage_scale(
3048 cm, cpi->un_scaled_source, &cpi->scaled_source, &cpi->svc.scaled_temp);
3049 cpi->svc.scaled_one_half = 1;
3050 } else if (is_one_pass_cbr_svc(cpi) &&
3051 cpi->un_scaled_source->y_width == cm->width << 1 &&
3052 cpi->un_scaled_source->y_height == cm->height << 1 &&
3053 cpi->svc.scaled_one_half) {
3054 // If the spatial layer is 1/2x1/2 and the scaling is already done in the
3055 // two-stage scaling, use the result directly.
3056 cpi->Source = &cpi->svc.scaled_temp;
3057 cpi->svc.scaled_one_half = 0;
3059 cpi->Source = vp9_scale_if_required(
3060 cm, cpi->un_scaled_source, &cpi->scaled_source, (cpi->oxcf.pass == 0));
3062 // Unfiltered raw source used in metrics calculation if the source
3063 // has been filtered.
3064 if (is_psnr_calc_enabled(cpi)) {
3065 #ifdef ENABLE_KF_DENOISE
3066 if (is_spatial_denoise_enabled(cpi)) {
3067 cpi->raw_source_frame =
3068 vp9_scale_if_required(cm, &cpi->raw_unscaled_source,
3069 &cpi->raw_scaled_source, (cpi->oxcf.pass == 0));
3071 cpi->raw_source_frame = cpi->Source;
3074 cpi->raw_source_frame = cpi->Source;
3078 // Avoid scaling last_source unless its needed.
3079 // Last source is needed if vp9_avg_source_sad() is used, or if
3080 // partition_search_type == SOURCE_VAR_BASED_PARTITION, or if noise
3081 // estimation is enabled.
3082 if (cpi->unscaled_last_source != NULL &&
3083 (cpi->oxcf.content == VP9E_CONTENT_SCREEN ||
3084 (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_VBR &&
3085 cpi->oxcf.mode == REALTIME && cpi->oxcf.speed >= 5) ||
3086 cpi->sf.partition_search_type == SOURCE_VAR_BASED_PARTITION ||
3087 cpi->noise_estimate.enabled))
3089 vp9_scale_if_required(cm, cpi->unscaled_last_source,
3090 &cpi->scaled_last_source, (cpi->oxcf.pass == 0));
3092 if (cm->frame_type == KEY_FRAME || cpi->resize_pending != 0) {
3093 memset(cpi->consec_zero_mv, 0,
3094 cm->mi_rows * cm->mi_cols * sizeof(*cpi->consec_zero_mv));
3097 vp9_update_noise_estimate(cpi);
3099 if (cpi->oxcf.pass == 0 && cpi->oxcf.mode == REALTIME &&
3100 cpi->oxcf.speed >= 5 && cpi->resize_state == 0 &&
3101 (cpi->oxcf.content == VP9E_CONTENT_SCREEN ||
3102 cpi->oxcf.rc_mode == VPX_VBR))
3103 vp9_avg_source_sad(cpi);
3105 // For 1 pass SVC, since only ZEROMV is allowed for upsampled reference
3106 // frame (i.e, svc->force_zero_mode_spatial_ref = 0), we can avoid this
3107 // frame-level upsampling.
3108 if (frame_is_intra_only(cm) == 0 && !is_one_pass_cbr_svc(cpi)) {
3109 vp9_scale_references(cpi);
3112 set_size_independent_vars(cpi);
3113 set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
3115 if (cpi->oxcf.speed >= 5 && cpi->oxcf.pass == 0 &&
3116 cpi->oxcf.rc_mode == VPX_CBR &&
3117 cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
3118 cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3119 cpi->use_skin_detection = 1;
3122 vp9_set_quantizer(cm, q);
3123 vp9_set_variance_partition_thresholds(cpi, q);
3127 suppress_active_map(cpi);
3128 // Variance adaptive and in frame q adjustment experiments are mutually
3130 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3131 vp9_vaq_frame_setup(cpi);
3132 } else if (cpi->oxcf.aq_mode == EQUATOR360_AQ) {
3133 vp9_360aq_frame_setup(cpi);
3134 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
3135 vp9_setup_in_frame_q_adj(cpi);
3136 } else if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3137 vp9_cyclic_refresh_setup(cpi);
3139 apply_active_map(cpi);
3141 vp9_encode_frame(cpi);
3143 // Check if we should drop this frame because of high overshoot.
3144 // Only for frames where high temporal-source SAD is detected.
3145 if (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_CBR &&
3146 cpi->resize_state == 0 && cm->frame_type != KEY_FRAME &&
3147 cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
3148 cpi->rc.high_source_sad == 1) {
3150 // Get an estimate of the encoded frame size.
3151 save_coding_context(cpi);
3152 vp9_pack_bitstream(cpi, dest, size);
3153 restore_coding_context(cpi);
3154 frame_size = (int)(*size) << 3;
3155 // Check if encoded frame will overshoot too much, and if so, set the q and
3156 // adjust some rate control parameters, and return to re-encode the frame.
3157 if (vp9_encodedframe_overshoot(cpi, frame_size, &q)) {
3158 vpx_clear_system_state();
3159 vp9_set_quantizer(cm, q);
3160 vp9_set_variance_partition_thresholds(cpi, q);
3161 suppress_active_map(cpi);
3162 // Turn-off cyclic refresh for re-encoded frame.
3163 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3164 unsigned char *const seg_map = cpi->segmentation_map;
3165 memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
3166 vp9_disable_segmentation(&cm->seg);
3168 apply_active_map(cpi);
3169 vp9_encode_frame(cpi);
3173 // Update some stats from cyclic refresh, and check if we should not update
3174 // golden reference, for non-SVC 1 pass CBR.
3175 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->frame_type != KEY_FRAME &&
3176 !cpi->use_svc && cpi->ext_refresh_frame_flags_pending == 0 &&
3177 (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_CBR))
3178 vp9_cyclic_refresh_check_golden_update(cpi);
3180 // Update the skip mb flag probabilities based on the distribution
3181 // seen in the last encoder iteration.
3182 // update_base_skip_probs(cpi);
3183 vpx_clear_system_state();
3186 static void encode_with_recode_loop(VP9_COMP *cpi, size_t *size,
3188 VP9_COMMON *const cm = &cpi->common;
3189 RATE_CONTROL *const rc = &cpi->rc;
3190 int bottom_index, top_index;
3192 int loop_at_this_size = 0;
3194 int overshoot_seen = 0;
3195 int undershoot_seen = 0;
3196 int frame_over_shoot_limit;
3197 int frame_under_shoot_limit;
3198 int q = 0, q_low = 0, q_high = 0;
3200 set_size_independent_vars(cpi);
3203 vpx_clear_system_state();
3205 set_frame_size(cpi);
3207 if (loop_count == 0 || cpi->resize_pending != 0) {
3208 set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
3210 // TODO(agrange) Scale cpi->max_mv_magnitude if frame-size has changed.
3211 set_mv_search_params(cpi);
3213 // Reset the loop state for new frame size.
3215 undershoot_seen = 0;
3217 // Reconfiguration for change in frame size has concluded.
3218 cpi->resize_pending = 0;
3220 q_low = bottom_index;
3223 loop_at_this_size = 0;
3226 // Decide frame size bounds first time through.
3227 if (loop_count == 0) {
3228 vp9_rc_compute_frame_size_bounds(cpi, rc->this_frame_target,
3229 &frame_under_shoot_limit,
3230 &frame_over_shoot_limit);
3233 cpi->Source = vp9_scale_if_required(
3234 cm, cpi->un_scaled_source, &cpi->scaled_source, (cpi->oxcf.pass == 0));
3236 // Unfiltered raw source used in metrics calculation if the source
3237 // has been filtered.
3238 if (is_psnr_calc_enabled(cpi)) {
3239 #ifdef ENABLE_KF_DENOISE
3240 if (is_spatial_denoise_enabled(cpi)) {
3241 cpi->raw_source_frame = vp9_scale_if_required(
3242 cm, &cpi->raw_unscaled_source, &cpi->raw_scaled_source,
3243 (cpi->oxcf.pass == 0));
3245 cpi->raw_source_frame = cpi->Source;
3248 cpi->raw_source_frame = cpi->Source;
3252 if (cpi->unscaled_last_source != NULL)
3253 cpi->Last_Source = vp9_scale_if_required(cm, cpi->unscaled_last_source,
3254 &cpi->scaled_last_source,
3255 (cpi->oxcf.pass == 0));
3257 if (frame_is_intra_only(cm) == 0) {
3258 if (loop_count > 0) {
3259 release_scaled_references(cpi);
3261 vp9_scale_references(cpi);
3264 vp9_set_quantizer(cm, q);
3266 if (loop_count == 0) setup_frame(cpi);
3268 // Variance adaptive and in frame q adjustment experiments are mutually
3270 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3271 vp9_vaq_frame_setup(cpi);
3272 } else if (cpi->oxcf.aq_mode == EQUATOR360_AQ) {
3273 vp9_360aq_frame_setup(cpi);
3274 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
3275 vp9_setup_in_frame_q_adj(cpi);
3278 vp9_encode_frame(cpi);
3280 // Update the skip mb flag probabilities based on the distribution
3281 // seen in the last encoder iteration.
3282 // update_base_skip_probs(cpi);
3284 vpx_clear_system_state();
3286 // Dummy pack of the bitstream using up to date stats to get an
3287 // accurate estimate of output frame size to determine if we need
3289 if (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF) {
3290 save_coding_context(cpi);
3291 if (!cpi->sf.use_nonrd_pick_mode) vp9_pack_bitstream(cpi, dest, size);
3293 rc->projected_frame_size = (int)(*size) << 3;
3294 restore_coding_context(cpi);
3296 if (frame_over_shoot_limit == 0) frame_over_shoot_limit = 1;
3299 if (cpi->oxcf.rc_mode == VPX_Q) {
3302 if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced &&
3303 (rc->projected_frame_size < rc->max_frame_bandwidth)) {
3307 int64_t high_err_target = cpi->ambient_err;
3308 int64_t low_err_target = cpi->ambient_err >> 1;
3310 #if CONFIG_VP9_HIGHBITDEPTH
3311 if (cm->use_highbitdepth) {
3312 kf_err = vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3314 kf_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3317 kf_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3318 #endif // CONFIG_VP9_HIGHBITDEPTH
3320 // Prevent possible divide by zero error below for perfect KF
3323 // The key frame is not good enough or we can afford
3324 // to make it better without undue risk of popping.
3325 if ((kf_err > high_err_target &&
3326 rc->projected_frame_size <= frame_over_shoot_limit) ||
3327 (kf_err > low_err_target &&
3328 rc->projected_frame_size <= frame_under_shoot_limit)) {
3330 q_high = q > q_low ? q - 1 : q_low;
3333 q = (int)((q * high_err_target) / kf_err);
3334 q = VPXMIN(q, (q_high + q_low) >> 1);
3335 } else if (kf_err < low_err_target &&
3336 rc->projected_frame_size >= frame_under_shoot_limit) {
3337 // The key frame is much better than the previous frame
3339 q_low = q < q_high ? q + 1 : q_high;
3342 q = (int)((q * low_err_target) / kf_err);
3343 q = VPXMIN(q, (q_high + q_low + 1) >> 1);
3346 // Clamp Q to upper and lower limits:
3347 q = clamp(q, q_low, q_high);
3350 } else if (recode_loop_test(cpi, frame_over_shoot_limit,
3351 frame_under_shoot_limit, q,
3352 VPXMAX(q_high, top_index), bottom_index)) {
3353 // Is the projected frame size out of range and are we allowed
3354 // to attempt to recode.
3358 if (cpi->resize_pending == 1) {
3359 // Change in frame size so go back around the recode loop.
3360 cpi->rc.frame_size_selector =
3361 SCALE_STEP1 - cpi->rc.frame_size_selector;
3362 cpi->rc.next_frame_size_selector = cpi->rc.frame_size_selector;
3364 #if CONFIG_INTERNAL_STATS
3365 ++cpi->tot_recode_hits;
3372 // Frame size out of permitted range:
3373 // Update correction factor & compute new Q to try...
3375 // Frame is too large
3376 if (rc->projected_frame_size > rc->this_frame_target) {
3377 // Special case if the projected size is > the max allowed.
3378 if (rc->projected_frame_size >= rc->max_frame_bandwidth)
3379 q_high = rc->worst_quality;
3381 // Raise Qlow as to at least the current value
3382 q_low = q < q_high ? q + 1 : q_high;
3384 if (undershoot_seen || loop_at_this_size > 1) {
3385 // Update rate_correction_factor unless
3386 vp9_rc_update_rate_correction_factors(cpi);
3388 q = (q_high + q_low + 1) / 2;
3390 // Update rate_correction_factor unless
3391 vp9_rc_update_rate_correction_factors(cpi);
3393 q = vp9_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
3394 VPXMAX(q_high, top_index));
3396 while (q < q_low && retries < 10) {
3397 vp9_rc_update_rate_correction_factors(cpi);
3398 q = vp9_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
3399 VPXMAX(q_high, top_index));
3406 // Frame is too small
3407 q_high = q > q_low ? q - 1 : q_low;
3409 if (overshoot_seen || loop_at_this_size > 1) {
3410 vp9_rc_update_rate_correction_factors(cpi);
3411 q = (q_high + q_low) / 2;
3413 vp9_rc_update_rate_correction_factors(cpi);
3414 q = vp9_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
3416 // Special case reset for qlow for constrained quality.
3417 // This should only trigger where there is very substantial
3418 // undershoot on a frame and the auto cq level is above
3419 // the user passsed in value.
3420 if (cpi->oxcf.rc_mode == VPX_CQ && q < q_low) {
3424 while (q > q_high && retries < 10) {
3425 vp9_rc_update_rate_correction_factors(cpi);
3426 q = vp9_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
3432 undershoot_seen = 1;
3435 // Clamp Q to upper and lower limits:
3436 q = clamp(q, q_low, q_high);
3438 loop = (q != last_q);
3444 // Special case for overlay frame.
3445 if (rc->is_src_frame_alt_ref &&
3446 rc->projected_frame_size < rc->max_frame_bandwidth)
3451 ++loop_at_this_size;
3453 #if CONFIG_INTERNAL_STATS
3454 ++cpi->tot_recode_hits;
3460 static int get_ref_frame_flags(const VP9_COMP *cpi) {
3461 const int *const map = cpi->common.ref_frame_map;
3462 const int gold_is_last = map[cpi->gld_fb_idx] == map[cpi->lst_fb_idx];
3463 const int alt_is_last = map[cpi->alt_fb_idx] == map[cpi->lst_fb_idx];
3464 const int gold_is_alt = map[cpi->gld_fb_idx] == map[cpi->alt_fb_idx];
3465 int flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
3467 if (gold_is_last) flags &= ~VP9_GOLD_FLAG;
3469 if (cpi->rc.frames_till_gf_update_due == INT_MAX &&
3470 (cpi->svc.number_temporal_layers == 1 &&
3471 cpi->svc.number_spatial_layers == 1))
3472 flags &= ~VP9_GOLD_FLAG;
3474 if (alt_is_last) flags &= ~VP9_ALT_FLAG;
3476 if (gold_is_alt) flags &= ~VP9_ALT_FLAG;
3481 static void set_ext_overrides(VP9_COMP *cpi) {
3482 // Overrides the defaults with the externally supplied values with
3483 // vp9_update_reference() and vp9_update_entropy() calls
3484 // Note: The overrides are valid only for the next frame passed
3485 // to encode_frame_to_data_rate() function
3486 if (cpi->ext_refresh_frame_context_pending) {
3487 cpi->common.refresh_frame_context = cpi->ext_refresh_frame_context;
3488 cpi->ext_refresh_frame_context_pending = 0;
3490 if (cpi->ext_refresh_frame_flags_pending) {
3491 cpi->refresh_last_frame = cpi->ext_refresh_last_frame;
3492 cpi->refresh_golden_frame = cpi->ext_refresh_golden_frame;
3493 cpi->refresh_alt_ref_frame = cpi->ext_refresh_alt_ref_frame;
3497 YV12_BUFFER_CONFIG *vp9_svc_twostage_scale(VP9_COMMON *cm,
3498 YV12_BUFFER_CONFIG *unscaled,
3499 YV12_BUFFER_CONFIG *scaled,
3500 YV12_BUFFER_CONFIG *scaled_temp) {
3501 if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
3502 cm->mi_rows * MI_SIZE != unscaled->y_height) {
3503 #if CONFIG_VP9_HIGHBITDEPTH
3504 scale_and_extend_frame(unscaled, scaled_temp, (int)cm->bit_depth);
3505 scale_and_extend_frame(scaled_temp, scaled, (int)cm->bit_depth);
3507 vp9_scale_and_extend_frame(unscaled, scaled_temp);
3508 vp9_scale_and_extend_frame(scaled_temp, scaled);
3509 #endif // CONFIG_VP9_HIGHBITDEPTH
3516 YV12_BUFFER_CONFIG *vp9_scale_if_required(VP9_COMMON *cm,
3517 YV12_BUFFER_CONFIG *unscaled,
3518 YV12_BUFFER_CONFIG *scaled,
3519 int use_normative_scaler) {
3520 if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
3521 cm->mi_rows * MI_SIZE != unscaled->y_height) {
3522 #if CONFIG_VP9_HIGHBITDEPTH
3523 if (use_normative_scaler && unscaled->y_width <= (scaled->y_width << 1) &&
3524 unscaled->y_height <= (scaled->y_height << 1))
3525 scale_and_extend_frame(unscaled, scaled, (int)cm->bit_depth);
3527 scale_and_extend_frame_nonnormative(unscaled, scaled, (int)cm->bit_depth);
3529 if (use_normative_scaler && unscaled->y_width <= (scaled->y_width << 1) &&
3530 unscaled->y_height <= (scaled->y_height << 1))
3531 vp9_scale_and_extend_frame(unscaled, scaled);
3533 scale_and_extend_frame_nonnormative(unscaled, scaled);
3534 #endif // CONFIG_VP9_HIGHBITDEPTH
3541 static void set_arf_sign_bias(VP9_COMP *cpi) {
3542 VP9_COMMON *const cm = &cpi->common;
3545 if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
3546 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
3547 arf_sign_bias = cpi->rc.source_alt_ref_active &&
3548 (!cpi->refresh_alt_ref_frame ||
3549 (gf_group->rf_level[gf_group->index] == GF_ARF_LOW));
3552 (cpi->rc.source_alt_ref_active && !cpi->refresh_alt_ref_frame);
3554 cm->ref_frame_sign_bias[ALTREF_FRAME] = arf_sign_bias;
3557 static int setup_interp_filter_search_mask(VP9_COMP *cpi) {
3558 INTERP_FILTER ifilter;
3559 int ref_total[MAX_REF_FRAMES] = { 0 };
3560 MV_REFERENCE_FRAME ref;
3562 if (cpi->common.last_frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame)
3564 for (ref = LAST_FRAME; ref <= ALTREF_FRAME; ++ref)
3565 for (ifilter = EIGHTTAP; ifilter <= EIGHTTAP_SHARP; ++ifilter)
3566 ref_total[ref] += cpi->interp_filter_selected[ref][ifilter];
3568 for (ifilter = EIGHTTAP; ifilter <= EIGHTTAP_SHARP; ++ifilter) {
3569 if ((ref_total[LAST_FRAME] &&
3570 cpi->interp_filter_selected[LAST_FRAME][ifilter] == 0) &&
3571 (ref_total[GOLDEN_FRAME] == 0 ||
3572 cpi->interp_filter_selected[GOLDEN_FRAME][ifilter] * 50 <
3573 ref_total[GOLDEN_FRAME]) &&
3574 (ref_total[ALTREF_FRAME] == 0 ||
3575 cpi->interp_filter_selected[ALTREF_FRAME][ifilter] * 50 <
3576 ref_total[ALTREF_FRAME]))
3577 mask |= 1 << ifilter;
3582 #ifdef ENABLE_KF_DENOISE
3583 // Baseline Kernal weights for denoise
3584 static uint8_t dn_kernal_3[9] = { 1, 2, 1, 2, 4, 2, 1, 2, 1 };
3585 static uint8_t dn_kernal_5[25] = { 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 4,
3586 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1 };
3588 static INLINE void add_denoise_point(int centre_val, int data_val, int thresh,
3589 uint8_t point_weight, int *sum_val,
3591 if (abs(centre_val - data_val) <= thresh) {
3592 *sum_weight += point_weight;
3593 *sum_val += (int)data_val * (int)point_weight;
3597 static void spatial_denoise_point(uint8_t *src_ptr, const int stride,
3598 const int strength) {
3601 int thresh = strength;
3602 int kernal_size = 5;
3603 int half_k_size = 2;
3607 uint8_t *kernal_ptr;
3609 // Find the maximum deviation from the source point in the locale.
3610 tmp_ptr = src_ptr - (stride * (half_k_size + 1)) - (half_k_size + 1);
3611 for (i = 0; i < kernal_size + 2; ++i) {
3612 for (j = 0; j < kernal_size + 2; ++j) {
3613 max_diff = VPXMAX(max_diff, abs((int)*src_ptr - (int)tmp_ptr[j]));
3618 // Select the kernal size.
3619 if (max_diff > (strength + (strength >> 1))) {
3622 thresh = thresh >> 1;
3624 kernal_ptr = (kernal_size == 3) ? dn_kernal_3 : dn_kernal_5;
3627 tmp_ptr = src_ptr - (stride * half_k_size) - half_k_size;
3628 for (i = 0; i < kernal_size; ++i) {
3629 for (j = 0; j < kernal_size; ++j) {
3630 add_denoise_point((int)*src_ptr, (int)tmp_ptr[j], thresh, *kernal_ptr,
3631 &sum_val, &sum_weight);
3637 // Update the source value with the new filtered value
3638 *src_ptr = (uint8_t)((sum_val + (sum_weight >> 1)) / sum_weight);
3641 #if CONFIG_VP9_HIGHBITDEPTH
3642 static void highbd_spatial_denoise_point(uint16_t *src_ptr, const int stride,
3643 const int strength) {
3646 int thresh = strength;
3647 int kernal_size = 5;
3648 int half_k_size = 2;
3652 uint8_t *kernal_ptr;
3654 // Find the maximum deviation from the source point in the locale.
3655 tmp_ptr = src_ptr - (stride * (half_k_size + 1)) - (half_k_size + 1);
3656 for (i = 0; i < kernal_size + 2; ++i) {
3657 for (j = 0; j < kernal_size + 2; ++j) {
3658 max_diff = VPXMAX(max_diff, abs((int)src_ptr - (int)tmp_ptr[j]));
3663 // Select the kernal size.
3664 if (max_diff > (strength + (strength >> 1))) {
3667 thresh = thresh >> 1;
3669 kernal_ptr = (kernal_size == 3) ? dn_kernal_3 : dn_kernal_5;
3672 tmp_ptr = src_ptr - (stride * half_k_size) - half_k_size;
3673 for (i = 0; i < kernal_size; ++i) {
3674 for (j = 0; j < kernal_size; ++j) {
3675 add_denoise_point((int)*src_ptr, (int)tmp_ptr[j], thresh, *kernal_ptr,
3676 &sum_val, &sum_weight);
3682 // Update the source value with the new filtered value
3683 *src_ptr = (uint16_t)((sum_val + (sum_weight >> 1)) / sum_weight);
3685 #endif // CONFIG_VP9_HIGHBITDEPTH
3687 // Apply thresholded spatial noise supression to a given buffer.
3688 static void spatial_denoise_buffer(VP9_COMP *cpi, uint8_t *buffer,
3689 const int stride, const int width,
3690 const int height, const int strength) {
3691 VP9_COMMON *const cm = &cpi->common;
3692 uint8_t *src_ptr = buffer;
3696 for (row = 0; row < height; ++row) {
3697 for (col = 0; col < width; ++col) {
3698 #if CONFIG_VP9_HIGHBITDEPTH
3699 if (cm->use_highbitdepth)
3700 highbd_spatial_denoise_point(CONVERT_TO_SHORTPTR(&src_ptr[col]), stride,
3703 spatial_denoise_point(&src_ptr[col], stride, strength);
3705 spatial_denoise_point(&src_ptr[col], stride, strength);
3706 #endif // CONFIG_VP9_HIGHBITDEPTH
3712 // Apply thresholded spatial noise supression to source.
3713 static void spatial_denoise_frame(VP9_COMP *cpi) {
3714 YV12_BUFFER_CONFIG *src = cpi->Source;
3715 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3716 TWO_PASS *const twopass = &cpi->twopass;
3717 VP9_COMMON *const cm = &cpi->common;
3719 // Base the filter strength on the current active max Q.
3720 const int q = (int)(vp9_convert_qindex_to_q(twopass->active_worst_quality,
3723 VPXMAX(oxcf->arnr_strength >> 2, VPXMIN(oxcf->arnr_strength, (q >> 4)));
3725 // Denoise each of Y,U and V buffers.
3726 spatial_denoise_buffer(cpi, src->y_buffer, src->y_stride, src->y_width,
3727 src->y_height, strength);
3729 strength += (strength >> 1);
3730 spatial_denoise_buffer(cpi, src->u_buffer, src->uv_stride, src->uv_width,
3731 src->uv_height, strength << 1);
3733 spatial_denoise_buffer(cpi, src->v_buffer, src->uv_stride, src->uv_width,
3734 src->uv_height, strength << 1);
3736 #endif // ENABLE_KF_DENOISE
3738 static void encode_frame_to_data_rate(VP9_COMP *cpi, size_t *size,
3740 unsigned int *frame_flags) {
3741 VP9_COMMON *const cm = &cpi->common;
3742 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3743 struct segmentation *const seg = &cm->seg;
3746 set_ext_overrides(cpi);
3747 vpx_clear_system_state();
3749 #ifdef ENABLE_KF_DENOISE
3750 // Spatial denoise of key frame.
3751 if (is_spatial_denoise_enabled(cpi)) spatial_denoise_frame(cpi);
3754 // Set the arf sign bias for this frame.
3755 set_arf_sign_bias(cpi);
3757 // Set default state for segment based loop filter update flags.
3758 cm->lf.mode_ref_delta_update = 0;
3760 if (cpi->oxcf.pass == 2 && cpi->sf.adaptive_interp_filter_search)
3761 cpi->sf.interp_filter_search_mask = setup_interp_filter_search_mask(cpi);
3763 // Set various flags etc to special state if it is a key frame.
3764 if (frame_is_intra_only(cm)) {
3765 // Reset the loop filter deltas and segmentation map.
3766 vp9_reset_segment_features(&cm->seg);
3768 // If segmentation is enabled force a map update for key frames.
3770 seg->update_map = 1;
3771 seg->update_data = 1;
3774 // The alternate reference frame cannot be active for a key frame.
3775 cpi->rc.source_alt_ref_active = 0;
3777 cm->error_resilient_mode = oxcf->error_resilient_mode;
3778 cm->frame_parallel_decoding_mode = oxcf->frame_parallel_decoding_mode;
3780 // By default, encoder assumes decoder can use prev_mi.
3781 if (cm->error_resilient_mode) {
3782 cm->frame_parallel_decoding_mode = 1;
3783 cm->reset_frame_context = 0;
3784 cm->refresh_frame_context = 0;
3785 } else if (cm->intra_only) {
3786 // Only reset the current context.
3787 cm->reset_frame_context = 2;
3790 if (is_two_pass_svc(cpi) && cm->error_resilient_mode == 0) {
3791 // Use context 0 for intra only empty frame, but the last frame context
3792 // for other empty frames.
3793 if (cpi->svc.encode_empty_frame_state == ENCODING) {
3794 if (cpi->svc.encode_intra_empty_frame != 0)
3795 cm->frame_context_idx = 0;
3797 cm->frame_context_idx = FRAME_CONTEXTS - 1;
3799 cm->frame_context_idx =
3800 cpi->svc.spatial_layer_id * cpi->svc.number_temporal_layers +
3801 cpi->svc.temporal_layer_id;
3804 cm->frame_parallel_decoding_mode = oxcf->frame_parallel_decoding_mode;
3806 // The probs will be updated based on the frame type of its previous
3807 // frame if frame_parallel_decoding_mode is 0. The type may vary for
3808 // the frame after a key frame in base layer since we may drop enhancement
3809 // layers. So set frame_parallel_decoding_mode to 1 in this case.
3810 if (cm->frame_parallel_decoding_mode == 0) {
3811 if (cpi->svc.number_temporal_layers == 1) {
3812 if (cpi->svc.spatial_layer_id == 0 &&
3813 cpi->svc.layer_context[0].last_frame_type == KEY_FRAME)
3814 cm->frame_parallel_decoding_mode = 1;
3815 } else if (cpi->svc.spatial_layer_id == 0) {
3816 // Find the 2nd frame in temporal base layer and 1st frame in temporal
3817 // enhancement layers from the key frame.
3819 for (i = 0; i < cpi->svc.number_temporal_layers; ++i) {
3820 if (cpi->svc.layer_context[0].frames_from_key_frame == 1 << i) {
3821 cm->frame_parallel_decoding_mode = 1;
3829 // For 1 pass CBR, check if we are dropping this frame.
3830 // For spatial layers, for now only check for frame-dropping on first spatial
3831 // layer, and if decision is to drop, we drop whole super-frame.
3832 if (oxcf->pass == 0 && oxcf->rc_mode == VPX_CBR &&
3833 cm->frame_type != KEY_FRAME) {
3834 if (vp9_rc_drop_frame(cpi) ||
3835 (is_one_pass_cbr_svc(cpi) && cpi->svc.rc_drop_superframe == 1)) {
3836 vp9_rc_postencode_update_drop_frame(cpi);
3837 ++cm->current_video_frame;
3838 cpi->ext_refresh_frame_flags_pending = 0;
3839 cpi->svc.rc_drop_superframe = 1;
3840 // TODO(marpan): Advancing the svc counters on dropped frames can break
3841 // the referencing scheme for the fixed svc patterns defined in
3842 // vp9_one_pass_cbr_svc_start_layer(). Look into fixing this issue, but
3843 // for now, don't advance the svc frame counters on dropped frame.
3844 // if (cpi->use_svc)
3845 // vp9_inc_frame_in_layer(cpi);
3850 vpx_clear_system_state();
3852 #if CONFIG_INTERNAL_STATS
3853 memset(cpi->mode_chosen_counts, 0,
3854 MAX_MODES * sizeof(*cpi->mode_chosen_counts));
3857 if (cpi->sf.recode_loop == DISALLOW_RECODE) {
3858 encode_without_recode_loop(cpi, size, dest);
3860 encode_with_recode_loop(cpi, size, dest);
3863 #if CONFIG_VP9_TEMPORAL_DENOISING
3864 #ifdef OUTPUT_YUV_DENOISED
3865 if (oxcf->noise_sensitivity > 0) {
3866 vp9_write_yuv_frame_420(&cpi->denoiser.running_avg_y[INTRA_FRAME],
3871 #ifdef OUTPUT_YUV_SKINMAP
3872 if (cpi->common.current_video_frame > 1) {
3873 vp9_compute_skin_map(cpi, yuv_skinmap_file);
3877 // Special case code to reduce pulsing when key frames are forced at a
3878 // fixed interval. Note the reconstruction error if it is the frame before
3879 // the force key frame
3880 if (cpi->rc.next_key_frame_forced && cpi->rc.frames_to_key == 1) {
3881 #if CONFIG_VP9_HIGHBITDEPTH
3882 if (cm->use_highbitdepth) {
3884 vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3886 cpi->ambient_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3889 cpi->ambient_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3890 #endif // CONFIG_VP9_HIGHBITDEPTH
3893 // If the encoder forced a KEY_FRAME decision
3894 if (cm->frame_type == KEY_FRAME) cpi->refresh_last_frame = 1;
3896 cm->frame_to_show = get_frame_new_buffer(cm);
3897 cm->frame_to_show->color_space = cm->color_space;
3898 cm->frame_to_show->color_range = cm->color_range;
3899 cm->frame_to_show->render_width = cm->render_width;
3900 cm->frame_to_show->render_height = cm->render_height;
3902 // Pick the loop filter level for the frame.
3903 loopfilter_frame(cpi, cm);
3905 // build the bitstream
3906 vp9_pack_bitstream(cpi, dest, size);
3908 if (cm->seg.update_map) update_reference_segmentation_map(cpi);
3910 if (frame_is_intra_only(cm) == 0) {
3911 release_scaled_references(cpi);
3913 vp9_update_reference_frames(cpi);
3915 for (t = TX_4X4; t <= TX_32X32; t++)
3916 full_to_model_counts(cpi->td.counts->coef[t],
3917 cpi->td.rd_counts.coef_counts[t]);
3919 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode)
3920 vp9_adapt_coef_probs(cm);
3922 if (!frame_is_intra_only(cm)) {
3923 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
3924 vp9_adapt_mode_probs(cm);
3925 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
3929 cpi->ext_refresh_frame_flags_pending = 0;
3931 if (cpi->refresh_golden_frame == 1)
3932 cpi->frame_flags |= FRAMEFLAGS_GOLDEN;
3934 cpi->frame_flags &= ~FRAMEFLAGS_GOLDEN;
3936 if (cpi->refresh_alt_ref_frame == 1)
3937 cpi->frame_flags |= FRAMEFLAGS_ALTREF;
3939 cpi->frame_flags &= ~FRAMEFLAGS_ALTREF;
3941 cpi->ref_frame_flags = get_ref_frame_flags(cpi);
3943 cm->last_frame_type = cm->frame_type;
3945 if (!(is_two_pass_svc(cpi) && cpi->svc.encode_empty_frame_state == ENCODING))
3946 vp9_rc_postencode_update(cpi, *size);
3949 output_frame_level_debug_stats(cpi);
3952 if (cm->frame_type == KEY_FRAME) {
3953 // Tell the caller that the frame was coded as a key frame
3954 *frame_flags = cpi->frame_flags | FRAMEFLAGS_KEY;
3956 *frame_flags = cpi->frame_flags & ~FRAMEFLAGS_KEY;
3959 // Clear the one shot update flags for segmentation map and mode/ref loop
3961 cm->seg.update_map = 0;
3962 cm->seg.update_data = 0;
3963 cm->lf.mode_ref_delta_update = 0;
3965 // keep track of the last coded dimensions
3966 cm->last_width = cm->width;
3967 cm->last_height = cm->height;
3969 // reset to normal state now that we are done.
3970 if (!cm->show_existing_frame) cm->last_show_frame = cm->show_frame;
3972 if (cm->show_frame) {
3973 vp9_swap_mi_and_prev_mi(cm);
3974 // Don't increment frame counters if this was an altref buffer
3975 // update not a real frame
3976 ++cm->current_video_frame;
3977 if (cpi->use_svc) vp9_inc_frame_in_layer(cpi);
3979 cm->prev_frame = cm->cur_frame;
3982 cpi->svc.layer_context[cpi->svc.spatial_layer_id *
3983 cpi->svc.number_temporal_layers +
3984 cpi->svc.temporal_layer_id]
3985 .last_frame_type = cm->frame_type;
3988 static void SvcEncode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
3989 unsigned int *frame_flags) {
3990 vp9_rc_get_svc_params(cpi);
3991 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3994 static void Pass0Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
3995 unsigned int *frame_flags) {
3996 if (cpi->oxcf.rc_mode == VPX_CBR) {
3997 vp9_rc_get_one_pass_cbr_params(cpi);
3999 vp9_rc_get_one_pass_vbr_params(cpi);
4001 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4004 static void Pass2Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
4005 unsigned int *frame_flags) {
4006 cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
4007 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4009 if (!(is_two_pass_svc(cpi) && cpi->svc.encode_empty_frame_state == ENCODING))
4010 vp9_twopass_postencode_update(cpi);
4013 static void init_ref_frame_bufs(VP9_COMMON *cm) {
4015 BufferPool *const pool = cm->buffer_pool;
4016 cm->new_fb_idx = INVALID_IDX;
4017 for (i = 0; i < REF_FRAMES; ++i) {
4018 cm->ref_frame_map[i] = INVALID_IDX;
4019 pool->frame_bufs[i].ref_count = 0;
4023 static void check_initial_width(VP9_COMP *cpi,
4024 #if CONFIG_VP9_HIGHBITDEPTH
4025 int use_highbitdepth,
4027 int subsampling_x, int subsampling_y) {
4028 VP9_COMMON *const cm = &cpi->common;
4030 if (!cpi->initial_width ||
4031 #if CONFIG_VP9_HIGHBITDEPTH
4032 cm->use_highbitdepth != use_highbitdepth ||
4034 cm->subsampling_x != subsampling_x ||
4035 cm->subsampling_y != subsampling_y) {
4036 cm->subsampling_x = subsampling_x;
4037 cm->subsampling_y = subsampling_y;
4038 #if CONFIG_VP9_HIGHBITDEPTH
4039 cm->use_highbitdepth = use_highbitdepth;
4042 alloc_raw_frame_buffers(cpi);
4043 init_ref_frame_bufs(cm);
4044 alloc_util_frame_buffers(cpi);
4046 init_motion_estimation(cpi); // TODO(agrange) This can be removed.
4048 cpi->initial_width = cm->width;
4049 cpi->initial_height = cm->height;
4050 cpi->initial_mbs = cm->MBs;
4054 int vp9_receive_raw_frame(VP9_COMP *cpi, unsigned int frame_flags,
4055 YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
4057 VP9_COMMON *const cm = &cpi->common;
4058 struct vpx_usec_timer timer;
4060 const int subsampling_x = sd->subsampling_x;
4061 const int subsampling_y = sd->subsampling_y;
4062 #if CONFIG_VP9_HIGHBITDEPTH
4063 const int use_highbitdepth = (sd->flags & YV12_FLAG_HIGHBITDEPTH) != 0;
4066 #if CONFIG_VP9_HIGHBITDEPTH
4067 check_initial_width(cpi, use_highbitdepth, subsampling_x, subsampling_y);
4069 check_initial_width(cpi, subsampling_x, subsampling_y);
4070 #endif // CONFIG_VP9_HIGHBITDEPTH
4072 #if CONFIG_VP9_TEMPORAL_DENOISING
4073 setup_denoiser_buffer(cpi);
4075 vpx_usec_timer_start(&timer);
4077 if (vp9_lookahead_push(cpi->lookahead, sd, time_stamp, end_time,
4078 #if CONFIG_VP9_HIGHBITDEPTH
4080 #endif // CONFIG_VP9_HIGHBITDEPTH
4083 vpx_usec_timer_mark(&timer);
4084 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
4086 if ((cm->profile == PROFILE_0 || cm->profile == PROFILE_2) &&
4087 (subsampling_x != 1 || subsampling_y != 1)) {
4088 vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
4089 "Non-4:2:0 color format requires profile 1 or 3");
4092 if ((cm->profile == PROFILE_1 || cm->profile == PROFILE_3) &&
4093 (subsampling_x == 1 && subsampling_y == 1)) {
4094 vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
4095 "4:2:0 color format requires profile 0 or 2");
4102 static int frame_is_reference(const VP9_COMP *cpi) {
4103 const VP9_COMMON *cm = &cpi->common;
4105 return cm->frame_type == KEY_FRAME || cpi->refresh_last_frame ||
4106 cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame ||
4107 cm->refresh_frame_context || cm->lf.mode_ref_delta_update ||
4108 cm->seg.update_map || cm->seg.update_data;
4111 static void adjust_frame_rate(VP9_COMP *cpi,
4112 const struct lookahead_entry *source) {
4113 int64_t this_duration;
4116 if (source->ts_start == cpi->first_time_stamp_ever) {
4117 this_duration = source->ts_end - source->ts_start;
4120 int64_t last_duration =
4121 cpi->last_end_time_stamp_seen - cpi->last_time_stamp_seen;
4123 this_duration = source->ts_end - cpi->last_end_time_stamp_seen;
4125 // do a step update if the duration changes by 10%
4127 step = (int)((this_duration - last_duration) * 10 / last_duration);
4130 if (this_duration) {
4132 vp9_new_framerate(cpi, 10000000.0 / this_duration);
4134 // Average this frame's rate into the last second's average
4135 // frame rate. If we haven't seen 1 second yet, then average
4136 // over the whole interval seen.
4137 const double interval = VPXMIN(
4138 (double)(source->ts_end - cpi->first_time_stamp_ever), 10000000.0);
4139 double avg_duration = 10000000.0 / cpi->framerate;
4140 avg_duration *= (interval - avg_duration + this_duration);
4141 avg_duration /= interval;
4143 vp9_new_framerate(cpi, 10000000.0 / avg_duration);
4146 cpi->last_time_stamp_seen = source->ts_start;
4147 cpi->last_end_time_stamp_seen = source->ts_end;
4150 // Returns 0 if this is not an alt ref else the offset of the source frame
4151 // used as the arf midpoint.
4152 static int get_arf_src_index(VP9_COMP *cpi) {
4153 RATE_CONTROL *const rc = &cpi->rc;
4154 int arf_src_index = 0;
4155 if (is_altref_enabled(cpi)) {
4156 if (cpi->oxcf.pass == 2) {
4157 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4158 if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
4159 arf_src_index = gf_group->arf_src_offset[gf_group->index];
4161 } else if (rc->source_alt_ref_pending) {
4162 arf_src_index = rc->frames_till_gf_update_due;
4165 return arf_src_index;
4168 static void check_src_altref(VP9_COMP *cpi,
4169 const struct lookahead_entry *source) {
4170 RATE_CONTROL *const rc = &cpi->rc;
4172 if (cpi->oxcf.pass == 2) {
4173 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4174 rc->is_src_frame_alt_ref =
4175 (gf_group->update_type[gf_group->index] == OVERLAY_UPDATE);
4177 rc->is_src_frame_alt_ref =
4178 cpi->alt_ref_source && (source == cpi->alt_ref_source);
4181 if (rc->is_src_frame_alt_ref) {
4182 // Current frame is an ARF overlay frame.
4183 cpi->alt_ref_source = NULL;
4185 // Don't refresh the last buffer for an ARF overlay frame. It will
4186 // become the GF so preserve last as an alternative prediction option.
4187 cpi->refresh_last_frame = 0;
4191 #if CONFIG_INTERNAL_STATS
4192 extern double vp9_get_blockiness(const uint8_t *img1, int img1_pitch,
4193 const uint8_t *img2, int img2_pitch, int width,
4196 static void adjust_image_stat(double y, double u, double v, double all,
4201 s->stat[ALL] += all;
4202 s->worst = VPXMIN(s->worst, all);
4204 #endif // CONFIG_INTERNAL_STATS
4206 static void update_level_info(VP9_COMP *cpi, size_t *size, int arf_src_index) {
4207 VP9_COMMON *const cm = &cpi->common;
4208 Vp9LevelInfo *const level_info = &cpi->level_info;
4209 Vp9LevelSpec *const level_spec = &level_info->level_spec;
4210 Vp9LevelStats *const level_stats = &level_info->level_stats;
4212 uint64_t luma_samples, dur_end;
4213 const uint32_t luma_pic_size = cm->width * cm->height;
4214 double cpb_data_size;
4216 vpx_clear_system_state();
4218 // update level_stats
4219 level_stats->total_compressed_size += *size;
4220 if (cm->show_frame) {
4221 level_stats->total_uncompressed_size +=
4223 2 * (luma_pic_size >> (cm->subsampling_x + cm->subsampling_y));
4224 level_stats->time_encoded =
4225 (cpi->last_end_time_stamp_seen - cpi->first_time_stamp_ever) /
4226 (double)TICKS_PER_SEC;
4229 if (arf_src_index > 0) {
4230 if (!level_stats->seen_first_altref) {
4231 level_stats->seen_first_altref = 1;
4232 } else if (level_stats->frames_since_last_altref <
4233 level_spec->min_altref_distance) {
4234 level_spec->min_altref_distance = level_stats->frames_since_last_altref;
4236 level_stats->frames_since_last_altref = 0;
4238 ++level_stats->frames_since_last_altref;
4241 if (level_stats->frame_window_buffer.len < FRAME_WINDOW_SIZE - 1) {
4242 idx = (level_stats->frame_window_buffer.start +
4243 level_stats->frame_window_buffer.len++) %
4246 idx = level_stats->frame_window_buffer.start;
4247 level_stats->frame_window_buffer.start = (idx + 1) % FRAME_WINDOW_SIZE;
4249 level_stats->frame_window_buffer.buf[idx].ts = cpi->last_time_stamp_seen;
4250 level_stats->frame_window_buffer.buf[idx].size = (uint32_t)(*size);
4251 level_stats->frame_window_buffer.buf[idx].luma_samples = luma_pic_size;
4253 if (cm->frame_type == KEY_FRAME) {
4254 level_stats->ref_refresh_map = 0;
4257 level_stats->ref_refresh_map |= vp9_get_refresh_mask(cpi);
4258 // Also need to consider the case where the encoder refers to a buffer
4259 // that has been implicitly refreshed after encoding a keyframe.
4260 if (!cm->intra_only) {
4261 level_stats->ref_refresh_map |= (1 << cpi->lst_fb_idx);
4262 level_stats->ref_refresh_map |= (1 << cpi->gld_fb_idx);
4263 level_stats->ref_refresh_map |= (1 << cpi->alt_fb_idx);
4265 for (i = 0; i < REF_FRAMES; ++i) {
4266 count += (level_stats->ref_refresh_map >> i) & 1;
4268 if (count > level_spec->max_ref_frame_buffers) {
4269 level_spec->max_ref_frame_buffers = count;
4273 // update average_bitrate
4274 level_spec->average_bitrate = (double)level_stats->total_compressed_size /
4275 125.0 / level_stats->time_encoded;
4277 // update max_luma_sample_rate
4279 for (i = 0; i < level_stats->frame_window_buffer.len; ++i) {
4280 idx = (level_stats->frame_window_buffer.start +
4281 level_stats->frame_window_buffer.len - 1 - i) %
4284 dur_end = level_stats->frame_window_buffer.buf[idx].ts;
4286 if (dur_end - level_stats->frame_window_buffer.buf[idx].ts >=
4290 luma_samples += level_stats->frame_window_buffer.buf[idx].luma_samples;
4292 if (luma_samples > level_spec->max_luma_sample_rate) {
4293 level_spec->max_luma_sample_rate = luma_samples;
4296 // update max_cpb_size
4298 for (i = 0; i < CPB_WINDOW_SIZE; ++i) {
4299 if (i >= level_stats->frame_window_buffer.len) break;
4300 idx = (level_stats->frame_window_buffer.start +
4301 level_stats->frame_window_buffer.len - 1 - i) %
4303 cpb_data_size += level_stats->frame_window_buffer.buf[idx].size;
4305 cpb_data_size = cpb_data_size / 125.0;
4306 if (cpb_data_size > level_spec->max_cpb_size) {
4307 level_spec->max_cpb_size = cpb_data_size;
4310 // update max_luma_picture_size
4311 if (luma_pic_size > level_spec->max_luma_picture_size) {
4312 level_spec->max_luma_picture_size = luma_pic_size;
4315 // update compression_ratio
4316 level_spec->compression_ratio = (double)level_stats->total_uncompressed_size *
4318 level_stats->total_compressed_size / 8.0;
4320 // update max_col_tiles
4321 if (level_spec->max_col_tiles < (1 << cm->log2_tile_cols)) {
4322 level_spec->max_col_tiles = (1 << cm->log2_tile_cols);
4326 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
4327 size_t *size, uint8_t *dest, int64_t *time_stamp,
4328 int64_t *time_end, int flush) {
4329 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
4330 VP9_COMMON *const cm = &cpi->common;
4331 BufferPool *const pool = cm->buffer_pool;
4332 RATE_CONTROL *const rc = &cpi->rc;
4333 struct vpx_usec_timer cmptimer;
4334 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
4335 struct lookahead_entry *last_source = NULL;
4336 struct lookahead_entry *source = NULL;
4340 if (is_two_pass_svc(cpi)) {
4341 #if CONFIG_SPATIAL_SVC
4342 vp9_svc_start_frame(cpi);
4343 // Use a small empty frame instead of a real frame
4344 if (cpi->svc.encode_empty_frame_state == ENCODING)
4345 source = &cpi->svc.empty_frame;
4347 if (oxcf->pass == 2) vp9_restore_layer_context(cpi);
4348 } else if (is_one_pass_cbr_svc(cpi)) {
4349 vp9_one_pass_cbr_svc_start_layer(cpi);
4352 vpx_usec_timer_start(&cmptimer);
4354 vp9_set_high_precision_mv(cpi, ALTREF_HIGH_PRECISION_MV);
4356 // Is multi-arf enabled.
4357 // Note that at the moment multi_arf is only configured for 2 pass VBR and
4358 // will not work properly with svc.
4359 if ((oxcf->pass == 2) && !cpi->use_svc && (cpi->oxcf.enable_auto_arf > 1))
4360 cpi->multi_arf_allowed = 1;
4362 cpi->multi_arf_allowed = 0;
4365 cm->reset_frame_context = 0;
4366 cm->refresh_frame_context = 1;
4367 if (!is_one_pass_cbr_svc(cpi)) {
4368 cpi->refresh_last_frame = 1;
4369 cpi->refresh_golden_frame = 0;
4370 cpi->refresh_alt_ref_frame = 0;
4373 // Should we encode an arf frame.
4374 arf_src_index = get_arf_src_index(cpi);
4376 // Skip alt frame if we encode the empty frame
4377 if (is_two_pass_svc(cpi) && source != NULL) arf_src_index = 0;
4379 if (arf_src_index) {
4380 for (i = 0; i <= arf_src_index; ++i) {
4381 struct lookahead_entry *e = vp9_lookahead_peek(cpi->lookahead, i);
4382 // Avoid creating an alt-ref if there's a forced keyframe pending.
4385 } else if (e->flags == VPX_EFLAG_FORCE_KF) {
4393 if (arf_src_index) {
4394 assert(arf_src_index <= rc->frames_to_key);
4396 if ((source = vp9_lookahead_peek(cpi->lookahead, arf_src_index)) != NULL) {
4397 cpi->alt_ref_source = source;
4399 #if CONFIG_SPATIAL_SVC
4400 if (is_two_pass_svc(cpi) && cpi->svc.spatial_layer_id > 0) {
4402 // Reference a hidden frame from a lower layer
4403 for (i = cpi->svc.spatial_layer_id - 1; i >= 0; --i) {
4404 if (oxcf->ss_enable_auto_arf[i]) {
4405 cpi->gld_fb_idx = cpi->svc.layer_context[i].alt_ref_idx;
4410 cpi->svc.layer_context[cpi->svc.spatial_layer_id].has_alt_frame = 1;
4413 if ((oxcf->arnr_max_frames > 0) && (oxcf->arnr_strength > 0)) {
4414 // Produce the filtered ARF frame.
4415 vp9_temporal_filter(cpi, arf_src_index);
4416 vpx_extend_frame_borders(&cpi->alt_ref_buffer);
4417 force_src_buffer = &cpi->alt_ref_buffer;
4422 cpi->refresh_alt_ref_frame = 1;
4423 cpi->refresh_golden_frame = 0;
4424 cpi->refresh_last_frame = 0;
4425 rc->is_src_frame_alt_ref = 0;
4426 rc->source_alt_ref_pending = 0;
4428 rc->source_alt_ref_pending = 0;
4433 // Get last frame source.
4434 if (cm->current_video_frame > 0) {
4435 if ((last_source = vp9_lookahead_peek(cpi->lookahead, -1)) == NULL)
4439 // Read in the source frame.
4441 source = vp9_svc_lookahead_pop(cpi, cpi->lookahead, flush);
4443 source = vp9_lookahead_pop(cpi->lookahead, flush);
4445 if (source != NULL) {
4448 // if the flags indicate intra frame, but if the current picture is for
4449 // non-zero spatial layer, it should not be an intra picture.
4450 // TODO(Won Kap): this needs to change if per-layer intra frame is
4452 if ((source->flags & VPX_EFLAG_FORCE_KF) &&
4453 cpi->svc.spatial_layer_id > cpi->svc.first_spatial_layer_to_encode) {
4454 source->flags &= ~(unsigned int)(VPX_EFLAG_FORCE_KF);
4457 // Check to see if the frame should be encoded as an arf overlay.
4458 check_src_altref(cpi, source);
4463 cpi->un_scaled_source = cpi->Source =
4464 force_src_buffer ? force_src_buffer : &source->img;
4466 #ifdef ENABLE_KF_DENOISE
4467 // Copy of raw source for metrics calculation.
4468 if (is_psnr_calc_enabled(cpi))
4469 vp9_copy_and_extend_frame(cpi->Source, &cpi->raw_unscaled_source);
4472 cpi->unscaled_last_source = last_source != NULL ? &last_source->img : NULL;
4474 *time_stamp = source->ts_start;
4475 *time_end = source->ts_end;
4476 *frame_flags = (source->flags & VPX_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
4480 if (flush && oxcf->pass == 1 && !cpi->twopass.first_pass_done) {
4481 vp9_end_first_pass(cpi); /* get last stats packet */
4482 cpi->twopass.first_pass_done = 1;
4487 if (source->ts_start < cpi->first_time_stamp_ever) {
4488 cpi->first_time_stamp_ever = source->ts_start;
4489 cpi->last_end_time_stamp_seen = source->ts_start;
4492 // Clear down mmx registers
4493 vpx_clear_system_state();
4495 // adjust frame rates based on timestamps given
4496 if (cm->show_frame) {
4497 adjust_frame_rate(cpi, source);
4500 if (is_one_pass_cbr_svc(cpi)) {
4501 vp9_update_temporal_layer_framerate(cpi);
4502 vp9_restore_layer_context(cpi);
4505 // Find a free buffer for the new frame, releasing the reference previously
4507 if (cm->new_fb_idx != INVALID_IDX) {
4508 --pool->frame_bufs[cm->new_fb_idx].ref_count;
4510 cm->new_fb_idx = get_free_fb(cm);
4512 if (cm->new_fb_idx == INVALID_IDX) return -1;
4514 cm->cur_frame = &pool->frame_bufs[cm->new_fb_idx];
4516 if (!cpi->use_svc && cpi->multi_arf_allowed) {
4517 if (cm->frame_type == KEY_FRAME) {
4518 init_buffer_indices(cpi);
4519 } else if (oxcf->pass == 2) {
4520 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4521 cpi->alt_fb_idx = gf_group->arf_ref_idx[gf_group->index];
4525 // Start with a 0 size frame.
4528 cpi->frame_flags = *frame_flags;
4530 if ((oxcf->pass == 2) &&
4531 (!cpi->use_svc || (is_two_pass_svc(cpi) &&
4532 cpi->svc.encode_empty_frame_state != ENCODING))) {
4533 vp9_rc_get_second_pass_params(cpi);
4534 } else if (oxcf->pass == 1) {
4535 set_frame_size(cpi);
4538 if (cpi->oxcf.pass != 0 || cpi->use_svc || frame_is_intra_only(cm) == 1) {
4539 for (i = 0; i < MAX_REF_FRAMES; ++i) cpi->scaled_ref_idx[i] = INVALID_IDX;
4542 if (oxcf->pass == 1 && (!cpi->use_svc || is_two_pass_svc(cpi))) {
4543 const int lossless = is_lossless_requested(oxcf);
4544 #if CONFIG_VP9_HIGHBITDEPTH
4545 if (cpi->oxcf.use_highbitdepth)
4546 cpi->td.mb.fwd_txm4x4 =
4547 lossless ? vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
4549 cpi->td.mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vpx_fdct4x4;
4550 cpi->td.mb.highbd_itxm_add =
4551 lossless ? vp9_highbd_iwht4x4_add : vp9_highbd_idct4x4_add;
4553 cpi->td.mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vpx_fdct4x4;
4554 #endif // CONFIG_VP9_HIGHBITDEPTH
4555 cpi->td.mb.itxm_add = lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
4556 vp9_first_pass(cpi, source);
4557 } else if (oxcf->pass == 2 && (!cpi->use_svc || is_two_pass_svc(cpi))) {
4558 Pass2Encode(cpi, size, dest, frame_flags);
4559 } else if (cpi->use_svc) {
4560 SvcEncode(cpi, size, dest, frame_flags);
4563 Pass0Encode(cpi, size, dest, frame_flags);
4566 if (cm->refresh_frame_context)
4567 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
4569 // No frame encoded, or frame was dropped, release scaled references.
4570 if ((*size == 0) && (frame_is_intra_only(cm) == 0)) {
4571 release_scaled_references(cpi);
4575 cpi->droppable = !frame_is_reference(cpi);
4578 // Save layer specific state.
4579 if (is_one_pass_cbr_svc(cpi) || ((cpi->svc.number_temporal_layers > 1 ||
4580 cpi->svc.number_spatial_layers > 1) &&
4582 vp9_save_layer_context(cpi);
4585 vpx_usec_timer_mark(&cmptimer);
4586 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
4588 // Should we calculate metrics for the frame.
4589 if (is_psnr_calc_enabled(cpi)) generate_psnr_packet(cpi);
4591 if (cpi->keep_level_stats && oxcf->pass != 1)
4592 update_level_info(cpi, size, arf_src_index);
4594 #if CONFIG_INTERNAL_STATS
4596 if (oxcf->pass != 1) {
4597 double samples = 0.0;
4598 cpi->bytes += (int)(*size);
4600 if (cm->show_frame) {
4601 uint32_t bit_depth = 8;
4602 uint32_t in_bit_depth = 8;
4604 #if CONFIG_VP9_HIGHBITDEPTH
4605 if (cm->use_highbitdepth) {
4606 in_bit_depth = cpi->oxcf.input_bit_depth;
4607 bit_depth = cm->bit_depth;
4611 if (cpi->b_calculate_psnr) {
4612 YV12_BUFFER_CONFIG *orig = cpi->raw_source_frame;
4613 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
4614 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
4616 #if CONFIG_VP9_HIGHBITDEPTH
4617 vpx_calc_highbd_psnr(orig, recon, &psnr, cpi->td.mb.e_mbd.bd,
4620 vpx_calc_psnr(orig, recon, &psnr);
4621 #endif // CONFIG_VP9_HIGHBITDEPTH
4623 adjust_image_stat(psnr.psnr[1], psnr.psnr[2], psnr.psnr[3],
4624 psnr.psnr[0], &cpi->psnr);
4625 cpi->total_sq_error += psnr.sse[0];
4626 cpi->total_samples += psnr.samples[0];
4627 samples = psnr.samples[0];
4631 double frame_ssim2 = 0, weight = 0;
4632 #if CONFIG_VP9_POSTPROC
4633 if (vpx_alloc_frame_buffer(
4634 pp, recon->y_crop_width, recon->y_crop_height,
4635 cm->subsampling_x, cm->subsampling_y,
4636 #if CONFIG_VP9_HIGHBITDEPTH
4637 cm->use_highbitdepth,
4639 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment) < 0) {
4640 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
4641 "Failed to allocate post processing buffer");
4644 vp9_ppflags_t ppflags;
4645 ppflags.post_proc_flag = VP9D_DEBLOCK;
4646 ppflags.deblocking_level = 0; // not used in vp9_post_proc_frame()
4647 ppflags.noise_level = 0; // not used in vp9_post_proc_frame()
4648 vp9_post_proc_frame(cm, pp, &ppflags);
4651 vpx_clear_system_state();
4653 #if CONFIG_VP9_HIGHBITDEPTH
4654 vpx_calc_highbd_psnr(orig, pp, &psnr2, cpi->td.mb.e_mbd.bd,
4655 cpi->oxcf.input_bit_depth);
4657 vpx_calc_psnr(orig, pp, &psnr2);
4658 #endif // CONFIG_VP9_HIGHBITDEPTH
4660 cpi->totalp_sq_error += psnr2.sse[0];
4661 cpi->totalp_samples += psnr2.samples[0];
4662 adjust_image_stat(psnr2.psnr[1], psnr2.psnr[2], psnr2.psnr[3],
4663 psnr2.psnr[0], &cpi->psnrp);
4665 #if CONFIG_VP9_HIGHBITDEPTH
4666 if (cm->use_highbitdepth) {
4667 frame_ssim2 = vpx_highbd_calc_ssim(orig, recon, &weight, bit_depth,
4670 frame_ssim2 = vpx_calc_ssim(orig, recon, &weight);
4673 frame_ssim2 = vpx_calc_ssim(orig, recon, &weight);
4674 #endif // CONFIG_VP9_HIGHBITDEPTH
4676 cpi->worst_ssim = VPXMIN(cpi->worst_ssim, frame_ssim2);
4677 cpi->summed_quality += frame_ssim2 * weight;
4678 cpi->summed_weights += weight;
4680 #if CONFIG_VP9_HIGHBITDEPTH
4681 if (cm->use_highbitdepth) {
4682 frame_ssim2 = vpx_highbd_calc_ssim(orig, pp, &weight, bit_depth,
4685 frame_ssim2 = vpx_calc_ssim(orig, pp, &weight);
4688 frame_ssim2 = vpx_calc_ssim(orig, pp, &weight);
4689 #endif // CONFIG_VP9_HIGHBITDEPTH
4691 cpi->summedp_quality += frame_ssim2 * weight;
4692 cpi->summedp_weights += weight;
4695 FILE *f = fopen("q_used.stt", "a");
4696 fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
4697 cpi->common.current_video_frame, y2, u2, v2,
4698 frame_psnr2, frame_ssim2);
4704 if (cpi->b_calculate_blockiness) {
4705 #if CONFIG_VP9_HIGHBITDEPTH
4706 if (!cm->use_highbitdepth)
4709 double frame_blockiness = vp9_get_blockiness(
4710 cpi->Source->y_buffer, cpi->Source->y_stride,
4711 cm->frame_to_show->y_buffer, cm->frame_to_show->y_stride,
4712 cpi->Source->y_width, cpi->Source->y_height);
4713 cpi->worst_blockiness =
4714 VPXMAX(cpi->worst_blockiness, frame_blockiness);
4715 cpi->total_blockiness += frame_blockiness;
4719 if (cpi->b_calculate_consistency) {
4720 #if CONFIG_VP9_HIGHBITDEPTH
4721 if (!cm->use_highbitdepth)
4724 double this_inconsistency = vpx_get_ssim_metrics(
4725 cpi->Source->y_buffer, cpi->Source->y_stride,
4726 cm->frame_to_show->y_buffer, cm->frame_to_show->y_stride,
4727 cpi->Source->y_width, cpi->Source->y_height, cpi->ssim_vars,
4730 const double peak = (double)((1 << cpi->oxcf.input_bit_depth) - 1);
4731 double consistency =
4732 vpx_sse_to_psnr(samples, peak, (double)cpi->total_inconsistency);
4733 if (consistency > 0.0)
4734 cpi->worst_consistency =
4735 VPXMIN(cpi->worst_consistency, consistency);
4736 cpi->total_inconsistency += this_inconsistency;
4741 double y, u, v, frame_all;
4742 frame_all = vpx_calc_fastssim(cpi->Source, cm->frame_to_show, &y, &u,
4743 &v, bit_depth, in_bit_depth);
4744 adjust_image_stat(y, u, v, frame_all, &cpi->fastssim);
4747 double y, u, v, frame_all;
4748 frame_all = vpx_psnrhvs(cpi->Source, cm->frame_to_show, &y, &u, &v,
4749 bit_depth, in_bit_depth);
4750 adjust_image_stat(y, u, v, frame_all, &cpi->psnrhvs);
4757 if (is_two_pass_svc(cpi)) {
4758 if (cpi->svc.encode_empty_frame_state == ENCODING) {
4759 cpi->svc.encode_empty_frame_state = ENCODED;
4760 cpi->svc.encode_intra_empty_frame = 0;
4763 if (cm->show_frame) {
4764 ++cpi->svc.spatial_layer_to_encode;
4765 if (cpi->svc.spatial_layer_to_encode >= cpi->svc.number_spatial_layers)
4766 cpi->svc.spatial_layer_to_encode = 0;
4768 // May need the empty frame after an visible frame.
4769 cpi->svc.encode_empty_frame_state = NEED_TO_ENCODE;
4771 } else if (is_one_pass_cbr_svc(cpi)) {
4772 if (cm->show_frame) {
4773 ++cpi->svc.spatial_layer_to_encode;
4774 if (cpi->svc.spatial_layer_to_encode >= cpi->svc.number_spatial_layers)
4775 cpi->svc.spatial_layer_to_encode = 0;
4778 vpx_clear_system_state();
4782 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
4783 vp9_ppflags_t *flags) {
4784 VP9_COMMON *cm = &cpi->common;
4785 #if !CONFIG_VP9_POSTPROC
4789 if (!cm->show_frame) {
4793 #if CONFIG_VP9_POSTPROC
4794 ret = vp9_post_proc_frame(cm, dest, flags);
4796 if (cm->frame_to_show) {
4797 *dest = *cm->frame_to_show;
4798 dest->y_width = cm->width;
4799 dest->y_height = cm->height;
4800 dest->uv_width = cm->width >> cm->subsampling_x;
4801 dest->uv_height = cm->height >> cm->subsampling_y;
4806 #endif // !CONFIG_VP9_POSTPROC
4807 vpx_clear_system_state();
4812 int vp9_set_internal_size(VP9_COMP *cpi, VPX_SCALING horiz_mode,
4813 VPX_SCALING vert_mode) {
4814 VP9_COMMON *cm = &cpi->common;
4815 int hr = 0, hs = 0, vr = 0, vs = 0;
4817 if (horiz_mode > ONETWO || vert_mode > ONETWO) return -1;
4819 Scale2Ratio(horiz_mode, &hr, &hs);
4820 Scale2Ratio(vert_mode, &vr, &vs);
4822 // always go to the next whole number
4823 cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
4824 cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
4825 if (cm->current_video_frame) {
4826 assert(cm->width <= cpi->initial_width);
4827 assert(cm->height <= cpi->initial_height);
4830 update_frame_size(cpi);
4835 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
4836 unsigned int height) {
4837 VP9_COMMON *cm = &cpi->common;
4838 #if CONFIG_VP9_HIGHBITDEPTH
4839 check_initial_width(cpi, cm->use_highbitdepth, 1, 1);
4841 check_initial_width(cpi, 1, 1);
4842 #endif // CONFIG_VP9_HIGHBITDEPTH
4844 #if CONFIG_VP9_TEMPORAL_DENOISING
4845 setup_denoiser_buffer(cpi);
4850 if (cm->width > cpi->initial_width) {
4851 cm->width = cpi->initial_width;
4852 printf("Warning: Desired width too large, changed to %d\n", cm->width);
4857 cm->height = height;
4858 if (cm->height > cpi->initial_height) {
4859 cm->height = cpi->initial_height;
4860 printf("Warning: Desired height too large, changed to %d\n", cm->height);
4863 assert(cm->width <= cpi->initial_width);
4864 assert(cm->height <= cpi->initial_height);
4866 update_frame_size(cpi);
4871 void vp9_set_svc(VP9_COMP *cpi, int use_svc) {
4872 cpi->use_svc = use_svc;
4876 int vp9_get_quantizer(VP9_COMP *cpi) { return cpi->common.base_qindex; }
4878 void vp9_apply_encoding_flags(VP9_COMP *cpi, vpx_enc_frame_flags_t flags) {
4880 (VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF)) {
4883 if (flags & VP8_EFLAG_NO_REF_LAST) ref ^= VP9_LAST_FLAG;
4885 if (flags & VP8_EFLAG_NO_REF_GF) ref ^= VP9_GOLD_FLAG;
4887 if (flags & VP8_EFLAG_NO_REF_ARF) ref ^= VP9_ALT_FLAG;
4889 vp9_use_as_reference(cpi, ref);
4893 (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF |
4894 VP8_EFLAG_FORCE_GF | VP8_EFLAG_FORCE_ARF)) {
4897 if (flags & VP8_EFLAG_NO_UPD_LAST) upd ^= VP9_LAST_FLAG;
4899 if (flags & VP8_EFLAG_NO_UPD_GF) upd ^= VP9_GOLD_FLAG;
4901 if (flags & VP8_EFLAG_NO_UPD_ARF) upd ^= VP9_ALT_FLAG;
4903 vp9_update_reference(cpi, upd);
4906 if (flags & VP8_EFLAG_NO_UPD_ENTROPY) {
4907 vp9_update_entropy(cpi, 0);