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_alt_ref_aq.h"
40 #include "vp9/encoder/vp9_aq_360.h"
41 #include "vp9/encoder/vp9_aq_complexity.h"
42 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
43 #include "vp9/encoder/vp9_aq_variance.h"
44 #include "vp9/encoder/vp9_bitstream.h"
45 #include "vp9/encoder/vp9_context_tree.h"
46 #include "vp9/encoder/vp9_encodeframe.h"
47 #include "vp9/encoder/vp9_encodemv.h"
48 #include "vp9/encoder/vp9_encoder.h"
49 #include "vp9/encoder/vp9_extend.h"
50 #include "vp9/encoder/vp9_ethread.h"
51 #include "vp9/encoder/vp9_firstpass.h"
52 #include "vp9/encoder/vp9_mbgraph.h"
53 #include "vp9/encoder/vp9_noise_estimate.h"
54 #include "vp9/encoder/vp9_picklpf.h"
55 #include "vp9/encoder/vp9_ratectrl.h"
56 #include "vp9/encoder/vp9_rd.h"
57 #include "vp9/encoder/vp9_resize.h"
58 #include "vp9/encoder/vp9_segmentation.h"
59 #include "vp9/encoder/vp9_skin_detection.h"
60 #include "vp9/encoder/vp9_speed_features.h"
61 #include "vp9/encoder/vp9_svc_layercontext.h"
62 #include "vp9/encoder/vp9_temporal_filter.h"
64 #define AM_SEGMENT_ID_INACTIVE 7
65 #define AM_SEGMENT_ID_ACTIVE 0
67 #define ALTREF_HIGH_PRECISION_MV 1 // Whether to use high precision mv
68 // for altref computation.
69 #define HIGH_PRECISION_MV_QTHRESH 200 // Q threshold for high precision
70 // mv. Choose a very high value for
71 // now so that HIGH_PRECISION is always
73 // #define OUTPUT_YUV_REC
75 #ifdef OUTPUT_YUV_DENOISED
76 FILE *yuv_denoised_file = NULL;
78 #ifdef OUTPUT_YUV_SKINMAP
79 FILE *yuv_skinmap_file = NULL;
91 #ifdef ENABLE_KF_DENOISE
92 // Test condition for spatial denoise of source.
93 static int is_spatial_denoise_enabled(VP9_COMP *cpi) {
94 VP9_COMMON *const cm = &cpi->common;
95 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
97 return (oxcf->pass != 1) && !is_lossless_requested(&cpi->oxcf) &&
98 frame_is_intra_only(cm);
102 // Test for whether to calculate metrics for the frame.
103 static int is_psnr_calc_enabled(VP9_COMP *cpi) {
104 VP9_COMMON *const cm = &cpi->common;
105 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
107 return cpi->b_calculate_psnr && (oxcf->pass != 1) && cm->show_frame;
110 /* clang-format off */
111 static const Vp9LevelSpec vp9_level_defs[VP9_LEVELS] = {
112 { LEVEL_1, 829440, 36864, 200, 400, 2, 1, 4, 8 },
113 { LEVEL_1_1, 2764800, 73728, 800, 1000, 2, 1, 4, 8 },
114 { LEVEL_2, 4608000, 122880, 1800, 1500, 2, 1, 4, 8 },
115 { LEVEL_2_1, 9216000, 245760, 3600, 2800, 2, 2, 4, 8 },
116 { LEVEL_3, 20736000, 552960, 7200, 6000, 2, 4, 4, 8 },
117 { LEVEL_3_1, 36864000, 983040, 12000, 10000, 2, 4, 4, 8 },
118 { LEVEL_4, 83558400, 2228224, 18000, 16000, 4, 4, 4, 8 },
119 { LEVEL_4_1, 160432128, 2228224, 30000, 18000, 4, 4, 5, 6 },
120 { LEVEL_5, 311951360, 8912896, 60000, 36000, 6, 8, 6, 4 },
121 { LEVEL_5_1, 588251136, 8912896, 120000, 46000, 8, 8, 10, 4 },
122 // TODO(huisu): update max_cpb_size for level 5_2 ~ 6_2 when
123 // they are finalized (currently TBD).
124 { LEVEL_5_2, 1176502272, 8912896, 180000, 0, 8, 8, 10, 4 },
125 { LEVEL_6, 1176502272, 35651584, 180000, 0, 8, 16, 10, 4 },
126 { LEVEL_6_1, 2353004544u, 35651584, 240000, 0, 8, 16, 10, 4 },
127 { LEVEL_6_2, 4706009088u, 35651584, 480000, 0, 8, 16, 10, 4 },
129 /* clang-format on */
131 static INLINE void Scale2Ratio(VPX_SCALING mode, int *hr, int *hs) {
157 // Mark all inactive blocks as active. Other segmentation features may be set
158 // so memset cannot be used, instead only inactive blocks should be reset.
159 static void suppress_active_map(VP9_COMP *cpi) {
160 unsigned char *const seg_map = cpi->segmentation_map;
162 if (cpi->active_map.enabled || cpi->active_map.update) {
163 const int rows = cpi->common.mi_rows;
164 const int cols = cpi->common.mi_cols;
167 for (i = 0; i < rows * cols; ++i)
168 if (seg_map[i] == AM_SEGMENT_ID_INACTIVE)
169 seg_map[i] = AM_SEGMENT_ID_ACTIVE;
173 static void apply_active_map(VP9_COMP *cpi) {
174 struct segmentation *const seg = &cpi->common.seg;
175 unsigned char *const seg_map = cpi->segmentation_map;
176 const unsigned char *const active_map = cpi->active_map.map;
179 assert(AM_SEGMENT_ID_ACTIVE == CR_SEGMENT_ID_BASE);
181 if (frame_is_intra_only(&cpi->common)) {
182 cpi->active_map.enabled = 0;
183 cpi->active_map.update = 1;
186 if (cpi->active_map.update) {
187 if (cpi->active_map.enabled) {
188 for (i = 0; i < cpi->common.mi_rows * cpi->common.mi_cols; ++i)
189 if (seg_map[i] == AM_SEGMENT_ID_ACTIVE) seg_map[i] = active_map[i];
190 vp9_enable_segmentation(seg);
191 vp9_enable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
192 vp9_enable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
193 // Setting the data to -MAX_LOOP_FILTER will result in the computed loop
194 // filter level being zero regardless of the value of seg->abs_delta.
195 vp9_set_segdata(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF,
198 vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
199 vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
201 seg->update_data = 1;
205 cpi->active_map.update = 0;
209 static void init_level_info(Vp9LevelInfo *level_info) {
210 Vp9LevelStats *const level_stats = &level_info->level_stats;
211 Vp9LevelSpec *const level_spec = &level_info->level_spec;
213 memset(level_stats, 0, sizeof(*level_stats));
214 memset(level_spec, 0, sizeof(*level_spec));
215 level_spec->level = LEVEL_UNKNOWN;
216 level_spec->min_altref_distance = INT_MAX;
219 VP9_LEVEL vp9_get_level(const Vp9LevelSpec *const level_spec) {
221 const Vp9LevelSpec *this_level;
223 vpx_clear_system_state();
225 for (i = 0; i < VP9_LEVELS; ++i) {
226 this_level = &vp9_level_defs[i];
227 if ((double)level_spec->max_luma_sample_rate * (1 + SAMPLE_RATE_GRACE_P) >
228 (double)this_level->max_luma_sample_rate ||
229 level_spec->max_luma_picture_size > this_level->max_luma_picture_size ||
230 level_spec->average_bitrate > this_level->average_bitrate ||
231 level_spec->max_cpb_size > this_level->max_cpb_size ||
232 level_spec->compression_ratio < this_level->compression_ratio ||
233 level_spec->max_col_tiles > this_level->max_col_tiles ||
234 level_spec->min_altref_distance < this_level->min_altref_distance ||
235 level_spec->max_ref_frame_buffers > this_level->max_ref_frame_buffers)
239 return (i == VP9_LEVELS) ? LEVEL_UNKNOWN : vp9_level_defs[i].level;
242 int vp9_set_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
244 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
245 unsigned char *const active_map_8x8 = cpi->active_map.map;
246 const int mi_rows = cpi->common.mi_rows;
247 const int mi_cols = cpi->common.mi_cols;
248 cpi->active_map.update = 1;
251 for (r = 0; r < mi_rows; ++r) {
252 for (c = 0; c < mi_cols; ++c) {
253 active_map_8x8[r * mi_cols + c] =
254 new_map_16x16[(r >> 1) * cols + (c >> 1)]
255 ? AM_SEGMENT_ID_ACTIVE
256 : AM_SEGMENT_ID_INACTIVE;
259 cpi->active_map.enabled = 1;
261 cpi->active_map.enabled = 0;
269 int vp9_get_active_map(VP9_COMP *cpi, unsigned char *new_map_16x16, int rows,
271 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols &&
273 unsigned char *const seg_map_8x8 = cpi->segmentation_map;
274 const int mi_rows = cpi->common.mi_rows;
275 const int mi_cols = cpi->common.mi_cols;
276 memset(new_map_16x16, !cpi->active_map.enabled, rows * cols);
277 if (cpi->active_map.enabled) {
279 for (r = 0; r < mi_rows; ++r) {
280 for (c = 0; c < mi_cols; ++c) {
281 // Cyclic refresh segments are considered active despite not having
282 // AM_SEGMENT_ID_ACTIVE
283 new_map_16x16[(r >> 1) * cols + (c >> 1)] |=
284 seg_map_8x8[r * mi_cols + c] != AM_SEGMENT_ID_INACTIVE;
294 void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv) {
295 MACROBLOCK *const mb = &cpi->td.mb;
296 cpi->common.allow_high_precision_mv = allow_high_precision_mv;
297 if (cpi->common.allow_high_precision_mv) {
298 mb->mvcost = mb->nmvcost_hp;
299 mb->mvsadcost = mb->nmvsadcost_hp;
301 mb->mvcost = mb->nmvcost;
302 mb->mvsadcost = mb->nmvsadcost;
306 static void setup_frame(VP9_COMP *cpi) {
307 VP9_COMMON *const cm = &cpi->common;
308 // Set up entropy context depending on frame type. The decoder mandates
309 // the use of the default context, index 0, for keyframes and inter
310 // frames where the error_resilient_mode or intra_only flag is set. For
311 // other inter-frames the encoder currently uses only two contexts;
312 // context 1 for ALTREF frames and context 0 for the others.
313 if (frame_is_intra_only(cm) || cm->error_resilient_mode) {
314 vp9_setup_past_independence(cm);
316 if (!cpi->use_svc) cm->frame_context_idx = cpi->refresh_alt_ref_frame;
319 if (cm->frame_type == KEY_FRAME) {
320 if (!is_two_pass_svc(cpi)) cpi->refresh_golden_frame = 1;
321 cpi->refresh_alt_ref_frame = 1;
322 vp9_zero(cpi->interp_filter_selected);
324 *cm->fc = cm->frame_contexts[cm->frame_context_idx];
325 vp9_zero(cpi->interp_filter_selected[0]);
329 static void vp9_enc_setup_mi(VP9_COMMON *cm) {
331 cm->mi = cm->mip + cm->mi_stride + 1;
332 memset(cm->mip, 0, cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mip));
333 cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
334 // Clear top border row
335 memset(cm->prev_mip, 0, sizeof(*cm->prev_mip) * cm->mi_stride);
336 // Clear left border column
337 for (i = 1; i < cm->mi_rows + 1; ++i)
338 memset(&cm->prev_mip[i * cm->mi_stride], 0, sizeof(*cm->prev_mip));
340 cm->mi_grid_visible = cm->mi_grid_base + cm->mi_stride + 1;
341 cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mi_stride + 1;
343 memset(cm->mi_grid_base, 0,
344 cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mi_grid_base));
347 static int vp9_enc_alloc_mi(VP9_COMMON *cm, int mi_size) {
348 cm->mip = vpx_calloc(mi_size, sizeof(*cm->mip));
349 if (!cm->mip) return 1;
350 cm->prev_mip = vpx_calloc(mi_size, sizeof(*cm->prev_mip));
351 if (!cm->prev_mip) return 1;
352 cm->mi_alloc_size = mi_size;
354 cm->mi_grid_base = (MODE_INFO **)vpx_calloc(mi_size, sizeof(MODE_INFO *));
355 if (!cm->mi_grid_base) return 1;
356 cm->prev_mi_grid_base =
357 (MODE_INFO **)vpx_calloc(mi_size, sizeof(MODE_INFO *));
358 if (!cm->prev_mi_grid_base) return 1;
363 static void vp9_enc_free_mi(VP9_COMMON *cm) {
366 vpx_free(cm->prev_mip);
368 vpx_free(cm->mi_grid_base);
369 cm->mi_grid_base = NULL;
370 vpx_free(cm->prev_mi_grid_base);
371 cm->prev_mi_grid_base = NULL;
374 static void vp9_swap_mi_and_prev_mi(VP9_COMMON *cm) {
375 // Current mip will be the prev_mip for the next frame.
376 MODE_INFO **temp_base = cm->prev_mi_grid_base;
377 MODE_INFO *temp = cm->prev_mip;
378 cm->prev_mip = cm->mip;
381 // Update the upper left visible macroblock ptrs.
382 cm->mi = cm->mip + cm->mi_stride + 1;
383 cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
385 cm->prev_mi_grid_base = cm->mi_grid_base;
386 cm->mi_grid_base = temp_base;
387 cm->mi_grid_visible = cm->mi_grid_base + cm->mi_stride + 1;
388 cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mi_stride + 1;
391 void vp9_initialize_enc(void) {
392 static volatile int init_done = 0;
398 vp9_init_intra_predictors();
400 vp9_rc_init_minq_luts();
401 vp9_entropy_mv_init();
402 vp9_temporal_filter_init();
407 static void dealloc_compressor_data(VP9_COMP *cpi) {
408 VP9_COMMON *const cm = &cpi->common;
411 vpx_free(cpi->mbmi_ext_base);
412 cpi->mbmi_ext_base = NULL;
414 vpx_free(cpi->tile_data);
415 cpi->tile_data = NULL;
417 vpx_free(cpi->segmentation_map);
418 cpi->segmentation_map = NULL;
419 vpx_free(cpi->coding_context.last_frame_seg_map_copy);
420 cpi->coding_context.last_frame_seg_map_copy = NULL;
422 vpx_free(cpi->nmvcosts[0]);
423 vpx_free(cpi->nmvcosts[1]);
424 cpi->nmvcosts[0] = NULL;
425 cpi->nmvcosts[1] = NULL;
427 vpx_free(cpi->nmvcosts_hp[0]);
428 vpx_free(cpi->nmvcosts_hp[1]);
429 cpi->nmvcosts_hp[0] = NULL;
430 cpi->nmvcosts_hp[1] = NULL;
432 vpx_free(cpi->nmvsadcosts[0]);
433 vpx_free(cpi->nmvsadcosts[1]);
434 cpi->nmvsadcosts[0] = NULL;
435 cpi->nmvsadcosts[1] = NULL;
437 vpx_free(cpi->nmvsadcosts_hp[0]);
438 vpx_free(cpi->nmvsadcosts_hp[1]);
439 cpi->nmvsadcosts_hp[0] = NULL;
440 cpi->nmvsadcosts_hp[1] = NULL;
442 vp9_cyclic_refresh_free(cpi->cyclic_refresh);
443 cpi->cyclic_refresh = NULL;
445 vpx_free(cpi->active_map.map);
446 cpi->active_map.map = NULL;
448 vpx_free(cpi->consec_zero_mv);
449 cpi->consec_zero_mv = NULL;
451 vp9_free_ref_frame_buffers(cm->buffer_pool);
452 #if CONFIG_VP9_POSTPROC
453 vp9_free_postproc_buffers(cm);
455 vp9_free_context_buffers(cm);
457 vpx_free_frame_buffer(&cpi->last_frame_uf);
458 vpx_free_frame_buffer(&cpi->scaled_source);
459 vpx_free_frame_buffer(&cpi->scaled_last_source);
460 vpx_free_frame_buffer(&cpi->alt_ref_buffer);
461 #ifdef ENABLE_KF_DENOISE
462 vpx_free_frame_buffer(&cpi->raw_unscaled_source);
463 vpx_free_frame_buffer(&cpi->raw_scaled_source);
466 vp9_lookahead_destroy(cpi->lookahead);
468 vpx_free(cpi->tile_tok[0][0]);
469 cpi->tile_tok[0][0] = 0;
471 vp9_free_pc_tree(&cpi->td);
473 for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
474 LAYER_CONTEXT *const lc = &cpi->svc.layer_context[i];
475 vpx_free(lc->rc_twopass_stats_in.buf);
476 lc->rc_twopass_stats_in.buf = NULL;
477 lc->rc_twopass_stats_in.sz = 0;
480 if (cpi->source_diff_var != NULL) {
481 vpx_free(cpi->source_diff_var);
482 cpi->source_diff_var = NULL;
485 for (i = 0; i < MAX_LAG_BUFFERS; ++i) {
486 vpx_free_frame_buffer(&cpi->svc.scaled_frames[i]);
488 memset(&cpi->svc.scaled_frames[0], 0,
489 MAX_LAG_BUFFERS * sizeof(cpi->svc.scaled_frames[0]));
491 vpx_free_frame_buffer(&cpi->svc.scaled_temp);
492 memset(&cpi->svc.scaled_temp, 0, sizeof(cpi->svc.scaled_temp));
494 vpx_free_frame_buffer(&cpi->svc.empty_frame.img);
495 memset(&cpi->svc.empty_frame, 0, sizeof(cpi->svc.empty_frame));
497 vp9_free_svc_cyclic_refresh(cpi);
500 static void save_coding_context(VP9_COMP *cpi) {
501 CODING_CONTEXT *const cc = &cpi->coding_context;
502 VP9_COMMON *cm = &cpi->common;
504 // Stores a snapshot of key state variables which can subsequently be
505 // restored with a call to vp9_restore_coding_context. These functions are
506 // intended for use in a re-code loop in vp9_compress_frame where the
507 // quantizer value is adjusted between loop iterations.
508 vp9_copy(cc->nmvjointcost, cpi->td.mb.nmvjointcost);
510 memcpy(cc->nmvcosts[0], cpi->nmvcosts[0],
511 MV_VALS * sizeof(*cpi->nmvcosts[0]));
512 memcpy(cc->nmvcosts[1], cpi->nmvcosts[1],
513 MV_VALS * sizeof(*cpi->nmvcosts[1]));
514 memcpy(cc->nmvcosts_hp[0], cpi->nmvcosts_hp[0],
515 MV_VALS * sizeof(*cpi->nmvcosts_hp[0]));
516 memcpy(cc->nmvcosts_hp[1], cpi->nmvcosts_hp[1],
517 MV_VALS * sizeof(*cpi->nmvcosts_hp[1]));
519 vp9_copy(cc->segment_pred_probs, cm->seg.pred_probs);
521 memcpy(cpi->coding_context.last_frame_seg_map_copy, cm->last_frame_seg_map,
522 (cm->mi_rows * cm->mi_cols));
524 vp9_copy(cc->last_ref_lf_deltas, cm->lf.last_ref_deltas);
525 vp9_copy(cc->last_mode_lf_deltas, cm->lf.last_mode_deltas);
530 static void restore_coding_context(VP9_COMP *cpi) {
531 CODING_CONTEXT *const cc = &cpi->coding_context;
532 VP9_COMMON *cm = &cpi->common;
534 // Restore key state variables to the snapshot state stored in the
535 // previous call to vp9_save_coding_context.
536 vp9_copy(cpi->td.mb.nmvjointcost, cc->nmvjointcost);
538 memcpy(cpi->nmvcosts[0], cc->nmvcosts[0], MV_VALS * sizeof(*cc->nmvcosts[0]));
539 memcpy(cpi->nmvcosts[1], cc->nmvcosts[1], MV_VALS * sizeof(*cc->nmvcosts[1]));
540 memcpy(cpi->nmvcosts_hp[0], cc->nmvcosts_hp[0],
541 MV_VALS * sizeof(*cc->nmvcosts_hp[0]));
542 memcpy(cpi->nmvcosts_hp[1], cc->nmvcosts_hp[1],
543 MV_VALS * sizeof(*cc->nmvcosts_hp[1]));
545 vp9_copy(cm->seg.pred_probs, cc->segment_pred_probs);
547 memcpy(cm->last_frame_seg_map, cpi->coding_context.last_frame_seg_map_copy,
548 (cm->mi_rows * cm->mi_cols));
550 vp9_copy(cm->lf.last_ref_deltas, cc->last_ref_lf_deltas);
551 vp9_copy(cm->lf.last_mode_deltas, cc->last_mode_lf_deltas);
556 static void configure_static_seg_features(VP9_COMP *cpi) {
557 VP9_COMMON *const cm = &cpi->common;
558 const RATE_CONTROL *const rc = &cpi->rc;
559 struct segmentation *const seg = &cm->seg;
561 int high_q = (int)(rc->avg_q > 48.0);
564 // Disable and clear down for KF
565 if (cm->frame_type == KEY_FRAME) {
566 // Clear down the global segmentation map
567 memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
569 seg->update_data = 0;
570 cpi->static_mb_pct = 0;
572 // Disable segmentation
573 vp9_disable_segmentation(seg);
575 // Clear down the segment features.
576 vp9_clearall_segfeatures(seg);
577 } else if (cpi->refresh_alt_ref_frame) {
578 // If this is an alt ref frame
579 // Clear down the global segmentation map
580 memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
582 seg->update_data = 0;
583 cpi->static_mb_pct = 0;
585 // Disable segmentation and individual segment features by default
586 vp9_disable_segmentation(seg);
587 vp9_clearall_segfeatures(seg);
589 // Scan frames from current to arf frame.
590 // This function re-enables segmentation if appropriate.
591 vp9_update_mbgraph_stats(cpi);
593 // If segmentation was enabled set those features needed for the
597 seg->update_data = 1;
600 vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 0.875, cm->bit_depth);
601 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta - 2);
602 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
604 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
605 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
607 // Where relevant assume segment data is delta data
608 seg->abs_delta = SEGMENT_DELTADATA;
610 } else if (seg->enabled) {
611 // All other frames if segmentation has been enabled
613 // First normal frame in a valid gf or alt ref group
614 if (rc->frames_since_golden == 0) {
615 // Set up segment features for normal frames in an arf group
616 if (rc->source_alt_ref_active) {
618 seg->update_data = 1;
619 seg->abs_delta = SEGMENT_DELTADATA;
622 vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 1.125, cm->bit_depth);
623 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta + 2);
624 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
626 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
627 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
629 // Segment coding disabled for compred testing
630 if (high_q || (cpi->static_mb_pct == 100)) {
631 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
632 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
633 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
636 // Disable segmentation and clear down features if alt ref
637 // is not active for this group
639 vp9_disable_segmentation(seg);
641 memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
644 seg->update_data = 0;
646 vp9_clearall_segfeatures(seg);
648 } else if (rc->is_src_frame_alt_ref) {
649 // Special case where we are coding over the top of a previous
651 // Segment coding disabled for compred testing
653 // Enable ref frame features for segment 0 as well
654 vp9_enable_segfeature(seg, 0, SEG_LVL_REF_FRAME);
655 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
657 // All mbs should use ALTREF_FRAME
658 vp9_clear_segdata(seg, 0, SEG_LVL_REF_FRAME);
659 vp9_set_segdata(seg, 0, SEG_LVL_REF_FRAME, ALTREF_FRAME);
660 vp9_clear_segdata(seg, 1, SEG_LVL_REF_FRAME);
661 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
663 // Skip all MBs if high Q (0,0 mv and skip coeffs)
665 vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
666 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
668 // Enable data update
669 seg->update_data = 1;
673 // No updates.. leave things as they are.
675 seg->update_data = 0;
680 static void update_reference_segmentation_map(VP9_COMP *cpi) {
681 VP9_COMMON *const cm = &cpi->common;
682 MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
683 uint8_t *cache_ptr = cm->last_frame_seg_map;
686 for (row = 0; row < cm->mi_rows; row++) {
687 MODE_INFO **mi_8x8 = mi_8x8_ptr;
688 uint8_t *cache = cache_ptr;
689 for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
690 cache[0] = mi_8x8[0]->segment_id;
691 mi_8x8_ptr += cm->mi_stride;
692 cache_ptr += cm->mi_cols;
696 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
697 VP9_COMMON *cm = &cpi->common;
698 const VP9EncoderConfig *oxcf = &cpi->oxcf;
701 cpi->lookahead = vp9_lookahead_init(oxcf->width, oxcf->height,
702 cm->subsampling_x, cm->subsampling_y,
703 #if CONFIG_VP9_HIGHBITDEPTH
704 cm->use_highbitdepth,
706 oxcf->lag_in_frames);
708 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
709 "Failed to allocate lag buffers");
711 // TODO(agrange) Check if ARF is enabled and skip allocation if not.
712 if (vpx_realloc_frame_buffer(&cpi->alt_ref_buffer, oxcf->width, oxcf->height,
713 cm->subsampling_x, cm->subsampling_y,
714 #if CONFIG_VP9_HIGHBITDEPTH
715 cm->use_highbitdepth,
717 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
719 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
720 "Failed to allocate altref buffer");
723 static void alloc_util_frame_buffers(VP9_COMP *cpi) {
724 VP9_COMMON *const cm = &cpi->common;
725 if (vpx_realloc_frame_buffer(&cpi->last_frame_uf, cm->width, cm->height,
726 cm->subsampling_x, cm->subsampling_y,
727 #if CONFIG_VP9_HIGHBITDEPTH
728 cm->use_highbitdepth,
730 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
732 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
733 "Failed to allocate last frame buffer");
735 if (vpx_realloc_frame_buffer(&cpi->scaled_source, cm->width, cm->height,
736 cm->subsampling_x, cm->subsampling_y,
737 #if CONFIG_VP9_HIGHBITDEPTH
738 cm->use_highbitdepth,
740 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
742 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
743 "Failed to allocate scaled source buffer");
745 // For 1 pass cbr: allocate scaled_frame that may be used as an intermediate
746 // buffer for a 2 stage down-sampling: two stages of 1:2 down-sampling for a
747 // target of 1/4x1/4.
748 if (is_one_pass_cbr_svc(cpi) && !cpi->svc.scaled_temp_is_alloc) {
749 cpi->svc.scaled_temp_is_alloc = 1;
750 if (vpx_realloc_frame_buffer(
751 &cpi->svc.scaled_temp, cm->width >> 1, cm->height >> 1,
752 cm->subsampling_x, cm->subsampling_y,
753 #if CONFIG_VP9_HIGHBITDEPTH
754 cm->use_highbitdepth,
756 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment, NULL, NULL, NULL))
757 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
758 "Failed to allocate scaled_frame for svc ");
761 if (vpx_realloc_frame_buffer(&cpi->scaled_last_source, cm->width, cm->height,
762 cm->subsampling_x, cm->subsampling_y,
763 #if CONFIG_VP9_HIGHBITDEPTH
764 cm->use_highbitdepth,
766 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
768 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
769 "Failed to allocate scaled last source buffer");
770 #ifdef ENABLE_KF_DENOISE
771 if (vpx_realloc_frame_buffer(&cpi->raw_unscaled_source, cm->width, cm->height,
772 cm->subsampling_x, cm->subsampling_y,
773 #if CONFIG_VP9_HIGHBITDEPTH
774 cm->use_highbitdepth,
776 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
778 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
779 "Failed to allocate unscaled raw source frame buffer");
781 if (vpx_realloc_frame_buffer(&cpi->raw_scaled_source, cm->width, cm->height,
782 cm->subsampling_x, cm->subsampling_y,
783 #if CONFIG_VP9_HIGHBITDEPTH
784 cm->use_highbitdepth,
786 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
788 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
789 "Failed to allocate scaled raw source frame buffer");
793 static int alloc_context_buffers_ext(VP9_COMP *cpi) {
794 VP9_COMMON *cm = &cpi->common;
795 int mi_size = cm->mi_cols * cm->mi_rows;
797 cpi->mbmi_ext_base = vpx_calloc(mi_size, sizeof(*cpi->mbmi_ext_base));
798 if (!cpi->mbmi_ext_base) return 1;
803 static void alloc_compressor_data(VP9_COMP *cpi) {
804 VP9_COMMON *cm = &cpi->common;
806 vp9_alloc_context_buffers(cm, cm->width, cm->height);
808 alloc_context_buffers_ext(cpi);
810 vpx_free(cpi->tile_tok[0][0]);
813 unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
814 CHECK_MEM_ERROR(cm, cpi->tile_tok[0][0],
815 vpx_calloc(tokens, sizeof(*cpi->tile_tok[0][0])));
818 vp9_setup_pc_tree(&cpi->common, &cpi->td);
821 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
822 cpi->framerate = framerate < 0.1 ? 30 : framerate;
823 vp9_rc_update_framerate(cpi);
826 static void set_tile_limits(VP9_COMP *cpi) {
827 VP9_COMMON *const cm = &cpi->common;
829 int min_log2_tile_cols, max_log2_tile_cols;
830 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
832 if (is_two_pass_svc(cpi) && (cpi->svc.encode_empty_frame_state == ENCODING ||
833 cpi->svc.number_spatial_layers > 1)) {
834 cm->log2_tile_cols = 0;
835 cm->log2_tile_rows = 0;
838 clamp(cpi->oxcf.tile_columns, min_log2_tile_cols, max_log2_tile_cols);
839 cm->log2_tile_rows = cpi->oxcf.tile_rows;
843 static void update_frame_size(VP9_COMP *cpi) {
844 VP9_COMMON *const cm = &cpi->common;
845 MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
847 vp9_set_mb_mi(cm, cm->width, cm->height);
848 vp9_init_context_buffers(cm);
849 vp9_init_macroblockd(cm, xd, NULL);
850 cpi->td.mb.mbmi_ext_base = cpi->mbmi_ext_base;
851 memset(cpi->mbmi_ext_base, 0,
852 cm->mi_rows * cm->mi_cols * sizeof(*cpi->mbmi_ext_base));
854 set_tile_limits(cpi);
856 if (is_two_pass_svc(cpi)) {
857 if (vpx_realloc_frame_buffer(&cpi->alt_ref_buffer, cm->width, cm->height,
858 cm->subsampling_x, cm->subsampling_y,
859 #if CONFIG_VP9_HIGHBITDEPTH
860 cm->use_highbitdepth,
862 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
864 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
865 "Failed to reallocate alt_ref_buffer");
869 static void init_buffer_indices(VP9_COMP *cpi) {
875 static void init_config(struct VP9_COMP *cpi, VP9EncoderConfig *oxcf) {
876 VP9_COMMON *const cm = &cpi->common;
879 cpi->framerate = oxcf->init_framerate;
880 cm->profile = oxcf->profile;
881 cm->bit_depth = oxcf->bit_depth;
882 #if CONFIG_VP9_HIGHBITDEPTH
883 cm->use_highbitdepth = oxcf->use_highbitdepth;
885 cm->color_space = oxcf->color_space;
886 cm->color_range = oxcf->color_range;
888 cpi->target_level = oxcf->target_level;
889 cpi->keep_level_stats = oxcf->target_level != LEVEL_MAX;
891 cm->width = oxcf->width;
892 cm->height = oxcf->height;
893 alloc_compressor_data(cpi);
895 cpi->svc.temporal_layering_mode = oxcf->temporal_layering_mode;
897 // Single thread case: use counts in common.
898 cpi->td.counts = &cm->counts;
900 // Spatial scalability.
901 cpi->svc.number_spatial_layers = oxcf->ss_number_layers;
902 // Temporal scalability.
903 cpi->svc.number_temporal_layers = oxcf->ts_number_layers;
905 if ((cpi->svc.number_temporal_layers > 1 && cpi->oxcf.rc_mode == VPX_CBR) ||
906 ((cpi->svc.number_temporal_layers > 1 ||
907 cpi->svc.number_spatial_layers > 1) &&
908 cpi->oxcf.pass != 1)) {
909 vp9_init_layer_context(cpi);
912 // change includes all joint functionality
913 vp9_change_config(cpi, oxcf);
915 cpi->static_mb_pct = 0;
916 cpi->ref_frame_flags = 0;
918 init_buffer_indices(cpi);
920 vp9_noise_estimate_init(&cpi->noise_estimate, cm->width, cm->height);
923 static void set_rc_buffer_sizes(RATE_CONTROL *rc,
924 const VP9EncoderConfig *oxcf) {
925 const int64_t bandwidth = oxcf->target_bandwidth;
926 const int64_t starting = oxcf->starting_buffer_level_ms;
927 const int64_t optimal = oxcf->optimal_buffer_level_ms;
928 const int64_t maximum = oxcf->maximum_buffer_size_ms;
930 rc->starting_buffer_level = starting * bandwidth / 1000;
931 rc->optimal_buffer_level =
932 (optimal == 0) ? bandwidth / 8 : optimal * bandwidth / 1000;
933 rc->maximum_buffer_size =
934 (maximum == 0) ? bandwidth / 8 : maximum * bandwidth / 1000;
937 #if CONFIG_VP9_HIGHBITDEPTH
938 #define HIGHBD_BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF) \
939 cpi->fn_ptr[BT].sdf = SDF; \
940 cpi->fn_ptr[BT].sdaf = SDAF; \
941 cpi->fn_ptr[BT].vf = VF; \
942 cpi->fn_ptr[BT].svf = SVF; \
943 cpi->fn_ptr[BT].svaf = SVAF; \
944 cpi->fn_ptr[BT].sdx3f = SDX3F; \
945 cpi->fn_ptr[BT].sdx8f = SDX8F; \
946 cpi->fn_ptr[BT].sdx4df = SDX4DF;
948 #define MAKE_BFP_SAD_WRAPPER(fnname) \
949 static unsigned int fnname##_bits8(const uint8_t *src_ptr, \
951 const uint8_t *ref_ptr, int ref_stride) { \
952 return fnname(src_ptr, source_stride, ref_ptr, ref_stride); \
954 static unsigned int fnname##_bits10( \
955 const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr, \
957 return fnname(src_ptr, source_stride, ref_ptr, ref_stride) >> 2; \
959 static unsigned int fnname##_bits12( \
960 const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr, \
962 return fnname(src_ptr, source_stride, ref_ptr, ref_stride) >> 4; \
965 #define MAKE_BFP_SADAVG_WRAPPER(fnname) \
966 static unsigned int fnname##_bits8( \
967 const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr, \
968 int ref_stride, const uint8_t *second_pred) { \
969 return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred); \
971 static unsigned int fnname##_bits10( \
972 const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr, \
973 int ref_stride, const uint8_t *second_pred) { \
974 return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred) >> \
977 static unsigned int fnname##_bits12( \
978 const uint8_t *src_ptr, int source_stride, const uint8_t *ref_ptr, \
979 int ref_stride, const uint8_t *second_pred) { \
980 return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred) >> \
984 #define MAKE_BFP_SAD3_WRAPPER(fnname) \
985 static void fnname##_bits8(const uint8_t *src_ptr, int source_stride, \
986 const uint8_t *ref_ptr, int ref_stride, \
987 unsigned int *sad_array) { \
988 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
990 static void fnname##_bits10(const uint8_t *src_ptr, int source_stride, \
991 const uint8_t *ref_ptr, int ref_stride, \
992 unsigned int *sad_array) { \
994 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
995 for (i = 0; i < 3; i++) sad_array[i] >>= 2; \
997 static void fnname##_bits12(const uint8_t *src_ptr, int source_stride, \
998 const uint8_t *ref_ptr, int ref_stride, \
999 unsigned int *sad_array) { \
1001 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1002 for (i = 0; i < 3; i++) sad_array[i] >>= 4; \
1005 #define MAKE_BFP_SAD8_WRAPPER(fnname) \
1006 static void fnname##_bits8(const uint8_t *src_ptr, int source_stride, \
1007 const uint8_t *ref_ptr, int ref_stride, \
1008 unsigned int *sad_array) { \
1009 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1011 static void fnname##_bits10(const uint8_t *src_ptr, int source_stride, \
1012 const uint8_t *ref_ptr, int ref_stride, \
1013 unsigned int *sad_array) { \
1015 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1016 for (i = 0; i < 8; i++) sad_array[i] >>= 2; \
1018 static void fnname##_bits12(const uint8_t *src_ptr, int source_stride, \
1019 const uint8_t *ref_ptr, int ref_stride, \
1020 unsigned int *sad_array) { \
1022 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1023 for (i = 0; i < 8; i++) sad_array[i] >>= 4; \
1025 #define MAKE_BFP_SAD4D_WRAPPER(fnname) \
1026 static void fnname##_bits8(const uint8_t *src_ptr, int source_stride, \
1027 const uint8_t *const ref_ptr[], int ref_stride, \
1028 unsigned int *sad_array) { \
1029 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1031 static void fnname##_bits10(const uint8_t *src_ptr, int source_stride, \
1032 const uint8_t *const ref_ptr[], int ref_stride, \
1033 unsigned int *sad_array) { \
1035 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1036 for (i = 0; i < 4; i++) sad_array[i] >>= 2; \
1038 static void fnname##_bits12(const uint8_t *src_ptr, int source_stride, \
1039 const uint8_t *const ref_ptr[], int ref_stride, \
1040 unsigned int *sad_array) { \
1042 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1043 for (i = 0; i < 4; i++) sad_array[i] >>= 4; \
1046 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x16)
1047 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x16_avg)
1048 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x16x4d)
1049 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x32)
1050 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x32_avg)
1051 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x32x4d)
1052 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad64x32)
1053 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad64x32_avg)
1054 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad64x32x4d)
1055 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x64)
1056 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x64_avg)
1057 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x64x4d)
1058 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x32)
1059 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x32_avg)
1060 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad32x32x3)
1061 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad32x32x8)
1062 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x32x4d)
1063 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad64x64)
1064 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad64x64_avg)
1065 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad64x64x3)
1066 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad64x64x8)
1067 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad64x64x4d)
1068 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x16)
1069 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x16_avg)
1070 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad16x16x3)
1071 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad16x16x8)
1072 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x16x4d)
1073 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x8)
1074 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x8_avg)
1075 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad16x8x3)
1076 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad16x8x8)
1077 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x8x4d)
1078 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x16)
1079 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x16_avg)
1080 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad8x16x3)
1081 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x16x8)
1082 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x16x4d)
1083 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x8)
1084 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x8_avg)
1085 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad8x8x3)
1086 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x8x8)
1087 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x8x4d)
1088 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x4)
1089 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x4_avg)
1090 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x4x8)
1091 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x4x4d)
1092 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad4x8)
1093 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad4x8_avg)
1094 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad4x8x8)
1095 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad4x8x4d)
1096 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad4x4)
1097 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad4x4_avg)
1098 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad4x4x3)
1099 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad4x4x8)
1100 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad4x4x4d)
1102 static void highbd_set_var_fns(VP9_COMP *const cpi) {
1103 VP9_COMMON *const cm = &cpi->common;
1104 if (cm->use_highbitdepth) {
1105 switch (cm->bit_depth) {
1107 HIGHBD_BFP(BLOCK_32X16, vpx_highbd_sad32x16_bits8,
1108 vpx_highbd_sad32x16_avg_bits8, vpx_highbd_8_variance32x16,
1109 vpx_highbd_8_sub_pixel_variance32x16,
1110 vpx_highbd_8_sub_pixel_avg_variance32x16, NULL, NULL,
1111 vpx_highbd_sad32x16x4d_bits8)
1113 HIGHBD_BFP(BLOCK_16X32, vpx_highbd_sad16x32_bits8,
1114 vpx_highbd_sad16x32_avg_bits8, vpx_highbd_8_variance16x32,
1115 vpx_highbd_8_sub_pixel_variance16x32,
1116 vpx_highbd_8_sub_pixel_avg_variance16x32, NULL, NULL,
1117 vpx_highbd_sad16x32x4d_bits8)
1119 HIGHBD_BFP(BLOCK_64X32, vpx_highbd_sad64x32_bits8,
1120 vpx_highbd_sad64x32_avg_bits8, vpx_highbd_8_variance64x32,
1121 vpx_highbd_8_sub_pixel_variance64x32,
1122 vpx_highbd_8_sub_pixel_avg_variance64x32, NULL, NULL,
1123 vpx_highbd_sad64x32x4d_bits8)
1125 HIGHBD_BFP(BLOCK_32X64, vpx_highbd_sad32x64_bits8,
1126 vpx_highbd_sad32x64_avg_bits8, vpx_highbd_8_variance32x64,
1127 vpx_highbd_8_sub_pixel_variance32x64,
1128 vpx_highbd_8_sub_pixel_avg_variance32x64, NULL, NULL,
1129 vpx_highbd_sad32x64x4d_bits8)
1131 HIGHBD_BFP(BLOCK_32X32, vpx_highbd_sad32x32_bits8,
1132 vpx_highbd_sad32x32_avg_bits8, vpx_highbd_8_variance32x32,
1133 vpx_highbd_8_sub_pixel_variance32x32,
1134 vpx_highbd_8_sub_pixel_avg_variance32x32,
1135 vpx_highbd_sad32x32x3_bits8, vpx_highbd_sad32x32x8_bits8,
1136 vpx_highbd_sad32x32x4d_bits8)
1138 HIGHBD_BFP(BLOCK_64X64, vpx_highbd_sad64x64_bits8,
1139 vpx_highbd_sad64x64_avg_bits8, vpx_highbd_8_variance64x64,
1140 vpx_highbd_8_sub_pixel_variance64x64,
1141 vpx_highbd_8_sub_pixel_avg_variance64x64,
1142 vpx_highbd_sad64x64x3_bits8, vpx_highbd_sad64x64x8_bits8,
1143 vpx_highbd_sad64x64x4d_bits8)
1145 HIGHBD_BFP(BLOCK_16X16, vpx_highbd_sad16x16_bits8,
1146 vpx_highbd_sad16x16_avg_bits8, vpx_highbd_8_variance16x16,
1147 vpx_highbd_8_sub_pixel_variance16x16,
1148 vpx_highbd_8_sub_pixel_avg_variance16x16,
1149 vpx_highbd_sad16x16x3_bits8, vpx_highbd_sad16x16x8_bits8,
1150 vpx_highbd_sad16x16x4d_bits8)
1153 BLOCK_16X8, vpx_highbd_sad16x8_bits8, vpx_highbd_sad16x8_avg_bits8,
1154 vpx_highbd_8_variance16x8, vpx_highbd_8_sub_pixel_variance16x8,
1155 vpx_highbd_8_sub_pixel_avg_variance16x8, vpx_highbd_sad16x8x3_bits8,
1156 vpx_highbd_sad16x8x8_bits8, vpx_highbd_sad16x8x4d_bits8)
1159 BLOCK_8X16, vpx_highbd_sad8x16_bits8, vpx_highbd_sad8x16_avg_bits8,
1160 vpx_highbd_8_variance8x16, vpx_highbd_8_sub_pixel_variance8x16,
1161 vpx_highbd_8_sub_pixel_avg_variance8x16, vpx_highbd_sad8x16x3_bits8,
1162 vpx_highbd_sad8x16x8_bits8, vpx_highbd_sad8x16x4d_bits8)
1165 BLOCK_8X8, vpx_highbd_sad8x8_bits8, vpx_highbd_sad8x8_avg_bits8,
1166 vpx_highbd_8_variance8x8, vpx_highbd_8_sub_pixel_variance8x8,
1167 vpx_highbd_8_sub_pixel_avg_variance8x8, vpx_highbd_sad8x8x3_bits8,
1168 vpx_highbd_sad8x8x8_bits8, vpx_highbd_sad8x8x4d_bits8)
1170 HIGHBD_BFP(BLOCK_8X4, vpx_highbd_sad8x4_bits8,
1171 vpx_highbd_sad8x4_avg_bits8, vpx_highbd_8_variance8x4,
1172 vpx_highbd_8_sub_pixel_variance8x4,
1173 vpx_highbd_8_sub_pixel_avg_variance8x4, NULL,
1174 vpx_highbd_sad8x4x8_bits8, vpx_highbd_sad8x4x4d_bits8)
1176 HIGHBD_BFP(BLOCK_4X8, vpx_highbd_sad4x8_bits8,
1177 vpx_highbd_sad4x8_avg_bits8, vpx_highbd_8_variance4x8,
1178 vpx_highbd_8_sub_pixel_variance4x8,
1179 vpx_highbd_8_sub_pixel_avg_variance4x8, NULL,
1180 vpx_highbd_sad4x8x8_bits8, vpx_highbd_sad4x8x4d_bits8)
1183 BLOCK_4X4, vpx_highbd_sad4x4_bits8, vpx_highbd_sad4x4_avg_bits8,
1184 vpx_highbd_8_variance4x4, vpx_highbd_8_sub_pixel_variance4x4,
1185 vpx_highbd_8_sub_pixel_avg_variance4x4, vpx_highbd_sad4x4x3_bits8,
1186 vpx_highbd_sad4x4x8_bits8, vpx_highbd_sad4x4x4d_bits8)
1190 HIGHBD_BFP(BLOCK_32X16, vpx_highbd_sad32x16_bits10,
1191 vpx_highbd_sad32x16_avg_bits10, vpx_highbd_10_variance32x16,
1192 vpx_highbd_10_sub_pixel_variance32x16,
1193 vpx_highbd_10_sub_pixel_avg_variance32x16, NULL, NULL,
1194 vpx_highbd_sad32x16x4d_bits10)
1196 HIGHBD_BFP(BLOCK_16X32, vpx_highbd_sad16x32_bits10,
1197 vpx_highbd_sad16x32_avg_bits10, vpx_highbd_10_variance16x32,
1198 vpx_highbd_10_sub_pixel_variance16x32,
1199 vpx_highbd_10_sub_pixel_avg_variance16x32, NULL, NULL,
1200 vpx_highbd_sad16x32x4d_bits10)
1202 HIGHBD_BFP(BLOCK_64X32, vpx_highbd_sad64x32_bits10,
1203 vpx_highbd_sad64x32_avg_bits10, vpx_highbd_10_variance64x32,
1204 vpx_highbd_10_sub_pixel_variance64x32,
1205 vpx_highbd_10_sub_pixel_avg_variance64x32, NULL, NULL,
1206 vpx_highbd_sad64x32x4d_bits10)
1208 HIGHBD_BFP(BLOCK_32X64, vpx_highbd_sad32x64_bits10,
1209 vpx_highbd_sad32x64_avg_bits10, vpx_highbd_10_variance32x64,
1210 vpx_highbd_10_sub_pixel_variance32x64,
1211 vpx_highbd_10_sub_pixel_avg_variance32x64, NULL, NULL,
1212 vpx_highbd_sad32x64x4d_bits10)
1214 HIGHBD_BFP(BLOCK_32X32, vpx_highbd_sad32x32_bits10,
1215 vpx_highbd_sad32x32_avg_bits10, vpx_highbd_10_variance32x32,
1216 vpx_highbd_10_sub_pixel_variance32x32,
1217 vpx_highbd_10_sub_pixel_avg_variance32x32,
1218 vpx_highbd_sad32x32x3_bits10, vpx_highbd_sad32x32x8_bits10,
1219 vpx_highbd_sad32x32x4d_bits10)
1221 HIGHBD_BFP(BLOCK_64X64, vpx_highbd_sad64x64_bits10,
1222 vpx_highbd_sad64x64_avg_bits10, vpx_highbd_10_variance64x64,
1223 vpx_highbd_10_sub_pixel_variance64x64,
1224 vpx_highbd_10_sub_pixel_avg_variance64x64,
1225 vpx_highbd_sad64x64x3_bits10, vpx_highbd_sad64x64x8_bits10,
1226 vpx_highbd_sad64x64x4d_bits10)
1228 HIGHBD_BFP(BLOCK_16X16, vpx_highbd_sad16x16_bits10,
1229 vpx_highbd_sad16x16_avg_bits10, vpx_highbd_10_variance16x16,
1230 vpx_highbd_10_sub_pixel_variance16x16,
1231 vpx_highbd_10_sub_pixel_avg_variance16x16,
1232 vpx_highbd_sad16x16x3_bits10, vpx_highbd_sad16x16x8_bits10,
1233 vpx_highbd_sad16x16x4d_bits10)
1235 HIGHBD_BFP(BLOCK_16X8, vpx_highbd_sad16x8_bits10,
1236 vpx_highbd_sad16x8_avg_bits10, vpx_highbd_10_variance16x8,
1237 vpx_highbd_10_sub_pixel_variance16x8,
1238 vpx_highbd_10_sub_pixel_avg_variance16x8,
1239 vpx_highbd_sad16x8x3_bits10, vpx_highbd_sad16x8x8_bits10,
1240 vpx_highbd_sad16x8x4d_bits10)
1242 HIGHBD_BFP(BLOCK_8X16, vpx_highbd_sad8x16_bits10,
1243 vpx_highbd_sad8x16_avg_bits10, vpx_highbd_10_variance8x16,
1244 vpx_highbd_10_sub_pixel_variance8x16,
1245 vpx_highbd_10_sub_pixel_avg_variance8x16,
1246 vpx_highbd_sad8x16x3_bits10, vpx_highbd_sad8x16x8_bits10,
1247 vpx_highbd_sad8x16x4d_bits10)
1250 BLOCK_8X8, vpx_highbd_sad8x8_bits10, vpx_highbd_sad8x8_avg_bits10,
1251 vpx_highbd_10_variance8x8, vpx_highbd_10_sub_pixel_variance8x8,
1252 vpx_highbd_10_sub_pixel_avg_variance8x8, vpx_highbd_sad8x8x3_bits10,
1253 vpx_highbd_sad8x8x8_bits10, vpx_highbd_sad8x8x4d_bits10)
1255 HIGHBD_BFP(BLOCK_8X4, vpx_highbd_sad8x4_bits10,
1256 vpx_highbd_sad8x4_avg_bits10, vpx_highbd_10_variance8x4,
1257 vpx_highbd_10_sub_pixel_variance8x4,
1258 vpx_highbd_10_sub_pixel_avg_variance8x4, NULL,
1259 vpx_highbd_sad8x4x8_bits10, vpx_highbd_sad8x4x4d_bits10)
1261 HIGHBD_BFP(BLOCK_4X8, vpx_highbd_sad4x8_bits10,
1262 vpx_highbd_sad4x8_avg_bits10, vpx_highbd_10_variance4x8,
1263 vpx_highbd_10_sub_pixel_variance4x8,
1264 vpx_highbd_10_sub_pixel_avg_variance4x8, NULL,
1265 vpx_highbd_sad4x8x8_bits10, vpx_highbd_sad4x8x4d_bits10)
1268 BLOCK_4X4, vpx_highbd_sad4x4_bits10, vpx_highbd_sad4x4_avg_bits10,
1269 vpx_highbd_10_variance4x4, vpx_highbd_10_sub_pixel_variance4x4,
1270 vpx_highbd_10_sub_pixel_avg_variance4x4, vpx_highbd_sad4x4x3_bits10,
1271 vpx_highbd_sad4x4x8_bits10, vpx_highbd_sad4x4x4d_bits10)
1275 HIGHBD_BFP(BLOCK_32X16, vpx_highbd_sad32x16_bits12,
1276 vpx_highbd_sad32x16_avg_bits12, vpx_highbd_12_variance32x16,
1277 vpx_highbd_12_sub_pixel_variance32x16,
1278 vpx_highbd_12_sub_pixel_avg_variance32x16, NULL, NULL,
1279 vpx_highbd_sad32x16x4d_bits12)
1281 HIGHBD_BFP(BLOCK_16X32, vpx_highbd_sad16x32_bits12,
1282 vpx_highbd_sad16x32_avg_bits12, vpx_highbd_12_variance16x32,
1283 vpx_highbd_12_sub_pixel_variance16x32,
1284 vpx_highbd_12_sub_pixel_avg_variance16x32, NULL, NULL,
1285 vpx_highbd_sad16x32x4d_bits12)
1287 HIGHBD_BFP(BLOCK_64X32, vpx_highbd_sad64x32_bits12,
1288 vpx_highbd_sad64x32_avg_bits12, vpx_highbd_12_variance64x32,
1289 vpx_highbd_12_sub_pixel_variance64x32,
1290 vpx_highbd_12_sub_pixel_avg_variance64x32, NULL, NULL,
1291 vpx_highbd_sad64x32x4d_bits12)
1293 HIGHBD_BFP(BLOCK_32X64, vpx_highbd_sad32x64_bits12,
1294 vpx_highbd_sad32x64_avg_bits12, vpx_highbd_12_variance32x64,
1295 vpx_highbd_12_sub_pixel_variance32x64,
1296 vpx_highbd_12_sub_pixel_avg_variance32x64, NULL, NULL,
1297 vpx_highbd_sad32x64x4d_bits12)
1299 HIGHBD_BFP(BLOCK_32X32, vpx_highbd_sad32x32_bits12,
1300 vpx_highbd_sad32x32_avg_bits12, vpx_highbd_12_variance32x32,
1301 vpx_highbd_12_sub_pixel_variance32x32,
1302 vpx_highbd_12_sub_pixel_avg_variance32x32,
1303 vpx_highbd_sad32x32x3_bits12, vpx_highbd_sad32x32x8_bits12,
1304 vpx_highbd_sad32x32x4d_bits12)
1306 HIGHBD_BFP(BLOCK_64X64, vpx_highbd_sad64x64_bits12,
1307 vpx_highbd_sad64x64_avg_bits12, vpx_highbd_12_variance64x64,
1308 vpx_highbd_12_sub_pixel_variance64x64,
1309 vpx_highbd_12_sub_pixel_avg_variance64x64,
1310 vpx_highbd_sad64x64x3_bits12, vpx_highbd_sad64x64x8_bits12,
1311 vpx_highbd_sad64x64x4d_bits12)
1313 HIGHBD_BFP(BLOCK_16X16, vpx_highbd_sad16x16_bits12,
1314 vpx_highbd_sad16x16_avg_bits12, vpx_highbd_12_variance16x16,
1315 vpx_highbd_12_sub_pixel_variance16x16,
1316 vpx_highbd_12_sub_pixel_avg_variance16x16,
1317 vpx_highbd_sad16x16x3_bits12, vpx_highbd_sad16x16x8_bits12,
1318 vpx_highbd_sad16x16x4d_bits12)
1320 HIGHBD_BFP(BLOCK_16X8, vpx_highbd_sad16x8_bits12,
1321 vpx_highbd_sad16x8_avg_bits12, vpx_highbd_12_variance16x8,
1322 vpx_highbd_12_sub_pixel_variance16x8,
1323 vpx_highbd_12_sub_pixel_avg_variance16x8,
1324 vpx_highbd_sad16x8x3_bits12, vpx_highbd_sad16x8x8_bits12,
1325 vpx_highbd_sad16x8x4d_bits12)
1327 HIGHBD_BFP(BLOCK_8X16, vpx_highbd_sad8x16_bits12,
1328 vpx_highbd_sad8x16_avg_bits12, vpx_highbd_12_variance8x16,
1329 vpx_highbd_12_sub_pixel_variance8x16,
1330 vpx_highbd_12_sub_pixel_avg_variance8x16,
1331 vpx_highbd_sad8x16x3_bits12, vpx_highbd_sad8x16x8_bits12,
1332 vpx_highbd_sad8x16x4d_bits12)
1335 BLOCK_8X8, vpx_highbd_sad8x8_bits12, vpx_highbd_sad8x8_avg_bits12,
1336 vpx_highbd_12_variance8x8, vpx_highbd_12_sub_pixel_variance8x8,
1337 vpx_highbd_12_sub_pixel_avg_variance8x8, vpx_highbd_sad8x8x3_bits12,
1338 vpx_highbd_sad8x8x8_bits12, vpx_highbd_sad8x8x4d_bits12)
1340 HIGHBD_BFP(BLOCK_8X4, vpx_highbd_sad8x4_bits12,
1341 vpx_highbd_sad8x4_avg_bits12, vpx_highbd_12_variance8x4,
1342 vpx_highbd_12_sub_pixel_variance8x4,
1343 vpx_highbd_12_sub_pixel_avg_variance8x4, NULL,
1344 vpx_highbd_sad8x4x8_bits12, vpx_highbd_sad8x4x4d_bits12)
1346 HIGHBD_BFP(BLOCK_4X8, vpx_highbd_sad4x8_bits12,
1347 vpx_highbd_sad4x8_avg_bits12, vpx_highbd_12_variance4x8,
1348 vpx_highbd_12_sub_pixel_variance4x8,
1349 vpx_highbd_12_sub_pixel_avg_variance4x8, NULL,
1350 vpx_highbd_sad4x8x8_bits12, vpx_highbd_sad4x8x4d_bits12)
1353 BLOCK_4X4, vpx_highbd_sad4x4_bits12, vpx_highbd_sad4x4_avg_bits12,
1354 vpx_highbd_12_variance4x4, vpx_highbd_12_sub_pixel_variance4x4,
1355 vpx_highbd_12_sub_pixel_avg_variance4x4, vpx_highbd_sad4x4x3_bits12,
1356 vpx_highbd_sad4x4x8_bits12, vpx_highbd_sad4x4x4d_bits12)
1361 "cm->bit_depth should be VPX_BITS_8, "
1362 "VPX_BITS_10 or VPX_BITS_12");
1366 #endif // CONFIG_VP9_HIGHBITDEPTH
1368 static void realloc_segmentation_maps(VP9_COMP *cpi) {
1369 VP9_COMMON *const cm = &cpi->common;
1371 // Create the encoder segmentation map and set all entries to 0
1372 vpx_free(cpi->segmentation_map);
1373 CHECK_MEM_ERROR(cm, cpi->segmentation_map,
1374 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1376 // Create a map used for cyclic background refresh.
1377 if (cpi->cyclic_refresh) vp9_cyclic_refresh_free(cpi->cyclic_refresh);
1378 CHECK_MEM_ERROR(cm, cpi->cyclic_refresh,
1379 vp9_cyclic_refresh_alloc(cm->mi_rows, cm->mi_cols));
1381 // Create a map used to mark inactive areas.
1382 vpx_free(cpi->active_map.map);
1383 CHECK_MEM_ERROR(cm, cpi->active_map.map,
1384 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1386 // And a place holder structure is the coding context
1387 // for use if we want to save and restore it
1388 vpx_free(cpi->coding_context.last_frame_seg_map_copy);
1389 CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
1390 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1393 void vp9_change_config(struct VP9_COMP *cpi, const VP9EncoderConfig *oxcf) {
1394 VP9_COMMON *const cm = &cpi->common;
1395 RATE_CONTROL *const rc = &cpi->rc;
1396 int last_w = cpi->oxcf.width;
1397 int last_h = cpi->oxcf.height;
1399 if (cm->profile != oxcf->profile) cm->profile = oxcf->profile;
1400 cm->bit_depth = oxcf->bit_depth;
1401 cm->color_space = oxcf->color_space;
1402 cm->color_range = oxcf->color_range;
1404 cpi->target_level = oxcf->target_level;
1405 cpi->keep_level_stats = oxcf->target_level != LEVEL_MAX;
1407 if (cm->profile <= PROFILE_1)
1408 assert(cm->bit_depth == VPX_BITS_8);
1410 assert(cm->bit_depth > VPX_BITS_8);
1413 #if CONFIG_VP9_HIGHBITDEPTH
1414 cpi->td.mb.e_mbd.bd = (int)cm->bit_depth;
1415 #endif // CONFIG_VP9_HIGHBITDEPTH
1417 if ((oxcf->pass == 0) && (oxcf->rc_mode == VPX_Q)) {
1418 rc->baseline_gf_interval = FIXED_GF_INTERVAL;
1420 rc->baseline_gf_interval = (MIN_GF_INTERVAL + MAX_GF_INTERVAL) / 2;
1423 cpi->refresh_golden_frame = 0;
1424 cpi->refresh_last_frame = 1;
1425 cm->refresh_frame_context = 1;
1426 cm->reset_frame_context = 0;
1428 vp9_reset_segment_features(&cm->seg);
1429 vp9_set_high_precision_mv(cpi, 0);
1434 for (i = 0; i < MAX_SEGMENTS; i++)
1435 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1437 cpi->encode_breakout = cpi->oxcf.encode_breakout;
1439 set_rc_buffer_sizes(rc, &cpi->oxcf);
1441 // Under a configuration change, where maximum_buffer_size may change,
1442 // keep buffer level clipped to the maximum allowed buffer size.
1443 rc->bits_off_target = VPXMIN(rc->bits_off_target, rc->maximum_buffer_size);
1444 rc->buffer_level = VPXMIN(rc->buffer_level, rc->maximum_buffer_size);
1446 // Set up frame rate and related parameters rate control values.
1447 vp9_new_framerate(cpi, cpi->framerate);
1449 // Set absolute upper and lower quality limits
1450 rc->worst_quality = cpi->oxcf.worst_allowed_q;
1451 rc->best_quality = cpi->oxcf.best_allowed_q;
1453 cm->interp_filter = cpi->sf.default_interp_filter;
1455 if (cpi->oxcf.render_width > 0 && cpi->oxcf.render_height > 0) {
1456 cm->render_width = cpi->oxcf.render_width;
1457 cm->render_height = cpi->oxcf.render_height;
1459 cm->render_width = cpi->oxcf.width;
1460 cm->render_height = cpi->oxcf.height;
1462 if (last_w != cpi->oxcf.width || last_h != cpi->oxcf.height) {
1463 cm->width = cpi->oxcf.width;
1464 cm->height = cpi->oxcf.height;
1465 cpi->external_resize = 1;
1468 if (cpi->initial_width) {
1469 int new_mi_size = 0;
1470 vp9_set_mb_mi(cm, cm->width, cm->height);
1471 new_mi_size = cm->mi_stride * calc_mi_size(cm->mi_rows);
1472 if (cm->mi_alloc_size < new_mi_size) {
1473 vp9_free_context_buffers(cm);
1474 alloc_compressor_data(cpi);
1475 realloc_segmentation_maps(cpi);
1476 cpi->initial_width = cpi->initial_height = 0;
1477 cpi->external_resize = 0;
1478 } else if (cm->mi_alloc_size == new_mi_size &&
1479 (cpi->oxcf.width > last_w || cpi->oxcf.height > last_h)) {
1480 vp9_alloc_loop_filter(cm);
1484 update_frame_size(cpi);
1486 if (last_w != cpi->oxcf.width || last_h != cpi->oxcf.height) {
1487 memset(cpi->consec_zero_mv, 0,
1488 cm->mi_rows * cm->mi_cols * sizeof(*cpi->consec_zero_mv));
1489 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1490 vp9_cyclic_refresh_reset_resize(cpi);
1493 if ((cpi->svc.number_temporal_layers > 1 && cpi->oxcf.rc_mode == VPX_CBR) ||
1494 ((cpi->svc.number_temporal_layers > 1 ||
1495 cpi->svc.number_spatial_layers > 1) &&
1496 cpi->oxcf.pass != 1)) {
1497 vp9_update_layer_context_change_config(cpi,
1498 (int)cpi->oxcf.target_bandwidth);
1501 cpi->alt_ref_source = NULL;
1502 rc->is_src_frame_alt_ref = 0;
1505 // Experimental RD Code
1506 cpi->frame_distortion = 0;
1507 cpi->last_frame_distortion = 0;
1510 set_tile_limits(cpi);
1512 cpi->ext_refresh_frame_flags_pending = 0;
1513 cpi->ext_refresh_frame_context_pending = 0;
1515 #if CONFIG_VP9_HIGHBITDEPTH
1516 highbd_set_var_fns(cpi);
1521 #define M_LOG2_E 0.693147180559945309417
1523 #define log2f(x) (log(x) / (float)M_LOG2_E)
1525 /***********************************************************************
1526 * Read before modifying 'cal_nmvjointsadcost' or 'cal_nmvsadcosts' *
1527 ***********************************************************************
1528 * The following 2 functions ('cal_nmvjointsadcost' and *
1529 * 'cal_nmvsadcosts') are used to calculate cost lookup tables *
1530 * used by 'vp9_diamond_search_sad'. The C implementation of the *
1531 * function is generic, but the AVX intrinsics optimised version *
1532 * relies on the following properties of the computed tables: *
1533 * For cal_nmvjointsadcost: *
1534 * - mvjointsadcost[1] == mvjointsadcost[2] == mvjointsadcost[3] *
1535 * For cal_nmvsadcosts: *
1536 * - For all i: mvsadcost[0][i] == mvsadcost[1][i] *
1537 * (Equal costs for both components) *
1538 * - For all i: mvsadcost[0][i] == mvsadcost[0][-i] *
1539 * (Cost function is even) *
1540 * If these do not hold, then the AVX optimised version of the *
1541 * 'vp9_diamond_search_sad' function cannot be used as it is, in which *
1542 * case you can revert to using the C function instead. *
1543 ***********************************************************************/
1545 static void cal_nmvjointsadcost(int *mvjointsadcost) {
1546 /*********************************************************************
1547 * Warning: Read the comments above before modifying this function *
1548 *********************************************************************/
1549 mvjointsadcost[0] = 600;
1550 mvjointsadcost[1] = 300;
1551 mvjointsadcost[2] = 300;
1552 mvjointsadcost[3] = 300;
1555 static void cal_nmvsadcosts(int *mvsadcost[2]) {
1556 /*********************************************************************
1557 * Warning: Read the comments above before modifying this function *
1558 *********************************************************************/
1561 mvsadcost[0][0] = 0;
1562 mvsadcost[1][0] = 0;
1565 double z = 256 * (2 * (log2f(8 * i) + .6));
1566 mvsadcost[0][i] = (int)z;
1567 mvsadcost[1][i] = (int)z;
1568 mvsadcost[0][-i] = (int)z;
1569 mvsadcost[1][-i] = (int)z;
1570 } while (++i <= MV_MAX);
1573 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
1576 mvsadcost[0][0] = 0;
1577 mvsadcost[1][0] = 0;
1580 double z = 256 * (2 * (log2f(8 * i) + .6));
1581 mvsadcost[0][i] = (int)z;
1582 mvsadcost[1][i] = (int)z;
1583 mvsadcost[0][-i] = (int)z;
1584 mvsadcost[1][-i] = (int)z;
1585 } while (++i <= MV_MAX);
1588 VP9_COMP *vp9_create_compressor(VP9EncoderConfig *oxcf,
1589 BufferPool *const pool) {
1591 VP9_COMP *volatile const cpi = vpx_memalign(32, sizeof(VP9_COMP));
1592 VP9_COMMON *volatile const cm = cpi != NULL ? &cpi->common : NULL;
1594 if (!cm) return NULL;
1598 if (setjmp(cm->error.jmp)) {
1599 cm->error.setjmp = 0;
1600 vp9_remove_compressor(cpi);
1604 cm->error.setjmp = 1;
1605 cm->alloc_mi = vp9_enc_alloc_mi;
1606 cm->free_mi = vp9_enc_free_mi;
1607 cm->setup_mi = vp9_enc_setup_mi;
1609 CHECK_MEM_ERROR(cm, cm->fc, (FRAME_CONTEXT *)vpx_calloc(1, sizeof(*cm->fc)));
1611 cm, cm->frame_contexts,
1612 (FRAME_CONTEXT *)vpx_calloc(FRAME_CONTEXTS, sizeof(*cm->frame_contexts)));
1615 cpi->resize_state = 0;
1616 cpi->external_resize = 0;
1617 cpi->resize_avg_qp = 0;
1618 cpi->resize_buffer_underflow = 0;
1619 cpi->use_skin_detection = 0;
1620 cpi->common.buffer_pool = pool;
1622 cpi->force_update_segmentation = 0;
1624 init_config(cpi, oxcf);
1625 vp9_rc_init(&cpi->oxcf, oxcf->pass, &cpi->rc);
1627 cm->current_video_frame = 0;
1628 cpi->partition_search_skippable_frame = 0;
1629 cpi->tile_data = NULL;
1631 realloc_segmentation_maps(cpi);
1633 CHECK_MEM_ERROR(cm, cpi->alt_ref_aq, vp9_alt_ref_aq_create());
1636 cm, cpi->consec_zero_mv,
1637 vpx_calloc(cm->mi_rows * cm->mi_cols, sizeof(*cpi->consec_zero_mv)));
1639 CHECK_MEM_ERROR(cm, cpi->nmvcosts[0],
1640 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts[0])));
1641 CHECK_MEM_ERROR(cm, cpi->nmvcosts[1],
1642 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts[1])));
1643 CHECK_MEM_ERROR(cm, cpi->nmvcosts_hp[0],
1644 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts_hp[0])));
1645 CHECK_MEM_ERROR(cm, cpi->nmvcosts_hp[1],
1646 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts_hp[1])));
1647 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts[0],
1648 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts[0])));
1649 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts[1],
1650 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts[1])));
1651 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts_hp[0],
1652 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts_hp[0])));
1653 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts_hp[1],
1654 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts_hp[1])));
1656 for (i = 0; i < (sizeof(cpi->mbgraph_stats) / sizeof(cpi->mbgraph_stats[0]));
1659 cm, cpi->mbgraph_stats[i].mb_stats,
1660 vpx_calloc(cm->MBs * sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
1663 #if CONFIG_FP_MB_STATS
1664 cpi->use_fp_mb_stats = 0;
1665 if (cpi->use_fp_mb_stats) {
1666 // a place holder used to store the first pass mb stats in the first pass
1667 CHECK_MEM_ERROR(cm, cpi->twopass.frame_mb_stats_buf,
1668 vpx_calloc(cm->MBs * sizeof(uint8_t), 1));
1670 cpi->twopass.frame_mb_stats_buf = NULL;
1674 cpi->refresh_alt_ref_frame = 0;
1675 cpi->multi_arf_last_grp_enabled = 0;
1677 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1679 init_level_info(&cpi->level_info);
1681 #if CONFIG_INTERNAL_STATS
1682 cpi->b_calculate_blockiness = 1;
1683 cpi->b_calculate_consistency = 1;
1684 cpi->total_inconsistency = 0;
1685 cpi->psnr.worst = 100.0;
1686 cpi->worst_ssim = 100.0;
1691 if (cpi->b_calculate_psnr) {
1692 cpi->total_sq_error = 0;
1693 cpi->total_samples = 0;
1695 cpi->totalp_sq_error = 0;
1696 cpi->totalp_samples = 0;
1698 cpi->tot_recode_hits = 0;
1699 cpi->summed_quality = 0;
1700 cpi->summed_weights = 0;
1701 cpi->summedp_quality = 0;
1702 cpi->summedp_weights = 0;
1705 cpi->fastssim.worst = 100.0;
1707 cpi->psnrhvs.worst = 100.0;
1709 if (cpi->b_calculate_blockiness) {
1710 cpi->total_blockiness = 0;
1711 cpi->worst_blockiness = 0.0;
1714 if (cpi->b_calculate_consistency) {
1715 CHECK_MEM_ERROR(cm, cpi->ssim_vars,
1716 vpx_malloc(sizeof(*cpi->ssim_vars) * 4 *
1717 cpi->common.mi_rows * cpi->common.mi_cols));
1718 cpi->worst_consistency = 100.0;
1723 cpi->first_time_stamp_ever = INT64_MAX;
1725 /*********************************************************************
1726 * Warning: Read the comments around 'cal_nmvjointsadcost' and *
1727 * 'cal_nmvsadcosts' before modifying how these tables are computed. *
1728 *********************************************************************/
1729 cal_nmvjointsadcost(cpi->td.mb.nmvjointsadcost);
1730 cpi->td.mb.nmvcost[0] = &cpi->nmvcosts[0][MV_MAX];
1731 cpi->td.mb.nmvcost[1] = &cpi->nmvcosts[1][MV_MAX];
1732 cpi->td.mb.nmvsadcost[0] = &cpi->nmvsadcosts[0][MV_MAX];
1733 cpi->td.mb.nmvsadcost[1] = &cpi->nmvsadcosts[1][MV_MAX];
1734 cal_nmvsadcosts(cpi->td.mb.nmvsadcost);
1736 cpi->td.mb.nmvcost_hp[0] = &cpi->nmvcosts_hp[0][MV_MAX];
1737 cpi->td.mb.nmvcost_hp[1] = &cpi->nmvcosts_hp[1][MV_MAX];
1738 cpi->td.mb.nmvsadcost_hp[0] = &cpi->nmvsadcosts_hp[0][MV_MAX];
1739 cpi->td.mb.nmvsadcost_hp[1] = &cpi->nmvsadcosts_hp[1][MV_MAX];
1740 cal_nmvsadcosts_hp(cpi->td.mb.nmvsadcost_hp);
1742 #if CONFIG_VP9_TEMPORAL_DENOISING
1743 #ifdef OUTPUT_YUV_DENOISED
1744 yuv_denoised_file = fopen("denoised.yuv", "ab");
1747 #ifdef OUTPUT_YUV_SKINMAP
1748 yuv_skinmap_file = fopen("skinmap.yuv", "ab");
1750 #ifdef OUTPUT_YUV_REC
1751 yuv_rec_file = fopen("rec.yuv", "wb");
1755 framepsnr = fopen("framepsnr.stt", "a");
1756 kf_list = fopen("kf_list.stt", "w");
1759 cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
1761 if (oxcf->pass == 1) {
1762 vp9_init_first_pass(cpi);
1763 } else if (oxcf->pass == 2) {
1764 const size_t packet_sz = sizeof(FIRSTPASS_STATS);
1765 const int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
1767 if (cpi->svc.number_spatial_layers > 1 ||
1768 cpi->svc.number_temporal_layers > 1) {
1769 FIRSTPASS_STATS *const stats = oxcf->two_pass_stats_in.buf;
1770 FIRSTPASS_STATS *stats_copy[VPX_SS_MAX_LAYERS] = { 0 };
1773 for (i = 0; i < oxcf->ss_number_layers; ++i) {
1774 FIRSTPASS_STATS *const last_packet_for_layer =
1775 &stats[packets - oxcf->ss_number_layers + i];
1776 const int layer_id = (int)last_packet_for_layer->spatial_layer_id;
1777 const int packets_in_layer = (int)last_packet_for_layer->count + 1;
1778 if (layer_id >= 0 && layer_id < oxcf->ss_number_layers) {
1779 LAYER_CONTEXT *const lc = &cpi->svc.layer_context[layer_id];
1781 vpx_free(lc->rc_twopass_stats_in.buf);
1783 lc->rc_twopass_stats_in.sz = packets_in_layer * packet_sz;
1784 CHECK_MEM_ERROR(cm, lc->rc_twopass_stats_in.buf,
1785 vpx_malloc(lc->rc_twopass_stats_in.sz));
1786 lc->twopass.stats_in_start = lc->rc_twopass_stats_in.buf;
1787 lc->twopass.stats_in = lc->twopass.stats_in_start;
1788 lc->twopass.stats_in_end =
1789 lc->twopass.stats_in_start + packets_in_layer - 1;
1790 stats_copy[layer_id] = lc->rc_twopass_stats_in.buf;
1794 for (i = 0; i < packets; ++i) {
1795 const int layer_id = (int)stats[i].spatial_layer_id;
1796 if (layer_id >= 0 && layer_id < oxcf->ss_number_layers &&
1797 stats_copy[layer_id] != NULL) {
1798 *stats_copy[layer_id] = stats[i];
1799 ++stats_copy[layer_id];
1803 vp9_init_second_pass_spatial_svc(cpi);
1805 #if CONFIG_FP_MB_STATS
1806 if (cpi->use_fp_mb_stats) {
1807 const size_t psz = cpi->common.MBs * sizeof(uint8_t);
1808 const int ps = (int)(oxcf->firstpass_mb_stats_in.sz / psz);
1810 cpi->twopass.firstpass_mb_stats.mb_stats_start =
1811 oxcf->firstpass_mb_stats_in.buf;
1812 cpi->twopass.firstpass_mb_stats.mb_stats_end =
1813 cpi->twopass.firstpass_mb_stats.mb_stats_start +
1814 (ps - 1) * cpi->common.MBs * sizeof(uint8_t);
1818 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1819 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1820 cpi->twopass.stats_in_end = &cpi->twopass.stats_in[packets - 1];
1822 vp9_init_second_pass(cpi);
1826 vp9_set_speed_features_framesize_independent(cpi);
1827 vp9_set_speed_features_framesize_dependent(cpi);
1829 // Allocate memory to store variances for a frame.
1830 CHECK_MEM_ERROR(cm, cpi->source_diff_var, vpx_calloc(cm->MBs, sizeof(diff)));
1831 cpi->source_var_thresh = 0;
1832 cpi->frames_till_next_var_check = 0;
1834 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF) \
1835 cpi->fn_ptr[BT].sdf = SDF; \
1836 cpi->fn_ptr[BT].sdaf = SDAF; \
1837 cpi->fn_ptr[BT].vf = VF; \
1838 cpi->fn_ptr[BT].svf = SVF; \
1839 cpi->fn_ptr[BT].svaf = SVAF; \
1840 cpi->fn_ptr[BT].sdx3f = SDX3F; \
1841 cpi->fn_ptr[BT].sdx8f = SDX8F; \
1842 cpi->fn_ptr[BT].sdx4df = SDX4DF;
1844 BFP(BLOCK_32X16, vpx_sad32x16, vpx_sad32x16_avg, vpx_variance32x16,
1845 vpx_sub_pixel_variance32x16, vpx_sub_pixel_avg_variance32x16, NULL, NULL,
1848 BFP(BLOCK_16X32, vpx_sad16x32, vpx_sad16x32_avg, vpx_variance16x32,
1849 vpx_sub_pixel_variance16x32, vpx_sub_pixel_avg_variance16x32, NULL, NULL,
1852 BFP(BLOCK_64X32, vpx_sad64x32, vpx_sad64x32_avg, vpx_variance64x32,
1853 vpx_sub_pixel_variance64x32, vpx_sub_pixel_avg_variance64x32, NULL, NULL,
1856 BFP(BLOCK_32X64, vpx_sad32x64, vpx_sad32x64_avg, vpx_variance32x64,
1857 vpx_sub_pixel_variance32x64, vpx_sub_pixel_avg_variance32x64, NULL, NULL,
1860 BFP(BLOCK_32X32, vpx_sad32x32, vpx_sad32x32_avg, vpx_variance32x32,
1861 vpx_sub_pixel_variance32x32, vpx_sub_pixel_avg_variance32x32,
1862 vpx_sad32x32x3, vpx_sad32x32x8, vpx_sad32x32x4d)
1864 BFP(BLOCK_64X64, vpx_sad64x64, vpx_sad64x64_avg, vpx_variance64x64,
1865 vpx_sub_pixel_variance64x64, vpx_sub_pixel_avg_variance64x64,
1866 vpx_sad64x64x3, vpx_sad64x64x8, vpx_sad64x64x4d)
1868 BFP(BLOCK_16X16, vpx_sad16x16, vpx_sad16x16_avg, vpx_variance16x16,
1869 vpx_sub_pixel_variance16x16, vpx_sub_pixel_avg_variance16x16,
1870 vpx_sad16x16x3, vpx_sad16x16x8, vpx_sad16x16x4d)
1872 BFP(BLOCK_16X8, vpx_sad16x8, vpx_sad16x8_avg, vpx_variance16x8,
1873 vpx_sub_pixel_variance16x8, vpx_sub_pixel_avg_variance16x8, vpx_sad16x8x3,
1874 vpx_sad16x8x8, vpx_sad16x8x4d)
1876 BFP(BLOCK_8X16, vpx_sad8x16, vpx_sad8x16_avg, vpx_variance8x16,
1877 vpx_sub_pixel_variance8x16, vpx_sub_pixel_avg_variance8x16, vpx_sad8x16x3,
1878 vpx_sad8x16x8, vpx_sad8x16x4d)
1880 BFP(BLOCK_8X8, vpx_sad8x8, vpx_sad8x8_avg, vpx_variance8x8,
1881 vpx_sub_pixel_variance8x8, vpx_sub_pixel_avg_variance8x8, vpx_sad8x8x3,
1882 vpx_sad8x8x8, vpx_sad8x8x4d)
1884 BFP(BLOCK_8X4, vpx_sad8x4, vpx_sad8x4_avg, vpx_variance8x4,
1885 vpx_sub_pixel_variance8x4, vpx_sub_pixel_avg_variance8x4, NULL,
1886 vpx_sad8x4x8, vpx_sad8x4x4d)
1888 BFP(BLOCK_4X8, vpx_sad4x8, vpx_sad4x8_avg, vpx_variance4x8,
1889 vpx_sub_pixel_variance4x8, vpx_sub_pixel_avg_variance4x8, NULL,
1890 vpx_sad4x8x8, vpx_sad4x8x4d)
1892 BFP(BLOCK_4X4, vpx_sad4x4, vpx_sad4x4_avg, vpx_variance4x4,
1893 vpx_sub_pixel_variance4x4, vpx_sub_pixel_avg_variance4x4, vpx_sad4x4x3,
1894 vpx_sad4x4x8, vpx_sad4x4x4d)
1896 #if CONFIG_VP9_HIGHBITDEPTH
1897 highbd_set_var_fns(cpi);
1900 /* vp9_init_quantizer() is first called here. Add check in
1901 * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
1902 * called later when needed. This will avoid unnecessary calls of
1903 * vp9_init_quantizer() for every frame.
1905 vp9_init_quantizer(cpi);
1907 vp9_loop_filter_init(cm);
1909 cm->error.setjmp = 0;
1914 #if CONFIG_INTERNAL_STATS
1915 #define SNPRINT(H, T) snprintf((H) + strlen(H), sizeof(H) - strlen(H), (T))
1917 #define SNPRINT2(H, T, V) \
1918 snprintf((H) + strlen(H), sizeof(H) - strlen(H), (T), (V))
1919 #endif // CONFIG_INTERNAL_STATS
1921 void vp9_remove_compressor(VP9_COMP *cpi) {
1929 if (cm->current_video_frame > 0) {
1930 #if CONFIG_INTERNAL_STATS
1931 vpx_clear_system_state();
1933 if (cpi->oxcf.pass != 1) {
1934 char headings[512] = { 0 };
1935 char results[512] = { 0 };
1936 FILE *f = fopen("opsnr.stt", "a");
1937 double time_encoded =
1938 (cpi->last_end_time_stamp_seen - cpi->first_time_stamp_ever) /
1940 double total_encode_time =
1941 (cpi->time_receive_data + cpi->time_compress_data) / 1000.000;
1943 (double)cpi->bytes * (double)8 / (double)1000 / time_encoded;
1944 const double peak = (double)((1 << cpi->oxcf.input_bit_depth) - 1);
1945 const double target_rate = (double)cpi->oxcf.target_bandwidth / 1000;
1946 const double rate_err = ((100.0 * (dr - target_rate)) / target_rate);
1948 if (cpi->b_calculate_psnr) {
1949 const double total_psnr = vpx_sse_to_psnr(
1950 (double)cpi->total_samples, peak, (double)cpi->total_sq_error);
1951 const double totalp_psnr = vpx_sse_to_psnr(
1952 (double)cpi->totalp_samples, peak, (double)cpi->totalp_sq_error);
1953 const double total_ssim =
1954 100 * pow(cpi->summed_quality / cpi->summed_weights, 8.0);
1955 const double totalp_ssim =
1956 100 * pow(cpi->summedp_quality / cpi->summedp_weights, 8.0);
1958 snprintf(headings, sizeof(headings),
1959 "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
1960 "VPXSSIM\tVPSSIMP\tFASTSIM\tPSNRHVS\t"
1961 "WstPsnr\tWstSsim\tWstFast\tWstHVS");
1962 snprintf(results, sizeof(results),
1963 "%7.2f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
1964 "%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
1965 "%7.3f\t%7.3f\t%7.3f\t%7.3f",
1966 dr, cpi->psnr.stat[ALL] / cpi->count, total_psnr,
1967 cpi->psnrp.stat[ALL] / cpi->count, totalp_psnr, total_ssim,
1968 totalp_ssim, cpi->fastssim.stat[ALL] / cpi->count,
1969 cpi->psnrhvs.stat[ALL] / cpi->count, cpi->psnr.worst,
1970 cpi->worst_ssim, cpi->fastssim.worst, cpi->psnrhvs.worst);
1972 if (cpi->b_calculate_blockiness) {
1973 SNPRINT(headings, "\t Block\tWstBlck");
1974 SNPRINT2(results, "\t%7.3f", cpi->total_blockiness / cpi->count);
1975 SNPRINT2(results, "\t%7.3f", cpi->worst_blockiness);
1978 if (cpi->b_calculate_consistency) {
1979 double consistency =
1980 vpx_sse_to_psnr((double)cpi->totalp_samples, peak,
1981 (double)cpi->total_inconsistency);
1983 SNPRINT(headings, "\tConsist\tWstCons");
1984 SNPRINT2(results, "\t%7.3f", consistency);
1985 SNPRINT2(results, "\t%7.3f", cpi->worst_consistency);
1988 fprintf(f, "%s\t Time\tRcErr\tAbsErr\n", headings);
1989 fprintf(f, "%s\t%8.0f\t%7.2f\t%7.2f\n", results, total_encode_time,
1990 rate_err, fabs(rate_err));
2000 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
2001 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
2002 printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
2003 cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
2004 cpi->time_compress_data / 1000,
2005 (cpi->time_receive_data + cpi->time_compress_data) / 1000);
2010 #if CONFIG_VP9_TEMPORAL_DENOISING
2011 vp9_denoiser_free(&(cpi->denoiser));
2014 for (t = 0; t < cpi->num_workers; ++t) {
2015 VPxWorker *const worker = &cpi->workers[t];
2016 EncWorkerData *const thread_data = &cpi->tile_thr_data[t];
2018 // Deallocate allocated threads.
2019 vpx_get_worker_interface()->end(worker);
2021 // Deallocate allocated thread data.
2022 if (t < cpi->num_workers - 1) {
2023 vpx_free(thread_data->td->counts);
2024 vp9_free_pc_tree(thread_data->td);
2025 vpx_free(thread_data->td);
2028 vpx_free(cpi->tile_thr_data);
2029 vpx_free(cpi->workers);
2031 if (cpi->num_workers > 1) vp9_loop_filter_dealloc(&cpi->lf_row_sync);
2033 vp9_alt_ref_aq_destroy(cpi->alt_ref_aq);
2035 dealloc_compressor_data(cpi);
2037 for (i = 0; i < sizeof(cpi->mbgraph_stats) / sizeof(cpi->mbgraph_stats[0]);
2039 vpx_free(cpi->mbgraph_stats[i].mb_stats);
2042 #if CONFIG_FP_MB_STATS
2043 if (cpi->use_fp_mb_stats) {
2044 vpx_free(cpi->twopass.frame_mb_stats_buf);
2045 cpi->twopass.frame_mb_stats_buf = NULL;
2049 vp9_remove_common(cm);
2050 vp9_free_ref_frame_buffers(cm->buffer_pool);
2051 #if CONFIG_VP9_POSTPROC
2052 vp9_free_postproc_buffers(cm);
2056 #if CONFIG_VP9_TEMPORAL_DENOISING
2057 #ifdef OUTPUT_YUV_DENOISED
2058 fclose(yuv_denoised_file);
2061 #ifdef OUTPUT_YUV_SKINMAP
2062 fclose(yuv_skinmap_file);
2064 #ifdef OUTPUT_YUV_REC
2065 fclose(yuv_rec_file);
2082 static void generate_psnr_packet(VP9_COMP *cpi) {
2083 struct vpx_codec_cx_pkt pkt;
2086 #if CONFIG_VP9_HIGHBITDEPTH
2087 vpx_calc_highbd_psnr(cpi->raw_source_frame, cpi->common.frame_to_show, &psnr,
2088 cpi->td.mb.e_mbd.bd, cpi->oxcf.input_bit_depth);
2090 vpx_calc_psnr(cpi->raw_source_frame, cpi->common.frame_to_show, &psnr);
2093 for (i = 0; i < 4; ++i) {
2094 pkt.data.psnr.samples[i] = psnr.samples[i];
2095 pkt.data.psnr.sse[i] = psnr.sse[i];
2096 pkt.data.psnr.psnr[i] = psnr.psnr[i];
2098 pkt.kind = VPX_CODEC_PSNR_PKT;
2100 cpi->svc.layer_context[cpi->svc.spatial_layer_id *
2101 cpi->svc.number_temporal_layers]
2102 .psnr_pkt = pkt.data.psnr;
2104 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2107 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags) {
2108 if (ref_frame_flags > 7) return -1;
2110 cpi->ref_frame_flags = ref_frame_flags;
2114 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags) {
2115 cpi->ext_refresh_golden_frame = (ref_frame_flags & VP9_GOLD_FLAG) != 0;
2116 cpi->ext_refresh_alt_ref_frame = (ref_frame_flags & VP9_ALT_FLAG) != 0;
2117 cpi->ext_refresh_last_frame = (ref_frame_flags & VP9_LAST_FLAG) != 0;
2118 cpi->ext_refresh_frame_flags_pending = 1;
2121 static YV12_BUFFER_CONFIG *get_vp9_ref_frame_buffer(
2122 VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag) {
2123 MV_REFERENCE_FRAME ref_frame = NONE;
2124 if (ref_frame_flag == VP9_LAST_FLAG)
2125 ref_frame = LAST_FRAME;
2126 else if (ref_frame_flag == VP9_GOLD_FLAG)
2127 ref_frame = GOLDEN_FRAME;
2128 else if (ref_frame_flag == VP9_ALT_FLAG)
2129 ref_frame = ALTREF_FRAME;
2131 return ref_frame == NONE ? NULL : get_ref_frame_buffer(cpi, ref_frame);
2134 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
2135 YV12_BUFFER_CONFIG *sd) {
2136 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2138 vp8_yv12_copy_frame(cfg, sd);
2145 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
2146 YV12_BUFFER_CONFIG *sd) {
2147 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2149 vp8_yv12_copy_frame(sd, cfg);
2156 int vp9_update_entropy(VP9_COMP *cpi, int update) {
2157 cpi->ext_refresh_frame_context = update;
2158 cpi->ext_refresh_frame_context_pending = 1;
2162 #if defined(OUTPUT_YUV_DENOISED) || defined(OUTPUT_YUV_SKINMAP)
2163 // The denoiser buffer is allocated as a YUV 440 buffer. This function writes it
2164 // as YUV 420. We simply use the top-left pixels of the UV buffers, since we do
2165 // not denoise the UV channels at this time. If ever we implement UV channel
2166 // denoising we will have to modify this.
2167 void vp9_write_yuv_frame_420(YV12_BUFFER_CONFIG *s, FILE *f) {
2168 uint8_t *src = s->y_buffer;
2169 int h = s->y_height;
2172 fwrite(src, s->y_width, 1, f);
2180 fwrite(src, s->uv_width, 1, f);
2181 src += s->uv_stride;
2188 fwrite(src, s->uv_width, 1, f);
2189 src += s->uv_stride;
2194 #ifdef OUTPUT_YUV_REC
2195 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
2196 YV12_BUFFER_CONFIG *s = cm->frame_to_show;
2197 uint8_t *src = s->y_buffer;
2200 #if CONFIG_VP9_HIGHBITDEPTH
2201 if (s->flags & YV12_FLAG_HIGHBITDEPTH) {
2202 uint16_t *src16 = CONVERT_TO_SHORTPTR(s->y_buffer);
2205 fwrite(src16, s->y_width, 2, yuv_rec_file);
2206 src16 += s->y_stride;
2209 src16 = CONVERT_TO_SHORTPTR(s->u_buffer);
2213 fwrite(src16, s->uv_width, 2, yuv_rec_file);
2214 src16 += s->uv_stride;
2217 src16 = CONVERT_TO_SHORTPTR(s->v_buffer);
2221 fwrite(src16, s->uv_width, 2, yuv_rec_file);
2222 src16 += s->uv_stride;
2225 fflush(yuv_rec_file);
2228 #endif // CONFIG_VP9_HIGHBITDEPTH
2231 fwrite(src, s->y_width, 1, yuv_rec_file);
2239 fwrite(src, s->uv_width, 1, yuv_rec_file);
2240 src += s->uv_stride;
2247 fwrite(src, s->uv_width, 1, yuv_rec_file);
2248 src += s->uv_stride;
2251 fflush(yuv_rec_file);
2255 #if CONFIG_VP9_HIGHBITDEPTH
2256 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
2257 YV12_BUFFER_CONFIG *dst,
2260 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
2261 YV12_BUFFER_CONFIG *dst) {
2262 #endif // CONFIG_VP9_HIGHBITDEPTH
2263 // TODO(dkovalev): replace YV12_BUFFER_CONFIG with vpx_image_t
2265 const uint8_t *const srcs[3] = { src->y_buffer, src->u_buffer,
2267 const int src_strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
2268 const int src_widths[3] = { src->y_crop_width, src->uv_crop_width,
2269 src->uv_crop_width };
2270 const int src_heights[3] = { src->y_crop_height, src->uv_crop_height,
2271 src->uv_crop_height };
2272 uint8_t *const dsts[3] = { dst->y_buffer, dst->u_buffer, dst->v_buffer };
2273 const int dst_strides[3] = { dst->y_stride, dst->uv_stride, dst->uv_stride };
2274 const int dst_widths[3] = { dst->y_crop_width, dst->uv_crop_width,
2275 dst->uv_crop_width };
2276 const int dst_heights[3] = { dst->y_crop_height, dst->uv_crop_height,
2277 dst->uv_crop_height };
2279 for (i = 0; i < MAX_MB_PLANE; ++i) {
2280 #if CONFIG_VP9_HIGHBITDEPTH
2281 if (src->flags & YV12_FLAG_HIGHBITDEPTH) {
2282 vp9_highbd_resize_plane(srcs[i], src_heights[i], src_widths[i],
2283 src_strides[i], dsts[i], dst_heights[i],
2284 dst_widths[i], dst_strides[i], bd);
2286 vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
2287 dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
2290 vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
2291 dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
2292 #endif // CONFIG_VP9_HIGHBITDEPTH
2294 vpx_extend_frame_borders(dst);
2297 #if CONFIG_VP9_HIGHBITDEPTH
2298 static void scale_and_extend_frame(const YV12_BUFFER_CONFIG *src,
2299 YV12_BUFFER_CONFIG *dst, int bd) {
2300 const int src_w = src->y_crop_width;
2301 const int src_h = src->y_crop_height;
2302 const int dst_w = dst->y_crop_width;
2303 const int dst_h = dst->y_crop_height;
2304 const uint8_t *const srcs[3] = { src->y_buffer, src->u_buffer,
2306 const int src_strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
2307 uint8_t *const dsts[3] = { dst->y_buffer, dst->u_buffer, dst->v_buffer };
2308 const int dst_strides[3] = { dst->y_stride, dst->uv_stride, dst->uv_stride };
2309 const InterpKernel *const kernel = vp9_filter_kernels[EIGHTTAP];
2312 for (i = 0; i < MAX_MB_PLANE; ++i) {
2313 const int factor = (i == 0 || i == 3 ? 1 : 2);
2314 const int src_stride = src_strides[i];
2315 const int dst_stride = dst_strides[i];
2316 for (y = 0; y < dst_h; y += 16) {
2317 const int y_q4 = y * (16 / factor) * src_h / dst_h;
2318 for (x = 0; x < dst_w; x += 16) {
2319 const int x_q4 = x * (16 / factor) * src_w / dst_w;
2320 const uint8_t *src_ptr = srcs[i] +
2321 (y / factor) * src_h / dst_h * src_stride +
2322 (x / factor) * src_w / dst_w;
2323 uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
2325 if (src->flags & YV12_FLAG_HIGHBITDEPTH) {
2326 vpx_highbd_convolve8(src_ptr, src_stride, dst_ptr, dst_stride,
2327 kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2328 kernel[y_q4 & 0xf], 16 * src_h / dst_h,
2329 16 / factor, 16 / factor, bd);
2331 vpx_scaled_2d(src_ptr, src_stride, dst_ptr, dst_stride,
2332 kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2333 kernel[y_q4 & 0xf], 16 * src_h / dst_h, 16 / factor,
2340 vpx_extend_frame_borders(dst);
2343 void vp9_scale_and_extend_frame_c(const YV12_BUFFER_CONFIG *src,
2344 YV12_BUFFER_CONFIG *dst) {
2345 const int src_w = src->y_crop_width;
2346 const int src_h = src->y_crop_height;
2347 const int dst_w = dst->y_crop_width;
2348 const int dst_h = dst->y_crop_height;
2349 const uint8_t *const srcs[3] = { src->y_buffer, src->u_buffer,
2351 const int src_strides[3] = { src->y_stride, src->uv_stride, src->uv_stride };
2352 uint8_t *const dsts[3] = { dst->y_buffer, dst->u_buffer, dst->v_buffer };
2353 const int dst_strides[3] = { dst->y_stride, dst->uv_stride, dst->uv_stride };
2354 const InterpKernel *const kernel = vp9_filter_kernels[EIGHTTAP];
2357 for (i = 0; i < MAX_MB_PLANE; ++i) {
2358 const int factor = (i == 0 || i == 3 ? 1 : 2);
2359 const int src_stride = src_strides[i];
2360 const int dst_stride = dst_strides[i];
2361 for (y = 0; y < dst_h; y += 16) {
2362 const int y_q4 = y * (16 / factor) * src_h / dst_h;
2363 for (x = 0; x < dst_w; x += 16) {
2364 const int x_q4 = x * (16 / factor) * src_w / dst_w;
2365 const uint8_t *src_ptr = srcs[i] +
2366 (y / factor) * src_h / dst_h * src_stride +
2367 (x / factor) * src_w / dst_w;
2368 uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
2370 vpx_scaled_2d(src_ptr, src_stride, dst_ptr, dst_stride,
2371 kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2372 kernel[y_q4 & 0xf], 16 * src_h / dst_h, 16 / factor,
2378 vpx_extend_frame_borders(dst);
2380 #endif // CONFIG_VP9_HIGHBITDEPTH
2382 static int scale_down(VP9_COMP *cpi, int q) {
2383 RATE_CONTROL *const rc = &cpi->rc;
2384 GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2386 assert(frame_is_kf_gf_arf(cpi));
2388 if (rc->frame_size_selector == UNSCALED &&
2389 q >= rc->rf_level_maxq[gf_group->rf_level[gf_group->index]]) {
2390 const int max_size_thresh =
2391 (int)(rate_thresh_mult[SCALE_STEP1] *
2392 VPXMAX(rc->this_frame_target, rc->avg_frame_bandwidth));
2393 scale = rc->projected_frame_size > max_size_thresh ? 1 : 0;
2398 static int big_rate_miss(VP9_COMP *cpi, int high_limit, int low_limit) {
2399 const RATE_CONTROL *const rc = &cpi->rc;
2401 return (rc->projected_frame_size > ((high_limit * 3) / 2)) ||
2402 (rc->projected_frame_size < (low_limit / 2));
2405 // test in two pass for the first
2406 static int two_pass_first_group_inter(VP9_COMP *cpi) {
2407 TWO_PASS *const twopass = &cpi->twopass;
2408 GF_GROUP *const gf_group = &twopass->gf_group;
2409 if ((cpi->oxcf.pass == 2) &&
2410 (gf_group->index == gf_group->first_inter_index)) {
2417 // Function to test for conditions that indicate we should loop
2418 // back and recode a frame.
2419 static int recode_loop_test(VP9_COMP *cpi, int high_limit, int low_limit, int q,
2420 int maxq, int minq) {
2421 const RATE_CONTROL *const rc = &cpi->rc;
2422 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2423 const int frame_is_kfgfarf = frame_is_kf_gf_arf(cpi);
2424 int force_recode = 0;
2426 if ((rc->projected_frame_size >= rc->max_frame_bandwidth) ||
2427 big_rate_miss(cpi, high_limit, low_limit) ||
2428 (cpi->sf.recode_loop == ALLOW_RECODE) ||
2429 (two_pass_first_group_inter(cpi) &&
2430 (cpi->sf.recode_loop == ALLOW_RECODE_FIRST)) ||
2431 (frame_is_kfgfarf && (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF))) {
2432 if (frame_is_kfgfarf && (oxcf->resize_mode == RESIZE_DYNAMIC) &&
2433 scale_down(cpi, q)) {
2434 // Code this group at a lower resolution.
2435 cpi->resize_pending = 1;
2439 // TODO(agrange) high_limit could be greater than the scale-down threshold.
2440 if ((rc->projected_frame_size > high_limit && q < maxq) ||
2441 (rc->projected_frame_size < low_limit && q > minq)) {
2443 } else if (cpi->oxcf.rc_mode == VPX_CQ) {
2444 // Deal with frame undershoot and whether or not we are
2445 // below the automatically set cq level.
2446 if (q > oxcf->cq_level &&
2447 rc->projected_frame_size < ((rc->this_frame_target * 7) >> 3)) {
2452 return force_recode;
2455 void vp9_update_reference_frames(VP9_COMP *cpi) {
2456 VP9_COMMON *const cm = &cpi->common;
2457 BufferPool *const pool = cm->buffer_pool;
2459 // At this point the new frame has been encoded.
2460 // If any buffer copy / swapping is signaled it should be done here.
2461 if (cm->frame_type == KEY_FRAME) {
2462 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
2464 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->alt_fb_idx],
2466 } else if (vp9_preserve_existing_gf(cpi)) {
2467 // We have decided to preserve the previously existing golden frame as our
2468 // new ARF frame. However, in the short term in function
2469 // vp9_get_refresh_mask() we left it in the GF slot and, if
2470 // we're updating the GF with the current decoded frame, we save it to the
2471 // ARF slot instead.
2472 // We now have to update the ARF with the current frame and swap gld_fb_idx
2473 // and alt_fb_idx so that, overall, we've stored the old GF in the new ARF
2474 // slot and, if we're updating the GF, the current frame becomes the new GF.
2477 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->alt_fb_idx],
2480 tmp = cpi->alt_fb_idx;
2481 cpi->alt_fb_idx = cpi->gld_fb_idx;
2482 cpi->gld_fb_idx = tmp;
2484 if (is_two_pass_svc(cpi)) {
2485 cpi->svc.layer_context[0].gold_ref_idx = cpi->gld_fb_idx;
2486 cpi->svc.layer_context[0].alt_ref_idx = cpi->alt_fb_idx;
2488 } else { /* For non key/golden frames */
2489 if (cpi->refresh_alt_ref_frame) {
2490 int arf_idx = cpi->alt_fb_idx;
2491 if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
2492 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2493 arf_idx = gf_group->arf_update_idx[gf_group->index];
2496 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
2497 memcpy(cpi->interp_filter_selected[ALTREF_FRAME],
2498 cpi->interp_filter_selected[0],
2499 sizeof(cpi->interp_filter_selected[0]));
2502 if (cpi->refresh_golden_frame) {
2503 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
2505 if (!cpi->rc.is_src_frame_alt_ref)
2506 memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
2507 cpi->interp_filter_selected[0],
2508 sizeof(cpi->interp_filter_selected[0]));
2510 memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
2511 cpi->interp_filter_selected[ALTREF_FRAME],
2512 sizeof(cpi->interp_filter_selected[ALTREF_FRAME]));
2516 if (cpi->refresh_last_frame) {
2517 ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->lst_fb_idx],
2519 if (!cpi->rc.is_src_frame_alt_ref)
2520 memcpy(cpi->interp_filter_selected[LAST_FRAME],
2521 cpi->interp_filter_selected[0],
2522 sizeof(cpi->interp_filter_selected[0]));
2524 #if CONFIG_VP9_TEMPORAL_DENOISING
2525 if (cpi->oxcf.noise_sensitivity > 0 &&
2526 cpi->denoiser.denoising_level > kDenLowLow) {
2527 vp9_denoiser_update_frame_info(
2528 &cpi->denoiser, *cpi->Source, cpi->common.frame_type,
2529 cpi->refresh_alt_ref_frame, cpi->refresh_golden_frame,
2530 cpi->refresh_last_frame, cpi->resize_pending);
2533 if (is_one_pass_cbr_svc(cpi)) {
2534 // Keep track of frame index for each reference frame.
2535 SVC *const svc = &cpi->svc;
2536 if (cm->frame_type == KEY_FRAME) {
2537 svc->ref_frame_index[cpi->lst_fb_idx] = svc->current_superframe;
2538 svc->ref_frame_index[cpi->gld_fb_idx] = svc->current_superframe;
2539 svc->ref_frame_index[cpi->alt_fb_idx] = svc->current_superframe;
2541 if (cpi->refresh_last_frame)
2542 svc->ref_frame_index[cpi->lst_fb_idx] = svc->current_superframe;
2543 if (cpi->refresh_golden_frame)
2544 svc->ref_frame_index[cpi->gld_fb_idx] = svc->current_superframe;
2545 if (cpi->refresh_alt_ref_frame)
2546 svc->ref_frame_index[cpi->alt_fb_idx] = svc->current_superframe;
2551 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
2552 MACROBLOCKD *xd = &cpi->td.mb.e_mbd;
2553 struct loopfilter *lf = &cm->lf;
2556 lf->filter_level = 0;
2557 lf->last_filt_level = 0;
2559 struct vpx_usec_timer timer;
2561 vpx_clear_system_state();
2563 vpx_usec_timer_start(&timer);
2565 if (!cpi->rc.is_src_frame_alt_ref) {
2566 if ((cpi->common.frame_type == KEY_FRAME) &&
2567 (!cpi->rc.this_key_frame_forced)) {
2568 lf->last_filt_level = 0;
2570 vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.lpf_pick);
2571 lf->last_filt_level = lf->filter_level;
2573 lf->filter_level = 0;
2576 vpx_usec_timer_mark(&timer);
2577 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
2580 if (lf->filter_level > 0) {
2581 vp9_build_mask_frame(cm, lf->filter_level, 0);
2583 if (cpi->num_workers > 1)
2584 vp9_loop_filter_frame_mt(cm->frame_to_show, cm, xd->plane,
2585 lf->filter_level, 0, 0, cpi->workers,
2586 cpi->num_workers, &cpi->lf_row_sync);
2588 vp9_loop_filter_frame(cm->frame_to_show, cm, xd, lf->filter_level, 0, 0);
2591 vpx_extend_frame_inner_borders(cm->frame_to_show);
2594 static INLINE void alloc_frame_mvs(VP9_COMMON *const cm, int buffer_idx) {
2595 RefCntBuffer *const new_fb_ptr = &cm->buffer_pool->frame_bufs[buffer_idx];
2596 if (new_fb_ptr->mvs == NULL || new_fb_ptr->mi_rows < cm->mi_rows ||
2597 new_fb_ptr->mi_cols < cm->mi_cols) {
2598 vpx_free(new_fb_ptr->mvs);
2599 CHECK_MEM_ERROR(cm, new_fb_ptr->mvs,
2600 (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
2601 sizeof(*new_fb_ptr->mvs)));
2602 new_fb_ptr->mi_rows = cm->mi_rows;
2603 new_fb_ptr->mi_cols = cm->mi_cols;
2607 void vp9_scale_references(VP9_COMP *cpi) {
2608 VP9_COMMON *cm = &cpi->common;
2609 MV_REFERENCE_FRAME ref_frame;
2610 const VP9_REFFRAME ref_mask[3] = { VP9_LAST_FLAG, VP9_GOLD_FLAG,
2613 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2614 // Need to convert from VP9_REFFRAME to index into ref_mask (subtract 1).
2615 if (cpi->ref_frame_flags & ref_mask[ref_frame - 1]) {
2616 BufferPool *const pool = cm->buffer_pool;
2617 const YV12_BUFFER_CONFIG *const ref =
2618 get_ref_frame_buffer(cpi, ref_frame);
2621 cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2625 #if CONFIG_VP9_HIGHBITDEPTH
2626 if (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height) {
2627 RefCntBuffer *new_fb_ptr = NULL;
2628 int force_scaling = 0;
2629 int new_fb = cpi->scaled_ref_idx[ref_frame - 1];
2630 if (new_fb == INVALID_IDX) {
2631 new_fb = get_free_fb(cm);
2634 if (new_fb == INVALID_IDX) return;
2635 new_fb_ptr = &pool->frame_bufs[new_fb];
2636 if (force_scaling || new_fb_ptr->buf.y_crop_width != cm->width ||
2637 new_fb_ptr->buf.y_crop_height != cm->height) {
2638 if (vpx_realloc_frame_buffer(&new_fb_ptr->buf, cm->width, cm->height,
2639 cm->subsampling_x, cm->subsampling_y,
2640 cm->use_highbitdepth,
2641 VP9_ENC_BORDER_IN_PIXELS,
2642 cm->byte_alignment, NULL, NULL, NULL))
2643 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2644 "Failed to allocate frame buffer");
2645 scale_and_extend_frame(ref, &new_fb_ptr->buf, (int)cm->bit_depth);
2646 cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
2647 alloc_frame_mvs(cm, new_fb);
2650 if (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height) {
2651 RefCntBuffer *new_fb_ptr = NULL;
2652 int force_scaling = 0;
2653 int new_fb = cpi->scaled_ref_idx[ref_frame - 1];
2654 if (new_fb == INVALID_IDX) {
2655 new_fb = get_free_fb(cm);
2658 if (new_fb == INVALID_IDX) return;
2659 new_fb_ptr = &pool->frame_bufs[new_fb];
2660 if (force_scaling || new_fb_ptr->buf.y_crop_width != cm->width ||
2661 new_fb_ptr->buf.y_crop_height != cm->height) {
2662 if (vpx_realloc_frame_buffer(&new_fb_ptr->buf, cm->width, cm->height,
2663 cm->subsampling_x, cm->subsampling_y,
2664 VP9_ENC_BORDER_IN_PIXELS,
2665 cm->byte_alignment, NULL, NULL, NULL))
2666 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2667 "Failed to allocate frame buffer");
2668 vp9_scale_and_extend_frame(ref, &new_fb_ptr->buf);
2669 cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
2670 alloc_frame_mvs(cm, new_fb);
2672 #endif // CONFIG_VP9_HIGHBITDEPTH
2675 RefCntBuffer *buf = NULL;
2676 if (cpi->oxcf.pass == 0 && !cpi->use_svc) {
2677 // Check for release of scaled reference.
2678 buf_idx = cpi->scaled_ref_idx[ref_frame - 1];
2679 buf = (buf_idx != INVALID_IDX) ? &pool->frame_bufs[buf_idx] : NULL;
2682 cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2685 buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
2686 buf = &pool->frame_bufs[buf_idx];
2687 buf->buf.y_crop_width = ref->y_crop_width;
2688 buf->buf.y_crop_height = ref->y_crop_height;
2689 cpi->scaled_ref_idx[ref_frame - 1] = buf_idx;
2693 if (cpi->oxcf.pass != 0 || cpi->use_svc)
2694 cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2699 static void release_scaled_references(VP9_COMP *cpi) {
2700 VP9_COMMON *cm = &cpi->common;
2702 if (cpi->oxcf.pass == 0 && !cpi->use_svc) {
2703 // Only release scaled references under certain conditions:
2704 // if reference will be updated, or if scaled reference has same resolution.
2706 refresh[0] = (cpi->refresh_last_frame) ? 1 : 0;
2707 refresh[1] = (cpi->refresh_golden_frame) ? 1 : 0;
2708 refresh[2] = (cpi->refresh_alt_ref_frame) ? 1 : 0;
2709 for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
2710 const int idx = cpi->scaled_ref_idx[i - 1];
2711 RefCntBuffer *const buf =
2712 idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[idx] : NULL;
2713 const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi, i);
2715 (refresh[i - 1] || (buf->buf.y_crop_width == ref->y_crop_width &&
2716 buf->buf.y_crop_height == ref->y_crop_height))) {
2718 cpi->scaled_ref_idx[i - 1] = INVALID_IDX;
2722 for (i = 0; i < MAX_REF_FRAMES; ++i) {
2723 const int idx = cpi->scaled_ref_idx[i];
2724 RefCntBuffer *const buf =
2725 idx != INVALID_IDX ? &cm->buffer_pool->frame_bufs[idx] : NULL;
2728 cpi->scaled_ref_idx[i] = INVALID_IDX;
2734 static void full_to_model_count(unsigned int *model_count,
2735 unsigned int *full_count) {
2737 model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
2738 model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
2739 model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
2740 for (n = THREE_TOKEN; n < EOB_TOKEN; ++n)
2741 model_count[TWO_TOKEN] += full_count[n];
2742 model_count[EOB_MODEL_TOKEN] = full_count[EOB_TOKEN];
2745 static void full_to_model_counts(vp9_coeff_count_model *model_count,
2746 vp9_coeff_count *full_count) {
2749 for (i = 0; i < PLANE_TYPES; ++i)
2750 for (j = 0; j < REF_TYPES; ++j)
2751 for (k = 0; k < COEF_BANDS; ++k)
2752 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
2753 full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
2756 #if 0 && CONFIG_INTERNAL_STATS
2757 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
2758 VP9_COMMON *const cm = &cpi->common;
2759 FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
2762 vpx_clear_system_state();
2764 #if CONFIG_VP9_HIGHBITDEPTH
2765 if (cm->use_highbitdepth) {
2766 recon_err = vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2768 recon_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2771 recon_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2772 #endif // CONFIG_VP9_HIGHBITDEPTH
2775 if (cpi->twopass.total_left_stats.coded_error != 0.0) {
2776 double dc_quant_devisor;
2777 #if CONFIG_VP9_HIGHBITDEPTH
2778 switch (cm->bit_depth) {
2780 dc_quant_devisor = 4.0;
2783 dc_quant_devisor = 16.0;
2786 dc_quant_devisor = 64.0;
2789 assert(0 && "bit_depth must be VPX_BITS_8, VPX_BITS_10 or VPX_BITS_12");
2793 dc_quant_devisor = 4.0;
2796 fprintf(f, "%10u %dx%d %10d %10d %d %d %10d %10d %10d %10d"
2797 "%10"PRId64" %10"PRId64" %5d %5d %10"PRId64" "
2798 "%10"PRId64" %10"PRId64" %10d "
2799 "%7.2lf %7.2lf %7.2lf %7.2lf %7.2lf"
2800 "%6d %6d %5d %5d %5d "
2801 "%10"PRId64" %10.3lf"
2802 "%10lf %8u %10"PRId64" %10d %10d %10d %10d %10d\n",
2803 cpi->common.current_video_frame,
2804 cm->width, cm->height,
2805 cpi->td.rd_counts.m_search_count,
2806 cpi->td.rd_counts.ex_search_count,
2807 cpi->rc.source_alt_ref_pending,
2808 cpi->rc.source_alt_ref_active,
2809 cpi->rc.this_frame_target,
2810 cpi->rc.projected_frame_size,
2811 cpi->rc.projected_frame_size / cpi->common.MBs,
2812 (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
2813 cpi->rc.vbr_bits_off_target,
2814 cpi->rc.vbr_bits_off_target_fast,
2815 cpi->twopass.extend_minq,
2816 cpi->twopass.extend_minq_fast,
2817 cpi->rc.total_target_vs_actual,
2818 (cpi->rc.starting_buffer_level - cpi->rc.bits_off_target),
2819 cpi->rc.total_actual_bits, cm->base_qindex,
2820 vp9_convert_qindex_to_q(cm->base_qindex, cm->bit_depth),
2821 (double)vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) /
2823 vp9_convert_qindex_to_q(cpi->twopass.active_worst_quality,
2826 vp9_convert_qindex_to_q(cpi->oxcf.cq_level, cm->bit_depth),
2827 cpi->refresh_last_frame, cpi->refresh_golden_frame,
2828 cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
2829 cpi->twopass.bits_left,
2830 cpi->twopass.total_left_stats.coded_error,
2831 cpi->twopass.bits_left /
2832 (1 + cpi->twopass.total_left_stats.coded_error),
2833 cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
2834 cpi->twopass.kf_zeromotion_pct,
2835 cpi->twopass.fr_content_type,
2836 cm->lf.filter_level,
2837 cm->seg.aq_av_offset);
2842 FILE *const fmodes = fopen("Modes.stt", "a");
2845 fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
2846 cm->frame_type, cpi->refresh_golden_frame,
2847 cpi->refresh_alt_ref_frame);
2849 for (i = 0; i < MAX_MODES; ++i)
2850 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
2852 fprintf(fmodes, "\n");
2859 static void set_mv_search_params(VP9_COMP *cpi) {
2860 const VP9_COMMON *const cm = &cpi->common;
2861 const unsigned int max_mv_def = VPXMIN(cm->width, cm->height);
2863 // Default based on max resolution.
2864 cpi->mv_step_param = vp9_init_search_range(max_mv_def);
2866 if (cpi->sf.mv.auto_mv_step_size) {
2867 if (frame_is_intra_only(cm)) {
2868 // Initialize max_mv_magnitude for use in the first INTER frame
2869 // after a key/intra-only frame.
2870 cpi->max_mv_magnitude = max_mv_def;
2872 if (cm->show_frame) {
2873 // Allow mv_steps to correspond to twice the max mv magnitude found
2874 // in the previous frame, capped by the default max_mv_magnitude based
2876 cpi->mv_step_param = vp9_init_search_range(
2877 VPXMIN(max_mv_def, 2 * cpi->max_mv_magnitude));
2879 cpi->max_mv_magnitude = 0;
2884 static void set_size_independent_vars(VP9_COMP *cpi) {
2885 vp9_set_speed_features_framesize_independent(cpi);
2886 vp9_set_rd_speed_thresholds(cpi);
2887 vp9_set_rd_speed_thresholds_sub8x8(cpi);
2888 cpi->common.interp_filter = cpi->sf.default_interp_filter;
2891 static void set_size_dependent_vars(VP9_COMP *cpi, int *q, int *bottom_index,
2893 VP9_COMMON *const cm = &cpi->common;
2894 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2896 // Setup variables that depend on the dimensions of the frame.
2897 vp9_set_speed_features_framesize_dependent(cpi);
2899 // Decide q and q bounds.
2900 *q = vp9_rc_pick_q_and_bounds(cpi, bottom_index, top_index);
2902 if (!frame_is_intra_only(cm)) {
2903 vp9_set_high_precision_mv(cpi, (*q) < HIGH_PRECISION_MV_QTHRESH);
2906 // Configure experimental use of segmentation for enhanced coding of
2907 // static regions if indicated.
2908 // Only allowed in the second pass of a two pass encode, as it requires
2909 // lagged coding, and if the relevant speed feature flag is set.
2910 if (oxcf->pass == 2 && cpi->sf.static_segmentation)
2911 configure_static_seg_features(cpi);
2913 #if CONFIG_VP9_POSTPROC && !(CONFIG_VP9_TEMPORAL_DENOISING)
2914 if (oxcf->noise_sensitivity > 0) {
2916 switch (oxcf->noise_sensitivity) {
2917 case 1: l = 20; break;
2918 case 2: l = 40; break;
2919 case 3: l = 60; break;
2921 case 5: l = 100; break;
2922 case 6: l = 150; break;
2924 if (!cpi->common.postproc_state.limits) {
2925 cpi->common.postproc_state.limits = vpx_calloc(
2926 cpi->common.width, sizeof(*cpi->common.postproc_state.limits));
2928 vp9_denoise(cpi->Source, cpi->Source, l, cpi->common.postproc_state.limits);
2930 #endif // CONFIG_VP9_POSTPROC
2933 #if CONFIG_VP9_TEMPORAL_DENOISING
2934 static void setup_denoiser_buffer(VP9_COMP *cpi) {
2935 VP9_COMMON *const cm = &cpi->common;
2936 if (cpi->oxcf.noise_sensitivity > 0 &&
2937 !cpi->denoiser.frame_buffer_initialized) {
2938 if (vp9_denoiser_alloc(&cpi->denoiser, cm->width, cm->height,
2939 cm->subsampling_x, cm->subsampling_y,
2940 #if CONFIG_VP9_HIGHBITDEPTH
2941 cm->use_highbitdepth,
2943 VP9_ENC_BORDER_IN_PIXELS))
2944 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2945 "Failed to allocate denoiser");
2950 static void init_motion_estimation(VP9_COMP *cpi) {
2951 int y_stride = cpi->scaled_source.y_stride;
2953 if (cpi->sf.mv.search_method == NSTEP) {
2954 vp9_init3smotion_compensation(&cpi->ss_cfg, y_stride);
2955 } else if (cpi->sf.mv.search_method == DIAMOND) {
2956 vp9_init_dsmotion_compensation(&cpi->ss_cfg, y_stride);
2960 static void set_frame_size(VP9_COMP *cpi) {
2962 VP9_COMMON *const cm = &cpi->common;
2963 VP9EncoderConfig *const oxcf = &cpi->oxcf;
2964 MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
2966 if (oxcf->pass == 2 && oxcf->rc_mode == VPX_VBR &&
2967 ((oxcf->resize_mode == RESIZE_FIXED && cm->current_video_frame == 0) ||
2968 (oxcf->resize_mode == RESIZE_DYNAMIC && cpi->resize_pending))) {
2969 calculate_coded_size(cpi, &oxcf->scaled_frame_width,
2970 &oxcf->scaled_frame_height);
2972 // There has been a change in frame size.
2973 vp9_set_size_literal(cpi, oxcf->scaled_frame_width,
2974 oxcf->scaled_frame_height);
2977 if (oxcf->pass == 0 && oxcf->rc_mode == VPX_CBR && !cpi->use_svc &&
2978 oxcf->resize_mode == RESIZE_DYNAMIC && cpi->resize_pending != 0) {
2979 oxcf->scaled_frame_width =
2980 (oxcf->width * cpi->resize_scale_num) / cpi->resize_scale_den;
2981 oxcf->scaled_frame_height =
2982 (oxcf->height * cpi->resize_scale_num) / cpi->resize_scale_den;
2983 // There has been a change in frame size.
2984 vp9_set_size_literal(cpi, oxcf->scaled_frame_width,
2985 oxcf->scaled_frame_height);
2987 // TODO(agrange) Scale cpi->max_mv_magnitude if frame-size has changed.
2988 set_mv_search_params(cpi);
2990 vp9_noise_estimate_init(&cpi->noise_estimate, cm->width, cm->height);
2991 #if CONFIG_VP9_TEMPORAL_DENOISING
2992 // Reset the denoiser on the resized frame.
2993 if (cpi->oxcf.noise_sensitivity > 0) {
2994 vp9_denoiser_free(&(cpi->denoiser));
2995 setup_denoiser_buffer(cpi);
2996 // Dynamic resize is only triggered for non-SVC, so we can force
2997 // golden frame update here as temporary fix to denoiser.
2998 cpi->refresh_golden_frame = 1;
3003 if ((oxcf->pass == 2) &&
3004 (!cpi->use_svc || (is_two_pass_svc(cpi) &&
3005 cpi->svc.encode_empty_frame_state != ENCODING))) {
3006 vp9_set_target_rate(cpi);
3009 alloc_frame_mvs(cm, cm->new_fb_idx);
3011 // Reset the frame pointers to the current frame size.
3012 if (vpx_realloc_frame_buffer(get_frame_new_buffer(cm), cm->width, cm->height,
3013 cm->subsampling_x, cm->subsampling_y,
3014 #if CONFIG_VP9_HIGHBITDEPTH
3015 cm->use_highbitdepth,
3017 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
3019 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
3020 "Failed to allocate frame buffer");
3022 alloc_util_frame_buffers(cpi);
3023 init_motion_estimation(cpi);
3025 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3026 RefBuffer *const ref_buf = &cm->frame_refs[ref_frame - 1];
3027 const int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
3029 ref_buf->idx = buf_idx;
3031 if (buf_idx != INVALID_IDX) {
3032 YV12_BUFFER_CONFIG *const buf = &cm->buffer_pool->frame_bufs[buf_idx].buf;
3034 #if CONFIG_VP9_HIGHBITDEPTH
3035 vp9_setup_scale_factors_for_frame(
3036 &ref_buf->sf, buf->y_crop_width, buf->y_crop_height, cm->width,
3037 cm->height, (buf->flags & YV12_FLAG_HIGHBITDEPTH) ? 1 : 0);
3039 vp9_setup_scale_factors_for_frame(&ref_buf->sf, buf->y_crop_width,
3040 buf->y_crop_height, cm->width,
3042 #endif // CONFIG_VP9_HIGHBITDEPTH
3043 if (vp9_is_scaled(&ref_buf->sf)) vpx_extend_frame_borders(buf);
3045 ref_buf->buf = NULL;
3049 set_ref_ptrs(cm, xd, LAST_FRAME, LAST_FRAME);
3052 static void encode_without_recode_loop(VP9_COMP *cpi, size_t *size,
3054 VP9_COMMON *const cm = &cpi->common;
3055 int q = 0, bottom_index = 0, top_index = 0; // Dummy variables.
3057 vpx_clear_system_state();
3059 set_frame_size(cpi);
3061 if (is_one_pass_cbr_svc(cpi) &&
3062 cpi->un_scaled_source->y_width == cm->width << 2 &&
3063 cpi->un_scaled_source->y_height == cm->height << 2 &&
3064 cpi->svc.scaled_temp.y_width == cm->width << 1 &&
3065 cpi->svc.scaled_temp.y_height == cm->height << 1) {
3066 // For svc, if it is a 1/4x1/4 downscaling, do a two-stage scaling to take
3067 // advantage of the 1:2 optimized scaler. In the process, the 1/2x1/2
3068 // result will be saved in scaled_temp and might be used later.
3069 cpi->Source = vp9_svc_twostage_scale(
3070 cm, cpi->un_scaled_source, &cpi->scaled_source, &cpi->svc.scaled_temp);
3071 cpi->svc.scaled_one_half = 1;
3072 } else if (is_one_pass_cbr_svc(cpi) &&
3073 cpi->un_scaled_source->y_width == cm->width << 1 &&
3074 cpi->un_scaled_source->y_height == cm->height << 1 &&
3075 cpi->svc.scaled_one_half) {
3076 // If the spatial layer is 1/2x1/2 and the scaling is already done in the
3077 // two-stage scaling, use the result directly.
3078 cpi->Source = &cpi->svc.scaled_temp;
3079 cpi->svc.scaled_one_half = 0;
3081 cpi->Source = vp9_scale_if_required(
3082 cm, cpi->un_scaled_source, &cpi->scaled_source, (cpi->oxcf.pass == 0));
3084 // Unfiltered raw source used in metrics calculation if the source
3085 // has been filtered.
3086 if (is_psnr_calc_enabled(cpi)) {
3087 #ifdef ENABLE_KF_DENOISE
3088 if (is_spatial_denoise_enabled(cpi)) {
3089 cpi->raw_source_frame =
3090 vp9_scale_if_required(cm, &cpi->raw_unscaled_source,
3091 &cpi->raw_scaled_source, (cpi->oxcf.pass == 0));
3093 cpi->raw_source_frame = cpi->Source;
3096 cpi->raw_source_frame = cpi->Source;
3100 // Avoid scaling last_source unless its needed.
3101 // Last source is needed if vp9_avg_source_sad() is used, or if
3102 // partition_search_type == SOURCE_VAR_BASED_PARTITION, or if noise
3103 // estimation is enabled.
3104 if (cpi->unscaled_last_source != NULL &&
3105 (cpi->oxcf.content == VP9E_CONTENT_SCREEN ||
3106 (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_VBR &&
3107 cpi->oxcf.mode == REALTIME && cpi->oxcf.speed >= 5) ||
3108 cpi->sf.partition_search_type == SOURCE_VAR_BASED_PARTITION ||
3109 cpi->noise_estimate.enabled))
3111 vp9_scale_if_required(cm, cpi->unscaled_last_source,
3112 &cpi->scaled_last_source, (cpi->oxcf.pass == 0));
3114 if (cm->frame_type == KEY_FRAME || cpi->resize_pending != 0) {
3115 memset(cpi->consec_zero_mv, 0,
3116 cm->mi_rows * cm->mi_cols * sizeof(*cpi->consec_zero_mv));
3119 vp9_update_noise_estimate(cpi);
3121 if (cpi->oxcf.pass == 0 && cpi->oxcf.mode == REALTIME &&
3122 cpi->oxcf.speed >= 5 && cpi->resize_state == 0 &&
3123 (cpi->oxcf.content == VP9E_CONTENT_SCREEN ||
3124 cpi->oxcf.rc_mode == VPX_VBR))
3125 vp9_avg_source_sad(cpi);
3127 // For 1 pass SVC, since only ZEROMV is allowed for upsampled reference
3128 // frame (i.e, svc->force_zero_mode_spatial_ref = 0), we can avoid this
3129 // frame-level upsampling.
3130 if (frame_is_intra_only(cm) == 0 && !is_one_pass_cbr_svc(cpi)) {
3131 vp9_scale_references(cpi);
3134 set_size_independent_vars(cpi);
3135 set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
3137 if (cpi->oxcf.speed >= 5 && cpi->oxcf.pass == 0 &&
3138 cpi->oxcf.rc_mode == VPX_CBR &&
3139 cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
3140 cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3141 cpi->use_skin_detection = 1;
3144 vp9_set_quantizer(cm, q);
3145 vp9_set_variance_partition_thresholds(cpi, q);
3149 suppress_active_map(cpi);
3151 // Variance adaptive and in frame q adjustment experiments are mutually
3153 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3154 vp9_vaq_frame_setup(cpi);
3155 } else if (cpi->oxcf.aq_mode == EQUATOR360_AQ) {
3156 vp9_360aq_frame_setup(cpi);
3157 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
3158 vp9_setup_in_frame_q_adj(cpi);
3159 } else if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3160 vp9_cyclic_refresh_setup(cpi);
3161 } else if (cpi->oxcf.aq_mode == LOOKAHEAD_AQ) {
3162 // it may be pretty bad for rate-control,
3163 // and I should handle it somehow
3164 vp9_alt_ref_aq_setup_map(cpi->alt_ref_aq, cpi);
3167 apply_active_map(cpi);
3169 vp9_encode_frame(cpi);
3171 // Check if we should drop this frame because of high overshoot.
3172 // Only for frames where high temporal-source SAD is detected.
3173 if (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_CBR &&
3174 cpi->resize_state == 0 && cm->frame_type != KEY_FRAME &&
3175 cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
3176 cpi->rc.high_source_sad == 1) {
3178 // Get an estimate of the encoded frame size.
3179 save_coding_context(cpi);
3180 vp9_pack_bitstream(cpi, dest, size);
3181 restore_coding_context(cpi);
3182 frame_size = (int)(*size) << 3;
3183 // Check if encoded frame will overshoot too much, and if so, set the q and
3184 // adjust some rate control parameters, and return to re-encode the frame.
3185 if (vp9_encodedframe_overshoot(cpi, frame_size, &q)) {
3186 vpx_clear_system_state();
3187 vp9_set_quantizer(cm, q);
3188 vp9_set_variance_partition_thresholds(cpi, q);
3189 suppress_active_map(cpi);
3190 // Turn-off cyclic refresh for re-encoded frame.
3191 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3192 unsigned char *const seg_map = cpi->segmentation_map;
3193 memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
3194 vp9_disable_segmentation(&cm->seg);
3196 apply_active_map(cpi);
3197 vp9_encode_frame(cpi);
3201 // Update some stats from cyclic refresh, and check if we should not update
3202 // golden reference, for non-SVC 1 pass CBR.
3203 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->frame_type != KEY_FRAME &&
3204 !cpi->use_svc && cpi->ext_refresh_frame_flags_pending == 0 &&
3205 (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_CBR))
3206 vp9_cyclic_refresh_check_golden_update(cpi);
3208 // Update the skip mb flag probabilities based on the distribution
3209 // seen in the last encoder iteration.
3210 // update_base_skip_probs(cpi);
3211 vpx_clear_system_state();
3214 static void encode_with_recode_loop(VP9_COMP *cpi, size_t *size,
3216 VP9_COMMON *const cm = &cpi->common;
3217 RATE_CONTROL *const rc = &cpi->rc;
3218 int bottom_index, top_index;
3220 int loop_at_this_size = 0;
3222 int overshoot_seen = 0;
3223 int undershoot_seen = 0;
3224 int frame_over_shoot_limit;
3225 int frame_under_shoot_limit;
3226 int q = 0, q_low = 0, q_high = 0;
3228 set_size_independent_vars(cpi);
3231 vpx_clear_system_state();
3233 set_frame_size(cpi);
3235 if (loop_count == 0 || cpi->resize_pending != 0) {
3236 set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
3238 // TODO(agrange) Scale cpi->max_mv_magnitude if frame-size has changed.
3239 set_mv_search_params(cpi);
3241 // Reset the loop state for new frame size.
3243 undershoot_seen = 0;
3245 // Reconfiguration for change in frame size has concluded.
3246 cpi->resize_pending = 0;
3248 q_low = bottom_index;
3251 loop_at_this_size = 0;
3254 // Decide frame size bounds first time through.
3255 if (loop_count == 0) {
3256 vp9_rc_compute_frame_size_bounds(cpi, rc->this_frame_target,
3257 &frame_under_shoot_limit,
3258 &frame_over_shoot_limit);
3261 cpi->Source = vp9_scale_if_required(
3262 cm, cpi->un_scaled_source, &cpi->scaled_source, (cpi->oxcf.pass == 0));
3264 // Unfiltered raw source used in metrics calculation if the source
3265 // has been filtered.
3266 if (is_psnr_calc_enabled(cpi)) {
3267 #ifdef ENABLE_KF_DENOISE
3268 if (is_spatial_denoise_enabled(cpi)) {
3269 cpi->raw_source_frame = vp9_scale_if_required(
3270 cm, &cpi->raw_unscaled_source, &cpi->raw_scaled_source,
3271 (cpi->oxcf.pass == 0));
3273 cpi->raw_source_frame = cpi->Source;
3276 cpi->raw_source_frame = cpi->Source;
3280 if (cpi->unscaled_last_source != NULL)
3281 cpi->Last_Source = vp9_scale_if_required(cm, cpi->unscaled_last_source,
3282 &cpi->scaled_last_source,
3283 (cpi->oxcf.pass == 0));
3285 if (frame_is_intra_only(cm) == 0) {
3286 if (loop_count > 0) {
3287 release_scaled_references(cpi);
3289 vp9_scale_references(cpi);
3292 vp9_set_quantizer(cm, q);
3294 if (loop_count == 0) setup_frame(cpi);
3296 // Variance adaptive and in frame q adjustment experiments are mutually
3298 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3299 vp9_vaq_frame_setup(cpi);
3300 } else if (cpi->oxcf.aq_mode == EQUATOR360_AQ) {
3301 vp9_360aq_frame_setup(cpi);
3302 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
3303 vp9_setup_in_frame_q_adj(cpi);
3304 } else if (cpi->oxcf.aq_mode == LOOKAHEAD_AQ) {
3305 vp9_alt_ref_aq_setup_map(cpi->alt_ref_aq, cpi);
3308 vp9_encode_frame(cpi);
3310 // Update the skip mb flag probabilities based on the distribution
3311 // seen in the last encoder iteration.
3312 // update_base_skip_probs(cpi);
3314 vpx_clear_system_state();
3316 // Dummy pack of the bitstream using up to date stats to get an
3317 // accurate estimate of output frame size to determine if we need
3319 if (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF) {
3320 save_coding_context(cpi);
3321 if (!cpi->sf.use_nonrd_pick_mode) vp9_pack_bitstream(cpi, dest, size);
3323 rc->projected_frame_size = (int)(*size) << 3;
3324 restore_coding_context(cpi);
3326 if (frame_over_shoot_limit == 0) frame_over_shoot_limit = 1;
3329 if (cpi->oxcf.rc_mode == VPX_Q) {
3332 if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced &&
3333 (rc->projected_frame_size < rc->max_frame_bandwidth)) {
3337 int64_t high_err_target = cpi->ambient_err;
3338 int64_t low_err_target = cpi->ambient_err >> 1;
3340 #if CONFIG_VP9_HIGHBITDEPTH
3341 if (cm->use_highbitdepth) {
3342 kf_err = vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3344 kf_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3347 kf_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3348 #endif // CONFIG_VP9_HIGHBITDEPTH
3350 // Prevent possible divide by zero error below for perfect KF
3353 // The key frame is not good enough or we can afford
3354 // to make it better without undue risk of popping.
3355 if ((kf_err > high_err_target &&
3356 rc->projected_frame_size <= frame_over_shoot_limit) ||
3357 (kf_err > low_err_target &&
3358 rc->projected_frame_size <= frame_under_shoot_limit)) {
3360 q_high = q > q_low ? q - 1 : q_low;
3363 q = (int)((q * high_err_target) / kf_err);
3364 q = VPXMIN(q, (q_high + q_low) >> 1);
3365 } else if (kf_err < low_err_target &&
3366 rc->projected_frame_size >= frame_under_shoot_limit) {
3367 // The key frame is much better than the previous frame
3369 q_low = q < q_high ? q + 1 : q_high;
3372 q = (int)((q * low_err_target) / kf_err);
3373 q = VPXMIN(q, (q_high + q_low + 1) >> 1);
3376 // Clamp Q to upper and lower limits:
3377 q = clamp(q, q_low, q_high);
3380 } else if (recode_loop_test(cpi, frame_over_shoot_limit,
3381 frame_under_shoot_limit, q,
3382 VPXMAX(q_high, top_index), bottom_index)) {
3383 // Is the projected frame size out of range and are we allowed
3384 // to attempt to recode.
3388 if (cpi->resize_pending == 1) {
3389 // Change in frame size so go back around the recode loop.
3390 cpi->rc.frame_size_selector =
3391 SCALE_STEP1 - cpi->rc.frame_size_selector;
3392 cpi->rc.next_frame_size_selector = cpi->rc.frame_size_selector;
3394 #if CONFIG_INTERNAL_STATS
3395 ++cpi->tot_recode_hits;
3402 // Frame size out of permitted range:
3403 // Update correction factor & compute new Q to try...
3405 // Frame is too large
3406 if (rc->projected_frame_size > rc->this_frame_target) {
3407 // Special case if the projected size is > the max allowed.
3408 if (rc->projected_frame_size >= rc->max_frame_bandwidth)
3409 q_high = rc->worst_quality;
3411 // Raise Qlow as to at least the current value
3412 q_low = q < q_high ? q + 1 : q_high;
3414 if (undershoot_seen || loop_at_this_size > 1) {
3415 // Update rate_correction_factor unless
3416 vp9_rc_update_rate_correction_factors(cpi);
3418 q = (q_high + q_low + 1) / 2;
3420 // Update rate_correction_factor unless
3421 vp9_rc_update_rate_correction_factors(cpi);
3423 q = vp9_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
3424 VPXMAX(q_high, top_index));
3426 while (q < q_low && retries < 10) {
3427 vp9_rc_update_rate_correction_factors(cpi);
3428 q = vp9_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
3429 VPXMAX(q_high, top_index));
3436 // Frame is too small
3437 q_high = q > q_low ? q - 1 : q_low;
3439 if (overshoot_seen || loop_at_this_size > 1) {
3440 vp9_rc_update_rate_correction_factors(cpi);
3441 q = (q_high + q_low) / 2;
3443 vp9_rc_update_rate_correction_factors(cpi);
3444 q = vp9_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
3446 // Special case reset for qlow for constrained quality.
3447 // This should only trigger where there is very substantial
3448 // undershoot on a frame and the auto cq level is above
3449 // the user passsed in value.
3450 if (cpi->oxcf.rc_mode == VPX_CQ && q < q_low) {
3454 while (q > q_high && retries < 10) {
3455 vp9_rc_update_rate_correction_factors(cpi);
3456 q = vp9_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
3462 undershoot_seen = 1;
3465 // Clamp Q to upper and lower limits:
3466 q = clamp(q, q_low, q_high);
3468 loop = (q != last_q);
3474 // Special case for overlay frame.
3475 if (rc->is_src_frame_alt_ref &&
3476 rc->projected_frame_size < rc->max_frame_bandwidth)
3481 ++loop_at_this_size;
3483 #if CONFIG_INTERNAL_STATS
3484 ++cpi->tot_recode_hits;
3490 static int get_ref_frame_flags(const VP9_COMP *cpi) {
3491 const int *const map = cpi->common.ref_frame_map;
3492 const int gold_is_last = map[cpi->gld_fb_idx] == map[cpi->lst_fb_idx];
3493 const int alt_is_last = map[cpi->alt_fb_idx] == map[cpi->lst_fb_idx];
3494 const int gold_is_alt = map[cpi->gld_fb_idx] == map[cpi->alt_fb_idx];
3495 int flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
3497 if (gold_is_last) flags &= ~VP9_GOLD_FLAG;
3499 if (cpi->rc.frames_till_gf_update_due == INT_MAX &&
3500 (cpi->svc.number_temporal_layers == 1 &&
3501 cpi->svc.number_spatial_layers == 1))
3502 flags &= ~VP9_GOLD_FLAG;
3504 if (alt_is_last) flags &= ~VP9_ALT_FLAG;
3506 if (gold_is_alt) flags &= ~VP9_ALT_FLAG;
3511 static void set_ext_overrides(VP9_COMP *cpi) {
3512 // Overrides the defaults with the externally supplied values with
3513 // vp9_update_reference() and vp9_update_entropy() calls
3514 // Note: The overrides are valid only for the next frame passed
3515 // to encode_frame_to_data_rate() function
3516 if (cpi->ext_refresh_frame_context_pending) {
3517 cpi->common.refresh_frame_context = cpi->ext_refresh_frame_context;
3518 cpi->ext_refresh_frame_context_pending = 0;
3520 if (cpi->ext_refresh_frame_flags_pending) {
3521 cpi->refresh_last_frame = cpi->ext_refresh_last_frame;
3522 cpi->refresh_golden_frame = cpi->ext_refresh_golden_frame;
3523 cpi->refresh_alt_ref_frame = cpi->ext_refresh_alt_ref_frame;
3527 YV12_BUFFER_CONFIG *vp9_svc_twostage_scale(VP9_COMMON *cm,
3528 YV12_BUFFER_CONFIG *unscaled,
3529 YV12_BUFFER_CONFIG *scaled,
3530 YV12_BUFFER_CONFIG *scaled_temp) {
3531 if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
3532 cm->mi_rows * MI_SIZE != unscaled->y_height) {
3533 #if CONFIG_VP9_HIGHBITDEPTH
3534 scale_and_extend_frame(unscaled, scaled_temp, (int)cm->bit_depth);
3535 scale_and_extend_frame(scaled_temp, scaled, (int)cm->bit_depth);
3537 vp9_scale_and_extend_frame(unscaled, scaled_temp);
3538 vp9_scale_and_extend_frame(scaled_temp, scaled);
3539 #endif // CONFIG_VP9_HIGHBITDEPTH
3546 YV12_BUFFER_CONFIG *vp9_scale_if_required(VP9_COMMON *cm,
3547 YV12_BUFFER_CONFIG *unscaled,
3548 YV12_BUFFER_CONFIG *scaled,
3549 int use_normative_scaler) {
3550 if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
3551 cm->mi_rows * MI_SIZE != unscaled->y_height) {
3552 #if CONFIG_VP9_HIGHBITDEPTH
3553 if (use_normative_scaler && unscaled->y_width <= (scaled->y_width << 1) &&
3554 unscaled->y_height <= (scaled->y_height << 1))
3555 scale_and_extend_frame(unscaled, scaled, (int)cm->bit_depth);
3557 scale_and_extend_frame_nonnormative(unscaled, scaled, (int)cm->bit_depth);
3559 if (use_normative_scaler && unscaled->y_width <= (scaled->y_width << 1) &&
3560 unscaled->y_height <= (scaled->y_height << 1))
3561 vp9_scale_and_extend_frame(unscaled, scaled);
3563 scale_and_extend_frame_nonnormative(unscaled, scaled);
3564 #endif // CONFIG_VP9_HIGHBITDEPTH
3571 static void set_arf_sign_bias(VP9_COMP *cpi) {
3572 VP9_COMMON *const cm = &cpi->common;
3575 if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
3576 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
3577 arf_sign_bias = cpi->rc.source_alt_ref_active &&
3578 (!cpi->refresh_alt_ref_frame ||
3579 (gf_group->rf_level[gf_group->index] == GF_ARF_LOW));
3582 (cpi->rc.source_alt_ref_active && !cpi->refresh_alt_ref_frame);
3584 cm->ref_frame_sign_bias[ALTREF_FRAME] = arf_sign_bias;
3587 static int setup_interp_filter_search_mask(VP9_COMP *cpi) {
3588 INTERP_FILTER ifilter;
3589 int ref_total[MAX_REF_FRAMES] = { 0 };
3590 MV_REFERENCE_FRAME ref;
3592 if (cpi->common.last_frame_type == KEY_FRAME || cpi->refresh_alt_ref_frame)
3594 for (ref = LAST_FRAME; ref <= ALTREF_FRAME; ++ref)
3595 for (ifilter = EIGHTTAP; ifilter <= EIGHTTAP_SHARP; ++ifilter)
3596 ref_total[ref] += cpi->interp_filter_selected[ref][ifilter];
3598 for (ifilter = EIGHTTAP; ifilter <= EIGHTTAP_SHARP; ++ifilter) {
3599 if ((ref_total[LAST_FRAME] &&
3600 cpi->interp_filter_selected[LAST_FRAME][ifilter] == 0) &&
3601 (ref_total[GOLDEN_FRAME] == 0 ||
3602 cpi->interp_filter_selected[GOLDEN_FRAME][ifilter] * 50 <
3603 ref_total[GOLDEN_FRAME]) &&
3604 (ref_total[ALTREF_FRAME] == 0 ||
3605 cpi->interp_filter_selected[ALTREF_FRAME][ifilter] * 50 <
3606 ref_total[ALTREF_FRAME]))
3607 mask |= 1 << ifilter;
3612 #ifdef ENABLE_KF_DENOISE
3613 // Baseline Kernal weights for denoise
3614 static uint8_t dn_kernal_3[9] = { 1, 2, 1, 2, 4, 2, 1, 2, 1 };
3615 static uint8_t dn_kernal_5[25] = { 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 4,
3616 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1 };
3618 static INLINE void add_denoise_point(int centre_val, int data_val, int thresh,
3619 uint8_t point_weight, int *sum_val,
3621 if (abs(centre_val - data_val) <= thresh) {
3622 *sum_weight += point_weight;
3623 *sum_val += (int)data_val * (int)point_weight;
3627 static void spatial_denoise_point(uint8_t *src_ptr, const int stride,
3628 const int strength) {
3631 int thresh = strength;
3632 int kernal_size = 5;
3633 int half_k_size = 2;
3637 uint8_t *kernal_ptr;
3639 // Find the maximum deviation from the source point in the locale.
3640 tmp_ptr = src_ptr - (stride * (half_k_size + 1)) - (half_k_size + 1);
3641 for (i = 0; i < kernal_size + 2; ++i) {
3642 for (j = 0; j < kernal_size + 2; ++j) {
3643 max_diff = VPXMAX(max_diff, abs((int)*src_ptr - (int)tmp_ptr[j]));
3648 // Select the kernal size.
3649 if (max_diff > (strength + (strength >> 1))) {
3652 thresh = thresh >> 1;
3654 kernal_ptr = (kernal_size == 3) ? dn_kernal_3 : dn_kernal_5;
3657 tmp_ptr = src_ptr - (stride * half_k_size) - half_k_size;
3658 for (i = 0; i < kernal_size; ++i) {
3659 for (j = 0; j < kernal_size; ++j) {
3660 add_denoise_point((int)*src_ptr, (int)tmp_ptr[j], thresh, *kernal_ptr,
3661 &sum_val, &sum_weight);
3667 // Update the source value with the new filtered value
3668 *src_ptr = (uint8_t)((sum_val + (sum_weight >> 1)) / sum_weight);
3671 #if CONFIG_VP9_HIGHBITDEPTH
3672 static void highbd_spatial_denoise_point(uint16_t *src_ptr, const int stride,
3673 const int strength) {
3676 int thresh = strength;
3677 int kernal_size = 5;
3678 int half_k_size = 2;
3682 uint8_t *kernal_ptr;
3684 // Find the maximum deviation from the source point in the locale.
3685 tmp_ptr = src_ptr - (stride * (half_k_size + 1)) - (half_k_size + 1);
3686 for (i = 0; i < kernal_size + 2; ++i) {
3687 for (j = 0; j < kernal_size + 2; ++j) {
3688 max_diff = VPXMAX(max_diff, abs((int)src_ptr - (int)tmp_ptr[j]));
3693 // Select the kernal size.
3694 if (max_diff > (strength + (strength >> 1))) {
3697 thresh = thresh >> 1;
3699 kernal_ptr = (kernal_size == 3) ? dn_kernal_3 : dn_kernal_5;
3702 tmp_ptr = src_ptr - (stride * half_k_size) - half_k_size;
3703 for (i = 0; i < kernal_size; ++i) {
3704 for (j = 0; j < kernal_size; ++j) {
3705 add_denoise_point((int)*src_ptr, (int)tmp_ptr[j], thresh, *kernal_ptr,
3706 &sum_val, &sum_weight);
3712 // Update the source value with the new filtered value
3713 *src_ptr = (uint16_t)((sum_val + (sum_weight >> 1)) / sum_weight);
3715 #endif // CONFIG_VP9_HIGHBITDEPTH
3717 // Apply thresholded spatial noise supression to a given buffer.
3718 static void spatial_denoise_buffer(VP9_COMP *cpi, uint8_t *buffer,
3719 const int stride, const int width,
3720 const int height, const int strength) {
3721 VP9_COMMON *const cm = &cpi->common;
3722 uint8_t *src_ptr = buffer;
3726 for (row = 0; row < height; ++row) {
3727 for (col = 0; col < width; ++col) {
3728 #if CONFIG_VP9_HIGHBITDEPTH
3729 if (cm->use_highbitdepth)
3730 highbd_spatial_denoise_point(CONVERT_TO_SHORTPTR(&src_ptr[col]), stride,
3733 spatial_denoise_point(&src_ptr[col], stride, strength);
3735 spatial_denoise_point(&src_ptr[col], stride, strength);
3736 #endif // CONFIG_VP9_HIGHBITDEPTH
3742 // Apply thresholded spatial noise supression to source.
3743 static void spatial_denoise_frame(VP9_COMP *cpi) {
3744 YV12_BUFFER_CONFIG *src = cpi->Source;
3745 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3746 TWO_PASS *const twopass = &cpi->twopass;
3747 VP9_COMMON *const cm = &cpi->common;
3749 // Base the filter strength on the current active max Q.
3750 const int q = (int)(vp9_convert_qindex_to_q(twopass->active_worst_quality,
3753 VPXMAX(oxcf->arnr_strength >> 2, VPXMIN(oxcf->arnr_strength, (q >> 4)));
3755 // Denoise each of Y,U and V buffers.
3756 spatial_denoise_buffer(cpi, src->y_buffer, src->y_stride, src->y_width,
3757 src->y_height, strength);
3759 strength += (strength >> 1);
3760 spatial_denoise_buffer(cpi, src->u_buffer, src->uv_stride, src->uv_width,
3761 src->uv_height, strength << 1);
3763 spatial_denoise_buffer(cpi, src->v_buffer, src->uv_stride, src->uv_width,
3764 src->uv_height, strength << 1);
3766 #endif // ENABLE_KF_DENOISE
3768 static void vp9_try_disable_lookahead_aq(VP9_COMP *cpi, size_t *size,
3770 if (cpi->common.seg.enabled)
3771 if (ALT_REF_AQ_PROTECT_GAIN) {
3772 size_t nsize = *size;
3775 // TODO(yuryg): optimize this, as
3776 // we don't really need to repack
3778 save_coding_context(cpi);
3779 vp9_disable_segmentation(&cpi->common.seg);
3780 vp9_pack_bitstream(cpi, dest, &nsize);
3781 restore_coding_context(cpi);
3783 overhead = (int)*size - (int)nsize;
3785 if (vp9_alt_ref_aq_disable_if(cpi->alt_ref_aq, overhead, (int)*size))
3786 vp9_encode_frame(cpi);
3788 vp9_enable_segmentation(&cpi->common.seg);
3792 static void encode_frame_to_data_rate(VP9_COMP *cpi, size_t *size,
3794 unsigned int *frame_flags) {
3795 VP9_COMMON *const cm = &cpi->common;
3796 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3797 struct segmentation *const seg = &cm->seg;
3800 set_ext_overrides(cpi);
3801 vpx_clear_system_state();
3803 #ifdef ENABLE_KF_DENOISE
3804 // Spatial denoise of key frame.
3805 if (is_spatial_denoise_enabled(cpi)) spatial_denoise_frame(cpi);
3808 // Set the arf sign bias for this frame.
3809 set_arf_sign_bias(cpi);
3811 // Set default state for segment based loop filter update flags.
3812 cm->lf.mode_ref_delta_update = 0;
3814 if (cpi->oxcf.pass == 2 && cpi->sf.adaptive_interp_filter_search)
3815 cpi->sf.interp_filter_search_mask = setup_interp_filter_search_mask(cpi);
3817 // Set various flags etc to special state if it is a key frame.
3818 if (frame_is_intra_only(cm)) {
3819 // Reset the loop filter deltas and segmentation map.
3820 vp9_reset_segment_features(&cm->seg);
3822 // If segmentation is enabled force a map update for key frames.
3824 seg->update_map = 1;
3825 seg->update_data = 1;
3828 // The alternate reference frame cannot be active for a key frame.
3829 cpi->rc.source_alt_ref_active = 0;
3831 cm->error_resilient_mode = oxcf->error_resilient_mode;
3832 cm->frame_parallel_decoding_mode = oxcf->frame_parallel_decoding_mode;
3834 // By default, encoder assumes decoder can use prev_mi.
3835 if (cm->error_resilient_mode) {
3836 cm->frame_parallel_decoding_mode = 1;
3837 cm->reset_frame_context = 0;
3838 cm->refresh_frame_context = 0;
3839 } else if (cm->intra_only) {
3840 // Only reset the current context.
3841 cm->reset_frame_context = 2;
3844 if (is_two_pass_svc(cpi) && cm->error_resilient_mode == 0) {
3845 // Use context 0 for intra only empty frame, but the last frame context
3846 // for other empty frames.
3847 if (cpi->svc.encode_empty_frame_state == ENCODING) {
3848 if (cpi->svc.encode_intra_empty_frame != 0)
3849 cm->frame_context_idx = 0;
3851 cm->frame_context_idx = FRAME_CONTEXTS - 1;
3853 cm->frame_context_idx =
3854 cpi->svc.spatial_layer_id * cpi->svc.number_temporal_layers +
3855 cpi->svc.temporal_layer_id;
3858 cm->frame_parallel_decoding_mode = oxcf->frame_parallel_decoding_mode;
3860 // The probs will be updated based on the frame type of its previous
3861 // frame if frame_parallel_decoding_mode is 0. The type may vary for
3862 // the frame after a key frame in base layer since we may drop enhancement
3863 // layers. So set frame_parallel_decoding_mode to 1 in this case.
3864 if (cm->frame_parallel_decoding_mode == 0) {
3865 if (cpi->svc.number_temporal_layers == 1) {
3866 if (cpi->svc.spatial_layer_id == 0 &&
3867 cpi->svc.layer_context[0].last_frame_type == KEY_FRAME)
3868 cm->frame_parallel_decoding_mode = 1;
3869 } else if (cpi->svc.spatial_layer_id == 0) {
3870 // Find the 2nd frame in temporal base layer and 1st frame in temporal
3871 // enhancement layers from the key frame.
3873 for (i = 0; i < cpi->svc.number_temporal_layers; ++i) {
3874 if (cpi->svc.layer_context[0].frames_from_key_frame == 1 << i) {
3875 cm->frame_parallel_decoding_mode = 1;
3883 // For 1 pass CBR, check if we are dropping this frame.
3884 // For spatial layers, for now only check for frame-dropping on first spatial
3885 // layer, and if decision is to drop, we drop whole super-frame.
3886 if (oxcf->pass == 0 && oxcf->rc_mode == VPX_CBR &&
3887 cm->frame_type != KEY_FRAME) {
3888 if (vp9_rc_drop_frame(cpi) ||
3889 (is_one_pass_cbr_svc(cpi) && cpi->svc.rc_drop_superframe == 1)) {
3890 vp9_rc_postencode_update_drop_frame(cpi);
3891 ++cm->current_video_frame;
3892 cpi->ext_refresh_frame_flags_pending = 0;
3893 cpi->svc.rc_drop_superframe = 1;
3894 // TODO(marpan): Advancing the svc counters on dropped frames can break
3895 // the referencing scheme for the fixed svc patterns defined in
3896 // vp9_one_pass_cbr_svc_start_layer(). Look into fixing this issue, but
3897 // for now, don't advance the svc frame counters on dropped frame.
3898 // if (cpi->use_svc)
3899 // vp9_inc_frame_in_layer(cpi);
3904 vpx_clear_system_state();
3906 #if CONFIG_INTERNAL_STATS
3907 memset(cpi->mode_chosen_counts, 0,
3908 MAX_MODES * sizeof(*cpi->mode_chosen_counts));
3911 if (cpi->sf.recode_loop == DISALLOW_RECODE) {
3912 encode_without_recode_loop(cpi, size, dest);
3914 encode_with_recode_loop(cpi, size, dest);
3917 // Disable segmentation if it decrease rate/distortion ratio
3918 if (cpi->oxcf.aq_mode == LOOKAHEAD_AQ)
3919 vp9_try_disable_lookahead_aq(cpi, size, dest);
3921 #if CONFIG_VP9_TEMPORAL_DENOISING
3922 #ifdef OUTPUT_YUV_DENOISED
3923 if (oxcf->noise_sensitivity > 0) {
3924 vp9_write_yuv_frame_420(&cpi->denoiser.running_avg_y[INTRA_FRAME],
3929 #ifdef OUTPUT_YUV_SKINMAP
3930 if (cpi->common.current_video_frame > 1) {
3931 vp9_compute_skin_map(cpi, yuv_skinmap_file);
3935 // Special case code to reduce pulsing when key frames are forced at a
3936 // fixed interval. Note the reconstruction error if it is the frame before
3937 // the force key frame
3938 if (cpi->rc.next_key_frame_forced && cpi->rc.frames_to_key == 1) {
3939 #if CONFIG_VP9_HIGHBITDEPTH
3940 if (cm->use_highbitdepth) {
3942 vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3944 cpi->ambient_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3947 cpi->ambient_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3948 #endif // CONFIG_VP9_HIGHBITDEPTH
3951 // If the encoder forced a KEY_FRAME decision
3952 if (cm->frame_type == KEY_FRAME) cpi->refresh_last_frame = 1;
3954 cm->frame_to_show = get_frame_new_buffer(cm);
3955 cm->frame_to_show->color_space = cm->color_space;
3956 cm->frame_to_show->color_range = cm->color_range;
3957 cm->frame_to_show->render_width = cm->render_width;
3958 cm->frame_to_show->render_height = cm->render_height;
3960 // Pick the loop filter level for the frame.
3961 loopfilter_frame(cpi, cm);
3963 // build the bitstream
3964 vp9_pack_bitstream(cpi, dest, size);
3966 if (cm->seg.update_map) update_reference_segmentation_map(cpi);
3968 if (frame_is_intra_only(cm) == 0) {
3969 release_scaled_references(cpi);
3971 vp9_update_reference_frames(cpi);
3973 for (t = TX_4X4; t <= TX_32X32; t++)
3974 full_to_model_counts(cpi->td.counts->coef[t],
3975 cpi->td.rd_counts.coef_counts[t]);
3977 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode)
3978 vp9_adapt_coef_probs(cm);
3980 if (!frame_is_intra_only(cm)) {
3981 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
3982 vp9_adapt_mode_probs(cm);
3983 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
3987 cpi->ext_refresh_frame_flags_pending = 0;
3989 if (cpi->refresh_golden_frame == 1)
3990 cpi->frame_flags |= FRAMEFLAGS_GOLDEN;
3992 cpi->frame_flags &= ~FRAMEFLAGS_GOLDEN;
3994 if (cpi->refresh_alt_ref_frame == 1)
3995 cpi->frame_flags |= FRAMEFLAGS_ALTREF;
3997 cpi->frame_flags &= ~FRAMEFLAGS_ALTREF;
3999 cpi->ref_frame_flags = get_ref_frame_flags(cpi);
4001 cm->last_frame_type = cm->frame_type;
4003 if (!(is_two_pass_svc(cpi) && cpi->svc.encode_empty_frame_state == ENCODING))
4004 vp9_rc_postencode_update(cpi, *size);
4007 output_frame_level_debug_stats(cpi);
4010 if (cm->frame_type == KEY_FRAME) {
4011 // Tell the caller that the frame was coded as a key frame
4012 *frame_flags = cpi->frame_flags | FRAMEFLAGS_KEY;
4014 *frame_flags = cpi->frame_flags & ~FRAMEFLAGS_KEY;
4017 // Clear the one shot update flags for segmentation map and mode/ref loop
4019 cm->seg.update_map = 0;
4020 cm->seg.update_data = 0;
4021 cm->lf.mode_ref_delta_update = 0;
4023 // keep track of the last coded dimensions
4024 cm->last_width = cm->width;
4025 cm->last_height = cm->height;
4027 // reset to normal state now that we are done.
4028 if (!cm->show_existing_frame) cm->last_show_frame = cm->show_frame;
4030 if (cm->show_frame) {
4031 vp9_swap_mi_and_prev_mi(cm);
4032 // Don't increment frame counters if this was an altref buffer
4033 // update not a real frame
4034 ++cm->current_video_frame;
4035 if (cpi->use_svc) vp9_inc_frame_in_layer(cpi);
4037 cm->prev_frame = cm->cur_frame;
4040 cpi->svc.layer_context[cpi->svc.spatial_layer_id *
4041 cpi->svc.number_temporal_layers +
4042 cpi->svc.temporal_layer_id]
4043 .last_frame_type = cm->frame_type;
4045 cpi->force_update_segmentation = 0;
4047 if (cpi->oxcf.aq_mode == LOOKAHEAD_AQ)
4048 vp9_alt_ref_aq_unset_all(cpi->alt_ref_aq, cpi);
4051 static void SvcEncode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
4052 unsigned int *frame_flags) {
4053 vp9_rc_get_svc_params(cpi);
4054 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4057 static void Pass0Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
4058 unsigned int *frame_flags) {
4059 if (cpi->oxcf.rc_mode == VPX_CBR) {
4060 vp9_rc_get_one_pass_cbr_params(cpi);
4062 vp9_rc_get_one_pass_vbr_params(cpi);
4064 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4067 static void Pass2Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
4068 unsigned int *frame_flags) {
4069 cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
4070 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4072 if (!(is_two_pass_svc(cpi) && cpi->svc.encode_empty_frame_state == ENCODING))
4073 vp9_twopass_postencode_update(cpi);
4076 static void init_ref_frame_bufs(VP9_COMMON *cm) {
4078 BufferPool *const pool = cm->buffer_pool;
4079 cm->new_fb_idx = INVALID_IDX;
4080 for (i = 0; i < REF_FRAMES; ++i) {
4081 cm->ref_frame_map[i] = INVALID_IDX;
4082 pool->frame_bufs[i].ref_count = 0;
4086 static void check_initial_width(VP9_COMP *cpi,
4087 #if CONFIG_VP9_HIGHBITDEPTH
4088 int use_highbitdepth,
4090 int subsampling_x, int subsampling_y) {
4091 VP9_COMMON *const cm = &cpi->common;
4093 if (!cpi->initial_width ||
4094 #if CONFIG_VP9_HIGHBITDEPTH
4095 cm->use_highbitdepth != use_highbitdepth ||
4097 cm->subsampling_x != subsampling_x ||
4098 cm->subsampling_y != subsampling_y) {
4099 cm->subsampling_x = subsampling_x;
4100 cm->subsampling_y = subsampling_y;
4101 #if CONFIG_VP9_HIGHBITDEPTH
4102 cm->use_highbitdepth = use_highbitdepth;
4105 alloc_raw_frame_buffers(cpi);
4106 init_ref_frame_bufs(cm);
4107 alloc_util_frame_buffers(cpi);
4109 init_motion_estimation(cpi); // TODO(agrange) This can be removed.
4111 cpi->initial_width = cm->width;
4112 cpi->initial_height = cm->height;
4113 cpi->initial_mbs = cm->MBs;
4117 int vp9_receive_raw_frame(VP9_COMP *cpi, vpx_enc_frame_flags_t frame_flags,
4118 YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
4120 VP9_COMMON *const cm = &cpi->common;
4121 struct vpx_usec_timer timer;
4123 const int subsampling_x = sd->subsampling_x;
4124 const int subsampling_y = sd->subsampling_y;
4125 #if CONFIG_VP9_HIGHBITDEPTH
4126 const int use_highbitdepth = (sd->flags & YV12_FLAG_HIGHBITDEPTH) != 0;
4129 #if CONFIG_VP9_HIGHBITDEPTH
4130 check_initial_width(cpi, use_highbitdepth, subsampling_x, subsampling_y);
4132 check_initial_width(cpi, subsampling_x, subsampling_y);
4133 #endif // CONFIG_VP9_HIGHBITDEPTH
4135 #if CONFIG_VP9_TEMPORAL_DENOISING
4136 setup_denoiser_buffer(cpi);
4138 vpx_usec_timer_start(&timer);
4140 if (vp9_lookahead_push(cpi->lookahead, sd, time_stamp, end_time,
4141 #if CONFIG_VP9_HIGHBITDEPTH
4143 #endif // CONFIG_VP9_HIGHBITDEPTH
4146 vpx_usec_timer_mark(&timer);
4147 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
4149 if ((cm->profile == PROFILE_0 || cm->profile == PROFILE_2) &&
4150 (subsampling_x != 1 || subsampling_y != 1)) {
4151 vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
4152 "Non-4:2:0 color format requires profile 1 or 3");
4155 if ((cm->profile == PROFILE_1 || cm->profile == PROFILE_3) &&
4156 (subsampling_x == 1 && subsampling_y == 1)) {
4157 vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
4158 "4:2:0 color format requires profile 0 or 2");
4165 static int frame_is_reference(const VP9_COMP *cpi) {
4166 const VP9_COMMON *cm = &cpi->common;
4168 return cm->frame_type == KEY_FRAME || cpi->refresh_last_frame ||
4169 cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame ||
4170 cm->refresh_frame_context || cm->lf.mode_ref_delta_update ||
4171 cm->seg.update_map || cm->seg.update_data;
4174 static void adjust_frame_rate(VP9_COMP *cpi,
4175 const struct lookahead_entry *source) {
4176 int64_t this_duration;
4179 if (source->ts_start == cpi->first_time_stamp_ever) {
4180 this_duration = source->ts_end - source->ts_start;
4183 int64_t last_duration =
4184 cpi->last_end_time_stamp_seen - cpi->last_time_stamp_seen;
4186 this_duration = source->ts_end - cpi->last_end_time_stamp_seen;
4188 // do a step update if the duration changes by 10%
4190 step = (int)((this_duration - last_duration) * 10 / last_duration);
4193 if (this_duration) {
4195 vp9_new_framerate(cpi, 10000000.0 / this_duration);
4197 // Average this frame's rate into the last second's average
4198 // frame rate. If we haven't seen 1 second yet, then average
4199 // over the whole interval seen.
4200 const double interval = VPXMIN(
4201 (double)(source->ts_end - cpi->first_time_stamp_ever), 10000000.0);
4202 double avg_duration = 10000000.0 / cpi->framerate;
4203 avg_duration *= (interval - avg_duration + this_duration);
4204 avg_duration /= interval;
4206 vp9_new_framerate(cpi, 10000000.0 / avg_duration);
4209 cpi->last_time_stamp_seen = source->ts_start;
4210 cpi->last_end_time_stamp_seen = source->ts_end;
4213 // Returns 0 if this is not an alt ref else the offset of the source frame
4214 // used as the arf midpoint.
4215 static int get_arf_src_index(VP9_COMP *cpi) {
4216 RATE_CONTROL *const rc = &cpi->rc;
4217 int arf_src_index = 0;
4218 if (is_altref_enabled(cpi)) {
4219 if (cpi->oxcf.pass == 2) {
4220 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4221 if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
4222 arf_src_index = gf_group->arf_src_offset[gf_group->index];
4224 } else if (rc->source_alt_ref_pending) {
4225 arf_src_index = rc->frames_till_gf_update_due;
4228 return arf_src_index;
4231 static void check_src_altref(VP9_COMP *cpi,
4232 const struct lookahead_entry *source) {
4233 RATE_CONTROL *const rc = &cpi->rc;
4235 if (cpi->oxcf.pass == 2) {
4236 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4237 rc->is_src_frame_alt_ref =
4238 (gf_group->update_type[gf_group->index] == OVERLAY_UPDATE);
4240 rc->is_src_frame_alt_ref =
4241 cpi->alt_ref_source && (source == cpi->alt_ref_source);
4244 if (rc->is_src_frame_alt_ref) {
4245 // Current frame is an ARF overlay frame.
4246 cpi->alt_ref_source = NULL;
4248 // Don't refresh the last buffer for an ARF overlay frame. It will
4249 // become the GF so preserve last as an alternative prediction option.
4250 cpi->refresh_last_frame = 0;
4254 #if CONFIG_INTERNAL_STATS
4255 extern double vp9_get_blockiness(const uint8_t *img1, int img1_pitch,
4256 const uint8_t *img2, int img2_pitch, int width,
4259 static void adjust_image_stat(double y, double u, double v, double all,
4264 s->stat[ALL] += all;
4265 s->worst = VPXMIN(s->worst, all);
4267 #endif // CONFIG_INTERNAL_STATS
4269 static void update_level_info(VP9_COMP *cpi, size_t *size, int arf_src_index) {
4270 VP9_COMMON *const cm = &cpi->common;
4271 Vp9LevelInfo *const level_info = &cpi->level_info;
4272 Vp9LevelSpec *const level_spec = &level_info->level_spec;
4273 Vp9LevelStats *const level_stats = &level_info->level_stats;
4275 uint64_t luma_samples, dur_end;
4276 const uint32_t luma_pic_size = cm->width * cm->height;
4277 double cpb_data_size;
4279 vpx_clear_system_state();
4281 // update level_stats
4282 level_stats->total_compressed_size += *size;
4283 if (cm->show_frame) {
4284 level_stats->total_uncompressed_size +=
4286 2 * (luma_pic_size >> (cm->subsampling_x + cm->subsampling_y));
4287 level_stats->time_encoded =
4288 (cpi->last_end_time_stamp_seen - cpi->first_time_stamp_ever) /
4289 (double)TICKS_PER_SEC;
4292 if (arf_src_index > 0) {
4293 if (!level_stats->seen_first_altref) {
4294 level_stats->seen_first_altref = 1;
4295 } else if (level_stats->frames_since_last_altref <
4296 level_spec->min_altref_distance) {
4297 level_spec->min_altref_distance = level_stats->frames_since_last_altref;
4299 level_stats->frames_since_last_altref = 0;
4301 ++level_stats->frames_since_last_altref;
4304 if (level_stats->frame_window_buffer.len < FRAME_WINDOW_SIZE - 1) {
4305 idx = (level_stats->frame_window_buffer.start +
4306 level_stats->frame_window_buffer.len++) %
4309 idx = level_stats->frame_window_buffer.start;
4310 level_stats->frame_window_buffer.start = (idx + 1) % FRAME_WINDOW_SIZE;
4312 level_stats->frame_window_buffer.buf[idx].ts = cpi->last_time_stamp_seen;
4313 level_stats->frame_window_buffer.buf[idx].size = (uint32_t)(*size);
4314 level_stats->frame_window_buffer.buf[idx].luma_samples = luma_pic_size;
4316 if (cm->frame_type == KEY_FRAME) {
4317 level_stats->ref_refresh_map = 0;
4320 level_stats->ref_refresh_map |= vp9_get_refresh_mask(cpi);
4321 // Also need to consider the case where the encoder refers to a buffer
4322 // that has been implicitly refreshed after encoding a keyframe.
4323 if (!cm->intra_only) {
4324 level_stats->ref_refresh_map |= (1 << cpi->lst_fb_idx);
4325 level_stats->ref_refresh_map |= (1 << cpi->gld_fb_idx);
4326 level_stats->ref_refresh_map |= (1 << cpi->alt_fb_idx);
4328 for (i = 0; i < REF_FRAMES; ++i) {
4329 count += (level_stats->ref_refresh_map >> i) & 1;
4331 if (count > level_spec->max_ref_frame_buffers) {
4332 level_spec->max_ref_frame_buffers = count;
4336 // update average_bitrate
4337 level_spec->average_bitrate = (double)level_stats->total_compressed_size /
4338 125.0 / level_stats->time_encoded;
4340 // update max_luma_sample_rate
4342 for (i = 0; i < level_stats->frame_window_buffer.len; ++i) {
4343 idx = (level_stats->frame_window_buffer.start +
4344 level_stats->frame_window_buffer.len - 1 - i) %
4347 dur_end = level_stats->frame_window_buffer.buf[idx].ts;
4349 if (dur_end - level_stats->frame_window_buffer.buf[idx].ts >=
4353 luma_samples += level_stats->frame_window_buffer.buf[idx].luma_samples;
4355 if (luma_samples > level_spec->max_luma_sample_rate) {
4356 level_spec->max_luma_sample_rate = luma_samples;
4359 // update max_cpb_size
4361 for (i = 0; i < CPB_WINDOW_SIZE; ++i) {
4362 if (i >= level_stats->frame_window_buffer.len) break;
4363 idx = (level_stats->frame_window_buffer.start +
4364 level_stats->frame_window_buffer.len - 1 - i) %
4366 cpb_data_size += level_stats->frame_window_buffer.buf[idx].size;
4368 cpb_data_size = cpb_data_size / 125.0;
4369 if (cpb_data_size > level_spec->max_cpb_size) {
4370 level_spec->max_cpb_size = cpb_data_size;
4373 // update max_luma_picture_size
4374 if (luma_pic_size > level_spec->max_luma_picture_size) {
4375 level_spec->max_luma_picture_size = luma_pic_size;
4378 // update compression_ratio
4379 level_spec->compression_ratio = (double)level_stats->total_uncompressed_size *
4381 level_stats->total_compressed_size / 8.0;
4383 // update max_col_tiles
4384 if (level_spec->max_col_tiles < (1 << cm->log2_tile_cols)) {
4385 level_spec->max_col_tiles = (1 << cm->log2_tile_cols);
4389 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
4390 size_t *size, uint8_t *dest, int64_t *time_stamp,
4391 int64_t *time_end, int flush) {
4392 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
4393 VP9_COMMON *const cm = &cpi->common;
4394 BufferPool *const pool = cm->buffer_pool;
4395 RATE_CONTROL *const rc = &cpi->rc;
4396 struct vpx_usec_timer cmptimer;
4397 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
4398 struct lookahead_entry *last_source = NULL;
4399 struct lookahead_entry *source = NULL;
4403 if (is_two_pass_svc(cpi)) {
4404 #if CONFIG_SPATIAL_SVC
4405 vp9_svc_start_frame(cpi);
4406 // Use a small empty frame instead of a real frame
4407 if (cpi->svc.encode_empty_frame_state == ENCODING)
4408 source = &cpi->svc.empty_frame;
4410 if (oxcf->pass == 2) vp9_restore_layer_context(cpi);
4411 } else if (is_one_pass_cbr_svc(cpi)) {
4412 vp9_one_pass_cbr_svc_start_layer(cpi);
4415 vpx_usec_timer_start(&cmptimer);
4417 vp9_set_high_precision_mv(cpi, ALTREF_HIGH_PRECISION_MV);
4419 // Is multi-arf enabled.
4420 // Note that at the moment multi_arf is only configured for 2 pass VBR and
4421 // will not work properly with svc.
4422 if ((oxcf->pass == 2) && !cpi->use_svc && (cpi->oxcf.enable_auto_arf > 1))
4423 cpi->multi_arf_allowed = 1;
4425 cpi->multi_arf_allowed = 0;
4428 cm->reset_frame_context = 0;
4429 cm->refresh_frame_context = 1;
4430 if (!is_one_pass_cbr_svc(cpi)) {
4431 cpi->refresh_last_frame = 1;
4432 cpi->refresh_golden_frame = 0;
4433 cpi->refresh_alt_ref_frame = 0;
4436 // Should we encode an arf frame.
4437 arf_src_index = get_arf_src_index(cpi);
4439 // Skip alt frame if we encode the empty frame
4440 if (is_two_pass_svc(cpi) && source != NULL) arf_src_index = 0;
4442 if (arf_src_index) {
4443 for (i = 0; i <= arf_src_index; ++i) {
4444 struct lookahead_entry *e = vp9_lookahead_peek(cpi->lookahead, i);
4445 // Avoid creating an alt-ref if there's a forced keyframe pending.
4448 } else if (e->flags == VPX_EFLAG_FORCE_KF) {
4456 if (arf_src_index) {
4457 assert(arf_src_index <= rc->frames_to_key);
4459 if ((source = vp9_lookahead_peek(cpi->lookahead, arf_src_index)) != NULL) {
4460 cpi->alt_ref_source = source;
4462 #if CONFIG_SPATIAL_SVC
4463 if (is_two_pass_svc(cpi) && cpi->svc.spatial_layer_id > 0) {
4465 // Reference a hidden frame from a lower layer
4466 for (i = cpi->svc.spatial_layer_id - 1; i >= 0; --i) {
4467 if (oxcf->ss_enable_auto_arf[i]) {
4468 cpi->gld_fb_idx = cpi->svc.layer_context[i].alt_ref_idx;
4473 cpi->svc.layer_context[cpi->svc.spatial_layer_id].has_alt_frame = 1;
4476 if ((oxcf->arnr_max_frames > 0) && (oxcf->arnr_strength > 0)) {
4477 int bitrate = cpi->rc.avg_frame_bandwidth / 40;
4478 int not_low_bitrate = bitrate > ALT_REF_AQ_LOW_BITRATE_BOUNDARY;
4480 int not_last_frame = (cpi->lookahead->sz - arf_src_index > 1);
4481 not_last_frame |= ALT_REF_AQ_APPLY_TO_LAST_FRAME;
4483 // Produce the filtered ARF frame.
4484 vp9_temporal_filter(cpi, arf_src_index);
4485 vpx_extend_frame_borders(&cpi->alt_ref_buffer);
4487 // for small bitrates segmentation overhead usually
4488 // eats all bitrate gain from enabling delta quantizers
4489 if (cpi->oxcf.alt_ref_aq != 0 && not_low_bitrate && not_last_frame)
4490 vp9_alt_ref_aq_setup_mode(cpi->alt_ref_aq, cpi);
4492 force_src_buffer = &cpi->alt_ref_buffer;
4497 cpi->refresh_alt_ref_frame = 1;
4498 cpi->refresh_golden_frame = 0;
4499 cpi->refresh_last_frame = 0;
4500 rc->is_src_frame_alt_ref = 0;
4501 rc->source_alt_ref_pending = 0;
4503 rc->source_alt_ref_pending = 0;
4508 // Get last frame source.
4509 if (cm->current_video_frame > 0) {
4510 if ((last_source = vp9_lookahead_peek(cpi->lookahead, -1)) == NULL)
4514 // Read in the source frame.
4516 source = vp9_svc_lookahead_pop(cpi, cpi->lookahead, flush);
4518 source = vp9_lookahead_pop(cpi->lookahead, flush);
4520 if (source != NULL) {
4523 // if the flags indicate intra frame, but if the current picture is for
4524 // non-zero spatial layer, it should not be an intra picture.
4525 // TODO(Won Kap): this needs to change if per-layer intra frame is
4527 if ((source->flags & VPX_EFLAG_FORCE_KF) &&
4528 cpi->svc.spatial_layer_id > cpi->svc.first_spatial_layer_to_encode) {
4529 source->flags &= ~(unsigned int)(VPX_EFLAG_FORCE_KF);
4532 // Check to see if the frame should be encoded as an arf overlay.
4533 check_src_altref(cpi, source);
4538 cpi->un_scaled_source = cpi->Source =
4539 force_src_buffer ? force_src_buffer : &source->img;
4541 #ifdef ENABLE_KF_DENOISE
4542 // Copy of raw source for metrics calculation.
4543 if (is_psnr_calc_enabled(cpi))
4544 vp9_copy_and_extend_frame(cpi->Source, &cpi->raw_unscaled_source);
4547 cpi->unscaled_last_source = last_source != NULL ? &last_source->img : NULL;
4549 *time_stamp = source->ts_start;
4550 *time_end = source->ts_end;
4551 *frame_flags = (source->flags & VPX_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
4555 if (flush && oxcf->pass == 1 && !cpi->twopass.first_pass_done) {
4556 vp9_end_first_pass(cpi); /* get last stats packet */
4557 cpi->twopass.first_pass_done = 1;
4562 if (source->ts_start < cpi->first_time_stamp_ever) {
4563 cpi->first_time_stamp_ever = source->ts_start;
4564 cpi->last_end_time_stamp_seen = source->ts_start;
4567 // Clear down mmx registers
4568 vpx_clear_system_state();
4570 // adjust frame rates based on timestamps given
4571 if (cm->show_frame) {
4572 adjust_frame_rate(cpi, source);
4575 if (is_one_pass_cbr_svc(cpi)) {
4576 vp9_update_temporal_layer_framerate(cpi);
4577 vp9_restore_layer_context(cpi);
4580 // Find a free buffer for the new frame, releasing the reference previously
4582 if (cm->new_fb_idx != INVALID_IDX) {
4583 --pool->frame_bufs[cm->new_fb_idx].ref_count;
4585 cm->new_fb_idx = get_free_fb(cm);
4587 if (cm->new_fb_idx == INVALID_IDX) return -1;
4589 cm->cur_frame = &pool->frame_bufs[cm->new_fb_idx];
4591 if (!cpi->use_svc && cpi->multi_arf_allowed) {
4592 if (cm->frame_type == KEY_FRAME) {
4593 init_buffer_indices(cpi);
4594 } else if (oxcf->pass == 2) {
4595 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4596 cpi->alt_fb_idx = gf_group->arf_ref_idx[gf_group->index];
4600 // Start with a 0 size frame.
4603 cpi->frame_flags = *frame_flags;
4605 if ((oxcf->pass == 2) &&
4606 (!cpi->use_svc || (is_two_pass_svc(cpi) &&
4607 cpi->svc.encode_empty_frame_state != ENCODING))) {
4608 vp9_rc_get_second_pass_params(cpi);
4609 } else if (oxcf->pass == 1) {
4610 set_frame_size(cpi);
4613 if (cpi->oxcf.pass != 0 || cpi->use_svc || frame_is_intra_only(cm) == 1) {
4614 for (i = 0; i < MAX_REF_FRAMES; ++i) cpi->scaled_ref_idx[i] = INVALID_IDX;
4617 if (oxcf->pass == 1 && (!cpi->use_svc || is_two_pass_svc(cpi))) {
4618 const int lossless = is_lossless_requested(oxcf);
4619 #if CONFIG_VP9_HIGHBITDEPTH
4620 if (cpi->oxcf.use_highbitdepth)
4621 cpi->td.mb.fwd_txm4x4 =
4622 lossless ? vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
4624 cpi->td.mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vpx_fdct4x4;
4625 cpi->td.mb.highbd_itxm_add =
4626 lossless ? vp9_highbd_iwht4x4_add : vp9_highbd_idct4x4_add;
4628 cpi->td.mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vpx_fdct4x4;
4629 #endif // CONFIG_VP9_HIGHBITDEPTH
4630 cpi->td.mb.itxm_add = lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
4631 vp9_first_pass(cpi, source);
4632 } else if (oxcf->pass == 2 && (!cpi->use_svc || is_two_pass_svc(cpi))) {
4633 Pass2Encode(cpi, size, dest, frame_flags);
4634 } else if (cpi->use_svc) {
4635 SvcEncode(cpi, size, dest, frame_flags);
4638 Pass0Encode(cpi, size, dest, frame_flags);
4641 if (cm->refresh_frame_context)
4642 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
4644 // No frame encoded, or frame was dropped, release scaled references.
4645 if ((*size == 0) && (frame_is_intra_only(cm) == 0)) {
4646 release_scaled_references(cpi);
4650 cpi->droppable = !frame_is_reference(cpi);
4653 // Save layer specific state.
4654 if (is_one_pass_cbr_svc(cpi) || ((cpi->svc.number_temporal_layers > 1 ||
4655 cpi->svc.number_spatial_layers > 1) &&
4657 vp9_save_layer_context(cpi);
4660 vpx_usec_timer_mark(&cmptimer);
4661 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
4663 // Should we calculate metrics for the frame.
4664 if (is_psnr_calc_enabled(cpi)) generate_psnr_packet(cpi);
4666 if (cpi->keep_level_stats && oxcf->pass != 1)
4667 update_level_info(cpi, size, arf_src_index);
4669 #if CONFIG_INTERNAL_STATS
4671 if (oxcf->pass != 1) {
4672 double samples = 0.0;
4673 cpi->bytes += (int)(*size);
4675 if (cm->show_frame) {
4676 uint32_t bit_depth = 8;
4677 uint32_t in_bit_depth = 8;
4679 #if CONFIG_VP9_HIGHBITDEPTH
4680 if (cm->use_highbitdepth) {
4681 in_bit_depth = cpi->oxcf.input_bit_depth;
4682 bit_depth = cm->bit_depth;
4686 if (cpi->b_calculate_psnr) {
4687 YV12_BUFFER_CONFIG *orig = cpi->raw_source_frame;
4688 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
4689 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
4691 #if CONFIG_VP9_HIGHBITDEPTH
4692 vpx_calc_highbd_psnr(orig, recon, &psnr, cpi->td.mb.e_mbd.bd,
4695 vpx_calc_psnr(orig, recon, &psnr);
4696 #endif // CONFIG_VP9_HIGHBITDEPTH
4698 adjust_image_stat(psnr.psnr[1], psnr.psnr[2], psnr.psnr[3],
4699 psnr.psnr[0], &cpi->psnr);
4700 cpi->total_sq_error += psnr.sse[0];
4701 cpi->total_samples += psnr.samples[0];
4702 samples = psnr.samples[0];
4706 double frame_ssim2 = 0, weight = 0;
4707 #if CONFIG_VP9_POSTPROC
4708 if (vpx_alloc_frame_buffer(
4709 pp, recon->y_crop_width, recon->y_crop_height,
4710 cm->subsampling_x, cm->subsampling_y,
4711 #if CONFIG_VP9_HIGHBITDEPTH
4712 cm->use_highbitdepth,
4714 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment) < 0) {
4715 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
4716 "Failed to allocate post processing buffer");
4719 vp9_ppflags_t ppflags;
4720 ppflags.post_proc_flag = VP9D_DEBLOCK;
4721 ppflags.deblocking_level = 0; // not used in vp9_post_proc_frame()
4722 ppflags.noise_level = 0; // not used in vp9_post_proc_frame()
4723 vp9_post_proc_frame(cm, pp, &ppflags);
4726 vpx_clear_system_state();
4728 #if CONFIG_VP9_HIGHBITDEPTH
4729 vpx_calc_highbd_psnr(orig, pp, &psnr2, cpi->td.mb.e_mbd.bd,
4730 cpi->oxcf.input_bit_depth);
4732 vpx_calc_psnr(orig, pp, &psnr2);
4733 #endif // CONFIG_VP9_HIGHBITDEPTH
4735 cpi->totalp_sq_error += psnr2.sse[0];
4736 cpi->totalp_samples += psnr2.samples[0];
4737 adjust_image_stat(psnr2.psnr[1], psnr2.psnr[2], psnr2.psnr[3],
4738 psnr2.psnr[0], &cpi->psnrp);
4740 #if CONFIG_VP9_HIGHBITDEPTH
4741 if (cm->use_highbitdepth) {
4742 frame_ssim2 = vpx_highbd_calc_ssim(orig, recon, &weight, bit_depth,
4745 frame_ssim2 = vpx_calc_ssim(orig, recon, &weight);
4748 frame_ssim2 = vpx_calc_ssim(orig, recon, &weight);
4749 #endif // CONFIG_VP9_HIGHBITDEPTH
4751 cpi->worst_ssim = VPXMIN(cpi->worst_ssim, frame_ssim2);
4752 cpi->summed_quality += frame_ssim2 * weight;
4753 cpi->summed_weights += weight;
4755 #if CONFIG_VP9_HIGHBITDEPTH
4756 if (cm->use_highbitdepth) {
4757 frame_ssim2 = vpx_highbd_calc_ssim(orig, pp, &weight, bit_depth,
4760 frame_ssim2 = vpx_calc_ssim(orig, pp, &weight);
4763 frame_ssim2 = vpx_calc_ssim(orig, pp, &weight);
4764 #endif // CONFIG_VP9_HIGHBITDEPTH
4766 cpi->summedp_quality += frame_ssim2 * weight;
4767 cpi->summedp_weights += weight;
4770 FILE *f = fopen("q_used.stt", "a");
4771 fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
4772 cpi->common.current_video_frame, y2, u2, v2,
4773 frame_psnr2, frame_ssim2);
4779 if (cpi->b_calculate_blockiness) {
4780 #if CONFIG_VP9_HIGHBITDEPTH
4781 if (!cm->use_highbitdepth)
4784 double frame_blockiness = vp9_get_blockiness(
4785 cpi->Source->y_buffer, cpi->Source->y_stride,
4786 cm->frame_to_show->y_buffer, cm->frame_to_show->y_stride,
4787 cpi->Source->y_width, cpi->Source->y_height);
4788 cpi->worst_blockiness =
4789 VPXMAX(cpi->worst_blockiness, frame_blockiness);
4790 cpi->total_blockiness += frame_blockiness;
4794 if (cpi->b_calculate_consistency) {
4795 #if CONFIG_VP9_HIGHBITDEPTH
4796 if (!cm->use_highbitdepth)
4799 double this_inconsistency = vpx_get_ssim_metrics(
4800 cpi->Source->y_buffer, cpi->Source->y_stride,
4801 cm->frame_to_show->y_buffer, cm->frame_to_show->y_stride,
4802 cpi->Source->y_width, cpi->Source->y_height, cpi->ssim_vars,
4805 const double peak = (double)((1 << cpi->oxcf.input_bit_depth) - 1);
4806 double consistency =
4807 vpx_sse_to_psnr(samples, peak, (double)cpi->total_inconsistency);
4808 if (consistency > 0.0)
4809 cpi->worst_consistency =
4810 VPXMIN(cpi->worst_consistency, consistency);
4811 cpi->total_inconsistency += this_inconsistency;
4816 double y, u, v, frame_all;
4817 frame_all = vpx_calc_fastssim(cpi->Source, cm->frame_to_show, &y, &u,
4818 &v, bit_depth, in_bit_depth);
4819 adjust_image_stat(y, u, v, frame_all, &cpi->fastssim);
4822 double y, u, v, frame_all;
4823 frame_all = vpx_psnrhvs(cpi->Source, cm->frame_to_show, &y, &u, &v,
4824 bit_depth, in_bit_depth);
4825 adjust_image_stat(y, u, v, frame_all, &cpi->psnrhvs);
4832 if (is_two_pass_svc(cpi)) {
4833 if (cpi->svc.encode_empty_frame_state == ENCODING) {
4834 cpi->svc.encode_empty_frame_state = ENCODED;
4835 cpi->svc.encode_intra_empty_frame = 0;
4838 if (cm->show_frame) {
4839 ++cpi->svc.spatial_layer_to_encode;
4840 if (cpi->svc.spatial_layer_to_encode >= cpi->svc.number_spatial_layers)
4841 cpi->svc.spatial_layer_to_encode = 0;
4843 // May need the empty frame after an visible frame.
4844 cpi->svc.encode_empty_frame_state = NEED_TO_ENCODE;
4846 } else if (is_one_pass_cbr_svc(cpi)) {
4847 if (cm->show_frame) {
4848 ++cpi->svc.spatial_layer_to_encode;
4849 if (cpi->svc.spatial_layer_to_encode >= cpi->svc.number_spatial_layers)
4850 cpi->svc.spatial_layer_to_encode = 0;
4854 vpx_clear_system_state();
4858 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
4859 vp9_ppflags_t *flags) {
4860 VP9_COMMON *cm = &cpi->common;
4861 #if !CONFIG_VP9_POSTPROC
4865 if (!cm->show_frame) {
4869 #if CONFIG_VP9_POSTPROC
4870 ret = vp9_post_proc_frame(cm, dest, flags);
4872 if (cm->frame_to_show) {
4873 *dest = *cm->frame_to_show;
4874 dest->y_width = cm->width;
4875 dest->y_height = cm->height;
4876 dest->uv_width = cm->width >> cm->subsampling_x;
4877 dest->uv_height = cm->height >> cm->subsampling_y;
4882 #endif // !CONFIG_VP9_POSTPROC
4883 vpx_clear_system_state();
4888 int vp9_set_internal_size(VP9_COMP *cpi, VPX_SCALING horiz_mode,
4889 VPX_SCALING vert_mode) {
4890 VP9_COMMON *cm = &cpi->common;
4891 int hr = 0, hs = 0, vr = 0, vs = 0;
4893 if (horiz_mode > ONETWO || vert_mode > ONETWO) return -1;
4895 Scale2Ratio(horiz_mode, &hr, &hs);
4896 Scale2Ratio(vert_mode, &vr, &vs);
4898 // always go to the next whole number
4899 cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
4900 cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
4901 if (cm->current_video_frame) {
4902 assert(cm->width <= cpi->initial_width);
4903 assert(cm->height <= cpi->initial_height);
4906 update_frame_size(cpi);
4911 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
4912 unsigned int height) {
4913 VP9_COMMON *cm = &cpi->common;
4914 #if CONFIG_VP9_HIGHBITDEPTH
4915 check_initial_width(cpi, cm->use_highbitdepth, 1, 1);
4917 check_initial_width(cpi, 1, 1);
4918 #endif // CONFIG_VP9_HIGHBITDEPTH
4920 #if CONFIG_VP9_TEMPORAL_DENOISING
4921 setup_denoiser_buffer(cpi);
4926 if (cm->width > cpi->initial_width) {
4927 cm->width = cpi->initial_width;
4928 printf("Warning: Desired width too large, changed to %d\n", cm->width);
4933 cm->height = height;
4934 if (cm->height > cpi->initial_height) {
4935 cm->height = cpi->initial_height;
4936 printf("Warning: Desired height too large, changed to %d\n", cm->height);
4939 assert(cm->width <= cpi->initial_width);
4940 assert(cm->height <= cpi->initial_height);
4942 update_frame_size(cpi);
4947 void vp9_set_svc(VP9_COMP *cpi, int use_svc) {
4948 cpi->use_svc = use_svc;
4952 int vp9_get_quantizer(VP9_COMP *cpi) { return cpi->common.base_qindex; }
4954 void vp9_apply_encoding_flags(VP9_COMP *cpi, vpx_enc_frame_flags_t flags) {
4956 (VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF)) {
4959 if (flags & VP8_EFLAG_NO_REF_LAST) ref ^= VP9_LAST_FLAG;
4961 if (flags & VP8_EFLAG_NO_REF_GF) ref ^= VP9_GOLD_FLAG;
4963 if (flags & VP8_EFLAG_NO_REF_ARF) ref ^= VP9_ALT_FLAG;
4965 vp9_use_as_reference(cpi, ref);
4969 (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF |
4970 VP8_EFLAG_FORCE_GF | VP8_EFLAG_FORCE_ARF)) {
4973 if (flags & VP8_EFLAG_NO_UPD_LAST) upd ^= VP9_LAST_FLAG;
4975 if (flags & VP8_EFLAG_NO_UPD_GF) upd ^= VP9_GOLD_FLAG;
4977 if (flags & VP8_EFLAG_NO_UPD_ARF) upd ^= VP9_ALT_FLAG;
4979 vp9_update_reference(cpi, upd);
4982 if (flags & VP8_EFLAG_NO_UPD_ENTROPY) {
4983 vp9_update_entropy(cpi, 0);