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
80 static INLINE void Scale2Ratio(VPX_SCALING mode, int *hr, int *hs) {
106 static void set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv) {
107 MACROBLOCK *const mb = &cpi->mb;
108 cpi->common.allow_high_precision_mv = allow_high_precision_mv;
109 if (cpi->common.allow_high_precision_mv) {
110 mb->mvcost = mb->nmvcost_hp;
111 mb->mvsadcost = mb->nmvsadcost_hp;
113 mb->mvcost = mb->nmvcost;
114 mb->mvsadcost = mb->nmvsadcost;
118 static void setup_key_frame(VP9_COMP *cpi) {
119 vp9_setup_past_independence(&cpi->common);
121 // All buffers are implicitly updated on key frames.
122 cpi->refresh_golden_frame = 1;
123 cpi->refresh_alt_ref_frame = 1;
126 static void setup_inter_frame(VP9_COMMON *cm) {
127 if (cm->error_resilient_mode || cm->intra_only)
128 vp9_setup_past_independence(cm);
130 assert(cm->frame_context_idx < FRAME_CONTEXTS);
131 cm->fc = cm->frame_contexts[cm->frame_context_idx];
134 static void setup_frame(VP9_COMP *cpi) {
135 VP9_COMMON *const cm = &cpi->common;
136 // Set up entropy context depending on frame type. The decoder mandates
137 // the use of the default context, index 0, for keyframes and inter
138 // frames where the error_resilient_mode or intra_only flag is set. For
139 // other inter-frames the encoder currently uses only two contexts;
140 // context 1 for ALTREF frames and context 0 for the others.
141 if (cm->frame_type == KEY_FRAME) {
142 setup_key_frame(cpi);
144 if (!cm->intra_only && !cm->error_resilient_mode && !cpi->use_svc)
145 cm->frame_context_idx = cpi->refresh_alt_ref_frame;
146 setup_inter_frame(cm);
152 void vp9_initialize_enc() {
153 static int init_done = 0;
156 vp9_init_neighbors();
157 vp9_init_quant_tables();
159 vp9_coef_tree_initialize();
160 vp9_tokenize_initialize();
162 vp9_rc_init_minq_luts();
163 vp9_entropy_mv_init();
164 vp9_entropy_mode_init();
165 vp9_temporal_filter_init();
170 static void dealloc_compressor_data(VP9_COMP *cpi) {
171 VP9_COMMON *const cm = &cpi->common;
174 // Delete sementation map
175 vpx_free(cpi->segmentation_map);
176 cpi->segmentation_map = NULL;
177 vpx_free(cm->last_frame_seg_map);
178 cm->last_frame_seg_map = NULL;
179 vpx_free(cpi->coding_context.last_frame_seg_map_copy);
180 cpi->coding_context.last_frame_seg_map_copy = NULL;
182 vpx_free(cpi->complexity_map);
183 cpi->complexity_map = NULL;
185 vp9_cyclic_refresh_free(cpi->cyclic_refresh);
186 cpi->cyclic_refresh = NULL;
188 vpx_free(cpi->active_map);
189 cpi->active_map = NULL;
191 vp9_free_frame_buffers(cm);
193 vp9_free_frame_buffer(&cpi->last_frame_uf);
194 vp9_free_frame_buffer(&cpi->scaled_source);
195 vp9_free_frame_buffer(&cpi->scaled_last_source);
196 vp9_free_frame_buffer(&cpi->alt_ref_buffer);
197 vp9_lookahead_destroy(cpi->lookahead);
202 vp9_free_pc_tree(&cpi->mb);
204 for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
205 LAYER_CONTEXT *const lc = &cpi->svc.layer_context[i];
206 vpx_free(lc->rc_twopass_stats_in.buf);
207 lc->rc_twopass_stats_in.buf = NULL;
208 lc->rc_twopass_stats_in.sz = 0;
212 static void save_coding_context(VP9_COMP *cpi) {
213 CODING_CONTEXT *const cc = &cpi->coding_context;
214 VP9_COMMON *cm = &cpi->common;
216 // Stores a snapshot of key state variables which can subsequently be
217 // restored with a call to vp9_restore_coding_context. These functions are
218 // intended for use in a re-code loop in vp9_compress_frame where the
219 // quantizer value is adjusted between loop iterations.
220 vp9_copy(cc->nmvjointcost, cpi->mb.nmvjointcost);
221 vp9_copy(cc->nmvcosts, cpi->mb.nmvcosts);
222 vp9_copy(cc->nmvcosts_hp, cpi->mb.nmvcosts_hp);
224 vp9_copy(cc->segment_pred_probs, cm->seg.pred_probs);
226 vpx_memcpy(cpi->coding_context.last_frame_seg_map_copy,
227 cm->last_frame_seg_map, (cm->mi_rows * cm->mi_cols));
229 vp9_copy(cc->last_ref_lf_deltas, cm->lf.last_ref_deltas);
230 vp9_copy(cc->last_mode_lf_deltas, cm->lf.last_mode_deltas);
235 static void restore_coding_context(VP9_COMP *cpi) {
236 CODING_CONTEXT *const cc = &cpi->coding_context;
237 VP9_COMMON *cm = &cpi->common;
239 // Restore key state variables to the snapshot state stored in the
240 // previous call to vp9_save_coding_context.
241 vp9_copy(cpi->mb.nmvjointcost, cc->nmvjointcost);
242 vp9_copy(cpi->mb.nmvcosts, cc->nmvcosts);
243 vp9_copy(cpi->mb.nmvcosts_hp, cc->nmvcosts_hp);
245 vp9_copy(cm->seg.pred_probs, cc->segment_pred_probs);
247 vpx_memcpy(cm->last_frame_seg_map,
248 cpi->coding_context.last_frame_seg_map_copy,
249 (cm->mi_rows * cm->mi_cols));
251 vp9_copy(cm->lf.last_ref_deltas, cc->last_ref_lf_deltas);
252 vp9_copy(cm->lf.last_mode_deltas, cc->last_mode_lf_deltas);
257 static void configure_static_seg_features(VP9_COMP *cpi) {
258 VP9_COMMON *const cm = &cpi->common;
259 const RATE_CONTROL *const rc = &cpi->rc;
260 struct segmentation *const seg = &cm->seg;
262 int high_q = (int)(rc->avg_q > 48.0);
265 // Disable and clear down for KF
266 if (cm->frame_type == KEY_FRAME) {
267 // Clear down the global segmentation map
268 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
270 seg->update_data = 0;
271 cpi->static_mb_pct = 0;
273 // Disable segmentation
274 vp9_disable_segmentation(seg);
276 // Clear down the segment features.
277 vp9_clearall_segfeatures(seg);
278 } else if (cpi->refresh_alt_ref_frame) {
279 // If this is an alt ref frame
280 // Clear down the global segmentation map
281 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
283 seg->update_data = 0;
284 cpi->static_mb_pct = 0;
286 // Disable segmentation and individual segment features by default
287 vp9_disable_segmentation(seg);
288 vp9_clearall_segfeatures(seg);
290 // Scan frames from current to arf frame.
291 // This function re-enables segmentation if appropriate.
292 vp9_update_mbgraph_stats(cpi);
294 // If segmentation was enabled set those features needed for the
298 seg->update_data = 1;
300 qi_delta = vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 0.875);
301 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta - 2);
302 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
304 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
305 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
307 // Where relevant assume segment data is delta data
308 seg->abs_delta = SEGMENT_DELTADATA;
310 } else if (seg->enabled) {
311 // All other frames if segmentation has been enabled
313 // First normal frame in a valid gf or alt ref group
314 if (rc->frames_since_golden == 0) {
315 // Set up segment features for normal frames in an arf group
316 if (rc->source_alt_ref_active) {
318 seg->update_data = 1;
319 seg->abs_delta = SEGMENT_DELTADATA;
321 qi_delta = vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 1.125);
322 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta + 2);
323 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
325 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
326 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
328 // Segment coding disabled for compred testing
329 if (high_q || (cpi->static_mb_pct == 100)) {
330 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
331 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
332 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
335 // Disable segmentation and clear down features if alt ref
336 // is not active for this group
338 vp9_disable_segmentation(seg);
340 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
343 seg->update_data = 0;
345 vp9_clearall_segfeatures(seg);
347 } else if (rc->is_src_frame_alt_ref) {
348 // Special case where we are coding over the top of a previous
350 // Segment coding disabled for compred testing
352 // Enable ref frame features for segment 0 as well
353 vp9_enable_segfeature(seg, 0, SEG_LVL_REF_FRAME);
354 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
356 // All mbs should use ALTREF_FRAME
357 vp9_clear_segdata(seg, 0, SEG_LVL_REF_FRAME);
358 vp9_set_segdata(seg, 0, SEG_LVL_REF_FRAME, ALTREF_FRAME);
359 vp9_clear_segdata(seg, 1, SEG_LVL_REF_FRAME);
360 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
362 // Skip all MBs if high Q (0,0 mv and skip coeffs)
364 vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
365 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
367 // Enable data update
368 seg->update_data = 1;
372 // No updates.. leave things as they are.
374 seg->update_data = 0;
379 static void update_reference_segmentation_map(VP9_COMP *cpi) {
380 VP9_COMMON *const cm = &cpi->common;
381 MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
382 uint8_t *cache_ptr = cm->last_frame_seg_map;
385 for (row = 0; row < cm->mi_rows; row++) {
386 MODE_INFO **mi_8x8 = mi_8x8_ptr;
387 uint8_t *cache = cache_ptr;
388 for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
389 cache[0] = mi_8x8[0]->mbmi.segment_id;
390 mi_8x8_ptr += cm->mi_stride;
391 cache_ptr += cm->mi_cols;
396 static void set_speed_features(VP9_COMP *cpi) {
397 #if CONFIG_INTERNAL_STATS
399 for (i = 0; i < MAX_MODES; ++i)
400 cpi->mode_chosen_counts[i] = 0;
403 vp9_set_speed_features(cpi);
405 // Set rd thresholds based on mode and speed setting
406 vp9_set_rd_speed_thresholds(cpi);
407 vp9_set_rd_speed_thresholds_sub8x8(cpi);
409 cpi->mb.fwd_txm4x4 = vp9_fdct4x4;
410 if (cpi->oxcf.lossless || cpi->mb.e_mbd.lossless) {
411 cpi->mb.fwd_txm4x4 = vp9_fwht4x4;
415 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
416 VP9_COMMON *cm = &cpi->common;
417 const VP9EncoderConfig *oxcf = &cpi->oxcf;
419 cpi->lookahead = vp9_lookahead_init(oxcf->width, oxcf->height,
420 cm->subsampling_x, cm->subsampling_y,
421 oxcf->lag_in_frames);
423 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
424 "Failed to allocate lag buffers");
426 if (vp9_realloc_frame_buffer(&cpi->alt_ref_buffer,
427 oxcf->width, oxcf->height,
428 cm->subsampling_x, cm->subsampling_y,
429 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
430 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
431 "Failed to allocate altref buffer");
434 void vp9_alloc_compressor_data(VP9_COMP *cpi) {
435 VP9_COMMON *cm = &cpi->common;
437 if (vp9_alloc_frame_buffers(cm, cm->width, cm->height))
438 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
439 "Failed to allocate frame buffers");
441 if (vp9_alloc_frame_buffer(&cpi->last_frame_uf,
442 cm->width, cm->height,
443 cm->subsampling_x, cm->subsampling_y,
444 VP9_ENC_BORDER_IN_PIXELS))
445 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
446 "Failed to allocate last frame buffer");
448 if (vp9_alloc_frame_buffer(&cpi->scaled_source,
449 cm->width, cm->height,
450 cm->subsampling_x, cm->subsampling_y,
451 VP9_ENC_BORDER_IN_PIXELS))
452 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
453 "Failed to allocate scaled source buffer");
455 if (vp9_alloc_frame_buffer(&cpi->scaled_last_source,
456 cm->width, cm->height,
457 cm->subsampling_x, cm->subsampling_y,
458 VP9_ENC_BORDER_IN_PIXELS))
459 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
460 "Failed to allocate scaled last source buffer");
465 unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
467 CHECK_MEM_ERROR(cm, cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
470 vp9_setup_pc_tree(&cpi->common, &cpi->mb);
473 static void update_frame_size(VP9_COMP *cpi) {
474 VP9_COMMON *const cm = &cpi->common;
475 MACROBLOCKD *const xd = &cpi->mb.e_mbd;
477 vp9_update_frame_size(cm);
479 // Update size of buffers local to this frame
480 if (vp9_realloc_frame_buffer(&cpi->last_frame_uf,
481 cm->width, cm->height,
482 cm->subsampling_x, cm->subsampling_y,
483 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
484 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
485 "Failed to reallocate last frame buffer");
487 if (vp9_realloc_frame_buffer(&cpi->scaled_source,
488 cm->width, cm->height,
489 cm->subsampling_x, cm->subsampling_y,
490 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
491 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
492 "Failed to reallocate scaled source buffer");
494 if (vp9_realloc_frame_buffer(&cpi->scaled_last_source,
495 cm->width, cm->height,
496 cm->subsampling_x, cm->subsampling_y,
497 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
498 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
499 "Failed to reallocate scaled last source buffer");
502 int y_stride = cpi->scaled_source.y_stride;
504 if (cpi->sf.search_method == NSTEP) {
505 vp9_init3smotion_compensation(&cpi->ss_cfg, y_stride);
506 } else if (cpi->sf.search_method == DIAMOND) {
507 vp9_init_dsmotion_compensation(&cpi->ss_cfg, y_stride);
511 init_macroblockd(cm, xd);
514 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
515 cpi->oxcf.framerate = framerate < 0.1 ? 30 : framerate;
516 vp9_rc_update_framerate(cpi);
519 int64_t vp9_rescale(int64_t val, int64_t num, int denom) {
521 int64_t llden = denom;
524 return (llval * llnum / llden);
527 static void set_tile_limits(VP9_COMP *cpi) {
528 VP9_COMMON *const cm = &cpi->common;
530 int min_log2_tile_cols, max_log2_tile_cols;
531 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
533 cm->log2_tile_cols = clamp(cpi->oxcf.tile_columns,
534 min_log2_tile_cols, max_log2_tile_cols);
535 cm->log2_tile_rows = cpi->oxcf.tile_rows;
538 static void init_config(struct VP9_COMP *cpi, VP9EncoderConfig *oxcf) {
539 VP9_COMMON *const cm = &cpi->common;
543 cm->profile = oxcf->profile;
544 cm->bit_depth = oxcf->bit_depth;
546 cm->width = oxcf->width;
547 cm->height = oxcf->height;
548 cm->subsampling_x = 0;
549 cm->subsampling_y = 0;
550 vp9_alloc_compressor_data(cpi);
552 // Spatial scalability.
553 cpi->svc.number_spatial_layers = oxcf->ss_number_layers;
554 // Temporal scalability.
555 cpi->svc.number_temporal_layers = oxcf->ts_number_layers;
557 if ((cpi->svc.number_temporal_layers > 1 &&
558 cpi->oxcf.rc_mode == RC_MODE_CBR) ||
559 (cpi->svc.number_spatial_layers > 1 &&
560 cpi->oxcf.mode == TWO_PASS_SECOND_BEST)) {
561 vp9_init_layer_context(cpi);
564 // change includes all joint functionality
565 vp9_change_config(cpi, oxcf);
567 cpi->static_mb_pct = 0;
573 set_tile_limits(cpi);
576 static int get_pass(MODE mode) {
586 case TWO_PASS_SECOND_GOOD:
587 case TWO_PASS_SECOND_BEST:
593 void vp9_change_config(struct VP9_COMP *cpi, const VP9EncoderConfig *oxcf) {
594 VP9_COMMON *const cm = &cpi->common;
595 RATE_CONTROL *const rc = &cpi->rc;
597 if (cm->profile != oxcf->profile)
598 cm->profile = oxcf->profile;
599 cm->bit_depth = oxcf->bit_depth;
601 if (cm->profile <= PROFILE_1)
602 assert(cm->bit_depth == BITS_8);
604 assert(cm->bit_depth > BITS_8);
607 cpi->pass = get_pass(cpi->oxcf.mode);
608 if (cpi->oxcf.mode == REALTIME)
609 cpi->oxcf.play_alternate = 0;
611 cpi->oxcf.lossless = oxcf->lossless;
612 if (cpi->oxcf.lossless) {
613 // In lossless mode, make sure right quantizer range and correct transform
615 cpi->oxcf.worst_allowed_q = 0;
616 cpi->oxcf.best_allowed_q = 0;
617 cpi->mb.e_mbd.itxm_add = vp9_iwht4x4_add;
619 cpi->mb.e_mbd.itxm_add = vp9_idct4x4_add;
621 rc->baseline_gf_interval = DEFAULT_GF_INTERVAL;
622 cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
624 cpi->refresh_golden_frame = 0;
625 cpi->refresh_last_frame = 1;
626 cm->refresh_frame_context = 1;
627 cm->reset_frame_context = 0;
629 vp9_reset_segment_features(&cm->seg);
630 set_high_precision_mv(cpi, 0);
635 for (i = 0; i < MAX_SEGMENTS; i++)
636 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
638 cpi->encode_breakout = cpi->oxcf.encode_breakout;
640 // local file playback mode == really big buffer
641 if (cpi->oxcf.rc_mode == RC_MODE_VBR) {
642 cpi->oxcf.starting_buffer_level = 60000;
643 cpi->oxcf.optimal_buffer_level = 60000;
644 cpi->oxcf.maximum_buffer_size = 240000;
647 // Convert target bandwidth from Kbit/s to Bit/s
648 cpi->oxcf.target_bandwidth *= 1000;
650 cpi->oxcf.starting_buffer_level =
651 vp9_rescale(cpi->oxcf.starting_buffer_level,
652 cpi->oxcf.target_bandwidth, 1000);
654 // Set or reset optimal and maximum buffer levels.
655 if (cpi->oxcf.optimal_buffer_level == 0)
656 cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
658 cpi->oxcf.optimal_buffer_level =
659 vp9_rescale(cpi->oxcf.optimal_buffer_level,
660 cpi->oxcf.target_bandwidth, 1000);
662 if (cpi->oxcf.maximum_buffer_size == 0)
663 cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
665 cpi->oxcf.maximum_buffer_size =
666 vp9_rescale(cpi->oxcf.maximum_buffer_size,
667 cpi->oxcf.target_bandwidth, 1000);
668 // Under a configuration change, where maximum_buffer_size may change,
669 // keep buffer level clipped to the maximum allowed buffer size.
670 rc->bits_off_target = MIN(rc->bits_off_target, cpi->oxcf.maximum_buffer_size);
671 rc->buffer_level = MIN(rc->buffer_level, cpi->oxcf.maximum_buffer_size);
673 // Set up frame rate and related parameters rate control values.
674 vp9_new_framerate(cpi, cpi->oxcf.framerate);
676 // Set absolute upper and lower quality limits
677 rc->worst_quality = cpi->oxcf.worst_allowed_q;
678 rc->best_quality = cpi->oxcf.best_allowed_q;
680 cm->interp_filter = DEFAULT_INTERP_FILTER;
682 cm->display_width = cpi->oxcf.width;
683 cm->display_height = cpi->oxcf.height;
685 if (cpi->initial_width) {
686 // Increasing the size of the frame beyond the first seen frame, or some
687 // otherwise signaled maximum size, is not supported.
688 // TODO(jkoleszar): exit gracefully.
689 assert(cm->width <= cpi->initial_width);
690 assert(cm->height <= cpi->initial_height);
692 update_frame_size(cpi);
694 if ((cpi->svc.number_temporal_layers > 1 &&
695 cpi->oxcf.rc_mode == RC_MODE_CBR) ||
696 (cpi->svc.number_spatial_layers > 1 && cpi->pass == 2)) {
697 vp9_update_layer_context_change_config(cpi,
698 (int)cpi->oxcf.target_bandwidth);
701 #if CONFIG_MULTIPLE_ARF
702 vp9_zero(cpi->alt_ref_source);
704 cpi->alt_ref_source = NULL;
706 rc->is_src_frame_alt_ref = 0;
709 // Experimental RD Code
710 cpi->frame_distortion = 0;
711 cpi->last_frame_distortion = 0;
714 set_tile_limits(cpi);
716 cpi->ext_refresh_frame_flags_pending = 0;
717 cpi->ext_refresh_frame_context_pending = 0;
721 #define M_LOG2_E 0.693147180559945309417
723 #define log2f(x) (log (x) / (float) M_LOG2_E)
725 static void cal_nmvjointsadcost(int *mvjointsadcost) {
726 mvjointsadcost[0] = 600;
727 mvjointsadcost[1] = 300;
728 mvjointsadcost[2] = 300;
729 mvjointsadcost[3] = 300;
732 static void cal_nmvsadcosts(int *mvsadcost[2]) {
739 double z = 256 * (2 * (log2f(8 * i) + .6));
740 mvsadcost[0][i] = (int)z;
741 mvsadcost[1][i] = (int)z;
742 mvsadcost[0][-i] = (int)z;
743 mvsadcost[1][-i] = (int)z;
744 } while (++i <= MV_MAX);
747 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
754 double z = 256 * (2 * (log2f(8 * i) + .6));
755 mvsadcost[0][i] = (int)z;
756 mvsadcost[1][i] = (int)z;
757 mvsadcost[0][-i] = (int)z;
758 mvsadcost[1][-i] = (int)z;
759 } while (++i <= MV_MAX);
763 VP9_COMP *vp9_create_compressor(VP9EncoderConfig *oxcf) {
765 VP9_COMP *const cpi = vpx_memalign(32, sizeof(VP9_COMP));
766 VP9_COMMON *const cm = cpi != NULL ? &cpi->common : NULL;
773 if (setjmp(cm->error.jmp)) {
774 cm->error.setjmp = 0;
775 vp9_remove_compressor(cpi);
779 cm->error.setjmp = 1;
785 init_config(cpi, oxcf);
786 vp9_rc_init(&cpi->oxcf, cpi->pass, &cpi->rc);
788 cm->current_video_frame = 0;
790 // Set reference frame sign bias for ALTREF frame to 1 (for now)
791 cm->ref_frame_sign_bias[ALTREF_FRAME] = 1;
793 cpi->gold_is_last = 0;
794 cpi->alt_is_last = 0;
795 cpi->gold_is_alt = 0;
797 // Create the encoder segmentation map and set all entries to 0
798 CHECK_MEM_ERROR(cm, cpi->segmentation_map,
799 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
801 // Create a complexity map used for rd adjustment
802 CHECK_MEM_ERROR(cm, cpi->complexity_map,
803 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
805 // Create a map used for cyclic background refresh.
806 CHECK_MEM_ERROR(cm, cpi->cyclic_refresh,
807 vp9_cyclic_refresh_alloc(cm->mi_rows, cm->mi_cols));
809 // And a place holder structure is the coding context
810 // for use if we want to save and restore it
811 CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
812 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
814 CHECK_MEM_ERROR(cm, cpi->active_map, vpx_calloc(cm->MBs, 1));
815 vpx_memset(cpi->active_map, 1, cm->MBs);
816 cpi->active_map_enabled = 0;
818 for (i = 0; i < (sizeof(cpi->mbgraph_stats) /
819 sizeof(cpi->mbgraph_stats[0])); i++) {
820 CHECK_MEM_ERROR(cm, cpi->mbgraph_stats[i].mb_stats,
822 sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
825 cpi->refresh_alt_ref_frame = 0;
827 #if CONFIG_MULTIPLE_ARF
828 // Turn multiple ARF usage on/off. This is a quick hack for the initial test
829 // version. It should eventually be set via the codec API.
830 cpi->multi_arf_enabled = 1;
832 if (cpi->multi_arf_enabled) {
833 cpi->sequence_number = 0;
834 cpi->frame_coding_order_period = 0;
835 vp9_zero(cpi->frame_coding_order);
836 vp9_zero(cpi->arf_buffer_idx);
840 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
841 #if CONFIG_INTERNAL_STATS
842 cpi->b_calculate_ssimg = 0;
847 if (cpi->b_calculate_psnr) {
852 cpi->total_sq_error = 0;
853 cpi->total_samples = 0;
859 cpi->totalp_sq_error = 0;
860 cpi->totalp_samples = 0;
862 cpi->tot_recode_hits = 0;
863 cpi->summed_quality = 0;
864 cpi->summed_weights = 0;
865 cpi->summedp_quality = 0;
866 cpi->summedp_weights = 0;
869 if (cpi->b_calculate_ssimg) {
870 cpi->total_ssimg_y = 0;
871 cpi->total_ssimg_u = 0;
872 cpi->total_ssimg_v = 0;
873 cpi->total_ssimg_all = 0;
878 cpi->first_time_stamp_ever = INT64_MAX;
880 cal_nmvjointsadcost(cpi->mb.nmvjointsadcost);
881 cpi->mb.nmvcost[0] = &cpi->mb.nmvcosts[0][MV_MAX];
882 cpi->mb.nmvcost[1] = &cpi->mb.nmvcosts[1][MV_MAX];
883 cpi->mb.nmvsadcost[0] = &cpi->mb.nmvsadcosts[0][MV_MAX];
884 cpi->mb.nmvsadcost[1] = &cpi->mb.nmvsadcosts[1][MV_MAX];
885 cal_nmvsadcosts(cpi->mb.nmvsadcost);
887 cpi->mb.nmvcost_hp[0] = &cpi->mb.nmvcosts_hp[0][MV_MAX];
888 cpi->mb.nmvcost_hp[1] = &cpi->mb.nmvcosts_hp[1][MV_MAX];
889 cpi->mb.nmvsadcost_hp[0] = &cpi->mb.nmvsadcosts_hp[0][MV_MAX];
890 cpi->mb.nmvsadcost_hp[1] = &cpi->mb.nmvsadcosts_hp[1][MV_MAX];
891 cal_nmvsadcosts_hp(cpi->mb.nmvsadcost_hp);
893 #ifdef OUTPUT_YUV_SRC
894 yuv_file = fopen("bd.yuv", "ab");
896 #ifdef OUTPUT_YUV_REC
897 yuv_rec_file = fopen("rec.yuv", "wb");
901 framepsnr = fopen("framepsnr.stt", "a");
902 kf_list = fopen("kf_list.stt", "w");
905 cpi->output_pkt_list = oxcf->output_pkt_list;
907 cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
909 if (cpi->pass == 1) {
910 vp9_init_first_pass(cpi);
911 } else if (cpi->pass == 2) {
912 const size_t packet_sz = sizeof(FIRSTPASS_STATS);
913 const int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
915 if (cpi->svc.number_spatial_layers > 1
916 && cpi->svc.number_temporal_layers == 1) {
917 FIRSTPASS_STATS *const stats = oxcf->two_pass_stats_in.buf;
918 FIRSTPASS_STATS *stats_copy[VPX_SS_MAX_LAYERS] = {0};
921 for (i = 0; i < oxcf->ss_number_layers; ++i) {
922 FIRSTPASS_STATS *const last_packet_for_layer =
923 &stats[packets - oxcf->ss_number_layers + i];
924 const int layer_id = (int)last_packet_for_layer->spatial_layer_id;
925 const int packets_in_layer = (int)last_packet_for_layer->count + 1;
926 if (layer_id >= 0 && layer_id < oxcf->ss_number_layers) {
927 LAYER_CONTEXT *const lc = &cpi->svc.layer_context[layer_id];
929 vpx_free(lc->rc_twopass_stats_in.buf);
931 lc->rc_twopass_stats_in.sz = packets_in_layer * packet_sz;
932 CHECK_MEM_ERROR(cm, lc->rc_twopass_stats_in.buf,
933 vpx_malloc(lc->rc_twopass_stats_in.sz));
934 lc->twopass.stats_in_start = lc->rc_twopass_stats_in.buf;
935 lc->twopass.stats_in = lc->twopass.stats_in_start;
936 lc->twopass.stats_in_end = lc->twopass.stats_in_start
937 + packets_in_layer - 1;
938 stats_copy[layer_id] = lc->rc_twopass_stats_in.buf;
942 for (i = 0; i < packets; ++i) {
943 const int layer_id = (int)stats[i].spatial_layer_id;
944 if (layer_id >= 0 && layer_id < oxcf->ss_number_layers
945 && stats_copy[layer_id] != NULL) {
946 *stats_copy[layer_id] = stats[i];
947 ++stats_copy[layer_id];
951 vp9_init_second_pass_spatial_svc(cpi);
953 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
954 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
955 cpi->twopass.stats_in_end = &cpi->twopass.stats_in[packets - 1];
957 vp9_init_second_pass(cpi);
961 set_speed_features(cpi);
963 // Default rd threshold factors for mode selection
964 for (i = 0; i < BLOCK_SIZES; ++i) {
965 for (j = 0; j < MAX_MODES; ++j)
966 cpi->rd.thresh_freq_fact[i][j] = 32;
969 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF)\
970 cpi->fn_ptr[BT].sdf = SDF; \
971 cpi->fn_ptr[BT].sdaf = SDAF; \
972 cpi->fn_ptr[BT].vf = VF; \
973 cpi->fn_ptr[BT].svf = SVF; \
974 cpi->fn_ptr[BT].svaf = SVAF; \
975 cpi->fn_ptr[BT].sdx3f = SDX3F; \
976 cpi->fn_ptr[BT].sdx8f = SDX8F; \
977 cpi->fn_ptr[BT].sdx4df = SDX4DF;
979 BFP(BLOCK_32X16, vp9_sad32x16, vp9_sad32x16_avg,
980 vp9_variance32x16, vp9_sub_pixel_variance32x16,
981 vp9_sub_pixel_avg_variance32x16, NULL, NULL, vp9_sad32x16x4d)
983 BFP(BLOCK_16X32, vp9_sad16x32, vp9_sad16x32_avg,
984 vp9_variance16x32, vp9_sub_pixel_variance16x32,
985 vp9_sub_pixel_avg_variance16x32, NULL, NULL, vp9_sad16x32x4d)
987 BFP(BLOCK_64X32, vp9_sad64x32, vp9_sad64x32_avg,
988 vp9_variance64x32, vp9_sub_pixel_variance64x32,
989 vp9_sub_pixel_avg_variance64x32, NULL, NULL, vp9_sad64x32x4d)
991 BFP(BLOCK_32X64, vp9_sad32x64, vp9_sad32x64_avg,
992 vp9_variance32x64, vp9_sub_pixel_variance32x64,
993 vp9_sub_pixel_avg_variance32x64, NULL, NULL, vp9_sad32x64x4d)
995 BFP(BLOCK_32X32, vp9_sad32x32, vp9_sad32x32_avg,
996 vp9_variance32x32, vp9_sub_pixel_variance32x32,
997 vp9_sub_pixel_avg_variance32x32, vp9_sad32x32x3, vp9_sad32x32x8,
1000 BFP(BLOCK_64X64, vp9_sad64x64, vp9_sad64x64_avg,
1001 vp9_variance64x64, vp9_sub_pixel_variance64x64,
1002 vp9_sub_pixel_avg_variance64x64, vp9_sad64x64x3, vp9_sad64x64x8,
1005 BFP(BLOCK_16X16, vp9_sad16x16, vp9_sad16x16_avg,
1006 vp9_variance16x16, vp9_sub_pixel_variance16x16,
1007 vp9_sub_pixel_avg_variance16x16, vp9_sad16x16x3, vp9_sad16x16x8,
1010 BFP(BLOCK_16X8, vp9_sad16x8, vp9_sad16x8_avg,
1011 vp9_variance16x8, vp9_sub_pixel_variance16x8,
1012 vp9_sub_pixel_avg_variance16x8,
1013 vp9_sad16x8x3, vp9_sad16x8x8, vp9_sad16x8x4d)
1015 BFP(BLOCK_8X16, vp9_sad8x16, vp9_sad8x16_avg,
1016 vp9_variance8x16, vp9_sub_pixel_variance8x16,
1017 vp9_sub_pixel_avg_variance8x16,
1018 vp9_sad8x16x3, vp9_sad8x16x8, vp9_sad8x16x4d)
1020 BFP(BLOCK_8X8, vp9_sad8x8, vp9_sad8x8_avg,
1021 vp9_variance8x8, vp9_sub_pixel_variance8x8,
1022 vp9_sub_pixel_avg_variance8x8,
1023 vp9_sad8x8x3, vp9_sad8x8x8, vp9_sad8x8x4d)
1025 BFP(BLOCK_8X4, vp9_sad8x4, vp9_sad8x4_avg,
1026 vp9_variance8x4, vp9_sub_pixel_variance8x4,
1027 vp9_sub_pixel_avg_variance8x4, NULL, vp9_sad8x4x8, vp9_sad8x4x4d)
1029 BFP(BLOCK_4X8, vp9_sad4x8, vp9_sad4x8_avg,
1030 vp9_variance4x8, vp9_sub_pixel_variance4x8,
1031 vp9_sub_pixel_avg_variance4x8, NULL, vp9_sad4x8x8, vp9_sad4x8x4d)
1033 BFP(BLOCK_4X4, vp9_sad4x4, vp9_sad4x4_avg,
1034 vp9_variance4x4, vp9_sub_pixel_variance4x4,
1035 vp9_sub_pixel_avg_variance4x4,
1036 vp9_sad4x4x3, vp9_sad4x4x8, vp9_sad4x4x4d)
1038 cpi->full_search_sad = vp9_full_search_sad;
1039 cpi->diamond_search_sad = vp9_diamond_search_sad;
1040 cpi->refining_search_sad = vp9_refining_search_sad;
1042 /* vp9_init_quantizer() is first called here. Add check in
1043 * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
1044 * called later when needed. This will avoid unnecessary calls of
1045 * vp9_init_quantizer() for every frame.
1047 vp9_init_quantizer(cpi);
1049 vp9_loop_filter_init(cm);
1051 cm->error.setjmp = 0;
1056 void vp9_remove_compressor(VP9_COMP *cpi) {
1062 if (cpi && (cpi->common.current_video_frame > 0)) {
1063 #if CONFIG_INTERNAL_STATS
1065 vp9_clear_system_state();
1067 // printf("\n8x8-4x4:%d-%d\n", cpi->t8x8_count, cpi->t4x4_count);
1068 if (cpi->pass != 1) {
1069 FILE *f = fopen("opsnr.stt", "a");
1070 double time_encoded = (cpi->last_end_time_stamp_seen
1071 - cpi->first_time_stamp_ever) / 10000000.000;
1072 double total_encode_time = (cpi->time_receive_data +
1073 cpi->time_compress_data) / 1000.000;
1074 double dr = (double)cpi->bytes * (double) 8 / (double)1000
1077 if (cpi->b_calculate_psnr) {
1078 const double total_psnr =
1079 vpx_sse_to_psnr((double)cpi->total_samples, 255.0,
1080 (double)cpi->total_sq_error);
1081 const double totalp_psnr =
1082 vpx_sse_to_psnr((double)cpi->totalp_samples, 255.0,
1083 (double)cpi->totalp_sq_error);
1084 const double total_ssim = 100 * pow(cpi->summed_quality /
1085 cpi->summed_weights, 8.0);
1086 const double totalp_ssim = 100 * pow(cpi->summedp_quality /
1087 cpi->summedp_weights, 8.0);
1089 fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
1090 "VPXSSIM\tVPSSIMP\t Time(ms)\n");
1091 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",
1092 dr, cpi->total / cpi->count, total_psnr,
1093 cpi->totalp / cpi->count, totalp_psnr, total_ssim, totalp_ssim,
1097 if (cpi->b_calculate_ssimg) {
1098 fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t Time(ms)\n");
1099 fprintf(f, "%7.2f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
1100 cpi->total_ssimg_y / cpi->count,
1101 cpi->total_ssimg_u / cpi->count,
1102 cpi->total_ssimg_v / cpi->count,
1103 cpi->total_ssimg_all / cpi->count, total_encode_time);
1113 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
1114 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
1115 printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
1116 cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
1117 cpi->time_compress_data / 1000,
1118 (cpi->time_receive_data + cpi->time_compress_data) / 1000);
1123 dealloc_compressor_data(cpi);
1126 for (i = 0; i < sizeof(cpi->mbgraph_stats) /
1127 sizeof(cpi->mbgraph_stats[0]); ++i) {
1128 vpx_free(cpi->mbgraph_stats[i].mb_stats);
1131 vp9_remove_common(&cpi->common);
1134 #ifdef OUTPUT_YUV_SRC
1137 #ifdef OUTPUT_YUV_REC
1138 fclose(yuv_rec_file);
1154 static int64_t get_sse(const uint8_t *a, int a_stride,
1155 const uint8_t *b, int b_stride,
1156 int width, int height) {
1157 const int dw = width % 16;
1158 const int dh = height % 16;
1159 int64_t total_sse = 0;
1160 unsigned int sse = 0;
1165 variance(&a[width - dw], a_stride, &b[width - dw], b_stride,
1166 dw, height, &sse, &sum);
1171 variance(&a[(height - dh) * a_stride], a_stride,
1172 &b[(height - dh) * b_stride], b_stride,
1173 width - dw, dh, &sse, &sum);
1177 for (y = 0; y < height / 16; ++y) {
1178 const uint8_t *pa = a;
1179 const uint8_t *pb = b;
1180 for (x = 0; x < width / 16; ++x) {
1181 vp9_mse16x16(pa, a_stride, pb, b_stride, &sse);
1196 double psnr[4]; // total/y/u/v
1197 uint64_t sse[4]; // total/y/u/v
1198 uint32_t samples[4]; // total/y/u/v
1201 static void calc_psnr(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b,
1203 const int widths[3] = {a->y_width, a->uv_width, a->uv_width };
1204 const int heights[3] = {a->y_height, a->uv_height, a->uv_height};
1205 const uint8_t *a_planes[3] = {a->y_buffer, a->u_buffer, a->v_buffer };
1206 const int a_strides[3] = {a->y_stride, a->uv_stride, a->uv_stride};
1207 const uint8_t *b_planes[3] = {b->y_buffer, b->u_buffer, b->v_buffer };
1208 const int b_strides[3] = {b->y_stride, b->uv_stride, b->uv_stride};
1210 uint64_t total_sse = 0;
1211 uint32_t total_samples = 0;
1213 for (i = 0; i < 3; ++i) {
1214 const int w = widths[i];
1215 const int h = heights[i];
1216 const uint32_t samples = w * h;
1217 const uint64_t sse = get_sse(a_planes[i], a_strides[i],
1218 b_planes[i], b_strides[i],
1220 psnr->sse[1 + i] = sse;
1221 psnr->samples[1 + i] = samples;
1222 psnr->psnr[1 + i] = vpx_sse_to_psnr(samples, 255.0, (double)sse);
1225 total_samples += samples;
1228 psnr->sse[0] = total_sse;
1229 psnr->samples[0] = total_samples;
1230 psnr->psnr[0] = vpx_sse_to_psnr((double)total_samples, 255.0,
1234 static void generate_psnr_packet(VP9_COMP *cpi) {
1235 struct vpx_codec_cx_pkt pkt;
1238 calc_psnr(cpi->Source, cpi->common.frame_to_show, &psnr);
1239 for (i = 0; i < 4; ++i) {
1240 pkt.data.psnr.samples[i] = psnr.samples[i];
1241 pkt.data.psnr.sse[i] = psnr.sse[i];
1242 pkt.data.psnr.psnr[i] = psnr.psnr[i];
1244 pkt.kind = VPX_CODEC_PSNR_PKT;
1245 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
1248 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags) {
1249 if (ref_frame_flags > 7)
1252 cpi->ref_frame_flags = ref_frame_flags;
1256 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags) {
1257 cpi->ext_refresh_golden_frame = (ref_frame_flags & VP9_GOLD_FLAG) != 0;
1258 cpi->ext_refresh_alt_ref_frame = (ref_frame_flags & VP9_ALT_FLAG) != 0;
1259 cpi->ext_refresh_last_frame = (ref_frame_flags & VP9_LAST_FLAG) != 0;
1260 cpi->ext_refresh_frame_flags_pending = 1;
1263 static YV12_BUFFER_CONFIG *get_vp9_ref_frame_buffer(VP9_COMP *cpi,
1264 VP9_REFFRAME ref_frame_flag) {
1265 MV_REFERENCE_FRAME ref_frame = NONE;
1266 if (ref_frame_flag == VP9_LAST_FLAG)
1267 ref_frame = LAST_FRAME;
1268 else if (ref_frame_flag == VP9_GOLD_FLAG)
1269 ref_frame = GOLDEN_FRAME;
1270 else if (ref_frame_flag == VP9_ALT_FLAG)
1271 ref_frame = ALTREF_FRAME;
1273 return ref_frame == NONE ? NULL : get_ref_frame_buffer(cpi, ref_frame);
1276 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
1277 YV12_BUFFER_CONFIG *sd) {
1278 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
1280 vp8_yv12_copy_frame(cfg, sd);
1287 int vp9_get_reference_enc(VP9_COMP *cpi, int index, YV12_BUFFER_CONFIG **fb) {
1288 VP9_COMMON *cm = &cpi->common;
1290 if (index < 0 || index >= REF_FRAMES)
1293 *fb = &cm->frame_bufs[cm->ref_frame_map[index]].buf;
1297 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
1298 YV12_BUFFER_CONFIG *sd) {
1299 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
1301 vp8_yv12_copy_frame(sd, cfg);
1308 int vp9_update_entropy(VP9_COMP * cpi, int update) {
1309 cpi->ext_refresh_frame_context = update;
1310 cpi->ext_refresh_frame_context_pending = 1;
1315 #ifdef OUTPUT_YUV_SRC
1316 void vp9_write_yuv_frame(YV12_BUFFER_CONFIG *s) {
1317 uint8_t *src = s->y_buffer;
1318 int h = s->y_height;
1321 fwrite(src, s->y_width, 1, yuv_file);
1329 fwrite(src, s->uv_width, 1, yuv_file);
1330 src += s->uv_stride;
1337 fwrite(src, s->uv_width, 1, yuv_file);
1338 src += s->uv_stride;
1343 #ifdef OUTPUT_YUV_REC
1344 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
1345 YV12_BUFFER_CONFIG *s = cm->frame_to_show;
1346 uint8_t *src = s->y_buffer;
1350 fwrite(src, s->y_width, 1, yuv_rec_file);
1358 fwrite(src, s->uv_width, 1, yuv_rec_file);
1359 src += s->uv_stride;
1366 fwrite(src, s->uv_width, 1, yuv_rec_file);
1367 src += s->uv_stride;
1371 if (s->alpha_buffer) {
1372 src = s->alpha_buffer;
1373 h = s->alpha_height;
1375 fwrite(src, s->alpha_width, 1, yuv_rec_file);
1376 src += s->alpha_stride;
1381 fflush(yuv_rec_file);
1385 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
1386 YV12_BUFFER_CONFIG *dst) {
1387 // TODO(dkovalev): replace YV12_BUFFER_CONFIG with vpx_image_t
1389 const uint8_t *const srcs[4] = {src->y_buffer, src->u_buffer, src->v_buffer,
1391 const int src_strides[4] = {src->y_stride, src->uv_stride, src->uv_stride,
1393 const int src_widths[4] = {src->y_crop_width, src->uv_crop_width,
1394 src->uv_crop_width, src->y_crop_width};
1395 const int src_heights[4] = {src->y_crop_height, src->uv_crop_height,
1396 src->uv_crop_height, src->y_crop_height};
1397 uint8_t *const dsts[4] = {dst->y_buffer, dst->u_buffer, dst->v_buffer,
1399 const int dst_strides[4] = {dst->y_stride, dst->uv_stride, dst->uv_stride,
1401 const int dst_widths[4] = {dst->y_crop_width, dst->uv_crop_width,
1402 dst->uv_crop_width, dst->y_crop_width};
1403 const int dst_heights[4] = {dst->y_crop_height, dst->uv_crop_height,
1404 dst->uv_crop_height, dst->y_crop_height};
1406 for (i = 0; i < MAX_MB_PLANE; ++i)
1407 vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
1408 dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
1410 // TODO(hkuang): Call C version explicitly
1411 // as neon version only expand border size 32.
1412 vp8_yv12_extend_frame_borders_c(dst);
1415 static void scale_and_extend_frame(const YV12_BUFFER_CONFIG *src,
1416 YV12_BUFFER_CONFIG *dst) {
1417 const int src_w = src->y_crop_width;
1418 const int src_h = src->y_crop_height;
1419 const int dst_w = dst->y_crop_width;
1420 const int dst_h = dst->y_crop_height;
1421 const uint8_t *const srcs[4] = {src->y_buffer, src->u_buffer, src->v_buffer,
1423 const int src_strides[4] = {src->y_stride, src->uv_stride, src->uv_stride,
1425 uint8_t *const dsts[4] = {dst->y_buffer, dst->u_buffer, dst->v_buffer,
1427 const int dst_strides[4] = {dst->y_stride, dst->uv_stride, dst->uv_stride,
1431 for (y = 0; y < dst_h; y += 16) {
1432 for (x = 0; x < dst_w; x += 16) {
1433 for (i = 0; i < MAX_MB_PLANE; ++i) {
1434 const int factor = (i == 0 || i == 3 ? 1 : 2);
1435 const int x_q4 = x * (16 / factor) * src_w / dst_w;
1436 const int y_q4 = y * (16 / factor) * src_h / dst_h;
1437 const int src_stride = src_strides[i];
1438 const int dst_stride = dst_strides[i];
1439 const uint8_t *src_ptr = srcs[i] + (y / factor) * src_h / dst_h *
1440 src_stride + (x / factor) * src_w / dst_w;
1441 uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
1443 vp9_convolve8(src_ptr, src_stride, dst_ptr, dst_stride,
1444 vp9_sub_pel_filters_8[x_q4 & 0xf], 16 * src_w / dst_w,
1445 vp9_sub_pel_filters_8[y_q4 & 0xf], 16 * src_h / dst_h,
1446 16 / factor, 16 / factor);
1451 // TODO(hkuang): Call C version explicitly
1452 // as neon version only expand border size 32.
1453 vp8_yv12_extend_frame_borders_c(dst);
1456 static int find_fp_qindex() {
1459 for (i = 0; i < QINDEX_RANGE; i++) {
1460 if (vp9_convert_qindex_to_q(i) >= 30.0) {
1465 if (i == QINDEX_RANGE)
1471 #define WRITE_RECON_BUFFER 0
1472 #if WRITE_RECON_BUFFER
1473 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame) {
1478 snprintf(filename, sizeof(filename), "cx\\y%04d.raw", this_frame);
1479 yframe = fopen(filename, "wb");
1481 for (i = 0; i < frame->y_height; i++)
1482 fwrite(frame->y_buffer + i * frame->y_stride,
1483 frame->y_width, 1, yframe);
1486 snprintf(filename, sizeof(filename), "cx\\u%04d.raw", this_frame);
1487 yframe = fopen(filename, "wb");
1489 for (i = 0; i < frame->uv_height; i++)
1490 fwrite(frame->u_buffer + i * frame->uv_stride,
1491 frame->uv_width, 1, yframe);
1494 snprintf(filename, sizeof(filename), "cx\\v%04d.raw", this_frame);
1495 yframe = fopen(filename, "wb");
1497 for (i = 0; i < frame->uv_height; i++)
1498 fwrite(frame->v_buffer + i * frame->uv_stride,
1499 frame->uv_width, 1, yframe);
1505 // Function to test for conditions that indicate we should loop
1506 // back and recode a frame.
1507 static int recode_loop_test(const VP9_COMP *cpi,
1508 int high_limit, int low_limit,
1509 int q, int maxq, int minq) {
1510 const VP9_COMMON *const cm = &cpi->common;
1511 const RATE_CONTROL *const rc = &cpi->rc;
1512 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1513 int force_recode = 0;
1515 // Special case trap if maximum allowed frame size exceeded.
1516 if (rc->projected_frame_size > rc->max_frame_bandwidth) {
1519 // Is frame recode allowed.
1520 // Yes if either recode mode 1 is selected or mode 2 is selected
1521 // and the frame is a key frame, golden frame or alt_ref_frame
1522 } else if ((cpi->sf.recode_loop == ALLOW_RECODE) ||
1523 ((cpi->sf.recode_loop == ALLOW_RECODE_KFARFGF) &&
1524 (cm->frame_type == KEY_FRAME ||
1525 cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
1526 // General over and under shoot tests
1527 if ((rc->projected_frame_size > high_limit && q < maxq) ||
1528 (rc->projected_frame_size < low_limit && q > minq)) {
1530 } else if (cpi->oxcf.rc_mode == RC_MODE_CONSTRAINED_QUALITY) {
1531 // Deal with frame undershoot and whether or not we are
1532 // below the automatically set cq level.
1533 if (q > oxcf->cq_level &&
1534 rc->projected_frame_size < ((rc->this_frame_target * 7) >> 3)) {
1539 return force_recode;
1542 void vp9_update_reference_frames(VP9_COMP *cpi) {
1543 VP9_COMMON * const cm = &cpi->common;
1545 // At this point the new frame has been encoded.
1546 // If any buffer copy / swapping is signaled it should be done here.
1547 if (cm->frame_type == KEY_FRAME) {
1548 ref_cnt_fb(cm->frame_bufs,
1549 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
1550 ref_cnt_fb(cm->frame_bufs,
1551 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
1553 #if CONFIG_MULTIPLE_ARF
1554 else if (!cpi->multi_arf_enabled && cpi->refresh_golden_frame &&
1555 !cpi->refresh_alt_ref_frame) {
1557 else if (cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame &&
1560 /* Preserve the previously existing golden frame and update the frame in
1561 * the alt ref slot instead. This is highly specific to the current use of
1562 * alt-ref as a forward reference, and this needs to be generalized as
1563 * other uses are implemented (like RTC/temporal scaling)
1565 * The update to the buffer in the alt ref slot was signaled in
1566 * vp9_pack_bitstream(), now swap the buffer pointers so that it's treated
1567 * as the golden frame next time.
1571 ref_cnt_fb(cm->frame_bufs,
1572 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
1574 tmp = cpi->alt_fb_idx;
1575 cpi->alt_fb_idx = cpi->gld_fb_idx;
1576 cpi->gld_fb_idx = tmp;
1577 } else { /* For non key/golden frames */
1578 if (cpi->refresh_alt_ref_frame) {
1579 int arf_idx = cpi->alt_fb_idx;
1580 #if CONFIG_MULTIPLE_ARF
1581 if (cpi->multi_arf_enabled) {
1582 arf_idx = cpi->arf_buffer_idx[cpi->sequence_number + 1];
1585 ref_cnt_fb(cm->frame_bufs,
1586 &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
1589 if (cpi->refresh_golden_frame) {
1590 ref_cnt_fb(cm->frame_bufs,
1591 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
1595 if (cpi->refresh_last_frame) {
1596 ref_cnt_fb(cm->frame_bufs,
1597 &cm->ref_frame_map[cpi->lst_fb_idx], cm->new_fb_idx);
1601 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
1602 MACROBLOCKD *xd = &cpi->mb.e_mbd;
1603 struct loopfilter *lf = &cm->lf;
1605 lf->filter_level = 0;
1607 struct vpx_usec_timer timer;
1609 vp9_clear_system_state();
1611 vpx_usec_timer_start(&timer);
1613 vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.lpf_pick);
1615 vpx_usec_timer_mark(&timer);
1616 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
1619 if (lf->filter_level > 0) {
1620 vp9_loop_filter_frame(cm, xd, lf->filter_level, 0, 0);
1623 vp9_extend_frame_inner_borders(cm->frame_to_show);
1626 void vp9_scale_references(VP9_COMP *cpi) {
1627 VP9_COMMON *cm = &cpi->common;
1628 MV_REFERENCE_FRAME ref_frame;
1630 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
1631 const int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, ref_frame)];
1632 const YV12_BUFFER_CONFIG *const ref = &cm->frame_bufs[idx].buf;
1634 if (ref->y_crop_width != cm->width ||
1635 ref->y_crop_height != cm->height) {
1636 const int new_fb = get_free_fb(cm);
1637 vp9_realloc_frame_buffer(&cm->frame_bufs[new_fb].buf,
1638 cm->width, cm->height,
1639 cm->subsampling_x, cm->subsampling_y,
1640 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL);
1641 scale_and_extend_frame(ref, &cm->frame_bufs[new_fb].buf);
1642 cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
1644 cpi->scaled_ref_idx[ref_frame - 1] = idx;
1645 cm->frame_bufs[idx].ref_count++;
1650 static void release_scaled_references(VP9_COMP *cpi) {
1651 VP9_COMMON *cm = &cpi->common;
1654 for (i = 0; i < 3; i++)
1655 cm->frame_bufs[cpi->scaled_ref_idx[i]].ref_count--;
1658 static void full_to_model_count(unsigned int *model_count,
1659 unsigned int *full_count) {
1661 model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
1662 model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
1663 model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
1664 for (n = THREE_TOKEN; n < EOB_TOKEN; ++n)
1665 model_count[TWO_TOKEN] += full_count[n];
1666 model_count[EOB_MODEL_TOKEN] = full_count[EOB_TOKEN];
1669 static void full_to_model_counts(vp9_coeff_count_model *model_count,
1670 vp9_coeff_count *full_count) {
1673 for (i = 0; i < PLANE_TYPES; ++i)
1674 for (j = 0; j < REF_TYPES; ++j)
1675 for (k = 0; k < COEF_BANDS; ++k)
1676 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
1677 full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
1680 #if 0 && CONFIG_INTERNAL_STATS
1681 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
1682 VP9_COMMON *const cm = &cpi->common;
1683 FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
1686 vp9_clear_system_state();
1688 recon_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
1690 if (cpi->twopass.total_left_stats.coded_error != 0.0)
1691 fprintf(f, "%10u %10d %10d %10d %10d"
1692 "%10"PRId64" %10"PRId64" %10"PRId64" %10"PRId64" %10d "
1693 "%7.2lf %7.2lf %7.2lf %7.2lf %7.2lf"
1694 "%6d %6d %5d %5d %5d "
1695 "%10"PRId64" %10.3lf"
1696 "%10lf %8u %10d %10d %10d\n",
1697 cpi->common.current_video_frame, cpi->rc.this_frame_target,
1698 cpi->rc.projected_frame_size,
1699 cpi->rc.projected_frame_size / cpi->common.MBs,
1700 (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
1701 cpi->rc.vbr_bits_off_target,
1702 cpi->rc.total_target_vs_actual,
1703 (cpi->oxcf.starting_buffer_level - cpi->rc.bits_off_target),
1704 cpi->rc.total_actual_bits, cm->base_qindex,
1705 vp9_convert_qindex_to_q(cm->base_qindex),
1706 (double)vp9_dc_quant(cm->base_qindex, 0) / 4.0,
1708 vp9_convert_qindex_to_q(cpi->rc.ni_av_qi),
1709 vp9_convert_qindex_to_q(cpi->oxcf.cq_level),
1710 cpi->refresh_last_frame, cpi->refresh_golden_frame,
1711 cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
1712 cpi->twopass.bits_left,
1713 cpi->twopass.total_left_stats.coded_error,
1714 cpi->twopass.bits_left /
1715 (1 + cpi->twopass.total_left_stats.coded_error),
1716 cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
1717 cpi->twopass.kf_zeromotion_pct);
1722 FILE *const fmodes = fopen("Modes.stt", "a");
1725 fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
1726 cm->frame_type, cpi->refresh_golden_frame,
1727 cpi->refresh_alt_ref_frame);
1729 for (i = 0; i < MAX_MODES; ++i)
1730 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
1732 fprintf(fmodes, "\n");
1739 static void encode_without_recode_loop(VP9_COMP *cpi,
1743 VP9_COMMON *const cm = &cpi->common;
1744 vp9_clear_system_state();
1745 vp9_set_quantizer(cm, q);
1747 // Variance adaptive and in frame q adjustment experiments are mutually
1749 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
1750 vp9_vaq_frame_setup(cpi);
1751 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1752 vp9_setup_in_frame_q_adj(cpi);
1753 } else if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
1754 vp9_cyclic_refresh_setup(cpi);
1756 // transform / motion compensation build reconstruction frame
1757 vp9_encode_frame(cpi);
1759 // Update the skip mb flag probabilities based on the distribution
1760 // seen in the last encoder iteration.
1761 // update_base_skip_probs(cpi);
1762 vp9_clear_system_state();
1765 static void encode_with_recode_loop(VP9_COMP *cpi,
1771 VP9_COMMON *const cm = &cpi->common;
1772 RATE_CONTROL *const rc = &cpi->rc;
1775 int overshoot_seen = 0;
1776 int undershoot_seen = 0;
1777 int q_low = bottom_index, q_high = top_index;
1778 int frame_over_shoot_limit;
1779 int frame_under_shoot_limit;
1781 // Decide frame size bounds
1782 vp9_rc_compute_frame_size_bounds(cpi, rc->this_frame_target,
1783 &frame_under_shoot_limit,
1784 &frame_over_shoot_limit);
1787 vp9_clear_system_state();
1789 vp9_set_quantizer(cm, q);
1791 if (loop_count == 0)
1794 // Variance adaptive and in frame q adjustment experiments are mutually
1796 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
1797 vp9_vaq_frame_setup(cpi);
1798 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1799 vp9_setup_in_frame_q_adj(cpi);
1802 // transform / motion compensation build reconstruction frame
1803 vp9_encode_frame(cpi);
1805 // Update the skip mb flag probabilities based on the distribution
1806 // seen in the last encoder iteration.
1807 // update_base_skip_probs(cpi);
1809 vp9_clear_system_state();
1811 // Dummy pack of the bitstream using up to date stats to get an
1812 // accurate estimate of output frame size to determine if we need
1814 if (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF) {
1815 save_coding_context(cpi);
1816 cpi->dummy_packing = 1;
1817 if (!cpi->sf.use_nonrd_pick_mode)
1818 vp9_pack_bitstream(cpi, dest, size);
1820 rc->projected_frame_size = (int)(*size) << 3;
1821 restore_coding_context(cpi);
1823 if (frame_over_shoot_limit == 0)
1824 frame_over_shoot_limit = 1;
1827 if (cpi->oxcf.rc_mode == RC_MODE_CONSTANT_QUALITY) {
1830 if ((cm->frame_type == KEY_FRAME) &&
1831 rc->this_key_frame_forced &&
1832 (rc->projected_frame_size < rc->max_frame_bandwidth)) {
1834 int kf_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
1836 int high_err_target = cpi->ambient_err;
1837 int low_err_target = cpi->ambient_err >> 1;
1839 // Prevent possible divide by zero error below for perfect KF
1842 // The key frame is not good enough or we can afford
1843 // to make it better without undue risk of popping.
1844 if ((kf_err > high_err_target &&
1845 rc->projected_frame_size <= frame_over_shoot_limit) ||
1846 (kf_err > low_err_target &&
1847 rc->projected_frame_size <= frame_under_shoot_limit)) {
1849 q_high = q > q_low ? q - 1 : q_low;
1852 q = (q * high_err_target) / kf_err;
1853 q = MIN(q, (q_high + q_low) >> 1);
1854 } else if (kf_err < low_err_target &&
1855 rc->projected_frame_size >= frame_under_shoot_limit) {
1856 // The key frame is much better than the previous frame
1858 q_low = q < q_high ? q + 1 : q_high;
1861 q = (q * low_err_target) / kf_err;
1862 q = MIN(q, (q_high + q_low + 1) >> 1);
1865 // Clamp Q to upper and lower limits:
1866 q = clamp(q, q_low, q_high);
1869 } else if (recode_loop_test(
1870 cpi, frame_over_shoot_limit, frame_under_shoot_limit,
1871 q, MAX(q_high, top_index), bottom_index)) {
1872 // Is the projected frame size out of range and are we allowed
1873 // to attempt to recode.
1877 // Frame size out of permitted range:
1878 // Update correction factor & compute new Q to try...
1880 // Frame is too large
1881 if (rc->projected_frame_size > rc->this_frame_target) {
1882 // Special case if the projected size is > the max allowed.
1883 if (rc->projected_frame_size >= rc->max_frame_bandwidth)
1884 q_high = rc->worst_quality;
1886 // Raise Qlow as to at least the current value
1887 q_low = q < q_high ? q + 1 : q_high;
1889 if (undershoot_seen || loop_count > 1) {
1890 // Update rate_correction_factor unless
1891 vp9_rc_update_rate_correction_factors(cpi, 1);
1893 q = (q_high + q_low + 1) / 2;
1895 // Update rate_correction_factor unless
1896 vp9_rc_update_rate_correction_factors(cpi, 0);
1898 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1899 bottom_index, MAX(q_high, top_index));
1901 while (q < q_low && retries < 10) {
1902 vp9_rc_update_rate_correction_factors(cpi, 0);
1903 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1904 bottom_index, MAX(q_high, top_index));
1911 // Frame is too small
1912 q_high = q > q_low ? q - 1 : q_low;
1914 if (overshoot_seen || loop_count > 1) {
1915 vp9_rc_update_rate_correction_factors(cpi, 1);
1916 q = (q_high + q_low) / 2;
1918 vp9_rc_update_rate_correction_factors(cpi, 0);
1919 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1920 bottom_index, top_index);
1921 // Special case reset for qlow for constrained quality.
1922 // This should only trigger where there is very substantial
1923 // undershoot on a frame and the auto cq level is above
1924 // the user passsed in value.
1925 if (cpi->oxcf.rc_mode == RC_MODE_CONSTRAINED_QUALITY &&
1930 while (q > q_high && retries < 10) {
1931 vp9_rc_update_rate_correction_factors(cpi, 0);
1932 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1933 bottom_index, top_index);
1938 undershoot_seen = 1;
1941 // Clamp Q to upper and lower limits:
1942 q = clamp(q, q_low, q_high);
1950 // Special case for overlay frame.
1951 if (rc->is_src_frame_alt_ref &&
1952 rc->projected_frame_size < rc->max_frame_bandwidth)
1958 #if CONFIG_INTERNAL_STATS
1959 cpi->tot_recode_hits++;
1965 static void get_ref_frame_flags(VP9_COMP *cpi) {
1966 if (cpi->refresh_last_frame & cpi->refresh_golden_frame)
1967 cpi->gold_is_last = 1;
1968 else if (cpi->refresh_last_frame ^ cpi->refresh_golden_frame)
1969 cpi->gold_is_last = 0;
1971 if (cpi->refresh_last_frame & cpi->refresh_alt_ref_frame)
1972 cpi->alt_is_last = 1;
1973 else if (cpi->refresh_last_frame ^ cpi->refresh_alt_ref_frame)
1974 cpi->alt_is_last = 0;
1976 if (cpi->refresh_alt_ref_frame & cpi->refresh_golden_frame)
1977 cpi->gold_is_alt = 1;
1978 else if (cpi->refresh_alt_ref_frame ^ cpi->refresh_golden_frame)
1979 cpi->gold_is_alt = 0;
1981 cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
1983 if (cpi->gold_is_last)
1984 cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
1986 if (cpi->rc.frames_till_gf_update_due == INT_MAX)
1987 cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
1989 if (cpi->alt_is_last)
1990 cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
1992 if (cpi->gold_is_alt)
1993 cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
1996 static void set_ext_overrides(VP9_COMP *cpi) {
1997 // Overrides the defaults with the externally supplied values with
1998 // vp9_update_reference() and vp9_update_entropy() calls
1999 // Note: The overrides are valid only for the next frame passed
2000 // to encode_frame_to_data_rate() function
2001 if (cpi->ext_refresh_frame_context_pending) {
2002 cpi->common.refresh_frame_context = cpi->ext_refresh_frame_context;
2003 cpi->ext_refresh_frame_context_pending = 0;
2005 if (cpi->ext_refresh_frame_flags_pending) {
2006 cpi->refresh_last_frame = cpi->ext_refresh_last_frame;
2007 cpi->refresh_golden_frame = cpi->ext_refresh_golden_frame;
2008 cpi->refresh_alt_ref_frame = cpi->ext_refresh_alt_ref_frame;
2009 cpi->ext_refresh_frame_flags_pending = 0;
2013 YV12_BUFFER_CONFIG *vp9_scale_if_required(VP9_COMMON *cm,
2014 YV12_BUFFER_CONFIG *unscaled,
2015 YV12_BUFFER_CONFIG *scaled) {
2016 if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
2017 cm->mi_rows * MI_SIZE != unscaled->y_height) {
2018 scale_and_extend_frame_nonnormative(unscaled, scaled);
2025 static void encode_frame_to_data_rate(VP9_COMP *cpi,
2028 unsigned int *frame_flags) {
2029 VP9_COMMON *const cm = &cpi->common;
2035 const SPEED_FEATURES *const sf = &cpi->sf;
2036 const unsigned int max_mv_def = MIN(cm->width, cm->height);
2037 struct segmentation *const seg = &cm->seg;
2038 set_ext_overrides(cpi);
2040 cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
2041 &cpi->scaled_source);
2043 if (cpi->unscaled_last_source != NULL)
2044 cpi->Last_Source = vp9_scale_if_required(cm, cpi->unscaled_last_source,
2045 &cpi->scaled_last_source);
2047 vp9_scale_references(cpi);
2049 vp9_clear_system_state();
2051 // Enable or disable mode based tweaking of the zbin.
2052 // For 2 pass only used where GF/ARF prediction quality
2053 // is above a threshold.
2054 cpi->zbin_mode_boost = 0;
2055 cpi->zbin_mode_boost_enabled = 0;
2057 // Current default encoder behavior for the altref sign bias.
2058 cm->ref_frame_sign_bias[ALTREF_FRAME] = cpi->rc.source_alt_ref_active;
2060 // Set default state for segment based loop filter update flags.
2061 cm->lf.mode_ref_delta_update = 0;
2063 // Initialize cpi->mv_step_param to default based on max resolution.
2064 cpi->mv_step_param = vp9_init_search_range(sf, max_mv_def);
2065 // Initialize cpi->max_mv_magnitude and cpi->mv_step_param if appropriate.
2066 if (sf->auto_mv_step_size) {
2067 if (frame_is_intra_only(cm)) {
2068 // Initialize max_mv_magnitude for use in the first INTER frame
2069 // after a key/intra-only frame.
2070 cpi->max_mv_magnitude = max_mv_def;
2073 // Allow mv_steps to correspond to twice the max mv magnitude found
2074 // in the previous frame, capped by the default max_mv_magnitude based
2076 cpi->mv_step_param = vp9_init_search_range(sf, MIN(max_mv_def, 2 *
2077 cpi->max_mv_magnitude));
2078 cpi->max_mv_magnitude = 0;
2082 // Set various flags etc to special state if it is a key frame.
2083 if (frame_is_intra_only(cm)) {
2084 // Reset the loop filter deltas and segmentation map.
2085 vp9_reset_segment_features(&cm->seg);
2087 // If segmentation is enabled force a map update for key frames.
2089 seg->update_map = 1;
2090 seg->update_data = 1;
2093 // The alternate reference frame cannot be active for a key frame.
2094 cpi->rc.source_alt_ref_active = 0;
2096 cm->error_resilient_mode = (cpi->oxcf.error_resilient_mode != 0);
2097 cm->frame_parallel_decoding_mode =
2098 (cpi->oxcf.frame_parallel_decoding_mode != 0);
2100 // By default, encoder assumes decoder can use prev_mi.
2101 cm->coding_use_prev_mi = 1;
2102 if (cm->error_resilient_mode) {
2103 cm->coding_use_prev_mi = 0;
2104 cm->frame_parallel_decoding_mode = 1;
2105 cm->reset_frame_context = 0;
2106 cm->refresh_frame_context = 0;
2107 } else if (cm->intra_only) {
2108 // Only reset the current context.
2109 cm->reset_frame_context = 2;
2113 // Configure experimental use of segmentation for enhanced coding of
2114 // static regions if indicated.
2115 // Only allowed in second pass of two pass (as requires lagged coding)
2116 // and if the relevant speed feature flag is set.
2117 if (cpi->pass == 2 && cpi->sf.static_segmentation)
2118 configure_static_seg_features(cpi);
2120 // For 1 pass CBR, check if we are dropping this frame.
2121 // Never drop on key frame.
2122 if (cpi->pass == 0 &&
2123 cpi->oxcf.rc_mode == RC_MODE_CBR &&
2124 cm->frame_type != KEY_FRAME) {
2125 if (vp9_rc_drop_frame(cpi)) {
2126 vp9_rc_postencode_update_drop_frame(cpi);
2127 ++cm->current_video_frame;
2132 vp9_clear_system_state();
2134 vp9_zero(cpi->rd.tx_select_threshes);
2136 #if CONFIG_VP9_POSTPROC
2137 if (cpi->oxcf.noise_sensitivity > 0) {
2139 switch (cpi->oxcf.noise_sensitivity) {
2157 vp9_denoise(cpi->Source, cpi->Source, l);
2161 #ifdef OUTPUT_YUV_SRC
2162 vp9_write_yuv_frame(cpi->Source);
2165 set_speed_features(cpi);
2167 // Decide q and q bounds.
2168 q = vp9_rc_pick_q_and_bounds(cpi, &bottom_index, &top_index);
2170 if (!frame_is_intra_only(cm)) {
2171 cm->interp_filter = DEFAULT_INTERP_FILTER;
2172 /* TODO: Decide this more intelligently */
2173 set_high_precision_mv(cpi, q < HIGH_PRECISION_MV_QTHRESH);
2176 if (cpi->sf.recode_loop == DISALLOW_RECODE) {
2177 encode_without_recode_loop(cpi, size, dest, q);
2179 encode_with_recode_loop(cpi, size, dest, q, bottom_index, top_index);
2182 // Special case code to reduce pulsing when key frames are forced at a
2183 // fixed interval. Note the reconstruction error if it is the frame before
2184 // the force key frame
2185 if (cpi->rc.next_key_frame_forced && cpi->rc.frames_to_key == 1) {
2186 cpi->ambient_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2189 // If the encoder forced a KEY_FRAME decision
2190 if (cm->frame_type == KEY_FRAME)
2191 cpi->refresh_last_frame = 1;
2193 cm->frame_to_show = get_frame_new_buffer(cm);
2195 #if WRITE_RECON_BUFFER
2197 write_cx_frame_to_file(cm->frame_to_show,
2198 cm->current_video_frame);
2200 write_cx_frame_to_file(cm->frame_to_show,
2201 cm->current_video_frame + 1000);
2204 // Pick the loop filter level for the frame.
2205 loopfilter_frame(cpi, cm);
2207 #if WRITE_RECON_BUFFER
2209 write_cx_frame_to_file(cm->frame_to_show,
2210 cm->current_video_frame + 2000);
2212 write_cx_frame_to_file(cm->frame_to_show,
2213 cm->current_video_frame + 3000);
2216 // build the bitstream
2217 cpi->dummy_packing = 0;
2218 vp9_pack_bitstream(cpi, dest, size);
2220 if (cm->seg.update_map)
2221 update_reference_segmentation_map(cpi);
2223 release_scaled_references(cpi);
2224 vp9_update_reference_frames(cpi);
2226 for (t = TX_4X4; t <= TX_32X32; t++)
2227 full_to_model_counts(cm->counts.coef[t], cpi->coef_counts[t]);
2229 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode)
2230 vp9_adapt_coef_probs(cm);
2232 if (!frame_is_intra_only(cm)) {
2233 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2234 vp9_adapt_mode_probs(cm);
2235 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2240 output_frame_level_debug_stats(cpi);
2242 if (cpi->refresh_golden_frame == 1)
2243 cpi->frame_flags |= FRAMEFLAGS_GOLDEN;
2245 cpi->frame_flags &= ~FRAMEFLAGS_GOLDEN;
2247 if (cpi->refresh_alt_ref_frame == 1)
2248 cpi->frame_flags |= FRAMEFLAGS_ALTREF;
2250 cpi->frame_flags &= ~FRAMEFLAGS_ALTREF;
2252 get_ref_frame_flags(cpi);
2254 cm->last_frame_type = cm->frame_type;
2255 vp9_rc_postencode_update(cpi, *size);
2257 if (cm->frame_type == KEY_FRAME) {
2258 // Tell the caller that the frame was coded as a key frame
2259 *frame_flags = cpi->frame_flags | FRAMEFLAGS_KEY;
2261 #if CONFIG_MULTIPLE_ARF
2262 // Reset the sequence number.
2263 if (cpi->multi_arf_enabled) {
2264 cpi->sequence_number = 0;
2265 cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
2266 cpi->new_frame_coding_order_period = -1;
2270 *frame_flags = cpi->frame_flags & ~FRAMEFLAGS_KEY;
2272 #if CONFIG_MULTIPLE_ARF
2273 /* Increment position in the coded frame sequence. */
2274 if (cpi->multi_arf_enabled) {
2275 ++cpi->sequence_number;
2276 if (cpi->sequence_number >= cpi->frame_coding_order_period) {
2277 cpi->sequence_number = 0;
2278 cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
2279 cpi->new_frame_coding_order_period = -1;
2281 cpi->this_frame_weight = cpi->arf_weight[cpi->sequence_number];
2282 assert(cpi->this_frame_weight >= 0);
2287 // Clear the one shot update flags for segmentation map and mode/ref loop
2289 cm->seg.update_map = 0;
2290 cm->seg.update_data = 0;
2291 cm->lf.mode_ref_delta_update = 0;
2293 // keep track of the last coded dimensions
2294 cm->last_width = cm->width;
2295 cm->last_height = cm->height;
2297 // reset to normal state now that we are done.
2298 if (!cm->show_existing_frame)
2299 cm->last_show_frame = cm->show_frame;
2301 if (cm->show_frame) {
2302 vp9_swap_mi_and_prev_mi(cm);
2304 // Don't increment frame counters if this was an altref buffer
2305 // update not a real frame
2306 ++cm->current_video_frame;
2308 vp9_inc_frame_in_layer(&cpi->svc);
2312 static void SvcEncode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
2313 unsigned int *frame_flags) {
2314 vp9_rc_get_svc_params(cpi);
2315 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2318 static void Pass0Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
2319 unsigned int *frame_flags) {
2320 if (cpi->oxcf.rc_mode == RC_MODE_CBR) {
2321 vp9_rc_get_one_pass_cbr_params(cpi);
2323 vp9_rc_get_one_pass_vbr_params(cpi);
2325 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2328 static void Pass1Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
2329 unsigned int *frame_flags) {
2334 vp9_rc_get_first_pass_params(cpi);
2335 vp9_set_quantizer(&cpi->common, find_fp_qindex());
2336 vp9_first_pass(cpi);
2339 static void Pass2Encode(VP9_COMP *cpi, size_t *size,
2340 uint8_t *dest, unsigned int *frame_flags) {
2341 cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
2343 vp9_rc_get_second_pass_params(cpi);
2344 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2346 vp9_twopass_postencode_update(cpi);
2349 static void check_initial_width(VP9_COMP *cpi, int subsampling_x,
2350 int subsampling_y) {
2351 VP9_COMMON *const cm = &cpi->common;
2353 if (!cpi->initial_width) {
2354 cm->subsampling_x = subsampling_x;
2355 cm->subsampling_y = subsampling_y;
2356 alloc_raw_frame_buffers(cpi);
2357 cpi->initial_width = cm->width;
2358 cpi->initial_height = cm->height;
2363 int vp9_receive_raw_frame(VP9_COMP *cpi, unsigned int frame_flags,
2364 YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
2366 VP9_COMMON *cm = &cpi->common;
2367 struct vpx_usec_timer timer;
2369 const int subsampling_x = sd->uv_width < sd->y_width;
2370 const int subsampling_y = sd->uv_height < sd->y_height;
2372 check_initial_width(cpi, subsampling_x, subsampling_y);
2373 vpx_usec_timer_start(&timer);
2374 if (vp9_lookahead_push(cpi->lookahead,
2375 sd, time_stamp, end_time, frame_flags))
2377 vpx_usec_timer_mark(&timer);
2378 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
2380 if (cm->profile == PROFILE_0 && (subsampling_x != 1 || subsampling_y != 1)) {
2381 vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
2382 "Non-4:2:0 color space requires profile >= 1");
2390 static int frame_is_reference(const VP9_COMP *cpi) {
2391 const VP9_COMMON *cm = &cpi->common;
2393 return cm->frame_type == KEY_FRAME ||
2394 cpi->refresh_last_frame ||
2395 cpi->refresh_golden_frame ||
2396 cpi->refresh_alt_ref_frame ||
2397 cm->refresh_frame_context ||
2398 cm->lf.mode_ref_delta_update ||
2399 cm->seg.update_map ||
2400 cm->seg.update_data;
2403 #if CONFIG_MULTIPLE_ARF
2404 int is_next_frame_arf(VP9_COMP *cpi) {
2405 // Negative entry in frame_coding_order indicates an ARF at this position.
2406 return cpi->frame_coding_order[cpi->sequence_number + 1] < 0 ? 1 : 0;
2410 void adjust_frame_rate(VP9_COMP *cpi) {
2411 int64_t this_duration;
2414 if (cpi->source->ts_start == cpi->first_time_stamp_ever) {
2415 this_duration = cpi->source->ts_end - cpi->source->ts_start;
2418 int64_t last_duration = cpi->last_end_time_stamp_seen
2419 - cpi->last_time_stamp_seen;
2421 this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
2423 // do a step update if the duration changes by 10%
2425 step = (int)((this_duration - last_duration) * 10 / last_duration);
2428 if (this_duration) {
2430 vp9_new_framerate(cpi, 10000000.0 / this_duration);
2432 // Average this frame's rate into the last second's average
2433 // frame rate. If we haven't seen 1 second yet, then average
2434 // over the whole interval seen.
2435 const double interval = MIN((double)(cpi->source->ts_end
2436 - cpi->first_time_stamp_ever), 10000000.0);
2437 double avg_duration = 10000000.0 / cpi->oxcf.framerate;
2438 avg_duration *= (interval - avg_duration + this_duration);
2439 avg_duration /= interval;
2441 vp9_new_framerate(cpi, 10000000.0 / avg_duration);
2444 cpi->last_time_stamp_seen = cpi->source->ts_start;
2445 cpi->last_end_time_stamp_seen = cpi->source->ts_end;
2448 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
2449 size_t *size, uint8_t *dest,
2450 int64_t *time_stamp, int64_t *time_end, int flush) {
2451 VP9_COMMON *const cm = &cpi->common;
2452 MACROBLOCKD *const xd = &cpi->mb.e_mbd;
2453 RATE_CONTROL *const rc = &cpi->rc;
2454 struct vpx_usec_timer cmptimer;
2455 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
2456 MV_REFERENCE_FRAME ref_frame;
2461 if (cpi->svc.number_spatial_layers > 1 && cpi->pass == 2) {
2462 vp9_restore_layer_context(cpi);
2465 vpx_usec_timer_start(&cmptimer);
2468 cpi->last_source = NULL;
2470 set_high_precision_mv(cpi, ALTREF_HIGH_PRECISION_MV);
2473 cm->reset_frame_context = 0;
2474 cm->refresh_frame_context = 1;
2475 cpi->refresh_last_frame = 1;
2476 cpi->refresh_golden_frame = 0;
2477 cpi->refresh_alt_ref_frame = 0;
2479 // Should we code an alternate reference frame.
2480 if (cpi->oxcf.play_alternate && rc->source_alt_ref_pending) {
2483 #if CONFIG_MULTIPLE_ARF
2484 assert(!cpi->multi_arf_enabled ||
2485 cpi->frame_coding_order[cpi->sequence_number] < 0);
2487 if (cpi->multi_arf_enabled && (cpi->pass == 2))
2488 frames_to_arf = (-cpi->frame_coding_order[cpi->sequence_number])
2489 - cpi->next_frame_in_order;
2492 frames_to_arf = rc->frames_till_gf_update_due;
2494 assert(frames_to_arf <= rc->frames_to_key);
2496 if ((cpi->source = vp9_lookahead_peek(cpi->lookahead, frames_to_arf))) {
2497 #if CONFIG_MULTIPLE_ARF
2498 cpi->alt_ref_source[cpi->arf_buffered] = cpi->source;
2500 cpi->alt_ref_source = cpi->source;
2503 if (cpi->oxcf.arnr_max_frames > 0) {
2504 // Produce the filtered ARF frame.
2505 // TODO(agrange) merge these two functions.
2506 vp9_configure_arnr_filter(cpi, frames_to_arf, rc->gfu_boost);
2507 vp9_temporal_filter_prepare(cpi, frames_to_arf);
2508 vp9_extend_frame_borders(&cpi->alt_ref_buffer);
2509 force_src_buffer = &cpi->alt_ref_buffer;
2513 cpi->refresh_alt_ref_frame = 1;
2514 cpi->refresh_golden_frame = 0;
2515 cpi->refresh_last_frame = 0;
2516 rc->is_src_frame_alt_ref = 0;
2518 #if CONFIG_MULTIPLE_ARF
2519 if (!cpi->multi_arf_enabled)
2521 rc->source_alt_ref_pending = 0;
2523 rc->source_alt_ref_pending = 0;
2528 #if CONFIG_MULTIPLE_ARF
2532 // Get last frame source.
2533 if (cm->current_video_frame > 0) {
2534 if ((cpi->last_source = vp9_lookahead_peek(cpi->lookahead, -1)) == NULL)
2538 if ((cpi->source = vp9_lookahead_pop(cpi->lookahead, flush))) {
2542 #if CONFIG_MULTIPLE_ARF
2543 // Is this frame the ARF overlay.
2544 rc->is_src_frame_alt_ref = 0;
2545 for (i = 0; i < cpi->arf_buffered; ++i) {
2546 if (cpi->source == cpi->alt_ref_source[i]) {
2547 rc->is_src_frame_alt_ref = 1;
2548 cpi->refresh_golden_frame = 1;
2553 rc->is_src_frame_alt_ref = cpi->alt_ref_source &&
2554 (cpi->source == cpi->alt_ref_source);
2556 if (rc->is_src_frame_alt_ref) {
2557 // Current frame is an ARF overlay frame.
2558 #if CONFIG_MULTIPLE_ARF
2559 cpi->alt_ref_source[i] = NULL;
2561 cpi->alt_ref_source = NULL;
2563 // Don't refresh the last buffer for an ARF overlay frame. It will
2564 // become the GF so preserve last as an alternative prediction option.
2565 cpi->refresh_last_frame = 0;
2567 #if CONFIG_MULTIPLE_ARF
2568 ++cpi->next_frame_in_order;
2574 cpi->un_scaled_source = cpi->Source = force_src_buffer ? force_src_buffer
2575 : &cpi->source->img;
2577 if (cpi->last_source != NULL) {
2578 cpi->unscaled_last_source = &cpi->last_source->img;
2580 cpi->unscaled_last_source = NULL;
2583 *time_stamp = cpi->source->ts_start;
2584 *time_end = cpi->source->ts_end;
2585 *frame_flags = cpi->source->flags;
2587 #if CONFIG_MULTIPLE_ARF
2588 if (cm->frame_type != KEY_FRAME && cpi->pass == 2)
2589 rc->source_alt_ref_pending = is_next_frame_arf(cpi);
2593 if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done) {
2594 vp9_end_first_pass(cpi); /* get last stats packet */
2595 cpi->twopass.first_pass_done = 1;
2600 if (cpi->source->ts_start < cpi->first_time_stamp_ever) {
2601 cpi->first_time_stamp_ever = cpi->source->ts_start;
2602 cpi->last_end_time_stamp_seen = cpi->source->ts_start;
2605 // adjust frame rates based on timestamps given
2606 if (cm->show_frame) {
2607 adjust_frame_rate(cpi);
2610 if (cpi->svc.number_temporal_layers > 1 &&
2611 cpi->oxcf.rc_mode == RC_MODE_CBR) {
2612 vp9_update_temporal_layer_framerate(cpi);
2613 vp9_restore_layer_context(cpi);
2616 // start with a 0 size frame
2619 // Clear down mmx registers
2620 vp9_clear_system_state();
2622 /* find a free buffer for the new frame, releasing the reference previously
2625 cm->frame_bufs[cm->new_fb_idx].ref_count--;
2626 cm->new_fb_idx = get_free_fb(cm);
2628 #if CONFIG_MULTIPLE_ARF
2629 /* Set up the correct ARF frame. */
2630 if (cpi->refresh_alt_ref_frame) {
2631 ++cpi->arf_buffered;
2633 if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
2635 cpi->alt_fb_idx = cpi->arf_buffer_idx[cpi->sequence_number];
2639 cpi->frame_flags = *frame_flags;
2641 if (cpi->pass == 2 &&
2642 cm->current_video_frame == 0 &&
2643 cpi->oxcf.allow_spatial_resampling &&
2644 cpi->oxcf.rc_mode == RC_MODE_VBR) {
2645 // Internal scaling is triggered on the first frame.
2646 vp9_set_size_literal(cpi, cpi->oxcf.scaled_frame_width,
2647 cpi->oxcf.scaled_frame_height);
2650 // Reset the frame pointers to the current frame size
2651 vp9_realloc_frame_buffer(get_frame_new_buffer(cm),
2652 cm->width, cm->height,
2653 cm->subsampling_x, cm->subsampling_y,
2654 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL);
2656 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2657 const int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, ref_frame)];
2658 YV12_BUFFER_CONFIG *const buf = &cm->frame_bufs[idx].buf;
2659 RefBuffer *const ref_buf = &cm->frame_refs[ref_frame - 1];
2662 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
2663 buf->y_crop_width, buf->y_crop_height,
2664 cm->width, cm->height);
2666 if (vp9_is_scaled(&ref_buf->sf))
2667 vp9_extend_frame_borders(buf);
2670 set_ref_ptrs(cm, xd, LAST_FRAME, LAST_FRAME);
2672 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
2676 if (cpi->pass == 1 &&
2677 (!cpi->use_svc || cpi->svc.number_temporal_layers == 1)) {
2678 Pass1Encode(cpi, size, dest, frame_flags);
2679 } else if (cpi->pass == 2 &&
2680 (!cpi->use_svc || cpi->svc.number_temporal_layers == 1)) {
2681 Pass2Encode(cpi, size, dest, frame_flags);
2682 } else if (cpi->use_svc) {
2683 SvcEncode(cpi, size, dest, frame_flags);
2686 Pass0Encode(cpi, size, dest, frame_flags);
2689 if (cm->refresh_frame_context)
2690 cm->frame_contexts[cm->frame_context_idx] = cm->fc;
2692 // Frame was dropped, release scaled references.
2694 release_scaled_references(cpi);
2698 cpi->droppable = !frame_is_reference(cpi);
2701 // Save layer specific state.
2702 if ((cpi->svc.number_temporal_layers > 1 &&
2703 cpi->oxcf.rc_mode == RC_MODE_CBR) ||
2704 (cpi->svc.number_spatial_layers > 1 && cpi->pass == 2)) {
2705 vp9_save_layer_context(cpi);
2708 vpx_usec_timer_mark(&cmptimer);
2709 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
2711 if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
2712 generate_psnr_packet(cpi);
2714 #if CONFIG_INTERNAL_STATS
2716 if (cpi->pass != 1) {
2717 cpi->bytes += (int)(*size);
2719 if (cm->show_frame) {
2722 if (cpi->b_calculate_psnr) {
2723 YV12_BUFFER_CONFIG *orig = cpi->Source;
2724 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
2725 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
2727 calc_psnr(orig, recon, &psnr);
2729 cpi->total += psnr.psnr[0];
2730 cpi->total_y += psnr.psnr[1];
2731 cpi->total_u += psnr.psnr[2];
2732 cpi->total_v += psnr.psnr[3];
2733 cpi->total_sq_error += psnr.sse[0];
2734 cpi->total_samples += psnr.samples[0];
2738 double frame_ssim2 = 0, weight = 0;
2739 #if CONFIG_VP9_POSTPROC
2740 vp9_deblock(cm->frame_to_show, &cm->post_proc_buffer,
2741 cm->lf.filter_level * 10 / 6);
2743 vp9_clear_system_state();
2745 calc_psnr(orig, pp, &psnr2);
2747 cpi->totalp += psnr2.psnr[0];
2748 cpi->totalp_y += psnr2.psnr[1];
2749 cpi->totalp_u += psnr2.psnr[2];
2750 cpi->totalp_v += psnr2.psnr[3];
2751 cpi->totalp_sq_error += psnr2.sse[0];
2752 cpi->totalp_samples += psnr2.samples[0];
2754 frame_ssim2 = vp9_calc_ssim(orig, recon, 1, &weight);
2756 cpi->summed_quality += frame_ssim2 * weight;
2757 cpi->summed_weights += weight;
2759 frame_ssim2 = vp9_calc_ssim(orig, &cm->post_proc_buffer, 1, &weight);
2761 cpi->summedp_quality += frame_ssim2 * weight;
2762 cpi->summedp_weights += weight;
2765 FILE *f = fopen("q_used.stt", "a");
2766 fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
2767 cpi->common.current_video_frame, y2, u2, v2,
2768 frame_psnr2, frame_ssim2);
2775 if (cpi->b_calculate_ssimg) {
2776 double y, u, v, frame_all;
2777 frame_all = vp9_calc_ssimg(cpi->Source, cm->frame_to_show, &y, &u, &v);
2778 cpi->total_ssimg_y += y;
2779 cpi->total_ssimg_u += u;
2780 cpi->total_ssimg_v += v;
2781 cpi->total_ssimg_all += frame_all;
2790 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
2791 vp9_ppflags_t *flags) {
2792 VP9_COMMON *cm = &cpi->common;
2794 if (!cm->show_frame) {
2798 #if CONFIG_VP9_POSTPROC
2799 ret = vp9_post_proc_frame(cm, dest, flags);
2802 if (cm->frame_to_show) {
2803 *dest = *cm->frame_to_show;
2804 dest->y_width = cm->width;
2805 dest->y_height = cm->height;
2806 dest->uv_width = cm->width >> cm->subsampling_x;
2807 dest->uv_height = cm->height >> cm->subsampling_y;
2813 #endif // !CONFIG_VP9_POSTPROC
2814 vp9_clear_system_state();
2819 int vp9_set_roimap(VP9_COMP *cpi, unsigned char *map, unsigned int rows,
2820 unsigned int cols, int delta_q[MAX_SEGMENTS],
2821 int delta_lf[MAX_SEGMENTS],
2822 unsigned int threshold[MAX_SEGMENTS]) {
2823 signed char feature_data[SEG_LVL_MAX][MAX_SEGMENTS];
2824 struct segmentation *seg = &cpi->common.seg;
2825 const VP9_COMMON *const cm = &cpi->common;
2828 if (cm->mb_rows != rows || cm->mb_cols != cols)
2832 vp9_disable_segmentation(seg);
2836 vpx_memcpy(cpi->segmentation_map, map, cm->mi_rows * cm->mi_cols);
2838 // Activate segmentation.
2839 vp9_enable_segmentation(seg);
2841 // Set up the quant, LF and breakout threshold segment data
2842 for (i = 0; i < MAX_SEGMENTS; i++) {
2843 feature_data[SEG_LVL_ALT_Q][i] = delta_q[i];
2844 feature_data[SEG_LVL_ALT_LF][i] = delta_lf[i];
2845 cpi->segment_encode_breakout[i] = threshold[i];
2848 // Enable the loop and quant changes in the feature mask
2849 for (i = 0; i < MAX_SEGMENTS; i++) {
2851 vp9_enable_segfeature(seg, i, SEG_LVL_ALT_Q);
2853 vp9_disable_segfeature(seg, i, SEG_LVL_ALT_Q);
2856 vp9_enable_segfeature(seg, i, SEG_LVL_ALT_LF);
2858 vp9_disable_segfeature(seg, i, SEG_LVL_ALT_LF);
2861 // Initialize the feature data structure
2862 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
2863 vp9_set_segment_data(seg, &feature_data[0][0], SEGMENT_DELTADATA);
2868 int vp9_set_active_map(VP9_COMP *cpi, unsigned char *map,
2869 unsigned int rows, unsigned int cols) {
2870 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
2872 vpx_memcpy(cpi->active_map, map, rows * cols);
2873 cpi->active_map_enabled = 1;
2875 cpi->active_map_enabled = 0;
2880 // cpi->active_map_enabled = 0;
2885 int vp9_set_internal_size(VP9_COMP *cpi,
2886 VPX_SCALING horiz_mode, VPX_SCALING vert_mode) {
2887 VP9_COMMON *cm = &cpi->common;
2888 int hr = 0, hs = 0, vr = 0, vs = 0;
2890 if (horiz_mode > ONETWO || vert_mode > ONETWO)
2893 Scale2Ratio(horiz_mode, &hr, &hs);
2894 Scale2Ratio(vert_mode, &vr, &vs);
2896 // always go to the next whole number
2897 cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
2898 cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
2900 assert(cm->width <= cpi->initial_width);
2901 assert(cm->height <= cpi->initial_height);
2902 update_frame_size(cpi);
2906 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
2907 unsigned int height) {
2908 VP9_COMMON *cm = &cpi->common;
2910 check_initial_width(cpi, 1, 1);
2914 if (cm->width * 5 < cpi->initial_width) {
2915 cm->width = cpi->initial_width / 5 + 1;
2916 printf("Warning: Desired width too small, changed to %d\n", cm->width);
2918 if (cm->width > cpi->initial_width) {
2919 cm->width = cpi->initial_width;
2920 printf("Warning: Desired width too large, changed to %d\n", cm->width);
2925 cm->height = height;
2926 if (cm->height * 5 < cpi->initial_height) {
2927 cm->height = cpi->initial_height / 5 + 1;
2928 printf("Warning: Desired height too small, changed to %d\n", cm->height);
2930 if (cm->height > cpi->initial_height) {
2931 cm->height = cpi->initial_height;
2932 printf("Warning: Desired height too large, changed to %d\n", cm->height);
2936 assert(cm->width <= cpi->initial_width);
2937 assert(cm->height <= cpi->initial_height);
2938 update_frame_size(cpi);
2942 void vp9_set_svc(VP9_COMP *cpi, int use_svc) {
2943 cpi->use_svc = use_svc;
2947 int vp9_get_y_sse(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b) {
2948 assert(a->y_crop_width == b->y_crop_width);
2949 assert(a->y_crop_height == b->y_crop_height);
2951 return (int)get_sse(a->y_buffer, a->y_stride, b->y_buffer, b->y_stride,
2952 a->y_crop_width, a->y_crop_height);
2956 int vp9_get_quantizer(VP9_COMP *cpi) {
2957 return cpi->common.base_qindex;