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 "./vpx_scale_rtcd.h"
17 #include "vpx/internal/vpx_psnr.h"
18 #include "vpx_ports/vpx_timer.h"
20 #include "vp9/common/vp9_alloccommon.h"
21 #include "vp9/common/vp9_filter.h"
22 #include "vp9/common/vp9_idct.h"
23 #if CONFIG_VP9_POSTPROC
24 #include "vp9/common/vp9_postproc.h"
26 #include "vp9/common/vp9_reconinter.h"
27 #include "vp9/common/vp9_systemdependent.h"
28 #include "vp9/common/vp9_tile_common.h"
30 #include "vp9/encoder/vp9_aq_complexity.h"
31 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
32 #include "vp9/encoder/vp9_aq_variance.h"
33 #include "vp9/encoder/vp9_bitstream.h"
34 #include "vp9/encoder/vp9_context_tree.h"
35 #include "vp9/encoder/vp9_encodeframe.h"
36 #include "vp9/encoder/vp9_encodemv.h"
37 #include "vp9/encoder/vp9_firstpass.h"
38 #include "vp9/encoder/vp9_mbgraph.h"
39 #include "vp9/encoder/vp9_encoder.h"
40 #include "vp9/encoder/vp9_picklpf.h"
41 #include "vp9/encoder/vp9_ratectrl.h"
42 #include "vp9/encoder/vp9_rdopt.h"
43 #include "vp9/encoder/vp9_segmentation.h"
44 #include "vp9/encoder/vp9_speed_features.h"
45 #if CONFIG_INTERNAL_STATS
46 #include "vp9/encoder/vp9_ssim.h"
48 #include "vp9/encoder/vp9_temporal_filter.h"
49 #include "vp9/encoder/vp9_resize.h"
50 #include "vp9/encoder/vp9_svc_layercontext.h"
52 void vp9_coef_tree_initialize();
54 #define DEFAULT_INTERP_FILTER SWITCHABLE
56 #define SHARP_FILTER_QTHRESH 0 /* Q threshold for 8-tap sharp filter */
58 #define ALTREF_HIGH_PRECISION_MV 1 // Whether to use high precision mv
59 // for altref computation.
60 #define HIGH_PRECISION_MV_QTHRESH 200 // Q threshold for high precision
61 // mv. Choose a very high value for
62 // now so that HIGH_PRECISION is always
65 // #define OUTPUT_YUV_REC
67 #ifdef OUTPUT_YUV_DENOISED
68 FILE *yuv_denoised_file;
83 static INLINE void Scale2Ratio(VPX_SCALING mode, int *hr, int *hs) {
109 static void set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv) {
110 MACROBLOCK *const mb = &cpi->mb;
111 cpi->common.allow_high_precision_mv = allow_high_precision_mv;
112 if (cpi->common.allow_high_precision_mv) {
113 mb->mvcost = mb->nmvcost_hp;
114 mb->mvsadcost = mb->nmvsadcost_hp;
116 mb->mvcost = mb->nmvcost;
117 mb->mvsadcost = mb->nmvsadcost;
121 static void setup_frame(VP9_COMP *cpi) {
122 VP9_COMMON *const cm = &cpi->common;
123 // Set up entropy context depending on frame type. The decoder mandates
124 // the use of the default context, index 0, for keyframes and inter
125 // frames where the error_resilient_mode or intra_only flag is set. For
126 // other inter-frames the encoder currently uses only two contexts;
127 // context 1 for ALTREF frames and context 0 for the others.
128 if (frame_is_intra_only(cm) || cm->error_resilient_mode) {
129 vp9_setup_past_independence(cm);
132 cm->frame_context_idx = cpi->refresh_alt_ref_frame;
135 if (cm->frame_type == KEY_FRAME) {
136 cpi->refresh_golden_frame = 1;
137 cpi->refresh_alt_ref_frame = 1;
139 cm->fc = cm->frame_contexts[cm->frame_context_idx];
143 void vp9_initialize_enc() {
144 static int init_done = 0;
147 vp9_init_neighbors();
148 vp9_coef_tree_initialize();
149 vp9_tokenize_initialize();
151 vp9_rc_init_minq_luts();
152 vp9_entropy_mv_init();
153 vp9_entropy_mode_init();
154 vp9_temporal_filter_init();
159 static void dealloc_compressor_data(VP9_COMP *cpi) {
160 VP9_COMMON *const cm = &cpi->common;
163 // Delete sementation map
164 vpx_free(cpi->segmentation_map);
165 cpi->segmentation_map = NULL;
166 vpx_free(cm->last_frame_seg_map);
167 cm->last_frame_seg_map = NULL;
168 vpx_free(cpi->coding_context.last_frame_seg_map_copy);
169 cpi->coding_context.last_frame_seg_map_copy = NULL;
171 vpx_free(cpi->complexity_map);
172 cpi->complexity_map = NULL;
174 vp9_cyclic_refresh_free(cpi->cyclic_refresh);
175 cpi->cyclic_refresh = NULL;
177 vpx_free(cpi->active_map);
178 cpi->active_map = NULL;
180 vp9_free_frame_buffers(cm);
182 vp9_free_frame_buffer(&cpi->last_frame_uf);
183 vp9_free_frame_buffer(&cpi->scaled_source);
184 vp9_free_frame_buffer(&cpi->scaled_last_source);
185 vp9_free_frame_buffer(&cpi->alt_ref_buffer);
186 vp9_lookahead_destroy(cpi->lookahead);
191 vp9_free_pc_tree(cpi);
193 for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
194 LAYER_CONTEXT *const lc = &cpi->svc.layer_context[i];
195 vpx_free(lc->rc_twopass_stats_in.buf);
196 lc->rc_twopass_stats_in.buf = NULL;
197 lc->rc_twopass_stats_in.sz = 0;
201 static void save_coding_context(VP9_COMP *cpi) {
202 CODING_CONTEXT *const cc = &cpi->coding_context;
203 VP9_COMMON *cm = &cpi->common;
205 // Stores a snapshot of key state variables which can subsequently be
206 // restored with a call to vp9_restore_coding_context. These functions are
207 // intended for use in a re-code loop in vp9_compress_frame where the
208 // quantizer value is adjusted between loop iterations.
209 vp9_copy(cc->nmvjointcost, cpi->mb.nmvjointcost);
210 vp9_copy(cc->nmvcosts, cpi->mb.nmvcosts);
211 vp9_copy(cc->nmvcosts_hp, cpi->mb.nmvcosts_hp);
213 vp9_copy(cc->segment_pred_probs, cm->seg.pred_probs);
215 vpx_memcpy(cpi->coding_context.last_frame_seg_map_copy,
216 cm->last_frame_seg_map, (cm->mi_rows * cm->mi_cols));
218 vp9_copy(cc->last_ref_lf_deltas, cm->lf.last_ref_deltas);
219 vp9_copy(cc->last_mode_lf_deltas, cm->lf.last_mode_deltas);
224 static void restore_coding_context(VP9_COMP *cpi) {
225 CODING_CONTEXT *const cc = &cpi->coding_context;
226 VP9_COMMON *cm = &cpi->common;
228 // Restore key state variables to the snapshot state stored in the
229 // previous call to vp9_save_coding_context.
230 vp9_copy(cpi->mb.nmvjointcost, cc->nmvjointcost);
231 vp9_copy(cpi->mb.nmvcosts, cc->nmvcosts);
232 vp9_copy(cpi->mb.nmvcosts_hp, cc->nmvcosts_hp);
234 vp9_copy(cm->seg.pred_probs, cc->segment_pred_probs);
236 vpx_memcpy(cm->last_frame_seg_map,
237 cpi->coding_context.last_frame_seg_map_copy,
238 (cm->mi_rows * cm->mi_cols));
240 vp9_copy(cm->lf.last_ref_deltas, cc->last_ref_lf_deltas);
241 vp9_copy(cm->lf.last_mode_deltas, cc->last_mode_lf_deltas);
246 static void configure_static_seg_features(VP9_COMP *cpi) {
247 VP9_COMMON *const cm = &cpi->common;
248 const RATE_CONTROL *const rc = &cpi->rc;
249 struct segmentation *const seg = &cm->seg;
251 int high_q = (int)(rc->avg_q > 48.0);
254 // Disable and clear down for KF
255 if (cm->frame_type == KEY_FRAME) {
256 // Clear down the global segmentation map
257 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
259 seg->update_data = 0;
260 cpi->static_mb_pct = 0;
262 // Disable segmentation
263 vp9_disable_segmentation(seg);
265 // Clear down the segment features.
266 vp9_clearall_segfeatures(seg);
267 } else if (cpi->refresh_alt_ref_frame) {
268 // If this is an alt ref frame
269 // Clear down the global segmentation map
270 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
272 seg->update_data = 0;
273 cpi->static_mb_pct = 0;
275 // Disable segmentation and individual segment features by default
276 vp9_disable_segmentation(seg);
277 vp9_clearall_segfeatures(seg);
279 // Scan frames from current to arf frame.
280 // This function re-enables segmentation if appropriate.
281 vp9_update_mbgraph_stats(cpi);
283 // If segmentation was enabled set those features needed for the
287 seg->update_data = 1;
289 qi_delta = vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 0.875);
290 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta - 2);
291 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
293 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
294 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
296 // Where relevant assume segment data is delta data
297 seg->abs_delta = SEGMENT_DELTADATA;
299 } else if (seg->enabled) {
300 // All other frames if segmentation has been enabled
302 // First normal frame in a valid gf or alt ref group
303 if (rc->frames_since_golden == 0) {
304 // Set up segment features for normal frames in an arf group
305 if (rc->source_alt_ref_active) {
307 seg->update_data = 1;
308 seg->abs_delta = SEGMENT_DELTADATA;
310 qi_delta = vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 1.125);
311 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta + 2);
312 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
314 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
315 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
317 // Segment coding disabled for compred testing
318 if (high_q || (cpi->static_mb_pct == 100)) {
319 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
320 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
321 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
324 // Disable segmentation and clear down features if alt ref
325 // is not active for this group
327 vp9_disable_segmentation(seg);
329 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
332 seg->update_data = 0;
334 vp9_clearall_segfeatures(seg);
336 } else if (rc->is_src_frame_alt_ref) {
337 // Special case where we are coding over the top of a previous
339 // Segment coding disabled for compred testing
341 // Enable ref frame features for segment 0 as well
342 vp9_enable_segfeature(seg, 0, SEG_LVL_REF_FRAME);
343 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
345 // All mbs should use ALTREF_FRAME
346 vp9_clear_segdata(seg, 0, SEG_LVL_REF_FRAME);
347 vp9_set_segdata(seg, 0, SEG_LVL_REF_FRAME, ALTREF_FRAME);
348 vp9_clear_segdata(seg, 1, SEG_LVL_REF_FRAME);
349 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
351 // Skip all MBs if high Q (0,0 mv and skip coeffs)
353 vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
354 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
356 // Enable data update
357 seg->update_data = 1;
361 // No updates.. leave things as they are.
363 seg->update_data = 0;
368 static void update_reference_segmentation_map(VP9_COMP *cpi) {
369 VP9_COMMON *const cm = &cpi->common;
370 MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
371 uint8_t *cache_ptr = cm->last_frame_seg_map;
374 for (row = 0; row < cm->mi_rows; row++) {
375 MODE_INFO **mi_8x8 = mi_8x8_ptr;
376 uint8_t *cache = cache_ptr;
377 for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
378 cache[0] = mi_8x8[0]->mbmi.segment_id;
379 mi_8x8_ptr += cm->mi_stride;
380 cache_ptr += cm->mi_cols;
385 static void set_speed_features(VP9_COMP *cpi) {
386 #if CONFIG_INTERNAL_STATS
388 for (i = 0; i < MAX_MODES; ++i)
389 cpi->mode_chosen_counts[i] = 0;
392 vp9_set_speed_features(cpi);
394 // Set rd thresholds based on mode and speed setting
395 vp9_set_rd_speed_thresholds(cpi);
396 vp9_set_rd_speed_thresholds_sub8x8(cpi);
399 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
400 VP9_COMMON *cm = &cpi->common;
401 const VP9EncoderConfig *oxcf = &cpi->oxcf;
403 cpi->lookahead = vp9_lookahead_init(oxcf->width, oxcf->height,
404 cm->subsampling_x, cm->subsampling_y,
405 oxcf->lag_in_frames);
407 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
408 "Failed to allocate lag buffers");
410 if (vp9_realloc_frame_buffer(&cpi->alt_ref_buffer,
411 oxcf->width, oxcf->height,
412 cm->subsampling_x, cm->subsampling_y,
413 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
414 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
415 "Failed to allocate altref buffer");
418 void vp9_alloc_compressor_data(VP9_COMP *cpi) {
419 VP9_COMMON *cm = &cpi->common;
421 if (vp9_alloc_frame_buffers(cm, cm->width, cm->height))
422 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
423 "Failed to allocate frame buffers");
425 if (vp9_alloc_frame_buffer(&cpi->last_frame_uf,
426 cm->width, cm->height,
427 cm->subsampling_x, cm->subsampling_y,
428 VP9_ENC_BORDER_IN_PIXELS))
429 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
430 "Failed to allocate last frame buffer");
432 if (vp9_alloc_frame_buffer(&cpi->scaled_source,
433 cm->width, cm->height,
434 cm->subsampling_x, cm->subsampling_y,
435 VP9_ENC_BORDER_IN_PIXELS))
436 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
437 "Failed to allocate scaled source buffer");
439 if (vp9_alloc_frame_buffer(&cpi->scaled_last_source,
440 cm->width, cm->height,
441 cm->subsampling_x, cm->subsampling_y,
442 VP9_ENC_BORDER_IN_PIXELS))
443 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
444 "Failed to allocate scaled last source buffer");
449 unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
451 CHECK_MEM_ERROR(cm, cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
454 vp9_setup_pc_tree(&cpi->common, cpi);
457 static void update_frame_size(VP9_COMP *cpi) {
458 VP9_COMMON *const cm = &cpi->common;
459 MACROBLOCKD *const xd = &cpi->mb.e_mbd;
461 vp9_update_frame_size(cm);
463 // Update size of buffers local to this frame
464 if (vp9_realloc_frame_buffer(&cpi->last_frame_uf,
465 cm->width, cm->height,
466 cm->subsampling_x, cm->subsampling_y,
467 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
468 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
469 "Failed to reallocate last frame buffer");
471 if (vp9_realloc_frame_buffer(&cpi->scaled_source,
472 cm->width, cm->height,
473 cm->subsampling_x, cm->subsampling_y,
474 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
475 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
476 "Failed to reallocate scaled source buffer");
478 if (vp9_realloc_frame_buffer(&cpi->scaled_last_source,
479 cm->width, cm->height,
480 cm->subsampling_x, cm->subsampling_y,
481 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
482 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
483 "Failed to reallocate scaled last source buffer");
486 int y_stride = cpi->scaled_source.y_stride;
488 if (cpi->sf.mv.search_method == NSTEP) {
489 vp9_init3smotion_compensation(&cpi->ss_cfg, y_stride);
490 } else if (cpi->sf.mv.search_method == DIAMOND) {
491 vp9_init_dsmotion_compensation(&cpi->ss_cfg, y_stride);
495 init_macroblockd(cm, xd);
498 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
499 cpi->oxcf.framerate = framerate < 0.1 ? 30 : framerate;
500 vp9_rc_update_framerate(cpi);
503 int64_t vp9_rescale(int64_t val, int64_t num, int denom) {
505 int64_t llden = denom;
508 return (llval * llnum / llden);
511 static void set_tile_limits(VP9_COMP *cpi) {
512 VP9_COMMON *const cm = &cpi->common;
514 int min_log2_tile_cols, max_log2_tile_cols;
515 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
517 cm->log2_tile_cols = clamp(cpi->oxcf.tile_columns,
518 min_log2_tile_cols, max_log2_tile_cols);
519 cm->log2_tile_rows = cpi->oxcf.tile_rows;
522 static void init_config(struct VP9_COMP *cpi, VP9EncoderConfig *oxcf) {
523 VP9_COMMON *const cm = &cpi->common;
527 cm->profile = oxcf->profile;
528 cm->bit_depth = oxcf->bit_depth;
530 cm->width = oxcf->width;
531 cm->height = oxcf->height;
532 cm->subsampling_x = 0;
533 cm->subsampling_y = 0;
534 vp9_alloc_compressor_data(cpi);
536 // Spatial scalability.
537 cpi->svc.number_spatial_layers = oxcf->ss_number_layers;
538 // Temporal scalability.
539 cpi->svc.number_temporal_layers = oxcf->ts_number_layers;
541 if ((cpi->svc.number_temporal_layers > 1 &&
542 cpi->oxcf.rc_mode == VPX_CBR) ||
543 (cpi->svc.number_spatial_layers > 1 &&
544 cpi->oxcf.mode == TWO_PASS_SECOND_BEST)) {
545 vp9_init_layer_context(cpi);
548 // change includes all joint functionality
549 vp9_change_config(cpi, oxcf);
551 cpi->static_mb_pct = 0;
557 set_tile_limits(cpi);
560 static int get_pass(MODE mode) {
570 case TWO_PASS_SECOND_GOOD:
571 case TWO_PASS_SECOND_BEST:
577 void vp9_change_config(struct VP9_COMP *cpi, const VP9EncoderConfig *oxcf) {
578 VP9_COMMON *const cm = &cpi->common;
579 RATE_CONTROL *const rc = &cpi->rc;
581 if (cm->profile != oxcf->profile)
582 cm->profile = oxcf->profile;
583 cm->bit_depth = oxcf->bit_depth;
585 if (cm->profile <= PROFILE_1)
586 assert(cm->bit_depth == BITS_8);
588 assert(cm->bit_depth > BITS_8);
591 cpi->pass = get_pass(cpi->oxcf.mode);
593 rc->baseline_gf_interval = DEFAULT_GF_INTERVAL;
594 cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
596 cpi->refresh_golden_frame = 0;
597 cpi->refresh_last_frame = 1;
598 cm->refresh_frame_context = 1;
599 cm->reset_frame_context = 0;
601 vp9_reset_segment_features(&cm->seg);
602 set_high_precision_mv(cpi, 0);
607 for (i = 0; i < MAX_SEGMENTS; i++)
608 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
610 cpi->encode_breakout = cpi->oxcf.encode_breakout;
612 // local file playback mode == really big buffer
613 if (cpi->oxcf.rc_mode == VPX_VBR) {
614 cpi->oxcf.starting_buffer_level_ms = 60000;
615 cpi->oxcf.optimal_buffer_level_ms = 60000;
616 cpi->oxcf.maximum_buffer_size_ms = 240000;
619 rc->starting_buffer_level = vp9_rescale(cpi->oxcf.starting_buffer_level_ms,
620 cpi->oxcf.target_bandwidth, 1000);
622 // Set or reset optimal and maximum buffer levels.
623 if (cpi->oxcf.optimal_buffer_level_ms == 0)
624 rc->optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
626 rc->optimal_buffer_level = vp9_rescale(cpi->oxcf.optimal_buffer_level_ms,
627 cpi->oxcf.target_bandwidth, 1000);
629 if (cpi->oxcf.maximum_buffer_size_ms == 0)
630 rc->maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
632 rc->maximum_buffer_size = vp9_rescale(cpi->oxcf.maximum_buffer_size_ms,
633 cpi->oxcf.target_bandwidth, 1000);
634 // Under a configuration change, where maximum_buffer_size may change,
635 // keep buffer level clipped to the maximum allowed buffer size.
636 rc->bits_off_target = MIN(rc->bits_off_target, rc->maximum_buffer_size);
637 rc->buffer_level = MIN(rc->buffer_level, rc->maximum_buffer_size);
639 // Set up frame rate and related parameters rate control values.
640 vp9_new_framerate(cpi, cpi->oxcf.framerate);
642 // Set absolute upper and lower quality limits
643 rc->worst_quality = cpi->oxcf.worst_allowed_q;
644 rc->best_quality = cpi->oxcf.best_allowed_q;
646 cm->interp_filter = DEFAULT_INTERP_FILTER;
648 cm->display_width = cpi->oxcf.width;
649 cm->display_height = cpi->oxcf.height;
651 if (cpi->initial_width) {
652 // Increasing the size of the frame beyond the first seen frame, or some
653 // otherwise signaled maximum size, is not supported.
654 // TODO(jkoleszar): exit gracefully.
655 assert(cm->width <= cpi->initial_width);
656 assert(cm->height <= cpi->initial_height);
658 update_frame_size(cpi);
660 if ((cpi->svc.number_temporal_layers > 1 &&
661 cpi->oxcf.rc_mode == VPX_CBR) ||
662 (cpi->svc.number_spatial_layers > 1 && cpi->pass == 2)) {
663 vp9_update_layer_context_change_config(cpi,
664 (int)cpi->oxcf.target_bandwidth);
667 #if CONFIG_MULTIPLE_ARF
668 vp9_zero(cpi->alt_ref_source);
670 cpi->alt_ref_source = NULL;
672 rc->is_src_frame_alt_ref = 0;
675 // Experimental RD Code
676 cpi->frame_distortion = 0;
677 cpi->last_frame_distortion = 0;
680 set_tile_limits(cpi);
682 cpi->ext_refresh_frame_flags_pending = 0;
683 cpi->ext_refresh_frame_context_pending = 0;
686 vp9_denoiser_alloc(&(cpi->denoiser), cm->width, cm->height,
687 // TODO(tkopp) An unrelated bug causes
688 // cm->subsampling_{x,y} to be uninitialized at this point
689 // in execution. For now we assume YUV-420, which is x/y
692 // cm->subsampling_x, cm->subsampling_y,
693 VP9_ENC_BORDER_IN_PIXELS);
698 #define M_LOG2_E 0.693147180559945309417
700 #define log2f(x) (log (x) / (float) M_LOG2_E)
702 static void cal_nmvjointsadcost(int *mvjointsadcost) {
703 mvjointsadcost[0] = 600;
704 mvjointsadcost[1] = 300;
705 mvjointsadcost[2] = 300;
706 mvjointsadcost[3] = 300;
709 static void cal_nmvsadcosts(int *mvsadcost[2]) {
716 double z = 256 * (2 * (log2f(8 * i) + .6));
717 mvsadcost[0][i] = (int)z;
718 mvsadcost[1][i] = (int)z;
719 mvsadcost[0][-i] = (int)z;
720 mvsadcost[1][-i] = (int)z;
721 } while (++i <= MV_MAX);
724 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
731 double z = 256 * (2 * (log2f(8 * i) + .6));
732 mvsadcost[0][i] = (int)z;
733 mvsadcost[1][i] = (int)z;
734 mvsadcost[0][-i] = (int)z;
735 mvsadcost[1][-i] = (int)z;
736 } while (++i <= MV_MAX);
740 VP9_COMP *vp9_create_compressor(VP9EncoderConfig *oxcf) {
742 VP9_COMP *const cpi = vpx_memalign(32, sizeof(VP9_COMP));
743 VP9_COMMON *const cm = cpi != NULL ? &cpi->common : NULL;
750 if (setjmp(cm->error.jmp)) {
751 cm->error.setjmp = 0;
752 vp9_remove_compressor(cpi);
756 cm->error.setjmp = 1;
762 init_config(cpi, oxcf);
763 vp9_rc_init(&cpi->oxcf, cpi->pass, &cpi->rc);
765 cm->current_video_frame = 0;
767 // Set reference frame sign bias for ALTREF frame to 1 (for now)
768 cm->ref_frame_sign_bias[ALTREF_FRAME] = 1;
770 cpi->gold_is_last = 0;
771 cpi->alt_is_last = 0;
772 cpi->gold_is_alt = 0;
774 // Create the encoder segmentation map and set all entries to 0
775 CHECK_MEM_ERROR(cm, cpi->segmentation_map,
776 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
778 // Create a complexity map used for rd adjustment
779 CHECK_MEM_ERROR(cm, cpi->complexity_map,
780 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
782 // Create a map used for cyclic background refresh.
783 CHECK_MEM_ERROR(cm, cpi->cyclic_refresh,
784 vp9_cyclic_refresh_alloc(cm->mi_rows, cm->mi_cols));
786 // And a place holder structure is the coding context
787 // for use if we want to save and restore it
788 CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
789 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
791 CHECK_MEM_ERROR(cm, cpi->active_map, vpx_calloc(cm->MBs, 1));
792 vpx_memset(cpi->active_map, 1, cm->MBs);
793 cpi->active_map_enabled = 0;
795 for (i = 0; i < (sizeof(cpi->mbgraph_stats) /
796 sizeof(cpi->mbgraph_stats[0])); i++) {
797 CHECK_MEM_ERROR(cm, cpi->mbgraph_stats[i].mb_stats,
799 sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
802 cpi->refresh_alt_ref_frame = 0;
804 #if CONFIG_MULTIPLE_ARF
805 // Turn multiple ARF usage on/off. This is a quick hack for the initial test
806 // version. It should eventually be set via the codec API.
807 cpi->multi_arf_enabled = 1;
809 if (cpi->multi_arf_enabled) {
810 cpi->sequence_number = 0;
811 cpi->frame_coding_order_period = 0;
812 vp9_zero(cpi->frame_coding_order);
813 vp9_zero(cpi->arf_buffer_idx);
817 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
818 #if CONFIG_INTERNAL_STATS
819 cpi->b_calculate_ssimg = 0;
824 if (cpi->b_calculate_psnr) {
829 cpi->total_sq_error = 0;
830 cpi->total_samples = 0;
836 cpi->totalp_sq_error = 0;
837 cpi->totalp_samples = 0;
839 cpi->tot_recode_hits = 0;
840 cpi->summed_quality = 0;
841 cpi->summed_weights = 0;
842 cpi->summedp_quality = 0;
843 cpi->summedp_weights = 0;
846 if (cpi->b_calculate_ssimg) {
847 cpi->total_ssimg_y = 0;
848 cpi->total_ssimg_u = 0;
849 cpi->total_ssimg_v = 0;
850 cpi->total_ssimg_all = 0;
855 cpi->first_time_stamp_ever = INT64_MAX;
857 cal_nmvjointsadcost(cpi->mb.nmvjointsadcost);
858 cpi->mb.nmvcost[0] = &cpi->mb.nmvcosts[0][MV_MAX];
859 cpi->mb.nmvcost[1] = &cpi->mb.nmvcosts[1][MV_MAX];
860 cpi->mb.nmvsadcost[0] = &cpi->mb.nmvsadcosts[0][MV_MAX];
861 cpi->mb.nmvsadcost[1] = &cpi->mb.nmvsadcosts[1][MV_MAX];
862 cal_nmvsadcosts(cpi->mb.nmvsadcost);
864 cpi->mb.nmvcost_hp[0] = &cpi->mb.nmvcosts_hp[0][MV_MAX];
865 cpi->mb.nmvcost_hp[1] = &cpi->mb.nmvcosts_hp[1][MV_MAX];
866 cpi->mb.nmvsadcost_hp[0] = &cpi->mb.nmvsadcosts_hp[0][MV_MAX];
867 cpi->mb.nmvsadcost_hp[1] = &cpi->mb.nmvsadcosts_hp[1][MV_MAX];
868 cal_nmvsadcosts_hp(cpi->mb.nmvsadcost_hp);
870 #ifdef OUTPUT_YUV_DENOISED
871 yuv_denoised_file = fopen("denoised.yuv", "ab");
873 #ifdef OUTPUT_YUV_SRC
874 yuv_file = fopen("bd.yuv", "ab");
876 #ifdef OUTPUT_YUV_REC
877 yuv_rec_file = fopen("rec.yuv", "wb");
881 framepsnr = fopen("framepsnr.stt", "a");
882 kf_list = fopen("kf_list.stt", "w");
885 cpi->output_pkt_list = oxcf->output_pkt_list;
887 cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
889 if (cpi->pass == 1) {
890 vp9_init_first_pass(cpi);
891 } else if (cpi->pass == 2) {
892 const size_t packet_sz = sizeof(FIRSTPASS_STATS);
893 const int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
895 if (cpi->svc.number_spatial_layers > 1
896 && cpi->svc.number_temporal_layers == 1) {
897 FIRSTPASS_STATS *const stats = oxcf->two_pass_stats_in.buf;
898 FIRSTPASS_STATS *stats_copy[VPX_SS_MAX_LAYERS] = {0};
901 for (i = 0; i < oxcf->ss_number_layers; ++i) {
902 FIRSTPASS_STATS *const last_packet_for_layer =
903 &stats[packets - oxcf->ss_number_layers + i];
904 const int layer_id = (int)last_packet_for_layer->spatial_layer_id;
905 const int packets_in_layer = (int)last_packet_for_layer->count + 1;
906 if (layer_id >= 0 && layer_id < oxcf->ss_number_layers) {
907 LAYER_CONTEXT *const lc = &cpi->svc.layer_context[layer_id];
909 vpx_free(lc->rc_twopass_stats_in.buf);
911 lc->rc_twopass_stats_in.sz = packets_in_layer * packet_sz;
912 CHECK_MEM_ERROR(cm, lc->rc_twopass_stats_in.buf,
913 vpx_malloc(lc->rc_twopass_stats_in.sz));
914 lc->twopass.stats_in_start = lc->rc_twopass_stats_in.buf;
915 lc->twopass.stats_in = lc->twopass.stats_in_start;
916 lc->twopass.stats_in_end = lc->twopass.stats_in_start
917 + packets_in_layer - 1;
918 stats_copy[layer_id] = lc->rc_twopass_stats_in.buf;
922 for (i = 0; i < packets; ++i) {
923 const int layer_id = (int)stats[i].spatial_layer_id;
924 if (layer_id >= 0 && layer_id < oxcf->ss_number_layers
925 && stats_copy[layer_id] != NULL) {
926 *stats_copy[layer_id] = stats[i];
927 ++stats_copy[layer_id];
931 vp9_init_second_pass_spatial_svc(cpi);
933 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
934 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
935 cpi->twopass.stats_in_end = &cpi->twopass.stats_in[packets - 1];
937 vp9_init_second_pass(cpi);
941 set_speed_features(cpi);
943 // Default rd threshold factors for mode selection
944 for (i = 0; i < BLOCK_SIZES; ++i) {
945 for (j = 0; j < MAX_MODES; ++j)
946 cpi->rd.thresh_freq_fact[i][j] = 32;
949 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF)\
950 cpi->fn_ptr[BT].sdf = SDF; \
951 cpi->fn_ptr[BT].sdaf = SDAF; \
952 cpi->fn_ptr[BT].vf = VF; \
953 cpi->fn_ptr[BT].svf = SVF; \
954 cpi->fn_ptr[BT].svaf = SVAF; \
955 cpi->fn_ptr[BT].sdx3f = SDX3F; \
956 cpi->fn_ptr[BT].sdx8f = SDX8F; \
957 cpi->fn_ptr[BT].sdx4df = SDX4DF;
959 BFP(BLOCK_32X16, vp9_sad32x16, vp9_sad32x16_avg,
960 vp9_variance32x16, vp9_sub_pixel_variance32x16,
961 vp9_sub_pixel_avg_variance32x16, NULL, NULL, vp9_sad32x16x4d)
963 BFP(BLOCK_16X32, vp9_sad16x32, vp9_sad16x32_avg,
964 vp9_variance16x32, vp9_sub_pixel_variance16x32,
965 vp9_sub_pixel_avg_variance16x32, NULL, NULL, vp9_sad16x32x4d)
967 BFP(BLOCK_64X32, vp9_sad64x32, vp9_sad64x32_avg,
968 vp9_variance64x32, vp9_sub_pixel_variance64x32,
969 vp9_sub_pixel_avg_variance64x32, NULL, NULL, vp9_sad64x32x4d)
971 BFP(BLOCK_32X64, vp9_sad32x64, vp9_sad32x64_avg,
972 vp9_variance32x64, vp9_sub_pixel_variance32x64,
973 vp9_sub_pixel_avg_variance32x64, NULL, NULL, vp9_sad32x64x4d)
975 BFP(BLOCK_32X32, vp9_sad32x32, vp9_sad32x32_avg,
976 vp9_variance32x32, vp9_sub_pixel_variance32x32,
977 vp9_sub_pixel_avg_variance32x32, vp9_sad32x32x3, vp9_sad32x32x8,
980 BFP(BLOCK_64X64, vp9_sad64x64, vp9_sad64x64_avg,
981 vp9_variance64x64, vp9_sub_pixel_variance64x64,
982 vp9_sub_pixel_avg_variance64x64, vp9_sad64x64x3, vp9_sad64x64x8,
985 BFP(BLOCK_16X16, vp9_sad16x16, vp9_sad16x16_avg,
986 vp9_variance16x16, vp9_sub_pixel_variance16x16,
987 vp9_sub_pixel_avg_variance16x16, vp9_sad16x16x3, vp9_sad16x16x8,
990 BFP(BLOCK_16X8, vp9_sad16x8, vp9_sad16x8_avg,
991 vp9_variance16x8, vp9_sub_pixel_variance16x8,
992 vp9_sub_pixel_avg_variance16x8,
993 vp9_sad16x8x3, vp9_sad16x8x8, vp9_sad16x8x4d)
995 BFP(BLOCK_8X16, vp9_sad8x16, vp9_sad8x16_avg,
996 vp9_variance8x16, vp9_sub_pixel_variance8x16,
997 vp9_sub_pixel_avg_variance8x16,
998 vp9_sad8x16x3, vp9_sad8x16x8, vp9_sad8x16x4d)
1000 BFP(BLOCK_8X8, vp9_sad8x8, vp9_sad8x8_avg,
1001 vp9_variance8x8, vp9_sub_pixel_variance8x8,
1002 vp9_sub_pixel_avg_variance8x8,
1003 vp9_sad8x8x3, vp9_sad8x8x8, vp9_sad8x8x4d)
1005 BFP(BLOCK_8X4, vp9_sad8x4, vp9_sad8x4_avg,
1006 vp9_variance8x4, vp9_sub_pixel_variance8x4,
1007 vp9_sub_pixel_avg_variance8x4, NULL, vp9_sad8x4x8, vp9_sad8x4x4d)
1009 BFP(BLOCK_4X8, vp9_sad4x8, vp9_sad4x8_avg,
1010 vp9_variance4x8, vp9_sub_pixel_variance4x8,
1011 vp9_sub_pixel_avg_variance4x8, NULL, vp9_sad4x8x8, vp9_sad4x8x4d)
1013 BFP(BLOCK_4X4, vp9_sad4x4, vp9_sad4x4_avg,
1014 vp9_variance4x4, vp9_sub_pixel_variance4x4,
1015 vp9_sub_pixel_avg_variance4x4,
1016 vp9_sad4x4x3, vp9_sad4x4x8, vp9_sad4x4x4d)
1018 cpi->full_search_sad = vp9_full_search_sad;
1019 cpi->diamond_search_sad = vp9_diamond_search_sad;
1020 cpi->refining_search_sad = vp9_refining_search_sad;
1022 /* vp9_init_quantizer() is first called here. Add check in
1023 * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
1024 * called later when needed. This will avoid unnecessary calls of
1025 * vp9_init_quantizer() for every frame.
1027 vp9_init_quantizer(cpi);
1029 vp9_loop_filter_init(cm);
1031 cm->error.setjmp = 0;
1036 void vp9_remove_compressor(VP9_COMP *cpi) {
1042 if (cpi && (cpi->common.current_video_frame > 0)) {
1043 #if CONFIG_INTERNAL_STATS
1045 vp9_clear_system_state();
1047 // printf("\n8x8-4x4:%d-%d\n", cpi->t8x8_count, cpi->t4x4_count);
1048 if (cpi->pass != 1) {
1049 FILE *f = fopen("opsnr.stt", "a");
1050 double time_encoded = (cpi->last_end_time_stamp_seen
1051 - cpi->first_time_stamp_ever) / 10000000.000;
1052 double total_encode_time = (cpi->time_receive_data +
1053 cpi->time_compress_data) / 1000.000;
1054 double dr = (double)cpi->bytes * (double) 8 / (double)1000
1057 if (cpi->b_calculate_psnr) {
1058 const double total_psnr =
1059 vpx_sse_to_psnr((double)cpi->total_samples, 255.0,
1060 (double)cpi->total_sq_error);
1061 const double totalp_psnr =
1062 vpx_sse_to_psnr((double)cpi->totalp_samples, 255.0,
1063 (double)cpi->totalp_sq_error);
1064 const double total_ssim = 100 * pow(cpi->summed_quality /
1065 cpi->summed_weights, 8.0);
1066 const double totalp_ssim = 100 * pow(cpi->summedp_quality /
1067 cpi->summedp_weights, 8.0);
1069 fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
1070 "VPXSSIM\tVPSSIMP\t Time(ms)\n");
1071 fprintf(f, "%7.2f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%8.0f\n",
1072 dr, cpi->total / cpi->count, total_psnr,
1073 cpi->totalp / cpi->count, totalp_psnr, total_ssim, totalp_ssim,
1077 if (cpi->b_calculate_ssimg) {
1078 fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t Time(ms)\n");
1079 fprintf(f, "%7.2f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
1080 cpi->total_ssimg_y / cpi->count,
1081 cpi->total_ssimg_u / cpi->count,
1082 cpi->total_ssimg_v / cpi->count,
1083 cpi->total_ssimg_all / cpi->count, total_encode_time);
1093 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
1094 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
1095 printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
1096 cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
1097 cpi->time_compress_data / 1000,
1098 (cpi->time_receive_data + cpi->time_compress_data) / 1000);
1103 #if CONFIG_DENOISING
1104 vp9_denoiser_free(&(cpi->denoiser));
1107 dealloc_compressor_data(cpi);
1110 for (i = 0; i < sizeof(cpi->mbgraph_stats) /
1111 sizeof(cpi->mbgraph_stats[0]); ++i) {
1112 vpx_free(cpi->mbgraph_stats[i].mb_stats);
1115 vp9_remove_common(&cpi->common);
1118 #ifdef OUTPUT_YUV_DENOISED
1119 fclose(yuv_denoised_file);
1121 #ifdef OUTPUT_YUV_SRC
1124 #ifdef OUTPUT_YUV_REC
1125 fclose(yuv_rec_file);
1141 static int64_t get_sse(const uint8_t *a, int a_stride,
1142 const uint8_t *b, int b_stride,
1143 int width, int height) {
1144 const int dw = width % 16;
1145 const int dh = height % 16;
1146 int64_t total_sse = 0;
1147 unsigned int sse = 0;
1152 variance(&a[width - dw], a_stride, &b[width - dw], b_stride,
1153 dw, height, &sse, &sum);
1158 variance(&a[(height - dh) * a_stride], a_stride,
1159 &b[(height - dh) * b_stride], b_stride,
1160 width - dw, dh, &sse, &sum);
1164 for (y = 0; y < height / 16; ++y) {
1165 const uint8_t *pa = a;
1166 const uint8_t *pb = b;
1167 for (x = 0; x < width / 16; ++x) {
1168 vp9_mse16x16(pa, a_stride, pb, b_stride, &sse);
1183 double psnr[4]; // total/y/u/v
1184 uint64_t sse[4]; // total/y/u/v
1185 uint32_t samples[4]; // total/y/u/v
1188 static void calc_psnr(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b,
1190 const int widths[3] = {a->y_width, a->uv_width, a->uv_width };
1191 const int heights[3] = {a->y_height, a->uv_height, a->uv_height};
1192 const uint8_t *a_planes[3] = {a->y_buffer, a->u_buffer, a->v_buffer };
1193 const int a_strides[3] = {a->y_stride, a->uv_stride, a->uv_stride};
1194 const uint8_t *b_planes[3] = {b->y_buffer, b->u_buffer, b->v_buffer };
1195 const int b_strides[3] = {b->y_stride, b->uv_stride, b->uv_stride};
1197 uint64_t total_sse = 0;
1198 uint32_t total_samples = 0;
1200 for (i = 0; i < 3; ++i) {
1201 const int w = widths[i];
1202 const int h = heights[i];
1203 const uint32_t samples = w * h;
1204 const uint64_t sse = get_sse(a_planes[i], a_strides[i],
1205 b_planes[i], b_strides[i],
1207 psnr->sse[1 + i] = sse;
1208 psnr->samples[1 + i] = samples;
1209 psnr->psnr[1 + i] = vpx_sse_to_psnr(samples, 255.0, (double)sse);
1212 total_samples += samples;
1215 psnr->sse[0] = total_sse;
1216 psnr->samples[0] = total_samples;
1217 psnr->psnr[0] = vpx_sse_to_psnr((double)total_samples, 255.0,
1221 static void generate_psnr_packet(VP9_COMP *cpi) {
1222 struct vpx_codec_cx_pkt pkt;
1225 calc_psnr(cpi->Source, cpi->common.frame_to_show, &psnr);
1226 for (i = 0; i < 4; ++i) {
1227 pkt.data.psnr.samples[i] = psnr.samples[i];
1228 pkt.data.psnr.sse[i] = psnr.sse[i];
1229 pkt.data.psnr.psnr[i] = psnr.psnr[i];
1231 pkt.kind = VPX_CODEC_PSNR_PKT;
1232 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
1235 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags) {
1236 if (ref_frame_flags > 7)
1239 cpi->ref_frame_flags = ref_frame_flags;
1243 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags) {
1244 cpi->ext_refresh_golden_frame = (ref_frame_flags & VP9_GOLD_FLAG) != 0;
1245 cpi->ext_refresh_alt_ref_frame = (ref_frame_flags & VP9_ALT_FLAG) != 0;
1246 cpi->ext_refresh_last_frame = (ref_frame_flags & VP9_LAST_FLAG) != 0;
1247 cpi->ext_refresh_frame_flags_pending = 1;
1250 static YV12_BUFFER_CONFIG *get_vp9_ref_frame_buffer(VP9_COMP *cpi,
1251 VP9_REFFRAME ref_frame_flag) {
1252 MV_REFERENCE_FRAME ref_frame = NONE;
1253 if (ref_frame_flag == VP9_LAST_FLAG)
1254 ref_frame = LAST_FRAME;
1255 else if (ref_frame_flag == VP9_GOLD_FLAG)
1256 ref_frame = GOLDEN_FRAME;
1257 else if (ref_frame_flag == VP9_ALT_FLAG)
1258 ref_frame = ALTREF_FRAME;
1260 return ref_frame == NONE ? NULL : get_ref_frame_buffer(cpi, ref_frame);
1263 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
1264 YV12_BUFFER_CONFIG *sd) {
1265 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
1267 vp8_yv12_copy_frame(cfg, sd);
1274 int vp9_get_reference_enc(VP9_COMP *cpi, int index, YV12_BUFFER_CONFIG **fb) {
1275 VP9_COMMON *cm = &cpi->common;
1277 if (index < 0 || index >= REF_FRAMES)
1280 *fb = &cm->frame_bufs[cm->ref_frame_map[index]].buf;
1284 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
1285 YV12_BUFFER_CONFIG *sd) {
1286 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
1288 vp8_yv12_copy_frame(sd, cfg);
1295 int vp9_update_entropy(VP9_COMP * cpi, int update) {
1296 cpi->ext_refresh_frame_context = update;
1297 cpi->ext_refresh_frame_context_pending = 1;
1302 #if defined(OUTPUT_YUV_SRC) || defined(OUTPUT_YUV_DENOISED)
1303 void vp9_write_yuv_frame(YV12_BUFFER_CONFIG *s, FILE *f) {
1304 uint8_t *src = s->y_buffer;
1305 int h = s->y_height;
1308 fwrite(src, s->y_width, 1, f);
1316 fwrite(src, s->uv_width, 1, f);
1317 src += s->uv_stride;
1324 fwrite(src, s->uv_width, 1, f);
1325 src += s->uv_stride;
1330 #ifdef OUTPUT_YUV_REC
1331 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
1332 YV12_BUFFER_CONFIG *s = cm->frame_to_show;
1333 uint8_t *src = s->y_buffer;
1337 fwrite(src, s->y_width, 1, yuv_rec_file);
1345 fwrite(src, s->uv_width, 1, yuv_rec_file);
1346 src += s->uv_stride;
1353 fwrite(src, s->uv_width, 1, yuv_rec_file);
1354 src += s->uv_stride;
1358 if (s->alpha_buffer) {
1359 src = s->alpha_buffer;
1360 h = s->alpha_height;
1362 fwrite(src, s->alpha_width, 1, yuv_rec_file);
1363 src += s->alpha_stride;
1368 fflush(yuv_rec_file);
1372 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
1373 YV12_BUFFER_CONFIG *dst) {
1374 // TODO(dkovalev): replace YV12_BUFFER_CONFIG with vpx_image_t
1376 const uint8_t *const srcs[4] = {src->y_buffer, src->u_buffer, src->v_buffer,
1378 const int src_strides[4] = {src->y_stride, src->uv_stride, src->uv_stride,
1380 const int src_widths[4] = {src->y_crop_width, src->uv_crop_width,
1381 src->uv_crop_width, src->y_crop_width};
1382 const int src_heights[4] = {src->y_crop_height, src->uv_crop_height,
1383 src->uv_crop_height, src->y_crop_height};
1384 uint8_t *const dsts[4] = {dst->y_buffer, dst->u_buffer, dst->v_buffer,
1386 const int dst_strides[4] = {dst->y_stride, dst->uv_stride, dst->uv_stride,
1388 const int dst_widths[4] = {dst->y_crop_width, dst->uv_crop_width,
1389 dst->uv_crop_width, dst->y_crop_width};
1390 const int dst_heights[4] = {dst->y_crop_height, dst->uv_crop_height,
1391 dst->uv_crop_height, dst->y_crop_height};
1393 for (i = 0; i < MAX_MB_PLANE; ++i)
1394 vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
1395 dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
1397 // TODO(hkuang): Call C version explicitly
1398 // as neon version only expand border size 32.
1399 vp8_yv12_extend_frame_borders_c(dst);
1402 static void scale_and_extend_frame(const YV12_BUFFER_CONFIG *src,
1403 YV12_BUFFER_CONFIG *dst) {
1404 const int src_w = src->y_crop_width;
1405 const int src_h = src->y_crop_height;
1406 const int dst_w = dst->y_crop_width;
1407 const int dst_h = dst->y_crop_height;
1408 const uint8_t *const srcs[4] = {src->y_buffer, src->u_buffer, src->v_buffer,
1410 const int src_strides[4] = {src->y_stride, src->uv_stride, src->uv_stride,
1412 uint8_t *const dsts[4] = {dst->y_buffer, dst->u_buffer, dst->v_buffer,
1414 const int dst_strides[4] = {dst->y_stride, dst->uv_stride, dst->uv_stride,
1416 const InterpKernel *const kernel = vp9_get_interp_kernel(EIGHTTAP);
1419 for (y = 0; y < dst_h; y += 16) {
1420 for (x = 0; x < dst_w; x += 16) {
1421 for (i = 0; i < MAX_MB_PLANE; ++i) {
1422 const int factor = (i == 0 || i == 3 ? 1 : 2);
1423 const int x_q4 = x * (16 / factor) * src_w / dst_w;
1424 const int y_q4 = y * (16 / factor) * src_h / dst_h;
1425 const int src_stride = src_strides[i];
1426 const int dst_stride = dst_strides[i];
1427 const uint8_t *src_ptr = srcs[i] + (y / factor) * src_h / dst_h *
1428 src_stride + (x / factor) * src_w / dst_w;
1429 uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
1431 vp9_convolve8(src_ptr, src_stride, dst_ptr, dst_stride,
1432 kernel[x_q4 & 0xf], 16 * src_w / dst_w,
1433 kernel[y_q4 & 0xf], 16 * src_h / dst_h,
1434 16 / factor, 16 / factor);
1439 // TODO(hkuang): Call C version explicitly
1440 // as neon version only expand border size 32.
1441 vp8_yv12_extend_frame_borders_c(dst);
1444 #define WRITE_RECON_BUFFER 0
1445 #if WRITE_RECON_BUFFER
1446 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame) {
1451 snprintf(filename, sizeof(filename), "cx\\y%04d.raw", this_frame);
1452 yframe = fopen(filename, "wb");
1454 for (i = 0; i < frame->y_height; i++)
1455 fwrite(frame->y_buffer + i * frame->y_stride,
1456 frame->y_width, 1, yframe);
1459 snprintf(filename, sizeof(filename), "cx\\u%04d.raw", this_frame);
1460 yframe = fopen(filename, "wb");
1462 for (i = 0; i < frame->uv_height; i++)
1463 fwrite(frame->u_buffer + i * frame->uv_stride,
1464 frame->uv_width, 1, yframe);
1467 snprintf(filename, sizeof(filename), "cx\\v%04d.raw", this_frame);
1468 yframe = fopen(filename, "wb");
1470 for (i = 0; i < frame->uv_height; i++)
1471 fwrite(frame->v_buffer + i * frame->uv_stride,
1472 frame->uv_width, 1, yframe);
1478 // Function to test for conditions that indicate we should loop
1479 // back and recode a frame.
1480 static int recode_loop_test(const VP9_COMP *cpi,
1481 int high_limit, int low_limit,
1482 int q, int maxq, int minq) {
1483 const VP9_COMMON *const cm = &cpi->common;
1484 const RATE_CONTROL *const rc = &cpi->rc;
1485 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1486 int force_recode = 0;
1488 // Special case trap if maximum allowed frame size exceeded.
1489 if (rc->projected_frame_size > rc->max_frame_bandwidth) {
1492 // Is frame recode allowed.
1493 // Yes if either recode mode 1 is selected or mode 2 is selected
1494 // and the frame is a key frame, golden frame or alt_ref_frame
1495 } else if ((cpi->sf.recode_loop == ALLOW_RECODE) ||
1496 ((cpi->sf.recode_loop == ALLOW_RECODE_KFARFGF) &&
1497 (cm->frame_type == KEY_FRAME ||
1498 cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
1499 // General over and under shoot tests
1500 if ((rc->projected_frame_size > high_limit && q < maxq) ||
1501 (rc->projected_frame_size < low_limit && q > minq)) {
1503 } else if (cpi->oxcf.rc_mode == VPX_CQ) {
1504 // Deal with frame undershoot and whether or not we are
1505 // below the automatically set cq level.
1506 if (q > oxcf->cq_level &&
1507 rc->projected_frame_size < ((rc->this_frame_target * 7) >> 3)) {
1512 return force_recode;
1515 void vp9_update_reference_frames(VP9_COMP *cpi) {
1516 VP9_COMMON * const cm = &cpi->common;
1518 // At this point the new frame has been encoded.
1519 // If any buffer copy / swapping is signaled it should be done here.
1520 if (cm->frame_type == KEY_FRAME) {
1521 ref_cnt_fb(cm->frame_bufs,
1522 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
1523 ref_cnt_fb(cm->frame_bufs,
1524 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
1526 #if CONFIG_MULTIPLE_ARF
1527 else if (!cpi->multi_arf_enabled && cpi->refresh_golden_frame &&
1528 !cpi->refresh_alt_ref_frame) {
1530 else if (cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame &&
1533 /* Preserve the previously existing golden frame and update the frame in
1534 * the alt ref slot instead. This is highly specific to the current use of
1535 * alt-ref as a forward reference, and this needs to be generalized as
1536 * other uses are implemented (like RTC/temporal scaling)
1538 * The update to the buffer in the alt ref slot was signaled in
1539 * vp9_pack_bitstream(), now swap the buffer pointers so that it's treated
1540 * as the golden frame next time.
1544 ref_cnt_fb(cm->frame_bufs,
1545 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
1547 tmp = cpi->alt_fb_idx;
1548 cpi->alt_fb_idx = cpi->gld_fb_idx;
1549 cpi->gld_fb_idx = tmp;
1550 } else { /* For non key/golden frames */
1551 if (cpi->refresh_alt_ref_frame) {
1552 int arf_idx = cpi->alt_fb_idx;
1553 #if CONFIG_MULTIPLE_ARF
1554 if (cpi->multi_arf_enabled) {
1555 arf_idx = cpi->arf_buffer_idx[cpi->sequence_number + 1];
1558 ref_cnt_fb(cm->frame_bufs,
1559 &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
1562 if (cpi->refresh_golden_frame) {
1563 ref_cnt_fb(cm->frame_bufs,
1564 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
1568 if (cpi->refresh_last_frame) {
1569 ref_cnt_fb(cm->frame_bufs,
1570 &cm->ref_frame_map[cpi->lst_fb_idx], cm->new_fb_idx);
1572 #if CONFIG_DENOISING
1573 vp9_denoiser_update_frame_info(&cpi->denoiser,
1575 cpi->common.frame_type,
1576 cpi->refresh_alt_ref_frame,
1577 cpi->refresh_golden_frame,
1578 cpi->refresh_last_frame);
1582 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
1583 MACROBLOCKD *xd = &cpi->mb.e_mbd;
1584 struct loopfilter *lf = &cm->lf;
1586 lf->filter_level = 0;
1588 struct vpx_usec_timer timer;
1590 vp9_clear_system_state();
1592 vpx_usec_timer_start(&timer);
1594 vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.lpf_pick);
1596 vpx_usec_timer_mark(&timer);
1597 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
1600 if (lf->filter_level > 0) {
1601 vp9_loop_filter_frame(cm->frame_to_show, cm, xd, lf->filter_level, 0, 0);
1604 vp9_extend_frame_inner_borders(cm->frame_to_show);
1607 void vp9_scale_references(VP9_COMP *cpi) {
1608 VP9_COMMON *cm = &cpi->common;
1609 MV_REFERENCE_FRAME ref_frame;
1611 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
1612 const int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, ref_frame)];
1613 const YV12_BUFFER_CONFIG *const ref = &cm->frame_bufs[idx].buf;
1615 if (ref->y_crop_width != cm->width ||
1616 ref->y_crop_height != cm->height) {
1617 const int new_fb = get_free_fb(cm);
1618 vp9_realloc_frame_buffer(&cm->frame_bufs[new_fb].buf,
1619 cm->width, cm->height,
1620 cm->subsampling_x, cm->subsampling_y,
1621 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL);
1622 scale_and_extend_frame(ref, &cm->frame_bufs[new_fb].buf);
1623 cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
1625 cpi->scaled_ref_idx[ref_frame - 1] = idx;
1626 cm->frame_bufs[idx].ref_count++;
1631 static void release_scaled_references(VP9_COMP *cpi) {
1632 VP9_COMMON *cm = &cpi->common;
1635 for (i = 0; i < 3; i++)
1636 cm->frame_bufs[cpi->scaled_ref_idx[i]].ref_count--;
1639 static void full_to_model_count(unsigned int *model_count,
1640 unsigned int *full_count) {
1642 model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
1643 model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
1644 model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
1645 for (n = THREE_TOKEN; n < EOB_TOKEN; ++n)
1646 model_count[TWO_TOKEN] += full_count[n];
1647 model_count[EOB_MODEL_TOKEN] = full_count[EOB_TOKEN];
1650 static void full_to_model_counts(vp9_coeff_count_model *model_count,
1651 vp9_coeff_count *full_count) {
1654 for (i = 0; i < PLANE_TYPES; ++i)
1655 for (j = 0; j < REF_TYPES; ++j)
1656 for (k = 0; k < COEF_BANDS; ++k)
1657 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
1658 full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
1661 #if 0 && CONFIG_INTERNAL_STATS
1662 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
1663 VP9_COMMON *const cm = &cpi->common;
1664 FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
1667 vp9_clear_system_state();
1669 recon_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
1671 if (cpi->twopass.total_left_stats.coded_error != 0.0)
1672 fprintf(f, "%10u %10d %10d %10d %10d"
1673 "%10"PRId64" %10"PRId64" %10"PRId64" %10"PRId64" %10d "
1674 "%7.2lf %7.2lf %7.2lf %7.2lf %7.2lf"
1675 "%6d %6d %5d %5d %5d "
1676 "%10"PRId64" %10.3lf"
1677 "%10lf %8u %10d %10d %10d\n",
1678 cpi->common.current_video_frame, cpi->rc.this_frame_target,
1679 cpi->rc.projected_frame_size,
1680 cpi->rc.projected_frame_size / cpi->common.MBs,
1681 (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
1682 cpi->rc.vbr_bits_off_target,
1683 cpi->rc.total_target_vs_actual,
1684 (cpi->rc.starting_buffer_level - cpi->rc.bits_off_target),
1685 cpi->rc.total_actual_bits, cm->base_qindex,
1686 vp9_convert_qindex_to_q(cm->base_qindex),
1687 (double)vp9_dc_quant(cm->base_qindex, 0) / 4.0,
1689 vp9_convert_qindex_to_q(cpi->rc.ni_av_qi),
1690 vp9_convert_qindex_to_q(cpi->oxcf.cq_level),
1691 cpi->refresh_last_frame, cpi->refresh_golden_frame,
1692 cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
1693 cpi->twopass.bits_left,
1694 cpi->twopass.total_left_stats.coded_error,
1695 cpi->twopass.bits_left /
1696 (1 + cpi->twopass.total_left_stats.coded_error),
1697 cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
1698 cpi->twopass.kf_zeromotion_pct);
1703 FILE *const fmodes = fopen("Modes.stt", "a");
1706 fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
1707 cm->frame_type, cpi->refresh_golden_frame,
1708 cpi->refresh_alt_ref_frame);
1710 for (i = 0; i < MAX_MODES; ++i)
1711 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
1713 fprintf(fmodes, "\n");
1720 static void encode_without_recode_loop(VP9_COMP *cpi,
1722 VP9_COMMON *const cm = &cpi->common;
1723 vp9_clear_system_state();
1724 vp9_set_quantizer(cm, q);
1726 // Variance adaptive and in frame q adjustment experiments are mutually
1728 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
1729 vp9_vaq_frame_setup(cpi);
1730 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1731 vp9_setup_in_frame_q_adj(cpi);
1732 } else if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
1733 vp9_cyclic_refresh_setup(cpi);
1735 // transform / motion compensation build reconstruction frame
1736 vp9_encode_frame(cpi);
1738 // Update the skip mb flag probabilities based on the distribution
1739 // seen in the last encoder iteration.
1740 // update_base_skip_probs(cpi);
1741 vp9_clear_system_state();
1744 static void encode_with_recode_loop(VP9_COMP *cpi,
1750 VP9_COMMON *const cm = &cpi->common;
1751 RATE_CONTROL *const rc = &cpi->rc;
1754 int overshoot_seen = 0;
1755 int undershoot_seen = 0;
1756 int q_low = bottom_index, q_high = top_index;
1757 int frame_over_shoot_limit;
1758 int frame_under_shoot_limit;
1760 // Decide frame size bounds
1761 vp9_rc_compute_frame_size_bounds(cpi, rc->this_frame_target,
1762 &frame_under_shoot_limit,
1763 &frame_over_shoot_limit);
1766 vp9_clear_system_state();
1768 vp9_set_quantizer(cm, q);
1770 if (loop_count == 0)
1773 // Variance adaptive and in frame q adjustment experiments are mutually
1775 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
1776 vp9_vaq_frame_setup(cpi);
1777 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1778 vp9_setup_in_frame_q_adj(cpi);
1781 // transform / motion compensation build reconstruction frame
1782 vp9_encode_frame(cpi);
1784 // Update the skip mb flag probabilities based on the distribution
1785 // seen in the last encoder iteration.
1786 // update_base_skip_probs(cpi);
1788 vp9_clear_system_state();
1790 // Dummy pack of the bitstream using up to date stats to get an
1791 // accurate estimate of output frame size to determine if we need
1793 if (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF) {
1794 save_coding_context(cpi);
1795 cpi->dummy_packing = 1;
1796 if (!cpi->sf.use_nonrd_pick_mode)
1797 vp9_pack_bitstream(cpi, dest, size);
1799 rc->projected_frame_size = (int)(*size) << 3;
1800 restore_coding_context(cpi);
1802 if (frame_over_shoot_limit == 0)
1803 frame_over_shoot_limit = 1;
1806 if (cpi->oxcf.rc_mode == VPX_Q) {
1809 if ((cm->frame_type == KEY_FRAME) &&
1810 rc->this_key_frame_forced &&
1811 (rc->projected_frame_size < rc->max_frame_bandwidth)) {
1813 int kf_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
1815 int high_err_target = cpi->ambient_err;
1816 int low_err_target = cpi->ambient_err >> 1;
1818 // Prevent possible divide by zero error below for perfect KF
1821 // The key frame is not good enough or we can afford
1822 // to make it better without undue risk of popping.
1823 if ((kf_err > high_err_target &&
1824 rc->projected_frame_size <= frame_over_shoot_limit) ||
1825 (kf_err > low_err_target &&
1826 rc->projected_frame_size <= frame_under_shoot_limit)) {
1828 q_high = q > q_low ? q - 1 : q_low;
1831 q = (q * high_err_target) / kf_err;
1832 q = MIN(q, (q_high + q_low) >> 1);
1833 } else if (kf_err < low_err_target &&
1834 rc->projected_frame_size >= frame_under_shoot_limit) {
1835 // The key frame is much better than the previous frame
1837 q_low = q < q_high ? q + 1 : q_high;
1840 q = (q * low_err_target) / kf_err;
1841 q = MIN(q, (q_high + q_low + 1) >> 1);
1844 // Clamp Q to upper and lower limits:
1845 q = clamp(q, q_low, q_high);
1848 } else if (recode_loop_test(
1849 cpi, frame_over_shoot_limit, frame_under_shoot_limit,
1850 q, MAX(q_high, top_index), bottom_index)) {
1851 // Is the projected frame size out of range and are we allowed
1852 // to attempt to recode.
1856 // Frame size out of permitted range:
1857 // Update correction factor & compute new Q to try...
1859 // Frame is too large
1860 if (rc->projected_frame_size > rc->this_frame_target) {
1861 // Special case if the projected size is > the max allowed.
1862 if (rc->projected_frame_size >= rc->max_frame_bandwidth)
1863 q_high = rc->worst_quality;
1865 // Raise Qlow as to at least the current value
1866 q_low = q < q_high ? q + 1 : q_high;
1868 if (undershoot_seen || loop_count > 1) {
1869 // Update rate_correction_factor unless
1870 vp9_rc_update_rate_correction_factors(cpi, 1);
1872 q = (q_high + q_low + 1) / 2;
1874 // Update rate_correction_factor unless
1875 vp9_rc_update_rate_correction_factors(cpi, 0);
1877 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1878 bottom_index, MAX(q_high, top_index));
1880 while (q < q_low && retries < 10) {
1881 vp9_rc_update_rate_correction_factors(cpi, 0);
1882 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1883 bottom_index, MAX(q_high, top_index));
1890 // Frame is too small
1891 q_high = q > q_low ? q - 1 : q_low;
1893 if (overshoot_seen || loop_count > 1) {
1894 vp9_rc_update_rate_correction_factors(cpi, 1);
1895 q = (q_high + q_low) / 2;
1897 vp9_rc_update_rate_correction_factors(cpi, 0);
1898 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1899 bottom_index, top_index);
1900 // Special case reset for qlow for constrained quality.
1901 // This should only trigger where there is very substantial
1902 // undershoot on a frame and the auto cq level is above
1903 // the user passsed in value.
1904 if (cpi->oxcf.rc_mode == VPX_CQ &&
1909 while (q > q_high && retries < 10) {
1910 vp9_rc_update_rate_correction_factors(cpi, 0);
1911 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1912 bottom_index, top_index);
1917 undershoot_seen = 1;
1920 // Clamp Q to upper and lower limits:
1921 q = clamp(q, q_low, q_high);
1929 // Special case for overlay frame.
1930 if (rc->is_src_frame_alt_ref &&
1931 rc->projected_frame_size < rc->max_frame_bandwidth)
1937 #if CONFIG_INTERNAL_STATS
1938 cpi->tot_recode_hits++;
1944 static void get_ref_frame_flags(VP9_COMP *cpi) {
1945 if (cpi->refresh_last_frame & cpi->refresh_golden_frame)
1946 cpi->gold_is_last = 1;
1947 else if (cpi->refresh_last_frame ^ cpi->refresh_golden_frame)
1948 cpi->gold_is_last = 0;
1950 if (cpi->refresh_last_frame & cpi->refresh_alt_ref_frame)
1951 cpi->alt_is_last = 1;
1952 else if (cpi->refresh_last_frame ^ cpi->refresh_alt_ref_frame)
1953 cpi->alt_is_last = 0;
1955 if (cpi->refresh_alt_ref_frame & cpi->refresh_golden_frame)
1956 cpi->gold_is_alt = 1;
1957 else if (cpi->refresh_alt_ref_frame ^ cpi->refresh_golden_frame)
1958 cpi->gold_is_alt = 0;
1960 cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
1962 if (cpi->gold_is_last)
1963 cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
1965 if (cpi->rc.frames_till_gf_update_due == INT_MAX)
1966 cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
1968 if (cpi->alt_is_last)
1969 cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
1971 if (cpi->gold_is_alt)
1972 cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
1975 static void set_ext_overrides(VP9_COMP *cpi) {
1976 // Overrides the defaults with the externally supplied values with
1977 // vp9_update_reference() and vp9_update_entropy() calls
1978 // Note: The overrides are valid only for the next frame passed
1979 // to encode_frame_to_data_rate() function
1980 if (cpi->ext_refresh_frame_context_pending) {
1981 cpi->common.refresh_frame_context = cpi->ext_refresh_frame_context;
1982 cpi->ext_refresh_frame_context_pending = 0;
1984 if (cpi->ext_refresh_frame_flags_pending) {
1985 cpi->refresh_last_frame = cpi->ext_refresh_last_frame;
1986 cpi->refresh_golden_frame = cpi->ext_refresh_golden_frame;
1987 cpi->refresh_alt_ref_frame = cpi->ext_refresh_alt_ref_frame;
1988 cpi->ext_refresh_frame_flags_pending = 0;
1992 YV12_BUFFER_CONFIG *vp9_scale_if_required(VP9_COMMON *cm,
1993 YV12_BUFFER_CONFIG *unscaled,
1994 YV12_BUFFER_CONFIG *scaled) {
1995 if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
1996 cm->mi_rows * MI_SIZE != unscaled->y_height) {
1997 scale_and_extend_frame_nonnormative(unscaled, scaled);
2004 static void encode_frame_to_data_rate(VP9_COMP *cpi,
2007 unsigned int *frame_flags) {
2008 VP9_COMMON *const cm = &cpi->common;
2014 const SPEED_FEATURES *const sf = &cpi->sf;
2015 const unsigned int max_mv_def = MIN(cm->width, cm->height);
2016 struct segmentation *const seg = &cm->seg;
2017 set_ext_overrides(cpi);
2019 cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
2020 &cpi->scaled_source);
2022 if (cpi->unscaled_last_source != NULL)
2023 cpi->Last_Source = vp9_scale_if_required(cm, cpi->unscaled_last_source,
2024 &cpi->scaled_last_source);
2026 vp9_scale_references(cpi);
2028 vp9_clear_system_state();
2030 // Enable or disable mode based tweaking of the zbin.
2031 // For 2 pass only used where GF/ARF prediction quality
2032 // is above a threshold.
2033 cpi->zbin_mode_boost = 0;
2034 cpi->zbin_mode_boost_enabled = 0;
2036 // Current default encoder behavior for the altref sign bias.
2037 cm->ref_frame_sign_bias[ALTREF_FRAME] = cpi->rc.source_alt_ref_active;
2039 // Set default state for segment based loop filter update flags.
2040 cm->lf.mode_ref_delta_update = 0;
2042 // Initialize cpi->mv_step_param to default based on max resolution.
2043 cpi->mv_step_param = vp9_init_search_range(sf, max_mv_def);
2044 // Initialize cpi->max_mv_magnitude and cpi->mv_step_param if appropriate.
2045 if (sf->mv.auto_mv_step_size) {
2046 if (frame_is_intra_only(cm)) {
2047 // Initialize max_mv_magnitude for use in the first INTER frame
2048 // after a key/intra-only frame.
2049 cpi->max_mv_magnitude = max_mv_def;
2052 // Allow mv_steps to correspond to twice the max mv magnitude found
2053 // in the previous frame, capped by the default max_mv_magnitude based
2055 cpi->mv_step_param = vp9_init_search_range(sf, MIN(max_mv_def, 2 *
2056 cpi->max_mv_magnitude));
2057 cpi->max_mv_magnitude = 0;
2061 // Set various flags etc to special state if it is a key frame.
2062 if (frame_is_intra_only(cm)) {
2063 // Reset the loop filter deltas and segmentation map.
2064 vp9_reset_segment_features(&cm->seg);
2066 // If segmentation is enabled force a map update for key frames.
2068 seg->update_map = 1;
2069 seg->update_data = 1;
2072 // The alternate reference frame cannot be active for a key frame.
2073 cpi->rc.source_alt_ref_active = 0;
2075 cm->error_resilient_mode = (cpi->oxcf.error_resilient_mode != 0);
2076 cm->frame_parallel_decoding_mode =
2077 (cpi->oxcf.frame_parallel_decoding_mode != 0);
2079 // By default, encoder assumes decoder can use prev_mi.
2080 cm->coding_use_prev_mi = 1;
2081 if (cm->error_resilient_mode) {
2082 cm->coding_use_prev_mi = 0;
2083 cm->frame_parallel_decoding_mode = 1;
2084 cm->reset_frame_context = 0;
2085 cm->refresh_frame_context = 0;
2086 } else if (cm->intra_only) {
2087 // Only reset the current context.
2088 cm->reset_frame_context = 2;
2092 // Configure experimental use of segmentation for enhanced coding of
2093 // static regions if indicated.
2094 // Only allowed in second pass of two pass (as requires lagged coding)
2095 // and if the relevant speed feature flag is set.
2096 if (cpi->pass == 2 && cpi->sf.static_segmentation)
2097 configure_static_seg_features(cpi);
2099 // For 1 pass CBR, check if we are dropping this frame.
2100 // Never drop on key frame.
2101 if (cpi->pass == 0 &&
2102 cpi->oxcf.rc_mode == VPX_CBR &&
2103 cm->frame_type != KEY_FRAME) {
2104 if (vp9_rc_drop_frame(cpi)) {
2105 vp9_rc_postencode_update_drop_frame(cpi);
2106 ++cm->current_video_frame;
2111 vp9_clear_system_state();
2113 #if CONFIG_VP9_POSTPROC
2114 if (cpi->oxcf.noise_sensitivity > 0) {
2116 switch (cpi->oxcf.noise_sensitivity) {
2134 vp9_denoise(cpi->Source, cpi->Source, l);
2138 #ifdef OUTPUT_YUV_DENOISED
2139 vp9_write_yuv_frame(&cpi->denoiser.running_avg_y[INTRA_FRAME],
2142 #ifdef OUTPUT_YUV_SRC
2143 vp9_write_yuv_frame(cpi->Source, yuv_file);
2146 set_speed_features(cpi);
2148 // Decide q and q bounds.
2149 q = vp9_rc_pick_q_and_bounds(cpi, &bottom_index, &top_index);
2151 if (!frame_is_intra_only(cm)) {
2152 cm->interp_filter = DEFAULT_INTERP_FILTER;
2153 /* TODO: Decide this more intelligently */
2154 set_high_precision_mv(cpi, q < HIGH_PRECISION_MV_QTHRESH);
2157 if (cpi->sf.recode_loop == DISALLOW_RECODE) {
2158 encode_without_recode_loop(cpi, q);
2160 encode_with_recode_loop(cpi, size, dest, q, bottom_index, top_index);
2163 // Special case code to reduce pulsing when key frames are forced at a
2164 // fixed interval. Note the reconstruction error if it is the frame before
2165 // the force key frame
2166 if (cpi->rc.next_key_frame_forced && cpi->rc.frames_to_key == 1) {
2167 cpi->ambient_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2170 // If the encoder forced a KEY_FRAME decision
2171 if (cm->frame_type == KEY_FRAME)
2172 cpi->refresh_last_frame = 1;
2174 cm->frame_to_show = get_frame_new_buffer(cm);
2176 #if WRITE_RECON_BUFFER
2178 write_cx_frame_to_file(cm->frame_to_show,
2179 cm->current_video_frame);
2181 write_cx_frame_to_file(cm->frame_to_show,
2182 cm->current_video_frame + 1000);
2185 // Pick the loop filter level for the frame.
2186 loopfilter_frame(cpi, cm);
2188 #if WRITE_RECON_BUFFER
2190 write_cx_frame_to_file(cm->frame_to_show,
2191 cm->current_video_frame + 2000);
2193 write_cx_frame_to_file(cm->frame_to_show,
2194 cm->current_video_frame + 3000);
2197 // build the bitstream
2198 cpi->dummy_packing = 0;
2199 vp9_pack_bitstream(cpi, dest, size);
2201 if (cm->seg.update_map)
2202 update_reference_segmentation_map(cpi);
2204 release_scaled_references(cpi);
2205 vp9_update_reference_frames(cpi);
2207 for (t = TX_4X4; t <= TX_32X32; t++)
2208 full_to_model_counts(cm->counts.coef[t], cpi->coef_counts[t]);
2210 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode)
2211 vp9_adapt_coef_probs(cm);
2213 if (!frame_is_intra_only(cm)) {
2214 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2215 vp9_adapt_mode_probs(cm);
2216 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2220 if (cpi->refresh_golden_frame == 1)
2221 cpi->frame_flags |= FRAMEFLAGS_GOLDEN;
2223 cpi->frame_flags &= ~FRAMEFLAGS_GOLDEN;
2225 if (cpi->refresh_alt_ref_frame == 1)
2226 cpi->frame_flags |= FRAMEFLAGS_ALTREF;
2228 cpi->frame_flags &= ~FRAMEFLAGS_ALTREF;
2230 get_ref_frame_flags(cpi);
2232 cm->last_frame_type = cm->frame_type;
2233 vp9_rc_postencode_update(cpi, *size);
2236 output_frame_level_debug_stats(cpi);
2239 if (cm->frame_type == KEY_FRAME) {
2240 // Tell the caller that the frame was coded as a key frame
2241 *frame_flags = cpi->frame_flags | FRAMEFLAGS_KEY;
2243 #if CONFIG_MULTIPLE_ARF
2244 // Reset the sequence number.
2245 if (cpi->multi_arf_enabled) {
2246 cpi->sequence_number = 0;
2247 cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
2248 cpi->new_frame_coding_order_period = -1;
2252 *frame_flags = cpi->frame_flags & ~FRAMEFLAGS_KEY;
2254 #if CONFIG_MULTIPLE_ARF
2255 /* Increment position in the coded frame sequence. */
2256 if (cpi->multi_arf_enabled) {
2257 ++cpi->sequence_number;
2258 if (cpi->sequence_number >= cpi->frame_coding_order_period) {
2259 cpi->sequence_number = 0;
2260 cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
2261 cpi->new_frame_coding_order_period = -1;
2263 cpi->this_frame_weight = cpi->arf_weight[cpi->sequence_number];
2264 assert(cpi->this_frame_weight >= 0);
2269 // Clear the one shot update flags for segmentation map and mode/ref loop
2271 cm->seg.update_map = 0;
2272 cm->seg.update_data = 0;
2273 cm->lf.mode_ref_delta_update = 0;
2275 // keep track of the last coded dimensions
2276 cm->last_width = cm->width;
2277 cm->last_height = cm->height;
2279 // reset to normal state now that we are done.
2280 if (!cm->show_existing_frame)
2281 cm->last_show_frame = cm->show_frame;
2283 if (cm->show_frame) {
2284 vp9_swap_mi_and_prev_mi(cm);
2286 // Don't increment frame counters if this was an altref buffer
2287 // update not a real frame
2288 ++cm->current_video_frame;
2290 vp9_inc_frame_in_layer(&cpi->svc);
2294 static void SvcEncode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
2295 unsigned int *frame_flags) {
2296 vp9_rc_get_svc_params(cpi);
2297 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2300 static void Pass0Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
2301 unsigned int *frame_flags) {
2302 if (cpi->oxcf.rc_mode == VPX_CBR) {
2303 vp9_rc_get_one_pass_cbr_params(cpi);
2305 vp9_rc_get_one_pass_vbr_params(cpi);
2307 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2310 static void Pass2Encode(VP9_COMP *cpi, size_t *size,
2311 uint8_t *dest, unsigned int *frame_flags) {
2312 cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
2314 vp9_rc_get_second_pass_params(cpi);
2315 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2317 vp9_twopass_postencode_update(cpi);
2320 static void check_initial_width(VP9_COMP *cpi, int subsampling_x,
2321 int subsampling_y) {
2322 VP9_COMMON *const cm = &cpi->common;
2324 if (!cpi->initial_width) {
2325 cm->subsampling_x = subsampling_x;
2326 cm->subsampling_y = subsampling_y;
2327 alloc_raw_frame_buffers(cpi);
2328 cpi->initial_width = cm->width;
2329 cpi->initial_height = cm->height;
2334 int vp9_receive_raw_frame(VP9_COMP *cpi, unsigned int frame_flags,
2335 YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
2337 VP9_COMMON *cm = &cpi->common;
2338 struct vpx_usec_timer timer;
2340 const int subsampling_x = sd->uv_width < sd->y_width;
2341 const int subsampling_y = sd->uv_height < sd->y_height;
2343 check_initial_width(cpi, subsampling_x, subsampling_y);
2344 vpx_usec_timer_start(&timer);
2345 if (vp9_lookahead_push(cpi->lookahead,
2346 sd, time_stamp, end_time, frame_flags))
2348 vpx_usec_timer_mark(&timer);
2349 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
2351 if (cm->profile == PROFILE_0 && (subsampling_x != 1 || subsampling_y != 1)) {
2352 vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
2353 "Non-4:2:0 color space requires profile >= 1");
2361 static int frame_is_reference(const VP9_COMP *cpi) {
2362 const VP9_COMMON *cm = &cpi->common;
2364 return cm->frame_type == KEY_FRAME ||
2365 cpi->refresh_last_frame ||
2366 cpi->refresh_golden_frame ||
2367 cpi->refresh_alt_ref_frame ||
2368 cm->refresh_frame_context ||
2369 cm->lf.mode_ref_delta_update ||
2370 cm->seg.update_map ||
2371 cm->seg.update_data;
2374 #if CONFIG_MULTIPLE_ARF
2375 int is_next_frame_arf(VP9_COMP *cpi) {
2376 // Negative entry in frame_coding_order indicates an ARF at this position.
2377 return cpi->frame_coding_order[cpi->sequence_number + 1] < 0 ? 1 : 0;
2381 void adjust_frame_rate(VP9_COMP *cpi) {
2382 int64_t this_duration;
2385 if (cpi->source->ts_start == cpi->first_time_stamp_ever) {
2386 this_duration = cpi->source->ts_end - cpi->source->ts_start;
2389 int64_t last_duration = cpi->last_end_time_stamp_seen
2390 - cpi->last_time_stamp_seen;
2392 this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
2394 // do a step update if the duration changes by 10%
2396 step = (int)((this_duration - last_duration) * 10 / last_duration);
2399 if (this_duration) {
2401 vp9_new_framerate(cpi, 10000000.0 / this_duration);
2403 // Average this frame's rate into the last second's average
2404 // frame rate. If we haven't seen 1 second yet, then average
2405 // over the whole interval seen.
2406 const double interval = MIN((double)(cpi->source->ts_end
2407 - cpi->first_time_stamp_ever), 10000000.0);
2408 double avg_duration = 10000000.0 / cpi->oxcf.framerate;
2409 avg_duration *= (interval - avg_duration + this_duration);
2410 avg_duration /= interval;
2412 vp9_new_framerate(cpi, 10000000.0 / avg_duration);
2415 cpi->last_time_stamp_seen = cpi->source->ts_start;
2416 cpi->last_end_time_stamp_seen = cpi->source->ts_end;
2419 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
2420 size_t *size, uint8_t *dest,
2421 int64_t *time_stamp, int64_t *time_end, int flush) {
2422 VP9_COMMON *const cm = &cpi->common;
2423 MACROBLOCKD *const xd = &cpi->mb.e_mbd;
2424 RATE_CONTROL *const rc = &cpi->rc;
2425 struct vpx_usec_timer cmptimer;
2426 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
2427 MV_REFERENCE_FRAME ref_frame;
2432 if (cpi->svc.number_spatial_layers > 1 && cpi->pass == 2) {
2433 vp9_restore_layer_context(cpi);
2436 vpx_usec_timer_start(&cmptimer);
2439 cpi->last_source = NULL;
2441 set_high_precision_mv(cpi, ALTREF_HIGH_PRECISION_MV);
2444 cm->reset_frame_context = 0;
2445 cm->refresh_frame_context = 1;
2446 cpi->refresh_last_frame = 1;
2447 cpi->refresh_golden_frame = 0;
2448 cpi->refresh_alt_ref_frame = 0;
2450 // Should we code an alternate reference frame.
2451 if (is_altref_enabled(&cpi->oxcf) && rc->source_alt_ref_pending) {
2454 #if CONFIG_MULTIPLE_ARF
2455 assert(!cpi->multi_arf_enabled ||
2456 cpi->frame_coding_order[cpi->sequence_number] < 0);
2458 if (cpi->multi_arf_enabled && (cpi->pass == 2))
2459 frames_to_arf = (-cpi->frame_coding_order[cpi->sequence_number])
2460 - cpi->next_frame_in_order;
2463 frames_to_arf = rc->frames_till_gf_update_due;
2465 assert(frames_to_arf <= rc->frames_to_key);
2467 if ((cpi->source = vp9_lookahead_peek(cpi->lookahead, frames_to_arf))) {
2468 #if CONFIG_MULTIPLE_ARF
2469 cpi->alt_ref_source[cpi->arf_buffered] = cpi->source;
2471 cpi->alt_ref_source = cpi->source;
2474 if (cpi->oxcf.arnr_max_frames > 0) {
2475 // Produce the filtered ARF frame.
2476 // TODO(agrange) merge these two functions.
2477 vp9_configure_arnr_filter(cpi, frames_to_arf, rc->gfu_boost);
2478 vp9_temporal_filter_prepare(cpi, frames_to_arf);
2479 vp9_extend_frame_borders(&cpi->alt_ref_buffer);
2480 force_src_buffer = &cpi->alt_ref_buffer;
2484 cpi->refresh_alt_ref_frame = 1;
2485 cpi->refresh_golden_frame = 0;
2486 cpi->refresh_last_frame = 0;
2487 rc->is_src_frame_alt_ref = 0;
2489 #if CONFIG_MULTIPLE_ARF
2490 if (!cpi->multi_arf_enabled)
2492 rc->source_alt_ref_pending = 0;
2494 rc->source_alt_ref_pending = 0;
2499 #if CONFIG_MULTIPLE_ARF
2503 // Get last frame source.
2504 if (cm->current_video_frame > 0) {
2505 if ((cpi->last_source = vp9_lookahead_peek(cpi->lookahead, -1)) == NULL)
2509 if ((cpi->source = vp9_lookahead_pop(cpi->lookahead, flush))) {
2513 #if CONFIG_MULTIPLE_ARF
2514 // Is this frame the ARF overlay.
2515 rc->is_src_frame_alt_ref = 0;
2516 for (i = 0; i < cpi->arf_buffered; ++i) {
2517 if (cpi->source == cpi->alt_ref_source[i]) {
2518 rc->is_src_frame_alt_ref = 1;
2519 cpi->refresh_golden_frame = 1;
2524 rc->is_src_frame_alt_ref = cpi->alt_ref_source &&
2525 (cpi->source == cpi->alt_ref_source);
2527 if (rc->is_src_frame_alt_ref) {
2528 // Current frame is an ARF overlay frame.
2529 #if CONFIG_MULTIPLE_ARF
2530 cpi->alt_ref_source[i] = NULL;
2532 cpi->alt_ref_source = NULL;
2534 // Don't refresh the last buffer for an ARF overlay frame. It will
2535 // become the GF so preserve last as an alternative prediction option.
2536 cpi->refresh_last_frame = 0;
2538 #if CONFIG_MULTIPLE_ARF
2539 ++cpi->next_frame_in_order;
2545 cpi->un_scaled_source = cpi->Source = force_src_buffer ? force_src_buffer
2546 : &cpi->source->img;
2548 if (cpi->last_source != NULL) {
2549 cpi->unscaled_last_source = &cpi->last_source->img;
2551 cpi->unscaled_last_source = NULL;
2554 *time_stamp = cpi->source->ts_start;
2555 *time_end = cpi->source->ts_end;
2556 *frame_flags = cpi->source->flags;
2558 #if CONFIG_MULTIPLE_ARF
2559 if (cm->frame_type != KEY_FRAME && cpi->pass == 2)
2560 rc->source_alt_ref_pending = is_next_frame_arf(cpi);
2564 if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done) {
2565 vp9_end_first_pass(cpi); /* get last stats packet */
2566 cpi->twopass.first_pass_done = 1;
2571 if (cpi->source->ts_start < cpi->first_time_stamp_ever) {
2572 cpi->first_time_stamp_ever = cpi->source->ts_start;
2573 cpi->last_end_time_stamp_seen = cpi->source->ts_start;
2576 // adjust frame rates based on timestamps given
2577 if (cm->show_frame) {
2578 adjust_frame_rate(cpi);
2581 if (cpi->svc.number_temporal_layers > 1 &&
2582 cpi->oxcf.rc_mode == VPX_CBR) {
2583 vp9_update_temporal_layer_framerate(cpi);
2584 vp9_restore_layer_context(cpi);
2587 // start with a 0 size frame
2590 // Clear down mmx registers
2591 vp9_clear_system_state();
2593 /* find a free buffer for the new frame, releasing the reference previously
2596 cm->frame_bufs[cm->new_fb_idx].ref_count--;
2597 cm->new_fb_idx = get_free_fb(cm);
2599 #if CONFIG_MULTIPLE_ARF
2600 /* Set up the correct ARF frame. */
2601 if (cpi->refresh_alt_ref_frame) {
2602 ++cpi->arf_buffered;
2604 if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
2606 cpi->alt_fb_idx = cpi->arf_buffer_idx[cpi->sequence_number];
2610 cpi->frame_flags = *frame_flags;
2612 if (cpi->pass == 2 &&
2613 cm->current_video_frame == 0 &&
2614 cpi->oxcf.allow_spatial_resampling &&
2615 cpi->oxcf.rc_mode == VPX_VBR) {
2616 // Internal scaling is triggered on the first frame.
2617 vp9_set_size_literal(cpi, cpi->oxcf.scaled_frame_width,
2618 cpi->oxcf.scaled_frame_height);
2621 // Reset the frame pointers to the current frame size
2622 vp9_realloc_frame_buffer(get_frame_new_buffer(cm),
2623 cm->width, cm->height,
2624 cm->subsampling_x, cm->subsampling_y,
2625 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL);
2627 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2628 const int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, ref_frame)];
2629 YV12_BUFFER_CONFIG *const buf = &cm->frame_bufs[idx].buf;
2630 RefBuffer *const ref_buf = &cm->frame_refs[ref_frame - 1];
2633 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
2634 buf->y_crop_width, buf->y_crop_height,
2635 cm->width, cm->height);
2637 if (vp9_is_scaled(&ref_buf->sf))
2638 vp9_extend_frame_borders(buf);
2641 set_ref_ptrs(cm, xd, LAST_FRAME, LAST_FRAME);
2643 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
2647 if (cpi->pass == 1 &&
2648 (!cpi->use_svc || cpi->svc.number_temporal_layers == 1)) {
2649 const int lossless = is_lossless_requested(&cpi->oxcf);
2650 cpi->mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vp9_fdct4x4;
2651 cpi->mb.itxm_add = lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
2652 vp9_first_pass(cpi);
2653 } else if (cpi->pass == 2 &&
2654 (!cpi->use_svc || cpi->svc.number_temporal_layers == 1)) {
2655 Pass2Encode(cpi, size, dest, frame_flags);
2656 } else if (cpi->use_svc) {
2657 SvcEncode(cpi, size, dest, frame_flags);
2660 Pass0Encode(cpi, size, dest, frame_flags);
2663 if (cm->refresh_frame_context)
2664 cm->frame_contexts[cm->frame_context_idx] = cm->fc;
2666 // Frame was dropped, release scaled references.
2668 release_scaled_references(cpi);
2672 cpi->droppable = !frame_is_reference(cpi);
2675 // Save layer specific state.
2676 if ((cpi->svc.number_temporal_layers > 1 &&
2677 cpi->oxcf.rc_mode == VPX_CBR) ||
2678 (cpi->svc.number_spatial_layers > 1 && cpi->pass == 2)) {
2679 vp9_save_layer_context(cpi);
2682 vpx_usec_timer_mark(&cmptimer);
2683 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
2685 if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
2686 generate_psnr_packet(cpi);
2688 #if CONFIG_INTERNAL_STATS
2690 if (cpi->pass != 1) {
2691 cpi->bytes += (int)(*size);
2693 if (cm->show_frame) {
2696 if (cpi->b_calculate_psnr) {
2697 YV12_BUFFER_CONFIG *orig = cpi->Source;
2698 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
2699 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
2701 calc_psnr(orig, recon, &psnr);
2703 cpi->total += psnr.psnr[0];
2704 cpi->total_y += psnr.psnr[1];
2705 cpi->total_u += psnr.psnr[2];
2706 cpi->total_v += psnr.psnr[3];
2707 cpi->total_sq_error += psnr.sse[0];
2708 cpi->total_samples += psnr.samples[0];
2712 double frame_ssim2 = 0, weight = 0;
2713 #if CONFIG_VP9_POSTPROC
2714 vp9_deblock(cm->frame_to_show, &cm->post_proc_buffer,
2715 cm->lf.filter_level * 10 / 6);
2717 vp9_clear_system_state();
2719 calc_psnr(orig, pp, &psnr2);
2721 cpi->totalp += psnr2.psnr[0];
2722 cpi->totalp_y += psnr2.psnr[1];
2723 cpi->totalp_u += psnr2.psnr[2];
2724 cpi->totalp_v += psnr2.psnr[3];
2725 cpi->totalp_sq_error += psnr2.sse[0];
2726 cpi->totalp_samples += psnr2.samples[0];
2728 frame_ssim2 = vp9_calc_ssim(orig, recon, 1, &weight);
2730 cpi->summed_quality += frame_ssim2 * weight;
2731 cpi->summed_weights += weight;
2733 frame_ssim2 = vp9_calc_ssim(orig, &cm->post_proc_buffer, 1, &weight);
2735 cpi->summedp_quality += frame_ssim2 * weight;
2736 cpi->summedp_weights += weight;
2739 FILE *f = fopen("q_used.stt", "a");
2740 fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
2741 cpi->common.current_video_frame, y2, u2, v2,
2742 frame_psnr2, frame_ssim2);
2749 if (cpi->b_calculate_ssimg) {
2750 double y, u, v, frame_all;
2751 frame_all = vp9_calc_ssimg(cpi->Source, cm->frame_to_show, &y, &u, &v);
2752 cpi->total_ssimg_y += y;
2753 cpi->total_ssimg_u += u;
2754 cpi->total_ssimg_v += v;
2755 cpi->total_ssimg_all += frame_all;
2764 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
2765 vp9_ppflags_t *flags) {
2766 VP9_COMMON *cm = &cpi->common;
2767 #if !CONFIG_VP9_POSTPROC
2771 if (!cm->show_frame) {
2775 #if CONFIG_VP9_POSTPROC
2776 ret = vp9_post_proc_frame(cm, dest, flags);
2778 if (cm->frame_to_show) {
2779 *dest = *cm->frame_to_show;
2780 dest->y_width = cm->width;
2781 dest->y_height = cm->height;
2782 dest->uv_width = cm->width >> cm->subsampling_x;
2783 dest->uv_height = cm->height >> cm->subsampling_y;
2788 #endif // !CONFIG_VP9_POSTPROC
2789 vp9_clear_system_state();
2794 int vp9_set_active_map(VP9_COMP *cpi, unsigned char *map, int rows, int cols) {
2795 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
2797 vpx_memcpy(cpi->active_map, map, rows * cols);
2798 cpi->active_map_enabled = 1;
2800 cpi->active_map_enabled = 0;
2805 // cpi->active_map_enabled = 0;
2810 int vp9_set_internal_size(VP9_COMP *cpi,
2811 VPX_SCALING horiz_mode, VPX_SCALING vert_mode) {
2812 VP9_COMMON *cm = &cpi->common;
2813 int hr = 0, hs = 0, vr = 0, vs = 0;
2815 if (horiz_mode > ONETWO || vert_mode > ONETWO)
2818 Scale2Ratio(horiz_mode, &hr, &hs);
2819 Scale2Ratio(vert_mode, &vr, &vs);
2821 // always go to the next whole number
2822 cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
2823 cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
2825 assert(cm->width <= cpi->initial_width);
2826 assert(cm->height <= cpi->initial_height);
2827 update_frame_size(cpi);
2831 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
2832 unsigned int height) {
2833 VP9_COMMON *cm = &cpi->common;
2835 check_initial_width(cpi, 1, 1);
2839 if (cm->width * 5 < cpi->initial_width) {
2840 cm->width = cpi->initial_width / 5 + 1;
2841 printf("Warning: Desired width too small, changed to %d\n", cm->width);
2843 if (cm->width > cpi->initial_width) {
2844 cm->width = cpi->initial_width;
2845 printf("Warning: Desired width too large, changed to %d\n", cm->width);
2850 cm->height = height;
2851 if (cm->height * 5 < cpi->initial_height) {
2852 cm->height = cpi->initial_height / 5 + 1;
2853 printf("Warning: Desired height too small, changed to %d\n", cm->height);
2855 if (cm->height > cpi->initial_height) {
2856 cm->height = cpi->initial_height;
2857 printf("Warning: Desired height too large, changed to %d\n", cm->height);
2861 assert(cm->width <= cpi->initial_width);
2862 assert(cm->height <= cpi->initial_height);
2863 update_frame_size(cpi);
2867 void vp9_set_svc(VP9_COMP *cpi, int use_svc) {
2868 cpi->use_svc = use_svc;
2872 int vp9_get_y_sse(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b) {
2873 assert(a->y_crop_width == b->y_crop_width);
2874 assert(a->y_crop_height == b->y_crop_height);
2876 return (int)get_sse(a->y_buffer, a->y_stride, b->y_buffer, b->y_stride,
2877 a->y_crop_width, a->y_crop_height);
2881 int vp9_get_quantizer(VP9_COMP *cpi) {
2882 return cpi->common.base_qindex;