2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
15 #include "./vp9_rtcd.h"
16 #include "./vpx_config.h"
17 #include "./vpx_dsp_rtcd.h"
18 #include "./vpx_scale_rtcd.h"
19 #include "vpx_dsp/psnr.h"
20 #include "vpx_dsp/vpx_dsp_common.h"
21 #include "vpx_dsp/vpx_filter.h"
22 #if CONFIG_INTERNAL_STATS
23 #include "vpx_dsp/ssim.h"
25 #include "vpx_ports/mem.h"
26 #include "vpx_ports/system_state.h"
27 #include "vpx_ports/vpx_timer.h"
29 #include "vp9/common/vp9_alloccommon.h"
30 #include "vp9/common/vp9_filter.h"
31 #include "vp9/common/vp9_idct.h"
32 #if CONFIG_VP9_POSTPROC
33 #include "vp9/common/vp9_postproc.h"
35 #include "vp9/common/vp9_reconinter.h"
36 #include "vp9/common/vp9_reconintra.h"
37 #include "vp9/common/vp9_tile_common.h"
39 #include "vp9/encoder/vp9_aq_360.h"
40 #include "vp9/encoder/vp9_aq_complexity.h"
41 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
42 #include "vp9/encoder/vp9_aq_variance.h"
43 #include "vp9/encoder/vp9_bitstream.h"
44 #include "vp9/encoder/vp9_context_tree.h"
45 #include "vp9/encoder/vp9_encodeframe.h"
46 #include "vp9/encoder/vp9_encodemv.h"
47 #include "vp9/encoder/vp9_encoder.h"
48 #include "vp9/encoder/vp9_ethread.h"
49 #include "vp9/encoder/vp9_firstpass.h"
50 #include "vp9/encoder/vp9_mbgraph.h"
51 #include "vp9/encoder/vp9_noise_estimate.h"
52 #include "vp9/encoder/vp9_picklpf.h"
53 #include "vp9/encoder/vp9_ratectrl.h"
54 #include "vp9/encoder/vp9_rd.h"
55 #include "vp9/encoder/vp9_resize.h"
56 #include "vp9/encoder/vp9_segmentation.h"
57 #include "vp9/encoder/vp9_skin_detection.h"
58 #include "vp9/encoder/vp9_speed_features.h"
59 #include "vp9/encoder/vp9_svc_layercontext.h"
60 #include "vp9/encoder/vp9_temporal_filter.h"
62 #define AM_SEGMENT_ID_INACTIVE 7
63 #define AM_SEGMENT_ID_ACTIVE 0
65 #define ALTREF_HIGH_PRECISION_MV 1 // Whether to use high precision mv
66 // for altref computation.
67 #define HIGH_PRECISION_MV_QTHRESH 200 // Q threshold for high precision
68 // mv. Choose a very high value for
69 // now so that HIGH_PRECISION is always
71 // #define OUTPUT_YUV_REC
73 #ifdef OUTPUT_YUV_DENOISED
74 FILE *yuv_denoised_file = NULL;
76 #ifdef OUTPUT_YUV_SKINMAP
77 FILE *yuv_skinmap_file = NULL;
89 static const Vp9LevelSpec vp9_level_defs[VP9_LEVELS] = {
90 {LEVEL_1, 829440, 36864, 200, 400, 2, 1, 4, 8},
91 {LEVEL_1_1, 2764800, 73728, 800, 1000, 2, 1, 4, 8},
92 {LEVEL_2, 4608000, 122880, 1800, 1500, 2, 1, 4, 8},
93 {LEVEL_2_1, 9216000, 245760, 3600, 2800, 2, 2, 4, 8},
94 {LEVEL_3, 20736000, 552960, 7200, 6000, 2, 4, 4, 8},
95 {LEVEL_3_1, 36864000, 983040, 12000, 10000, 2, 4, 4, 8},
96 {LEVEL_4, 83558400, 2228224, 18000, 16000, 4, 4, 4, 8},
97 {LEVEL_4_1, 160432128, 2228224, 30000, 18000, 4, 4, 5, 6},
98 {LEVEL_5, 311951360, 8912896, 60000, 36000, 6, 8, 6, 4},
99 {LEVEL_5_1, 588251136, 8912896, 120000, 46000, 8, 8, 10, 4},
100 // TODO(huisu): update max_cpb_size for level 5_2 ~ 6_2 when
101 // they are finalized (currently TBD).
102 {LEVEL_5_2, 1176502272, 8912896, 180000, 0, 8, 8, 10, 4},
103 {LEVEL_6, 1176502272, 35651584, 180000, 0, 8, 16, 10, 4},
104 {LEVEL_6_1, 2353004544u, 35651584, 240000, 0, 8, 16, 10, 4},
105 {LEVEL_6_2, 4706009088u, 35651584, 480000, 0, 8, 16, 10, 4},
108 static INLINE void Scale2Ratio(VPX_SCALING mode, int *hr, int *hs) {
134 // Mark all inactive blocks as active. Other segmentation features may be set
135 // so memset cannot be used, instead only inactive blocks should be reset.
136 static void suppress_active_map(VP9_COMP *cpi) {
137 unsigned char *const seg_map = cpi->segmentation_map;
139 if (cpi->active_map.enabled || cpi->active_map.update) {
140 const int rows = cpi->common.mi_rows;
141 const int cols = cpi->common.mi_cols;
144 for (i = 0; i < rows * cols; ++i)
145 if (seg_map[i] == AM_SEGMENT_ID_INACTIVE)
146 seg_map[i] = AM_SEGMENT_ID_ACTIVE;
150 static void apply_active_map(VP9_COMP *cpi) {
151 struct segmentation *const seg = &cpi->common.seg;
152 unsigned char *const seg_map = cpi->segmentation_map;
153 const unsigned char *const active_map = cpi->active_map.map;
156 assert(AM_SEGMENT_ID_ACTIVE == CR_SEGMENT_ID_BASE);
158 if (frame_is_intra_only(&cpi->common)) {
159 cpi->active_map.enabled = 0;
160 cpi->active_map.update = 1;
163 if (cpi->active_map.update) {
164 if (cpi->active_map.enabled) {
165 for (i = 0; i < cpi->common.mi_rows * cpi->common.mi_cols; ++i)
166 if (seg_map[i] == AM_SEGMENT_ID_ACTIVE) seg_map[i] = active_map[i];
167 vp9_enable_segmentation(seg);
168 vp9_enable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
169 vp9_enable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
170 // Setting the data to -MAX_LOOP_FILTER will result in the computed loop
171 // filter level being zero regardless of the value of seg->abs_delta.
172 vp9_set_segdata(seg, AM_SEGMENT_ID_INACTIVE,
173 SEG_LVL_ALT_LF, -MAX_LOOP_FILTER);
175 vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
176 vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
178 seg->update_data = 1;
182 cpi->active_map.update = 0;
186 static void init_level_info(Vp9LevelInfo *level_info) {
187 Vp9LevelStats *const level_stats = &level_info->level_stats;
188 Vp9LevelSpec *const level_spec = &level_info->level_spec;
190 memset(level_stats, 0, sizeof(*level_stats));
191 memset(level_spec, 0, sizeof(*level_spec));
192 level_spec->level = LEVEL_UNKNOWN;
193 level_spec->min_altref_distance = INT_MAX;
196 VP9_LEVEL vp9_get_level(const Vp9LevelSpec * const level_spec) {
198 const Vp9LevelSpec *this_level;
200 vpx_clear_system_state();
202 for (i = 0; i < VP9_LEVELS; ++i) {
203 this_level = &vp9_level_defs[i];
204 if ((double)level_spec->max_luma_sample_rate * (1 + SAMPLE_RATE_GRACE_P) >
205 (double)this_level->max_luma_sample_rate ||
206 level_spec->max_luma_picture_size > this_level->max_luma_picture_size ||
207 level_spec->average_bitrate > this_level->average_bitrate ||
208 level_spec->max_cpb_size > this_level->max_cpb_size ||
209 level_spec->compression_ratio < this_level->compression_ratio ||
210 level_spec->max_col_tiles > this_level->max_col_tiles ||
211 level_spec->min_altref_distance < this_level->min_altref_distance ||
212 level_spec->max_ref_frame_buffers > this_level->max_ref_frame_buffers)
216 return (i == VP9_LEVELS) ? LEVEL_UNKNOWN : vp9_level_defs[i].level;
219 int vp9_set_active_map(VP9_COMP* cpi,
220 unsigned char* new_map_16x16,
223 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
224 unsigned char *const active_map_8x8 = cpi->active_map.map;
225 const int mi_rows = cpi->common.mi_rows;
226 const int mi_cols = cpi->common.mi_cols;
227 cpi->active_map.update = 1;
230 for (r = 0; r < mi_rows; ++r) {
231 for (c = 0; c < mi_cols; ++c) {
232 active_map_8x8[r * mi_cols + c] =
233 new_map_16x16[(r >> 1) * cols + (c >> 1)]
234 ? AM_SEGMENT_ID_ACTIVE
235 : AM_SEGMENT_ID_INACTIVE;
238 cpi->active_map.enabled = 1;
240 cpi->active_map.enabled = 0;
248 int vp9_get_active_map(VP9_COMP* cpi,
249 unsigned char* new_map_16x16,
252 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols &&
254 unsigned char* const seg_map_8x8 = cpi->segmentation_map;
255 const int mi_rows = cpi->common.mi_rows;
256 const int mi_cols = cpi->common.mi_cols;
257 memset(new_map_16x16, !cpi->active_map.enabled, rows * cols);
258 if (cpi->active_map.enabled) {
260 for (r = 0; r < mi_rows; ++r) {
261 for (c = 0; c < mi_cols; ++c) {
262 // Cyclic refresh segments are considered active despite not having
263 // AM_SEGMENT_ID_ACTIVE
264 new_map_16x16[(r >> 1) * cols + (c >> 1)] |=
265 seg_map_8x8[r * mi_cols + c] != AM_SEGMENT_ID_INACTIVE;
275 void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv) {
276 MACROBLOCK *const mb = &cpi->td.mb;
277 cpi->common.allow_high_precision_mv = allow_high_precision_mv;
278 if (cpi->common.allow_high_precision_mv) {
279 mb->mvcost = mb->nmvcost_hp;
280 mb->mvsadcost = mb->nmvsadcost_hp;
282 mb->mvcost = mb->nmvcost;
283 mb->mvsadcost = mb->nmvsadcost;
287 static void setup_frame(VP9_COMP *cpi) {
288 VP9_COMMON *const cm = &cpi->common;
289 // Set up entropy context depending on frame type. The decoder mandates
290 // the use of the default context, index 0, for keyframes and inter
291 // frames where the error_resilient_mode or intra_only flag is set. For
292 // other inter-frames the encoder currently uses only two contexts;
293 // context 1 for ALTREF frames and context 0 for the others.
294 if (frame_is_intra_only(cm) || cm->error_resilient_mode) {
295 vp9_setup_past_independence(cm);
298 cm->frame_context_idx = cpi->refresh_alt_ref_frame;
301 if (cm->frame_type == KEY_FRAME) {
302 if (!is_two_pass_svc(cpi))
303 cpi->refresh_golden_frame = 1;
304 cpi->refresh_alt_ref_frame = 1;
305 vp9_zero(cpi->interp_filter_selected);
307 *cm->fc = cm->frame_contexts[cm->frame_context_idx];
308 vp9_zero(cpi->interp_filter_selected[0]);
312 static void vp9_enc_setup_mi(VP9_COMMON *cm) {
314 cm->mi = cm->mip + cm->mi_stride + 1;
315 memset(cm->mip, 0, cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mip));
316 cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
317 // Clear top border row
318 memset(cm->prev_mip, 0, sizeof(*cm->prev_mip) * cm->mi_stride);
319 // Clear left border column
320 for (i = 1; i < cm->mi_rows + 1; ++i)
321 memset(&cm->prev_mip[i * cm->mi_stride], 0, sizeof(*cm->prev_mip));
323 cm->mi_grid_visible = cm->mi_grid_base + cm->mi_stride + 1;
324 cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mi_stride + 1;
326 memset(cm->mi_grid_base, 0,
327 cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mi_grid_base));
330 static int vp9_enc_alloc_mi(VP9_COMMON *cm, int mi_size) {
331 cm->mip = vpx_calloc(mi_size, sizeof(*cm->mip));
334 cm->prev_mip = vpx_calloc(mi_size, sizeof(*cm->prev_mip));
337 cm->mi_alloc_size = mi_size;
339 cm->mi_grid_base = (MODE_INFO **)vpx_calloc(mi_size, sizeof(MODE_INFO*));
340 if (!cm->mi_grid_base)
342 cm->prev_mi_grid_base = (MODE_INFO **)vpx_calloc(mi_size, sizeof(MODE_INFO*));
343 if (!cm->prev_mi_grid_base)
349 static void vp9_enc_free_mi(VP9_COMMON *cm) {
352 vpx_free(cm->prev_mip);
354 vpx_free(cm->mi_grid_base);
355 cm->mi_grid_base = NULL;
356 vpx_free(cm->prev_mi_grid_base);
357 cm->prev_mi_grid_base = NULL;
360 static void vp9_swap_mi_and_prev_mi(VP9_COMMON *cm) {
361 // Current mip will be the prev_mip for the next frame.
362 MODE_INFO **temp_base = cm->prev_mi_grid_base;
363 MODE_INFO *temp = cm->prev_mip;
364 cm->prev_mip = cm->mip;
367 // Update the upper left visible macroblock ptrs.
368 cm->mi = cm->mip + cm->mi_stride + 1;
369 cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
371 cm->prev_mi_grid_base = cm->mi_grid_base;
372 cm->mi_grid_base = temp_base;
373 cm->mi_grid_visible = cm->mi_grid_base + cm->mi_stride + 1;
374 cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mi_stride + 1;
377 void vp9_initialize_enc(void) {
378 static volatile int init_done = 0;
384 vp9_init_intra_predictors();
386 vp9_rc_init_minq_luts();
387 vp9_entropy_mv_init();
388 vp9_temporal_filter_init();
393 static void dealloc_compressor_data(VP9_COMP *cpi) {
394 VP9_COMMON *const cm = &cpi->common;
397 vpx_free(cpi->mbmi_ext_base);
398 cpi->mbmi_ext_base = NULL;
400 vpx_free(cpi->tile_data);
401 cpi->tile_data = NULL;
403 // Delete sementation map
404 vpx_free(cpi->segmentation_map);
405 cpi->segmentation_map = NULL;
406 vpx_free(cpi->coding_context.last_frame_seg_map_copy);
407 cpi->coding_context.last_frame_seg_map_copy = NULL;
409 vpx_free(cpi->nmvcosts[0]);
410 vpx_free(cpi->nmvcosts[1]);
411 cpi->nmvcosts[0] = NULL;
412 cpi->nmvcosts[1] = NULL;
414 vpx_free(cpi->nmvcosts_hp[0]);
415 vpx_free(cpi->nmvcosts_hp[1]);
416 cpi->nmvcosts_hp[0] = NULL;
417 cpi->nmvcosts_hp[1] = NULL;
419 vpx_free(cpi->nmvsadcosts[0]);
420 vpx_free(cpi->nmvsadcosts[1]);
421 cpi->nmvsadcosts[0] = NULL;
422 cpi->nmvsadcosts[1] = NULL;
424 vpx_free(cpi->nmvsadcosts_hp[0]);
425 vpx_free(cpi->nmvsadcosts_hp[1]);
426 cpi->nmvsadcosts_hp[0] = NULL;
427 cpi->nmvsadcosts_hp[1] = NULL;
429 vp9_cyclic_refresh_free(cpi->cyclic_refresh);
430 cpi->cyclic_refresh = NULL;
432 vpx_free(cpi->active_map.map);
433 cpi->active_map.map = NULL;
435 vpx_free(cpi->consec_zero_mv);
436 cpi->consec_zero_mv = NULL;
438 vp9_free_ref_frame_buffers(cm->buffer_pool);
439 #if CONFIG_VP9_POSTPROC
440 vp9_free_postproc_buffers(cm);
442 vp9_free_context_buffers(cm);
444 vpx_free_frame_buffer(&cpi->last_frame_uf);
445 vpx_free_frame_buffer(&cpi->scaled_source);
446 vpx_free_frame_buffer(&cpi->scaled_last_source);
447 vpx_free_frame_buffer(&cpi->alt_ref_buffer);
448 vp9_lookahead_destroy(cpi->lookahead);
450 vpx_free(cpi->tile_tok[0][0]);
451 cpi->tile_tok[0][0] = 0;
453 vp9_free_pc_tree(&cpi->td);
455 for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
456 LAYER_CONTEXT *const lc = &cpi->svc.layer_context[i];
457 vpx_free(lc->rc_twopass_stats_in.buf);
458 lc->rc_twopass_stats_in.buf = NULL;
459 lc->rc_twopass_stats_in.sz = 0;
462 if (cpi->source_diff_var != NULL) {
463 vpx_free(cpi->source_diff_var);
464 cpi->source_diff_var = NULL;
467 for (i = 0; i < MAX_LAG_BUFFERS; ++i) {
468 vpx_free_frame_buffer(&cpi->svc.scaled_frames[i]);
470 memset(&cpi->svc.scaled_frames[0], 0,
471 MAX_LAG_BUFFERS * sizeof(cpi->svc.scaled_frames[0]));
473 vpx_free_frame_buffer(&cpi->svc.scaled_temp);
474 memset(&cpi->svc.scaled_temp, 0, sizeof(cpi->svc.scaled_temp));
476 vpx_free_frame_buffer(&cpi->svc.empty_frame.img);
477 memset(&cpi->svc.empty_frame, 0, sizeof(cpi->svc.empty_frame));
479 vp9_free_svc_cyclic_refresh(cpi);
482 static void save_coding_context(VP9_COMP *cpi) {
483 CODING_CONTEXT *const cc = &cpi->coding_context;
484 VP9_COMMON *cm = &cpi->common;
486 // Stores a snapshot of key state variables which can subsequently be
487 // restored with a call to vp9_restore_coding_context. These functions are
488 // intended for use in a re-code loop in vp9_compress_frame where the
489 // quantizer value is adjusted between loop iterations.
490 vp9_copy(cc->nmvjointcost, cpi->td.mb.nmvjointcost);
492 memcpy(cc->nmvcosts[0], cpi->nmvcosts[0],
493 MV_VALS * sizeof(*cpi->nmvcosts[0]));
494 memcpy(cc->nmvcosts[1], cpi->nmvcosts[1],
495 MV_VALS * sizeof(*cpi->nmvcosts[1]));
496 memcpy(cc->nmvcosts_hp[0], cpi->nmvcosts_hp[0],
497 MV_VALS * sizeof(*cpi->nmvcosts_hp[0]));
498 memcpy(cc->nmvcosts_hp[1], cpi->nmvcosts_hp[1],
499 MV_VALS * sizeof(*cpi->nmvcosts_hp[1]));
501 vp9_copy(cc->segment_pred_probs, cm->seg.pred_probs);
503 memcpy(cpi->coding_context.last_frame_seg_map_copy,
504 cm->last_frame_seg_map, (cm->mi_rows * cm->mi_cols));
506 vp9_copy(cc->last_ref_lf_deltas, cm->lf.last_ref_deltas);
507 vp9_copy(cc->last_mode_lf_deltas, cm->lf.last_mode_deltas);
512 static void restore_coding_context(VP9_COMP *cpi) {
513 CODING_CONTEXT *const cc = &cpi->coding_context;
514 VP9_COMMON *cm = &cpi->common;
516 // Restore key state variables to the snapshot state stored in the
517 // previous call to vp9_save_coding_context.
518 vp9_copy(cpi->td.mb.nmvjointcost, cc->nmvjointcost);
520 memcpy(cpi->nmvcosts[0], cc->nmvcosts[0], MV_VALS * sizeof(*cc->nmvcosts[0]));
521 memcpy(cpi->nmvcosts[1], cc->nmvcosts[1], MV_VALS * sizeof(*cc->nmvcosts[1]));
522 memcpy(cpi->nmvcosts_hp[0], cc->nmvcosts_hp[0],
523 MV_VALS * sizeof(*cc->nmvcosts_hp[0]));
524 memcpy(cpi->nmvcosts_hp[1], cc->nmvcosts_hp[1],
525 MV_VALS * sizeof(*cc->nmvcosts_hp[1]));
527 vp9_copy(cm->seg.pred_probs, cc->segment_pred_probs);
529 memcpy(cm->last_frame_seg_map,
530 cpi->coding_context.last_frame_seg_map_copy,
531 (cm->mi_rows * cm->mi_cols));
533 vp9_copy(cm->lf.last_ref_deltas, cc->last_ref_lf_deltas);
534 vp9_copy(cm->lf.last_mode_deltas, cc->last_mode_lf_deltas);
539 static void configure_static_seg_features(VP9_COMP *cpi) {
540 VP9_COMMON *const cm = &cpi->common;
541 const RATE_CONTROL *const rc = &cpi->rc;
542 struct segmentation *const seg = &cm->seg;
544 int high_q = (int)(rc->avg_q > 48.0);
547 // Disable and clear down for KF
548 if (cm->frame_type == KEY_FRAME) {
549 // Clear down the global segmentation map
550 memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
552 seg->update_data = 0;
553 cpi->static_mb_pct = 0;
555 // Disable segmentation
556 vp9_disable_segmentation(seg);
558 // Clear down the segment features.
559 vp9_clearall_segfeatures(seg);
560 } else if (cpi->refresh_alt_ref_frame) {
561 // If this is an alt ref frame
562 // Clear down the global segmentation map
563 memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
565 seg->update_data = 0;
566 cpi->static_mb_pct = 0;
568 // Disable segmentation and individual segment features by default
569 vp9_disable_segmentation(seg);
570 vp9_clearall_segfeatures(seg);
572 // Scan frames from current to arf frame.
573 // This function re-enables segmentation if appropriate.
574 vp9_update_mbgraph_stats(cpi);
576 // If segmentation was enabled set those features needed for the
580 seg->update_data = 1;
582 qi_delta = vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 0.875,
584 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta - 2);
585 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
587 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
588 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
590 // Where relevant assume segment data is delta data
591 seg->abs_delta = SEGMENT_DELTADATA;
593 } else if (seg->enabled) {
594 // All other frames if segmentation has been enabled
596 // First normal frame in a valid gf or alt ref group
597 if (rc->frames_since_golden == 0) {
598 // Set up segment features for normal frames in an arf group
599 if (rc->source_alt_ref_active) {
601 seg->update_data = 1;
602 seg->abs_delta = SEGMENT_DELTADATA;
604 qi_delta = vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 1.125,
606 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta + 2);
607 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
609 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
610 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
612 // Segment coding disabled for compred testing
613 if (high_q || (cpi->static_mb_pct == 100)) {
614 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
615 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
616 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
619 // Disable segmentation and clear down features if alt ref
620 // is not active for this group
622 vp9_disable_segmentation(seg);
624 memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
627 seg->update_data = 0;
629 vp9_clearall_segfeatures(seg);
631 } else if (rc->is_src_frame_alt_ref) {
632 // Special case where we are coding over the top of a previous
634 // Segment coding disabled for compred testing
636 // Enable ref frame features for segment 0 as well
637 vp9_enable_segfeature(seg, 0, SEG_LVL_REF_FRAME);
638 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
640 // All mbs should use ALTREF_FRAME
641 vp9_clear_segdata(seg, 0, SEG_LVL_REF_FRAME);
642 vp9_set_segdata(seg, 0, SEG_LVL_REF_FRAME, ALTREF_FRAME);
643 vp9_clear_segdata(seg, 1, SEG_LVL_REF_FRAME);
644 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
646 // Skip all MBs if high Q (0,0 mv and skip coeffs)
648 vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
649 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
651 // Enable data update
652 seg->update_data = 1;
656 // No updates.. leave things as they are.
658 seg->update_data = 0;
663 static void update_reference_segmentation_map(VP9_COMP *cpi) {
664 VP9_COMMON *const cm = &cpi->common;
665 MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
666 uint8_t *cache_ptr = cm->last_frame_seg_map;
669 for (row = 0; row < cm->mi_rows; row++) {
670 MODE_INFO **mi_8x8 = mi_8x8_ptr;
671 uint8_t *cache = cache_ptr;
672 for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
673 cache[0] = mi_8x8[0]->segment_id;
674 mi_8x8_ptr += cm->mi_stride;
675 cache_ptr += cm->mi_cols;
679 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
680 VP9_COMMON *cm = &cpi->common;
681 const VP9EncoderConfig *oxcf = &cpi->oxcf;
684 cpi->lookahead = vp9_lookahead_init(oxcf->width, oxcf->height,
685 cm->subsampling_x, cm->subsampling_y,
686 #if CONFIG_VP9_HIGHBITDEPTH
687 cm->use_highbitdepth,
689 oxcf->lag_in_frames);
691 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
692 "Failed to allocate lag buffers");
694 // TODO(agrange) Check if ARF is enabled and skip allocation if not.
695 if (vpx_realloc_frame_buffer(&cpi->alt_ref_buffer,
696 oxcf->width, oxcf->height,
697 cm->subsampling_x, cm->subsampling_y,
698 #if CONFIG_VP9_HIGHBITDEPTH
699 cm->use_highbitdepth,
701 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
703 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
704 "Failed to allocate altref buffer");
707 static void alloc_util_frame_buffers(VP9_COMP *cpi) {
708 VP9_COMMON *const cm = &cpi->common;
709 if (vpx_realloc_frame_buffer(&cpi->last_frame_uf,
710 cm->width, cm->height,
711 cm->subsampling_x, cm->subsampling_y,
712 #if CONFIG_VP9_HIGHBITDEPTH
713 cm->use_highbitdepth,
715 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
717 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
718 "Failed to allocate last frame buffer");
720 if (vpx_realloc_frame_buffer(&cpi->scaled_source,
721 cm->width, cm->height,
722 cm->subsampling_x, cm->subsampling_y,
723 #if CONFIG_VP9_HIGHBITDEPTH
724 cm->use_highbitdepth,
726 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
728 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
729 "Failed to allocate scaled source buffer");
731 if (vpx_realloc_frame_buffer(&cpi->scaled_last_source,
732 cm->width, cm->height,
733 cm->subsampling_x, cm->subsampling_y,
734 #if CONFIG_VP9_HIGHBITDEPTH
735 cm->use_highbitdepth,
737 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
739 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
740 "Failed to allocate scaled last source buffer");
744 static int alloc_context_buffers_ext(VP9_COMP *cpi) {
745 VP9_COMMON *cm = &cpi->common;
746 int mi_size = cm->mi_cols * cm->mi_rows;
748 cpi->mbmi_ext_base = vpx_calloc(mi_size, sizeof(*cpi->mbmi_ext_base));
749 if (!cpi->mbmi_ext_base)
755 static void alloc_compressor_data(VP9_COMP *cpi) {
756 VP9_COMMON *cm = &cpi->common;
758 vp9_alloc_context_buffers(cm, cm->width, cm->height);
760 alloc_context_buffers_ext(cpi);
762 vpx_free(cpi->tile_tok[0][0]);
765 unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
766 CHECK_MEM_ERROR(cm, cpi->tile_tok[0][0],
767 vpx_calloc(tokens, sizeof(*cpi->tile_tok[0][0])));
770 vp9_setup_pc_tree(&cpi->common, &cpi->td);
773 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
774 cpi->framerate = framerate < 0.1 ? 30 : framerate;
775 vp9_rc_update_framerate(cpi);
778 static void set_tile_limits(VP9_COMP *cpi) {
779 VP9_COMMON *const cm = &cpi->common;
781 int min_log2_tile_cols, max_log2_tile_cols;
782 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
784 if (is_two_pass_svc(cpi) &&
785 (cpi->svc.encode_empty_frame_state == ENCODING ||
786 cpi->svc.number_spatial_layers > 1)) {
787 cm->log2_tile_cols = 0;
788 cm->log2_tile_rows = 0;
790 cm->log2_tile_cols = clamp(cpi->oxcf.tile_columns,
791 min_log2_tile_cols, max_log2_tile_cols);
792 cm->log2_tile_rows = cpi->oxcf.tile_rows;
796 static void update_frame_size(VP9_COMP *cpi) {
797 VP9_COMMON *const cm = &cpi->common;
798 MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
800 vp9_set_mb_mi(cm, cm->width, cm->height);
801 vp9_init_context_buffers(cm);
802 vp9_init_macroblockd(cm, xd, NULL);
803 cpi->td.mb.mbmi_ext_base = cpi->mbmi_ext_base;
804 memset(cpi->mbmi_ext_base, 0,
805 cm->mi_rows * cm->mi_cols * sizeof(*cpi->mbmi_ext_base));
807 set_tile_limits(cpi);
809 if (is_two_pass_svc(cpi)) {
810 if (vpx_realloc_frame_buffer(&cpi->alt_ref_buffer,
811 cm->width, cm->height,
812 cm->subsampling_x, cm->subsampling_y,
813 #if CONFIG_VP9_HIGHBITDEPTH
814 cm->use_highbitdepth,
816 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
818 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
819 "Failed to reallocate alt_ref_buffer");
823 static void init_buffer_indices(VP9_COMP *cpi) {
829 static void init_config(struct VP9_COMP *cpi, VP9EncoderConfig *oxcf) {
830 VP9_COMMON *const cm = &cpi->common;
833 cpi->framerate = oxcf->init_framerate;
834 cm->profile = oxcf->profile;
835 cm->bit_depth = oxcf->bit_depth;
836 #if CONFIG_VP9_HIGHBITDEPTH
837 cm->use_highbitdepth = oxcf->use_highbitdepth;
839 cm->color_space = oxcf->color_space;
840 cm->color_range = oxcf->color_range;
842 cpi->target_level = oxcf->target_level;
843 cpi->keep_level_stats = oxcf->target_level != LEVEL_MAX;
845 cm->width = oxcf->width;
846 cm->height = oxcf->height;
847 alloc_compressor_data(cpi);
849 cpi->svc.temporal_layering_mode = oxcf->temporal_layering_mode;
851 // Single thread case: use counts in common.
852 cpi->td.counts = &cm->counts;
854 // Spatial scalability.
855 cpi->svc.number_spatial_layers = oxcf->ss_number_layers;
856 // Temporal scalability.
857 cpi->svc.number_temporal_layers = oxcf->ts_number_layers;
859 if ((cpi->svc.number_temporal_layers > 1 && cpi->oxcf.rc_mode == VPX_CBR) ||
860 ((cpi->svc.number_temporal_layers > 1 ||
861 cpi->svc.number_spatial_layers > 1) &&
862 cpi->oxcf.pass != 1)) {
863 vp9_init_layer_context(cpi);
866 // change includes all joint functionality
867 vp9_change_config(cpi, oxcf);
869 cpi->static_mb_pct = 0;
870 cpi->ref_frame_flags = 0;
872 init_buffer_indices(cpi);
874 vp9_noise_estimate_init(&cpi->noise_estimate, cm->width, cm->height);
877 static void set_rc_buffer_sizes(RATE_CONTROL *rc,
878 const VP9EncoderConfig *oxcf) {
879 const int64_t bandwidth = oxcf->target_bandwidth;
880 const int64_t starting = oxcf->starting_buffer_level_ms;
881 const int64_t optimal = oxcf->optimal_buffer_level_ms;
882 const int64_t maximum = oxcf->maximum_buffer_size_ms;
884 rc->starting_buffer_level = starting * bandwidth / 1000;
885 rc->optimal_buffer_level = (optimal == 0) ? bandwidth / 8
886 : optimal * bandwidth / 1000;
887 rc->maximum_buffer_size = (maximum == 0) ? bandwidth / 8
888 : maximum * bandwidth / 1000;
891 #if CONFIG_VP9_HIGHBITDEPTH
892 #define HIGHBD_BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF) \
893 cpi->fn_ptr[BT].sdf = SDF; \
894 cpi->fn_ptr[BT].sdaf = SDAF; \
895 cpi->fn_ptr[BT].vf = VF; \
896 cpi->fn_ptr[BT].svf = SVF; \
897 cpi->fn_ptr[BT].svaf = SVAF; \
898 cpi->fn_ptr[BT].sdx3f = SDX3F; \
899 cpi->fn_ptr[BT].sdx8f = SDX8F; \
900 cpi->fn_ptr[BT].sdx4df = SDX4DF;
902 #define MAKE_BFP_SAD_WRAPPER(fnname) \
903 static unsigned int fnname##_bits8(const uint8_t *src_ptr, \
905 const uint8_t *ref_ptr, \
907 return fnname(src_ptr, source_stride, ref_ptr, ref_stride); \
909 static unsigned int fnname##_bits10(const uint8_t *src_ptr, \
911 const uint8_t *ref_ptr, \
913 return fnname(src_ptr, source_stride, ref_ptr, ref_stride) >> 2; \
915 static unsigned int fnname##_bits12(const uint8_t *src_ptr, \
917 const uint8_t *ref_ptr, \
919 return fnname(src_ptr, source_stride, ref_ptr, ref_stride) >> 4; \
922 #define MAKE_BFP_SADAVG_WRAPPER(fnname) static unsigned int \
923 fnname##_bits8(const uint8_t *src_ptr, \
925 const uint8_t *ref_ptr, \
927 const uint8_t *second_pred) { \
928 return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred); \
930 static unsigned int fnname##_bits10(const uint8_t *src_ptr, \
932 const uint8_t *ref_ptr, \
934 const uint8_t *second_pred) { \
935 return fnname(src_ptr, source_stride, ref_ptr, ref_stride, \
938 static unsigned int fnname##_bits12(const uint8_t *src_ptr, \
940 const uint8_t *ref_ptr, \
942 const uint8_t *second_pred) { \
943 return fnname(src_ptr, source_stride, ref_ptr, ref_stride, \
947 #define MAKE_BFP_SAD3_WRAPPER(fnname) \
948 static void fnname##_bits8(const uint8_t *src_ptr, \
950 const uint8_t *ref_ptr, \
952 unsigned int *sad_array) { \
953 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
955 static void fnname##_bits10(const uint8_t *src_ptr, \
957 const uint8_t *ref_ptr, \
959 unsigned int *sad_array) { \
961 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
962 for (i = 0; i < 3; i++) \
963 sad_array[i] >>= 2; \
965 static void fnname##_bits12(const uint8_t *src_ptr, \
967 const uint8_t *ref_ptr, \
969 unsigned int *sad_array) { \
971 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
972 for (i = 0; i < 3; i++) \
973 sad_array[i] >>= 4; \
976 #define MAKE_BFP_SAD8_WRAPPER(fnname) \
977 static void fnname##_bits8(const uint8_t *src_ptr, \
979 const uint8_t *ref_ptr, \
981 unsigned int *sad_array) { \
982 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
984 static void fnname##_bits10(const uint8_t *src_ptr, \
986 const uint8_t *ref_ptr, \
988 unsigned int *sad_array) { \
990 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
991 for (i = 0; i < 8; i++) \
992 sad_array[i] >>= 2; \
994 static void fnname##_bits12(const uint8_t *src_ptr, \
996 const uint8_t *ref_ptr, \
998 unsigned int *sad_array) { \
1000 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1001 for (i = 0; i < 8; i++) \
1002 sad_array[i] >>= 4; \
1004 #define MAKE_BFP_SAD4D_WRAPPER(fnname) \
1005 static void fnname##_bits8(const uint8_t *src_ptr, \
1006 int source_stride, \
1007 const uint8_t* const ref_ptr[], \
1009 unsigned int *sad_array) { \
1010 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1012 static void fnname##_bits10(const uint8_t *src_ptr, \
1013 int source_stride, \
1014 const uint8_t* const ref_ptr[], \
1016 unsigned int *sad_array) { \
1018 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1019 for (i = 0; i < 4; i++) \
1020 sad_array[i] >>= 2; \
1022 static void fnname##_bits12(const uint8_t *src_ptr, \
1023 int source_stride, \
1024 const uint8_t* const ref_ptr[], \
1026 unsigned int *sad_array) { \
1028 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
1029 for (i = 0; i < 4; i++) \
1030 sad_array[i] >>= 4; \
1033 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x16)
1034 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x16_avg)
1035 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x16x4d)
1036 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x32)
1037 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x32_avg)
1038 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x32x4d)
1039 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad64x32)
1040 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad64x32_avg)
1041 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad64x32x4d)
1042 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x64)
1043 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x64_avg)
1044 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x64x4d)
1045 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x32)
1046 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x32_avg)
1047 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad32x32x3)
1048 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad32x32x8)
1049 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x32x4d)
1050 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad64x64)
1051 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad64x64_avg)
1052 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad64x64x3)
1053 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad64x64x8)
1054 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad64x64x4d)
1055 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x16)
1056 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x16_avg)
1057 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad16x16x3)
1058 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad16x16x8)
1059 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x16x4d)
1060 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x8)
1061 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x8_avg)
1062 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad16x8x3)
1063 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad16x8x8)
1064 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x8x4d)
1065 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x16)
1066 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x16_avg)
1067 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad8x16x3)
1068 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x16x8)
1069 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x16x4d)
1070 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x8)
1071 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x8_avg)
1072 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad8x8x3)
1073 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x8x8)
1074 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x8x4d)
1075 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x4)
1076 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x4_avg)
1077 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x4x8)
1078 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x4x4d)
1079 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad4x8)
1080 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad4x8_avg)
1081 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad4x8x8)
1082 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad4x8x4d)
1083 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad4x4)
1084 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad4x4_avg)
1085 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad4x4x3)
1086 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad4x4x8)
1087 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad4x4x4d)
1089 static void highbd_set_var_fns(VP9_COMP *const cpi) {
1090 VP9_COMMON *const cm = &cpi->common;
1091 if (cm->use_highbitdepth) {
1092 switch (cm->bit_depth) {
1094 HIGHBD_BFP(BLOCK_32X16,
1095 vpx_highbd_sad32x16_bits8,
1096 vpx_highbd_sad32x16_avg_bits8,
1097 vpx_highbd_8_variance32x16,
1098 vpx_highbd_8_sub_pixel_variance32x16,
1099 vpx_highbd_8_sub_pixel_avg_variance32x16,
1102 vpx_highbd_sad32x16x4d_bits8)
1104 HIGHBD_BFP(BLOCK_16X32,
1105 vpx_highbd_sad16x32_bits8,
1106 vpx_highbd_sad16x32_avg_bits8,
1107 vpx_highbd_8_variance16x32,
1108 vpx_highbd_8_sub_pixel_variance16x32,
1109 vpx_highbd_8_sub_pixel_avg_variance16x32,
1112 vpx_highbd_sad16x32x4d_bits8)
1114 HIGHBD_BFP(BLOCK_64X32,
1115 vpx_highbd_sad64x32_bits8,
1116 vpx_highbd_sad64x32_avg_bits8,
1117 vpx_highbd_8_variance64x32,
1118 vpx_highbd_8_sub_pixel_variance64x32,
1119 vpx_highbd_8_sub_pixel_avg_variance64x32,
1122 vpx_highbd_sad64x32x4d_bits8)
1124 HIGHBD_BFP(BLOCK_32X64,
1125 vpx_highbd_sad32x64_bits8,
1126 vpx_highbd_sad32x64_avg_bits8,
1127 vpx_highbd_8_variance32x64,
1128 vpx_highbd_8_sub_pixel_variance32x64,
1129 vpx_highbd_8_sub_pixel_avg_variance32x64,
1132 vpx_highbd_sad32x64x4d_bits8)
1134 HIGHBD_BFP(BLOCK_32X32,
1135 vpx_highbd_sad32x32_bits8,
1136 vpx_highbd_sad32x32_avg_bits8,
1137 vpx_highbd_8_variance32x32,
1138 vpx_highbd_8_sub_pixel_variance32x32,
1139 vpx_highbd_8_sub_pixel_avg_variance32x32,
1140 vpx_highbd_sad32x32x3_bits8,
1141 vpx_highbd_sad32x32x8_bits8,
1142 vpx_highbd_sad32x32x4d_bits8)
1144 HIGHBD_BFP(BLOCK_64X64,
1145 vpx_highbd_sad64x64_bits8,
1146 vpx_highbd_sad64x64_avg_bits8,
1147 vpx_highbd_8_variance64x64,
1148 vpx_highbd_8_sub_pixel_variance64x64,
1149 vpx_highbd_8_sub_pixel_avg_variance64x64,
1150 vpx_highbd_sad64x64x3_bits8,
1151 vpx_highbd_sad64x64x8_bits8,
1152 vpx_highbd_sad64x64x4d_bits8)
1154 HIGHBD_BFP(BLOCK_16X16,
1155 vpx_highbd_sad16x16_bits8,
1156 vpx_highbd_sad16x16_avg_bits8,
1157 vpx_highbd_8_variance16x16,
1158 vpx_highbd_8_sub_pixel_variance16x16,
1159 vpx_highbd_8_sub_pixel_avg_variance16x16,
1160 vpx_highbd_sad16x16x3_bits8,
1161 vpx_highbd_sad16x16x8_bits8,
1162 vpx_highbd_sad16x16x4d_bits8)
1164 HIGHBD_BFP(BLOCK_16X8,
1165 vpx_highbd_sad16x8_bits8,
1166 vpx_highbd_sad16x8_avg_bits8,
1167 vpx_highbd_8_variance16x8,
1168 vpx_highbd_8_sub_pixel_variance16x8,
1169 vpx_highbd_8_sub_pixel_avg_variance16x8,
1170 vpx_highbd_sad16x8x3_bits8,
1171 vpx_highbd_sad16x8x8_bits8,
1172 vpx_highbd_sad16x8x4d_bits8)
1174 HIGHBD_BFP(BLOCK_8X16,
1175 vpx_highbd_sad8x16_bits8,
1176 vpx_highbd_sad8x16_avg_bits8,
1177 vpx_highbd_8_variance8x16,
1178 vpx_highbd_8_sub_pixel_variance8x16,
1179 vpx_highbd_8_sub_pixel_avg_variance8x16,
1180 vpx_highbd_sad8x16x3_bits8,
1181 vpx_highbd_sad8x16x8_bits8,
1182 vpx_highbd_sad8x16x4d_bits8)
1184 HIGHBD_BFP(BLOCK_8X8,
1185 vpx_highbd_sad8x8_bits8,
1186 vpx_highbd_sad8x8_avg_bits8,
1187 vpx_highbd_8_variance8x8,
1188 vpx_highbd_8_sub_pixel_variance8x8,
1189 vpx_highbd_8_sub_pixel_avg_variance8x8,
1190 vpx_highbd_sad8x8x3_bits8,
1191 vpx_highbd_sad8x8x8_bits8,
1192 vpx_highbd_sad8x8x4d_bits8)
1194 HIGHBD_BFP(BLOCK_8X4,
1195 vpx_highbd_sad8x4_bits8,
1196 vpx_highbd_sad8x4_avg_bits8,
1197 vpx_highbd_8_variance8x4,
1198 vpx_highbd_8_sub_pixel_variance8x4,
1199 vpx_highbd_8_sub_pixel_avg_variance8x4,
1201 vpx_highbd_sad8x4x8_bits8,
1202 vpx_highbd_sad8x4x4d_bits8)
1204 HIGHBD_BFP(BLOCK_4X8,
1205 vpx_highbd_sad4x8_bits8,
1206 vpx_highbd_sad4x8_avg_bits8,
1207 vpx_highbd_8_variance4x8,
1208 vpx_highbd_8_sub_pixel_variance4x8,
1209 vpx_highbd_8_sub_pixel_avg_variance4x8,
1211 vpx_highbd_sad4x8x8_bits8,
1212 vpx_highbd_sad4x8x4d_bits8)
1214 HIGHBD_BFP(BLOCK_4X4,
1215 vpx_highbd_sad4x4_bits8,
1216 vpx_highbd_sad4x4_avg_bits8,
1217 vpx_highbd_8_variance4x4,
1218 vpx_highbd_8_sub_pixel_variance4x4,
1219 vpx_highbd_8_sub_pixel_avg_variance4x4,
1220 vpx_highbd_sad4x4x3_bits8,
1221 vpx_highbd_sad4x4x8_bits8,
1222 vpx_highbd_sad4x4x4d_bits8)
1226 HIGHBD_BFP(BLOCK_32X16,
1227 vpx_highbd_sad32x16_bits10,
1228 vpx_highbd_sad32x16_avg_bits10,
1229 vpx_highbd_10_variance32x16,
1230 vpx_highbd_10_sub_pixel_variance32x16,
1231 vpx_highbd_10_sub_pixel_avg_variance32x16,
1234 vpx_highbd_sad32x16x4d_bits10)
1236 HIGHBD_BFP(BLOCK_16X32,
1237 vpx_highbd_sad16x32_bits10,
1238 vpx_highbd_sad16x32_avg_bits10,
1239 vpx_highbd_10_variance16x32,
1240 vpx_highbd_10_sub_pixel_variance16x32,
1241 vpx_highbd_10_sub_pixel_avg_variance16x32,
1244 vpx_highbd_sad16x32x4d_bits10)
1246 HIGHBD_BFP(BLOCK_64X32,
1247 vpx_highbd_sad64x32_bits10,
1248 vpx_highbd_sad64x32_avg_bits10,
1249 vpx_highbd_10_variance64x32,
1250 vpx_highbd_10_sub_pixel_variance64x32,
1251 vpx_highbd_10_sub_pixel_avg_variance64x32,
1254 vpx_highbd_sad64x32x4d_bits10)
1256 HIGHBD_BFP(BLOCK_32X64,
1257 vpx_highbd_sad32x64_bits10,
1258 vpx_highbd_sad32x64_avg_bits10,
1259 vpx_highbd_10_variance32x64,
1260 vpx_highbd_10_sub_pixel_variance32x64,
1261 vpx_highbd_10_sub_pixel_avg_variance32x64,
1264 vpx_highbd_sad32x64x4d_bits10)
1266 HIGHBD_BFP(BLOCK_32X32,
1267 vpx_highbd_sad32x32_bits10,
1268 vpx_highbd_sad32x32_avg_bits10,
1269 vpx_highbd_10_variance32x32,
1270 vpx_highbd_10_sub_pixel_variance32x32,
1271 vpx_highbd_10_sub_pixel_avg_variance32x32,
1272 vpx_highbd_sad32x32x3_bits10,
1273 vpx_highbd_sad32x32x8_bits10,
1274 vpx_highbd_sad32x32x4d_bits10)
1276 HIGHBD_BFP(BLOCK_64X64,
1277 vpx_highbd_sad64x64_bits10,
1278 vpx_highbd_sad64x64_avg_bits10,
1279 vpx_highbd_10_variance64x64,
1280 vpx_highbd_10_sub_pixel_variance64x64,
1281 vpx_highbd_10_sub_pixel_avg_variance64x64,
1282 vpx_highbd_sad64x64x3_bits10,
1283 vpx_highbd_sad64x64x8_bits10,
1284 vpx_highbd_sad64x64x4d_bits10)
1286 HIGHBD_BFP(BLOCK_16X16,
1287 vpx_highbd_sad16x16_bits10,
1288 vpx_highbd_sad16x16_avg_bits10,
1289 vpx_highbd_10_variance16x16,
1290 vpx_highbd_10_sub_pixel_variance16x16,
1291 vpx_highbd_10_sub_pixel_avg_variance16x16,
1292 vpx_highbd_sad16x16x3_bits10,
1293 vpx_highbd_sad16x16x8_bits10,
1294 vpx_highbd_sad16x16x4d_bits10)
1296 HIGHBD_BFP(BLOCK_16X8,
1297 vpx_highbd_sad16x8_bits10,
1298 vpx_highbd_sad16x8_avg_bits10,
1299 vpx_highbd_10_variance16x8,
1300 vpx_highbd_10_sub_pixel_variance16x8,
1301 vpx_highbd_10_sub_pixel_avg_variance16x8,
1302 vpx_highbd_sad16x8x3_bits10,
1303 vpx_highbd_sad16x8x8_bits10,
1304 vpx_highbd_sad16x8x4d_bits10)
1306 HIGHBD_BFP(BLOCK_8X16,
1307 vpx_highbd_sad8x16_bits10,
1308 vpx_highbd_sad8x16_avg_bits10,
1309 vpx_highbd_10_variance8x16,
1310 vpx_highbd_10_sub_pixel_variance8x16,
1311 vpx_highbd_10_sub_pixel_avg_variance8x16,
1312 vpx_highbd_sad8x16x3_bits10,
1313 vpx_highbd_sad8x16x8_bits10,
1314 vpx_highbd_sad8x16x4d_bits10)
1316 HIGHBD_BFP(BLOCK_8X8,
1317 vpx_highbd_sad8x8_bits10,
1318 vpx_highbd_sad8x8_avg_bits10,
1319 vpx_highbd_10_variance8x8,
1320 vpx_highbd_10_sub_pixel_variance8x8,
1321 vpx_highbd_10_sub_pixel_avg_variance8x8,
1322 vpx_highbd_sad8x8x3_bits10,
1323 vpx_highbd_sad8x8x8_bits10,
1324 vpx_highbd_sad8x8x4d_bits10)
1326 HIGHBD_BFP(BLOCK_8X4,
1327 vpx_highbd_sad8x4_bits10,
1328 vpx_highbd_sad8x4_avg_bits10,
1329 vpx_highbd_10_variance8x4,
1330 vpx_highbd_10_sub_pixel_variance8x4,
1331 vpx_highbd_10_sub_pixel_avg_variance8x4,
1333 vpx_highbd_sad8x4x8_bits10,
1334 vpx_highbd_sad8x4x4d_bits10)
1336 HIGHBD_BFP(BLOCK_4X8,
1337 vpx_highbd_sad4x8_bits10,
1338 vpx_highbd_sad4x8_avg_bits10,
1339 vpx_highbd_10_variance4x8,
1340 vpx_highbd_10_sub_pixel_variance4x8,
1341 vpx_highbd_10_sub_pixel_avg_variance4x8,
1343 vpx_highbd_sad4x8x8_bits10,
1344 vpx_highbd_sad4x8x4d_bits10)
1346 HIGHBD_BFP(BLOCK_4X4,
1347 vpx_highbd_sad4x4_bits10,
1348 vpx_highbd_sad4x4_avg_bits10,
1349 vpx_highbd_10_variance4x4,
1350 vpx_highbd_10_sub_pixel_variance4x4,
1351 vpx_highbd_10_sub_pixel_avg_variance4x4,
1352 vpx_highbd_sad4x4x3_bits10,
1353 vpx_highbd_sad4x4x8_bits10,
1354 vpx_highbd_sad4x4x4d_bits10)
1358 HIGHBD_BFP(BLOCK_32X16,
1359 vpx_highbd_sad32x16_bits12,
1360 vpx_highbd_sad32x16_avg_bits12,
1361 vpx_highbd_12_variance32x16,
1362 vpx_highbd_12_sub_pixel_variance32x16,
1363 vpx_highbd_12_sub_pixel_avg_variance32x16,
1366 vpx_highbd_sad32x16x4d_bits12)
1368 HIGHBD_BFP(BLOCK_16X32,
1369 vpx_highbd_sad16x32_bits12,
1370 vpx_highbd_sad16x32_avg_bits12,
1371 vpx_highbd_12_variance16x32,
1372 vpx_highbd_12_sub_pixel_variance16x32,
1373 vpx_highbd_12_sub_pixel_avg_variance16x32,
1376 vpx_highbd_sad16x32x4d_bits12)
1378 HIGHBD_BFP(BLOCK_64X32,
1379 vpx_highbd_sad64x32_bits12,
1380 vpx_highbd_sad64x32_avg_bits12,
1381 vpx_highbd_12_variance64x32,
1382 vpx_highbd_12_sub_pixel_variance64x32,
1383 vpx_highbd_12_sub_pixel_avg_variance64x32,
1386 vpx_highbd_sad64x32x4d_bits12)
1388 HIGHBD_BFP(BLOCK_32X64,
1389 vpx_highbd_sad32x64_bits12,
1390 vpx_highbd_sad32x64_avg_bits12,
1391 vpx_highbd_12_variance32x64,
1392 vpx_highbd_12_sub_pixel_variance32x64,
1393 vpx_highbd_12_sub_pixel_avg_variance32x64,
1396 vpx_highbd_sad32x64x4d_bits12)
1398 HIGHBD_BFP(BLOCK_32X32,
1399 vpx_highbd_sad32x32_bits12,
1400 vpx_highbd_sad32x32_avg_bits12,
1401 vpx_highbd_12_variance32x32,
1402 vpx_highbd_12_sub_pixel_variance32x32,
1403 vpx_highbd_12_sub_pixel_avg_variance32x32,
1404 vpx_highbd_sad32x32x3_bits12,
1405 vpx_highbd_sad32x32x8_bits12,
1406 vpx_highbd_sad32x32x4d_bits12)
1408 HIGHBD_BFP(BLOCK_64X64,
1409 vpx_highbd_sad64x64_bits12,
1410 vpx_highbd_sad64x64_avg_bits12,
1411 vpx_highbd_12_variance64x64,
1412 vpx_highbd_12_sub_pixel_variance64x64,
1413 vpx_highbd_12_sub_pixel_avg_variance64x64,
1414 vpx_highbd_sad64x64x3_bits12,
1415 vpx_highbd_sad64x64x8_bits12,
1416 vpx_highbd_sad64x64x4d_bits12)
1418 HIGHBD_BFP(BLOCK_16X16,
1419 vpx_highbd_sad16x16_bits12,
1420 vpx_highbd_sad16x16_avg_bits12,
1421 vpx_highbd_12_variance16x16,
1422 vpx_highbd_12_sub_pixel_variance16x16,
1423 vpx_highbd_12_sub_pixel_avg_variance16x16,
1424 vpx_highbd_sad16x16x3_bits12,
1425 vpx_highbd_sad16x16x8_bits12,
1426 vpx_highbd_sad16x16x4d_bits12)
1428 HIGHBD_BFP(BLOCK_16X8,
1429 vpx_highbd_sad16x8_bits12,
1430 vpx_highbd_sad16x8_avg_bits12,
1431 vpx_highbd_12_variance16x8,
1432 vpx_highbd_12_sub_pixel_variance16x8,
1433 vpx_highbd_12_sub_pixel_avg_variance16x8,
1434 vpx_highbd_sad16x8x3_bits12,
1435 vpx_highbd_sad16x8x8_bits12,
1436 vpx_highbd_sad16x8x4d_bits12)
1438 HIGHBD_BFP(BLOCK_8X16,
1439 vpx_highbd_sad8x16_bits12,
1440 vpx_highbd_sad8x16_avg_bits12,
1441 vpx_highbd_12_variance8x16,
1442 vpx_highbd_12_sub_pixel_variance8x16,
1443 vpx_highbd_12_sub_pixel_avg_variance8x16,
1444 vpx_highbd_sad8x16x3_bits12,
1445 vpx_highbd_sad8x16x8_bits12,
1446 vpx_highbd_sad8x16x4d_bits12)
1448 HIGHBD_BFP(BLOCK_8X8,
1449 vpx_highbd_sad8x8_bits12,
1450 vpx_highbd_sad8x8_avg_bits12,
1451 vpx_highbd_12_variance8x8,
1452 vpx_highbd_12_sub_pixel_variance8x8,
1453 vpx_highbd_12_sub_pixel_avg_variance8x8,
1454 vpx_highbd_sad8x8x3_bits12,
1455 vpx_highbd_sad8x8x8_bits12,
1456 vpx_highbd_sad8x8x4d_bits12)
1458 HIGHBD_BFP(BLOCK_8X4,
1459 vpx_highbd_sad8x4_bits12,
1460 vpx_highbd_sad8x4_avg_bits12,
1461 vpx_highbd_12_variance8x4,
1462 vpx_highbd_12_sub_pixel_variance8x4,
1463 vpx_highbd_12_sub_pixel_avg_variance8x4,
1465 vpx_highbd_sad8x4x8_bits12,
1466 vpx_highbd_sad8x4x4d_bits12)
1468 HIGHBD_BFP(BLOCK_4X8,
1469 vpx_highbd_sad4x8_bits12,
1470 vpx_highbd_sad4x8_avg_bits12,
1471 vpx_highbd_12_variance4x8,
1472 vpx_highbd_12_sub_pixel_variance4x8,
1473 vpx_highbd_12_sub_pixel_avg_variance4x8,
1475 vpx_highbd_sad4x8x8_bits12,
1476 vpx_highbd_sad4x8x4d_bits12)
1478 HIGHBD_BFP(BLOCK_4X4,
1479 vpx_highbd_sad4x4_bits12,
1480 vpx_highbd_sad4x4_avg_bits12,
1481 vpx_highbd_12_variance4x4,
1482 vpx_highbd_12_sub_pixel_variance4x4,
1483 vpx_highbd_12_sub_pixel_avg_variance4x4,
1484 vpx_highbd_sad4x4x3_bits12,
1485 vpx_highbd_sad4x4x8_bits12,
1486 vpx_highbd_sad4x4x4d_bits12)
1490 assert(0 && "cm->bit_depth should be VPX_BITS_8, "
1491 "VPX_BITS_10 or VPX_BITS_12");
1495 #endif // CONFIG_VP9_HIGHBITDEPTH
1497 static void realloc_segmentation_maps(VP9_COMP *cpi) {
1498 VP9_COMMON *const cm = &cpi->common;
1500 // Create the encoder segmentation map and set all entries to 0
1501 vpx_free(cpi->segmentation_map);
1502 CHECK_MEM_ERROR(cm, cpi->segmentation_map,
1503 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1505 // Create a map used for cyclic background refresh.
1506 if (cpi->cyclic_refresh)
1507 vp9_cyclic_refresh_free(cpi->cyclic_refresh);
1508 CHECK_MEM_ERROR(cm, cpi->cyclic_refresh,
1509 vp9_cyclic_refresh_alloc(cm->mi_rows, cm->mi_cols));
1511 // Create a map used to mark inactive areas.
1512 vpx_free(cpi->active_map.map);
1513 CHECK_MEM_ERROR(cm, cpi->active_map.map,
1514 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1516 // And a place holder structure is the coding context
1517 // for use if we want to save and restore it
1518 vpx_free(cpi->coding_context.last_frame_seg_map_copy);
1519 CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
1520 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1523 void vp9_change_config(struct VP9_COMP *cpi, const VP9EncoderConfig *oxcf) {
1524 VP9_COMMON *const cm = &cpi->common;
1525 RATE_CONTROL *const rc = &cpi->rc;
1526 int last_w = cpi->oxcf.width;
1527 int last_h = cpi->oxcf.height;
1529 if (cm->profile != oxcf->profile)
1530 cm->profile = oxcf->profile;
1531 cm->bit_depth = oxcf->bit_depth;
1532 cm->color_space = oxcf->color_space;
1533 cm->color_range = oxcf->color_range;
1535 cpi->target_level = oxcf->target_level;
1536 cpi->keep_level_stats = oxcf->target_level != LEVEL_MAX;
1538 if (cm->profile <= PROFILE_1)
1539 assert(cm->bit_depth == VPX_BITS_8);
1541 assert(cm->bit_depth > VPX_BITS_8);
1544 #if CONFIG_VP9_HIGHBITDEPTH
1545 cpi->td.mb.e_mbd.bd = (int)cm->bit_depth;
1546 #endif // CONFIG_VP9_HIGHBITDEPTH
1548 if ((oxcf->pass == 0) && (oxcf->rc_mode == VPX_Q)) {
1549 rc->baseline_gf_interval = FIXED_GF_INTERVAL;
1551 rc->baseline_gf_interval = (MIN_GF_INTERVAL + MAX_GF_INTERVAL) / 2;
1554 cpi->refresh_golden_frame = 0;
1555 cpi->refresh_last_frame = 1;
1556 cm->refresh_frame_context = 1;
1557 cm->reset_frame_context = 0;
1559 vp9_reset_segment_features(&cm->seg);
1560 vp9_set_high_precision_mv(cpi, 0);
1565 for (i = 0; i < MAX_SEGMENTS; i++)
1566 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1568 cpi->encode_breakout = cpi->oxcf.encode_breakout;
1570 set_rc_buffer_sizes(rc, &cpi->oxcf);
1572 // Under a configuration change, where maximum_buffer_size may change,
1573 // keep buffer level clipped to the maximum allowed buffer size.
1574 rc->bits_off_target = VPXMIN(rc->bits_off_target, rc->maximum_buffer_size);
1575 rc->buffer_level = VPXMIN(rc->buffer_level, rc->maximum_buffer_size);
1577 // Set up frame rate and related parameters rate control values.
1578 vp9_new_framerate(cpi, cpi->framerate);
1580 // Set absolute upper and lower quality limits
1581 rc->worst_quality = cpi->oxcf.worst_allowed_q;
1582 rc->best_quality = cpi->oxcf.best_allowed_q;
1584 cm->interp_filter = cpi->sf.default_interp_filter;
1586 if (cpi->oxcf.render_width > 0 && cpi->oxcf.render_height > 0) {
1587 cm->render_width = cpi->oxcf.render_width;
1588 cm->render_height = cpi->oxcf.render_height;
1590 cm->render_width = cpi->oxcf.width;
1591 cm->render_height = cpi->oxcf.height;
1593 if (last_w != cpi->oxcf.width || last_h != cpi->oxcf.height) {
1594 cm->width = cpi->oxcf.width;
1595 cm->height = cpi->oxcf.height;
1596 cpi->external_resize = 1;
1599 if (cpi->initial_width) {
1600 int new_mi_size = 0;
1601 vp9_set_mb_mi(cm, cm->width, cm->height);
1602 new_mi_size = cm->mi_stride * calc_mi_size(cm->mi_rows);
1603 if (cm->mi_alloc_size < new_mi_size) {
1604 vp9_free_context_buffers(cm);
1605 alloc_compressor_data(cpi);
1606 realloc_segmentation_maps(cpi);
1607 cpi->initial_width = cpi->initial_height = 0;
1608 cpi->external_resize = 0;
1609 } else if (cm->mi_alloc_size == new_mi_size &&
1610 (cpi->oxcf.width > last_w || cpi->oxcf.height > last_h)) {
1611 vp9_alloc_loop_filter(cm);
1615 update_frame_size(cpi);
1617 if (last_w != cpi->oxcf.width || last_h != cpi->oxcf.height) {
1618 memset(cpi->consec_zero_mv, 0,
1619 cm->mi_rows * cm->mi_cols * sizeof(*cpi->consec_zero_mv));
1620 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1621 vp9_cyclic_refresh_reset_resize(cpi);
1624 if ((cpi->svc.number_temporal_layers > 1 &&
1625 cpi->oxcf.rc_mode == VPX_CBR) ||
1626 ((cpi->svc.number_temporal_layers > 1 ||
1627 cpi->svc.number_spatial_layers > 1) &&
1628 cpi->oxcf.pass != 1)) {
1629 vp9_update_layer_context_change_config(cpi,
1630 (int)cpi->oxcf.target_bandwidth);
1633 cpi->alt_ref_source = NULL;
1634 rc->is_src_frame_alt_ref = 0;
1637 // Experimental RD Code
1638 cpi->frame_distortion = 0;
1639 cpi->last_frame_distortion = 0;
1642 set_tile_limits(cpi);
1644 cpi->ext_refresh_frame_flags_pending = 0;
1645 cpi->ext_refresh_frame_context_pending = 0;
1647 #if CONFIG_VP9_HIGHBITDEPTH
1648 highbd_set_var_fns(cpi);
1653 #define M_LOG2_E 0.693147180559945309417
1655 #define log2f(x) (log (x) / (float) M_LOG2_E)
1657 /***********************************************************************
1658 * Read before modifying 'cal_nmvjointsadcost' or 'cal_nmvsadcosts' *
1659 ***********************************************************************
1660 * The following 2 functions ('cal_nmvjointsadcost' and *
1661 * 'cal_nmvsadcosts') are used to calculate cost lookup tables *
1662 * used by 'vp9_diamond_search_sad'. The C implementation of the *
1663 * function is generic, but the AVX intrinsics optimised version *
1664 * relies on the following properties of the computed tables: *
1665 * For cal_nmvjointsadcost: *
1666 * - mvjointsadcost[1] == mvjointsadcost[2] == mvjointsadcost[3] *
1667 * For cal_nmvsadcosts: *
1668 * - For all i: mvsadcost[0][i] == mvsadcost[1][i] *
1669 * (Equal costs for both components) *
1670 * - For all i: mvsadcost[0][i] == mvsadcost[0][-i] *
1671 * (Cost function is even) *
1672 * If these do not hold, then the AVX optimised version of the *
1673 * 'vp9_diamond_search_sad' function cannot be used as it is, in which *
1674 * case you can revert to using the C function instead. *
1675 ***********************************************************************/
1677 static void cal_nmvjointsadcost(int *mvjointsadcost) {
1678 /*********************************************************************
1679 * Warning: Read the comments above before modifying this function *
1680 *********************************************************************/
1681 mvjointsadcost[0] = 600;
1682 mvjointsadcost[1] = 300;
1683 mvjointsadcost[2] = 300;
1684 mvjointsadcost[3] = 300;
1687 static void cal_nmvsadcosts(int *mvsadcost[2]) {
1688 /*********************************************************************
1689 * Warning: Read the comments above before modifying this function *
1690 *********************************************************************/
1693 mvsadcost[0][0] = 0;
1694 mvsadcost[1][0] = 0;
1697 double z = 256 * (2 * (log2f(8 * i) + .6));
1698 mvsadcost[0][i] = (int)z;
1699 mvsadcost[1][i] = (int)z;
1700 mvsadcost[0][-i] = (int)z;
1701 mvsadcost[1][-i] = (int)z;
1702 } while (++i <= MV_MAX);
1705 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
1708 mvsadcost[0][0] = 0;
1709 mvsadcost[1][0] = 0;
1712 double z = 256 * (2 * (log2f(8 * i) + .6));
1713 mvsadcost[0][i] = (int)z;
1714 mvsadcost[1][i] = (int)z;
1715 mvsadcost[0][-i] = (int)z;
1716 mvsadcost[1][-i] = (int)z;
1717 } while (++i <= MV_MAX);
1720 VP9_COMP *vp9_create_compressor(VP9EncoderConfig *oxcf,
1721 BufferPool *const pool) {
1723 VP9_COMP *volatile const cpi = vpx_memalign(32, sizeof(VP9_COMP));
1724 VP9_COMMON *volatile const cm = cpi != NULL ? &cpi->common : NULL;
1731 if (setjmp(cm->error.jmp)) {
1732 cm->error.setjmp = 0;
1733 vp9_remove_compressor(cpi);
1737 cm->error.setjmp = 1;
1738 cm->alloc_mi = vp9_enc_alloc_mi;
1739 cm->free_mi = vp9_enc_free_mi;
1740 cm->setup_mi = vp9_enc_setup_mi;
1742 CHECK_MEM_ERROR(cm, cm->fc,
1743 (FRAME_CONTEXT *)vpx_calloc(1, sizeof(*cm->fc)));
1744 CHECK_MEM_ERROR(cm, cm->frame_contexts,
1745 (FRAME_CONTEXT *)vpx_calloc(FRAME_CONTEXTS,
1746 sizeof(*cm->frame_contexts)));
1749 cpi->resize_state = 0;
1750 cpi->external_resize = 0;
1751 cpi->resize_avg_qp = 0;
1752 cpi->resize_buffer_underflow = 0;
1753 cpi->use_skin_detection = 0;
1754 cpi->common.buffer_pool = pool;
1756 init_config(cpi, oxcf);
1757 vp9_rc_init(&cpi->oxcf, oxcf->pass, &cpi->rc);
1759 cm->current_video_frame = 0;
1760 cpi->partition_search_skippable_frame = 0;
1761 cpi->tile_data = NULL;
1763 realloc_segmentation_maps(cpi);
1765 CHECK_MEM_ERROR(cm, cpi->consec_zero_mv,
1766 vpx_calloc(cm->mi_rows * cm->mi_cols,
1767 sizeof(*cpi->consec_zero_mv)));
1769 CHECK_MEM_ERROR(cm, cpi->nmvcosts[0],
1770 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts[0])));
1771 CHECK_MEM_ERROR(cm, cpi->nmvcosts[1],
1772 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts[1])));
1773 CHECK_MEM_ERROR(cm, cpi->nmvcosts_hp[0],
1774 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts_hp[0])));
1775 CHECK_MEM_ERROR(cm, cpi->nmvcosts_hp[1],
1776 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts_hp[1])));
1777 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts[0],
1778 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts[0])));
1779 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts[1],
1780 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts[1])));
1781 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts_hp[0],
1782 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts_hp[0])));
1783 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts_hp[1],
1784 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts_hp[1])));
1786 for (i = 0; i < (sizeof(cpi->mbgraph_stats) /
1787 sizeof(cpi->mbgraph_stats[0])); i++) {
1788 CHECK_MEM_ERROR(cm, cpi->mbgraph_stats[i].mb_stats,
1789 vpx_calloc(cm->MBs *
1790 sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
1793 #if CONFIG_FP_MB_STATS
1794 cpi->use_fp_mb_stats = 0;
1795 if (cpi->use_fp_mb_stats) {
1796 // a place holder used to store the first pass mb stats in the first pass
1797 CHECK_MEM_ERROR(cm, cpi->twopass.frame_mb_stats_buf,
1798 vpx_calloc(cm->MBs * sizeof(uint8_t), 1));
1800 cpi->twopass.frame_mb_stats_buf = NULL;
1804 cpi->refresh_alt_ref_frame = 0;
1805 cpi->multi_arf_last_grp_enabled = 0;
1807 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1809 init_level_info(&cpi->level_info);
1811 #if CONFIG_INTERNAL_STATS
1812 cpi->b_calculate_blockiness = 1;
1813 cpi->b_calculate_consistency = 1;
1814 cpi->total_inconsistency = 0;
1815 cpi->psnr.worst = 100.0;
1816 cpi->worst_ssim = 100.0;
1821 if (cpi->b_calculate_psnr) {
1822 cpi->total_sq_error = 0;
1823 cpi->total_samples = 0;
1825 cpi->totalp_sq_error = 0;
1826 cpi->totalp_samples = 0;
1828 cpi->tot_recode_hits = 0;
1829 cpi->summed_quality = 0;
1830 cpi->summed_weights = 0;
1831 cpi->summedp_quality = 0;
1832 cpi->summedp_weights = 0;
1835 cpi->fastssim.worst = 100.0;
1837 cpi->psnrhvs.worst = 100.0;
1839 if (cpi->b_calculate_blockiness) {
1840 cpi->total_blockiness = 0;
1841 cpi->worst_blockiness = 0.0;
1844 if (cpi->b_calculate_consistency) {
1845 CHECK_MEM_ERROR(cm, cpi->ssim_vars,
1846 vpx_malloc(sizeof(*cpi->ssim_vars) * 4 *
1847 cpi->common.mi_rows * cpi->common.mi_cols));
1848 cpi->worst_consistency = 100.0;
1853 cpi->first_time_stamp_ever = INT64_MAX;
1855 /*********************************************************************
1856 * Warning: Read the comments around 'cal_nmvjointsadcost' and *
1857 * 'cal_nmvsadcosts' before modifying how these tables are computed. *
1858 *********************************************************************/
1859 cal_nmvjointsadcost(cpi->td.mb.nmvjointsadcost);
1860 cpi->td.mb.nmvcost[0] = &cpi->nmvcosts[0][MV_MAX];
1861 cpi->td.mb.nmvcost[1] = &cpi->nmvcosts[1][MV_MAX];
1862 cpi->td.mb.nmvsadcost[0] = &cpi->nmvsadcosts[0][MV_MAX];
1863 cpi->td.mb.nmvsadcost[1] = &cpi->nmvsadcosts[1][MV_MAX];
1864 cal_nmvsadcosts(cpi->td.mb.nmvsadcost);
1866 cpi->td.mb.nmvcost_hp[0] = &cpi->nmvcosts_hp[0][MV_MAX];
1867 cpi->td.mb.nmvcost_hp[1] = &cpi->nmvcosts_hp[1][MV_MAX];
1868 cpi->td.mb.nmvsadcost_hp[0] = &cpi->nmvsadcosts_hp[0][MV_MAX];
1869 cpi->td.mb.nmvsadcost_hp[1] = &cpi->nmvsadcosts_hp[1][MV_MAX];
1870 cal_nmvsadcosts_hp(cpi->td.mb.nmvsadcost_hp);
1872 #if CONFIG_VP9_TEMPORAL_DENOISING
1873 #ifdef OUTPUT_YUV_DENOISED
1874 yuv_denoised_file = fopen("denoised.yuv", "ab");
1877 #ifdef OUTPUT_YUV_SKINMAP
1878 yuv_skinmap_file = fopen("skinmap.yuv", "ab");
1880 #ifdef OUTPUT_YUV_REC
1881 yuv_rec_file = fopen("rec.yuv", "wb");
1885 framepsnr = fopen("framepsnr.stt", "a");
1886 kf_list = fopen("kf_list.stt", "w");
1889 cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
1891 if (oxcf->pass == 1) {
1892 vp9_init_first_pass(cpi);
1893 } else if (oxcf->pass == 2) {
1894 const size_t packet_sz = sizeof(FIRSTPASS_STATS);
1895 const int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
1897 if (cpi->svc.number_spatial_layers > 1
1898 || cpi->svc.number_temporal_layers > 1) {
1899 FIRSTPASS_STATS *const stats = oxcf->two_pass_stats_in.buf;
1900 FIRSTPASS_STATS *stats_copy[VPX_SS_MAX_LAYERS] = {0};
1903 for (i = 0; i < oxcf->ss_number_layers; ++i) {
1904 FIRSTPASS_STATS *const last_packet_for_layer =
1905 &stats[packets - oxcf->ss_number_layers + i];
1906 const int layer_id = (int)last_packet_for_layer->spatial_layer_id;
1907 const int packets_in_layer = (int)last_packet_for_layer->count + 1;
1908 if (layer_id >= 0 && layer_id < oxcf->ss_number_layers) {
1909 LAYER_CONTEXT *const lc = &cpi->svc.layer_context[layer_id];
1911 vpx_free(lc->rc_twopass_stats_in.buf);
1913 lc->rc_twopass_stats_in.sz = packets_in_layer * packet_sz;
1914 CHECK_MEM_ERROR(cm, lc->rc_twopass_stats_in.buf,
1915 vpx_malloc(lc->rc_twopass_stats_in.sz));
1916 lc->twopass.stats_in_start = lc->rc_twopass_stats_in.buf;
1917 lc->twopass.stats_in = lc->twopass.stats_in_start;
1918 lc->twopass.stats_in_end = lc->twopass.stats_in_start
1919 + packets_in_layer - 1;
1920 stats_copy[layer_id] = lc->rc_twopass_stats_in.buf;
1924 for (i = 0; i < packets; ++i) {
1925 const int layer_id = (int)stats[i].spatial_layer_id;
1926 if (layer_id >= 0 && layer_id < oxcf->ss_number_layers
1927 && stats_copy[layer_id] != NULL) {
1928 *stats_copy[layer_id] = stats[i];
1929 ++stats_copy[layer_id];
1933 vp9_init_second_pass_spatial_svc(cpi);
1935 #if CONFIG_FP_MB_STATS
1936 if (cpi->use_fp_mb_stats) {
1937 const size_t psz = cpi->common.MBs * sizeof(uint8_t);
1938 const int ps = (int)(oxcf->firstpass_mb_stats_in.sz / psz);
1940 cpi->twopass.firstpass_mb_stats.mb_stats_start =
1941 oxcf->firstpass_mb_stats_in.buf;
1942 cpi->twopass.firstpass_mb_stats.mb_stats_end =
1943 cpi->twopass.firstpass_mb_stats.mb_stats_start +
1944 (ps - 1) * cpi->common.MBs * sizeof(uint8_t);
1948 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1949 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1950 cpi->twopass.stats_in_end = &cpi->twopass.stats_in[packets - 1];
1952 vp9_init_second_pass(cpi);
1956 vp9_set_speed_features_framesize_independent(cpi);
1957 vp9_set_speed_features_framesize_dependent(cpi);
1959 // Allocate memory to store variances for a frame.
1960 CHECK_MEM_ERROR(cm, cpi->source_diff_var,
1961 vpx_calloc(cm->MBs, sizeof(diff)));
1962 cpi->source_var_thresh = 0;
1963 cpi->frames_till_next_var_check = 0;
1965 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF)\
1966 cpi->fn_ptr[BT].sdf = SDF; \
1967 cpi->fn_ptr[BT].sdaf = SDAF; \
1968 cpi->fn_ptr[BT].vf = VF; \
1969 cpi->fn_ptr[BT].svf = SVF; \
1970 cpi->fn_ptr[BT].svaf = SVAF; \
1971 cpi->fn_ptr[BT].sdx3f = SDX3F; \
1972 cpi->fn_ptr[BT].sdx8f = SDX8F; \
1973 cpi->fn_ptr[BT].sdx4df = SDX4DF;
1975 BFP(BLOCK_32X16, vpx_sad32x16, vpx_sad32x16_avg,
1976 vpx_variance32x16, vpx_sub_pixel_variance32x16,
1977 vpx_sub_pixel_avg_variance32x16, NULL, NULL, vpx_sad32x16x4d)
1979 BFP(BLOCK_16X32, vpx_sad16x32, vpx_sad16x32_avg,
1980 vpx_variance16x32, vpx_sub_pixel_variance16x32,
1981 vpx_sub_pixel_avg_variance16x32, NULL, NULL, vpx_sad16x32x4d)
1983 BFP(BLOCK_64X32, vpx_sad64x32, vpx_sad64x32_avg,
1984 vpx_variance64x32, vpx_sub_pixel_variance64x32,
1985 vpx_sub_pixel_avg_variance64x32, NULL, NULL, vpx_sad64x32x4d)
1987 BFP(BLOCK_32X64, vpx_sad32x64, vpx_sad32x64_avg,
1988 vpx_variance32x64, vpx_sub_pixel_variance32x64,
1989 vpx_sub_pixel_avg_variance32x64, NULL, NULL, vpx_sad32x64x4d)
1991 BFP(BLOCK_32X32, vpx_sad32x32, vpx_sad32x32_avg,
1992 vpx_variance32x32, vpx_sub_pixel_variance32x32,
1993 vpx_sub_pixel_avg_variance32x32, vpx_sad32x32x3, vpx_sad32x32x8,
1996 BFP(BLOCK_64X64, vpx_sad64x64, vpx_sad64x64_avg,
1997 vpx_variance64x64, vpx_sub_pixel_variance64x64,
1998 vpx_sub_pixel_avg_variance64x64, vpx_sad64x64x3, vpx_sad64x64x8,
2001 BFP(BLOCK_16X16, vpx_sad16x16, vpx_sad16x16_avg,
2002 vpx_variance16x16, vpx_sub_pixel_variance16x16,
2003 vpx_sub_pixel_avg_variance16x16, vpx_sad16x16x3, vpx_sad16x16x8,
2006 BFP(BLOCK_16X8, vpx_sad16x8, vpx_sad16x8_avg,
2007 vpx_variance16x8, vpx_sub_pixel_variance16x8,
2008 vpx_sub_pixel_avg_variance16x8,
2009 vpx_sad16x8x3, vpx_sad16x8x8, vpx_sad16x8x4d)
2011 BFP(BLOCK_8X16, vpx_sad8x16, vpx_sad8x16_avg,
2012 vpx_variance8x16, vpx_sub_pixel_variance8x16,
2013 vpx_sub_pixel_avg_variance8x16,
2014 vpx_sad8x16x3, vpx_sad8x16x8, vpx_sad8x16x4d)
2016 BFP(BLOCK_8X8, vpx_sad8x8, vpx_sad8x8_avg,
2017 vpx_variance8x8, vpx_sub_pixel_variance8x8,
2018 vpx_sub_pixel_avg_variance8x8,
2019 vpx_sad8x8x3, vpx_sad8x8x8, vpx_sad8x8x4d)
2021 BFP(BLOCK_8X4, vpx_sad8x4, vpx_sad8x4_avg,
2022 vpx_variance8x4, vpx_sub_pixel_variance8x4,
2023 vpx_sub_pixel_avg_variance8x4, NULL, vpx_sad8x4x8, vpx_sad8x4x4d)
2025 BFP(BLOCK_4X8, vpx_sad4x8, vpx_sad4x8_avg,
2026 vpx_variance4x8, vpx_sub_pixel_variance4x8,
2027 vpx_sub_pixel_avg_variance4x8, NULL, vpx_sad4x8x8, vpx_sad4x8x4d)
2029 BFP(BLOCK_4X4, vpx_sad4x4, vpx_sad4x4_avg,
2030 vpx_variance4x4, vpx_sub_pixel_variance4x4,
2031 vpx_sub_pixel_avg_variance4x4,
2032 vpx_sad4x4x3, vpx_sad4x4x8, vpx_sad4x4x4d)
2034 #if CONFIG_VP9_HIGHBITDEPTH
2035 highbd_set_var_fns(cpi);
2038 /* vp9_init_quantizer() is first called here. Add check in
2039 * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
2040 * called later when needed. This will avoid unnecessary calls of
2041 * vp9_init_quantizer() for every frame.
2043 vp9_init_quantizer(cpi);
2045 vp9_loop_filter_init(cm);
2047 cm->error.setjmp = 0;
2052 #if CONFIG_INTERNAL_STATS
2053 #define SNPRINT(H, T) \
2054 snprintf((H) + strlen(H), sizeof(H) - strlen(H), (T))
2056 #define SNPRINT2(H, T, V) \
2057 snprintf((H) + strlen(H), sizeof(H) - strlen(H), (T), (V))
2058 #endif // CONFIG_INTERNAL_STATS
2060 void vp9_remove_compressor(VP9_COMP *cpi) {
2069 if (cm->current_video_frame > 0) {
2070 #if CONFIG_INTERNAL_STATS
2071 vpx_clear_system_state();
2073 if (cpi->oxcf.pass != 1) {
2074 char headings[512] = {0};
2075 char results[512] = {0};
2076 FILE *f = fopen("opsnr.stt", "a");
2077 double time_encoded = (cpi->last_end_time_stamp_seen
2078 - cpi->first_time_stamp_ever) / 10000000.000;
2079 double total_encode_time = (cpi->time_receive_data +
2080 cpi->time_compress_data) / 1000.000;
2082 (double)cpi->bytes * (double) 8 / (double)1000 / time_encoded;
2083 const double peak = (double)((1 << cpi->oxcf.input_bit_depth) - 1);
2084 const double target_rate = (double)cpi->oxcf.target_bandwidth / 1000;
2085 const double rate_err = ((100.0 * (dr - target_rate)) / target_rate);
2087 if (cpi->b_calculate_psnr) {
2088 const double total_psnr =
2089 vpx_sse_to_psnr((double)cpi->total_samples, peak,
2090 (double)cpi->total_sq_error);
2091 const double totalp_psnr =
2092 vpx_sse_to_psnr((double)cpi->totalp_samples, peak,
2093 (double)cpi->totalp_sq_error);
2094 const double total_ssim = 100 * pow(cpi->summed_quality /
2095 cpi->summed_weights, 8.0);
2096 const double totalp_ssim = 100 * pow(cpi->summedp_quality /
2097 cpi->summedp_weights, 8.0);
2099 snprintf(headings, sizeof(headings),
2100 "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
2101 "VPXSSIM\tVPSSIMP\tFASTSIM\tPSNRHVS\t"
2102 "WstPsnr\tWstSsim\tWstFast\tWstHVS");
2103 snprintf(results, sizeof(results),
2104 "%7.2f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2105 "%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
2106 "%7.3f\t%7.3f\t%7.3f\t%7.3f",
2107 dr, cpi->psnr.stat[ALL] / cpi->count, total_psnr,
2108 cpi->psnrp.stat[ALL] / cpi->count, totalp_psnr,
2109 total_ssim, totalp_ssim,
2110 cpi->fastssim.stat[ALL] / cpi->count,
2111 cpi->psnrhvs.stat[ALL] / cpi->count,
2112 cpi->psnr.worst, cpi->worst_ssim, cpi->fastssim.worst,
2113 cpi->psnrhvs.worst);
2115 if (cpi->b_calculate_blockiness) {
2116 SNPRINT(headings, "\t Block\tWstBlck");
2117 SNPRINT2(results, "\t%7.3f", cpi->total_blockiness / cpi->count);
2118 SNPRINT2(results, "\t%7.3f", cpi->worst_blockiness);
2121 if (cpi->b_calculate_consistency) {
2122 double consistency =
2123 vpx_sse_to_psnr((double)cpi->totalp_samples, peak,
2124 (double)cpi->total_inconsistency);
2126 SNPRINT(headings, "\tConsist\tWstCons");
2127 SNPRINT2(results, "\t%7.3f", consistency);
2128 SNPRINT2(results, "\t%7.3f", cpi->worst_consistency);
2130 fprintf(f, "%s\t Time Rc-Err Abs Err\n", headings);
2131 fprintf(f, "%s\t%8.0f %7.2f %7.2f\n", results,
2132 total_encode_time, rate_err, fabs(rate_err));
2142 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
2143 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
2144 printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
2145 cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
2146 cpi->time_compress_data / 1000,
2147 (cpi->time_receive_data + cpi->time_compress_data) / 1000);
2152 #if CONFIG_VP9_TEMPORAL_DENOISING
2153 vp9_denoiser_free(&(cpi->denoiser));
2156 for (t = 0; t < cpi->num_workers; ++t) {
2157 VPxWorker *const worker = &cpi->workers[t];
2158 EncWorkerData *const thread_data = &cpi->tile_thr_data[t];
2160 // Deallocate allocated threads.
2161 vpx_get_worker_interface()->end(worker);
2163 // Deallocate allocated thread data.
2164 if (t < cpi->num_workers - 1) {
2165 vpx_free(thread_data->td->counts);
2166 vp9_free_pc_tree(thread_data->td);
2167 vpx_free(thread_data->td);
2170 vpx_free(cpi->tile_thr_data);
2171 vpx_free(cpi->workers);
2173 if (cpi->num_workers > 1)
2174 vp9_loop_filter_dealloc(&cpi->lf_row_sync);
2176 dealloc_compressor_data(cpi);
2178 for (i = 0; i < sizeof(cpi->mbgraph_stats) /
2179 sizeof(cpi->mbgraph_stats[0]); ++i) {
2180 vpx_free(cpi->mbgraph_stats[i].mb_stats);
2183 #if CONFIG_FP_MB_STATS
2184 if (cpi->use_fp_mb_stats) {
2185 vpx_free(cpi->twopass.frame_mb_stats_buf);
2186 cpi->twopass.frame_mb_stats_buf = NULL;
2190 vp9_remove_common(cm);
2191 vp9_free_ref_frame_buffers(cm->buffer_pool);
2192 #if CONFIG_VP9_POSTPROC
2193 vp9_free_postproc_buffers(cm);
2197 #if CONFIG_VP9_TEMPORAL_DENOISING
2198 #ifdef OUTPUT_YUV_DENOISED
2199 fclose(yuv_denoised_file);
2202 #ifdef OUTPUT_YUV_SKINMAP
2203 fclose(yuv_skinmap_file);
2205 #ifdef OUTPUT_YUV_REC
2206 fclose(yuv_rec_file);
2223 static void generate_psnr_packet(VP9_COMP *cpi) {
2224 struct vpx_codec_cx_pkt pkt;
2227 #if CONFIG_VP9_HIGHBITDEPTH
2228 vpx_calc_highbd_psnr(cpi->Source, cpi->common.frame_to_show, &psnr,
2229 cpi->td.mb.e_mbd.bd, cpi->oxcf.input_bit_depth);
2231 vpx_calc_psnr(cpi->Source, cpi->common.frame_to_show, &psnr);
2234 for (i = 0; i < 4; ++i) {
2235 pkt.data.psnr.samples[i] = psnr.samples[i];
2236 pkt.data.psnr.sse[i] = psnr.sse[i];
2237 pkt.data.psnr.psnr[i] = psnr.psnr[i];
2239 pkt.kind = VPX_CODEC_PSNR_PKT;
2241 cpi->svc.layer_context[cpi->svc.spatial_layer_id *
2242 cpi->svc.number_temporal_layers].psnr_pkt = pkt.data.psnr;
2244 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2247 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags) {
2248 if (ref_frame_flags > 7)
2251 cpi->ref_frame_flags = ref_frame_flags;
2255 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags) {
2256 cpi->ext_refresh_golden_frame = (ref_frame_flags & VP9_GOLD_FLAG) != 0;
2257 cpi->ext_refresh_alt_ref_frame = (ref_frame_flags & VP9_ALT_FLAG) != 0;
2258 cpi->ext_refresh_last_frame = (ref_frame_flags & VP9_LAST_FLAG) != 0;
2259 cpi->ext_refresh_frame_flags_pending = 1;
2262 static YV12_BUFFER_CONFIG *get_vp9_ref_frame_buffer(VP9_COMP *cpi,
2263 VP9_REFFRAME ref_frame_flag) {
2264 MV_REFERENCE_FRAME ref_frame = NONE;
2265 if (ref_frame_flag == VP9_LAST_FLAG)
2266 ref_frame = LAST_FRAME;
2267 else if (ref_frame_flag == VP9_GOLD_FLAG)
2268 ref_frame = GOLDEN_FRAME;
2269 else if (ref_frame_flag == VP9_ALT_FLAG)
2270 ref_frame = ALTREF_FRAME;
2272 return ref_frame == NONE ? NULL : get_ref_frame_buffer(cpi, ref_frame);
2275 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
2276 YV12_BUFFER_CONFIG *sd) {
2277 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2279 vp8_yv12_copy_frame(cfg, sd);
2286 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
2287 YV12_BUFFER_CONFIG *sd) {
2288 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2290 vp8_yv12_copy_frame(sd, cfg);
2297 int vp9_update_entropy(VP9_COMP * cpi, int update) {
2298 cpi->ext_refresh_frame_context = update;
2299 cpi->ext_refresh_frame_context_pending = 1;
2303 #if defined(OUTPUT_YUV_DENOISED) || defined(OUTPUT_YUV_SKINMAP)
2304 // The denoiser buffer is allocated as a YUV 440 buffer. This function writes it
2305 // as YUV 420. We simply use the top-left pixels of the UV buffers, since we do
2306 // not denoise the UV channels at this time. If ever we implement UV channel
2307 // denoising we will have to modify this.
2308 void vp9_write_yuv_frame_420(YV12_BUFFER_CONFIG *s, FILE *f) {
2309 uint8_t *src = s->y_buffer;
2310 int h = s->y_height;
2313 fwrite(src, s->y_width, 1, f);
2321 fwrite(src, s->uv_width, 1, f);
2322 src += s->uv_stride;
2329 fwrite(src, s->uv_width, 1, f);
2330 src += s->uv_stride;
2335 #ifdef OUTPUT_YUV_REC
2336 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
2337 YV12_BUFFER_CONFIG *s = cm->frame_to_show;
2338 uint8_t *src = s->y_buffer;
2341 #if CONFIG_VP9_HIGHBITDEPTH
2342 if (s->flags & YV12_FLAG_HIGHBITDEPTH) {
2343 uint16_t *src16 = CONVERT_TO_SHORTPTR(s->y_buffer);
2346 fwrite(src16, s->y_width, 2, yuv_rec_file);
2347 src16 += s->y_stride;
2350 src16 = CONVERT_TO_SHORTPTR(s->u_buffer);
2354 fwrite(src16, s->uv_width, 2, yuv_rec_file);
2355 src16 += s->uv_stride;
2358 src16 = CONVERT_TO_SHORTPTR(s->v_buffer);
2362 fwrite(src16, s->uv_width, 2, yuv_rec_file);
2363 src16 += s->uv_stride;
2366 fflush(yuv_rec_file);
2369 #endif // CONFIG_VP9_HIGHBITDEPTH
2372 fwrite(src, s->y_width, 1, yuv_rec_file);
2380 fwrite(src, s->uv_width, 1, yuv_rec_file);
2381 src += s->uv_stride;
2388 fwrite(src, s->uv_width, 1, yuv_rec_file);
2389 src += s->uv_stride;
2392 fflush(yuv_rec_file);
2396 #if CONFIG_VP9_HIGHBITDEPTH
2397 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
2398 YV12_BUFFER_CONFIG *dst,
2401 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
2402 YV12_BUFFER_CONFIG *dst) {
2403 #endif // CONFIG_VP9_HIGHBITDEPTH
2404 // TODO(dkovalev): replace YV12_BUFFER_CONFIG with vpx_image_t
2406 const uint8_t *const srcs[3] = {src->y_buffer, src->u_buffer, src->v_buffer};
2407 const int src_strides[3] = {src->y_stride, src->uv_stride, src->uv_stride};
2408 const int src_widths[3] = {src->y_crop_width, src->uv_crop_width,
2409 src->uv_crop_width };
2410 const int src_heights[3] = {src->y_crop_height, src->uv_crop_height,
2411 src->uv_crop_height};
2412 uint8_t *const dsts[3] = {dst->y_buffer, dst->u_buffer, dst->v_buffer};
2413 const int dst_strides[3] = {dst->y_stride, dst->uv_stride, dst->uv_stride};
2414 const int dst_widths[3] = {dst->y_crop_width, dst->uv_crop_width,
2415 dst->uv_crop_width};
2416 const int dst_heights[3] = {dst->y_crop_height, dst->uv_crop_height,
2417 dst->uv_crop_height};
2419 for (i = 0; i < MAX_MB_PLANE; ++i) {
2420 #if CONFIG_VP9_HIGHBITDEPTH
2421 if (src->flags & YV12_FLAG_HIGHBITDEPTH) {
2422 vp9_highbd_resize_plane(srcs[i], src_heights[i], src_widths[i],
2423 src_strides[i], dsts[i], dst_heights[i],
2424 dst_widths[i], dst_strides[i], bd);
2426 vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
2427 dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
2430 vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
2431 dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
2432 #endif // CONFIG_VP9_HIGHBITDEPTH
2434 vpx_extend_frame_borders(dst);
2437 #if CONFIG_VP9_HIGHBITDEPTH
2438 static void scale_and_extend_frame(const YV12_BUFFER_CONFIG *src,
2439 YV12_BUFFER_CONFIG *dst, int bd) {
2440 const int src_w = src->y_crop_width;
2441 const int src_h = src->y_crop_height;
2442 const int dst_w = dst->y_crop_width;
2443 const int dst_h = dst->y_crop_height;
2444 const uint8_t *const srcs[3] = {src->y_buffer, src->u_buffer, src->v_buffer};
2445 const int src_strides[3] = {src->y_stride, src->uv_stride, src->uv_stride};
2446 uint8_t *const dsts[3] = {dst->y_buffer, dst->u_buffer, dst->v_buffer};
2447 const int dst_strides[3] = {dst->y_stride, dst->uv_stride, dst->uv_stride};
2448 const InterpKernel *const kernel = vp9_filter_kernels[EIGHTTAP];
2451 for (i = 0; i < MAX_MB_PLANE; ++i) {
2452 const int factor = (i == 0 || i == 3 ? 1 : 2);
2453 const int src_stride = src_strides[i];
2454 const int dst_stride = dst_strides[i];
2455 for (y = 0; y < dst_h; y += 16) {
2456 const int y_q4 = y * (16 / factor) * src_h / dst_h;
2457 for (x = 0; x < dst_w; x += 16) {
2458 const int x_q4 = x * (16 / factor) * src_w / dst_w;
2459 const uint8_t *src_ptr = srcs[i] + (y / factor) * src_h / dst_h *
2460 src_stride + (x / factor) * src_w / dst_w;
2461 uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
2463 if (src->flags & YV12_FLAG_HIGHBITDEPTH) {
2464 vpx_highbd_convolve8(src_ptr, src_stride, dst_ptr, dst_stride,
2465 kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2466 kernel[y_q4 & 0xf], 16 * src_h / dst_h,
2467 16 / factor, 16 / factor, bd);
2469 vpx_scaled_2d(src_ptr, src_stride, dst_ptr, dst_stride,
2470 kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2471 kernel[y_q4 & 0xf], 16 * src_h / dst_h,
2472 16 / factor, 16 / factor);
2478 vpx_extend_frame_borders(dst);
2481 void vp9_scale_and_extend_frame_c(const YV12_BUFFER_CONFIG *src,
2482 YV12_BUFFER_CONFIG *dst) {
2483 const int src_w = src->y_crop_width;
2484 const int src_h = src->y_crop_height;
2485 const int dst_w = dst->y_crop_width;
2486 const int dst_h = dst->y_crop_height;
2487 const uint8_t *const srcs[3] = {src->y_buffer, src->u_buffer, src->v_buffer};
2488 const int src_strides[3] = {src->y_stride, src->uv_stride, src->uv_stride};
2489 uint8_t *const dsts[3] = {dst->y_buffer, dst->u_buffer, dst->v_buffer};
2490 const int dst_strides[3] = {dst->y_stride, dst->uv_stride, dst->uv_stride};
2491 const InterpKernel *const kernel = vp9_filter_kernels[EIGHTTAP];
2494 for (i = 0; i < MAX_MB_PLANE; ++i) {
2495 const int factor = (i == 0 || i == 3 ? 1 : 2);
2496 const int src_stride = src_strides[i];
2497 const int dst_stride = dst_strides[i];
2498 for (y = 0; y < dst_h; y += 16) {
2499 const int y_q4 = y * (16 / factor) * src_h / dst_h;
2500 for (x = 0; x < dst_w; x += 16) {
2501 const int x_q4 = x * (16 / factor) * src_w / dst_w;
2502 const uint8_t *src_ptr = srcs[i] + (y / factor) * src_h / dst_h *
2503 src_stride + (x / factor) * src_w / dst_w;
2504 uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
2506 vpx_scaled_2d(src_ptr, src_stride, dst_ptr, dst_stride,
2507 kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2508 kernel[y_q4 & 0xf], 16 * src_h / dst_h,
2509 16 / factor, 16 / factor);
2514 vpx_extend_frame_borders(dst);
2516 #endif // CONFIG_VP9_HIGHBITDEPTH
2518 static int scale_down(VP9_COMP *cpi, int q) {
2519 RATE_CONTROL *const rc = &cpi->rc;
2520 GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2522 assert(frame_is_kf_gf_arf(cpi));
2524 if (rc->frame_size_selector == UNSCALED &&
2525 q >= rc->rf_level_maxq[gf_group->rf_level[gf_group->index]]) {
2526 const int max_size_thresh = (int)(rate_thresh_mult[SCALE_STEP1]
2527 * VPXMAX(rc->this_frame_target, rc->avg_frame_bandwidth));
2528 scale = rc->projected_frame_size > max_size_thresh ? 1 : 0;
2533 static int big_rate_miss(VP9_COMP *cpi, int high_limit, int low_limit) {
2534 const RATE_CONTROL *const rc = &cpi->rc;
2536 return (rc->projected_frame_size > ((high_limit * 3) / 2)) ||
2537 (rc->projected_frame_size < (low_limit / 2));
2540 // Function to test for conditions that indicate we should loop
2541 // back and recode a frame.
2542 static int recode_loop_test(VP9_COMP *cpi,
2543 int high_limit, int low_limit,
2544 int q, int maxq, int minq) {
2545 const RATE_CONTROL *const rc = &cpi->rc;
2546 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2547 const int frame_is_kfgfarf = frame_is_kf_gf_arf(cpi);
2548 int force_recode = 0;
2550 if ((rc->projected_frame_size >= rc->max_frame_bandwidth) ||
2551 big_rate_miss(cpi, high_limit, low_limit) ||
2552 (cpi->sf.recode_loop == ALLOW_RECODE) ||
2553 (frame_is_kfgfarf &&
2554 (cpi->sf.recode_loop == ALLOW_RECODE_KFARFGF))) {
2555 if (frame_is_kfgfarf &&
2556 (oxcf->resize_mode == RESIZE_DYNAMIC) &&
2557 scale_down(cpi, q)) {
2558 // Code this group at a lower resolution.
2559 cpi->resize_pending = 1;
2563 // TODO(agrange) high_limit could be greater than the scale-down threshold.
2564 if ((rc->projected_frame_size > high_limit && q < maxq) ||
2565 (rc->projected_frame_size < low_limit && q > minq)) {
2567 } else if (cpi->oxcf.rc_mode == VPX_CQ) {
2568 // Deal with frame undershoot and whether or not we are
2569 // below the automatically set cq level.
2570 if (q > oxcf->cq_level &&
2571 rc->projected_frame_size < ((rc->this_frame_target * 7) >> 3)) {
2576 return force_recode;
2579 void vp9_update_reference_frames(VP9_COMP *cpi) {
2580 VP9_COMMON * const cm = &cpi->common;
2581 BufferPool *const pool = cm->buffer_pool;
2583 // At this point the new frame has been encoded.
2584 // If any buffer copy / swapping is signaled it should be done here.
2585 if (cm->frame_type == KEY_FRAME) {
2586 ref_cnt_fb(pool->frame_bufs,
2587 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2588 ref_cnt_fb(pool->frame_bufs,
2589 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2590 } else if (vp9_preserve_existing_gf(cpi)) {
2591 // We have decided to preserve the previously existing golden frame as our
2592 // new ARF frame. However, in the short term in function
2593 // vp9_get_refresh_mask() we left it in the GF slot and, if
2594 // we're updating the GF with the current decoded frame, we save it to the
2595 // ARF slot instead.
2596 // We now have to update the ARF with the current frame and swap gld_fb_idx
2597 // and alt_fb_idx so that, overall, we've stored the old GF in the new ARF
2598 // slot and, if we're updating the GF, the current frame becomes the new GF.
2601 ref_cnt_fb(pool->frame_bufs,
2602 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2604 tmp = cpi->alt_fb_idx;
2605 cpi->alt_fb_idx = cpi->gld_fb_idx;
2606 cpi->gld_fb_idx = tmp;
2608 if (is_two_pass_svc(cpi)) {
2609 cpi->svc.layer_context[0].gold_ref_idx = cpi->gld_fb_idx;
2610 cpi->svc.layer_context[0].alt_ref_idx = cpi->alt_fb_idx;
2612 } else { /* For non key/golden frames */
2613 if (cpi->refresh_alt_ref_frame) {
2614 int arf_idx = cpi->alt_fb_idx;
2615 if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
2616 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2617 arf_idx = gf_group->arf_update_idx[gf_group->index];
2620 ref_cnt_fb(pool->frame_bufs,
2621 &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
2622 memcpy(cpi->interp_filter_selected[ALTREF_FRAME],
2623 cpi->interp_filter_selected[0],
2624 sizeof(cpi->interp_filter_selected[0]));
2627 if (cpi->refresh_golden_frame) {
2628 ref_cnt_fb(pool->frame_bufs,
2629 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2630 if (!cpi->rc.is_src_frame_alt_ref)
2631 memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
2632 cpi->interp_filter_selected[0],
2633 sizeof(cpi->interp_filter_selected[0]));
2635 memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
2636 cpi->interp_filter_selected[ALTREF_FRAME],
2637 sizeof(cpi->interp_filter_selected[ALTREF_FRAME]));
2641 if (cpi->refresh_last_frame) {
2642 ref_cnt_fb(pool->frame_bufs,
2643 &cm->ref_frame_map[cpi->lst_fb_idx], cm->new_fb_idx);
2644 if (!cpi->rc.is_src_frame_alt_ref)
2645 memcpy(cpi->interp_filter_selected[LAST_FRAME],
2646 cpi->interp_filter_selected[0],
2647 sizeof(cpi->interp_filter_selected[0]));
2649 #if CONFIG_VP9_TEMPORAL_DENOISING
2650 if (cpi->oxcf.noise_sensitivity > 0 &&
2651 cpi->denoiser.denoising_level > kDenLowLow) {
2652 vp9_denoiser_update_frame_info(&cpi->denoiser,
2654 cpi->common.frame_type,
2655 cpi->refresh_alt_ref_frame,
2656 cpi->refresh_golden_frame,
2657 cpi->refresh_last_frame,
2658 cpi->resize_pending);
2661 if (is_one_pass_cbr_svc(cpi)) {
2662 // Keep track of frame index for each reference frame.
2663 SVC *const svc = &cpi->svc;
2664 if (cm->frame_type == KEY_FRAME) {
2665 svc->ref_frame_index[cpi->lst_fb_idx] = svc->current_superframe;
2666 svc->ref_frame_index[cpi->gld_fb_idx] = svc->current_superframe;
2667 svc->ref_frame_index[cpi->alt_fb_idx] = svc->current_superframe;
2669 if (cpi->refresh_last_frame)
2670 svc->ref_frame_index[cpi->lst_fb_idx] = svc->current_superframe;
2671 if (cpi->refresh_golden_frame)
2672 svc->ref_frame_index[cpi->gld_fb_idx] = svc->current_superframe;
2673 if (cpi->refresh_alt_ref_frame)
2674 svc->ref_frame_index[cpi->alt_fb_idx] = svc->current_superframe;
2679 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
2680 MACROBLOCKD *xd = &cpi->td.mb.e_mbd;
2681 struct loopfilter *lf = &cm->lf;
2684 lf->filter_level = 0;
2685 lf->last_filt_level = 0;
2687 struct vpx_usec_timer timer;
2689 vpx_clear_system_state();
2691 vpx_usec_timer_start(&timer);
2693 if (!cpi->rc.is_src_frame_alt_ref) {
2694 if ((cpi->common.frame_type == KEY_FRAME) &&
2695 (!cpi->rc.this_key_frame_forced)) {
2696 lf->last_filt_level = 0;
2698 vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.lpf_pick);
2699 lf->last_filt_level = lf->filter_level;
2701 lf->filter_level = 0;
2704 vpx_usec_timer_mark(&timer);
2705 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
2708 if (lf->filter_level > 0) {
2709 vp9_build_mask_frame(cm, lf->filter_level, 0);
2711 if (cpi->num_workers > 1)
2712 vp9_loop_filter_frame_mt(cm->frame_to_show, cm, xd->plane,
2713 lf->filter_level, 0, 0,
2714 cpi->workers, cpi->num_workers,
2717 vp9_loop_filter_frame(cm->frame_to_show, cm, xd, lf->filter_level, 0, 0);
2720 vpx_extend_frame_inner_borders(cm->frame_to_show);
2723 static INLINE void alloc_frame_mvs(VP9_COMMON *const cm,
2725 RefCntBuffer *const new_fb_ptr = &cm->buffer_pool->frame_bufs[buffer_idx];
2726 if (new_fb_ptr->mvs == NULL ||
2727 new_fb_ptr->mi_rows < cm->mi_rows ||
2728 new_fb_ptr->mi_cols < cm->mi_cols) {
2729 vpx_free(new_fb_ptr->mvs);
2730 CHECK_MEM_ERROR(cm, new_fb_ptr->mvs,
2731 (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
2732 sizeof(*new_fb_ptr->mvs)));
2733 new_fb_ptr->mi_rows = cm->mi_rows;
2734 new_fb_ptr->mi_cols = cm->mi_cols;
2738 void vp9_scale_references(VP9_COMP *cpi) {
2739 VP9_COMMON *cm = &cpi->common;
2740 MV_REFERENCE_FRAME ref_frame;
2741 const VP9_REFFRAME ref_mask[3] = {VP9_LAST_FLAG, VP9_GOLD_FLAG, VP9_ALT_FLAG};
2743 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2744 // Need to convert from VP9_REFFRAME to index into ref_mask (subtract 1).
2745 if (cpi->ref_frame_flags & ref_mask[ref_frame - 1]) {
2746 BufferPool *const pool = cm->buffer_pool;
2747 const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi,
2751 cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2755 #if CONFIG_VP9_HIGHBITDEPTH
2756 if (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height) {
2757 RefCntBuffer *new_fb_ptr = NULL;
2758 int force_scaling = 0;
2759 int new_fb = cpi->scaled_ref_idx[ref_frame - 1];
2760 if (new_fb == INVALID_IDX) {
2761 new_fb = get_free_fb(cm);
2764 if (new_fb == INVALID_IDX)
2766 new_fb_ptr = &pool->frame_bufs[new_fb];
2767 if (force_scaling ||
2768 new_fb_ptr->buf.y_crop_width != cm->width ||
2769 new_fb_ptr->buf.y_crop_height != cm->height) {
2770 if (vpx_realloc_frame_buffer(&new_fb_ptr->buf, cm->width, cm->height,
2771 cm->subsampling_x, cm->subsampling_y,
2772 cm->use_highbitdepth,
2773 VP9_ENC_BORDER_IN_PIXELS,
2774 cm->byte_alignment, NULL, NULL, NULL))
2775 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2776 "Failed to allocate frame buffer");
2777 scale_and_extend_frame(ref, &new_fb_ptr->buf, (int)cm->bit_depth);
2778 cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
2779 alloc_frame_mvs(cm, new_fb);
2782 if (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height) {
2783 RefCntBuffer *new_fb_ptr = NULL;
2784 int force_scaling = 0;
2785 int new_fb = cpi->scaled_ref_idx[ref_frame - 1];
2786 if (new_fb == INVALID_IDX) {
2787 new_fb = get_free_fb(cm);
2790 if (new_fb == INVALID_IDX)
2792 new_fb_ptr = &pool->frame_bufs[new_fb];
2793 if (force_scaling ||
2794 new_fb_ptr->buf.y_crop_width != cm->width ||
2795 new_fb_ptr->buf.y_crop_height != cm->height) {
2796 if (vpx_realloc_frame_buffer(&new_fb_ptr->buf, cm->width, cm->height,
2797 cm->subsampling_x, cm->subsampling_y,
2798 VP9_ENC_BORDER_IN_PIXELS,
2799 cm->byte_alignment, NULL, NULL, NULL))
2800 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
2801 "Failed to allocate frame buffer");
2802 vp9_scale_and_extend_frame(ref, &new_fb_ptr->buf);
2803 cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
2804 alloc_frame_mvs(cm, new_fb);
2806 #endif // CONFIG_VP9_HIGHBITDEPTH
2809 RefCntBuffer *buf = NULL;
2810 if (cpi->oxcf.pass == 0 && !cpi->use_svc) {
2811 // Check for release of scaled reference.
2812 buf_idx = cpi->scaled_ref_idx[ref_frame - 1];
2813 buf = (buf_idx != INVALID_IDX) ? &pool->frame_bufs[buf_idx] : NULL;
2816 cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2819 buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
2820 buf = &pool->frame_bufs[buf_idx];
2821 buf->buf.y_crop_width = ref->y_crop_width;
2822 buf->buf.y_crop_height = ref->y_crop_height;
2823 cpi->scaled_ref_idx[ref_frame - 1] = buf_idx;
2827 if (cpi->oxcf.pass != 0 || cpi->use_svc)
2828 cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2833 static void release_scaled_references(VP9_COMP *cpi) {
2834 VP9_COMMON *cm = &cpi->common;
2836 if (cpi->oxcf.pass == 0 && !cpi->use_svc) {
2837 // Only release scaled references under certain conditions:
2838 // if reference will be updated, or if scaled reference has same resolution.
2840 refresh[0] = (cpi->refresh_last_frame) ? 1 : 0;
2841 refresh[1] = (cpi->refresh_golden_frame) ? 1 : 0;
2842 refresh[2] = (cpi->refresh_alt_ref_frame) ? 1 : 0;
2843 for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
2844 const int idx = cpi->scaled_ref_idx[i - 1];
2845 RefCntBuffer *const buf = idx != INVALID_IDX ?
2846 &cm->buffer_pool->frame_bufs[idx] : NULL;
2847 const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi, i);
2850 (buf->buf.y_crop_width == ref->y_crop_width &&
2851 buf->buf.y_crop_height == ref->y_crop_height))) {
2853 cpi->scaled_ref_idx[i -1] = INVALID_IDX;
2857 for (i = 0; i < MAX_REF_FRAMES; ++i) {
2858 const int idx = cpi->scaled_ref_idx[i];
2859 RefCntBuffer *const buf = idx != INVALID_IDX ?
2860 &cm->buffer_pool->frame_bufs[idx] : NULL;
2863 cpi->scaled_ref_idx[i] = INVALID_IDX;
2869 static void full_to_model_count(unsigned int *model_count,
2870 unsigned int *full_count) {
2872 model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
2873 model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
2874 model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
2875 for (n = THREE_TOKEN; n < EOB_TOKEN; ++n)
2876 model_count[TWO_TOKEN] += full_count[n];
2877 model_count[EOB_MODEL_TOKEN] = full_count[EOB_TOKEN];
2880 static void full_to_model_counts(vp9_coeff_count_model *model_count,
2881 vp9_coeff_count *full_count) {
2884 for (i = 0; i < PLANE_TYPES; ++i)
2885 for (j = 0; j < REF_TYPES; ++j)
2886 for (k = 0; k < COEF_BANDS; ++k)
2887 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
2888 full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
2891 #if 0 && CONFIG_INTERNAL_STATS
2892 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
2893 VP9_COMMON *const cm = &cpi->common;
2894 FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
2897 vpx_clear_system_state();
2899 #if CONFIG_VP9_HIGHBITDEPTH
2900 if (cm->use_highbitdepth) {
2901 recon_err = vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2903 recon_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2906 recon_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2907 #endif // CONFIG_VP9_HIGHBITDEPTH
2910 if (cpi->twopass.total_left_stats.coded_error != 0.0) {
2911 double dc_quant_devisor;
2912 #if CONFIG_VP9_HIGHBITDEPTH
2913 switch (cm->bit_depth) {
2915 dc_quant_devisor = 4.0;
2918 dc_quant_devisor = 16.0;
2921 dc_quant_devisor = 64.0;
2924 assert(0 && "bit_depth must be VPX_BITS_8, VPX_BITS_10 or VPX_BITS_12");
2928 dc_quant_devisor = 4.0;
2931 fprintf(f, "%10u %dx%d %10d %10d %d %d %10d %10d %10d %10d"
2932 "%10"PRId64" %10"PRId64" %5d %5d %10"PRId64" "
2933 "%10"PRId64" %10"PRId64" %10d "
2934 "%7.2lf %7.2lf %7.2lf %7.2lf %7.2lf"
2935 "%6d %6d %5d %5d %5d "
2936 "%10"PRId64" %10.3lf"
2937 "%10lf %8u %10"PRId64" %10d %10d %10d %10d %10d\n",
2938 cpi->common.current_video_frame,
2939 cm->width, cm->height,
2940 cpi->td.rd_counts.m_search_count,
2941 cpi->td.rd_counts.ex_search_count,
2942 cpi->rc.source_alt_ref_pending,
2943 cpi->rc.source_alt_ref_active,
2944 cpi->rc.this_frame_target,
2945 cpi->rc.projected_frame_size,
2946 cpi->rc.projected_frame_size / cpi->common.MBs,
2947 (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
2948 cpi->rc.vbr_bits_off_target,
2949 cpi->rc.vbr_bits_off_target_fast,
2950 cpi->twopass.extend_minq,
2951 cpi->twopass.extend_minq_fast,
2952 cpi->rc.total_target_vs_actual,
2953 (cpi->rc.starting_buffer_level - cpi->rc.bits_off_target),
2954 cpi->rc.total_actual_bits, cm->base_qindex,
2955 vp9_convert_qindex_to_q(cm->base_qindex, cm->bit_depth),
2956 (double)vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) /
2958 vp9_convert_qindex_to_q(cpi->twopass.active_worst_quality,
2961 vp9_convert_qindex_to_q(cpi->oxcf.cq_level, cm->bit_depth),
2962 cpi->refresh_last_frame, cpi->refresh_golden_frame,
2963 cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
2964 cpi->twopass.bits_left,
2965 cpi->twopass.total_left_stats.coded_error,
2966 cpi->twopass.bits_left /
2967 (1 + cpi->twopass.total_left_stats.coded_error),
2968 cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
2969 cpi->twopass.kf_zeromotion_pct,
2970 cpi->twopass.fr_content_type,
2971 cm->lf.filter_level,
2972 cm->seg.aq_av_offset);
2977 FILE *const fmodes = fopen("Modes.stt", "a");
2980 fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
2981 cm->frame_type, cpi->refresh_golden_frame,
2982 cpi->refresh_alt_ref_frame);
2984 for (i = 0; i < MAX_MODES; ++i)
2985 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
2987 fprintf(fmodes, "\n");
2994 static void set_mv_search_params(VP9_COMP *cpi) {
2995 const VP9_COMMON *const cm = &cpi->common;
2996 const unsigned int max_mv_def = VPXMIN(cm->width, cm->height);
2998 // Default based on max resolution.
2999 cpi->mv_step_param = vp9_init_search_range(max_mv_def);
3001 if (cpi->sf.mv.auto_mv_step_size) {
3002 if (frame_is_intra_only(cm)) {
3003 // Initialize max_mv_magnitude for use in the first INTER frame
3004 // after a key/intra-only frame.
3005 cpi->max_mv_magnitude = max_mv_def;
3007 if (cm->show_frame) {
3008 // Allow mv_steps to correspond to twice the max mv magnitude found
3009 // in the previous frame, capped by the default max_mv_magnitude based
3011 cpi->mv_step_param = vp9_init_search_range(
3012 VPXMIN(max_mv_def, 2 * cpi->max_mv_magnitude));
3014 cpi->max_mv_magnitude = 0;
3019 static void set_size_independent_vars(VP9_COMP *cpi) {
3020 vp9_set_speed_features_framesize_independent(cpi);
3021 vp9_set_rd_speed_thresholds(cpi);
3022 vp9_set_rd_speed_thresholds_sub8x8(cpi);
3023 cpi->common.interp_filter = cpi->sf.default_interp_filter;
3026 static void set_size_dependent_vars(VP9_COMP *cpi, int *q,
3027 int *bottom_index, int *top_index) {
3028 VP9_COMMON *const cm = &cpi->common;
3029 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3031 // Setup variables that depend on the dimensions of the frame.
3032 vp9_set_speed_features_framesize_dependent(cpi);
3034 // Decide q and q bounds.
3035 *q = vp9_rc_pick_q_and_bounds(cpi, bottom_index, top_index);
3037 if (!frame_is_intra_only(cm)) {
3038 vp9_set_high_precision_mv(cpi, (*q) < HIGH_PRECISION_MV_QTHRESH);
3041 // Configure experimental use of segmentation for enhanced coding of
3042 // static regions if indicated.
3043 // Only allowed in the second pass of a two pass encode, as it requires
3044 // lagged coding, and if the relevant speed feature flag is set.
3045 if (oxcf->pass == 2 && cpi->sf.static_segmentation)
3046 configure_static_seg_features(cpi);
3048 #if CONFIG_VP9_POSTPROC && !(CONFIG_VP9_TEMPORAL_DENOISING)
3049 if (oxcf->noise_sensitivity > 0) {
3051 switch (oxcf->noise_sensitivity) {
3069 vp9_denoise(cpi->Source, cpi->Source, l);
3071 #endif // CONFIG_VP9_POSTPROC
3074 #if CONFIG_VP9_TEMPORAL_DENOISING
3075 static void setup_denoiser_buffer(VP9_COMP *cpi) {
3076 VP9_COMMON *const cm = &cpi->common;
3077 if (cpi->oxcf.noise_sensitivity > 0 &&
3078 !cpi->denoiser.frame_buffer_initialized) {
3079 if (vp9_denoiser_alloc(&cpi->denoiser, cm->width, cm->height,
3080 cm->subsampling_x, cm->subsampling_y,
3081 #if CONFIG_VP9_HIGHBITDEPTH
3082 cm->use_highbitdepth,
3084 VP9_ENC_BORDER_IN_PIXELS))
3085 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
3086 "Failed to allocate denoiser");
3091 static void init_motion_estimation(VP9_COMP *cpi) {
3092 int y_stride = cpi->scaled_source.y_stride;
3094 if (cpi->sf.mv.search_method == NSTEP) {
3095 vp9_init3smotion_compensation(&cpi->ss_cfg, y_stride);
3096 } else if (cpi->sf.mv.search_method == DIAMOND) {
3097 vp9_init_dsmotion_compensation(&cpi->ss_cfg, y_stride);
3101 static void set_frame_size(VP9_COMP *cpi) {
3103 VP9_COMMON *const cm = &cpi->common;
3104 VP9EncoderConfig *const oxcf = &cpi->oxcf;
3105 MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
3107 if (oxcf->pass == 2 &&
3108 oxcf->rc_mode == VPX_VBR &&
3109 ((oxcf->resize_mode == RESIZE_FIXED && cm->current_video_frame == 0) ||
3110 (oxcf->resize_mode == RESIZE_DYNAMIC && cpi->resize_pending))) {
3111 calculate_coded_size(
3112 cpi, &oxcf->scaled_frame_width, &oxcf->scaled_frame_height);
3114 // There has been a change in frame size.
3115 vp9_set_size_literal(cpi, oxcf->scaled_frame_width,
3116 oxcf->scaled_frame_height);
3119 if (oxcf->pass == 0 &&
3120 oxcf->rc_mode == VPX_CBR &&
3122 oxcf->resize_mode == RESIZE_DYNAMIC &&
3123 cpi->resize_pending != 0) {
3124 oxcf->scaled_frame_width =
3125 (oxcf->width * cpi->resize_scale_num) / cpi->resize_scale_den;
3126 oxcf->scaled_frame_height =
3127 (oxcf->height * cpi->resize_scale_num) /cpi->resize_scale_den;
3128 // There has been a change in frame size.
3129 vp9_set_size_literal(cpi,
3130 oxcf->scaled_frame_width,
3131 oxcf->scaled_frame_height);
3133 // TODO(agrange) Scale cpi->max_mv_magnitude if frame-size has changed.
3134 set_mv_search_params(cpi);
3136 vp9_noise_estimate_init(&cpi->noise_estimate, cm->width, cm->height);
3137 #if CONFIG_VP9_TEMPORAL_DENOISING
3138 // Reset the denoiser on the resized frame.
3139 if (cpi->oxcf.noise_sensitivity > 0) {
3140 vp9_denoiser_free(&(cpi->denoiser));
3141 setup_denoiser_buffer(cpi);
3142 // Dynamic resize is only triggered for non-SVC, so we can force
3143 // golden frame update here as temporary fix to denoiser.
3144 cpi->refresh_golden_frame = 1;
3149 if ((oxcf->pass == 2) &&
3151 (is_two_pass_svc(cpi) &&
3152 cpi->svc.encode_empty_frame_state != ENCODING))) {
3153 vp9_set_target_rate(cpi);
3156 alloc_frame_mvs(cm, cm->new_fb_idx);
3158 // Reset the frame pointers to the current frame size.
3159 if (vpx_realloc_frame_buffer(get_frame_new_buffer(cm), cm->width, cm->height,
3160 cm->subsampling_x, cm->subsampling_y,
3161 #if CONFIG_VP9_HIGHBITDEPTH
3162 cm->use_highbitdepth,
3164 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
3166 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
3167 "Failed to allocate frame buffer");
3169 alloc_util_frame_buffers(cpi);
3170 init_motion_estimation(cpi);
3172 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3173 RefBuffer *const ref_buf = &cm->frame_refs[ref_frame - 1];
3174 const int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
3176 ref_buf->idx = buf_idx;
3178 if (buf_idx != INVALID_IDX) {
3179 YV12_BUFFER_CONFIG *const buf = &cm->buffer_pool->frame_bufs[buf_idx].buf;
3181 #if CONFIG_VP9_HIGHBITDEPTH
3182 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
3183 buf->y_crop_width, buf->y_crop_height,
3184 cm->width, cm->height,
3185 (buf->flags & YV12_FLAG_HIGHBITDEPTH) ?
3188 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
3189 buf->y_crop_width, buf->y_crop_height,
3190 cm->width, cm->height);
3191 #endif // CONFIG_VP9_HIGHBITDEPTH
3192 if (vp9_is_scaled(&ref_buf->sf))
3193 vpx_extend_frame_borders(buf);
3195 ref_buf->buf = NULL;
3199 set_ref_ptrs(cm, xd, LAST_FRAME, LAST_FRAME);
3202 static void encode_without_recode_loop(VP9_COMP *cpi,
3205 VP9_COMMON *const cm = &cpi->common;
3206 int q = 0, bottom_index = 0, top_index = 0; // Dummy variables.
3208 vpx_clear_system_state();
3210 set_frame_size(cpi);
3212 if (is_one_pass_cbr_svc(cpi) &&
3213 cpi->un_scaled_source->y_width == cm->width << 2 &&
3214 cpi->un_scaled_source->y_height == cm->height << 2 &&
3215 cpi->svc.scaled_temp.y_width == cm->width << 1 &&
3216 cpi->svc.scaled_temp.y_height == cm->height << 1) {
3217 cpi->Source = vp9_svc_twostage_scale(cm,
3218 cpi->un_scaled_source,
3219 &cpi->scaled_source,
3220 &cpi->svc.scaled_temp);
3222 cpi->Source = vp9_scale_if_required(cm,
3223 cpi->un_scaled_source,
3224 &cpi->scaled_source,
3225 (cpi->oxcf.pass == 0));
3227 // Avoid scaling last_source unless its needed.
3228 // Last source is needed if vp9_avg_source_sad() is used, or if
3229 // partition_search_type == SOURCE_VAR_BASED_PARTITION, or if noise
3230 // estimation is enabled.
3231 if (cpi->unscaled_last_source != NULL &&
3232 (cpi->oxcf.content == VP9E_CONTENT_SCREEN ||
3233 (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_VBR &&
3234 cpi->oxcf.mode == REALTIME && cpi->oxcf.speed >= 5) ||
3235 cpi->sf.partition_search_type == SOURCE_VAR_BASED_PARTITION ||
3236 cpi->noise_estimate.enabled))
3237 cpi->Last_Source = vp9_scale_if_required(cm,
3238 cpi->unscaled_last_source,
3239 &cpi->scaled_last_source,
3240 (cpi->oxcf.pass == 0));
3242 if (cm->frame_type == KEY_FRAME || cpi->resize_pending != 0) {
3243 memset(cpi->consec_zero_mv, 0,
3244 cm->mi_rows * cm->mi_cols * sizeof(*cpi->consec_zero_mv));
3247 vp9_update_noise_estimate(cpi);
3249 if (cpi->oxcf.pass == 0 &&
3250 cpi->oxcf.mode == REALTIME &&
3251 cpi->oxcf.speed >= 5 &&
3252 cpi->resize_state == 0 &&
3253 cm->frame_type != KEY_FRAME &&
3254 (cpi->oxcf.content == VP9E_CONTENT_SCREEN ||
3255 cpi->oxcf.rc_mode == VPX_VBR))
3256 vp9_avg_source_sad(cpi);
3258 // For 1 pass SVC, since only ZEROMV is allowed for upsampled reference
3259 // frame (i.e, svc->force_zero_mode_spatial_ref = 0), we can avoid this
3260 // frame-level upsampling.
3261 if (frame_is_intra_only(cm) == 0 && !is_one_pass_cbr_svc(cpi)) {
3262 vp9_scale_references(cpi);
3265 set_size_independent_vars(cpi);
3266 set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
3268 if (cpi->oxcf.speed >= 5 &&
3269 cpi->oxcf.pass == 0 &&
3270 cpi->oxcf.rc_mode == VPX_CBR &&
3271 cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
3272 cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3273 cpi->use_skin_detection = 1;
3276 vp9_set_quantizer(cm, q);
3277 vp9_set_variance_partition_thresholds(cpi, q);
3281 suppress_active_map(cpi);
3282 // Variance adaptive and in frame q adjustment experiments are mutually
3284 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3285 vp9_vaq_frame_setup(cpi);
3286 } else if (cpi->oxcf.aq_mode == EQUATOR360_AQ) {
3287 vp9_360aq_frame_setup(cpi);
3288 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
3289 vp9_setup_in_frame_q_adj(cpi);
3290 } else if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3291 vp9_cyclic_refresh_setup(cpi);
3293 apply_active_map(cpi);
3295 // transform / motion compensation build reconstruction frame
3296 vp9_encode_frame(cpi);
3298 // Check if we should drop this frame because of high overshoot.
3299 // Only for frames where high temporal-source sad is detected.
3300 if (cpi->oxcf.pass == 0 &&
3301 cpi->oxcf.rc_mode == VPX_CBR &&
3302 cpi->resize_state == 0 &&
3303 cm->frame_type != KEY_FRAME &&
3304 cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
3305 cpi->rc.high_source_sad == 1) {
3307 // Get an estimate of the encoded frame size.
3308 save_coding_context(cpi);
3309 vp9_pack_bitstream(cpi, dest, size);
3310 restore_coding_context(cpi);
3311 frame_size = (int)(*size) << 3;
3312 // Check if encoded frame will overshoot too much, and if so, set the q and
3313 // adjust some rate control parameters, and return to re-encode the frame.
3314 if (vp9_encodedframe_overshoot(cpi, frame_size, &q)) {
3315 vpx_clear_system_state();
3316 vp9_set_quantizer(cm, q);
3317 vp9_set_variance_partition_thresholds(cpi, q);
3318 suppress_active_map(cpi);
3319 // Turn-off cyclic refresh for re-encoded frame.
3320 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3321 unsigned char *const seg_map = cpi->segmentation_map;
3322 memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
3323 vp9_disable_segmentation(&cm->seg);
3325 apply_active_map(cpi);
3326 vp9_encode_frame(cpi);
3330 // Update some stats from cyclic refresh, and check if we should not update
3331 // golden reference, for non-SVC 1 pass CBR.
3332 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
3333 cm->frame_type != KEY_FRAME &&
3335 cpi->ext_refresh_frame_flags_pending == 0 &&
3336 (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_CBR))
3337 vp9_cyclic_refresh_check_golden_update(cpi);
3339 // Update the skip mb flag probabilities based on the distribution
3340 // seen in the last encoder iteration.
3341 // update_base_skip_probs(cpi);
3342 vpx_clear_system_state();
3345 static void encode_with_recode_loop(VP9_COMP *cpi,
3348 VP9_COMMON *const cm = &cpi->common;
3349 RATE_CONTROL *const rc = &cpi->rc;
3350 int bottom_index, top_index;
3352 int loop_at_this_size = 0;
3354 int overshoot_seen = 0;
3355 int undershoot_seen = 0;
3356 int frame_over_shoot_limit;
3357 int frame_under_shoot_limit;
3358 int q = 0, q_low = 0, q_high = 0;
3360 set_size_independent_vars(cpi);
3363 vpx_clear_system_state();
3365 set_frame_size(cpi);
3367 if (loop_count == 0 || cpi->resize_pending != 0) {
3368 set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
3370 // TODO(agrange) Scale cpi->max_mv_magnitude if frame-size has changed.
3371 set_mv_search_params(cpi);
3373 // Reset the loop state for new frame size.
3375 undershoot_seen = 0;
3377 // Reconfiguration for change in frame size has concluded.
3378 cpi->resize_pending = 0;
3380 q_low = bottom_index;
3383 loop_at_this_size = 0;
3386 // Decide frame size bounds first time through.
3387 if (loop_count == 0) {
3388 vp9_rc_compute_frame_size_bounds(cpi, rc->this_frame_target,
3389 &frame_under_shoot_limit,
3390 &frame_over_shoot_limit);
3393 cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
3394 &cpi->scaled_source,
3395 (cpi->oxcf.pass == 0));
3397 if (cpi->unscaled_last_source != NULL)
3398 cpi->Last_Source = vp9_scale_if_required(cm, cpi->unscaled_last_source,
3399 &cpi->scaled_last_source,
3400 (cpi->oxcf.pass == 0));
3402 if (frame_is_intra_only(cm) == 0) {
3403 if (loop_count > 0) {
3404 release_scaled_references(cpi);
3406 vp9_scale_references(cpi);
3409 vp9_set_quantizer(cm, q);
3411 if (loop_count == 0)
3414 // Variance adaptive and in frame q adjustment experiments are mutually
3416 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3417 vp9_vaq_frame_setup(cpi);
3418 } else if (cpi->oxcf.aq_mode == EQUATOR360_AQ) {
3419 vp9_360aq_frame_setup(cpi);
3420 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
3421 vp9_setup_in_frame_q_adj(cpi);
3424 // transform / motion compensation build reconstruction frame
3425 vp9_encode_frame(cpi);
3427 // Update the skip mb flag probabilities based on the distribution
3428 // seen in the last encoder iteration.
3429 // update_base_skip_probs(cpi);
3431 vpx_clear_system_state();
3433 // Dummy pack of the bitstream using up to date stats to get an
3434 // accurate estimate of output frame size to determine if we need
3436 if (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF) {
3437 save_coding_context(cpi);
3438 if (!cpi->sf.use_nonrd_pick_mode)
3439 vp9_pack_bitstream(cpi, dest, size);
3441 rc->projected_frame_size = (int)(*size) << 3;
3442 restore_coding_context(cpi);
3444 if (frame_over_shoot_limit == 0)
3445 frame_over_shoot_limit = 1;
3448 if (cpi->oxcf.rc_mode == VPX_Q) {
3451 if ((cm->frame_type == KEY_FRAME) &&
3452 rc->this_key_frame_forced &&
3453 (rc->projected_frame_size < rc->max_frame_bandwidth)) {
3457 int64_t high_err_target = cpi->ambient_err;
3458 int64_t low_err_target = cpi->ambient_err >> 1;
3460 #if CONFIG_VP9_HIGHBITDEPTH
3461 if (cm->use_highbitdepth) {
3462 kf_err = vpx_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3464 kf_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3467 kf_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3468 #endif // CONFIG_VP9_HIGHBITDEPTH
3470 // Prevent possible divide by zero error below for perfect KF
3473 // The key frame is not good enough or we can afford
3474 // to make it better without undue risk of popping.
3475 if ((kf_err > high_err_target &&
3476 rc->projected_frame_size <= frame_over_shoot_limit) ||
3477 (kf_err > low_err_target &&
3478 rc->projected_frame_size <= frame_under_shoot_limit)) {
3480 q_high = q > q_low ? q - 1 : q_low;
3483 q = (int)((q * high_err_target) / kf_err);
3484 q = VPXMIN(q, (q_high + q_low) >> 1);
3485 } else if (kf_err < low_err_target &&
3486 rc->projected_frame_size >= frame_under_shoot_limit) {
3487 // The key frame is much better than the previous frame
3489 q_low = q < q_high ? q + 1 : q_high;
3492 q = (int)((q * low_err_target) / kf_err);
3493 q = VPXMIN(q, (q_high + q_low + 1) >> 1);
3496 // Clamp Q to upper and lower limits:
3497 q = clamp(q, q_low, q_high);
3500 } else if (recode_loop_test(
3501 cpi, frame_over_shoot_limit, frame_under_shoot_limit,
3502 q, VPXMAX(q_high, top_index), bottom_index)) {
3503 // Is the projected frame size out of range and are we allowed
3504 // to attempt to recode.
3508 if (cpi->resize_pending == 1) {
3509 // Change in frame size so go back around the recode loop.
3510 cpi->rc.frame_size_selector =
3511 SCALE_STEP1 - cpi->rc.frame_size_selector;
3512 cpi->rc.next_frame_size_selector = cpi->rc.frame_size_selector;
3514 #if CONFIG_INTERNAL_STATS
3515 ++cpi->tot_recode_hits;
3522 // Frame size out of permitted range:
3523 // Update correction factor & compute new Q to try...
3525 // Frame is too large
3526 if (rc->projected_frame_size > rc->this_frame_target) {
3527 // Special case if the projected size is > the max allowed.
3528 if (rc->projected_frame_size >= rc->max_frame_bandwidth)
3529 q_high = rc->worst_quality;
3531 // Raise Qlow as to at least the current value
3532 q_low = q < q_high ? q + 1 : q_high;
3534 if (undershoot_seen || loop_at_this_size > 1) {
3535 // Update rate_correction_factor unless
3536 vp9_rc_update_rate_correction_factors(cpi);
3538 q = (q_high + q_low + 1) / 2;
3540 // Update rate_correction_factor unless
3541 vp9_rc_update_rate_correction_factors(cpi);
3543 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
3544 bottom_index, VPXMAX(q_high, top_index));
3546 while (q < q_low && retries < 10) {
3547 vp9_rc_update_rate_correction_factors(cpi);
3548 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
3549 bottom_index, VPXMAX(q_high, top_index));
3556 // Frame is too small
3557 q_high = q > q_low ? q - 1 : q_low;
3559 if (overshoot_seen || loop_at_this_size > 1) {
3560 vp9_rc_update_rate_correction_factors(cpi);
3561 q = (q_high + q_low) / 2;
3563 vp9_rc_update_rate_correction_factors(cpi);
3564 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
3565 bottom_index, top_index);
3566 // Special case reset for qlow for constrained quality.
3567 // This should only trigger where there is very substantial
3568 // undershoot on a frame and the auto cq level is above
3569 // the user passsed in value.
3570 if (cpi->oxcf.rc_mode == VPX_CQ &&
3575 while (q > q_high && retries < 10) {
3576 vp9_rc_update_rate_correction_factors(cpi);
3577 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
3578 bottom_index, top_index);
3583 undershoot_seen = 1;
3586 // Clamp Q to upper and lower limits:
3587 q = clamp(q, q_low, q_high);
3589 loop = (q != last_q);
3595 // Special case for overlay frame.
3596 if (rc->is_src_frame_alt_ref &&
3597 rc->projected_frame_size < rc->max_frame_bandwidth)
3602 ++loop_at_this_size;
3604 #if CONFIG_INTERNAL_STATS
3605 ++cpi->tot_recode_hits;
3611 static int get_ref_frame_flags(const VP9_COMP *cpi) {
3612 const int *const map = cpi->common.ref_frame_map;
3613 const int gold_is_last = map[cpi->gld_fb_idx] == map[cpi->lst_fb_idx];
3614 const int alt_is_last = map[cpi->alt_fb_idx] == map[cpi->lst_fb_idx];
3615 const int gold_is_alt = map[cpi->gld_fb_idx] == map[cpi->alt_fb_idx];
3616 int flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
3619 flags &= ~VP9_GOLD_FLAG;
3621 if (cpi->rc.frames_till_gf_update_due == INT_MAX &&
3622 (cpi->svc.number_temporal_layers == 1 &&
3623 cpi->svc.number_spatial_layers == 1))
3624 flags &= ~VP9_GOLD_FLAG;
3627 flags &= ~VP9_ALT_FLAG;
3630 flags &= ~VP9_ALT_FLAG;
3635 static void set_ext_overrides(VP9_COMP *cpi) {
3636 // Overrides the defaults with the externally supplied values with
3637 // vp9_update_reference() and vp9_update_entropy() calls
3638 // Note: The overrides are valid only for the next frame passed
3639 // to encode_frame_to_data_rate() function
3640 if (cpi->ext_refresh_frame_context_pending) {
3641 cpi->common.refresh_frame_context = cpi->ext_refresh_frame_context;
3642 cpi->ext_refresh_frame_context_pending = 0;
3644 if (cpi->ext_refresh_frame_flags_pending) {
3645 cpi->refresh_last_frame = cpi->ext_refresh_last_frame;
3646 cpi->refresh_golden_frame = cpi->ext_refresh_golden_frame;
3647 cpi->refresh_alt_ref_frame = cpi->ext_refresh_alt_ref_frame;
3651 YV12_BUFFER_CONFIG *vp9_svc_twostage_scale(VP9_COMMON *cm,
3652 YV12_BUFFER_CONFIG *unscaled,
3653 YV12_BUFFER_CONFIG *scaled,
3654 YV12_BUFFER_CONFIG *scaled_temp) {
3655 if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
3656 cm->mi_rows * MI_SIZE != unscaled->y_height) {
3657 #if CONFIG_VP9_HIGHBITDEPTH
3658 scale_and_extend_frame(unscaled, scaled_temp, (int)cm->bit_depth);
3659 scale_and_extend_frame(scaled_temp, scaled, (int)cm->bit_depth);
3661 vp9_scale_and_extend_frame(unscaled, scaled_temp);
3662 vp9_scale_and_extend_frame(scaled_temp, scaled);
3663 #endif // CONFIG_VP9_HIGHBITDEPTH
3670 YV12_BUFFER_CONFIG *vp9_scale_if_required(VP9_COMMON *cm,
3671 YV12_BUFFER_CONFIG *unscaled,
3672 YV12_BUFFER_CONFIG *scaled,
3673 int use_normative_scaler) {
3674 if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
3675 cm->mi_rows * MI_SIZE != unscaled->y_height) {
3676 #if CONFIG_VP9_HIGHBITDEPTH
3677 if (use_normative_scaler &&
3678 unscaled->y_width <= (scaled->y_width << 1) &&
3679 unscaled->y_height <= (scaled->y_height << 1))
3680 scale_and_extend_frame(unscaled, scaled, (int)cm->bit_depth);
3682 scale_and_extend_frame_nonnormative(unscaled, scaled, (int)cm->bit_depth);
3684 if (use_normative_scaler &&
3685 unscaled->y_width <= (scaled->y_width << 1) &&
3686 unscaled->y_height <= (scaled->y_height << 1))
3687 vp9_scale_and_extend_frame(unscaled, scaled);
3689 scale_and_extend_frame_nonnormative(unscaled, scaled);
3690 #endif // CONFIG_VP9_HIGHBITDEPTH
3697 static void set_arf_sign_bias(VP9_COMP *cpi) {
3698 VP9_COMMON *const cm = &cpi->common;
3701 if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
3702 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
3703 arf_sign_bias = cpi->rc.source_alt_ref_active &&
3704 (!cpi->refresh_alt_ref_frame ||
3705 (gf_group->rf_level[gf_group->index] == GF_ARF_LOW));
3708 (cpi->rc.source_alt_ref_active && !cpi->refresh_alt_ref_frame);
3710 cm->ref_frame_sign_bias[ALTREF_FRAME] = arf_sign_bias;
3713 static int setup_interp_filter_search_mask(VP9_COMP *cpi) {
3714 INTERP_FILTER ifilter;
3715 int ref_total[MAX_REF_FRAMES] = {0};
3716 MV_REFERENCE_FRAME ref;
3718 if (cpi->common.last_frame_type == KEY_FRAME ||
3719 cpi->refresh_alt_ref_frame)
3721 for (ref = LAST_FRAME; ref <= ALTREF_FRAME; ++ref)
3722 for (ifilter = EIGHTTAP; ifilter <= EIGHTTAP_SHARP; ++ifilter)
3723 ref_total[ref] += cpi->interp_filter_selected[ref][ifilter];
3725 for (ifilter = EIGHTTAP; ifilter <= EIGHTTAP_SHARP; ++ifilter) {
3726 if ((ref_total[LAST_FRAME] &&
3727 cpi->interp_filter_selected[LAST_FRAME][ifilter] == 0) &&
3728 (ref_total[GOLDEN_FRAME] == 0 ||
3729 cpi->interp_filter_selected[GOLDEN_FRAME][ifilter] * 50
3730 < ref_total[GOLDEN_FRAME]) &&
3731 (ref_total[ALTREF_FRAME] == 0 ||
3732 cpi->interp_filter_selected[ALTREF_FRAME][ifilter] * 50
3733 < ref_total[ALTREF_FRAME]))
3734 mask |= 1 << ifilter;
3739 static void encode_frame_to_data_rate(VP9_COMP *cpi,
3742 unsigned int *frame_flags) {
3743 VP9_COMMON *const cm = &cpi->common;
3744 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3745 struct segmentation *const seg = &cm->seg;
3748 set_ext_overrides(cpi);
3749 vpx_clear_system_state();
3751 // Set the arf sign bias for this frame.
3752 set_arf_sign_bias(cpi);
3754 // Set default state for segment based loop filter update flags.
3755 cm->lf.mode_ref_delta_update = 0;
3757 if (cpi->oxcf.pass == 2 &&
3758 cpi->sf.adaptive_interp_filter_search)
3759 cpi->sf.interp_filter_search_mask =
3760 setup_interp_filter_search_mask(cpi);
3762 // Set various flags etc to special state if it is a key frame.
3763 if (frame_is_intra_only(cm)) {
3764 // Reset the loop filter deltas and segmentation map.
3765 vp9_reset_segment_features(&cm->seg);
3767 // If segmentation is enabled force a map update for key frames.
3769 seg->update_map = 1;
3770 seg->update_data = 1;
3773 // The alternate reference frame cannot be active for a key frame.
3774 cpi->rc.source_alt_ref_active = 0;
3776 cm->error_resilient_mode = oxcf->error_resilient_mode;
3777 cm->frame_parallel_decoding_mode = oxcf->frame_parallel_decoding_mode;
3779 // By default, encoder assumes decoder can use prev_mi.
3780 if (cm->error_resilient_mode) {
3781 cm->frame_parallel_decoding_mode = 1;
3782 cm->reset_frame_context = 0;
3783 cm->refresh_frame_context = 0;
3784 } else if (cm->intra_only) {
3785 // Only reset the current context.
3786 cm->reset_frame_context = 2;
3789 if (is_two_pass_svc(cpi) && cm->error_resilient_mode == 0) {
3790 // Use context 0 for intra only empty frame, but the last frame context
3791 // for other empty frames.
3792 if (cpi->svc.encode_empty_frame_state == ENCODING) {
3793 if (cpi->svc.encode_intra_empty_frame != 0)
3794 cm->frame_context_idx = 0;
3796 cm->frame_context_idx = FRAME_CONTEXTS - 1;
3798 cm->frame_context_idx =
3799 cpi->svc.spatial_layer_id * cpi->svc.number_temporal_layers +
3800 cpi->svc.temporal_layer_id;
3803 cm->frame_parallel_decoding_mode = oxcf->frame_parallel_decoding_mode;
3805 // The probs will be updated based on the frame type of its previous
3806 // frame if frame_parallel_decoding_mode is 0. The type may vary for
3807 // the frame after a key frame in base layer since we may drop enhancement
3808 // layers. So set frame_parallel_decoding_mode to 1 in this case.
3809 if (cm->frame_parallel_decoding_mode == 0) {
3810 if (cpi->svc.number_temporal_layers == 1) {
3811 if (cpi->svc.spatial_layer_id == 0 &&
3812 cpi->svc.layer_context[0].last_frame_type == KEY_FRAME)
3813 cm->frame_parallel_decoding_mode = 1;
3814 } else if (cpi->svc.spatial_layer_id == 0) {
3815 // Find the 2nd frame in temporal base layer and 1st frame in temporal
3816 // enhancement layers from the key frame.
3818 for (i = 0; i < cpi->svc.number_temporal_layers; ++i) {
3819 if (cpi->svc.layer_context[0].frames_from_key_frame == 1 << i) {
3820 cm->frame_parallel_decoding_mode = 1;
3828 // For 1 pass CBR, check if we are dropping this frame.
3829 // For spatial layers, for now only check for frame-dropping on first spatial
3830 // layer, and if decision is to drop, we drop whole super-frame.
3831 if (oxcf->pass == 0 &&
3832 oxcf->rc_mode == VPX_CBR &&
3833 cm->frame_type != KEY_FRAME) {
3834 if (vp9_rc_drop_frame(cpi) ||
3835 (is_one_pass_cbr_svc(cpi) && cpi->svc.rc_drop_superframe == 1)) {
3836 vp9_rc_postencode_update_drop_frame(cpi);
3837 ++cm->current_video_frame;
3838 cpi->ext_refresh_frame_flags_pending = 0;
3839 cpi->svc.rc_drop_superframe = 1;
3840 // TODO(marpan): Advancing the svc counters on dropped frames can break
3841 // the referencing scheme for the fixed svc patterns defined in
3842 // vp9_one_pass_cbr_svc_start_layer(). Look into fixing this issue, but
3843 // for now, don't advance the svc frame counters on dropped frame.
3844 // if (cpi->use_svc)
3845 // vp9_inc_frame_in_layer(cpi);
3850 vpx_clear_system_state();
3852 #if CONFIG_INTERNAL_STATS
3853 memset(cpi->mode_chosen_counts, 0,
3854 MAX_MODES * sizeof(*cpi->mode_chosen_counts));
3857 if (cpi->sf.recode_loop == DISALLOW_RECODE) {
3858 encode_without_recode_loop(cpi, size, dest);
3860 encode_with_recode_loop(cpi, size, dest);
3863 #if CONFIG_VP9_TEMPORAL_DENOISING
3864 #ifdef OUTPUT_YUV_DENOISED
3865 if (oxcf->noise_sensitivity > 0) {
3866 vp9_write_yuv_frame_420(&cpi->denoiser.running_avg_y[INTRA_FRAME],
3871 #ifdef OUTPUT_YUV_SKINMAP
3872 if (cpi->common.current_video_frame > 1) {
3873 vp9_compute_skin_map(cpi, yuv_skinmap_file);
3877 // Special case code to reduce pulsing when key frames are forced at a
3878 // fixed interval. Note the reconstruction error if it is the frame before
3879 // the force key frame
3880 if (cpi->rc.next_key_frame_forced && cpi->rc.frames_to_key == 1) {
3881 #if CONFIG_VP9_HIGHBITDEPTH
3882 if (cm->use_highbitdepth) {
3883 cpi->ambient_err = vpx_highbd_get_y_sse(cpi->Source,
3884 get_frame_new_buffer(cm));
3886 cpi->ambient_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3889 cpi->ambient_err = vpx_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3890 #endif // CONFIG_VP9_HIGHBITDEPTH
3893 // If the encoder forced a KEY_FRAME decision
3894 if (cm->frame_type == KEY_FRAME)
3895 cpi->refresh_last_frame = 1;
3897 cm->frame_to_show = get_frame_new_buffer(cm);
3898 cm->frame_to_show->color_space = cm->color_space;
3899 cm->frame_to_show->color_range = cm->color_range;
3900 cm->frame_to_show->render_width = cm->render_width;
3901 cm->frame_to_show->render_height = cm->render_height;
3903 // Pick the loop filter level for the frame.
3904 loopfilter_frame(cpi, cm);
3906 // build the bitstream
3907 vp9_pack_bitstream(cpi, dest, size);
3909 if (cm->seg.update_map)
3910 update_reference_segmentation_map(cpi);
3912 if (frame_is_intra_only(cm) == 0) {
3913 release_scaled_references(cpi);
3915 vp9_update_reference_frames(cpi);
3917 for (t = TX_4X4; t <= TX_32X32; t++)
3918 full_to_model_counts(cpi->td.counts->coef[t],
3919 cpi->td.rd_counts.coef_counts[t]);
3921 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode)
3922 vp9_adapt_coef_probs(cm);
3924 if (!frame_is_intra_only(cm)) {
3925 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
3926 vp9_adapt_mode_probs(cm);
3927 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
3931 cpi->ext_refresh_frame_flags_pending = 0;
3933 if (cpi->refresh_golden_frame == 1)
3934 cpi->frame_flags |= FRAMEFLAGS_GOLDEN;
3936 cpi->frame_flags &= ~FRAMEFLAGS_GOLDEN;
3938 if (cpi->refresh_alt_ref_frame == 1)
3939 cpi->frame_flags |= FRAMEFLAGS_ALTREF;
3941 cpi->frame_flags &= ~FRAMEFLAGS_ALTREF;
3943 cpi->ref_frame_flags = get_ref_frame_flags(cpi);
3945 cm->last_frame_type = cm->frame_type;
3947 if (!(is_two_pass_svc(cpi) && cpi->svc.encode_empty_frame_state == ENCODING))
3948 vp9_rc_postencode_update(cpi, *size);
3951 output_frame_level_debug_stats(cpi);
3954 if (cm->frame_type == KEY_FRAME) {
3955 // Tell the caller that the frame was coded as a key frame
3956 *frame_flags = cpi->frame_flags | FRAMEFLAGS_KEY;
3958 *frame_flags = cpi->frame_flags & ~FRAMEFLAGS_KEY;
3961 // Clear the one shot update flags for segmentation map and mode/ref loop
3963 cm->seg.update_map = 0;
3964 cm->seg.update_data = 0;
3965 cm->lf.mode_ref_delta_update = 0;
3967 // keep track of the last coded dimensions
3968 cm->last_width = cm->width;
3969 cm->last_height = cm->height;
3971 // reset to normal state now that we are done.
3972 if (!cm->show_existing_frame)
3973 cm->last_show_frame = cm->show_frame;
3975 if (cm->show_frame) {
3976 vp9_swap_mi_and_prev_mi(cm);
3977 // Don't increment frame counters if this was an altref buffer
3978 // update not a real frame
3979 ++cm->current_video_frame;
3981 vp9_inc_frame_in_layer(cpi);
3983 cm->prev_frame = cm->cur_frame;
3986 cpi->svc.layer_context[cpi->svc.spatial_layer_id *
3987 cpi->svc.number_temporal_layers +
3988 cpi->svc.temporal_layer_id].last_frame_type =
3992 static void SvcEncode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
3993 unsigned int *frame_flags) {
3994 vp9_rc_get_svc_params(cpi);
3995 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3998 static void Pass0Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
3999 unsigned int *frame_flags) {
4000 if (cpi->oxcf.rc_mode == VPX_CBR) {
4001 vp9_rc_get_one_pass_cbr_params(cpi);
4003 vp9_rc_get_one_pass_vbr_params(cpi);
4005 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4008 static void Pass2Encode(VP9_COMP *cpi, size_t *size,
4009 uint8_t *dest, unsigned int *frame_flags) {
4010 cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
4011 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
4013 if (!(is_two_pass_svc(cpi) && cpi->svc.encode_empty_frame_state == ENCODING))
4014 vp9_twopass_postencode_update(cpi);
4017 static void init_ref_frame_bufs(VP9_COMMON *cm) {
4019 BufferPool *const pool = cm->buffer_pool;
4020 cm->new_fb_idx = INVALID_IDX;
4021 for (i = 0; i < REF_FRAMES; ++i) {
4022 cm->ref_frame_map[i] = INVALID_IDX;
4023 pool->frame_bufs[i].ref_count = 0;
4027 static void check_initial_width(VP9_COMP *cpi,
4028 #if CONFIG_VP9_HIGHBITDEPTH
4029 int use_highbitdepth,
4031 int subsampling_x, int subsampling_y) {
4032 VP9_COMMON *const cm = &cpi->common;
4034 if (!cpi->initial_width ||
4035 #if CONFIG_VP9_HIGHBITDEPTH
4036 cm->use_highbitdepth != use_highbitdepth ||
4038 cm->subsampling_x != subsampling_x ||
4039 cm->subsampling_y != subsampling_y) {
4040 cm->subsampling_x = subsampling_x;
4041 cm->subsampling_y = subsampling_y;
4042 #if CONFIG_VP9_HIGHBITDEPTH
4043 cm->use_highbitdepth = use_highbitdepth;
4046 alloc_raw_frame_buffers(cpi);
4047 init_ref_frame_bufs(cm);
4048 alloc_util_frame_buffers(cpi);
4050 init_motion_estimation(cpi); // TODO(agrange) This can be removed.
4052 cpi->initial_width = cm->width;
4053 cpi->initial_height = cm->height;
4054 cpi->initial_mbs = cm->MBs;
4058 int vp9_receive_raw_frame(VP9_COMP *cpi, unsigned int frame_flags,
4059 YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
4061 VP9_COMMON *const cm = &cpi->common;
4062 struct vpx_usec_timer timer;
4064 const int subsampling_x = sd->subsampling_x;
4065 const int subsampling_y = sd->subsampling_y;
4066 #if CONFIG_VP9_HIGHBITDEPTH
4067 const int use_highbitdepth = (sd->flags & YV12_FLAG_HIGHBITDEPTH) != 0;
4070 #if CONFIG_VP9_HIGHBITDEPTH
4071 check_initial_width(cpi, use_highbitdepth, subsampling_x, subsampling_y);
4073 check_initial_width(cpi, subsampling_x, subsampling_y);
4074 #endif // CONFIG_VP9_HIGHBITDEPTH
4076 #if CONFIG_VP9_TEMPORAL_DENOISING
4077 setup_denoiser_buffer(cpi);
4079 vpx_usec_timer_start(&timer);
4081 if (vp9_lookahead_push(cpi->lookahead, sd, time_stamp, end_time,
4082 #if CONFIG_VP9_HIGHBITDEPTH
4084 #endif // CONFIG_VP9_HIGHBITDEPTH
4087 vpx_usec_timer_mark(&timer);
4088 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
4090 if ((cm->profile == PROFILE_0 || cm->profile == PROFILE_2) &&
4091 (subsampling_x != 1 || subsampling_y != 1)) {
4092 vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
4093 "Non-4:2:0 color format requires profile 1 or 3");
4096 if ((cm->profile == PROFILE_1 || cm->profile == PROFILE_3) &&
4097 (subsampling_x == 1 && subsampling_y == 1)) {
4098 vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
4099 "4:2:0 color format requires profile 0 or 2");
4107 static int frame_is_reference(const VP9_COMP *cpi) {
4108 const VP9_COMMON *cm = &cpi->common;
4110 return cm->frame_type == KEY_FRAME ||
4111 cpi->refresh_last_frame ||
4112 cpi->refresh_golden_frame ||
4113 cpi->refresh_alt_ref_frame ||
4114 cm->refresh_frame_context ||
4115 cm->lf.mode_ref_delta_update ||
4116 cm->seg.update_map ||
4117 cm->seg.update_data;
4120 static void adjust_frame_rate(VP9_COMP *cpi,
4121 const struct lookahead_entry *source) {
4122 int64_t this_duration;
4125 if (source->ts_start == cpi->first_time_stamp_ever) {
4126 this_duration = source->ts_end - source->ts_start;
4129 int64_t last_duration = cpi->last_end_time_stamp_seen
4130 - cpi->last_time_stamp_seen;
4132 this_duration = source->ts_end - cpi->last_end_time_stamp_seen;
4134 // do a step update if the duration changes by 10%
4136 step = (int)((this_duration - last_duration) * 10 / last_duration);
4139 if (this_duration) {
4141 vp9_new_framerate(cpi, 10000000.0 / this_duration);
4143 // Average this frame's rate into the last second's average
4144 // frame rate. If we haven't seen 1 second yet, then average
4145 // over the whole interval seen.
4146 const double interval = VPXMIN(
4147 (double)(source->ts_end - cpi->first_time_stamp_ever), 10000000.0);
4148 double avg_duration = 10000000.0 / cpi->framerate;
4149 avg_duration *= (interval - avg_duration + this_duration);
4150 avg_duration /= interval;
4152 vp9_new_framerate(cpi, 10000000.0 / avg_duration);
4155 cpi->last_time_stamp_seen = source->ts_start;
4156 cpi->last_end_time_stamp_seen = source->ts_end;
4159 // Returns 0 if this is not an alt ref else the offset of the source frame
4160 // used as the arf midpoint.
4161 static int get_arf_src_index(VP9_COMP *cpi) {
4162 RATE_CONTROL *const rc = &cpi->rc;
4163 int arf_src_index = 0;
4164 if (is_altref_enabled(cpi)) {
4165 if (cpi->oxcf.pass == 2) {
4166 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4167 if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
4168 arf_src_index = gf_group->arf_src_offset[gf_group->index];
4170 } else if (rc->source_alt_ref_pending) {
4171 arf_src_index = rc->frames_till_gf_update_due;
4174 return arf_src_index;
4177 static void check_src_altref(VP9_COMP *cpi,
4178 const struct lookahead_entry *source) {
4179 RATE_CONTROL *const rc = &cpi->rc;
4181 if (cpi->oxcf.pass == 2) {
4182 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4183 rc->is_src_frame_alt_ref =
4184 (gf_group->update_type[gf_group->index] == OVERLAY_UPDATE);
4186 rc->is_src_frame_alt_ref = cpi->alt_ref_source &&
4187 (source == cpi->alt_ref_source);
4190 if (rc->is_src_frame_alt_ref) {
4191 // Current frame is an ARF overlay frame.
4192 cpi->alt_ref_source = NULL;
4194 // Don't refresh the last buffer for an ARF overlay frame. It will
4195 // become the GF so preserve last as an alternative prediction option.
4196 cpi->refresh_last_frame = 0;
4200 #if CONFIG_INTERNAL_STATS
4201 extern double vp9_get_blockiness(const uint8_t *img1, int img1_pitch,
4202 const uint8_t *img2, int img2_pitch,
4203 int width, int height);
4205 static void adjust_image_stat(double y, double u, double v, double all,
4210 s->stat[ALL] += all;
4211 s->worst = VPXMIN(s->worst, all);
4213 #endif // CONFIG_INTERNAL_STATS
4215 static void update_level_info(VP9_COMP *cpi, size_t *size, int arf_src_index) {
4216 VP9_COMMON *const cm = &cpi->common;
4217 Vp9LevelInfo *const level_info = &cpi->level_info;
4218 Vp9LevelSpec *const level_spec = &level_info->level_spec;
4219 Vp9LevelStats *const level_stats = &level_info->level_stats;
4221 uint64_t luma_samples, dur_end;
4222 const uint32_t luma_pic_size = cm->width * cm->height;
4223 double cpb_data_size;
4225 vpx_clear_system_state();
4227 // update level_stats
4228 level_stats->total_compressed_size += *size;
4229 if (cm->show_frame) {
4230 level_stats->total_uncompressed_size +=
4232 2 * (luma_pic_size >> (cm->subsampling_x + cm->subsampling_y));
4233 level_stats->time_encoded =
4234 (cpi->last_end_time_stamp_seen - cpi->first_time_stamp_ever) /
4235 (double)TICKS_PER_SEC;
4238 if (arf_src_index > 0) {
4239 if (!level_stats->seen_first_altref) {
4240 level_stats->seen_first_altref = 1;
4241 } else if (level_stats->frames_since_last_altref <
4242 level_spec->min_altref_distance) {
4243 level_spec->min_altref_distance = level_stats->frames_since_last_altref;
4245 level_stats->frames_since_last_altref = 0;
4247 ++level_stats->frames_since_last_altref;
4250 if (level_stats->frame_window_buffer.len < FRAME_WINDOW_SIZE - 1) {
4251 idx = (level_stats->frame_window_buffer.start +
4252 level_stats->frame_window_buffer.len++) % FRAME_WINDOW_SIZE;
4254 idx = level_stats->frame_window_buffer.start;
4255 level_stats->frame_window_buffer.start = (idx + 1) % FRAME_WINDOW_SIZE;
4257 level_stats->frame_window_buffer.buf[idx].ts = cpi->last_time_stamp_seen;
4258 level_stats->frame_window_buffer.buf[idx].size = (uint32_t)(*size);
4259 level_stats->frame_window_buffer.buf[idx].luma_samples = luma_pic_size;
4261 if (cm->frame_type == KEY_FRAME) {
4262 level_stats->ref_refresh_map = 0;
4265 level_stats->ref_refresh_map |= vp9_get_refresh_mask(cpi);
4266 // Also need to consider the case where the encoder refers to a buffer
4267 // that has been implicitly refreshed after encoding a keyframe.
4268 if (!cm->intra_only) {
4269 level_stats->ref_refresh_map |= (1 << cpi->lst_fb_idx);
4270 level_stats->ref_refresh_map |= (1 << cpi->gld_fb_idx);
4271 level_stats->ref_refresh_map |= (1 << cpi->alt_fb_idx);
4273 for (i = 0; i < REF_FRAMES; ++i) {
4274 count += (level_stats->ref_refresh_map >> i) & 1;
4276 if (count > level_spec->max_ref_frame_buffers) {
4277 level_spec->max_ref_frame_buffers = count;
4281 // update average_bitrate
4282 level_spec->average_bitrate =
4283 (double)level_stats->total_compressed_size / 125.0 /
4284 level_stats->time_encoded;
4286 // update max_luma_sample_rate
4288 for (i = 0; i < level_stats->frame_window_buffer.len; ++i) {
4289 idx = (level_stats->frame_window_buffer.start +
4290 level_stats->frame_window_buffer.len - 1 - i) % FRAME_WINDOW_SIZE;
4292 dur_end = level_stats->frame_window_buffer.buf[idx].ts;
4294 if (dur_end - level_stats->frame_window_buffer.buf[idx].ts >=
4298 luma_samples += level_stats->frame_window_buffer.buf[idx].luma_samples;
4300 if (luma_samples > level_spec->max_luma_sample_rate) {
4301 level_spec->max_luma_sample_rate = luma_samples;
4304 // update max_cpb_size
4306 for (i = 0; i < CPB_WINDOW_SIZE; ++i) {
4307 if (i >= level_stats->frame_window_buffer.len) break;
4308 idx = (level_stats->frame_window_buffer.start +
4309 level_stats->frame_window_buffer.len - 1 - i) % FRAME_WINDOW_SIZE;
4310 cpb_data_size += level_stats->frame_window_buffer.buf[idx].size;
4312 cpb_data_size = cpb_data_size / 125.0;
4313 if (cpb_data_size > level_spec->max_cpb_size) {
4314 level_spec->max_cpb_size = cpb_data_size;
4317 // update max_luma_picture_size
4318 if (luma_pic_size > level_spec->max_luma_picture_size) {
4319 level_spec->max_luma_picture_size = luma_pic_size;
4322 // update compression_ratio
4323 level_spec->compression_ratio =
4324 (double)level_stats->total_uncompressed_size * cm->bit_depth /
4325 level_stats->total_compressed_size / 8.0;
4327 // update max_col_tiles
4328 if (level_spec->max_col_tiles < (1 << cm->log2_tile_cols)) {
4329 level_spec->max_col_tiles = (1 << cm->log2_tile_cols);
4333 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
4334 size_t *size, uint8_t *dest,
4335 int64_t *time_stamp, int64_t *time_end, int flush) {
4336 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
4337 VP9_COMMON *const cm = &cpi->common;
4338 BufferPool *const pool = cm->buffer_pool;
4339 RATE_CONTROL *const rc = &cpi->rc;
4340 struct vpx_usec_timer cmptimer;
4341 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
4342 struct lookahead_entry *last_source = NULL;
4343 struct lookahead_entry *source = NULL;
4347 if (is_two_pass_svc(cpi)) {
4348 #if CONFIG_SPATIAL_SVC
4349 vp9_svc_start_frame(cpi);
4350 // Use a small empty frame instead of a real frame
4351 if (cpi->svc.encode_empty_frame_state == ENCODING)
4352 source = &cpi->svc.empty_frame;
4354 if (oxcf->pass == 2)
4355 vp9_restore_layer_context(cpi);
4356 } else if (is_one_pass_cbr_svc(cpi)) {
4357 vp9_one_pass_cbr_svc_start_layer(cpi);
4360 vpx_usec_timer_start(&cmptimer);
4362 vp9_set_high_precision_mv(cpi, ALTREF_HIGH_PRECISION_MV);
4364 // Is multi-arf enabled.
4365 // Note that at the moment multi_arf is only configured for 2 pass VBR and
4366 // will not work properly with svc.
4367 if ((oxcf->pass == 2) && !cpi->use_svc &&
4368 (cpi->oxcf.enable_auto_arf > 1))
4369 cpi->multi_arf_allowed = 1;
4371 cpi->multi_arf_allowed = 0;
4374 cm->reset_frame_context = 0;
4375 cm->refresh_frame_context = 1;
4376 if (!is_one_pass_cbr_svc(cpi)) {
4377 cpi->refresh_last_frame = 1;
4378 cpi->refresh_golden_frame = 0;
4379 cpi->refresh_alt_ref_frame = 0;
4382 // Should we encode an arf frame.
4383 arf_src_index = get_arf_src_index(cpi);
4385 // Skip alt frame if we encode the empty frame
4386 if (is_two_pass_svc(cpi) && source != NULL)
4389 if (arf_src_index) {
4390 for (i = 0; i <= arf_src_index; ++i) {
4391 struct lookahead_entry *e = vp9_lookahead_peek(cpi->lookahead, i);
4392 // Avoid creating an alt-ref if there's a forced keyframe pending.
4395 } else if (e->flags == VPX_EFLAG_FORCE_KF) {
4403 if (arf_src_index) {
4404 assert(arf_src_index <= rc->frames_to_key);
4406 if ((source = vp9_lookahead_peek(cpi->lookahead, arf_src_index)) != NULL) {
4407 cpi->alt_ref_source = source;
4409 #if CONFIG_SPATIAL_SVC
4410 if (is_two_pass_svc(cpi) && cpi->svc.spatial_layer_id > 0) {
4412 // Reference a hidden frame from a lower layer
4413 for (i = cpi->svc.spatial_layer_id - 1; i >= 0; --i) {
4414 if (oxcf->ss_enable_auto_arf[i]) {
4415 cpi->gld_fb_idx = cpi->svc.layer_context[i].alt_ref_idx;
4420 cpi->svc.layer_context[cpi->svc.spatial_layer_id].has_alt_frame = 1;
4423 if ((oxcf->arnr_max_frames > 0) && (oxcf->arnr_strength > 0)) {
4424 // Produce the filtered ARF frame.
4425 vp9_temporal_filter(cpi, arf_src_index);
4426 vpx_extend_frame_borders(&cpi->alt_ref_buffer);
4427 force_src_buffer = &cpi->alt_ref_buffer;
4432 cpi->refresh_alt_ref_frame = 1;
4433 cpi->refresh_golden_frame = 0;
4434 cpi->refresh_last_frame = 0;
4435 rc->is_src_frame_alt_ref = 0;
4436 rc->source_alt_ref_pending = 0;
4438 rc->source_alt_ref_pending = 0;
4443 // Get last frame source.
4444 if (cm->current_video_frame > 0) {
4445 if ((last_source = vp9_lookahead_peek(cpi->lookahead, -1)) == NULL)
4449 // Read in the source frame.
4451 source = vp9_svc_lookahead_pop(cpi, cpi->lookahead, flush);
4453 source = vp9_lookahead_pop(cpi->lookahead, flush);
4455 if (source != NULL) {
4458 // if the flags indicate intra frame, but if the current picture is for
4459 // non-zero spatial layer, it should not be an intra picture.
4460 // TODO(Won Kap): this needs to change if per-layer intra frame is
4462 if ((source->flags & VPX_EFLAG_FORCE_KF) &&
4463 cpi->svc.spatial_layer_id > cpi->svc.first_spatial_layer_to_encode) {
4464 source->flags &= ~(unsigned int)(VPX_EFLAG_FORCE_KF);
4467 // Check to see if the frame should be encoded as an arf overlay.
4468 check_src_altref(cpi, source);
4473 cpi->un_scaled_source = cpi->Source = force_src_buffer ? force_src_buffer
4476 cpi->unscaled_last_source = last_source != NULL ? &last_source->img : NULL;
4478 *time_stamp = source->ts_start;
4479 *time_end = source->ts_end;
4480 *frame_flags = (source->flags & VPX_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
4484 if (flush && oxcf->pass == 1 && !cpi->twopass.first_pass_done) {
4485 vp9_end_first_pass(cpi); /* get last stats packet */
4486 cpi->twopass.first_pass_done = 1;
4491 if (source->ts_start < cpi->first_time_stamp_ever) {
4492 cpi->first_time_stamp_ever = source->ts_start;
4493 cpi->last_end_time_stamp_seen = source->ts_start;
4496 // Clear down mmx registers
4497 vpx_clear_system_state();
4499 // adjust frame rates based on timestamps given
4500 if (cm->show_frame) {
4501 adjust_frame_rate(cpi, source);
4504 if (is_one_pass_cbr_svc(cpi)) {
4505 vp9_update_temporal_layer_framerate(cpi);
4506 vp9_restore_layer_context(cpi);
4509 // Find a free buffer for the new frame, releasing the reference previously
4511 if (cm->new_fb_idx != INVALID_IDX) {
4512 --pool->frame_bufs[cm->new_fb_idx].ref_count;
4514 cm->new_fb_idx = get_free_fb(cm);
4516 if (cm->new_fb_idx == INVALID_IDX)
4519 cm->cur_frame = &pool->frame_bufs[cm->new_fb_idx];
4521 if (!cpi->use_svc && cpi->multi_arf_allowed) {
4522 if (cm->frame_type == KEY_FRAME) {
4523 init_buffer_indices(cpi);
4524 } else if (oxcf->pass == 2) {
4525 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4526 cpi->alt_fb_idx = gf_group->arf_ref_idx[gf_group->index];
4530 // Start with a 0 size frame.
4533 cpi->frame_flags = *frame_flags;
4535 if ((oxcf->pass == 2) &&
4537 (is_two_pass_svc(cpi) &&
4538 cpi->svc.encode_empty_frame_state != ENCODING))) {
4539 vp9_rc_get_second_pass_params(cpi);
4540 } else if (oxcf->pass == 1) {
4541 set_frame_size(cpi);
4544 if (cpi->oxcf.pass != 0 ||
4546 frame_is_intra_only(cm) == 1) {
4547 for (i = 0; i < MAX_REF_FRAMES; ++i)
4548 cpi->scaled_ref_idx[i] = INVALID_IDX;
4551 if (oxcf->pass == 1 &&
4552 (!cpi->use_svc || is_two_pass_svc(cpi))) {
4553 const int lossless = is_lossless_requested(oxcf);
4554 #if CONFIG_VP9_HIGHBITDEPTH
4555 if (cpi->oxcf.use_highbitdepth)
4556 cpi->td.mb.fwd_txm4x4 = lossless ?
4557 vp9_highbd_fwht4x4 : vpx_highbd_fdct4x4;
4559 cpi->td.mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vpx_fdct4x4;
4560 cpi->td.mb.highbd_itxm_add = lossless ? vp9_highbd_iwht4x4_add :
4561 vp9_highbd_idct4x4_add;
4563 cpi->td.mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vpx_fdct4x4;
4564 #endif // CONFIG_VP9_HIGHBITDEPTH
4565 cpi->td.mb.itxm_add = lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
4566 vp9_first_pass(cpi, source);
4567 } else if (oxcf->pass == 2 &&
4568 (!cpi->use_svc || is_two_pass_svc(cpi))) {
4569 Pass2Encode(cpi, size, dest, frame_flags);
4570 } else if (cpi->use_svc) {
4571 SvcEncode(cpi, size, dest, frame_flags);
4574 Pass0Encode(cpi, size, dest, frame_flags);
4577 if (cm->refresh_frame_context)
4578 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
4580 // No frame encoded, or frame was dropped, release scaled references.
4581 if ((*size == 0) && (frame_is_intra_only(cm) == 0)) {
4582 release_scaled_references(cpi);
4586 cpi->droppable = !frame_is_reference(cpi);
4589 // Save layer specific state.
4590 if (is_one_pass_cbr_svc(cpi) ||
4591 ((cpi->svc.number_temporal_layers > 1 ||
4592 cpi->svc.number_spatial_layers > 1) &&
4594 vp9_save_layer_context(cpi);
4597 vpx_usec_timer_mark(&cmptimer);
4598 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
4600 if (cpi->b_calculate_psnr && oxcf->pass != 1 && cm->show_frame)
4601 generate_psnr_packet(cpi);
4603 if (cpi->keep_level_stats && oxcf->pass != 1)
4604 update_level_info(cpi, size, arf_src_index);
4606 #if CONFIG_INTERNAL_STATS
4608 if (oxcf->pass != 1) {
4609 double samples = 0.0;
4610 cpi->bytes += (int)(*size);
4612 if (cm->show_frame) {
4613 uint32_t bit_depth = 8;
4614 uint32_t in_bit_depth = 8;
4616 #if CONFIG_VP9_HIGHBITDEPTH
4617 if (cm->use_highbitdepth) {
4618 in_bit_depth = cpi->oxcf.input_bit_depth;
4619 bit_depth = cm->bit_depth;
4623 if (cpi->b_calculate_psnr) {
4624 YV12_BUFFER_CONFIG *orig = cpi->Source;
4625 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
4626 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
4628 #if CONFIG_VP9_HIGHBITDEPTH
4629 vpx_calc_highbd_psnr(orig, recon, &psnr, cpi->td.mb.e_mbd.bd,
4632 vpx_calc_psnr(orig, recon, &psnr);
4633 #endif // CONFIG_VP9_HIGHBITDEPTH
4635 adjust_image_stat(psnr.psnr[1], psnr.psnr[2], psnr.psnr[3],
4636 psnr.psnr[0], &cpi->psnr);
4637 cpi->total_sq_error += psnr.sse[0];
4638 cpi->total_samples += psnr.samples[0];
4639 samples = psnr.samples[0];
4643 double frame_ssim2 = 0, weight = 0;
4644 #if CONFIG_VP9_POSTPROC
4645 if (vpx_alloc_frame_buffer(pp,
4646 recon->y_crop_width, recon->y_crop_height,
4647 cm->subsampling_x, cm->subsampling_y,
4648 #if CONFIG_VP9_HIGHBITDEPTH
4649 cm->use_highbitdepth,
4651 VP9_ENC_BORDER_IN_PIXELS,
4652 cm->byte_alignment) < 0) {
4653 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
4654 "Failed to allocate post processing buffer");
4657 vp9_deblock(cm->frame_to_show, pp,
4658 cm->lf.filter_level * 10 / 6);
4660 vpx_clear_system_state();
4662 #if CONFIG_VP9_HIGHBITDEPTH
4663 vpx_calc_highbd_psnr(orig, pp, &psnr2, cpi->td.mb.e_mbd.bd,
4664 cpi->oxcf.input_bit_depth);
4666 vpx_calc_psnr(orig, pp, &psnr2);
4667 #endif // CONFIG_VP9_HIGHBITDEPTH
4669 cpi->totalp_sq_error += psnr2.sse[0];
4670 cpi->totalp_samples += psnr2.samples[0];
4671 adjust_image_stat(psnr2.psnr[1], psnr2.psnr[2], psnr2.psnr[3],
4672 psnr2.psnr[0], &cpi->psnrp);
4674 #if CONFIG_VP9_HIGHBITDEPTH
4675 if (cm->use_highbitdepth) {
4676 frame_ssim2 = vpx_highbd_calc_ssim(orig, recon, &weight,
4677 bit_depth, in_bit_depth);
4679 frame_ssim2 = vpx_calc_ssim(orig, recon, &weight);
4682 frame_ssim2 = vpx_calc_ssim(orig, recon, &weight);
4683 #endif // CONFIG_VP9_HIGHBITDEPTH
4685 cpi->worst_ssim = VPXMIN(cpi->worst_ssim, frame_ssim2);
4686 cpi->summed_quality += frame_ssim2 * weight;
4687 cpi->summed_weights += weight;
4689 #if CONFIG_VP9_HIGHBITDEPTH
4690 if (cm->use_highbitdepth) {
4691 frame_ssim2 = vpx_highbd_calc_ssim(
4692 orig, pp, &weight, bit_depth, in_bit_depth);
4694 frame_ssim2 = vpx_calc_ssim(orig, pp, &weight);
4697 frame_ssim2 = vpx_calc_ssim(orig, pp, &weight);
4698 #endif // CONFIG_VP9_HIGHBITDEPTH
4700 cpi->summedp_quality += frame_ssim2 * weight;
4701 cpi->summedp_weights += weight;
4704 FILE *f = fopen("q_used.stt", "a");
4705 fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
4706 cpi->common.current_video_frame, y2, u2, v2,
4707 frame_psnr2, frame_ssim2);
4713 if (cpi->b_calculate_blockiness) {
4714 #if CONFIG_VP9_HIGHBITDEPTH
4715 if (!cm->use_highbitdepth)
4718 double frame_blockiness = vp9_get_blockiness(
4719 cpi->Source->y_buffer, cpi->Source->y_stride,
4720 cm->frame_to_show->y_buffer, cm->frame_to_show->y_stride,
4721 cpi->Source->y_width, cpi->Source->y_height);
4722 cpi->worst_blockiness =
4723 VPXMAX(cpi->worst_blockiness, frame_blockiness);
4724 cpi->total_blockiness += frame_blockiness;
4728 if (cpi->b_calculate_consistency) {
4729 #if CONFIG_VP9_HIGHBITDEPTH
4730 if (!cm->use_highbitdepth)
4733 double this_inconsistency = vpx_get_ssim_metrics(
4734 cpi->Source->y_buffer, cpi->Source->y_stride,
4735 cm->frame_to_show->y_buffer, cm->frame_to_show->y_stride,
4736 cpi->Source->y_width, cpi->Source->y_height, cpi->ssim_vars,
4739 const double peak = (double)((1 << cpi->oxcf.input_bit_depth) - 1);
4740 double consistency = vpx_sse_to_psnr(samples, peak,
4741 (double)cpi->total_inconsistency);
4742 if (consistency > 0.0)
4743 cpi->worst_consistency =
4744 VPXMIN(cpi->worst_consistency, consistency);
4745 cpi->total_inconsistency += this_inconsistency;
4750 double y, u, v, frame_all;
4751 frame_all = vpx_calc_fastssim(cpi->Source, cm->frame_to_show, &y, &u,
4752 &v, bit_depth, in_bit_depth);
4753 adjust_image_stat(y, u, v, frame_all, &cpi->fastssim);
4756 double y, u, v, frame_all;
4757 frame_all = vpx_psnrhvs(cpi->Source, cm->frame_to_show, &y, &u, &v,
4758 bit_depth, in_bit_depth);
4759 adjust_image_stat(y, u, v, frame_all, &cpi->psnrhvs);
4766 if (is_two_pass_svc(cpi)) {
4767 if (cpi->svc.encode_empty_frame_state == ENCODING) {
4768 cpi->svc.encode_empty_frame_state = ENCODED;
4769 cpi->svc.encode_intra_empty_frame = 0;
4772 if (cm->show_frame) {
4773 ++cpi->svc.spatial_layer_to_encode;
4774 if (cpi->svc.spatial_layer_to_encode >= cpi->svc.number_spatial_layers)
4775 cpi->svc.spatial_layer_to_encode = 0;
4777 // May need the empty frame after an visible frame.
4778 cpi->svc.encode_empty_frame_state = NEED_TO_ENCODE;
4780 } else if (is_one_pass_cbr_svc(cpi)) {
4781 if (cm->show_frame) {
4782 ++cpi->svc.spatial_layer_to_encode;
4783 if (cpi->svc.spatial_layer_to_encode >= cpi->svc.number_spatial_layers)
4784 cpi->svc.spatial_layer_to_encode = 0;
4787 vpx_clear_system_state();
4791 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
4792 vp9_ppflags_t *flags) {
4793 VP9_COMMON *cm = &cpi->common;
4794 #if !CONFIG_VP9_POSTPROC
4798 if (!cm->show_frame) {
4802 #if CONFIG_VP9_POSTPROC
4803 ret = vp9_post_proc_frame(cm, dest, flags);
4805 if (cm->frame_to_show) {
4806 *dest = *cm->frame_to_show;
4807 dest->y_width = cm->width;
4808 dest->y_height = cm->height;
4809 dest->uv_width = cm->width >> cm->subsampling_x;
4810 dest->uv_height = cm->height >> cm->subsampling_y;
4815 #endif // !CONFIG_VP9_POSTPROC
4816 vpx_clear_system_state();
4821 int vp9_set_internal_size(VP9_COMP *cpi,
4822 VPX_SCALING horiz_mode, VPX_SCALING vert_mode) {
4823 VP9_COMMON *cm = &cpi->common;
4824 int hr = 0, hs = 0, vr = 0, vs = 0;
4826 if (horiz_mode > ONETWO || vert_mode > ONETWO)
4829 Scale2Ratio(horiz_mode, &hr, &hs);
4830 Scale2Ratio(vert_mode, &vr, &vs);
4832 // always go to the next whole number
4833 cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
4834 cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
4835 if (cm->current_video_frame) {
4836 assert(cm->width <= cpi->initial_width);
4837 assert(cm->height <= cpi->initial_height);
4840 update_frame_size(cpi);
4845 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
4846 unsigned int height) {
4847 VP9_COMMON *cm = &cpi->common;
4848 #if CONFIG_VP9_HIGHBITDEPTH
4849 check_initial_width(cpi, cm->use_highbitdepth, 1, 1);
4851 check_initial_width(cpi, 1, 1);
4852 #endif // CONFIG_VP9_HIGHBITDEPTH
4854 #if CONFIG_VP9_TEMPORAL_DENOISING
4855 setup_denoiser_buffer(cpi);
4860 if (cm->width > cpi->initial_width) {
4861 cm->width = cpi->initial_width;
4862 printf("Warning: Desired width too large, changed to %d\n", cm->width);
4867 cm->height = height;
4868 if (cm->height > cpi->initial_height) {
4869 cm->height = cpi->initial_height;
4870 printf("Warning: Desired height too large, changed to %d\n", cm->height);
4873 assert(cm->width <= cpi->initial_width);
4874 assert(cm->height <= cpi->initial_height);
4876 update_frame_size(cpi);
4881 void vp9_set_svc(VP9_COMP *cpi, int use_svc) {
4882 cpi->use_svc = use_svc;
4886 int vp9_get_quantizer(VP9_COMP *cpi) {
4887 return cpi->common.base_qindex;
4890 void vp9_apply_encoding_flags(VP9_COMP *cpi, vpx_enc_frame_flags_t flags) {
4891 if (flags & (VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_GF |
4892 VP8_EFLAG_NO_REF_ARF)) {
4895 if (flags & VP8_EFLAG_NO_REF_LAST)
4896 ref ^= VP9_LAST_FLAG;
4898 if (flags & VP8_EFLAG_NO_REF_GF)
4899 ref ^= VP9_GOLD_FLAG;
4901 if (flags & VP8_EFLAG_NO_REF_ARF)
4902 ref ^= VP9_ALT_FLAG;
4904 vp9_use_as_reference(cpi, ref);
4907 if (flags & (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF |
4908 VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_FORCE_GF |
4909 VP8_EFLAG_FORCE_ARF)) {
4912 if (flags & VP8_EFLAG_NO_UPD_LAST)
4913 upd ^= VP9_LAST_FLAG;
4915 if (flags & VP8_EFLAG_NO_UPD_GF)
4916 upd ^= VP9_GOLD_FLAG;
4918 if (flags & VP8_EFLAG_NO_UPD_ARF)
4919 upd ^= VP9_ALT_FLAG;
4921 vp9_update_reference(cpi, upd);
4924 if (flags & VP8_EFLAG_NO_UPD_ENTROPY) {
4925 vp9_update_entropy(cpi, 0);