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 "./vpx_config.h"
16 #include "./vp9_rtcd.h"
17 #include "./vpx_dsp_rtcd.h"
18 #include "./vpx_scale_rtcd.h"
19 #include "vpx/internal/vpx_psnr.h"
20 #include "vpx_ports/mem.h"
21 #include "vpx_ports/vpx_timer.h"
23 #include "vp9/common/vp9_alloccommon.h"
24 #include "vp9/common/vp9_filter.h"
25 #include "vp9/common/vp9_idct.h"
26 #if CONFIG_VP9_POSTPROC
27 #include "vp9/common/vp9_postproc.h"
29 #include "vp9/common/vp9_reconinter.h"
30 #include "vp9/common/vp9_reconintra.h"
31 #include "vp9/common/vp9_systemdependent.h"
32 #include "vp9/common/vp9_tile_common.h"
34 #include "vp9/encoder/vp9_aq_complexity.h"
35 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
36 #include "vp9/encoder/vp9_aq_variance.h"
37 #include "vp9/encoder/vp9_bitstream.h"
38 #include "vp9/encoder/vp9_context_tree.h"
39 #include "vp9/encoder/vp9_encodeframe.h"
40 #include "vp9/encoder/vp9_encodemv.h"
41 #include "vp9/encoder/vp9_encoder.h"
42 #include "vp9/encoder/vp9_ethread.h"
43 #include "vp9/encoder/vp9_firstpass.h"
44 #include "vp9/encoder/vp9_mbgraph.h"
45 #include "vp9/encoder/vp9_picklpf.h"
46 #include "vp9/encoder/vp9_ratectrl.h"
47 #include "vp9/encoder/vp9_rd.h"
48 #include "vp9/encoder/vp9_resize.h"
49 #include "vp9/encoder/vp9_segmentation.h"
50 #include "vp9/encoder/vp9_skin_detection.h"
51 #include "vp9/encoder/vp9_speed_features.h"
52 #if CONFIG_INTERNAL_STATS
53 #include "vp9/encoder/vp9_ssim.h"
55 #include "vp9/encoder/vp9_svc_layercontext.h"
56 #include "vp9/encoder/vp9_temporal_filter.h"
58 #define AM_SEGMENT_ID_INACTIVE 7
59 #define AM_SEGMENT_ID_ACTIVE 0
61 #define SHARP_FILTER_QTHRESH 0 /* Q threshold for 8-tap sharp filter */
63 #define ALTREF_HIGH_PRECISION_MV 1 // Whether to use high precision mv
64 // for altref computation.
65 #define HIGH_PRECISION_MV_QTHRESH 200 // Q threshold for high precision
66 // mv. Choose a very high value for
67 // now so that HIGH_PRECISION is always
69 // #define OUTPUT_YUV_REC
71 #ifdef OUTPUT_YUV_DENOISED
72 FILE *yuv_denoised_file = NULL;
74 #ifdef OUTPUT_YUV_SKINMAP
75 FILE *yuv_skinmap_file = NULL;
87 static INLINE void Scale2Ratio(VPX_SCALING mode, int *hr, int *hs) {
113 // Mark all inactive blocks as active. Other segmentation features may be set
114 // so memset cannot be used, instead only inactive blocks should be reset.
115 static void suppress_active_map(VP9_COMP *cpi) {
116 unsigned char *const seg_map = cpi->segmentation_map;
118 if (cpi->active_map.enabled || cpi->active_map.update)
119 for (i = 0; i < cpi->common.mi_rows * cpi->common.mi_cols; ++i)
120 if (seg_map[i] == AM_SEGMENT_ID_INACTIVE)
121 seg_map[i] = AM_SEGMENT_ID_ACTIVE;
124 static void apply_active_map(VP9_COMP *cpi) {
125 struct segmentation *const seg = &cpi->common.seg;
126 unsigned char *const seg_map = cpi->segmentation_map;
127 const unsigned char *const active_map = cpi->active_map.map;
130 assert(AM_SEGMENT_ID_ACTIVE == CR_SEGMENT_ID_BASE);
132 if (frame_is_intra_only(&cpi->common)) {
133 cpi->active_map.enabled = 0;
134 cpi->active_map.update = 1;
137 if (cpi->active_map.update) {
138 if (cpi->active_map.enabled) {
139 for (i = 0; i < cpi->common.mi_rows * cpi->common.mi_cols; ++i)
140 if (seg_map[i] == AM_SEGMENT_ID_ACTIVE) seg_map[i] = active_map[i];
141 vp9_enable_segmentation(seg);
142 vp9_enable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
143 vp9_enable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
144 // Setting the data to -MAX_LOOP_FILTER will result in the computed loop
145 // filter level being zero regardless of the value of seg->abs_delta.
146 vp9_set_segdata(seg, AM_SEGMENT_ID_INACTIVE,
147 SEG_LVL_ALT_LF, -MAX_LOOP_FILTER);
149 vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_SKIP);
150 vp9_disable_segfeature(seg, AM_SEGMENT_ID_INACTIVE, SEG_LVL_ALT_LF);
152 seg->update_data = 1;
156 cpi->active_map.update = 0;
160 int vp9_set_active_map(VP9_COMP* cpi,
161 unsigned char* new_map_16x16,
164 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
165 unsigned char *const active_map_8x8 = cpi->active_map.map;
166 const int mi_rows = cpi->common.mi_rows;
167 const int mi_cols = cpi->common.mi_cols;
168 cpi->active_map.update = 1;
171 for (r = 0; r < mi_rows; ++r) {
172 for (c = 0; c < mi_cols; ++c) {
173 active_map_8x8[r * mi_cols + c] =
174 new_map_16x16[(r >> 1) * cols + (c >> 1)]
175 ? AM_SEGMENT_ID_ACTIVE
176 : AM_SEGMENT_ID_INACTIVE;
179 cpi->active_map.enabled = 1;
181 cpi->active_map.enabled = 0;
189 int vp9_get_active_map(VP9_COMP* cpi,
190 unsigned char* new_map_16x16,
193 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols &&
195 unsigned char* const seg_map_8x8 = cpi->segmentation_map;
196 const int mi_rows = cpi->common.mi_rows;
197 const int mi_cols = cpi->common.mi_cols;
198 memset(new_map_16x16, !cpi->active_map.enabled, rows * cols);
199 if (cpi->active_map.enabled) {
201 for (r = 0; r < mi_rows; ++r) {
202 for (c = 0; c < mi_cols; ++c) {
203 // Cyclic refresh segments are considered active despite not having
204 // AM_SEGMENT_ID_ACTIVE
205 new_map_16x16[(r >> 1) * cols + (c >> 1)] |=
206 seg_map_8x8[r * mi_cols + c] != AM_SEGMENT_ID_INACTIVE;
216 void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv) {
217 MACROBLOCK *const mb = &cpi->td.mb;
218 cpi->common.allow_high_precision_mv = allow_high_precision_mv;
219 if (cpi->common.allow_high_precision_mv) {
220 mb->mvcost = mb->nmvcost_hp;
221 mb->mvsadcost = mb->nmvsadcost_hp;
223 mb->mvcost = mb->nmvcost;
224 mb->mvsadcost = mb->nmvsadcost;
228 static void setup_frame(VP9_COMP *cpi) {
229 VP9_COMMON *const cm = &cpi->common;
230 // Set up entropy context depending on frame type. The decoder mandates
231 // the use of the default context, index 0, for keyframes and inter
232 // frames where the error_resilient_mode or intra_only flag is set. For
233 // other inter-frames the encoder currently uses only two contexts;
234 // context 1 for ALTREF frames and context 0 for the others.
235 if (frame_is_intra_only(cm) || cm->error_resilient_mode) {
236 vp9_setup_past_independence(cm);
239 cm->frame_context_idx = cpi->refresh_alt_ref_frame;
242 if (cm->frame_type == KEY_FRAME) {
243 if (!is_two_pass_svc(cpi))
244 cpi->refresh_golden_frame = 1;
245 cpi->refresh_alt_ref_frame = 1;
246 vp9_zero(cpi->interp_filter_selected);
248 *cm->fc = cm->frame_contexts[cm->frame_context_idx];
249 vp9_zero(cpi->interp_filter_selected[0]);
253 static void vp9_enc_setup_mi(VP9_COMMON *cm) {
255 cm->mi = cm->mip + cm->mi_stride + 1;
256 memset(cm->mip, 0, cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mip));
257 cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
258 // Clear top border row
259 memset(cm->prev_mip, 0, sizeof(*cm->prev_mip) * cm->mi_stride);
260 // Clear left border column
261 for (i = 1; i < cm->mi_rows + 1; ++i)
262 memset(&cm->prev_mip[i * cm->mi_stride], 0, sizeof(*cm->prev_mip));
264 cm->mi_grid_visible = cm->mi_grid_base + cm->mi_stride + 1;
265 cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mi_stride + 1;
267 memset(cm->mi_grid_base, 0,
268 cm->mi_stride * (cm->mi_rows + 1) * sizeof(*cm->mi_grid_base));
271 static int vp9_enc_alloc_mi(VP9_COMMON *cm, int mi_size) {
272 cm->mip = vpx_calloc(mi_size, sizeof(*cm->mip));
275 cm->prev_mip = vpx_calloc(mi_size, sizeof(*cm->prev_mip));
278 cm->mi_alloc_size = mi_size;
280 cm->mi_grid_base = (MODE_INFO **)vpx_calloc(mi_size, sizeof(MODE_INFO*));
281 if (!cm->mi_grid_base)
283 cm->prev_mi_grid_base = (MODE_INFO **)vpx_calloc(mi_size, sizeof(MODE_INFO*));
284 if (!cm->prev_mi_grid_base)
290 static void vp9_enc_free_mi(VP9_COMMON *cm) {
293 vpx_free(cm->prev_mip);
295 vpx_free(cm->mi_grid_base);
296 cm->mi_grid_base = NULL;
297 vpx_free(cm->prev_mi_grid_base);
298 cm->prev_mi_grid_base = NULL;
301 static void vp9_swap_mi_and_prev_mi(VP9_COMMON *cm) {
302 // Current mip will be the prev_mip for the next frame.
303 MODE_INFO **temp_base = cm->prev_mi_grid_base;
304 MODE_INFO *temp = cm->prev_mip;
305 cm->prev_mip = cm->mip;
308 // Update the upper left visible macroblock ptrs.
309 cm->mi = cm->mip + cm->mi_stride + 1;
310 cm->prev_mi = cm->prev_mip + cm->mi_stride + 1;
312 cm->prev_mi_grid_base = cm->mi_grid_base;
313 cm->mi_grid_base = temp_base;
314 cm->mi_grid_visible = cm->mi_grid_base + cm->mi_stride + 1;
315 cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mi_stride + 1;
318 void vp9_initialize_enc(void) {
319 static volatile int init_done = 0;
325 vp9_init_intra_predictors();
327 vp9_rc_init_minq_luts();
328 vp9_entropy_mv_init();
329 vp9_temporal_filter_init();
334 static void dealloc_compressor_data(VP9_COMP *cpi) {
335 VP9_COMMON *const cm = &cpi->common;
338 vpx_free(cpi->tile_data);
339 cpi->tile_data = NULL;
341 // Delete sementation map
342 vpx_free(cpi->segmentation_map);
343 cpi->segmentation_map = NULL;
344 vpx_free(cpi->coding_context.last_frame_seg_map_copy);
345 cpi->coding_context.last_frame_seg_map_copy = NULL;
347 vpx_free(cpi->nmvcosts[0]);
348 vpx_free(cpi->nmvcosts[1]);
349 cpi->nmvcosts[0] = NULL;
350 cpi->nmvcosts[1] = NULL;
352 vpx_free(cpi->nmvcosts_hp[0]);
353 vpx_free(cpi->nmvcosts_hp[1]);
354 cpi->nmvcosts_hp[0] = NULL;
355 cpi->nmvcosts_hp[1] = NULL;
357 vpx_free(cpi->nmvsadcosts[0]);
358 vpx_free(cpi->nmvsadcosts[1]);
359 cpi->nmvsadcosts[0] = NULL;
360 cpi->nmvsadcosts[1] = NULL;
362 vpx_free(cpi->nmvsadcosts_hp[0]);
363 vpx_free(cpi->nmvsadcosts_hp[1]);
364 cpi->nmvsadcosts_hp[0] = NULL;
365 cpi->nmvsadcosts_hp[1] = NULL;
367 vp9_cyclic_refresh_free(cpi->cyclic_refresh);
368 cpi->cyclic_refresh = NULL;
370 vpx_free(cpi->active_map.map);
371 cpi->active_map.map = NULL;
373 vp9_free_ref_frame_buffers(cm->buffer_pool);
374 #if CONFIG_VP9_POSTPROC
375 vp9_free_postproc_buffers(cm);
377 vp9_free_context_buffers(cm);
379 vp9_free_frame_buffer(&cpi->last_frame_uf);
380 vp9_free_frame_buffer(&cpi->scaled_source);
381 vp9_free_frame_buffer(&cpi->scaled_last_source);
382 vp9_free_frame_buffer(&cpi->alt_ref_buffer);
383 vp9_lookahead_destroy(cpi->lookahead);
385 vpx_free(cpi->tile_tok[0][0]);
386 cpi->tile_tok[0][0] = 0;
388 vp9_free_pc_tree(&cpi->td);
390 for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
391 LAYER_CONTEXT *const lc = &cpi->svc.layer_context[i];
392 vpx_free(lc->rc_twopass_stats_in.buf);
393 lc->rc_twopass_stats_in.buf = NULL;
394 lc->rc_twopass_stats_in.sz = 0;
397 if (cpi->source_diff_var != NULL) {
398 vpx_free(cpi->source_diff_var);
399 cpi->source_diff_var = NULL;
402 for (i = 0; i < MAX_LAG_BUFFERS; ++i) {
403 vp9_free_frame_buffer(&cpi->svc.scaled_frames[i]);
405 memset(&cpi->svc.scaled_frames[0], 0,
406 MAX_LAG_BUFFERS * sizeof(cpi->svc.scaled_frames[0]));
408 vp9_free_frame_buffer(&cpi->svc.empty_frame.img);
409 memset(&cpi->svc.empty_frame, 0, sizeof(cpi->svc.empty_frame));
412 static void save_coding_context(VP9_COMP *cpi) {
413 CODING_CONTEXT *const cc = &cpi->coding_context;
414 VP9_COMMON *cm = &cpi->common;
416 // Stores a snapshot of key state variables which can subsequently be
417 // restored with a call to vp9_restore_coding_context. These functions are
418 // intended for use in a re-code loop in vp9_compress_frame where the
419 // quantizer value is adjusted between loop iterations.
420 vp9_copy(cc->nmvjointcost, cpi->td.mb.nmvjointcost);
422 memcpy(cc->nmvcosts[0], cpi->nmvcosts[0],
423 MV_VALS * sizeof(*cpi->nmvcosts[0]));
424 memcpy(cc->nmvcosts[1], cpi->nmvcosts[1],
425 MV_VALS * sizeof(*cpi->nmvcosts[1]));
426 memcpy(cc->nmvcosts_hp[0], cpi->nmvcosts_hp[0],
427 MV_VALS * sizeof(*cpi->nmvcosts_hp[0]));
428 memcpy(cc->nmvcosts_hp[1], cpi->nmvcosts_hp[1],
429 MV_VALS * sizeof(*cpi->nmvcosts_hp[1]));
431 vp9_copy(cc->segment_pred_probs, cm->seg.pred_probs);
433 memcpy(cpi->coding_context.last_frame_seg_map_copy,
434 cm->last_frame_seg_map, (cm->mi_rows * cm->mi_cols));
436 vp9_copy(cc->last_ref_lf_deltas, cm->lf.last_ref_deltas);
437 vp9_copy(cc->last_mode_lf_deltas, cm->lf.last_mode_deltas);
442 static void restore_coding_context(VP9_COMP *cpi) {
443 CODING_CONTEXT *const cc = &cpi->coding_context;
444 VP9_COMMON *cm = &cpi->common;
446 // Restore key state variables to the snapshot state stored in the
447 // previous call to vp9_save_coding_context.
448 vp9_copy(cpi->td.mb.nmvjointcost, cc->nmvjointcost);
450 memcpy(cpi->nmvcosts[0], cc->nmvcosts[0], MV_VALS * sizeof(*cc->nmvcosts[0]));
451 memcpy(cpi->nmvcosts[1], cc->nmvcosts[1], MV_VALS * sizeof(*cc->nmvcosts[1]));
452 memcpy(cpi->nmvcosts_hp[0], cc->nmvcosts_hp[0],
453 MV_VALS * sizeof(*cc->nmvcosts_hp[0]));
454 memcpy(cpi->nmvcosts_hp[1], cc->nmvcosts_hp[1],
455 MV_VALS * sizeof(*cc->nmvcosts_hp[1]));
457 vp9_copy(cm->seg.pred_probs, cc->segment_pred_probs);
459 memcpy(cm->last_frame_seg_map,
460 cpi->coding_context.last_frame_seg_map_copy,
461 (cm->mi_rows * cm->mi_cols));
463 vp9_copy(cm->lf.last_ref_deltas, cc->last_ref_lf_deltas);
464 vp9_copy(cm->lf.last_mode_deltas, cc->last_mode_lf_deltas);
469 static void configure_static_seg_features(VP9_COMP *cpi) {
470 VP9_COMMON *const cm = &cpi->common;
471 const RATE_CONTROL *const rc = &cpi->rc;
472 struct segmentation *const seg = &cm->seg;
474 int high_q = (int)(rc->avg_q > 48.0);
477 // Disable and clear down for KF
478 if (cm->frame_type == KEY_FRAME) {
479 // Clear down the global segmentation map
480 memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
482 seg->update_data = 0;
483 cpi->static_mb_pct = 0;
485 // Disable segmentation
486 vp9_disable_segmentation(seg);
488 // Clear down the segment features.
489 vp9_clearall_segfeatures(seg);
490 } else if (cpi->refresh_alt_ref_frame) {
491 // If this is an alt ref frame
492 // Clear down the global segmentation map
493 memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
495 seg->update_data = 0;
496 cpi->static_mb_pct = 0;
498 // Disable segmentation and individual segment features by default
499 vp9_disable_segmentation(seg);
500 vp9_clearall_segfeatures(seg);
502 // Scan frames from current to arf frame.
503 // This function re-enables segmentation if appropriate.
504 vp9_update_mbgraph_stats(cpi);
506 // If segmentation was enabled set those features needed for the
510 seg->update_data = 1;
512 qi_delta = vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 0.875,
514 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta - 2);
515 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
517 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
518 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
520 // Where relevant assume segment data is delta data
521 seg->abs_delta = SEGMENT_DELTADATA;
523 } else if (seg->enabled) {
524 // All other frames if segmentation has been enabled
526 // First normal frame in a valid gf or alt ref group
527 if (rc->frames_since_golden == 0) {
528 // Set up segment features for normal frames in an arf group
529 if (rc->source_alt_ref_active) {
531 seg->update_data = 1;
532 seg->abs_delta = SEGMENT_DELTADATA;
534 qi_delta = vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 1.125,
536 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta + 2);
537 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
539 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
540 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
542 // Segment coding disabled for compred testing
543 if (high_q || (cpi->static_mb_pct == 100)) {
544 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
545 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
546 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
549 // Disable segmentation and clear down features if alt ref
550 // is not active for this group
552 vp9_disable_segmentation(seg);
554 memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
557 seg->update_data = 0;
559 vp9_clearall_segfeatures(seg);
561 } else if (rc->is_src_frame_alt_ref) {
562 // Special case where we are coding over the top of a previous
564 // Segment coding disabled for compred testing
566 // Enable ref frame features for segment 0 as well
567 vp9_enable_segfeature(seg, 0, SEG_LVL_REF_FRAME);
568 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
570 // All mbs should use ALTREF_FRAME
571 vp9_clear_segdata(seg, 0, SEG_LVL_REF_FRAME);
572 vp9_set_segdata(seg, 0, SEG_LVL_REF_FRAME, ALTREF_FRAME);
573 vp9_clear_segdata(seg, 1, SEG_LVL_REF_FRAME);
574 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
576 // Skip all MBs if high Q (0,0 mv and skip coeffs)
578 vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
579 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
581 // Enable data update
582 seg->update_data = 1;
586 // No updates.. leave things as they are.
588 seg->update_data = 0;
593 static void update_reference_segmentation_map(VP9_COMP *cpi) {
594 VP9_COMMON *const cm = &cpi->common;
595 MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
596 uint8_t *cache_ptr = cm->last_frame_seg_map;
599 for (row = 0; row < cm->mi_rows; row++) {
600 MODE_INFO **mi_8x8 = mi_8x8_ptr;
601 uint8_t *cache = cache_ptr;
602 for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
603 cache[0] = mi_8x8[0]->mbmi.segment_id;
604 mi_8x8_ptr += cm->mi_stride;
605 cache_ptr += cm->mi_cols;
609 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
610 VP9_COMMON *cm = &cpi->common;
611 const VP9EncoderConfig *oxcf = &cpi->oxcf;
614 cpi->lookahead = vp9_lookahead_init(oxcf->width, oxcf->height,
615 cm->subsampling_x, cm->subsampling_y,
616 #if CONFIG_VP9_HIGHBITDEPTH
617 cm->use_highbitdepth,
619 oxcf->lag_in_frames);
621 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
622 "Failed to allocate lag buffers");
624 // TODO(agrange) Check if ARF is enabled and skip allocation if not.
625 if (vp9_realloc_frame_buffer(&cpi->alt_ref_buffer,
626 oxcf->width, oxcf->height,
627 cm->subsampling_x, cm->subsampling_y,
628 #if CONFIG_VP9_HIGHBITDEPTH
629 cm->use_highbitdepth,
631 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
633 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
634 "Failed to allocate altref buffer");
637 static void alloc_util_frame_buffers(VP9_COMP *cpi) {
638 VP9_COMMON *const cm = &cpi->common;
639 if (vp9_realloc_frame_buffer(&cpi->last_frame_uf,
640 cm->width, cm->height,
641 cm->subsampling_x, cm->subsampling_y,
642 #if CONFIG_VP9_HIGHBITDEPTH
643 cm->use_highbitdepth,
645 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
647 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
648 "Failed to allocate last frame buffer");
650 if (vp9_realloc_frame_buffer(&cpi->scaled_source,
651 cm->width, cm->height,
652 cm->subsampling_x, cm->subsampling_y,
653 #if CONFIG_VP9_HIGHBITDEPTH
654 cm->use_highbitdepth,
656 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
658 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
659 "Failed to allocate scaled source buffer");
661 if (vp9_realloc_frame_buffer(&cpi->scaled_last_source,
662 cm->width, cm->height,
663 cm->subsampling_x, cm->subsampling_y,
664 #if CONFIG_VP9_HIGHBITDEPTH
665 cm->use_highbitdepth,
667 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
669 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
670 "Failed to allocate scaled last source buffer");
673 void vp9_alloc_compressor_data(VP9_COMP *cpi) {
674 VP9_COMMON *cm = &cpi->common;
676 vp9_alloc_context_buffers(cm, cm->width, cm->height);
678 vpx_free(cpi->tile_tok[0][0]);
681 unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
682 CHECK_MEM_ERROR(cm, cpi->tile_tok[0][0],
683 vpx_calloc(tokens, sizeof(*cpi->tile_tok[0][0])));
686 vp9_setup_pc_tree(&cpi->common, &cpi->td);
689 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
690 cpi->framerate = framerate < 0.1 ? 30 : framerate;
691 vp9_rc_update_framerate(cpi);
694 static void set_tile_limits(VP9_COMP *cpi) {
695 VP9_COMMON *const cm = &cpi->common;
697 int min_log2_tile_cols, max_log2_tile_cols;
698 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
700 if (is_two_pass_svc(cpi) &&
701 (cpi->svc.encode_empty_frame_state == ENCODING ||
702 cpi->svc.number_spatial_layers > 1)) {
703 cm->log2_tile_cols = 0;
704 cm->log2_tile_rows = 0;
706 cm->log2_tile_cols = clamp(cpi->oxcf.tile_columns,
707 min_log2_tile_cols, max_log2_tile_cols);
708 cm->log2_tile_rows = cpi->oxcf.tile_rows;
712 static void update_frame_size(VP9_COMP *cpi) {
713 VP9_COMMON *const cm = &cpi->common;
714 MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
716 vp9_set_mb_mi(cm, cm->width, cm->height);
717 vp9_init_context_buffers(cm);
718 init_macroblockd(cm, xd);
720 set_tile_limits(cpi);
722 if (is_two_pass_svc(cpi)) {
723 if (vp9_realloc_frame_buffer(&cpi->alt_ref_buffer,
724 cm->width, cm->height,
725 cm->subsampling_x, cm->subsampling_y,
726 #if CONFIG_VP9_HIGHBITDEPTH
727 cm->use_highbitdepth,
729 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
731 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
732 "Failed to reallocate alt_ref_buffer");
736 static void init_buffer_indices(VP9_COMP *cpi) {
742 static void init_config(struct VP9_COMP *cpi, VP9EncoderConfig *oxcf) {
743 VP9_COMMON *const cm = &cpi->common;
746 cpi->framerate = oxcf->init_framerate;
748 cm->profile = oxcf->profile;
749 cm->bit_depth = oxcf->bit_depth;
750 #if CONFIG_VP9_HIGHBITDEPTH
751 cm->use_highbitdepth = oxcf->use_highbitdepth;
753 cm->color_space = oxcf->color_space;
755 cm->width = oxcf->width;
756 cm->height = oxcf->height;
757 vp9_alloc_compressor_data(cpi);
759 cpi->svc.temporal_layering_mode = oxcf->temporal_layering_mode;
761 // Single thread case: use counts in common.
762 cpi->td.counts = &cm->counts;
764 // Spatial scalability.
765 cpi->svc.number_spatial_layers = oxcf->ss_number_layers;
766 // Temporal scalability.
767 cpi->svc.number_temporal_layers = oxcf->ts_number_layers;
769 if ((cpi->svc.number_temporal_layers > 1 && cpi->oxcf.rc_mode == VPX_CBR) ||
770 ((cpi->svc.number_temporal_layers > 1 ||
771 cpi->svc.number_spatial_layers > 1) &&
772 cpi->oxcf.pass != 1)) {
773 vp9_init_layer_context(cpi);
776 // change includes all joint functionality
777 vp9_change_config(cpi, oxcf);
779 cpi->static_mb_pct = 0;
780 cpi->ref_frame_flags = 0;
782 init_buffer_indices(cpi);
785 static void set_rc_buffer_sizes(RATE_CONTROL *rc,
786 const VP9EncoderConfig *oxcf) {
787 const int64_t bandwidth = oxcf->target_bandwidth;
788 const int64_t starting = oxcf->starting_buffer_level_ms;
789 const int64_t optimal = oxcf->optimal_buffer_level_ms;
790 const int64_t maximum = oxcf->maximum_buffer_size_ms;
792 rc->starting_buffer_level = starting * bandwidth / 1000;
793 rc->optimal_buffer_level = (optimal == 0) ? bandwidth / 8
794 : optimal * bandwidth / 1000;
795 rc->maximum_buffer_size = (maximum == 0) ? bandwidth / 8
796 : maximum * bandwidth / 1000;
799 #if CONFIG_VP9_HIGHBITDEPTH
800 #define HIGHBD_BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF) \
801 cpi->fn_ptr[BT].sdf = SDF; \
802 cpi->fn_ptr[BT].sdaf = SDAF; \
803 cpi->fn_ptr[BT].vf = VF; \
804 cpi->fn_ptr[BT].svf = SVF; \
805 cpi->fn_ptr[BT].svaf = SVAF; \
806 cpi->fn_ptr[BT].sdx3f = SDX3F; \
807 cpi->fn_ptr[BT].sdx8f = SDX8F; \
808 cpi->fn_ptr[BT].sdx4df = SDX4DF;
810 #define MAKE_BFP_SAD_WRAPPER(fnname) \
811 static unsigned int fnname##_bits8(const uint8_t *src_ptr, \
813 const uint8_t *ref_ptr, \
815 return fnname(src_ptr, source_stride, ref_ptr, ref_stride); \
817 static unsigned int fnname##_bits10(const uint8_t *src_ptr, \
819 const uint8_t *ref_ptr, \
821 return fnname(src_ptr, source_stride, ref_ptr, ref_stride) >> 2; \
823 static unsigned int fnname##_bits12(const uint8_t *src_ptr, \
825 const uint8_t *ref_ptr, \
827 return fnname(src_ptr, source_stride, ref_ptr, ref_stride) >> 4; \
830 #define MAKE_BFP_SADAVG_WRAPPER(fnname) static unsigned int \
831 fnname##_bits8(const uint8_t *src_ptr, \
833 const uint8_t *ref_ptr, \
835 const uint8_t *second_pred) { \
836 return fnname(src_ptr, source_stride, ref_ptr, ref_stride, second_pred); \
838 static unsigned int fnname##_bits10(const uint8_t *src_ptr, \
840 const uint8_t *ref_ptr, \
842 const uint8_t *second_pred) { \
843 return fnname(src_ptr, source_stride, ref_ptr, ref_stride, \
846 static unsigned int fnname##_bits12(const uint8_t *src_ptr, \
848 const uint8_t *ref_ptr, \
850 const uint8_t *second_pred) { \
851 return fnname(src_ptr, source_stride, ref_ptr, ref_stride, \
855 #define MAKE_BFP_SAD3_WRAPPER(fnname) \
856 static void fnname##_bits8(const uint8_t *src_ptr, \
858 const uint8_t *ref_ptr, \
860 unsigned int *sad_array) { \
861 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
863 static void fnname##_bits10(const uint8_t *src_ptr, \
865 const uint8_t *ref_ptr, \
867 unsigned int *sad_array) { \
869 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
870 for (i = 0; i < 3; i++) \
871 sad_array[i] >>= 2; \
873 static void fnname##_bits12(const uint8_t *src_ptr, \
875 const uint8_t *ref_ptr, \
877 unsigned int *sad_array) { \
879 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
880 for (i = 0; i < 3; i++) \
881 sad_array[i] >>= 4; \
884 #define MAKE_BFP_SAD8_WRAPPER(fnname) \
885 static void fnname##_bits8(const uint8_t *src_ptr, \
887 const uint8_t *ref_ptr, \
889 unsigned int *sad_array) { \
890 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
892 static void fnname##_bits10(const uint8_t *src_ptr, \
894 const uint8_t *ref_ptr, \
896 unsigned int *sad_array) { \
898 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
899 for (i = 0; i < 8; i++) \
900 sad_array[i] >>= 2; \
902 static void fnname##_bits12(const uint8_t *src_ptr, \
904 const uint8_t *ref_ptr, \
906 unsigned int *sad_array) { \
908 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
909 for (i = 0; i < 8; i++) \
910 sad_array[i] >>= 4; \
912 #define MAKE_BFP_SAD4D_WRAPPER(fnname) \
913 static void fnname##_bits8(const uint8_t *src_ptr, \
915 const uint8_t* const ref_ptr[], \
917 unsigned int *sad_array) { \
918 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
920 static void fnname##_bits10(const uint8_t *src_ptr, \
922 const uint8_t* const ref_ptr[], \
924 unsigned int *sad_array) { \
926 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
927 for (i = 0; i < 4; i++) \
928 sad_array[i] >>= 2; \
930 static void fnname##_bits12(const uint8_t *src_ptr, \
932 const uint8_t* const ref_ptr[], \
934 unsigned int *sad_array) { \
936 fnname(src_ptr, source_stride, ref_ptr, ref_stride, sad_array); \
937 for (i = 0; i < 4; i++) \
938 sad_array[i] >>= 4; \
941 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x16)
942 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x16_avg)
943 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x16x4d)
944 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x32)
945 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x32_avg)
946 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x32x4d)
947 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad64x32)
948 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad64x32_avg)
949 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad64x32x4d)
950 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x64)
951 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x64_avg)
952 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x64x4d)
953 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad32x32)
954 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad32x32_avg)
955 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad32x32x3)
956 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad32x32x8)
957 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad32x32x4d)
958 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad64x64)
959 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad64x64_avg)
960 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad64x64x3)
961 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad64x64x8)
962 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad64x64x4d)
963 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x16)
964 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x16_avg)
965 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad16x16x3)
966 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad16x16x8)
967 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x16x4d)
968 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad16x8)
969 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad16x8_avg)
970 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad16x8x3)
971 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad16x8x8)
972 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad16x8x4d)
973 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x16)
974 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x16_avg)
975 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad8x16x3)
976 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x16x8)
977 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x16x4d)
978 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x8)
979 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x8_avg)
980 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad8x8x3)
981 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x8x8)
982 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x8x4d)
983 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad8x4)
984 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad8x4_avg)
985 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad8x4x8)
986 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad8x4x4d)
987 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad4x8)
988 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad4x8_avg)
989 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad4x8x8)
990 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad4x8x4d)
991 MAKE_BFP_SAD_WRAPPER(vpx_highbd_sad4x4)
992 MAKE_BFP_SADAVG_WRAPPER(vpx_highbd_sad4x4_avg)
993 MAKE_BFP_SAD3_WRAPPER(vpx_highbd_sad4x4x3)
994 MAKE_BFP_SAD8_WRAPPER(vpx_highbd_sad4x4x8)
995 MAKE_BFP_SAD4D_WRAPPER(vpx_highbd_sad4x4x4d)
997 static void highbd_set_var_fns(VP9_COMP *const cpi) {
998 VP9_COMMON *const cm = &cpi->common;
999 if (cm->use_highbitdepth) {
1000 switch (cm->bit_depth) {
1002 HIGHBD_BFP(BLOCK_32X16,
1003 vpx_highbd_sad32x16_bits8,
1004 vpx_highbd_sad32x16_avg_bits8,
1005 vpx_highbd_8_variance32x16,
1006 vp9_highbd_sub_pixel_variance32x16,
1007 vp9_highbd_sub_pixel_avg_variance32x16,
1010 vpx_highbd_sad32x16x4d_bits8)
1012 HIGHBD_BFP(BLOCK_16X32,
1013 vpx_highbd_sad16x32_bits8,
1014 vpx_highbd_sad16x32_avg_bits8,
1015 vpx_highbd_8_variance16x32,
1016 vp9_highbd_sub_pixel_variance16x32,
1017 vp9_highbd_sub_pixel_avg_variance16x32,
1020 vpx_highbd_sad16x32x4d_bits8)
1022 HIGHBD_BFP(BLOCK_64X32,
1023 vpx_highbd_sad64x32_bits8,
1024 vpx_highbd_sad64x32_avg_bits8,
1025 vpx_highbd_8_variance64x32,
1026 vp9_highbd_sub_pixel_variance64x32,
1027 vp9_highbd_sub_pixel_avg_variance64x32,
1030 vpx_highbd_sad64x32x4d_bits8)
1032 HIGHBD_BFP(BLOCK_32X64,
1033 vpx_highbd_sad32x64_bits8,
1034 vpx_highbd_sad32x64_avg_bits8,
1035 vpx_highbd_8_variance32x64,
1036 vp9_highbd_sub_pixel_variance32x64,
1037 vp9_highbd_sub_pixel_avg_variance32x64,
1040 vpx_highbd_sad32x64x4d_bits8)
1042 HIGHBD_BFP(BLOCK_32X32,
1043 vpx_highbd_sad32x32_bits8,
1044 vpx_highbd_sad32x32_avg_bits8,
1045 vpx_highbd_8_variance32x32,
1046 vp9_highbd_sub_pixel_variance32x32,
1047 vp9_highbd_sub_pixel_avg_variance32x32,
1048 vpx_highbd_sad32x32x3_bits8,
1049 vpx_highbd_sad32x32x8_bits8,
1050 vpx_highbd_sad32x32x4d_bits8)
1052 HIGHBD_BFP(BLOCK_64X64,
1053 vpx_highbd_sad64x64_bits8,
1054 vpx_highbd_sad64x64_avg_bits8,
1055 vpx_highbd_8_variance64x64,
1056 vp9_highbd_sub_pixel_variance64x64,
1057 vp9_highbd_sub_pixel_avg_variance64x64,
1058 vpx_highbd_sad64x64x3_bits8,
1059 vpx_highbd_sad64x64x8_bits8,
1060 vpx_highbd_sad64x64x4d_bits8)
1062 HIGHBD_BFP(BLOCK_16X16,
1063 vpx_highbd_sad16x16_bits8,
1064 vpx_highbd_sad16x16_avg_bits8,
1065 vpx_highbd_8_variance16x16,
1066 vp9_highbd_sub_pixel_variance16x16,
1067 vp9_highbd_sub_pixel_avg_variance16x16,
1068 vpx_highbd_sad16x16x3_bits8,
1069 vpx_highbd_sad16x16x8_bits8,
1070 vpx_highbd_sad16x16x4d_bits8)
1072 HIGHBD_BFP(BLOCK_16X8,
1073 vpx_highbd_sad16x8_bits8,
1074 vpx_highbd_sad16x8_avg_bits8,
1075 vpx_highbd_8_variance16x8,
1076 vp9_highbd_sub_pixel_variance16x8,
1077 vp9_highbd_sub_pixel_avg_variance16x8,
1078 vpx_highbd_sad16x8x3_bits8,
1079 vpx_highbd_sad16x8x8_bits8,
1080 vpx_highbd_sad16x8x4d_bits8)
1082 HIGHBD_BFP(BLOCK_8X16,
1083 vpx_highbd_sad8x16_bits8,
1084 vpx_highbd_sad8x16_avg_bits8,
1085 vpx_highbd_8_variance8x16,
1086 vp9_highbd_sub_pixel_variance8x16,
1087 vp9_highbd_sub_pixel_avg_variance8x16,
1088 vpx_highbd_sad8x16x3_bits8,
1089 vpx_highbd_sad8x16x8_bits8,
1090 vpx_highbd_sad8x16x4d_bits8)
1092 HIGHBD_BFP(BLOCK_8X8,
1093 vpx_highbd_sad8x8_bits8,
1094 vpx_highbd_sad8x8_avg_bits8,
1095 vpx_highbd_8_variance8x8,
1096 vp9_highbd_sub_pixel_variance8x8,
1097 vp9_highbd_sub_pixel_avg_variance8x8,
1098 vpx_highbd_sad8x8x3_bits8,
1099 vpx_highbd_sad8x8x8_bits8,
1100 vpx_highbd_sad8x8x4d_bits8)
1102 HIGHBD_BFP(BLOCK_8X4,
1103 vpx_highbd_sad8x4_bits8,
1104 vpx_highbd_sad8x4_avg_bits8,
1105 vpx_highbd_8_variance8x4,
1106 vp9_highbd_sub_pixel_variance8x4,
1107 vp9_highbd_sub_pixel_avg_variance8x4,
1109 vpx_highbd_sad8x4x8_bits8,
1110 vpx_highbd_sad8x4x4d_bits8)
1112 HIGHBD_BFP(BLOCK_4X8,
1113 vpx_highbd_sad4x8_bits8,
1114 vpx_highbd_sad4x8_avg_bits8,
1115 vpx_highbd_8_variance4x8,
1116 vp9_highbd_sub_pixel_variance4x8,
1117 vp9_highbd_sub_pixel_avg_variance4x8,
1119 vpx_highbd_sad4x8x8_bits8,
1120 vpx_highbd_sad4x8x4d_bits8)
1122 HIGHBD_BFP(BLOCK_4X4,
1123 vpx_highbd_sad4x4_bits8,
1124 vpx_highbd_sad4x4_avg_bits8,
1125 vpx_highbd_8_variance4x4,
1126 vp9_highbd_sub_pixel_variance4x4,
1127 vp9_highbd_sub_pixel_avg_variance4x4,
1128 vpx_highbd_sad4x4x3_bits8,
1129 vpx_highbd_sad4x4x8_bits8,
1130 vpx_highbd_sad4x4x4d_bits8)
1134 HIGHBD_BFP(BLOCK_32X16,
1135 vpx_highbd_sad32x16_bits10,
1136 vpx_highbd_sad32x16_avg_bits10,
1137 vpx_highbd_10_variance32x16,
1138 vp9_highbd_10_sub_pixel_variance32x16,
1139 vp9_highbd_10_sub_pixel_avg_variance32x16,
1142 vpx_highbd_sad32x16x4d_bits10)
1144 HIGHBD_BFP(BLOCK_16X32,
1145 vpx_highbd_sad16x32_bits10,
1146 vpx_highbd_sad16x32_avg_bits10,
1147 vpx_highbd_10_variance16x32,
1148 vp9_highbd_10_sub_pixel_variance16x32,
1149 vp9_highbd_10_sub_pixel_avg_variance16x32,
1152 vpx_highbd_sad16x32x4d_bits10)
1154 HIGHBD_BFP(BLOCK_64X32,
1155 vpx_highbd_sad64x32_bits10,
1156 vpx_highbd_sad64x32_avg_bits10,
1157 vpx_highbd_10_variance64x32,
1158 vp9_highbd_10_sub_pixel_variance64x32,
1159 vp9_highbd_10_sub_pixel_avg_variance64x32,
1162 vpx_highbd_sad64x32x4d_bits10)
1164 HIGHBD_BFP(BLOCK_32X64,
1165 vpx_highbd_sad32x64_bits10,
1166 vpx_highbd_sad32x64_avg_bits10,
1167 vpx_highbd_10_variance32x64,
1168 vp9_highbd_10_sub_pixel_variance32x64,
1169 vp9_highbd_10_sub_pixel_avg_variance32x64,
1172 vpx_highbd_sad32x64x4d_bits10)
1174 HIGHBD_BFP(BLOCK_32X32,
1175 vpx_highbd_sad32x32_bits10,
1176 vpx_highbd_sad32x32_avg_bits10,
1177 vpx_highbd_10_variance32x32,
1178 vp9_highbd_10_sub_pixel_variance32x32,
1179 vp9_highbd_10_sub_pixel_avg_variance32x32,
1180 vpx_highbd_sad32x32x3_bits10,
1181 vpx_highbd_sad32x32x8_bits10,
1182 vpx_highbd_sad32x32x4d_bits10)
1184 HIGHBD_BFP(BLOCK_64X64,
1185 vpx_highbd_sad64x64_bits10,
1186 vpx_highbd_sad64x64_avg_bits10,
1187 vpx_highbd_10_variance64x64,
1188 vp9_highbd_10_sub_pixel_variance64x64,
1189 vp9_highbd_10_sub_pixel_avg_variance64x64,
1190 vpx_highbd_sad64x64x3_bits10,
1191 vpx_highbd_sad64x64x8_bits10,
1192 vpx_highbd_sad64x64x4d_bits10)
1194 HIGHBD_BFP(BLOCK_16X16,
1195 vpx_highbd_sad16x16_bits10,
1196 vpx_highbd_sad16x16_avg_bits10,
1197 vpx_highbd_10_variance16x16,
1198 vp9_highbd_10_sub_pixel_variance16x16,
1199 vp9_highbd_10_sub_pixel_avg_variance16x16,
1200 vpx_highbd_sad16x16x3_bits10,
1201 vpx_highbd_sad16x16x8_bits10,
1202 vpx_highbd_sad16x16x4d_bits10)
1204 HIGHBD_BFP(BLOCK_16X8,
1205 vpx_highbd_sad16x8_bits10,
1206 vpx_highbd_sad16x8_avg_bits10,
1207 vpx_highbd_10_variance16x8,
1208 vp9_highbd_10_sub_pixel_variance16x8,
1209 vp9_highbd_10_sub_pixel_avg_variance16x8,
1210 vpx_highbd_sad16x8x3_bits10,
1211 vpx_highbd_sad16x8x8_bits10,
1212 vpx_highbd_sad16x8x4d_bits10)
1214 HIGHBD_BFP(BLOCK_8X16,
1215 vpx_highbd_sad8x16_bits10,
1216 vpx_highbd_sad8x16_avg_bits10,
1217 vpx_highbd_10_variance8x16,
1218 vp9_highbd_10_sub_pixel_variance8x16,
1219 vp9_highbd_10_sub_pixel_avg_variance8x16,
1220 vpx_highbd_sad8x16x3_bits10,
1221 vpx_highbd_sad8x16x8_bits10,
1222 vpx_highbd_sad8x16x4d_bits10)
1224 HIGHBD_BFP(BLOCK_8X8,
1225 vpx_highbd_sad8x8_bits10,
1226 vpx_highbd_sad8x8_avg_bits10,
1227 vpx_highbd_10_variance8x8,
1228 vp9_highbd_10_sub_pixel_variance8x8,
1229 vp9_highbd_10_sub_pixel_avg_variance8x8,
1230 vpx_highbd_sad8x8x3_bits10,
1231 vpx_highbd_sad8x8x8_bits10,
1232 vpx_highbd_sad8x8x4d_bits10)
1234 HIGHBD_BFP(BLOCK_8X4,
1235 vpx_highbd_sad8x4_bits10,
1236 vpx_highbd_sad8x4_avg_bits10,
1237 vpx_highbd_10_variance8x4,
1238 vp9_highbd_10_sub_pixel_variance8x4,
1239 vp9_highbd_10_sub_pixel_avg_variance8x4,
1241 vpx_highbd_sad8x4x8_bits10,
1242 vpx_highbd_sad8x4x4d_bits10)
1244 HIGHBD_BFP(BLOCK_4X8,
1245 vpx_highbd_sad4x8_bits10,
1246 vpx_highbd_sad4x8_avg_bits10,
1247 vpx_highbd_10_variance4x8,
1248 vp9_highbd_10_sub_pixel_variance4x8,
1249 vp9_highbd_10_sub_pixel_avg_variance4x8,
1251 vpx_highbd_sad4x8x8_bits10,
1252 vpx_highbd_sad4x8x4d_bits10)
1254 HIGHBD_BFP(BLOCK_4X4,
1255 vpx_highbd_sad4x4_bits10,
1256 vpx_highbd_sad4x4_avg_bits10,
1257 vpx_highbd_10_variance4x4,
1258 vp9_highbd_10_sub_pixel_variance4x4,
1259 vp9_highbd_10_sub_pixel_avg_variance4x4,
1260 vpx_highbd_sad4x4x3_bits10,
1261 vpx_highbd_sad4x4x8_bits10,
1262 vpx_highbd_sad4x4x4d_bits10)
1266 HIGHBD_BFP(BLOCK_32X16,
1267 vpx_highbd_sad32x16_bits12,
1268 vpx_highbd_sad32x16_avg_bits12,
1269 vpx_highbd_12_variance32x16,
1270 vp9_highbd_12_sub_pixel_variance32x16,
1271 vp9_highbd_12_sub_pixel_avg_variance32x16,
1274 vpx_highbd_sad32x16x4d_bits12)
1276 HIGHBD_BFP(BLOCK_16X32,
1277 vpx_highbd_sad16x32_bits12,
1278 vpx_highbd_sad16x32_avg_bits12,
1279 vpx_highbd_12_variance16x32,
1280 vp9_highbd_12_sub_pixel_variance16x32,
1281 vp9_highbd_12_sub_pixel_avg_variance16x32,
1284 vpx_highbd_sad16x32x4d_bits12)
1286 HIGHBD_BFP(BLOCK_64X32,
1287 vpx_highbd_sad64x32_bits12,
1288 vpx_highbd_sad64x32_avg_bits12,
1289 vpx_highbd_12_variance64x32,
1290 vp9_highbd_12_sub_pixel_variance64x32,
1291 vp9_highbd_12_sub_pixel_avg_variance64x32,
1294 vpx_highbd_sad64x32x4d_bits12)
1296 HIGHBD_BFP(BLOCK_32X64,
1297 vpx_highbd_sad32x64_bits12,
1298 vpx_highbd_sad32x64_avg_bits12,
1299 vpx_highbd_12_variance32x64,
1300 vp9_highbd_12_sub_pixel_variance32x64,
1301 vp9_highbd_12_sub_pixel_avg_variance32x64,
1304 vpx_highbd_sad32x64x4d_bits12)
1306 HIGHBD_BFP(BLOCK_32X32,
1307 vpx_highbd_sad32x32_bits12,
1308 vpx_highbd_sad32x32_avg_bits12,
1309 vpx_highbd_12_variance32x32,
1310 vp9_highbd_12_sub_pixel_variance32x32,
1311 vp9_highbd_12_sub_pixel_avg_variance32x32,
1312 vpx_highbd_sad32x32x3_bits12,
1313 vpx_highbd_sad32x32x8_bits12,
1314 vpx_highbd_sad32x32x4d_bits12)
1316 HIGHBD_BFP(BLOCK_64X64,
1317 vpx_highbd_sad64x64_bits12,
1318 vpx_highbd_sad64x64_avg_bits12,
1319 vpx_highbd_12_variance64x64,
1320 vp9_highbd_12_sub_pixel_variance64x64,
1321 vp9_highbd_12_sub_pixel_avg_variance64x64,
1322 vpx_highbd_sad64x64x3_bits12,
1323 vpx_highbd_sad64x64x8_bits12,
1324 vpx_highbd_sad64x64x4d_bits12)
1326 HIGHBD_BFP(BLOCK_16X16,
1327 vpx_highbd_sad16x16_bits12,
1328 vpx_highbd_sad16x16_avg_bits12,
1329 vpx_highbd_12_variance16x16,
1330 vp9_highbd_12_sub_pixel_variance16x16,
1331 vp9_highbd_12_sub_pixel_avg_variance16x16,
1332 vpx_highbd_sad16x16x3_bits12,
1333 vpx_highbd_sad16x16x8_bits12,
1334 vpx_highbd_sad16x16x4d_bits12)
1336 HIGHBD_BFP(BLOCK_16X8,
1337 vpx_highbd_sad16x8_bits12,
1338 vpx_highbd_sad16x8_avg_bits12,
1339 vpx_highbd_12_variance16x8,
1340 vp9_highbd_12_sub_pixel_variance16x8,
1341 vp9_highbd_12_sub_pixel_avg_variance16x8,
1342 vpx_highbd_sad16x8x3_bits12,
1343 vpx_highbd_sad16x8x8_bits12,
1344 vpx_highbd_sad16x8x4d_bits12)
1346 HIGHBD_BFP(BLOCK_8X16,
1347 vpx_highbd_sad8x16_bits12,
1348 vpx_highbd_sad8x16_avg_bits12,
1349 vpx_highbd_12_variance8x16,
1350 vp9_highbd_12_sub_pixel_variance8x16,
1351 vp9_highbd_12_sub_pixel_avg_variance8x16,
1352 vpx_highbd_sad8x16x3_bits12,
1353 vpx_highbd_sad8x16x8_bits12,
1354 vpx_highbd_sad8x16x4d_bits12)
1356 HIGHBD_BFP(BLOCK_8X8,
1357 vpx_highbd_sad8x8_bits12,
1358 vpx_highbd_sad8x8_avg_bits12,
1359 vpx_highbd_12_variance8x8,
1360 vp9_highbd_12_sub_pixel_variance8x8,
1361 vp9_highbd_12_sub_pixel_avg_variance8x8,
1362 vpx_highbd_sad8x8x3_bits12,
1363 vpx_highbd_sad8x8x8_bits12,
1364 vpx_highbd_sad8x8x4d_bits12)
1366 HIGHBD_BFP(BLOCK_8X4,
1367 vpx_highbd_sad8x4_bits12,
1368 vpx_highbd_sad8x4_avg_bits12,
1369 vpx_highbd_12_variance8x4,
1370 vp9_highbd_12_sub_pixel_variance8x4,
1371 vp9_highbd_12_sub_pixel_avg_variance8x4,
1373 vpx_highbd_sad8x4x8_bits12,
1374 vpx_highbd_sad8x4x4d_bits12)
1376 HIGHBD_BFP(BLOCK_4X8,
1377 vpx_highbd_sad4x8_bits12,
1378 vpx_highbd_sad4x8_avg_bits12,
1379 vpx_highbd_12_variance4x8,
1380 vp9_highbd_12_sub_pixel_variance4x8,
1381 vp9_highbd_12_sub_pixel_avg_variance4x8,
1383 vpx_highbd_sad4x8x8_bits12,
1384 vpx_highbd_sad4x8x4d_bits12)
1386 HIGHBD_BFP(BLOCK_4X4,
1387 vpx_highbd_sad4x4_bits12,
1388 vpx_highbd_sad4x4_avg_bits12,
1389 vpx_highbd_12_variance4x4,
1390 vp9_highbd_12_sub_pixel_variance4x4,
1391 vp9_highbd_12_sub_pixel_avg_variance4x4,
1392 vpx_highbd_sad4x4x3_bits12,
1393 vpx_highbd_sad4x4x8_bits12,
1394 vpx_highbd_sad4x4x4d_bits12)
1398 assert(0 && "cm->bit_depth should be VPX_BITS_8, "
1399 "VPX_BITS_10 or VPX_BITS_12");
1403 #endif // CONFIG_VP9_HIGHBITDEPTH
1405 static void realloc_segmentation_maps(VP9_COMP *cpi) {
1406 VP9_COMMON *const cm = &cpi->common;
1408 // Create the encoder segmentation map and set all entries to 0
1409 vpx_free(cpi->segmentation_map);
1410 CHECK_MEM_ERROR(cm, cpi->segmentation_map,
1411 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1413 // Create a map used for cyclic background refresh.
1414 if (cpi->cyclic_refresh)
1415 vp9_cyclic_refresh_free(cpi->cyclic_refresh);
1416 CHECK_MEM_ERROR(cm, cpi->cyclic_refresh,
1417 vp9_cyclic_refresh_alloc(cm->mi_rows, cm->mi_cols));
1419 // Create a map used to mark inactive areas.
1420 vpx_free(cpi->active_map.map);
1421 CHECK_MEM_ERROR(cm, cpi->active_map.map,
1422 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1424 // And a place holder structure is the coding context
1425 // for use if we want to save and restore it
1426 vpx_free(cpi->coding_context.last_frame_seg_map_copy);
1427 CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
1428 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1431 void vp9_change_config(struct VP9_COMP *cpi, const VP9EncoderConfig *oxcf) {
1432 VP9_COMMON *const cm = &cpi->common;
1433 RATE_CONTROL *const rc = &cpi->rc;
1435 if (cm->profile != oxcf->profile)
1436 cm->profile = oxcf->profile;
1437 cm->bit_depth = oxcf->bit_depth;
1438 cm->color_space = oxcf->color_space;
1440 if (cm->profile <= PROFILE_1)
1441 assert(cm->bit_depth == VPX_BITS_8);
1443 assert(cm->bit_depth > VPX_BITS_8);
1446 #if CONFIG_VP9_HIGHBITDEPTH
1447 cpi->td.mb.e_mbd.bd = (int)cm->bit_depth;
1448 #endif // CONFIG_VP9_HIGHBITDEPTH
1450 rc->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1452 cpi->refresh_golden_frame = 0;
1453 cpi->refresh_last_frame = 1;
1454 cm->refresh_frame_context = 1;
1455 cm->reset_frame_context = 0;
1457 vp9_reset_segment_features(&cm->seg);
1458 vp9_set_high_precision_mv(cpi, 0);
1463 for (i = 0; i < MAX_SEGMENTS; i++)
1464 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1466 cpi->encode_breakout = cpi->oxcf.encode_breakout;
1468 set_rc_buffer_sizes(rc, &cpi->oxcf);
1470 // Under a configuration change, where maximum_buffer_size may change,
1471 // keep buffer level clipped to the maximum allowed buffer size.
1472 rc->bits_off_target = MIN(rc->bits_off_target, rc->maximum_buffer_size);
1473 rc->buffer_level = MIN(rc->buffer_level, rc->maximum_buffer_size);
1475 // Set up frame rate and related parameters rate control values.
1476 vp9_new_framerate(cpi, cpi->framerate);
1478 // Set absolute upper and lower quality limits
1479 rc->worst_quality = cpi->oxcf.worst_allowed_q;
1480 rc->best_quality = cpi->oxcf.best_allowed_q;
1482 cm->interp_filter = cpi->sf.default_interp_filter;
1484 cm->display_width = cpi->oxcf.width;
1485 cm->display_height = cpi->oxcf.height;
1486 cm->width = cpi->oxcf.width;
1487 cm->height = cpi->oxcf.height;
1489 if (cpi->initial_width) {
1490 if (cm->width > cpi->initial_width || cm->height > cpi->initial_height) {
1491 vp9_free_context_buffers(cm);
1492 vp9_alloc_compressor_data(cpi);
1493 realloc_segmentation_maps(cpi);
1494 cpi->initial_width = cpi->initial_height = 0;
1497 update_frame_size(cpi);
1499 if ((cpi->svc.number_temporal_layers > 1 &&
1500 cpi->oxcf.rc_mode == VPX_CBR) ||
1501 ((cpi->svc.number_temporal_layers > 1 ||
1502 cpi->svc.number_spatial_layers > 1) &&
1503 cpi->oxcf.pass != 1)) {
1504 vp9_update_layer_context_change_config(cpi,
1505 (int)cpi->oxcf.target_bandwidth);
1508 cpi->alt_ref_source = NULL;
1509 rc->is_src_frame_alt_ref = 0;
1512 // Experimental RD Code
1513 cpi->frame_distortion = 0;
1514 cpi->last_frame_distortion = 0;
1517 set_tile_limits(cpi);
1519 cpi->ext_refresh_frame_flags_pending = 0;
1520 cpi->ext_refresh_frame_context_pending = 0;
1522 #if CONFIG_VP9_HIGHBITDEPTH
1523 highbd_set_var_fns(cpi);
1528 #define M_LOG2_E 0.693147180559945309417
1530 #define log2f(x) (log (x) / (float) M_LOG2_E)
1532 static void cal_nmvjointsadcost(int *mvjointsadcost) {
1533 mvjointsadcost[0] = 600;
1534 mvjointsadcost[1] = 300;
1535 mvjointsadcost[2] = 300;
1536 mvjointsadcost[3] = 300;
1539 static void cal_nmvsadcosts(int *mvsadcost[2]) {
1542 mvsadcost[0][0] = 0;
1543 mvsadcost[1][0] = 0;
1546 double z = 256 * (2 * (log2f(8 * i) + .6));
1547 mvsadcost[0][i] = (int)z;
1548 mvsadcost[1][i] = (int)z;
1549 mvsadcost[0][-i] = (int)z;
1550 mvsadcost[1][-i] = (int)z;
1551 } while (++i <= MV_MAX);
1554 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
1557 mvsadcost[0][0] = 0;
1558 mvsadcost[1][0] = 0;
1561 double z = 256 * (2 * (log2f(8 * i) + .6));
1562 mvsadcost[0][i] = (int)z;
1563 mvsadcost[1][i] = (int)z;
1564 mvsadcost[0][-i] = (int)z;
1565 mvsadcost[1][-i] = (int)z;
1566 } while (++i <= MV_MAX);
1570 VP9_COMP *vp9_create_compressor(VP9EncoderConfig *oxcf,
1571 BufferPool *const pool) {
1573 VP9_COMP *volatile const cpi = vpx_memalign(32, sizeof(VP9_COMP));
1574 VP9_COMMON *volatile const cm = cpi != NULL ? &cpi->common : NULL;
1581 if (setjmp(cm->error.jmp)) {
1582 cm->error.setjmp = 0;
1583 vp9_remove_compressor(cpi);
1587 cm->error.setjmp = 1;
1588 cm->alloc_mi = vp9_enc_alloc_mi;
1589 cm->free_mi = vp9_enc_free_mi;
1590 cm->setup_mi = vp9_enc_setup_mi;
1592 CHECK_MEM_ERROR(cm, cm->fc,
1593 (FRAME_CONTEXT *)vpx_calloc(1, sizeof(*cm->fc)));
1594 CHECK_MEM_ERROR(cm, cm->frame_contexts,
1595 (FRAME_CONTEXT *)vpx_calloc(FRAME_CONTEXTS,
1596 sizeof(*cm->frame_contexts)));
1599 cpi->common.buffer_pool = pool;
1601 init_config(cpi, oxcf);
1602 vp9_rc_init(&cpi->oxcf, oxcf->pass, &cpi->rc);
1604 cm->current_video_frame = 0;
1605 cpi->partition_search_skippable_frame = 0;
1606 cpi->tile_data = NULL;
1608 realloc_segmentation_maps(cpi);
1610 CHECK_MEM_ERROR(cm, cpi->nmvcosts[0],
1611 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts[0])));
1612 CHECK_MEM_ERROR(cm, cpi->nmvcosts[1],
1613 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts[1])));
1614 CHECK_MEM_ERROR(cm, cpi->nmvcosts_hp[0],
1615 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts_hp[0])));
1616 CHECK_MEM_ERROR(cm, cpi->nmvcosts_hp[1],
1617 vpx_calloc(MV_VALS, sizeof(*cpi->nmvcosts_hp[1])));
1618 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts[0],
1619 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts[0])));
1620 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts[1],
1621 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts[1])));
1622 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts_hp[0],
1623 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts_hp[0])));
1624 CHECK_MEM_ERROR(cm, cpi->nmvsadcosts_hp[1],
1625 vpx_calloc(MV_VALS, sizeof(*cpi->nmvsadcosts_hp[1])));
1627 for (i = 0; i < (sizeof(cpi->mbgraph_stats) /
1628 sizeof(cpi->mbgraph_stats[0])); i++) {
1629 CHECK_MEM_ERROR(cm, cpi->mbgraph_stats[i].mb_stats,
1630 vpx_calloc(cm->MBs *
1631 sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
1634 #if CONFIG_FP_MB_STATS
1635 cpi->use_fp_mb_stats = 0;
1636 if (cpi->use_fp_mb_stats) {
1637 // a place holder used to store the first pass mb stats in the first pass
1638 CHECK_MEM_ERROR(cm, cpi->twopass.frame_mb_stats_buf,
1639 vpx_calloc(cm->MBs * sizeof(uint8_t), 1));
1641 cpi->twopass.frame_mb_stats_buf = NULL;
1645 cpi->refresh_alt_ref_frame = 0;
1646 cpi->multi_arf_last_grp_enabled = 0;
1648 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1649 #if CONFIG_INTERNAL_STATS
1650 cpi->b_calculate_ssimg = 0;
1651 cpi->b_calculate_blockiness = 1;
1652 cpi->b_calculate_consistency = 1;
1653 cpi->total_inconsistency = 0;
1654 cpi->psnr.worst = 100.0;
1655 cpi->worst_ssim = 100.0;
1660 if (cpi->b_calculate_psnr) {
1661 cpi->total_sq_error = 0;
1662 cpi->total_samples = 0;
1664 cpi->totalp_sq_error = 0;
1665 cpi->totalp_samples = 0;
1667 cpi->tot_recode_hits = 0;
1668 cpi->summed_quality = 0;
1669 cpi->summed_weights = 0;
1670 cpi->summedp_quality = 0;
1671 cpi->summedp_weights = 0;
1674 if (cpi->b_calculate_ssimg) {
1675 cpi->ssimg.worst= 100.0;
1677 cpi->fastssim.worst = 100.0;
1679 cpi->psnrhvs.worst = 100.0;
1681 if (cpi->b_calculate_blockiness) {
1682 cpi->total_blockiness = 0;
1683 cpi->worst_blockiness = 0.0;
1686 if (cpi->b_calculate_consistency) {
1687 cpi->ssim_vars = vpx_malloc(sizeof(*cpi->ssim_vars)*720*480);
1688 cpi->worst_consistency = 100.0;
1693 cpi->first_time_stamp_ever = INT64_MAX;
1695 cal_nmvjointsadcost(cpi->td.mb.nmvjointsadcost);
1696 cpi->td.mb.nmvcost[0] = &cpi->nmvcosts[0][MV_MAX];
1697 cpi->td.mb.nmvcost[1] = &cpi->nmvcosts[1][MV_MAX];
1698 cpi->td.mb.nmvsadcost[0] = &cpi->nmvsadcosts[0][MV_MAX];
1699 cpi->td.mb.nmvsadcost[1] = &cpi->nmvsadcosts[1][MV_MAX];
1700 cal_nmvsadcosts(cpi->td.mb.nmvsadcost);
1702 cpi->td.mb.nmvcost_hp[0] = &cpi->nmvcosts_hp[0][MV_MAX];
1703 cpi->td.mb.nmvcost_hp[1] = &cpi->nmvcosts_hp[1][MV_MAX];
1704 cpi->td.mb.nmvsadcost_hp[0] = &cpi->nmvsadcosts_hp[0][MV_MAX];
1705 cpi->td.mb.nmvsadcost_hp[1] = &cpi->nmvsadcosts_hp[1][MV_MAX];
1706 cal_nmvsadcosts_hp(cpi->td.mb.nmvsadcost_hp);
1708 #if CONFIG_VP9_TEMPORAL_DENOISING
1709 #ifdef OUTPUT_YUV_DENOISED
1710 yuv_denoised_file = fopen("denoised.yuv", "ab");
1713 #ifdef OUTPUT_YUV_SKINMAP
1714 yuv_skinmap_file = fopen("skinmap.yuv", "ab");
1716 #ifdef OUTPUT_YUV_REC
1717 yuv_rec_file = fopen("rec.yuv", "wb");
1721 framepsnr = fopen("framepsnr.stt", "a");
1722 kf_list = fopen("kf_list.stt", "w");
1725 cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
1727 if (oxcf->pass == 1) {
1728 vp9_init_first_pass(cpi);
1729 } else if (oxcf->pass == 2) {
1730 const size_t packet_sz = sizeof(FIRSTPASS_STATS);
1731 const int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
1733 if (cpi->svc.number_spatial_layers > 1
1734 || cpi->svc.number_temporal_layers > 1) {
1735 FIRSTPASS_STATS *const stats = oxcf->two_pass_stats_in.buf;
1736 FIRSTPASS_STATS *stats_copy[VPX_SS_MAX_LAYERS] = {0};
1739 for (i = 0; i < oxcf->ss_number_layers; ++i) {
1740 FIRSTPASS_STATS *const last_packet_for_layer =
1741 &stats[packets - oxcf->ss_number_layers + i];
1742 const int layer_id = (int)last_packet_for_layer->spatial_layer_id;
1743 const int packets_in_layer = (int)last_packet_for_layer->count + 1;
1744 if (layer_id >= 0 && layer_id < oxcf->ss_number_layers) {
1745 LAYER_CONTEXT *const lc = &cpi->svc.layer_context[layer_id];
1747 vpx_free(lc->rc_twopass_stats_in.buf);
1749 lc->rc_twopass_stats_in.sz = packets_in_layer * packet_sz;
1750 CHECK_MEM_ERROR(cm, lc->rc_twopass_stats_in.buf,
1751 vpx_malloc(lc->rc_twopass_stats_in.sz));
1752 lc->twopass.stats_in_start = lc->rc_twopass_stats_in.buf;
1753 lc->twopass.stats_in = lc->twopass.stats_in_start;
1754 lc->twopass.stats_in_end = lc->twopass.stats_in_start
1755 + packets_in_layer - 1;
1756 stats_copy[layer_id] = lc->rc_twopass_stats_in.buf;
1760 for (i = 0; i < packets; ++i) {
1761 const int layer_id = (int)stats[i].spatial_layer_id;
1762 if (layer_id >= 0 && layer_id < oxcf->ss_number_layers
1763 && stats_copy[layer_id] != NULL) {
1764 *stats_copy[layer_id] = stats[i];
1765 ++stats_copy[layer_id];
1769 vp9_init_second_pass_spatial_svc(cpi);
1771 #if CONFIG_FP_MB_STATS
1772 if (cpi->use_fp_mb_stats) {
1773 const size_t psz = cpi->common.MBs * sizeof(uint8_t);
1774 const int ps = (int)(oxcf->firstpass_mb_stats_in.sz / psz);
1776 cpi->twopass.firstpass_mb_stats.mb_stats_start =
1777 oxcf->firstpass_mb_stats_in.buf;
1778 cpi->twopass.firstpass_mb_stats.mb_stats_end =
1779 cpi->twopass.firstpass_mb_stats.mb_stats_start +
1780 (ps - 1) * cpi->common.MBs * sizeof(uint8_t);
1784 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1785 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1786 cpi->twopass.stats_in_end = &cpi->twopass.stats_in[packets - 1];
1788 vp9_init_second_pass(cpi);
1792 vp9_set_speed_features_framesize_independent(cpi);
1793 vp9_set_speed_features_framesize_dependent(cpi);
1795 // Allocate memory to store variances for a frame.
1796 CHECK_MEM_ERROR(cm, cpi->source_diff_var,
1797 vpx_calloc(cm->MBs, sizeof(diff)));
1798 cpi->source_var_thresh = 0;
1799 cpi->frames_till_next_var_check = 0;
1801 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF)\
1802 cpi->fn_ptr[BT].sdf = SDF; \
1803 cpi->fn_ptr[BT].sdaf = SDAF; \
1804 cpi->fn_ptr[BT].vf = VF; \
1805 cpi->fn_ptr[BT].svf = SVF; \
1806 cpi->fn_ptr[BT].svaf = SVAF; \
1807 cpi->fn_ptr[BT].sdx3f = SDX3F; \
1808 cpi->fn_ptr[BT].sdx8f = SDX8F; \
1809 cpi->fn_ptr[BT].sdx4df = SDX4DF;
1811 BFP(BLOCK_32X16, vpx_sad32x16, vpx_sad32x16_avg,
1812 vpx_variance32x16, vp9_sub_pixel_variance32x16,
1813 vp9_sub_pixel_avg_variance32x16, NULL, NULL, vpx_sad32x16x4d)
1815 BFP(BLOCK_16X32, vpx_sad16x32, vpx_sad16x32_avg,
1816 vpx_variance16x32, vp9_sub_pixel_variance16x32,
1817 vp9_sub_pixel_avg_variance16x32, NULL, NULL, vpx_sad16x32x4d)
1819 BFP(BLOCK_64X32, vpx_sad64x32, vpx_sad64x32_avg,
1820 vpx_variance64x32, vp9_sub_pixel_variance64x32,
1821 vp9_sub_pixel_avg_variance64x32, NULL, NULL, vpx_sad64x32x4d)
1823 BFP(BLOCK_32X64, vpx_sad32x64, vpx_sad32x64_avg,
1824 vpx_variance32x64, vp9_sub_pixel_variance32x64,
1825 vp9_sub_pixel_avg_variance32x64, NULL, NULL, vpx_sad32x64x4d)
1827 BFP(BLOCK_32X32, vpx_sad32x32, vpx_sad32x32_avg,
1828 vpx_variance32x32, vp9_sub_pixel_variance32x32,
1829 vp9_sub_pixel_avg_variance32x32, vpx_sad32x32x3, vpx_sad32x32x8,
1832 BFP(BLOCK_64X64, vpx_sad64x64, vpx_sad64x64_avg,
1833 vpx_variance64x64, vp9_sub_pixel_variance64x64,
1834 vp9_sub_pixel_avg_variance64x64, vpx_sad64x64x3, vpx_sad64x64x8,
1837 BFP(BLOCK_16X16, vpx_sad16x16, vpx_sad16x16_avg,
1838 vpx_variance16x16, vp9_sub_pixel_variance16x16,
1839 vp9_sub_pixel_avg_variance16x16, vpx_sad16x16x3, vpx_sad16x16x8,
1842 BFP(BLOCK_16X8, vpx_sad16x8, vpx_sad16x8_avg,
1843 vpx_variance16x8, vp9_sub_pixel_variance16x8,
1844 vp9_sub_pixel_avg_variance16x8,
1845 vpx_sad16x8x3, vpx_sad16x8x8, vpx_sad16x8x4d)
1847 BFP(BLOCK_8X16, vpx_sad8x16, vpx_sad8x16_avg,
1848 vpx_variance8x16, vp9_sub_pixel_variance8x16,
1849 vp9_sub_pixel_avg_variance8x16,
1850 vpx_sad8x16x3, vpx_sad8x16x8, vpx_sad8x16x4d)
1852 BFP(BLOCK_8X8, vpx_sad8x8, vpx_sad8x8_avg,
1853 vpx_variance8x8, vp9_sub_pixel_variance8x8,
1854 vp9_sub_pixel_avg_variance8x8,
1855 vpx_sad8x8x3, vpx_sad8x8x8, vpx_sad8x8x4d)
1857 BFP(BLOCK_8X4, vpx_sad8x4, vpx_sad8x4_avg,
1858 vpx_variance8x4, vp9_sub_pixel_variance8x4,
1859 vp9_sub_pixel_avg_variance8x4, NULL, vpx_sad8x4x8, vpx_sad8x4x4d)
1861 BFP(BLOCK_4X8, vpx_sad4x8, vpx_sad4x8_avg,
1862 vpx_variance4x8, vp9_sub_pixel_variance4x8,
1863 vp9_sub_pixel_avg_variance4x8, NULL, vpx_sad4x8x8, vpx_sad4x8x4d)
1865 BFP(BLOCK_4X4, vpx_sad4x4, vpx_sad4x4_avg,
1866 vpx_variance4x4, vp9_sub_pixel_variance4x4,
1867 vp9_sub_pixel_avg_variance4x4,
1868 vpx_sad4x4x3, vpx_sad4x4x8, vpx_sad4x4x4d)
1870 #if CONFIG_VP9_HIGHBITDEPTH
1871 highbd_set_var_fns(cpi);
1874 /* vp9_init_quantizer() is first called here. Add check in
1875 * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
1876 * called later when needed. This will avoid unnecessary calls of
1877 * vp9_init_quantizer() for every frame.
1879 vp9_init_quantizer(cpi);
1881 vp9_loop_filter_init(cm);
1883 cm->error.setjmp = 0;
1887 #define SNPRINT(H, T) \
1888 snprintf((H) + strlen(H), sizeof(H) - strlen(H), (T))
1890 #define SNPRINT2(H, T, V) \
1891 snprintf((H) + strlen(H), sizeof(H) - strlen(H), (T), (V))
1893 void vp9_remove_compressor(VP9_COMP *cpi) {
1894 VP9_COMMON *const cm = &cpi->common;
1901 if (cpi && (cm->current_video_frame > 0)) {
1902 #if CONFIG_INTERNAL_STATS
1903 vp9_clear_system_state();
1905 if (cpi->oxcf.pass != 1) {
1906 char headings[512] = {0};
1907 char results[512] = {0};
1908 FILE *f = fopen("opsnr.stt", "a");
1909 double time_encoded = (cpi->last_end_time_stamp_seen
1910 - cpi->first_time_stamp_ever) / 10000000.000;
1911 double total_encode_time = (cpi->time_receive_data +
1912 cpi->time_compress_data) / 1000.000;
1914 (double)cpi->bytes * (double) 8 / (double)1000 / time_encoded;
1915 const double peak = (double)((1 << cpi->oxcf.input_bit_depth) - 1);
1917 if (cpi->b_calculate_psnr) {
1918 const double total_psnr =
1919 vpx_sse_to_psnr((double)cpi->total_samples, peak,
1920 (double)cpi->total_sq_error);
1921 const double totalp_psnr =
1922 vpx_sse_to_psnr((double)cpi->totalp_samples, peak,
1923 (double)cpi->totalp_sq_error);
1924 const double total_ssim = 100 * pow(cpi->summed_quality /
1925 cpi->summed_weights, 8.0);
1926 const double totalp_ssim = 100 * pow(cpi->summedp_quality /
1927 cpi->summedp_weights, 8.0);
1929 snprintf(headings, sizeof(headings),
1930 "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
1931 "VPXSSIM\tVPSSIMP\tFASTSIM\tPSNRHVS\t"
1932 "WstPsnr\tWstSsim\tWstFast\tWstHVS");
1933 snprintf(results, sizeof(results),
1934 "%7.2f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
1935 "%7.3f\t%7.3f\t%7.3f\t%7.3f"
1936 "%7.3f\t%7.3f\t%7.3f\t%7.3f",
1937 dr, cpi->psnr.stat[ALL] / cpi->count, total_psnr,
1938 cpi->psnrp.stat[ALL] / cpi->count, totalp_psnr,
1939 total_ssim, totalp_ssim,
1940 cpi->fastssim.stat[ALL] / cpi->count,
1941 cpi->psnrhvs.stat[ALL] / cpi->count,
1942 cpi->psnr.worst, cpi->worst_ssim, cpi->fastssim.worst,
1943 cpi->psnrhvs.worst);
1945 if (cpi->b_calculate_blockiness) {
1946 SNPRINT(headings, "\t Block\tWstBlck");
1947 SNPRINT2(results, "\t%7.3f", cpi->total_blockiness / cpi->count);
1948 SNPRINT2(results, "\t%7.3f", cpi->worst_blockiness);
1951 if (cpi->b_calculate_consistency) {
1952 double consistency =
1953 vpx_sse_to_psnr((double)cpi->totalp_samples, peak,
1954 (double)cpi->total_inconsistency);
1956 SNPRINT(headings, "\tConsist\tWstCons");
1957 SNPRINT2(results, "\t%7.3f", consistency);
1958 SNPRINT2(results, "\t%7.3f", cpi->worst_consistency);
1961 if (cpi->b_calculate_ssimg) {
1962 SNPRINT(headings, "\t SSIMG\tWtSSIMG");
1963 SNPRINT2(results, "\t%7.3f", cpi->ssimg.stat[ALL] / cpi->count);
1964 SNPRINT2(results, "\t%7.3f", cpi->ssimg.worst);
1967 fprintf(f, "%s\t Time\n", headings);
1968 fprintf(f, "%s\t%8.0f\n", results, total_encode_time);
1978 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
1979 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
1980 printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
1981 cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
1982 cpi->time_compress_data / 1000,
1983 (cpi->time_receive_data + cpi->time_compress_data) / 1000);
1988 #if CONFIG_VP9_TEMPORAL_DENOISING
1989 vp9_denoiser_free(&(cpi->denoiser));
1992 for (t = 0; t < cpi->num_workers; ++t) {
1993 VP9Worker *const worker = &cpi->workers[t];
1994 EncWorkerData *const thread_data = &cpi->tile_thr_data[t];
1996 // Deallocate allocated threads.
1997 vp9_get_worker_interface()->end(worker);
1999 // Deallocate allocated thread data.
2000 if (t < cpi->num_workers - 1) {
2001 vpx_free(thread_data->td->counts);
2002 vp9_free_pc_tree(thread_data->td);
2003 vpx_free(thread_data->td);
2006 vpx_free(cpi->tile_thr_data);
2007 vpx_free(cpi->workers);
2009 if (cpi->num_workers > 1)
2010 vp9_loop_filter_dealloc(&cpi->lf_row_sync);
2012 dealloc_compressor_data(cpi);
2014 for (i = 0; i < sizeof(cpi->mbgraph_stats) /
2015 sizeof(cpi->mbgraph_stats[0]); ++i) {
2016 vpx_free(cpi->mbgraph_stats[i].mb_stats);
2019 #if CONFIG_FP_MB_STATS
2020 if (cpi->use_fp_mb_stats) {
2021 vpx_free(cpi->twopass.frame_mb_stats_buf);
2022 cpi->twopass.frame_mb_stats_buf = NULL;
2026 vp9_remove_common(cm);
2027 vp9_free_ref_frame_buffers(cm->buffer_pool);
2028 #if CONFIG_VP9_POSTPROC
2029 vp9_free_postproc_buffers(cm);
2033 #if CONFIG_VP9_TEMPORAL_DENOISING
2034 #ifdef OUTPUT_YUV_DENOISED
2035 fclose(yuv_denoised_file);
2038 #ifdef OUTPUT_YUV_SKINMAP
2039 fclose(yuv_skinmap_file);
2041 #ifdef OUTPUT_YUV_REC
2042 fclose(yuv_rec_file);
2059 /* TODO(yaowu): The block_variance calls the unoptimized versions of variance()
2060 * and highbd_8_variance(). It should not.
2062 static void encoder_variance(const uint8_t *a, int a_stride,
2063 const uint8_t *b, int b_stride,
2064 int w, int h, unsigned int *sse, int *sum) {
2070 for (i = 0; i < h; i++) {
2071 for (j = 0; j < w; j++) {
2072 const int diff = a[j] - b[j];
2074 *sse += diff * diff;
2082 #if CONFIG_VP9_HIGHBITDEPTH
2083 static void encoder_highbd_variance64(const uint8_t *a8, int a_stride,
2084 const uint8_t *b8, int b_stride,
2085 int w, int h, uint64_t *sse,
2089 uint16_t *a = CONVERT_TO_SHORTPTR(a8);
2090 uint16_t *b = CONVERT_TO_SHORTPTR(b8);
2094 for (i = 0; i < h; i++) {
2095 for (j = 0; j < w; j++) {
2096 const int diff = a[j] - b[j];
2098 *sse += diff * diff;
2105 static void encoder_highbd_8_variance(const uint8_t *a8, int a_stride,
2106 const uint8_t *b8, int b_stride,
2108 unsigned int *sse, int *sum) {
2109 uint64_t sse_long = 0;
2110 uint64_t sum_long = 0;
2111 encoder_highbd_variance64(a8, a_stride, b8, b_stride, w, h,
2112 &sse_long, &sum_long);
2113 *sse = (unsigned int)sse_long;
2114 *sum = (int)sum_long;
2116 #endif // CONFIG_VP9_HIGHBITDEPTH
2118 static int64_t get_sse(const uint8_t *a, int a_stride,
2119 const uint8_t *b, int b_stride,
2120 int width, int height) {
2121 const int dw = width % 16;
2122 const int dh = height % 16;
2123 int64_t total_sse = 0;
2124 unsigned int sse = 0;
2129 encoder_variance(&a[width - dw], a_stride, &b[width - dw], b_stride,
2130 dw, height, &sse, &sum);
2135 encoder_variance(&a[(height - dh) * a_stride], a_stride,
2136 &b[(height - dh) * b_stride], b_stride,
2137 width - dw, dh, &sse, &sum);
2141 for (y = 0; y < height / 16; ++y) {
2142 const uint8_t *pa = a;
2143 const uint8_t *pb = b;
2144 for (x = 0; x < width / 16; ++x) {
2145 vpx_mse16x16(pa, a_stride, pb, b_stride, &sse);
2159 #if CONFIG_VP9_HIGHBITDEPTH
2160 static int64_t highbd_get_sse_shift(const uint8_t *a8, int a_stride,
2161 const uint8_t *b8, int b_stride,
2162 int width, int height,
2163 unsigned int input_shift) {
2164 const uint16_t *a = CONVERT_TO_SHORTPTR(a8);
2165 const uint16_t *b = CONVERT_TO_SHORTPTR(b8);
2166 int64_t total_sse = 0;
2168 for (y = 0; y < height; ++y) {
2169 for (x = 0; x < width; ++x) {
2171 diff = (a[x] >> input_shift) - (b[x] >> input_shift);
2172 total_sse += diff * diff;
2180 static int64_t highbd_get_sse(const uint8_t *a, int a_stride,
2181 const uint8_t *b, int b_stride,
2182 int width, int height) {
2183 int64_t total_sse = 0;
2185 const int dw = width % 16;
2186 const int dh = height % 16;
2187 unsigned int sse = 0;
2190 encoder_highbd_8_variance(&a[width - dw], a_stride,
2191 &b[width - dw], b_stride,
2192 dw, height, &sse, &sum);
2196 encoder_highbd_8_variance(&a[(height - dh) * a_stride], a_stride,
2197 &b[(height - dh) * b_stride], b_stride,
2198 width - dw, dh, &sse, &sum);
2201 for (y = 0; y < height / 16; ++y) {
2202 const uint8_t *pa = a;
2203 const uint8_t *pb = b;
2204 for (x = 0; x < width / 16; ++x) {
2205 vpx_highbd_8_mse16x16(pa, a_stride, pb, b_stride, &sse);
2215 #endif // CONFIG_VP9_HIGHBITDEPTH
2218 double psnr[4]; // total/y/u/v
2219 uint64_t sse[4]; // total/y/u/v
2220 uint32_t samples[4]; // total/y/u/v
2223 static void calc_psnr(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b,
2225 static const double peak = 255.0;
2226 const int widths[3] = {
2227 a->y_crop_width, a->uv_crop_width, a->uv_crop_width};
2228 const int heights[3] = {
2229 a->y_crop_height, a->uv_crop_height, a->uv_crop_height};
2230 const uint8_t *a_planes[3] = {a->y_buffer, a->u_buffer, a->v_buffer};
2231 const int a_strides[3] = {a->y_stride, a->uv_stride, a->uv_stride};
2232 const uint8_t *b_planes[3] = {b->y_buffer, b->u_buffer, b->v_buffer};
2233 const int b_strides[3] = {b->y_stride, b->uv_stride, b->uv_stride};
2235 uint64_t total_sse = 0;
2236 uint32_t total_samples = 0;
2238 for (i = 0; i < 3; ++i) {
2239 const int w = widths[i];
2240 const int h = heights[i];
2241 const uint32_t samples = w * h;
2242 const uint64_t sse = get_sse(a_planes[i], a_strides[i],
2243 b_planes[i], b_strides[i],
2245 psnr->sse[1 + i] = sse;
2246 psnr->samples[1 + i] = samples;
2247 psnr->psnr[1 + i] = vpx_sse_to_psnr(samples, peak, (double)sse);
2250 total_samples += samples;
2253 psnr->sse[0] = total_sse;
2254 psnr->samples[0] = total_samples;
2255 psnr->psnr[0] = vpx_sse_to_psnr((double)total_samples, peak,
2259 #if CONFIG_VP9_HIGHBITDEPTH
2260 static void calc_highbd_psnr(const YV12_BUFFER_CONFIG *a,
2261 const YV12_BUFFER_CONFIG *b,
2263 unsigned int bit_depth,
2264 unsigned int in_bit_depth) {
2265 const int widths[3] =
2266 {a->y_crop_width, a->uv_crop_width, a->uv_crop_width };
2267 const int heights[3] =
2268 {a->y_crop_height, a->uv_crop_height, a->uv_crop_height};
2269 const uint8_t *a_planes[3] = {a->y_buffer, a->u_buffer, a->v_buffer };
2270 const int a_strides[3] = {a->y_stride, a->uv_stride, a->uv_stride};
2271 const uint8_t *b_planes[3] = {b->y_buffer, b->u_buffer, b->v_buffer };
2272 const int b_strides[3] = {b->y_stride, b->uv_stride, b->uv_stride};
2274 uint64_t total_sse = 0;
2275 uint32_t total_samples = 0;
2276 const double peak = (double)((1 << in_bit_depth) - 1);
2277 const unsigned int input_shift = bit_depth - in_bit_depth;
2279 for (i = 0; i < 3; ++i) {
2280 const int w = widths[i];
2281 const int h = heights[i];
2282 const uint32_t samples = w * h;
2284 if (a->flags & YV12_FLAG_HIGHBITDEPTH) {
2286 sse = highbd_get_sse_shift(a_planes[i], a_strides[i],
2287 b_planes[i], b_strides[i], w, h,
2290 sse = highbd_get_sse(a_planes[i], a_strides[i],
2291 b_planes[i], b_strides[i], w, h);
2294 sse = get_sse(a_planes[i], a_strides[i],
2295 b_planes[i], b_strides[i],
2298 psnr->sse[1 + i] = sse;
2299 psnr->samples[1 + i] = samples;
2300 psnr->psnr[1 + i] = vpx_sse_to_psnr(samples, peak, (double)sse);
2303 total_samples += samples;
2306 psnr->sse[0] = total_sse;
2307 psnr->samples[0] = total_samples;
2308 psnr->psnr[0] = vpx_sse_to_psnr((double)total_samples, peak,
2311 #endif // CONFIG_VP9_HIGHBITDEPTH
2313 static void generate_psnr_packet(VP9_COMP *cpi) {
2314 struct vpx_codec_cx_pkt pkt;
2317 #if CONFIG_VP9_HIGHBITDEPTH
2318 calc_highbd_psnr(cpi->Source, cpi->common.frame_to_show, &psnr,
2319 cpi->td.mb.e_mbd.bd, cpi->oxcf.input_bit_depth);
2321 calc_psnr(cpi->Source, cpi->common.frame_to_show, &psnr);
2324 for (i = 0; i < 4; ++i) {
2325 pkt.data.psnr.samples[i] = psnr.samples[i];
2326 pkt.data.psnr.sse[i] = psnr.sse[i];
2327 pkt.data.psnr.psnr[i] = psnr.psnr[i];
2329 pkt.kind = VPX_CODEC_PSNR_PKT;
2331 cpi->svc.layer_context[cpi->svc.spatial_layer_id *
2332 cpi->svc.number_temporal_layers].psnr_pkt = pkt.data.psnr;
2334 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2337 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags) {
2338 if (ref_frame_flags > 7)
2341 cpi->ref_frame_flags = ref_frame_flags;
2345 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags) {
2346 cpi->ext_refresh_golden_frame = (ref_frame_flags & VP9_GOLD_FLAG) != 0;
2347 cpi->ext_refresh_alt_ref_frame = (ref_frame_flags & VP9_ALT_FLAG) != 0;
2348 cpi->ext_refresh_last_frame = (ref_frame_flags & VP9_LAST_FLAG) != 0;
2349 cpi->ext_refresh_frame_flags_pending = 1;
2352 static YV12_BUFFER_CONFIG *get_vp9_ref_frame_buffer(VP9_COMP *cpi,
2353 VP9_REFFRAME ref_frame_flag) {
2354 MV_REFERENCE_FRAME ref_frame = NONE;
2355 if (ref_frame_flag == VP9_LAST_FLAG)
2356 ref_frame = LAST_FRAME;
2357 else if (ref_frame_flag == VP9_GOLD_FLAG)
2358 ref_frame = GOLDEN_FRAME;
2359 else if (ref_frame_flag == VP9_ALT_FLAG)
2360 ref_frame = ALTREF_FRAME;
2362 return ref_frame == NONE ? NULL : get_ref_frame_buffer(cpi, ref_frame);
2365 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
2366 YV12_BUFFER_CONFIG *sd) {
2367 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2369 vp8_yv12_copy_frame(cfg, sd);
2376 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
2377 YV12_BUFFER_CONFIG *sd) {
2378 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2380 vp8_yv12_copy_frame(sd, cfg);
2387 int vp9_update_entropy(VP9_COMP * cpi, int update) {
2388 cpi->ext_refresh_frame_context = update;
2389 cpi->ext_refresh_frame_context_pending = 1;
2393 #if defined(OUTPUT_YUV_DENOISED) || defined(OUTPUT_YUV_SKINMAP)
2394 // The denoiser buffer is allocated as a YUV 440 buffer. This function writes it
2395 // as YUV 420. We simply use the top-left pixels of the UV buffers, since we do
2396 // not denoise the UV channels at this time. If ever we implement UV channel
2397 // denoising we will have to modify this.
2398 void vp9_write_yuv_frame_420(YV12_BUFFER_CONFIG *s, FILE *f) {
2399 uint8_t *src = s->y_buffer;
2400 int h = s->y_height;
2403 fwrite(src, s->y_width, 1, f);
2411 fwrite(src, s->uv_width, 1, f);
2412 src += s->uv_stride;
2419 fwrite(src, s->uv_width, 1, f);
2420 src += s->uv_stride;
2425 #ifdef OUTPUT_YUV_REC
2426 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
2427 YV12_BUFFER_CONFIG *s = cm->frame_to_show;
2428 uint8_t *src = s->y_buffer;
2431 #if CONFIG_VP9_HIGHBITDEPTH
2432 if (s->flags & YV12_FLAG_HIGHBITDEPTH) {
2433 uint16_t *src16 = CONVERT_TO_SHORTPTR(s->y_buffer);
2436 fwrite(src16, s->y_width, 2, yuv_rec_file);
2437 src16 += s->y_stride;
2440 src16 = CONVERT_TO_SHORTPTR(s->u_buffer);
2444 fwrite(src16, s->uv_width, 2, yuv_rec_file);
2445 src16 += s->uv_stride;
2448 src16 = CONVERT_TO_SHORTPTR(s->v_buffer);
2452 fwrite(src16, s->uv_width, 2, yuv_rec_file);
2453 src16 += s->uv_stride;
2456 fflush(yuv_rec_file);
2459 #endif // CONFIG_VP9_HIGHBITDEPTH
2462 fwrite(src, s->y_width, 1, yuv_rec_file);
2470 fwrite(src, s->uv_width, 1, yuv_rec_file);
2471 src += s->uv_stride;
2478 fwrite(src, s->uv_width, 1, yuv_rec_file);
2479 src += s->uv_stride;
2482 fflush(yuv_rec_file);
2486 #if CONFIG_VP9_HIGHBITDEPTH
2487 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
2488 YV12_BUFFER_CONFIG *dst,
2491 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
2492 YV12_BUFFER_CONFIG *dst) {
2493 #endif // CONFIG_VP9_HIGHBITDEPTH
2494 // TODO(dkovalev): replace YV12_BUFFER_CONFIG with vpx_image_t
2496 const uint8_t *const srcs[3] = {src->y_buffer, src->u_buffer, src->v_buffer};
2497 const int src_strides[3] = {src->y_stride, src->uv_stride, src->uv_stride};
2498 const int src_widths[3] = {src->y_crop_width, src->uv_crop_width,
2499 src->uv_crop_width };
2500 const int src_heights[3] = {src->y_crop_height, src->uv_crop_height,
2501 src->uv_crop_height};
2502 uint8_t *const dsts[3] = {dst->y_buffer, dst->u_buffer, dst->v_buffer};
2503 const int dst_strides[3] = {dst->y_stride, dst->uv_stride, dst->uv_stride};
2504 const int dst_widths[3] = {dst->y_crop_width, dst->uv_crop_width,
2505 dst->uv_crop_width};
2506 const int dst_heights[3] = {dst->y_crop_height, dst->uv_crop_height,
2507 dst->uv_crop_height};
2509 for (i = 0; i < MAX_MB_PLANE; ++i) {
2510 #if CONFIG_VP9_HIGHBITDEPTH
2511 if (src->flags & YV12_FLAG_HIGHBITDEPTH) {
2512 vp9_highbd_resize_plane(srcs[i], src_heights[i], src_widths[i],
2513 src_strides[i], dsts[i], dst_heights[i],
2514 dst_widths[i], dst_strides[i], bd);
2516 vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
2517 dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
2520 vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
2521 dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
2522 #endif // CONFIG_VP9_HIGHBITDEPTH
2524 vp9_extend_frame_borders(dst);
2527 #if CONFIG_VP9_HIGHBITDEPTH
2528 static void scale_and_extend_frame(const YV12_BUFFER_CONFIG *src,
2529 YV12_BUFFER_CONFIG *dst, int bd) {
2531 static void scale_and_extend_frame(const YV12_BUFFER_CONFIG *src,
2532 YV12_BUFFER_CONFIG *dst) {
2533 #endif // CONFIG_VP9_HIGHBITDEPTH
2534 const int src_w = src->y_crop_width;
2535 const int src_h = src->y_crop_height;
2536 const int dst_w = dst->y_crop_width;
2537 const int dst_h = dst->y_crop_height;
2538 const uint8_t *const srcs[3] = {src->y_buffer, src->u_buffer, src->v_buffer};
2539 const int src_strides[3] = {src->y_stride, src->uv_stride, src->uv_stride};
2540 uint8_t *const dsts[3] = {dst->y_buffer, dst->u_buffer, dst->v_buffer};
2541 const int dst_strides[3] = {dst->y_stride, dst->uv_stride, dst->uv_stride};
2542 const InterpKernel *const kernel = vp9_get_interp_kernel(EIGHTTAP);
2545 for (y = 0; y < dst_h; y += 16) {
2546 for (x = 0; x < dst_w; x += 16) {
2547 for (i = 0; i < MAX_MB_PLANE; ++i) {
2548 const int factor = (i == 0 || i == 3 ? 1 : 2);
2549 const int x_q4 = x * (16 / factor) * src_w / dst_w;
2550 const int y_q4 = y * (16 / factor) * src_h / dst_h;
2551 const int src_stride = src_strides[i];
2552 const int dst_stride = dst_strides[i];
2553 const uint8_t *src_ptr = srcs[i] + (y / factor) * src_h / dst_h *
2554 src_stride + (x / factor) * src_w / dst_w;
2555 uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
2557 #if CONFIG_VP9_HIGHBITDEPTH
2558 if (src->flags & YV12_FLAG_HIGHBITDEPTH) {
2559 vp9_highbd_convolve8(src_ptr, src_stride, dst_ptr, dst_stride,
2560 kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2561 kernel[y_q4 & 0xf], 16 * src_h / dst_h,
2562 16 / factor, 16 / factor, bd);
2564 vp9_convolve8(src_ptr, src_stride, dst_ptr, dst_stride,
2565 kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2566 kernel[y_q4 & 0xf], 16 * src_h / dst_h,
2567 16 / factor, 16 / factor);
2570 vp9_convolve8(src_ptr, src_stride, dst_ptr, dst_stride,
2571 kernel[x_q4 & 0xf], 16 * src_w / dst_w,
2572 kernel[y_q4 & 0xf], 16 * src_h / dst_h,
2573 16 / factor, 16 / factor);
2574 #endif // CONFIG_VP9_HIGHBITDEPTH
2579 vp9_extend_frame_borders(dst);
2582 static int scale_down(VP9_COMP *cpi, int q) {
2583 RATE_CONTROL *const rc = &cpi->rc;
2584 GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2586 assert(frame_is_kf_gf_arf(cpi));
2588 if (rc->frame_size_selector == UNSCALED &&
2589 q >= rc->rf_level_maxq[gf_group->rf_level[gf_group->index]]) {
2590 const int max_size_thresh = (int)(rate_thresh_mult[SCALE_STEP1]
2591 * MAX(rc->this_frame_target, rc->avg_frame_bandwidth));
2592 scale = rc->projected_frame_size > max_size_thresh ? 1 : 0;
2597 // Function to test for conditions that indicate we should loop
2598 // back and recode a frame.
2599 static int recode_loop_test(VP9_COMP *cpi,
2600 int high_limit, int low_limit,
2601 int q, int maxq, int minq) {
2602 const RATE_CONTROL *const rc = &cpi->rc;
2603 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2604 const int frame_is_kfgfarf = frame_is_kf_gf_arf(cpi);
2605 int force_recode = 0;
2607 if ((cpi->sf.recode_loop == ALLOW_RECODE) ||
2608 (frame_is_kfgfarf &&
2609 (cpi->sf.recode_loop == ALLOW_RECODE_KFARFGF))) {
2610 if (frame_is_kfgfarf &&
2611 (oxcf->resize_mode == RESIZE_DYNAMIC) &&
2612 scale_down(cpi, q)) {
2613 // Code this group at a lower resolution.
2614 cpi->resize_pending = 1;
2618 // TODO(agrange) high_limit could be greater than the scale-down threshold.
2619 if ((rc->projected_frame_size > high_limit && q < maxq) ||
2620 (rc->projected_frame_size < low_limit && q > minq)) {
2622 } else if (cpi->oxcf.rc_mode == VPX_CQ) {
2623 // Deal with frame undershoot and whether or not we are
2624 // below the automatically set cq level.
2625 if (q > oxcf->cq_level &&
2626 rc->projected_frame_size < ((rc->this_frame_target * 7) >> 3)) {
2631 return force_recode;
2634 void vp9_update_reference_frames(VP9_COMP *cpi) {
2635 VP9_COMMON * const cm = &cpi->common;
2636 BufferPool *const pool = cm->buffer_pool;
2638 // At this point the new frame has been encoded.
2639 // If any buffer copy / swapping is signaled it should be done here.
2640 if (cm->frame_type == KEY_FRAME) {
2641 ref_cnt_fb(pool->frame_bufs,
2642 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2643 ref_cnt_fb(pool->frame_bufs,
2644 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2645 } else if (vp9_preserve_existing_gf(cpi)) {
2646 // We have decided to preserve the previously existing golden frame as our
2647 // new ARF frame. However, in the short term in function
2648 // vp9_bitstream.c::get_refresh_mask() we left it in the GF slot and, if
2649 // we're updating the GF with the current decoded frame, we save it to the
2650 // ARF slot instead.
2651 // We now have to update the ARF with the current frame and swap gld_fb_idx
2652 // and alt_fb_idx so that, overall, we've stored the old GF in the new ARF
2653 // slot and, if we're updating the GF, the current frame becomes the new GF.
2656 ref_cnt_fb(pool->frame_bufs,
2657 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2659 tmp = cpi->alt_fb_idx;
2660 cpi->alt_fb_idx = cpi->gld_fb_idx;
2661 cpi->gld_fb_idx = tmp;
2663 if (is_two_pass_svc(cpi)) {
2664 cpi->svc.layer_context[0].gold_ref_idx = cpi->gld_fb_idx;
2665 cpi->svc.layer_context[0].alt_ref_idx = cpi->alt_fb_idx;
2667 } else { /* For non key/golden frames */
2668 if (cpi->refresh_alt_ref_frame) {
2669 int arf_idx = cpi->alt_fb_idx;
2670 if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
2671 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2672 arf_idx = gf_group->arf_update_idx[gf_group->index];
2675 ref_cnt_fb(pool->frame_bufs,
2676 &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
2677 memcpy(cpi->interp_filter_selected[ALTREF_FRAME],
2678 cpi->interp_filter_selected[0],
2679 sizeof(cpi->interp_filter_selected[0]));
2682 if (cpi->refresh_golden_frame) {
2683 ref_cnt_fb(pool->frame_bufs,
2684 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2685 if (!cpi->rc.is_src_frame_alt_ref)
2686 memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
2687 cpi->interp_filter_selected[0],
2688 sizeof(cpi->interp_filter_selected[0]));
2690 memcpy(cpi->interp_filter_selected[GOLDEN_FRAME],
2691 cpi->interp_filter_selected[ALTREF_FRAME],
2692 sizeof(cpi->interp_filter_selected[ALTREF_FRAME]));
2696 if (cpi->refresh_last_frame) {
2697 ref_cnt_fb(pool->frame_bufs,
2698 &cm->ref_frame_map[cpi->lst_fb_idx], cm->new_fb_idx);
2699 if (!cpi->rc.is_src_frame_alt_ref)
2700 memcpy(cpi->interp_filter_selected[LAST_FRAME],
2701 cpi->interp_filter_selected[0],
2702 sizeof(cpi->interp_filter_selected[0]));
2704 #if CONFIG_VP9_TEMPORAL_DENOISING
2705 if (cpi->oxcf.noise_sensitivity > 0) {
2706 vp9_denoiser_update_frame_info(&cpi->denoiser,
2708 cpi->common.frame_type,
2709 cpi->refresh_alt_ref_frame,
2710 cpi->refresh_golden_frame,
2711 cpi->refresh_last_frame);
2716 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
2717 MACROBLOCKD *xd = &cpi->td.mb.e_mbd;
2718 struct loopfilter *lf = &cm->lf;
2720 lf->filter_level = 0;
2722 struct vpx_usec_timer timer;
2724 vp9_clear_system_state();
2726 vpx_usec_timer_start(&timer);
2728 vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.lpf_pick);
2730 vpx_usec_timer_mark(&timer);
2731 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
2734 if (lf->filter_level > 0) {
2735 if (cpi->num_workers > 1)
2736 vp9_loop_filter_frame_mt(cm->frame_to_show, cm, xd->plane,
2737 lf->filter_level, 0, 0,
2738 cpi->workers, cpi->num_workers,
2741 vp9_loop_filter_frame(cm->frame_to_show, cm, xd, lf->filter_level, 0, 0);
2744 vp9_extend_frame_inner_borders(cm->frame_to_show);
2747 static INLINE void alloc_frame_mvs(const VP9_COMMON *cm,
2749 RefCntBuffer *const new_fb_ptr = &cm->buffer_pool->frame_bufs[buffer_idx];
2750 if (new_fb_ptr->mvs == NULL ||
2751 new_fb_ptr->mi_rows < cm->mi_rows ||
2752 new_fb_ptr->mi_cols < cm->mi_cols) {
2753 vpx_free(new_fb_ptr->mvs);
2755 (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
2756 sizeof(*new_fb_ptr->mvs));
2757 new_fb_ptr->mi_rows = cm->mi_rows;
2758 new_fb_ptr->mi_cols = cm->mi_cols;
2762 void vp9_scale_references(VP9_COMP *cpi) {
2763 VP9_COMMON *cm = &cpi->common;
2764 MV_REFERENCE_FRAME ref_frame;
2765 const VP9_REFFRAME ref_mask[3] = {VP9_LAST_FLAG, VP9_GOLD_FLAG, VP9_ALT_FLAG};
2767 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2768 // Need to convert from VP9_REFFRAME to index into ref_mask (subtract 1).
2769 if (cpi->ref_frame_flags & ref_mask[ref_frame - 1]) {
2770 BufferPool *const pool = cm->buffer_pool;
2771 const YV12_BUFFER_CONFIG *const ref = get_ref_frame_buffer(cpi,
2775 cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2779 #if CONFIG_VP9_HIGHBITDEPTH
2780 if (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height) {
2781 const int new_fb = get_free_fb(cm);
2782 RefCntBuffer *new_fb_ptr = NULL;
2783 if (cm->new_fb_idx == INVALID_IDX)
2785 new_fb_ptr = &pool->frame_bufs[new_fb];
2786 cm->cur_frame = &pool->frame_bufs[new_fb];
2787 vp9_realloc_frame_buffer(&pool->frame_bufs[new_fb].buf,
2788 cm->width, cm->height,
2789 cm->subsampling_x, cm->subsampling_y,
2790 cm->use_highbitdepth,
2791 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
2793 scale_and_extend_frame(ref, &new_fb_ptr->buf, (int)cm->bit_depth);
2795 if (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height) {
2796 const int new_fb = get_free_fb(cm);
2797 RefCntBuffer *new_fb_ptr = NULL;
2798 if (cm->new_fb_idx == INVALID_IDX)
2800 new_fb_ptr = &pool->frame_bufs[new_fb];
2801 vp9_realloc_frame_buffer(&new_fb_ptr->buf,
2802 cm->width, cm->height,
2803 cm->subsampling_x, cm->subsampling_y,
2804 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
2806 scale_and_extend_frame(ref, &new_fb_ptr->buf);
2807 #endif // CONFIG_VP9_HIGHBITDEPTH
2808 cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
2810 alloc_frame_mvs(cm, new_fb);
2812 const int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
2813 cpi->scaled_ref_idx[ref_frame - 1] = buf_idx;
2814 ++pool->frame_bufs[buf_idx].ref_count;
2817 cpi->scaled_ref_idx[ref_frame - 1] = INVALID_IDX;
2822 static void release_scaled_references(VP9_COMP *cpi) {
2823 VP9_COMMON *cm = &cpi->common;
2825 for (i = 0; i < MAX_REF_FRAMES; ++i) {
2826 const int idx = cpi->scaled_ref_idx[i];
2827 RefCntBuffer *const buf = idx != INVALID_IDX ?
2828 &cm->buffer_pool->frame_bufs[idx] : NULL;
2831 cpi->scaled_ref_idx[i] = INVALID_IDX;
2836 static void full_to_model_count(unsigned int *model_count,
2837 unsigned int *full_count) {
2839 model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
2840 model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
2841 model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
2842 for (n = THREE_TOKEN; n < EOB_TOKEN; ++n)
2843 model_count[TWO_TOKEN] += full_count[n];
2844 model_count[EOB_MODEL_TOKEN] = full_count[EOB_TOKEN];
2847 static void full_to_model_counts(vp9_coeff_count_model *model_count,
2848 vp9_coeff_count *full_count) {
2851 for (i = 0; i < PLANE_TYPES; ++i)
2852 for (j = 0; j < REF_TYPES; ++j)
2853 for (k = 0; k < COEF_BANDS; ++k)
2854 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
2855 full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
2858 #if 0 && CONFIG_INTERNAL_STATS
2859 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
2860 VP9_COMMON *const cm = &cpi->common;
2861 FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
2864 vp9_clear_system_state();
2866 recon_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2868 if (cpi->twopass.total_left_stats.coded_error != 0.0)
2869 fprintf(f, "%10u %dx%d %d %d %10d %10d %10d %10d"
2870 "%10"PRId64" %10"PRId64" %5d %5d %10"PRId64" "
2871 "%10"PRId64" %10"PRId64" %10d "
2872 "%7.2lf %7.2lf %7.2lf %7.2lf %7.2lf"
2873 "%6d %6d %5d %5d %5d "
2874 "%10"PRId64" %10.3lf"
2875 "%10lf %8u %10"PRId64" %10d %10d %10d\n",
2876 cpi->common.current_video_frame,
2877 cm->width, cm->height,
2878 cpi->rc.source_alt_ref_pending,
2879 cpi->rc.source_alt_ref_active,
2880 cpi->rc.this_frame_target,
2881 cpi->rc.projected_frame_size,
2882 cpi->rc.projected_frame_size / cpi->common.MBs,
2883 (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
2884 cpi->rc.vbr_bits_off_target,
2885 cpi->rc.vbr_bits_off_target_fast,
2886 cpi->twopass.extend_minq,
2887 cpi->twopass.extend_minq_fast,
2888 cpi->rc.total_target_vs_actual,
2889 (cpi->rc.starting_buffer_level - cpi->rc.bits_off_target),
2890 cpi->rc.total_actual_bits, cm->base_qindex,
2891 vp9_convert_qindex_to_q(cm->base_qindex, cm->bit_depth),
2892 (double)vp9_dc_quant(cm->base_qindex, 0, cm->bit_depth) / 4.0,
2893 vp9_convert_qindex_to_q(cpi->twopass.active_worst_quality,
2896 vp9_convert_qindex_to_q(cpi->oxcf.cq_level, cm->bit_depth),
2897 cpi->refresh_last_frame, cpi->refresh_golden_frame,
2898 cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
2899 cpi->twopass.bits_left,
2900 cpi->twopass.total_left_stats.coded_error,
2901 cpi->twopass.bits_left /
2902 (1 + cpi->twopass.total_left_stats.coded_error),
2903 cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
2904 cpi->twopass.kf_zeromotion_pct,
2905 cpi->twopass.fr_content_type);
2910 FILE *const fmodes = fopen("Modes.stt", "a");
2913 fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
2914 cm->frame_type, cpi->refresh_golden_frame,
2915 cpi->refresh_alt_ref_frame);
2917 for (i = 0; i < MAX_MODES; ++i)
2918 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
2920 fprintf(fmodes, "\n");
2927 static void set_mv_search_params(VP9_COMP *cpi) {
2928 const VP9_COMMON *const cm = &cpi->common;
2929 const unsigned int max_mv_def = MIN(cm->width, cm->height);
2931 // Default based on max resolution.
2932 cpi->mv_step_param = vp9_init_search_range(max_mv_def);
2934 if (cpi->sf.mv.auto_mv_step_size) {
2935 if (frame_is_intra_only(cm)) {
2936 // Initialize max_mv_magnitude for use in the first INTER frame
2937 // after a key/intra-only frame.
2938 cpi->max_mv_magnitude = max_mv_def;
2940 if (cm->show_frame) {
2941 // Allow mv_steps to correspond to twice the max mv magnitude found
2942 // in the previous frame, capped by the default max_mv_magnitude based
2944 cpi->mv_step_param =
2945 vp9_init_search_range(MIN(max_mv_def, 2 * cpi->max_mv_magnitude));
2947 cpi->max_mv_magnitude = 0;
2952 static void set_size_independent_vars(VP9_COMP *cpi) {
2953 vp9_set_speed_features_framesize_independent(cpi);
2954 vp9_set_rd_speed_thresholds(cpi);
2955 vp9_set_rd_speed_thresholds_sub8x8(cpi);
2956 cpi->common.interp_filter = cpi->sf.default_interp_filter;
2959 static void set_size_dependent_vars(VP9_COMP *cpi, int *q,
2960 int *bottom_index, int *top_index) {
2961 VP9_COMMON *const cm = &cpi->common;
2962 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2964 // Setup variables that depend on the dimensions of the frame.
2965 vp9_set_speed_features_framesize_dependent(cpi);
2967 // Decide q and q bounds.
2968 *q = vp9_rc_pick_q_and_bounds(cpi, bottom_index, top_index);
2970 if (!frame_is_intra_only(cm)) {
2971 vp9_set_high_precision_mv(cpi, (*q) < HIGH_PRECISION_MV_QTHRESH);
2974 // Configure experimental use of segmentation for enhanced coding of
2975 // static regions if indicated.
2976 // Only allowed in the second pass of a two pass encode, as it requires
2977 // lagged coding, and if the relevant speed feature flag is set.
2978 if (oxcf->pass == 2 && cpi->sf.static_segmentation)
2979 configure_static_seg_features(cpi);
2981 #if CONFIG_VP9_POSTPROC
2982 if (oxcf->noise_sensitivity > 0) {
2984 switch (oxcf->noise_sensitivity) {
3002 vp9_denoise(cpi->Source, cpi->Source, l);
3004 #endif // CONFIG_VP9_POSTPROC
3007 static void init_motion_estimation(VP9_COMP *cpi) {
3008 int y_stride = cpi->scaled_source.y_stride;
3010 if (cpi->sf.mv.search_method == NSTEP) {
3011 vp9_init3smotion_compensation(&cpi->ss_cfg, y_stride);
3012 } else if (cpi->sf.mv.search_method == DIAMOND) {
3013 vp9_init_dsmotion_compensation(&cpi->ss_cfg, y_stride);
3017 static void set_frame_size(VP9_COMP *cpi) {
3019 VP9_COMMON *const cm = &cpi->common;
3020 VP9EncoderConfig *const oxcf = &cpi->oxcf;
3021 MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
3023 if (oxcf->pass == 2 &&
3024 oxcf->rc_mode == VPX_VBR &&
3025 ((oxcf->resize_mode == RESIZE_FIXED && cm->current_video_frame == 0) ||
3026 (oxcf->resize_mode == RESIZE_DYNAMIC && cpi->resize_pending))) {
3027 calculate_coded_size(
3028 cpi, &oxcf->scaled_frame_width, &oxcf->scaled_frame_height);
3030 // There has been a change in frame size.
3031 vp9_set_size_literal(cpi, oxcf->scaled_frame_width,
3032 oxcf->scaled_frame_height);
3035 if ((oxcf->pass == 2) &&
3037 (is_two_pass_svc(cpi) &&
3038 cpi->svc.encode_empty_frame_state != ENCODING))) {
3039 vp9_set_target_rate(cpi);
3042 alloc_frame_mvs(cm, cm->new_fb_idx);
3044 // Reset the frame pointers to the current frame size.
3045 vp9_realloc_frame_buffer(get_frame_new_buffer(cm),
3046 cm->width, cm->height,
3047 cm->subsampling_x, cm->subsampling_y,
3048 #if CONFIG_VP9_HIGHBITDEPTH
3049 cm->use_highbitdepth,
3051 VP9_ENC_BORDER_IN_PIXELS, cm->byte_alignment,
3054 alloc_util_frame_buffers(cpi);
3055 init_motion_estimation(cpi);
3057 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3058 RefBuffer *const ref_buf = &cm->frame_refs[ref_frame - 1];
3059 const int buf_idx = get_ref_frame_buf_idx(cpi, ref_frame);
3061 ref_buf->idx = buf_idx;
3063 if (buf_idx != INVALID_IDX) {
3064 YV12_BUFFER_CONFIG *const buf = &cm->buffer_pool->frame_bufs[buf_idx].buf;
3066 #if CONFIG_VP9_HIGHBITDEPTH
3067 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
3068 buf->y_crop_width, buf->y_crop_height,
3069 cm->width, cm->height,
3070 (buf->flags & YV12_FLAG_HIGHBITDEPTH) ?
3073 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
3074 buf->y_crop_width, buf->y_crop_height,
3075 cm->width, cm->height);
3076 #endif // CONFIG_VP9_HIGHBITDEPTH
3077 if (vp9_is_scaled(&ref_buf->sf))
3078 vp9_extend_frame_borders(buf);
3080 ref_buf->buf = NULL;
3084 set_ref_ptrs(cm, xd, LAST_FRAME, LAST_FRAME);
3087 static void encode_without_recode_loop(VP9_COMP *cpi) {
3088 VP9_COMMON *const cm = &cpi->common;
3089 int q = 0, bottom_index = 0, top_index = 0; // Dummy variables.
3091 vp9_clear_system_state();
3093 set_frame_size(cpi);
3095 cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
3096 &cpi->scaled_source);
3098 if (cpi->unscaled_last_source != NULL)
3099 cpi->Last_Source = vp9_scale_if_required(cm, cpi->unscaled_last_source,
3100 &cpi->scaled_last_source);
3102 if (frame_is_intra_only(cm) == 0) {
3103 vp9_scale_references(cpi);
3106 set_size_independent_vars(cpi);
3107 set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
3109 vp9_set_quantizer(cm, q);
3110 vp9_set_variance_partition_thresholds(cpi, q);
3114 suppress_active_map(cpi);
3115 // Variance adaptive and in frame q adjustment experiments are mutually
3117 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3118 vp9_vaq_frame_setup(cpi);
3119 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
3120 vp9_setup_in_frame_q_adj(cpi);
3121 } else if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
3122 vp9_cyclic_refresh_setup(cpi);
3124 apply_active_map(cpi);
3126 // transform / motion compensation build reconstruction frame
3127 vp9_encode_frame(cpi);
3129 // Update some stats from cyclic refresh, and check if we should not update
3130 // golden reference, for non-SVC 1 pass CBR.
3131 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
3132 cm->frame_type != KEY_FRAME &&
3134 (cpi->oxcf.pass == 0 && cpi->oxcf.rc_mode == VPX_CBR))
3135 vp9_cyclic_refresh_check_golden_update(cpi);
3137 // Update the skip mb flag probabilities based on the distribution
3138 // seen in the last encoder iteration.
3139 // update_base_skip_probs(cpi);
3140 vp9_clear_system_state();
3143 static void encode_with_recode_loop(VP9_COMP *cpi,
3146 VP9_COMMON *const cm = &cpi->common;
3147 RATE_CONTROL *const rc = &cpi->rc;
3148 int bottom_index, top_index;
3150 int loop_at_this_size = 0;
3152 int overshoot_seen = 0;
3153 int undershoot_seen = 0;
3154 int frame_over_shoot_limit;
3155 int frame_under_shoot_limit;
3156 int q = 0, q_low = 0, q_high = 0;
3158 set_size_independent_vars(cpi);
3161 vp9_clear_system_state();
3163 set_frame_size(cpi);
3165 if (loop_count == 0 || cpi->resize_pending != 0) {
3166 set_size_dependent_vars(cpi, &q, &bottom_index, &top_index);
3168 // TODO(agrange) Scale cpi->max_mv_magnitude if frame-size has changed.
3169 set_mv_search_params(cpi);
3171 // Reset the loop state for new frame size.
3173 undershoot_seen = 0;
3175 // Reconfiguration for change in frame size has concluded.
3176 cpi->resize_pending = 0;
3178 q_low = bottom_index;
3181 loop_at_this_size = 0;
3184 // Decide frame size bounds first time through.
3185 if (loop_count == 0) {
3186 vp9_rc_compute_frame_size_bounds(cpi, rc->this_frame_target,
3187 &frame_under_shoot_limit,
3188 &frame_over_shoot_limit);
3191 cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
3192 &cpi->scaled_source);
3194 if (cpi->unscaled_last_source != NULL)
3195 cpi->Last_Source = vp9_scale_if_required(cm, cpi->unscaled_last_source,
3196 &cpi->scaled_last_source);
3198 if (frame_is_intra_only(cm) == 0) {
3199 if (loop_count > 0) {
3200 release_scaled_references(cpi);
3202 vp9_scale_references(cpi);
3205 vp9_set_quantizer(cm, q);
3207 if (loop_count == 0)
3210 // Variance adaptive and in frame q adjustment experiments are mutually
3212 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3213 vp9_vaq_frame_setup(cpi);
3214 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
3215 vp9_setup_in_frame_q_adj(cpi);
3218 // transform / motion compensation build reconstruction frame
3219 vp9_encode_frame(cpi);
3221 // Update the skip mb flag probabilities based on the distribution
3222 // seen in the last encoder iteration.
3223 // update_base_skip_probs(cpi);
3225 vp9_clear_system_state();
3227 // Dummy pack of the bitstream using up to date stats to get an
3228 // accurate estimate of output frame size to determine if we need
3230 if (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF) {
3231 save_coding_context(cpi);
3232 if (!cpi->sf.use_nonrd_pick_mode)
3233 vp9_pack_bitstream(cpi, dest, size);
3235 rc->projected_frame_size = (int)(*size) << 3;
3236 restore_coding_context(cpi);
3238 if (frame_over_shoot_limit == 0)
3239 frame_over_shoot_limit = 1;
3242 if (cpi->oxcf.rc_mode == VPX_Q) {
3245 if ((cm->frame_type == KEY_FRAME) &&
3246 rc->this_key_frame_forced &&
3247 (rc->projected_frame_size < rc->max_frame_bandwidth)) {
3251 int64_t high_err_target = cpi->ambient_err;
3252 int64_t low_err_target = cpi->ambient_err >> 1;
3254 #if CONFIG_VP9_HIGHBITDEPTH
3255 if (cm->use_highbitdepth) {
3256 kf_err = vp9_highbd_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3258 kf_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3261 kf_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3262 #endif // CONFIG_VP9_HIGHBITDEPTH
3264 // Prevent possible divide by zero error below for perfect KF
3267 // The key frame is not good enough or we can afford
3268 // to make it better without undue risk of popping.
3269 if ((kf_err > high_err_target &&
3270 rc->projected_frame_size <= frame_over_shoot_limit) ||
3271 (kf_err > low_err_target &&
3272 rc->projected_frame_size <= frame_under_shoot_limit)) {
3274 q_high = q > q_low ? q - 1 : q_low;
3277 q = (int)((q * high_err_target) / kf_err);
3278 q = MIN(q, (q_high + q_low) >> 1);
3279 } else if (kf_err < low_err_target &&
3280 rc->projected_frame_size >= frame_under_shoot_limit) {
3281 // The key frame is much better than the previous frame
3283 q_low = q < q_high ? q + 1 : q_high;
3286 q = (int)((q * low_err_target) / kf_err);
3287 q = MIN(q, (q_high + q_low + 1) >> 1);
3290 // Clamp Q to upper and lower limits:
3291 q = clamp(q, q_low, q_high);
3294 } else if (recode_loop_test(
3295 cpi, frame_over_shoot_limit, frame_under_shoot_limit,
3296 q, MAX(q_high, top_index), bottom_index)) {
3297 // Is the projected frame size out of range and are we allowed
3298 // to attempt to recode.
3302 if (cpi->resize_pending == 1) {
3303 // Change in frame size so go back around the recode loop.
3304 cpi->rc.frame_size_selector =
3305 SCALE_STEP1 - cpi->rc.frame_size_selector;
3306 cpi->rc.next_frame_size_selector = cpi->rc.frame_size_selector;
3308 #if CONFIG_INTERNAL_STATS
3309 ++cpi->tot_recode_hits;
3316 // Frame size out of permitted range:
3317 // Update correction factor & compute new Q to try...
3319 // Frame is too large
3320 if (rc->projected_frame_size > rc->this_frame_target) {
3321 // Special case if the projected size is > the max allowed.
3322 if (rc->projected_frame_size >= rc->max_frame_bandwidth)
3323 q_high = rc->worst_quality;
3325 // Raise Qlow as to at least the current value
3326 q_low = q < q_high ? q + 1 : q_high;
3328 if (undershoot_seen || loop_at_this_size > 1) {
3329 // Update rate_correction_factor unless
3330 vp9_rc_update_rate_correction_factors(cpi);
3332 q = (q_high + q_low + 1) / 2;
3334 // Update rate_correction_factor unless
3335 vp9_rc_update_rate_correction_factors(cpi);
3337 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
3338 bottom_index, MAX(q_high, top_index));
3340 while (q < q_low && retries < 10) {
3341 vp9_rc_update_rate_correction_factors(cpi);
3342 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
3343 bottom_index, MAX(q_high, top_index));
3350 // Frame is too small
3351 q_high = q > q_low ? q - 1 : q_low;
3353 if (overshoot_seen || loop_at_this_size > 1) {
3354 vp9_rc_update_rate_correction_factors(cpi);
3355 q = (q_high + q_low) / 2;
3357 vp9_rc_update_rate_correction_factors(cpi);
3358 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
3359 bottom_index, top_index);
3360 // Special case reset for qlow for constrained quality.
3361 // This should only trigger where there is very substantial
3362 // undershoot on a frame and the auto cq level is above
3363 // the user passsed in value.
3364 if (cpi->oxcf.rc_mode == VPX_CQ &&
3369 while (q > q_high && retries < 10) {
3370 vp9_rc_update_rate_correction_factors(cpi);
3371 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
3372 bottom_index, top_index);
3377 undershoot_seen = 1;
3380 // Clamp Q to upper and lower limits:
3381 q = clamp(q, q_low, q_high);
3383 loop = (q != last_q);
3389 // Special case for overlay frame.
3390 if (rc->is_src_frame_alt_ref &&
3391 rc->projected_frame_size < rc->max_frame_bandwidth)
3396 ++loop_at_this_size;
3398 #if CONFIG_INTERNAL_STATS
3399 ++cpi->tot_recode_hits;
3405 static int get_ref_frame_flags(const VP9_COMP *cpi) {
3406 const int *const map = cpi->common.ref_frame_map;
3407 const int gold_is_last = map[cpi->gld_fb_idx] == map[cpi->lst_fb_idx];
3408 const int alt_is_last = map[cpi->alt_fb_idx] == map[cpi->lst_fb_idx];
3409 const int gold_is_alt = map[cpi->gld_fb_idx] == map[cpi->alt_fb_idx];
3410 int flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
3413 flags &= ~VP9_GOLD_FLAG;
3415 if (cpi->rc.frames_till_gf_update_due == INT_MAX &&
3416 (cpi->svc.number_temporal_layers == 1 &&
3417 cpi->svc.number_spatial_layers == 1))
3418 flags &= ~VP9_GOLD_FLAG;
3421 flags &= ~VP9_ALT_FLAG;
3424 flags &= ~VP9_ALT_FLAG;
3429 static void set_ext_overrides(VP9_COMP *cpi) {
3430 // Overrides the defaults with the externally supplied values with
3431 // vp9_update_reference() and vp9_update_entropy() calls
3432 // Note: The overrides are valid only for the next frame passed
3433 // to encode_frame_to_data_rate() function
3434 if (cpi->ext_refresh_frame_context_pending) {
3435 cpi->common.refresh_frame_context = cpi->ext_refresh_frame_context;
3436 cpi->ext_refresh_frame_context_pending = 0;
3438 if (cpi->ext_refresh_frame_flags_pending) {
3439 cpi->refresh_last_frame = cpi->ext_refresh_last_frame;
3440 cpi->refresh_golden_frame = cpi->ext_refresh_golden_frame;
3441 cpi->refresh_alt_ref_frame = cpi->ext_refresh_alt_ref_frame;
3442 cpi->ext_refresh_frame_flags_pending = 0;
3446 YV12_BUFFER_CONFIG *vp9_scale_if_required(VP9_COMMON *cm,
3447 YV12_BUFFER_CONFIG *unscaled,
3448 YV12_BUFFER_CONFIG *scaled) {
3449 if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
3450 cm->mi_rows * MI_SIZE != unscaled->y_height) {
3451 #if CONFIG_VP9_HIGHBITDEPTH
3452 scale_and_extend_frame_nonnormative(unscaled, scaled, (int)cm->bit_depth);
3454 scale_and_extend_frame_nonnormative(unscaled, scaled);
3455 #endif // CONFIG_VP9_HIGHBITDEPTH
3462 static void set_arf_sign_bias(VP9_COMP *cpi) {
3463 VP9_COMMON *const cm = &cpi->common;
3466 if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
3467 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
3468 arf_sign_bias = cpi->rc.source_alt_ref_active &&
3469 (!cpi->refresh_alt_ref_frame ||
3470 (gf_group->rf_level[gf_group->index] == GF_ARF_LOW));
3473 (cpi->rc.source_alt_ref_active && !cpi->refresh_alt_ref_frame);
3475 cm->ref_frame_sign_bias[ALTREF_FRAME] = arf_sign_bias;
3478 static int setup_interp_filter_search_mask(VP9_COMP *cpi) {
3479 INTERP_FILTER ifilter;
3480 int ref_total[MAX_REF_FRAMES] = {0};
3481 MV_REFERENCE_FRAME ref;
3483 if (cpi->common.last_frame_type == KEY_FRAME ||
3484 cpi->refresh_alt_ref_frame)
3486 for (ref = LAST_FRAME; ref <= ALTREF_FRAME; ++ref)
3487 for (ifilter = EIGHTTAP; ifilter <= EIGHTTAP_SHARP; ++ifilter)
3488 ref_total[ref] += cpi->interp_filter_selected[ref][ifilter];
3490 for (ifilter = EIGHTTAP; ifilter <= EIGHTTAP_SHARP; ++ifilter) {
3491 if ((ref_total[LAST_FRAME] &&
3492 cpi->interp_filter_selected[LAST_FRAME][ifilter] == 0) &&
3493 (ref_total[GOLDEN_FRAME] == 0 ||
3494 cpi->interp_filter_selected[GOLDEN_FRAME][ifilter] * 50
3495 < ref_total[GOLDEN_FRAME]) &&
3496 (ref_total[ALTREF_FRAME] == 0 ||
3497 cpi->interp_filter_selected[ALTREF_FRAME][ifilter] * 50
3498 < ref_total[ALTREF_FRAME]))
3499 mask |= 1 << ifilter;
3504 static void encode_frame_to_data_rate(VP9_COMP *cpi,
3507 unsigned int *frame_flags) {
3508 VP9_COMMON *const cm = &cpi->common;
3509 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3510 struct segmentation *const seg = &cm->seg;
3513 set_ext_overrides(cpi);
3514 vp9_clear_system_state();
3516 // Set the arf sign bias for this frame.
3517 set_arf_sign_bias(cpi);
3519 // Set default state for segment based loop filter update flags.
3520 cm->lf.mode_ref_delta_update = 0;
3522 if (cpi->oxcf.pass == 2 &&
3523 cpi->sf.adaptive_interp_filter_search)
3524 cpi->sf.interp_filter_search_mask =
3525 setup_interp_filter_search_mask(cpi);
3527 // Set various flags etc to special state if it is a key frame.
3528 if (frame_is_intra_only(cm)) {
3529 // Reset the loop filter deltas and segmentation map.
3530 vp9_reset_segment_features(&cm->seg);
3532 // If segmentation is enabled force a map update for key frames.
3534 seg->update_map = 1;
3535 seg->update_data = 1;
3538 // The alternate reference frame cannot be active for a key frame.
3539 cpi->rc.source_alt_ref_active = 0;
3541 cm->error_resilient_mode = oxcf->error_resilient_mode;
3542 cm->frame_parallel_decoding_mode = oxcf->frame_parallel_decoding_mode;
3544 // By default, encoder assumes decoder can use prev_mi.
3545 if (cm->error_resilient_mode) {
3546 cm->frame_parallel_decoding_mode = 1;
3547 cm->reset_frame_context = 0;
3548 cm->refresh_frame_context = 0;
3549 } else if (cm->intra_only) {
3550 // Only reset the current context.
3551 cm->reset_frame_context = 2;
3554 if (is_two_pass_svc(cpi) && cm->error_resilient_mode == 0) {
3555 // Use context 0 for intra only empty frame, but the last frame context
3556 // for other empty frames.
3557 if (cpi->svc.encode_empty_frame_state == ENCODING) {
3558 if (cpi->svc.encode_intra_empty_frame != 0)
3559 cm->frame_context_idx = 0;
3561 cm->frame_context_idx = FRAME_CONTEXTS - 1;
3563 cm->frame_context_idx =
3564 cpi->svc.spatial_layer_id * cpi->svc.number_temporal_layers +
3565 cpi->svc.temporal_layer_id;
3568 cm->frame_parallel_decoding_mode = oxcf->frame_parallel_decoding_mode;
3570 // The probs will be updated based on the frame type of its previous
3571 // frame if frame_parallel_decoding_mode is 0. The type may vary for
3572 // the frame after a key frame in base layer since we may drop enhancement
3573 // layers. So set frame_parallel_decoding_mode to 1 in this case.
3574 if (cm->frame_parallel_decoding_mode == 0) {
3575 if (cpi->svc.number_temporal_layers == 1) {
3576 if (cpi->svc.spatial_layer_id == 0 &&
3577 cpi->svc.layer_context[0].last_frame_type == KEY_FRAME)
3578 cm->frame_parallel_decoding_mode = 1;
3579 } else if (cpi->svc.spatial_layer_id == 0) {
3580 // Find the 2nd frame in temporal base layer and 1st frame in temporal
3581 // enhancement layers from the key frame.
3583 for (i = 0; i < cpi->svc.number_temporal_layers; ++i) {
3584 if (cpi->svc.layer_context[0].frames_from_key_frame == 1 << i) {
3585 cm->frame_parallel_decoding_mode = 1;
3593 // For 1 pass CBR, check if we are dropping this frame.
3594 // Never drop on key frame.
3595 if (oxcf->pass == 0 &&
3596 oxcf->rc_mode == VPX_CBR &&
3597 cm->frame_type != KEY_FRAME) {
3598 if (vp9_rc_drop_frame(cpi)) {
3599 vp9_rc_postencode_update_drop_frame(cpi);
3600 ++cm->current_video_frame;
3605 vp9_clear_system_state();
3607 #if CONFIG_INTERNAL_STATS
3608 memset(cpi->mode_chosen_counts, 0,
3609 MAX_MODES * sizeof(*cpi->mode_chosen_counts));
3612 if (cpi->sf.recode_loop == DISALLOW_RECODE) {
3613 encode_without_recode_loop(cpi);
3615 encode_with_recode_loop(cpi, size, dest);
3618 #if CONFIG_VP9_TEMPORAL_DENOISING
3619 #ifdef OUTPUT_YUV_DENOISED
3620 if (oxcf->noise_sensitivity > 0) {
3621 vp9_write_yuv_frame_420(&cpi->denoiser.running_avg_y[INTRA_FRAME],
3626 #ifdef OUTPUT_YUV_SKINMAP
3627 if (cpi->common.current_video_frame > 1) {
3628 vp9_compute_skin_map(cpi, yuv_skinmap_file);
3632 // Special case code to reduce pulsing when key frames are forced at a
3633 // fixed interval. Note the reconstruction error if it is the frame before
3634 // the force key frame
3635 if (cpi->rc.next_key_frame_forced && cpi->rc.frames_to_key == 1) {
3636 #if CONFIG_VP9_HIGHBITDEPTH
3637 if (cm->use_highbitdepth) {
3638 cpi->ambient_err = vp9_highbd_get_y_sse(cpi->Source,
3639 get_frame_new_buffer(cm));
3641 cpi->ambient_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3644 cpi->ambient_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
3645 #endif // CONFIG_VP9_HIGHBITDEPTH
3648 // If the encoder forced a KEY_FRAME decision
3649 if (cm->frame_type == KEY_FRAME)
3650 cpi->refresh_last_frame = 1;
3652 cm->frame_to_show = get_frame_new_buffer(cm);
3654 // Pick the loop filter level for the frame.
3655 loopfilter_frame(cpi, cm);
3657 // build the bitstream
3658 vp9_pack_bitstream(cpi, dest, size);
3660 if (cm->seg.update_map)
3661 update_reference_segmentation_map(cpi);
3663 if (frame_is_intra_only(cm) == 0) {
3664 release_scaled_references(cpi);
3666 vp9_update_reference_frames(cpi);
3668 for (t = TX_4X4; t <= TX_32X32; t++)
3669 full_to_model_counts(cpi->td.counts->coef[t],
3670 cpi->td.rd_counts.coef_counts[t]);
3672 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode)
3673 vp9_adapt_coef_probs(cm);
3675 if (!frame_is_intra_only(cm)) {
3676 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
3677 vp9_adapt_mode_probs(cm);
3678 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
3682 if (cpi->refresh_golden_frame == 1)
3683 cpi->frame_flags |= FRAMEFLAGS_GOLDEN;
3685 cpi->frame_flags &= ~FRAMEFLAGS_GOLDEN;
3687 if (cpi->refresh_alt_ref_frame == 1)
3688 cpi->frame_flags |= FRAMEFLAGS_ALTREF;
3690 cpi->frame_flags &= ~FRAMEFLAGS_ALTREF;
3692 cpi->ref_frame_flags = get_ref_frame_flags(cpi);
3694 cm->last_frame_type = cm->frame_type;
3696 if (!(is_two_pass_svc(cpi) && cpi->svc.encode_empty_frame_state == ENCODING))
3697 vp9_rc_postencode_update(cpi, *size);
3700 output_frame_level_debug_stats(cpi);
3703 if (cm->frame_type == KEY_FRAME) {
3704 // Tell the caller that the frame was coded as a key frame
3705 *frame_flags = cpi->frame_flags | FRAMEFLAGS_KEY;
3707 *frame_flags = cpi->frame_flags & ~FRAMEFLAGS_KEY;
3710 // Clear the one shot update flags for segmentation map and mode/ref loop
3712 cm->seg.update_map = 0;
3713 cm->seg.update_data = 0;
3714 cm->lf.mode_ref_delta_update = 0;
3716 // keep track of the last coded dimensions
3717 cm->last_width = cm->width;
3718 cm->last_height = cm->height;
3720 // reset to normal state now that we are done.
3721 if (!cm->show_existing_frame)
3722 cm->last_show_frame = cm->show_frame;
3724 if (cm->show_frame) {
3725 vp9_swap_mi_and_prev_mi(cm);
3726 // Don't increment frame counters if this was an altref buffer
3727 // update not a real frame
3728 ++cm->current_video_frame;
3730 vp9_inc_frame_in_layer(cpi);
3732 cm->prev_frame = cm->cur_frame;
3735 cpi->svc.layer_context[cpi->svc.spatial_layer_id *
3736 cpi->svc.number_temporal_layers +
3737 cpi->svc.temporal_layer_id].last_frame_type =
3741 static void SvcEncode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
3742 unsigned int *frame_flags) {
3743 vp9_rc_get_svc_params(cpi);
3744 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3747 static void Pass0Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
3748 unsigned int *frame_flags) {
3749 if (cpi->oxcf.rc_mode == VPX_CBR) {
3750 vp9_rc_get_one_pass_cbr_params(cpi);
3752 vp9_rc_get_one_pass_vbr_params(cpi);
3754 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3757 static void Pass2Encode(VP9_COMP *cpi, size_t *size,
3758 uint8_t *dest, unsigned int *frame_flags) {
3759 cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
3760 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3762 if (!(is_two_pass_svc(cpi) && cpi->svc.encode_empty_frame_state == ENCODING))
3763 vp9_twopass_postencode_update(cpi);
3766 static void init_ref_frame_bufs(VP9_COMMON *cm) {
3768 BufferPool *const pool = cm->buffer_pool;
3769 cm->new_fb_idx = INVALID_IDX;
3770 for (i = 0; i < REF_FRAMES; ++i) {
3771 cm->ref_frame_map[i] = INVALID_IDX;
3772 pool->frame_bufs[i].ref_count = 0;
3776 static void check_initial_width(VP9_COMP *cpi,
3777 #if CONFIG_VP9_HIGHBITDEPTH
3778 int use_highbitdepth,
3780 int subsampling_x, int subsampling_y) {
3781 VP9_COMMON *const cm = &cpi->common;
3783 if (!cpi->initial_width ||
3784 #if CONFIG_VP9_HIGHBITDEPTH
3785 cm->use_highbitdepth != use_highbitdepth ||
3787 cm->subsampling_x != subsampling_x ||
3788 cm->subsampling_y != subsampling_y) {
3789 cm->subsampling_x = subsampling_x;
3790 cm->subsampling_y = subsampling_y;
3791 #if CONFIG_VP9_HIGHBITDEPTH
3792 cm->use_highbitdepth = use_highbitdepth;
3795 alloc_raw_frame_buffers(cpi);
3796 init_ref_frame_bufs(cm);
3797 alloc_util_frame_buffers(cpi);
3799 init_motion_estimation(cpi); // TODO(agrange) This can be removed.
3801 cpi->initial_width = cm->width;
3802 cpi->initial_height = cm->height;
3803 cpi->initial_mbs = cm->MBs;
3807 #if CONFIG_VP9_TEMPORAL_DENOISING
3808 static void setup_denoiser_buffer(VP9_COMP *cpi) {
3809 VP9_COMMON *const cm = &cpi->common;
3810 if (cpi->oxcf.noise_sensitivity > 0 &&
3811 !cpi->denoiser.frame_buffer_initialized) {
3812 vp9_denoiser_alloc(&(cpi->denoiser), cm->width, cm->height,
3813 cm->subsampling_x, cm->subsampling_y,
3814 #if CONFIG_VP9_HIGHBITDEPTH
3815 cm->use_highbitdepth,
3817 VP9_ENC_BORDER_IN_PIXELS);
3822 int vp9_receive_raw_frame(VP9_COMP *cpi, unsigned int frame_flags,
3823 YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
3825 VP9_COMMON *cm = &cpi->common;
3826 struct vpx_usec_timer timer;
3828 const int subsampling_x = sd->subsampling_x;
3829 const int subsampling_y = sd->subsampling_y;
3830 #if CONFIG_VP9_HIGHBITDEPTH
3831 const int use_highbitdepth = sd->flags & YV12_FLAG_HIGHBITDEPTH;
3832 check_initial_width(cpi, use_highbitdepth, subsampling_x, subsampling_y);
3834 check_initial_width(cpi, subsampling_x, subsampling_y);
3835 #endif // CONFIG_VP9_HIGHBITDEPTH
3837 #if CONFIG_VP9_TEMPORAL_DENOISING
3838 setup_denoiser_buffer(cpi);
3840 vpx_usec_timer_start(&timer);
3842 if (vp9_lookahead_push(cpi->lookahead, sd, time_stamp, end_time,
3843 #if CONFIG_VP9_HIGHBITDEPTH
3845 #endif // CONFIG_VP9_HIGHBITDEPTH
3848 vpx_usec_timer_mark(&timer);
3849 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
3851 if ((cm->profile == PROFILE_0 || cm->profile == PROFILE_2) &&
3852 (subsampling_x != 1 || subsampling_y != 1)) {
3853 vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
3854 "Non-4:2:0 color format requires profile 1 or 3");
3857 if ((cm->profile == PROFILE_1 || cm->profile == PROFILE_3) &&
3858 (subsampling_x == 1 && subsampling_y == 1)) {
3859 vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
3860 "4:2:0 color format requires profile 0 or 2");
3868 static int frame_is_reference(const VP9_COMP *cpi) {
3869 const VP9_COMMON *cm = &cpi->common;
3871 return cm->frame_type == KEY_FRAME ||
3872 cpi->refresh_last_frame ||
3873 cpi->refresh_golden_frame ||
3874 cpi->refresh_alt_ref_frame ||
3875 cm->refresh_frame_context ||
3876 cm->lf.mode_ref_delta_update ||
3877 cm->seg.update_map ||
3878 cm->seg.update_data;
3881 static void adjust_frame_rate(VP9_COMP *cpi,
3882 const struct lookahead_entry *source) {
3883 int64_t this_duration;
3886 if (source->ts_start == cpi->first_time_stamp_ever) {
3887 this_duration = source->ts_end - source->ts_start;
3890 int64_t last_duration = cpi->last_end_time_stamp_seen
3891 - cpi->last_time_stamp_seen;
3893 this_duration = source->ts_end - cpi->last_end_time_stamp_seen;
3895 // do a step update if the duration changes by 10%
3897 step = (int)((this_duration - last_duration) * 10 / last_duration);
3900 if (this_duration) {
3902 vp9_new_framerate(cpi, 10000000.0 / this_duration);
3904 // Average this frame's rate into the last second's average
3905 // frame rate. If we haven't seen 1 second yet, then average
3906 // over the whole interval seen.
3907 const double interval = MIN((double)(source->ts_end
3908 - cpi->first_time_stamp_ever), 10000000.0);
3909 double avg_duration = 10000000.0 / cpi->framerate;
3910 avg_duration *= (interval - avg_duration + this_duration);
3911 avg_duration /= interval;
3913 vp9_new_framerate(cpi, 10000000.0 / avg_duration);
3916 cpi->last_time_stamp_seen = source->ts_start;
3917 cpi->last_end_time_stamp_seen = source->ts_end;
3920 // Returns 0 if this is not an alt ref else the offset of the source frame
3921 // used as the arf midpoint.
3922 static int get_arf_src_index(VP9_COMP *cpi) {
3923 RATE_CONTROL *const rc = &cpi->rc;
3924 int arf_src_index = 0;
3925 if (is_altref_enabled(cpi)) {
3926 if (cpi->oxcf.pass == 2) {
3927 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
3928 if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
3929 arf_src_index = gf_group->arf_src_offset[gf_group->index];
3931 } else if (rc->source_alt_ref_pending) {
3932 arf_src_index = rc->frames_till_gf_update_due;
3935 return arf_src_index;
3938 static void check_src_altref(VP9_COMP *cpi,
3939 const struct lookahead_entry *source) {
3940 RATE_CONTROL *const rc = &cpi->rc;
3942 if (cpi->oxcf.pass == 2) {
3943 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
3944 rc->is_src_frame_alt_ref =
3945 (gf_group->update_type[gf_group->index] == OVERLAY_UPDATE);
3947 rc->is_src_frame_alt_ref = cpi->alt_ref_source &&
3948 (source == cpi->alt_ref_source);
3951 if (rc->is_src_frame_alt_ref) {
3952 // Current frame is an ARF overlay frame.
3953 cpi->alt_ref_source = NULL;
3955 // Don't refresh the last buffer for an ARF overlay frame. It will
3956 // become the GF so preserve last as an alternative prediction option.
3957 cpi->refresh_last_frame = 0;
3961 #if CONFIG_INTERNAL_STATS
3962 extern double vp9_get_blockiness(const unsigned char *img1, int img1_pitch,
3963 const unsigned char *img2, int img2_pitch,
3964 int width, int height);
3967 static void adjust_image_stat(double y, double u, double v, double all,
3972 s->stat[ALL] += all;
3973 s->worst = MIN(s->worst, all);
3976 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
3977 size_t *size, uint8_t *dest,
3978 int64_t *time_stamp, int64_t *time_end, int flush) {
3979 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
3980 VP9_COMMON *const cm = &cpi->common;
3981 BufferPool *const pool = cm->buffer_pool;
3982 RATE_CONTROL *const rc = &cpi->rc;
3983 struct vpx_usec_timer cmptimer;
3984 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
3985 struct lookahead_entry *last_source = NULL;
3986 struct lookahead_entry *source = NULL;
3990 if (is_two_pass_svc(cpi)) {
3991 #if CONFIG_SPATIAL_SVC
3992 vp9_svc_start_frame(cpi);
3993 // Use a small empty frame instead of a real frame
3994 if (cpi->svc.encode_empty_frame_state == ENCODING)
3995 source = &cpi->svc.empty_frame;
3997 if (oxcf->pass == 2)
3998 vp9_restore_layer_context(cpi);
3999 } else if (is_one_pass_cbr_svc(cpi)) {
4000 vp9_one_pass_cbr_svc_start_layer(cpi);
4003 vpx_usec_timer_start(&cmptimer);
4005 vp9_set_high_precision_mv(cpi, ALTREF_HIGH_PRECISION_MV);
4007 // Is multi-arf enabled.
4008 // Note that at the moment multi_arf is only configured for 2 pass VBR and
4009 // will not work properly with svc.
4010 if ((oxcf->pass == 2) && !cpi->use_svc &&
4011 (cpi->oxcf.enable_auto_arf > 1))
4012 cpi->multi_arf_allowed = 1;
4014 cpi->multi_arf_allowed = 0;
4017 cm->reset_frame_context = 0;
4018 cm->refresh_frame_context = 1;
4019 if (!is_one_pass_cbr_svc(cpi)) {
4020 cpi->refresh_last_frame = 1;
4021 cpi->refresh_golden_frame = 0;
4022 cpi->refresh_alt_ref_frame = 0;
4025 // Should we encode an arf frame.
4026 arf_src_index = get_arf_src_index(cpi);
4028 // Skip alt frame if we encode the empty frame
4029 if (is_two_pass_svc(cpi) && source != NULL)
4032 if (arf_src_index) {
4033 assert(arf_src_index <= rc->frames_to_key);
4035 if ((source = vp9_lookahead_peek(cpi->lookahead, arf_src_index)) != NULL) {
4036 cpi->alt_ref_source = source;
4038 #if CONFIG_SPATIAL_SVC
4039 if (is_two_pass_svc(cpi) && cpi->svc.spatial_layer_id > 0) {
4041 // Reference a hidden frame from a lower layer
4042 for (i = cpi->svc.spatial_layer_id - 1; i >= 0; --i) {
4043 if (oxcf->ss_enable_auto_arf[i]) {
4044 cpi->gld_fb_idx = cpi->svc.layer_context[i].alt_ref_idx;
4049 cpi->svc.layer_context[cpi->svc.spatial_layer_id].has_alt_frame = 1;
4052 if (oxcf->arnr_max_frames > 0) {
4053 // Produce the filtered ARF frame.
4054 vp9_temporal_filter(cpi, arf_src_index);
4055 vp9_extend_frame_borders(&cpi->alt_ref_buffer);
4056 force_src_buffer = &cpi->alt_ref_buffer;
4061 cpi->refresh_alt_ref_frame = 1;
4062 cpi->refresh_golden_frame = 0;
4063 cpi->refresh_last_frame = 0;
4064 rc->is_src_frame_alt_ref = 0;
4065 rc->source_alt_ref_pending = 0;
4067 rc->source_alt_ref_pending = 0;
4072 // Get last frame source.
4073 if (cm->current_video_frame > 0) {
4074 if ((last_source = vp9_lookahead_peek(cpi->lookahead, -1)) == NULL)
4078 // Read in the source frame.
4080 source = vp9_svc_lookahead_pop(cpi, cpi->lookahead, flush);
4082 source = vp9_lookahead_pop(cpi->lookahead, flush);
4084 if (source != NULL) {
4087 // if the flags indicate intra frame, but if the current picture is for
4088 // non-zero spatial layer, it should not be an intra picture.
4089 // TODO(Won Kap): this needs to change if per-layer intra frame is
4091 if ((source->flags & VPX_EFLAG_FORCE_KF) && cpi->svc.spatial_layer_id) {
4092 source->flags &= ~(unsigned int)(VPX_EFLAG_FORCE_KF);
4095 // Check to see if the frame should be encoded as an arf overlay.
4096 check_src_altref(cpi, source);
4101 cpi->un_scaled_source = cpi->Source = force_src_buffer ? force_src_buffer
4104 cpi->unscaled_last_source = last_source != NULL ? &last_source->img : NULL;
4106 *time_stamp = source->ts_start;
4107 *time_end = source->ts_end;
4108 *frame_flags = (source->flags & VPX_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
4112 if (flush && oxcf->pass == 1 && !cpi->twopass.first_pass_done) {
4113 vp9_end_first_pass(cpi); /* get last stats packet */
4114 cpi->twopass.first_pass_done = 1;
4119 if (source->ts_start < cpi->first_time_stamp_ever) {
4120 cpi->first_time_stamp_ever = source->ts_start;
4121 cpi->last_end_time_stamp_seen = source->ts_start;
4124 // Clear down mmx registers
4125 vp9_clear_system_state();
4127 // adjust frame rates based on timestamps given
4128 if (cm->show_frame) {
4129 adjust_frame_rate(cpi, source);
4132 if (is_one_pass_cbr_svc(cpi)) {
4133 vp9_update_temporal_layer_framerate(cpi);
4134 vp9_restore_layer_context(cpi);
4137 // Find a free buffer for the new frame, releasing the reference previously
4139 if (cm->new_fb_idx != INVALID_IDX) {
4140 --pool->frame_bufs[cm->new_fb_idx].ref_count;
4142 cm->new_fb_idx = get_free_fb(cm);
4144 if (cm->new_fb_idx == INVALID_IDX)
4147 cm->cur_frame = &pool->frame_bufs[cm->new_fb_idx];
4149 if (!cpi->use_svc && cpi->multi_arf_allowed) {
4150 if (cm->frame_type == KEY_FRAME) {
4151 init_buffer_indices(cpi);
4152 } else if (oxcf->pass == 2) {
4153 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
4154 cpi->alt_fb_idx = gf_group->arf_ref_idx[gf_group->index];
4158 // Start with a 0 size frame.
4161 cpi->frame_flags = *frame_flags;
4163 if ((oxcf->pass == 2) &&
4165 (is_two_pass_svc(cpi) &&
4166 cpi->svc.encode_empty_frame_state != ENCODING))) {
4167 vp9_rc_get_second_pass_params(cpi);
4168 } else if (oxcf->pass == 1) {
4169 set_frame_size(cpi);
4172 for (i = 0; i < MAX_REF_FRAMES; ++i)
4173 cpi->scaled_ref_idx[i] = INVALID_IDX;
4175 if (oxcf->pass == 1 &&
4176 (!cpi->use_svc || is_two_pass_svc(cpi))) {
4177 const int lossless = is_lossless_requested(oxcf);
4178 #if CONFIG_VP9_HIGHBITDEPTH
4179 if (cpi->oxcf.use_highbitdepth)
4180 cpi->td.mb.fwd_txm4x4 = lossless ?
4181 vp9_highbd_fwht4x4 : vp9_highbd_fdct4x4;
4183 cpi->td.mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vp9_fdct4x4;
4184 cpi->td.mb.highbd_itxm_add = lossless ? vp9_highbd_iwht4x4_add :
4185 vp9_highbd_idct4x4_add;
4187 cpi->td.mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vp9_fdct4x4;
4188 #endif // CONFIG_VP9_HIGHBITDEPTH
4189 cpi->td.mb.itxm_add = lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
4190 vp9_first_pass(cpi, source);
4191 } else if (oxcf->pass == 2 &&
4192 (!cpi->use_svc || is_two_pass_svc(cpi))) {
4193 Pass2Encode(cpi, size, dest, frame_flags);
4194 } else if (cpi->use_svc) {
4195 SvcEncode(cpi, size, dest, frame_flags);
4198 Pass0Encode(cpi, size, dest, frame_flags);
4201 if (cm->refresh_frame_context)
4202 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;
4204 // No frame encoded, or frame was dropped, release scaled references.
4205 if ((*size == 0) && (frame_is_intra_only(cm) == 0)) {
4206 release_scaled_references(cpi);
4210 cpi->droppable = !frame_is_reference(cpi);
4213 // Save layer specific state.
4214 if (is_one_pass_cbr_svc(cpi) ||
4215 ((cpi->svc.number_temporal_layers > 1 ||
4216 cpi->svc.number_spatial_layers > 1) &&
4218 vp9_save_layer_context(cpi);
4221 vpx_usec_timer_mark(&cmptimer);
4222 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
4224 if (cpi->b_calculate_psnr && oxcf->pass != 1 && cm->show_frame)
4225 generate_psnr_packet(cpi);
4227 #if CONFIG_INTERNAL_STATS
4229 if (oxcf->pass != 1) {
4231 cpi->bytes += (int)(*size);
4233 if (cm->show_frame) {
4236 if (cpi->b_calculate_psnr) {
4237 YV12_BUFFER_CONFIG *orig = cpi->Source;
4238 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
4239 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
4241 #if CONFIG_VP9_HIGHBITDEPTH
4242 calc_highbd_psnr(orig, recon, &psnr, cpi->td.mb.e_mbd.bd,
4243 cpi->oxcf.input_bit_depth);
4245 calc_psnr(orig, recon, &psnr);
4246 #endif // CONFIG_VP9_HIGHBITDEPTH
4248 adjust_image_stat(psnr.psnr[1], psnr.psnr[2], psnr.psnr[3],
4249 psnr.psnr[0], &cpi->psnr);
4250 cpi->total_sq_error += psnr.sse[0];
4251 cpi->total_samples += psnr.samples[0];
4252 samples = psnr.samples[0];
4256 double frame_ssim2 = 0, weight = 0;
4257 #if CONFIG_VP9_POSTPROC
4258 if (vp9_alloc_frame_buffer(&cm->post_proc_buffer,
4259 recon->y_crop_width, recon->y_crop_height,
4260 cm->subsampling_x, cm->subsampling_y,
4261 #if CONFIG_VP9_HIGHBITDEPTH
4262 cm->use_highbitdepth,
4264 VP9_ENC_BORDER_IN_PIXELS,
4265 cm->byte_alignment) < 0) {
4266 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
4267 "Failed to allocate post processing buffer");
4270 vp9_deblock(cm->frame_to_show, &cm->post_proc_buffer,
4271 cm->lf.filter_level * 10 / 6);
4273 vp9_clear_system_state();
4275 #if CONFIG_VP9_HIGHBITDEPTH
4276 calc_highbd_psnr(orig, pp, &psnr2, cpi->td.mb.e_mbd.bd,
4277 cpi->oxcf.input_bit_depth);
4279 calc_psnr(orig, pp, &psnr2);
4280 #endif // CONFIG_VP9_HIGHBITDEPTH
4282 cpi->totalp_sq_error += psnr2.sse[0];
4283 cpi->totalp_samples += psnr2.samples[0];
4284 adjust_image_stat(psnr2.psnr[1], psnr2.psnr[2], psnr2.psnr[3],
4285 psnr2.psnr[0], &cpi->psnrp);
4287 #if CONFIG_VP9_HIGHBITDEPTH
4288 if (cm->use_highbitdepth) {
4289 frame_ssim2 = vp9_highbd_calc_ssim(orig, recon, &weight,
4290 (int)cm->bit_depth);
4292 frame_ssim2 = vp9_calc_ssim(orig, recon, &weight);
4295 frame_ssim2 = vp9_calc_ssim(orig, recon, &weight);
4296 #endif // CONFIG_VP9_HIGHBITDEPTH
4298 cpi->worst_ssim= MIN(cpi->worst_ssim, frame_ssim2);
4299 cpi->summed_quality += frame_ssim2 * weight;
4300 cpi->summed_weights += weight;
4302 #if CONFIG_VP9_HIGHBITDEPTH
4303 if (cm->use_highbitdepth) {
4304 frame_ssim2 = vp9_highbd_calc_ssim(
4305 orig, &cm->post_proc_buffer, &weight, (int)cm->bit_depth);
4307 frame_ssim2 = vp9_calc_ssim(orig, &cm->post_proc_buffer, &weight);
4310 frame_ssim2 = vp9_calc_ssim(orig, &cm->post_proc_buffer, &weight);
4311 #endif // CONFIG_VP9_HIGHBITDEPTH
4313 cpi->summedp_quality += frame_ssim2 * weight;
4314 cpi->summedp_weights += weight;
4317 FILE *f = fopen("q_used.stt", "a");
4318 fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
4319 cpi->common.current_video_frame, y2, u2, v2,
4320 frame_psnr2, frame_ssim2);
4326 if (cpi->b_calculate_blockiness) {
4327 #if CONFIG_VP9_HIGHBITDEPTH
4328 if (!cm->use_highbitdepth)
4331 double frame_blockiness = vp9_get_blockiness(
4332 cpi->Source->y_buffer, cpi->Source->y_stride,
4333 cm->frame_to_show->y_buffer, cm->frame_to_show->y_stride,
4334 cpi->Source->y_width, cpi->Source->y_height);
4335 cpi->worst_blockiness = MAX(cpi->worst_blockiness, frame_blockiness);
4336 cpi->total_blockiness += frame_blockiness;
4340 if (cpi->b_calculate_consistency) {
4341 #if CONFIG_VP9_HIGHBITDEPTH
4342 if (!cm->use_highbitdepth)
4345 double this_inconsistency = vp9_get_ssim_metrics(
4346 cpi->Source->y_buffer, cpi->Source->y_stride,
4347 cm->frame_to_show->y_buffer, cm->frame_to_show->y_stride,
4348 cpi->Source->y_width, cpi->Source->y_height, cpi->ssim_vars,
4351 const double peak = (double)((1 << cpi->oxcf.input_bit_depth) - 1);
4352 double consistency = vpx_sse_to_psnr(samples, peak,
4353 (double)cpi->total_inconsistency);
4354 if (consistency > 0.0)
4355 cpi->worst_consistency = MIN(cpi->worst_consistency,
4357 cpi->total_inconsistency += this_inconsistency;
4361 if (cpi->b_calculate_ssimg) {
4362 double y, u, v, frame_all;
4363 #if CONFIG_VP9_HIGHBITDEPTH
4364 if (cm->use_highbitdepth) {
4365 frame_all = vp9_highbd_calc_ssimg(cpi->Source, cm->frame_to_show, &y,
4366 &u, &v, (int)cm->bit_depth);
4368 frame_all = vp9_calc_ssimg(cpi->Source, cm->frame_to_show, &y, &u,
4372 frame_all = vp9_calc_ssimg(cpi->Source, cm->frame_to_show, &y, &u, &v);
4373 #endif // CONFIG_VP9_HIGHBITDEPTH
4374 adjust_image_stat(y, u, v, frame_all, &cpi->ssimg);
4376 #if CONFIG_VP9_HIGHBITDEPTH
4377 if (!cm->use_highbitdepth)
4380 double y, u, v, frame_all;
4381 frame_all = vp9_calc_fastssim(cpi->Source, cm->frame_to_show, &y, &u,
4383 adjust_image_stat(y, u, v, frame_all, &cpi->fastssim);
4384 /* TODO(JBB): add 10/12 bit support */
4386 #if CONFIG_VP9_HIGHBITDEPTH
4387 if (!cm->use_highbitdepth)
4390 double y, u, v, frame_all;
4391 frame_all = vp9_psnrhvs(cpi->Source, cm->frame_to_show, &y, &u, &v);
4392 adjust_image_stat(y, u, v, frame_all, &cpi->psnrhvs);
4399 if (is_two_pass_svc(cpi)) {
4400 if (cpi->svc.encode_empty_frame_state == ENCODING) {
4401 cpi->svc.encode_empty_frame_state = ENCODED;
4402 cpi->svc.encode_intra_empty_frame = 0;
4405 if (cm->show_frame) {
4406 ++cpi->svc.spatial_layer_to_encode;
4407 if (cpi->svc.spatial_layer_to_encode >= cpi->svc.number_spatial_layers)
4408 cpi->svc.spatial_layer_to_encode = 0;
4410 // May need the empty frame after an visible frame.
4411 cpi->svc.encode_empty_frame_state = NEED_TO_ENCODE;
4413 } else if (is_one_pass_cbr_svc(cpi)) {
4414 if (cm->show_frame) {
4415 ++cpi->svc.spatial_layer_to_encode;
4416 if (cpi->svc.spatial_layer_to_encode >= cpi->svc.number_spatial_layers)
4417 cpi->svc.spatial_layer_to_encode = 0;
4423 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
4424 vp9_ppflags_t *flags) {
4425 VP9_COMMON *cm = &cpi->common;
4426 #if !CONFIG_VP9_POSTPROC
4430 if (!cm->show_frame) {
4434 #if CONFIG_VP9_POSTPROC
4435 ret = vp9_post_proc_frame(cm, dest, flags);
4437 if (cm->frame_to_show) {
4438 *dest = *cm->frame_to_show;
4439 dest->y_width = cm->width;
4440 dest->y_height = cm->height;
4441 dest->uv_width = cm->width >> cm->subsampling_x;
4442 dest->uv_height = cm->height >> cm->subsampling_y;
4447 #endif // !CONFIG_VP9_POSTPROC
4448 vp9_clear_system_state();
4453 int vp9_set_internal_size(VP9_COMP *cpi,
4454 VPX_SCALING horiz_mode, VPX_SCALING vert_mode) {
4455 VP9_COMMON *cm = &cpi->common;
4456 int hr = 0, hs = 0, vr = 0, vs = 0;
4458 if (horiz_mode > ONETWO || vert_mode > ONETWO)
4461 Scale2Ratio(horiz_mode, &hr, &hs);
4462 Scale2Ratio(vert_mode, &vr, &vs);
4464 // always go to the next whole number
4465 cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
4466 cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
4467 assert(cm->width <= cpi->initial_width);
4468 assert(cm->height <= cpi->initial_height);
4470 update_frame_size(cpi);
4475 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
4476 unsigned int height) {
4477 VP9_COMMON *cm = &cpi->common;
4478 #if CONFIG_VP9_HIGHBITDEPTH
4479 check_initial_width(cpi, cm->use_highbitdepth, 1, 1);
4481 check_initial_width(cpi, 1, 1);
4482 #endif // CONFIG_VP9_HIGHBITDEPTH
4484 #if CONFIG_VP9_TEMPORAL_DENOISING
4485 setup_denoiser_buffer(cpi);
4490 if (cm->width > cpi->initial_width) {
4491 cm->width = cpi->initial_width;
4492 printf("Warning: Desired width too large, changed to %d\n", cm->width);
4497 cm->height = height;
4498 if (cm->height > cpi->initial_height) {
4499 cm->height = cpi->initial_height;
4500 printf("Warning: Desired height too large, changed to %d\n", cm->height);
4503 assert(cm->width <= cpi->initial_width);
4504 assert(cm->height <= cpi->initial_height);
4506 update_frame_size(cpi);
4511 void vp9_set_svc(VP9_COMP *cpi, int use_svc) {
4512 cpi->use_svc = use_svc;
4516 int64_t vp9_get_y_sse(const YV12_BUFFER_CONFIG *a,
4517 const YV12_BUFFER_CONFIG *b) {
4518 assert(a->y_crop_width == b->y_crop_width);
4519 assert(a->y_crop_height == b->y_crop_height);
4521 return get_sse(a->y_buffer, a->y_stride, b->y_buffer, b->y_stride,
4522 a->y_crop_width, a->y_crop_height);
4525 #if CONFIG_VP9_HIGHBITDEPTH
4526 int64_t vp9_highbd_get_y_sse(const YV12_BUFFER_CONFIG *a,
4527 const YV12_BUFFER_CONFIG *b) {
4528 assert(a->y_crop_width == b->y_crop_width);
4529 assert(a->y_crop_height == b->y_crop_height);
4530 assert((a->flags & YV12_FLAG_HIGHBITDEPTH) != 0);
4531 assert((b->flags & YV12_FLAG_HIGHBITDEPTH) != 0);
4533 return highbd_get_sse(a->y_buffer, a->y_stride, b->y_buffer, b->y_stride,
4534 a->y_crop_width, a->y_crop_height);
4536 #endif // CONFIG_VP9_HIGHBITDEPTH
4538 int vp9_get_quantizer(VP9_COMP *cpi) {
4539 return cpi->common.base_qindex;
4542 void vp9_apply_encoding_flags(VP9_COMP *cpi, vpx_enc_frame_flags_t flags) {
4543 if (flags & (VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_GF |
4544 VP8_EFLAG_NO_REF_ARF)) {
4547 if (flags & VP8_EFLAG_NO_REF_LAST)
4548 ref ^= VP9_LAST_FLAG;
4550 if (flags & VP8_EFLAG_NO_REF_GF)
4551 ref ^= VP9_GOLD_FLAG;
4553 if (flags & VP8_EFLAG_NO_REF_ARF)
4554 ref ^= VP9_ALT_FLAG;
4556 vp9_use_as_reference(cpi, ref);
4559 if (flags & (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF |
4560 VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_FORCE_GF |
4561 VP8_EFLAG_FORCE_ARF)) {
4564 if (flags & VP8_EFLAG_NO_UPD_LAST)
4565 upd ^= VP9_LAST_FLAG;
4567 if (flags & VP8_EFLAG_NO_UPD_GF)
4568 upd ^= VP9_GOLD_FLAG;
4570 if (flags & VP8_EFLAG_NO_UPD_ARF)
4571 upd ^= VP9_ALT_FLAG;
4573 vp9_update_reference(cpi, upd);
4576 if (flags & VP8_EFLAG_NO_UPD_ENTROPY) {
4577 vp9_update_entropy(cpi, 0);