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"
18 #include "vp9/common/vp9_alloccommon.h"
19 #include "vp9/common/vp9_filter.h"
20 #include "vp9/common/vp9_idct.h"
21 #if CONFIG_VP9_POSTPROC
22 #include "vp9/common/vp9_postproc.h"
24 #include "vp9/common/vp9_reconinter.h"
25 #include "vp9/common/vp9_systemdependent.h"
26 #include "vp9/common/vp9_tile_common.h"
28 #include "vp9/encoder/vp9_encodemv.h"
29 #include "vp9/encoder/vp9_firstpass.h"
30 #include "vp9/encoder/vp9_mbgraph.h"
31 #include "vp9/encoder/vp9_onyx_int.h"
32 #include "vp9/encoder/vp9_picklpf.h"
33 #include "vp9/encoder/vp9_psnr.h"
34 #include "vp9/encoder/vp9_ratectrl.h"
35 #include "vp9/encoder/vp9_rdopt.h"
36 #include "vp9/encoder/vp9_segmentation.h"
37 #include "vp9/encoder/vp9_temporal_filter.h"
38 #include "vp9/encoder/vp9_vaq.h"
40 #include "vpx_ports/vpx_timer.h"
42 static void set_default_lf_deltas(struct loopfilter *lf);
44 #define DEFAULT_INTERP_FILTER SWITCHABLE
46 #define SHARP_FILTER_QTHRESH 0 /* Q threshold for 8-tap sharp filter */
48 #define ALTREF_HIGH_PRECISION_MV 1 // Whether to use high precision mv
49 // for altref computation.
50 #define HIGH_PRECISION_MV_QTHRESH 200 // Q threshold for high precision
51 // mv. Choose a very high value for
52 // now so that HIGH_PRECISION is always
55 // Masks for partially or completely disabling split mode
56 #define DISABLE_ALL_SPLIT 0x3F
57 #define DISABLE_ALL_INTER_SPLIT 0x1F
58 #define DISABLE_COMPOUND_SPLIT 0x18
59 #define LAST_AND_INTRA_SPLIT_ONLY 0x1E
61 #if CONFIG_INTERNAL_STATS
62 extern double vp9_calc_ssim(YV12_BUFFER_CONFIG *source,
63 YV12_BUFFER_CONFIG *dest, int lumamask,
67 extern double vp9_calc_ssimg(YV12_BUFFER_CONFIG *source,
68 YV12_BUFFER_CONFIG *dest, double *ssim_y,
69 double *ssim_u, double *ssim_v);
74 // #define OUTPUT_YUV_REC
91 extern int intra_mode_stats[INTRA_MODES]
97 extern void init_tx_count_stats();
98 extern void write_tx_count_stats();
99 extern void init_switchable_interp_stats();
100 extern void write_switchable_interp_stats();
104 unsigned int frames_at_speed[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
108 #if defined(SECTIONBITS_OUTPUT)
109 extern unsigned __int64 Sectionbits[500];
112 extern void vp9_init_quantizer(VP9_COMP *cpi);
114 static const double in_frame_q_adj_ratio[MAX_SEGMENTS] =
115 {1.0, 1.5, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0};
117 static INLINE void Scale2Ratio(int mode, int *hr, int *hs) {
143 static void set_mvcost(VP9_COMP *cpi) {
144 MACROBLOCK *const mb = &cpi->mb;
145 if (cpi->common.allow_high_precision_mv) {
146 mb->mvcost = mb->nmvcost_hp;
147 mb->mvsadcost = mb->nmvsadcost_hp;
149 mb->mvcost = mb->nmvcost;
150 mb->mvsadcost = mb->nmvsadcost;
154 void vp9_initialize_enc() {
155 static int init_done = 0;
158 vp9_initialize_common();
159 vp9_tokenize_initialize();
160 vp9_init_quant_tables();
162 vp9_init_minq_luts();
163 // init_base_skip_probs();
164 vp9_entropy_mv_init();
169 static void setup_features(VP9_COMMON *cm) {
170 struct loopfilter *const lf = &cm->lf;
171 struct segmentation *const seg = &cm->seg;
173 // Set up default state for MB feature flags
177 seg->update_data = 0;
178 vpx_memset(seg->tree_probs, 255, sizeof(seg->tree_probs));
180 vp9_clearall_segfeatures(seg);
182 lf->mode_ref_delta_enabled = 0;
183 lf->mode_ref_delta_update = 0;
184 vp9_zero(lf->ref_deltas);
185 vp9_zero(lf->mode_deltas);
186 vp9_zero(lf->last_ref_deltas);
187 vp9_zero(lf->last_mode_deltas);
189 set_default_lf_deltas(lf);
192 static void dealloc_compressor_data(VP9_COMP *cpi) {
193 // Delete sementation map
194 vpx_free(cpi->segmentation_map);
195 cpi->segmentation_map = 0;
196 vpx_free(cpi->common.last_frame_seg_map);
197 cpi->common.last_frame_seg_map = 0;
198 vpx_free(cpi->coding_context.last_frame_seg_map_copy);
199 cpi->coding_context.last_frame_seg_map_copy = 0;
201 vpx_free(cpi->complexity_map);
202 cpi->complexity_map = 0;
203 vpx_free(cpi->active_map);
206 vp9_free_frame_buffers(&cpi->common);
208 vp9_free_frame_buffer(&cpi->last_frame_uf);
209 vp9_free_frame_buffer(&cpi->scaled_source);
210 vp9_free_frame_buffer(&cpi->alt_ref_buffer);
211 vp9_lookahead_destroy(cpi->lookahead);
216 // Activity mask based per mb zbin adjustments
217 vpx_free(cpi->mb_activity_map);
218 cpi->mb_activity_map = 0;
219 vpx_free(cpi->mb_norm_activity_map);
220 cpi->mb_norm_activity_map = 0;
222 vpx_free(cpi->above_context[0]);
223 cpi->above_context[0] = NULL;
225 vpx_free(cpi->above_seg_context);
226 cpi->above_seg_context = NULL;
229 // Computes a q delta (in "q index" terms) to get from a starting q value
232 int vp9_compute_qdelta(VP9_COMP *cpi, double qstart, double qtarget) {
234 int start_index = cpi->rc.worst_quality;
235 int target_index = cpi->rc.worst_quality;
237 // Convert the average q value to an index.
238 for (i = cpi->rc.best_quality; i < cpi->rc.worst_quality; i++) {
240 if (vp9_convert_qindex_to_q(i) >= qstart)
244 // Convert the q target to an index
245 for (i = cpi->rc.best_quality; i < cpi->rc.worst_quality; i++) {
247 if (vp9_convert_qindex_to_q(i) >= qtarget)
251 return target_index - start_index;
254 // Computes a q delta (in "q index" terms) to get from a starting q value
255 // to a value that should equate to thegiven rate ratio.
257 int vp9_compute_qdelta_by_rate(VP9_COMP *cpi,
258 double base_q_index, double rate_target_ratio) {
260 int base_bits_per_mb;
261 int target_bits_per_mb;
262 int target_index = cpi->rc.worst_quality;
264 // Make SURE use of floating point in this function is safe.
265 vp9_clear_system_state();
267 // Look up the current projected bits per block for the base index
268 base_bits_per_mb = vp9_bits_per_mb(cpi->common.frame_type,
271 // Find the target bits per mb based on the base value and given ratio.
272 target_bits_per_mb = rate_target_ratio * base_bits_per_mb;
274 // Convert the q target to an index
275 for (i = cpi->rc.best_quality; i < cpi->rc.worst_quality; i++) {
277 if (vp9_bits_per_mb(cpi->common.frame_type,
278 i, 1.0) <= target_bits_per_mb )
282 return target_index - base_q_index;
285 // This function sets up a set of segments with delta Q values around
286 // the baseline frame quantizer.
287 static void setup_in_frame_q_adj(VP9_COMP *cpi) {
288 VP9_COMMON *cm = &cpi->common;
289 struct segmentation *seg = &cm->seg;
294 // Make SURE use of floating point in this function is safe.
295 vp9_clear_system_state();
297 if (cm->frame_type == KEY_FRAME ||
298 cpi->refresh_alt_ref_frame ||
299 (cpi->refresh_golden_frame && !cpi->is_src_frame_alt_ref)) {
300 // Clear down the segment map
301 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
303 // Clear down the complexity map used for rd
304 vpx_memset(cpi->complexity_map, 0, cm->mi_rows * cm->mi_cols);
306 // Enable segmentation
307 vp9_enable_segmentation((VP9_PTR)cpi);
308 vp9_clearall_segfeatures(seg);
310 // Select delta coding method
311 seg->abs_delta = SEGMENT_DELTADATA;
313 // Segment 0 "Q" feature is disabled so it defaults to the baseline Q
314 vp9_disable_segfeature(seg, 0, SEG_LVL_ALT_Q);
316 // Use some of the segments for in frame Q adjustment
317 for (segment = 1; segment < 3; segment++) {
319 vp9_compute_qdelta_by_rate(cpi, cm->base_qindex,
320 in_frame_q_adj_ratio[segment]);
321 vp9_enable_segfeature(seg, segment, SEG_LVL_ALT_Q);
322 vp9_set_segdata(seg, segment, SEG_LVL_ALT_Q, qindex_delta);
327 static void configure_static_seg_features(VP9_COMP *cpi) {
328 VP9_COMMON *cm = &cpi->common;
329 struct segmentation *seg = &cm->seg;
331 int high_q = (int)(cpi->rc.avg_q > 48.0);
334 // Disable and clear down for KF
335 if (cm->frame_type == KEY_FRAME) {
336 // Clear down the global segmentation map
337 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
339 seg->update_data = 0;
340 cpi->static_mb_pct = 0;
342 // Disable segmentation
343 vp9_disable_segmentation((VP9_PTR)cpi);
345 // Clear down the segment features.
346 vp9_clearall_segfeatures(seg);
347 } else if (cpi->refresh_alt_ref_frame) {
348 // If this is an alt ref frame
349 // Clear down the global segmentation map
350 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
352 seg->update_data = 0;
353 cpi->static_mb_pct = 0;
355 // Disable segmentation and individual segment features by default
356 vp9_disable_segmentation((VP9_PTR)cpi);
357 vp9_clearall_segfeatures(seg);
359 // Scan frames from current to arf frame.
360 // This function re-enables segmentation if appropriate.
361 vp9_update_mbgraph_stats(cpi);
363 // If segmentation was enabled set those features needed for the
367 seg->update_data = 1;
369 qi_delta = vp9_compute_qdelta(
370 cpi, cpi->rc.avg_q, (cpi->rc.avg_q * 0.875));
371 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, (qi_delta - 2));
372 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
374 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
375 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
377 // Where relevant assume segment data is delta data
378 seg->abs_delta = SEGMENT_DELTADATA;
380 } else if (seg->enabled) {
381 // All other frames if segmentation has been enabled
383 // First normal frame in a valid gf or alt ref group
384 if (cpi->rc.frames_since_golden == 0) {
385 // Set up segment features for normal frames in an arf group
386 if (cpi->source_alt_ref_active) {
388 seg->update_data = 1;
389 seg->abs_delta = SEGMENT_DELTADATA;
391 qi_delta = vp9_compute_qdelta(cpi, cpi->rc.avg_q,
392 (cpi->rc.avg_q * 1.125));
393 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, (qi_delta + 2));
394 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
396 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
397 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
399 // Segment coding disabled for compred testing
400 if (high_q || (cpi->static_mb_pct == 100)) {
401 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
402 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
403 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
406 // Disable segmentation and clear down features if alt ref
407 // is not active for this group
409 vp9_disable_segmentation((VP9_PTR)cpi);
411 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
414 seg->update_data = 0;
416 vp9_clearall_segfeatures(seg);
418 } else if (cpi->is_src_frame_alt_ref) {
419 // Special case where we are coding over the top of a previous
421 // Segment coding disabled for compred testing
423 // Enable ref frame features for segment 0 as well
424 vp9_enable_segfeature(seg, 0, SEG_LVL_REF_FRAME);
425 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
427 // All mbs should use ALTREF_FRAME
428 vp9_clear_segdata(seg, 0, SEG_LVL_REF_FRAME);
429 vp9_set_segdata(seg, 0, SEG_LVL_REF_FRAME, ALTREF_FRAME);
430 vp9_clear_segdata(seg, 1, SEG_LVL_REF_FRAME);
431 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
433 // Skip all MBs if high Q (0,0 mv and skip coeffs)
435 vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
436 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
438 // Enable data update
439 seg->update_data = 1;
443 // No updates.. leave things as they are.
445 seg->update_data = 0;
450 // DEBUG: Print out the segment id of each MB in the current frame.
451 static void print_seg_map(VP9_COMP *cpi) {
452 VP9_COMMON *cm = &cpi->common;
455 FILE *statsfile = fopen("segmap.stt", "a");
457 fprintf(statsfile, "%10d\n", cm->current_video_frame);
459 for (row = 0; row < cpi->common.mi_rows; row++) {
460 for (col = 0; col < cpi->common.mi_cols; col++) {
461 fprintf(statsfile, "%10d", cpi->segmentation_map[map_index]);
464 fprintf(statsfile, "\n");
466 fprintf(statsfile, "\n");
471 static void update_reference_segmentation_map(VP9_COMP *cpi) {
472 VP9_COMMON *const cm = &cpi->common;
474 MODE_INFO **mi_8x8, **mi_8x8_ptr = cm->mi_grid_visible;
475 uint8_t *cache_ptr = cm->last_frame_seg_map, *cache;
477 for (row = 0; row < cm->mi_rows; row++) {
480 for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
481 cache[0] = mi_8x8[0]->mbmi.segment_id;
482 mi_8x8_ptr += cm->mode_info_stride;
483 cache_ptr += cm->mi_cols;
487 static void set_default_lf_deltas(struct loopfilter *lf) {
488 lf->mode_ref_delta_enabled = 1;
489 lf->mode_ref_delta_update = 1;
491 vp9_zero(lf->ref_deltas);
492 vp9_zero(lf->mode_deltas);
494 // Test of ref frame deltas
495 lf->ref_deltas[INTRA_FRAME] = 2;
496 lf->ref_deltas[LAST_FRAME] = 0;
497 lf->ref_deltas[GOLDEN_FRAME] = -2;
498 lf->ref_deltas[ALTREF_FRAME] = -2;
500 lf->mode_deltas[0] = 0; // Zero
501 lf->mode_deltas[1] = 0; // New mv
504 static void set_rd_speed_thresholds(VP9_COMP *cpi, int mode) {
505 SPEED_FEATURES *sf = &cpi->sf;
508 // Set baseline threshold values
509 for (i = 0; i < MAX_MODES; ++i)
510 sf->thresh_mult[i] = mode == 0 ? -500 : 0;
512 sf->thresh_mult[THR_NEARESTMV] = 0;
513 sf->thresh_mult[THR_NEARESTG] = 0;
514 sf->thresh_mult[THR_NEARESTA] = 0;
516 sf->thresh_mult[THR_DC] += 1000;
518 sf->thresh_mult[THR_NEWMV] += 1000;
519 sf->thresh_mult[THR_NEWA] += 1000;
520 sf->thresh_mult[THR_NEWG] += 1000;
522 sf->thresh_mult[THR_NEARMV] += 1000;
523 sf->thresh_mult[THR_NEARA] += 1000;
524 sf->thresh_mult[THR_COMP_NEARESTLA] += 1000;
525 sf->thresh_mult[THR_COMP_NEARESTGA] += 1000;
527 sf->thresh_mult[THR_TM] += 1000;
529 sf->thresh_mult[THR_COMP_NEARLA] += 1500;
530 sf->thresh_mult[THR_COMP_NEWLA] += 2000;
531 sf->thresh_mult[THR_NEARG] += 1000;
532 sf->thresh_mult[THR_COMP_NEARGA] += 1500;
533 sf->thresh_mult[THR_COMP_NEWGA] += 2000;
535 sf->thresh_mult[THR_ZEROMV] += 2000;
536 sf->thresh_mult[THR_ZEROG] += 2000;
537 sf->thresh_mult[THR_ZEROA] += 2000;
538 sf->thresh_mult[THR_COMP_ZEROLA] += 2500;
539 sf->thresh_mult[THR_COMP_ZEROGA] += 2500;
541 sf->thresh_mult[THR_H_PRED] += 2000;
542 sf->thresh_mult[THR_V_PRED] += 2000;
543 sf->thresh_mult[THR_D45_PRED ] += 2500;
544 sf->thresh_mult[THR_D135_PRED] += 2500;
545 sf->thresh_mult[THR_D117_PRED] += 2500;
546 sf->thresh_mult[THR_D153_PRED] += 2500;
547 sf->thresh_mult[THR_D207_PRED] += 2500;
548 sf->thresh_mult[THR_D63_PRED] += 2500;
550 /* disable frame modes if flags not set */
551 if (!(cpi->ref_frame_flags & VP9_LAST_FLAG)) {
552 sf->thresh_mult[THR_NEWMV ] = INT_MAX;
553 sf->thresh_mult[THR_NEARESTMV] = INT_MAX;
554 sf->thresh_mult[THR_ZEROMV ] = INT_MAX;
555 sf->thresh_mult[THR_NEARMV ] = INT_MAX;
557 if (!(cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
558 sf->thresh_mult[THR_NEARESTG ] = INT_MAX;
559 sf->thresh_mult[THR_ZEROG ] = INT_MAX;
560 sf->thresh_mult[THR_NEARG ] = INT_MAX;
561 sf->thresh_mult[THR_NEWG ] = INT_MAX;
563 if (!(cpi->ref_frame_flags & VP9_ALT_FLAG)) {
564 sf->thresh_mult[THR_NEARESTA ] = INT_MAX;
565 sf->thresh_mult[THR_ZEROA ] = INT_MAX;
566 sf->thresh_mult[THR_NEARA ] = INT_MAX;
567 sf->thresh_mult[THR_NEWA ] = INT_MAX;
570 if ((cpi->ref_frame_flags & (VP9_LAST_FLAG | VP9_ALT_FLAG)) !=
571 (VP9_LAST_FLAG | VP9_ALT_FLAG)) {
572 sf->thresh_mult[THR_COMP_ZEROLA ] = INT_MAX;
573 sf->thresh_mult[THR_COMP_NEARESTLA] = INT_MAX;
574 sf->thresh_mult[THR_COMP_NEARLA ] = INT_MAX;
575 sf->thresh_mult[THR_COMP_NEWLA ] = INT_MAX;
577 if ((cpi->ref_frame_flags & (VP9_GOLD_FLAG | VP9_ALT_FLAG)) !=
578 (VP9_GOLD_FLAG | VP9_ALT_FLAG)) {
579 sf->thresh_mult[THR_COMP_ZEROGA ] = INT_MAX;
580 sf->thresh_mult[THR_COMP_NEARESTGA] = INT_MAX;
581 sf->thresh_mult[THR_COMP_NEARGA ] = INT_MAX;
582 sf->thresh_mult[THR_COMP_NEWGA ] = INT_MAX;
586 static void set_rd_speed_thresholds_sub8x8(VP9_COMP *cpi, int mode) {
587 SPEED_FEATURES *sf = &cpi->sf;
590 for (i = 0; i < MAX_REFS; ++i)
591 sf->thresh_mult_sub8x8[i] = mode == 0 ? -500 : 0;
593 sf->thresh_mult_sub8x8[THR_LAST] += 2500;
594 sf->thresh_mult_sub8x8[THR_GOLD] += 2500;
595 sf->thresh_mult_sub8x8[THR_ALTR] += 2500;
596 sf->thresh_mult_sub8x8[THR_INTRA] += 2500;
597 sf->thresh_mult_sub8x8[THR_COMP_LA] += 4500;
598 sf->thresh_mult_sub8x8[THR_COMP_GA] += 4500;
600 // Check for masked out split cases.
601 for (i = 0; i < MAX_REFS; i++) {
602 if (sf->disable_split_mask & (1 << i))
603 sf->thresh_mult_sub8x8[i] = INT_MAX;
606 // disable mode test if frame flag is not set
607 if (!(cpi->ref_frame_flags & VP9_LAST_FLAG))
608 sf->thresh_mult_sub8x8[THR_LAST] = INT_MAX;
609 if (!(cpi->ref_frame_flags & VP9_GOLD_FLAG))
610 sf->thresh_mult_sub8x8[THR_GOLD] = INT_MAX;
611 if (!(cpi->ref_frame_flags & VP9_ALT_FLAG))
612 sf->thresh_mult_sub8x8[THR_ALTR] = INT_MAX;
613 if ((cpi->ref_frame_flags & (VP9_LAST_FLAG | VP9_ALT_FLAG)) !=
614 (VP9_LAST_FLAG | VP9_ALT_FLAG))
615 sf->thresh_mult_sub8x8[THR_COMP_LA] = INT_MAX;
616 if ((cpi->ref_frame_flags & (VP9_GOLD_FLAG | VP9_ALT_FLAG)) !=
617 (VP9_GOLD_FLAG | VP9_ALT_FLAG))
618 sf->thresh_mult_sub8x8[THR_COMP_GA] = INT_MAX;
621 void vp9_set_speed_features(VP9_COMP *cpi) {
622 SPEED_FEATURES *sf = &cpi->sf;
623 int mode = cpi->compressor_speed;
624 int speed = cpi->speed;
627 // Only modes 0 and 1 supported for now in experimental code basae
631 for (i = 0; i < MAX_MODES; ++i)
632 cpi->mode_chosen_counts[i] = 0;
634 // best quality defaults
636 sf->search_method = NSTEP;
639 sf->subpel_search_method = SUBPEL_TREE;
640 sf->subpel_iters_per_step = 2;
641 sf->optimize_coefficients = !cpi->oxcf.lossless;
642 sf->reduce_first_step_size = 0;
643 sf->auto_mv_step_size = 0;
644 sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
645 sf->comp_inter_joint_search_thresh = BLOCK_4X4;
646 sf->adaptive_rd_thresh = 0;
647 sf->use_lastframe_partitioning = LAST_FRAME_PARTITION_OFF;
648 sf->tx_size_search_method = USE_FULL_RD;
649 sf->use_lp32x32fdct = 0;
650 sf->adaptive_motion_search = 0;
651 sf->use_avoid_tested_higherror = 0;
652 sf->reference_masking = 0;
653 sf->use_one_partition_size_always = 0;
654 sf->less_rectangular_check = 0;
655 sf->use_square_partition_only = 0;
656 sf->auto_min_max_partition_size = 0;
657 sf->max_partition_size = BLOCK_64X64;
658 sf->min_partition_size = BLOCK_4X4;
659 sf->adjust_partitioning_from_last_frame = 0;
660 sf->last_partitioning_redo_frequency = 4;
661 sf->disable_split_mask = 0;
662 sf->mode_search_skip_flags = 0;
663 sf->disable_split_var_thresh = 0;
664 sf->disable_filter_search_var_thresh = 0;
665 for (i = 0; i < TX_SIZES; i++) {
666 sf->intra_y_mode_mask[i] = ALL_INTRA_MODES;
667 sf->intra_uv_mode_mask[i] = ALL_INTRA_MODES;
669 sf->use_rd_breakout = 0;
670 sf->skip_encode_sb = 0;
671 sf->use_uv_intra_rd_estimate = 0;
672 sf->use_fast_lpf_pick = 0;
673 sf->use_fast_coef_updates = 0;
674 sf->using_small_partition_info = 0;
675 sf->mode_skip_start = MAX_MODES; // Mode index at which mode skip mask set
677 #if CONFIG_MULTIPLE_ARF
678 // Switch segmentation off.
679 sf->static_segmentation = 0;
681 sf->static_segmentation = 0;
685 case 0: // This is the best quality mode.
689 #if CONFIG_MULTIPLE_ARF
690 // Switch segmentation off.
691 sf->static_segmentation = 0;
693 sf->static_segmentation = 0;
695 sf->use_avoid_tested_higherror = 1;
696 sf->adaptive_rd_thresh = 1;
697 sf->recode_loop = (speed < 1);
700 sf->use_square_partition_only = !frame_is_intra_only(&cpi->common);
701 sf->less_rectangular_check = 1;
702 sf->tx_size_search_method = frame_is_intra_only(&cpi->common)
703 ? USE_FULL_RD : USE_LARGESTALL;
705 if (MIN(cpi->common.width, cpi->common.height) >= 720)
706 sf->disable_split_mask = cpi->common.show_frame ?
707 DISABLE_ALL_SPLIT : DISABLE_ALL_INTER_SPLIT;
709 sf->disable_split_mask = DISABLE_COMPOUND_SPLIT;
711 sf->use_rd_breakout = 1;
712 sf->adaptive_motion_search = 1;
713 sf->auto_mv_step_size = 1;
714 sf->adaptive_rd_thresh = 2;
716 sf->intra_y_mode_mask[TX_32X32] = INTRA_DC_H_V;
717 sf->intra_uv_mode_mask[TX_32X32] = INTRA_DC_H_V;
718 sf->intra_uv_mode_mask[TX_16X16] = INTRA_DC_H_V;
721 sf->use_square_partition_only = !frame_is_intra_only(&cpi->common);
722 sf->less_rectangular_check = 1;
723 sf->tx_size_search_method = frame_is_intra_only(&cpi->common)
724 ? USE_FULL_RD : USE_LARGESTALL;
726 if (MIN(cpi->common.width, cpi->common.height) >= 720)
727 sf->disable_split_mask = cpi->common.show_frame ?
728 DISABLE_ALL_SPLIT : DISABLE_ALL_INTER_SPLIT;
730 sf->disable_split_mask = LAST_AND_INTRA_SPLIT_ONLY;
733 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
734 FLAG_SKIP_INTRA_BESTINTER |
735 FLAG_SKIP_COMP_BESTINTRA |
736 FLAG_SKIP_INTRA_LOWVAR;
738 sf->use_rd_breakout = 1;
739 sf->adaptive_motion_search = 1;
740 sf->auto_mv_step_size = 1;
742 sf->disable_filter_search_var_thresh = 16;
743 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
745 sf->auto_min_max_partition_size = 1;
746 sf->use_lastframe_partitioning = LAST_FRAME_PARTITION_LOW_MOTION;
747 sf->adjust_partitioning_from_last_frame = 1;
748 sf->last_partitioning_redo_frequency = 3;
750 sf->adaptive_rd_thresh = 2;
752 sf->use_lp32x32fdct = 1;
753 sf->mode_skip_start = 11;
754 sf->intra_y_mode_mask[TX_32X32] = INTRA_DC_H_V;
755 sf->intra_y_mode_mask[TX_16X16] = INTRA_DC_H_V;
756 sf->intra_uv_mode_mask[TX_32X32] = INTRA_DC_H_V;
757 sf->intra_uv_mode_mask[TX_16X16] = INTRA_DC_H_V;
760 sf->use_square_partition_only = 1;
761 sf->tx_size_search_method = USE_LARGESTALL;
763 if (MIN(cpi->common.width, cpi->common.height) >= 720)
764 sf->disable_split_mask = DISABLE_ALL_SPLIT;
766 sf->disable_split_mask = DISABLE_ALL_INTER_SPLIT;
768 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
769 FLAG_SKIP_INTRA_BESTINTER |
770 FLAG_SKIP_COMP_BESTINTRA |
771 FLAG_SKIP_INTRA_LOWVAR;
773 sf->use_rd_breakout = 1;
774 sf->adaptive_motion_search = 1;
775 sf->auto_mv_step_size = 1;
777 sf->disable_filter_search_var_thresh = 16;
778 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
780 sf->auto_min_max_partition_size = 1;
781 sf->use_lastframe_partitioning = LAST_FRAME_PARTITION_ALL;
782 sf->adjust_partitioning_from_last_frame = 1;
783 sf->last_partitioning_redo_frequency = 3;
785 sf->use_uv_intra_rd_estimate = 1;
786 sf->skip_encode_sb = 1;
787 sf->use_lp32x32fdct = 1;
788 sf->subpel_iters_per_step = 1;
789 sf->use_fast_coef_updates = 2;
791 sf->adaptive_rd_thresh = 4;
792 sf->mode_skip_start = 6;
795 sf->use_square_partition_only = 1;
796 sf->tx_size_search_method = USE_LARGESTALL;
797 sf->disable_split_mask = DISABLE_ALL_SPLIT;
799 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
800 FLAG_SKIP_INTRA_BESTINTER |
801 FLAG_SKIP_COMP_BESTINTRA |
802 FLAG_SKIP_COMP_REFMISMATCH |
803 FLAG_SKIP_INTRA_LOWVAR |
804 FLAG_EARLY_TERMINATE;
806 sf->use_rd_breakout = 1;
807 sf->adaptive_motion_search = 1;
808 sf->auto_mv_step_size = 1;
810 sf->disable_filter_search_var_thresh = 16;
811 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
813 sf->auto_min_max_partition_size = 1;
814 sf->use_lastframe_partitioning = LAST_FRAME_PARTITION_ALL;
815 sf->adjust_partitioning_from_last_frame = 1;
816 sf->last_partitioning_redo_frequency = 3;
818 sf->use_uv_intra_rd_estimate = 1;
819 sf->skip_encode_sb = 1;
820 sf->use_lp32x32fdct = 1;
821 sf->subpel_iters_per_step = 1;
822 sf->use_fast_coef_updates = 2;
824 sf->adaptive_rd_thresh = 4;
825 sf->mode_skip_start = 6;
827 /* sf->intra_y_mode_mask = INTRA_DC_ONLY;
828 sf->intra_uv_mode_mask = INTRA_DC_ONLY;
829 sf->search_method = BIGDIA;
830 sf->disable_split_var_thresh = 64;
831 sf->disable_filter_search_var_thresh = 64; */
834 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
835 sf->use_one_partition_size_always = 1;
836 sf->always_this_block_size = BLOCK_16X16;
837 sf->tx_size_search_method = frame_is_intra_only(&cpi->common) ?
838 USE_FULL_RD : USE_LARGESTALL;
839 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
840 FLAG_SKIP_INTRA_BESTINTER |
841 FLAG_SKIP_COMP_BESTINTRA |
842 FLAG_SKIP_COMP_REFMISMATCH |
843 FLAG_SKIP_INTRA_LOWVAR |
844 FLAG_EARLY_TERMINATE;
845 sf->use_rd_breakout = 1;
846 sf->use_lp32x32fdct = 1;
847 sf->optimize_coefficients = 0;
848 sf->auto_mv_step_size = 1;
849 // sf->reduce_first_step_size = 1;
850 // sf->reference_masking = 1;
852 sf->disable_split_mask = DISABLE_ALL_SPLIT;
853 sf->search_method = HEX;
854 sf->subpel_iters_per_step = 1;
855 sf->disable_split_var_thresh = 64;
856 sf->disable_filter_search_var_thresh = 96;
857 for (i = 0; i < TX_SIZES; i++) {
858 sf->intra_y_mode_mask[i] = INTRA_DC_ONLY;
859 sf->intra_uv_mode_mask[i] = INTRA_DC_ONLY;
861 sf->use_fast_coef_updates = 2;
862 sf->adaptive_rd_thresh = 4;
863 sf->mode_skip_start = 6;
868 // Set rd thresholds based on mode and speed setting
869 set_rd_speed_thresholds(cpi, mode);
870 set_rd_speed_thresholds_sub8x8(cpi, mode);
872 // Slow quant, dct and trellis not worthwhile for first pass
873 // so make sure they are always turned off.
874 if (cpi->pass == 1) {
875 sf->optimize_coefficients = 0;
878 // No recode for 1 pass.
879 if (cpi->pass == 0) {
881 sf->optimize_coefficients = 0;
884 cpi->mb.fwd_txm4x4 = vp9_fdct4x4;
885 if (cpi->oxcf.lossless || cpi->mb.e_mbd.lossless) {
886 cpi->mb.fwd_txm4x4 = vp9_fwht4x4;
889 if (cpi->sf.subpel_search_method == SUBPEL_ITERATIVE) {
890 cpi->find_fractional_mv_step = vp9_find_best_sub_pixel_iterative;
891 cpi->find_fractional_mv_step_comp = vp9_find_best_sub_pixel_comp_iterative;
892 } else if (cpi->sf.subpel_search_method == SUBPEL_TREE) {
893 cpi->find_fractional_mv_step = vp9_find_best_sub_pixel_tree;
894 cpi->find_fractional_mv_step_comp = vp9_find_best_sub_pixel_comp_tree;
897 cpi->mb.optimize = cpi->sf.optimize_coefficients == 1 && cpi->pass != 1;
900 frames_at_speed[cpi->speed]++;
904 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
905 VP9_COMMON *cm = &cpi->common;
907 cpi->lookahead = vp9_lookahead_init(cpi->oxcf.width, cpi->oxcf.height,
908 cm->subsampling_x, cm->subsampling_y,
909 cpi->oxcf.lag_in_frames);
911 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
912 "Failed to allocate lag buffers");
914 if (vp9_realloc_frame_buffer(&cpi->alt_ref_buffer,
915 cpi->oxcf.width, cpi->oxcf.height,
916 cm->subsampling_x, cm->subsampling_y,
918 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
919 "Failed to allocate altref buffer");
922 void vp9_alloc_compressor_data(VP9_COMP *cpi) {
923 VP9_COMMON *cm = &cpi->common;
925 if (vp9_alloc_frame_buffers(cm, cm->width, cm->height))
926 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
927 "Failed to allocate frame buffers");
929 if (vp9_alloc_frame_buffer(&cpi->last_frame_uf,
930 cm->width, cm->height,
931 cm->subsampling_x, cm->subsampling_y,
933 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
934 "Failed to allocate last frame buffer");
936 if (vp9_alloc_frame_buffer(&cpi->scaled_source,
937 cm->width, cm->height,
938 cm->subsampling_x, cm->subsampling_y,
940 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
941 "Failed to allocate scaled source buffer");
946 unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
948 CHECK_MEM_ERROR(cm, cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
951 vpx_free(cpi->mb_activity_map);
952 CHECK_MEM_ERROR(cm, cpi->mb_activity_map,
953 vpx_calloc(sizeof(unsigned int),
954 cm->mb_rows * cm->mb_cols));
956 vpx_free(cpi->mb_norm_activity_map);
957 CHECK_MEM_ERROR(cm, cpi->mb_norm_activity_map,
958 vpx_calloc(sizeof(unsigned int),
959 cm->mb_rows * cm->mb_cols));
961 // 2 contexts per 'mi unit', so that we have one context per 4x4 txfm
962 // block where mi unit size is 8x8.
963 vpx_free(cpi->above_context[0]);
964 CHECK_MEM_ERROR(cm, cpi->above_context[0],
965 vpx_calloc(2 * mi_cols_aligned_to_sb(cm->mi_cols) *
967 sizeof(*cpi->above_context[0])));
969 vpx_free(cpi->above_seg_context);
970 CHECK_MEM_ERROR(cm, cpi->above_seg_context,
971 vpx_calloc(mi_cols_aligned_to_sb(cm->mi_cols),
972 sizeof(*cpi->above_seg_context)));
976 static void update_frame_size(VP9_COMP *cpi) {
977 VP9_COMMON *cm = &cpi->common;
979 vp9_update_frame_size(cm);
981 // Update size of buffers local to this frame
982 if (vp9_realloc_frame_buffer(&cpi->last_frame_uf,
983 cm->width, cm->height,
984 cm->subsampling_x, cm->subsampling_y,
986 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
987 "Failed to reallocate last frame buffer");
989 if (vp9_realloc_frame_buffer(&cpi->scaled_source,
990 cm->width, cm->height,
991 cm->subsampling_x, cm->subsampling_y,
993 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
994 "Failed to reallocate scaled source buffer");
997 int y_stride = cpi->scaled_source.y_stride;
999 if (cpi->sf.search_method == NSTEP) {
1000 vp9_init3smotion_compensation(&cpi->mb, y_stride);
1001 } else if (cpi->sf.search_method == DIAMOND) {
1002 vp9_init_dsmotion_compensation(&cpi->mb, y_stride);
1008 for (i = 1; i < MAX_MB_PLANE; ++i) {
1009 cpi->above_context[i] = cpi->above_context[0] +
1010 i * sizeof(*cpi->above_context[0]) * 2 *
1011 mi_cols_aligned_to_sb(cm->mi_cols);
1017 // Table that converts 0-63 Q range values passed in outside to the Qindex
1018 // range used internally.
1019 static const int q_trans[] = {
1020 0, 4, 8, 12, 16, 20, 24, 28,
1021 32, 36, 40, 44, 48, 52, 56, 60,
1022 64, 68, 72, 76, 80, 84, 88, 92,
1023 96, 100, 104, 108, 112, 116, 120, 124,
1024 128, 132, 136, 140, 144, 148, 152, 156,
1025 160, 164, 168, 172, 176, 180, 184, 188,
1026 192, 196, 200, 204, 208, 212, 216, 220,
1027 224, 228, 232, 236, 240, 244, 249, 255,
1030 int vp9_reverse_trans(int x) {
1033 for (i = 0; i < 64; i++)
1034 if (q_trans[i] >= x)
1039 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
1040 if (framerate < 0.1)
1043 cpi->oxcf.framerate = framerate;
1044 cpi->output_framerate = cpi->oxcf.framerate;
1045 cpi->rc.per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth
1046 / cpi->output_framerate);
1047 cpi->rc.av_per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth
1048 / cpi->output_framerate);
1049 cpi->rc.min_frame_bandwidth = (int)(cpi->rc.av_per_frame_bandwidth *
1050 cpi->oxcf.two_pass_vbrmin_section / 100);
1053 cpi->rc.min_frame_bandwidth = MAX(cpi->rc.min_frame_bandwidth,
1054 FRAME_OVERHEAD_BITS);
1056 // Set Maximum gf/arf interval
1057 cpi->rc.max_gf_interval = 16;
1059 // Extended interval for genuinely static scenes
1060 cpi->twopass.static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
1062 // Special conditions when alt ref frame enabled in lagged compress mode
1063 if (cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames) {
1064 if (cpi->rc.max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1065 cpi->rc.max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1067 if (cpi->twopass.static_scene_max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1068 cpi->twopass.static_scene_max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1071 if (cpi->rc.max_gf_interval > cpi->twopass.static_scene_max_gf_interval)
1072 cpi->rc.max_gf_interval = cpi->twopass.static_scene_max_gf_interval;
1075 static int64_t rescale(int val, int64_t num, int denom) {
1076 int64_t llnum = num;
1077 int64_t llden = denom;
1078 int64_t llval = val;
1080 return (llval * llnum / llden);
1083 static void set_tile_limits(VP9_COMP *cpi) {
1084 VP9_COMMON *const cm = &cpi->common;
1086 int min_log2_tile_cols, max_log2_tile_cols;
1087 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1089 cm->log2_tile_cols = clamp(cpi->oxcf.tile_columns,
1090 min_log2_tile_cols, max_log2_tile_cols);
1091 cm->log2_tile_rows = cpi->oxcf.tile_rows;
1094 static void init_config(VP9_PTR ptr, VP9_CONFIG *oxcf) {
1095 VP9_COMP *cpi = (VP9_COMP *)(ptr);
1096 VP9_COMMON *const cm = &cpi->common;
1101 cm->version = oxcf->version;
1103 cm->width = oxcf->width;
1104 cm->height = oxcf->height;
1105 cm->subsampling_x = 0;
1106 cm->subsampling_y = 0;
1107 vp9_alloc_compressor_data(cpi);
1109 // change includes all joint functionality
1110 vp9_change_config(ptr, oxcf);
1112 // Initialize active best and worst q and average q values.
1113 cpi->rc.active_worst_quality = cpi->oxcf.worst_allowed_q;
1114 cpi->rc.active_best_quality = cpi->oxcf.best_allowed_q;
1115 cpi->rc.avg_frame_qindex = cpi->oxcf.worst_allowed_q;
1117 // Initialise the starting buffer levels
1118 cpi->rc.buffer_level = cpi->oxcf.starting_buffer_level;
1119 cpi->rc.bits_off_target = cpi->oxcf.starting_buffer_level;
1121 cpi->rc.rolling_target_bits = cpi->rc.av_per_frame_bandwidth;
1122 cpi->rc.rolling_actual_bits = cpi->rc.av_per_frame_bandwidth;
1123 cpi->rc.long_rolling_target_bits = cpi->rc.av_per_frame_bandwidth;
1124 cpi->rc.long_rolling_actual_bits = cpi->rc.av_per_frame_bandwidth;
1126 cpi->rc.total_actual_bits = 0;
1127 cpi->rc.total_target_vs_actual = 0;
1129 cpi->static_mb_pct = 0;
1131 cpi->lst_fb_idx = 0;
1132 cpi->gld_fb_idx = 1;
1133 cpi->alt_fb_idx = 2;
1135 cpi->current_layer = 0;
1138 set_tile_limits(cpi);
1140 cpi->fixed_divide[0] = 0;
1141 for (i = 1; i < 512; i++)
1142 cpi->fixed_divide[i] = 0x80000 / i;
1146 void vp9_change_config(VP9_PTR ptr, VP9_CONFIG *oxcf) {
1147 VP9_COMP *cpi = (VP9_COMP *)(ptr);
1148 VP9_COMMON *const cm = &cpi->common;
1153 if (cm->version != oxcf->version) {
1154 cm->version = oxcf->version;
1159 switch (cpi->oxcf.Mode) {
1160 // Real time and one pass deprecated in test code base
1161 case MODE_GOODQUALITY:
1163 cpi->compressor_speed = 2;
1164 cpi->oxcf.cpu_used = clamp(cpi->oxcf.cpu_used, -5, 5);
1167 case MODE_FIRSTPASS:
1169 cpi->compressor_speed = 1;
1172 case MODE_SECONDPASS:
1174 cpi->compressor_speed = 1;
1175 cpi->oxcf.cpu_used = clamp(cpi->oxcf.cpu_used, -5, 5);
1178 case MODE_SECONDPASS_BEST:
1180 cpi->compressor_speed = 0;
1184 cpi->oxcf.worst_allowed_q = q_trans[oxcf->worst_allowed_q];
1185 cpi->oxcf.best_allowed_q = q_trans[oxcf->best_allowed_q];
1186 cpi->oxcf.cq_level = q_trans[cpi->oxcf.cq_level];
1188 cpi->oxcf.lossless = oxcf->lossless;
1189 cpi->mb.e_mbd.itxm_add = cpi->oxcf.lossless ? vp9_iwht4x4_add
1191 cpi->rc.baseline_gf_interval = DEFAULT_GF_INTERVAL;
1193 cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
1195 // cpi->use_golden_frame_only = 0;
1196 // cpi->use_last_frame_only = 0;
1197 cpi->refresh_golden_frame = 0;
1198 cpi->refresh_last_frame = 1;
1199 cm->refresh_frame_context = 1;
1200 cm->reset_frame_context = 0;
1203 cpi->common.allow_high_precision_mv = 0; // Default mv precision
1209 for (i = 0; i < MAX_SEGMENTS; i++)
1210 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1213 // At the moment the first order values may not be > MAXQ
1214 cpi->oxcf.fixed_q = MIN(cpi->oxcf.fixed_q, MAXQ);
1216 // local file playback mode == really big buffer
1217 if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK) {
1218 cpi->oxcf.starting_buffer_level = 60000;
1219 cpi->oxcf.optimal_buffer_level = 60000;
1220 cpi->oxcf.maximum_buffer_size = 240000;
1223 // Convert target bandwidth from Kbit/s to Bit/s
1224 cpi->oxcf.target_bandwidth *= 1000;
1226 cpi->oxcf.starting_buffer_level = rescale(cpi->oxcf.starting_buffer_level,
1227 cpi->oxcf.target_bandwidth, 1000);
1229 // Set or reset optimal and maximum buffer levels.
1230 if (cpi->oxcf.optimal_buffer_level == 0)
1231 cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
1233 cpi->oxcf.optimal_buffer_level = rescale(cpi->oxcf.optimal_buffer_level,
1234 cpi->oxcf.target_bandwidth, 1000);
1236 if (cpi->oxcf.maximum_buffer_size == 0)
1237 cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
1239 cpi->oxcf.maximum_buffer_size = rescale(cpi->oxcf.maximum_buffer_size,
1240 cpi->oxcf.target_bandwidth, 1000);
1242 // Set up frame rate and related parameters rate control values.
1243 vp9_new_framerate(cpi, cpi->oxcf.framerate);
1245 // Set absolute upper and lower quality limits
1246 cpi->rc.worst_quality = cpi->oxcf.worst_allowed_q;
1247 cpi->rc.best_quality = cpi->oxcf.best_allowed_q;
1249 // active values should only be modified if out of new range
1250 cpi->rc.active_worst_quality = clamp(cpi->rc.active_worst_quality,
1251 cpi->oxcf.best_allowed_q,
1252 cpi->oxcf.worst_allowed_q);
1254 cpi->rc.active_best_quality = clamp(cpi->rc.active_best_quality,
1255 cpi->oxcf.best_allowed_q,
1256 cpi->oxcf.worst_allowed_q);
1258 cpi->cq_target_quality = cpi->oxcf.cq_level;
1260 cm->mcomp_filter_type = DEFAULT_INTERP_FILTER;
1262 cpi->target_bandwidth = cpi->oxcf.target_bandwidth;
1264 cm->display_width = cpi->oxcf.width;
1265 cm->display_height = cpi->oxcf.height;
1267 // VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs)
1268 cpi->oxcf.Sharpness = MIN(7, cpi->oxcf.Sharpness);
1270 cpi->common.lf.sharpness_level = cpi->oxcf.Sharpness;
1272 if (cpi->initial_width) {
1273 // Increasing the size of the frame beyond the first seen frame, or some
1274 // otherwise signalled maximum size, is not supported.
1275 // TODO(jkoleszar): exit gracefully.
1276 assert(cm->width <= cpi->initial_width);
1277 assert(cm->height <= cpi->initial_height);
1279 update_frame_size(cpi);
1281 if (cpi->oxcf.fixed_q >= 0) {
1282 cpi->rc.last_q[0] = cpi->oxcf.fixed_q;
1283 cpi->rc.last_q[1] = cpi->oxcf.fixed_q;
1284 cpi->rc.last_boosted_qindex = cpi->oxcf.fixed_q;
1287 cpi->speed = cpi->oxcf.cpu_used;
1289 if (cpi->oxcf.lag_in_frames == 0) {
1290 // force to allowlag to 0 if lag_in_frames is 0;
1291 cpi->oxcf.allow_lag = 0;
1292 } else if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS) {
1293 // Limit on lag buffers as these are not currently dynamically allocated
1294 cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
1298 #if CONFIG_MULTIPLE_ARF
1299 vp9_zero(cpi->alt_ref_source);
1301 cpi->alt_ref_source = NULL;
1303 cpi->is_src_frame_alt_ref = 0;
1306 // Experimental RD Code
1307 cpi->frame_distortion = 0;
1308 cpi->last_frame_distortion = 0;
1311 set_tile_limits(cpi);
1314 #define M_LOG2_E 0.693147180559945309417
1315 #define log2f(x) (log (x) / (float) M_LOG2_E)
1317 static void cal_nmvjointsadcost(int *mvjointsadcost) {
1318 mvjointsadcost[0] = 600;
1319 mvjointsadcost[1] = 300;
1320 mvjointsadcost[2] = 300;
1321 mvjointsadcost[0] = 300;
1324 static void cal_nmvsadcosts(int *mvsadcost[2]) {
1327 mvsadcost[0][0] = 0;
1328 mvsadcost[1][0] = 0;
1331 double z = 256 * (2 * (log2f(8 * i) + .6));
1332 mvsadcost[0][i] = (int)z;
1333 mvsadcost[1][i] = (int)z;
1334 mvsadcost[0][-i] = (int)z;
1335 mvsadcost[1][-i] = (int)z;
1336 } while (++i <= MV_MAX);
1339 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
1342 mvsadcost[0][0] = 0;
1343 mvsadcost[1][0] = 0;
1346 double z = 256 * (2 * (log2f(8 * i) + .6));
1347 mvsadcost[0][i] = (int)z;
1348 mvsadcost[1][i] = (int)z;
1349 mvsadcost[0][-i] = (int)z;
1350 mvsadcost[1][-i] = (int)z;
1351 } while (++i <= MV_MAX);
1354 static void alloc_mode_context(VP9_COMMON *cm, int num_4x4_blk,
1355 PICK_MODE_CONTEXT *ctx) {
1356 int num_pix = num_4x4_blk << 4;
1358 ctx->num_4x4_blk = num_4x4_blk;
1359 CHECK_MEM_ERROR(cm, ctx->zcoeff_blk,
1360 vpx_calloc(num_4x4_blk, sizeof(uint8_t)));
1361 for (i = 0; i < MAX_MB_PLANE; ++i) {
1362 for (k = 0; k < 3; ++k) {
1363 CHECK_MEM_ERROR(cm, ctx->coeff[i][k],
1364 vpx_memalign(16, num_pix * sizeof(int16_t)));
1365 CHECK_MEM_ERROR(cm, ctx->qcoeff[i][k],
1366 vpx_memalign(16, num_pix * sizeof(int16_t)));
1367 CHECK_MEM_ERROR(cm, ctx->dqcoeff[i][k],
1368 vpx_memalign(16, num_pix * sizeof(int16_t)));
1369 CHECK_MEM_ERROR(cm, ctx->eobs[i][k],
1370 vpx_memalign(16, num_pix * sizeof(uint16_t)));
1371 ctx->coeff_pbuf[i][k] = ctx->coeff[i][k];
1372 ctx->qcoeff_pbuf[i][k] = ctx->qcoeff[i][k];
1373 ctx->dqcoeff_pbuf[i][k] = ctx->dqcoeff[i][k];
1374 ctx->eobs_pbuf[i][k] = ctx->eobs[i][k];
1379 static void free_mode_context(PICK_MODE_CONTEXT *ctx) {
1381 vpx_free(ctx->zcoeff_blk);
1382 ctx->zcoeff_blk = 0;
1383 for (i = 0; i < MAX_MB_PLANE; ++i) {
1384 for (k = 0; k < 3; ++k) {
1385 vpx_free(ctx->coeff[i][k]);
1386 ctx->coeff[i][k] = 0;
1387 vpx_free(ctx->qcoeff[i][k]);
1388 ctx->qcoeff[i][k] = 0;
1389 vpx_free(ctx->dqcoeff[i][k]);
1390 ctx->dqcoeff[i][k] = 0;
1391 vpx_free(ctx->eobs[i][k]);
1392 ctx->eobs[i][k] = 0;
1397 static void init_pick_mode_context(VP9_COMP *cpi) {
1399 VP9_COMMON *const cm = &cpi->common;
1400 MACROBLOCK *const x = &cpi->mb;
1403 for (i = 0; i < BLOCK_SIZES; ++i) {
1404 const int num_4x4_w = num_4x4_blocks_wide_lookup[i];
1405 const int num_4x4_h = num_4x4_blocks_high_lookup[i];
1406 const int num_4x4_blk = MAX(4, num_4x4_w * num_4x4_h);
1407 if (i < BLOCK_16X16) {
1408 for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1409 for (x->mb_index = 0; x->mb_index < 4; ++x->mb_index) {
1410 for (x->b_index = 0; x->b_index < 16 / num_4x4_blk; ++x->b_index) {
1411 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1412 alloc_mode_context(cm, num_4x4_blk, ctx);
1416 } else if (i < BLOCK_32X32) {
1417 for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1418 for (x->mb_index = 0; x->mb_index < 64 / num_4x4_blk; ++x->mb_index) {
1419 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1420 ctx->num_4x4_blk = num_4x4_blk;
1421 alloc_mode_context(cm, num_4x4_blk, ctx);
1424 } else if (i < BLOCK_64X64) {
1425 for (x->sb_index = 0; x->sb_index < 256 / num_4x4_blk; ++x->sb_index) {
1426 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1427 ctx->num_4x4_blk = num_4x4_blk;
1428 alloc_mode_context(cm, num_4x4_blk, ctx);
1431 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1432 ctx->num_4x4_blk = num_4x4_blk;
1433 alloc_mode_context(cm, num_4x4_blk, ctx);
1438 static void free_pick_mode_context(MACROBLOCK *x) {
1441 for (i = 0; i < BLOCK_SIZES; ++i) {
1442 const int num_4x4_w = num_4x4_blocks_wide_lookup[i];
1443 const int num_4x4_h = num_4x4_blocks_high_lookup[i];
1444 const int num_4x4_blk = MAX(4, num_4x4_w * num_4x4_h);
1445 if (i < BLOCK_16X16) {
1446 for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1447 for (x->mb_index = 0; x->mb_index < 4; ++x->mb_index) {
1448 for (x->b_index = 0; x->b_index < 16 / num_4x4_blk; ++x->b_index) {
1449 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1450 free_mode_context(ctx);
1454 } else if (i < BLOCK_32X32) {
1455 for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1456 for (x->mb_index = 0; x->mb_index < 64 / num_4x4_blk; ++x->mb_index) {
1457 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1458 free_mode_context(ctx);
1461 } else if (i < BLOCK_64X64) {
1462 for (x->sb_index = 0; x->sb_index < 256 / num_4x4_blk; ++x->sb_index) {
1463 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1464 free_mode_context(ctx);
1467 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1468 free_mode_context(ctx);
1473 VP9_PTR vp9_create_compressor(VP9_CONFIG *oxcf) {
1483 cpi = ctx.cpi = vpx_memalign(32, sizeof(VP9_COMP));
1484 // Check that the CPI instance is valid
1492 if (setjmp(cm->error.jmp)) {
1493 VP9_PTR ptr = ctx.ptr;
1495 ctx.cpi->common.error.setjmp = 0;
1496 vp9_remove_compressor(&ptr);
1500 cm->error.setjmp = 1;
1502 CHECK_MEM_ERROR(cm, cpi->mb.ss, vpx_calloc(sizeof(search_site),
1503 (MAX_MVSEARCH_STEPS * 8) + 1));
1505 vp9_create_common(cm);
1507 init_config((VP9_PTR)cpi, oxcf);
1509 init_pick_mode_context(cpi);
1511 cm->current_video_frame = 0;
1512 cpi->rc.frames_till_gf_update_due = 0;
1514 // Set reference frame sign bias for ALTREF frame to 1 (for now)
1515 cm->ref_frame_sign_bias[ALTREF_FRAME] = 1;
1517 cpi->rc.baseline_gf_interval = DEFAULT_GF_INTERVAL;
1519 cpi->gold_is_last = 0;
1520 cpi->alt_is_last = 0;
1521 cpi->gold_is_alt = 0;
1523 // Spatial scalability
1524 cpi->number_spatial_layers = oxcf->ss_number_layers;
1526 // Create the encoder segmentation map and set all entries to 0
1527 CHECK_MEM_ERROR(cm, cpi->segmentation_map,
1528 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1530 // Create a complexity map used for rd adjustment
1531 CHECK_MEM_ERROR(cm, cpi->complexity_map,
1532 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1535 // And a place holder structure is the coding context
1536 // for use if we want to save and restore it
1537 CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
1538 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1540 CHECK_MEM_ERROR(cm, cpi->active_map, vpx_calloc(cm->MBs, 1));
1541 vpx_memset(cpi->active_map, 1, cm->MBs);
1542 cpi->active_map_enabled = 0;
1544 for (i = 0; i < (sizeof(cpi->mbgraph_stats) /
1545 sizeof(cpi->mbgraph_stats[0])); i++) {
1546 CHECK_MEM_ERROR(cm, cpi->mbgraph_stats[i].mb_stats,
1547 vpx_calloc(cm->MBs *
1548 sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
1551 #ifdef ENTROPY_STATS
1553 init_context_counters();
1557 init_tx_count_stats();
1558 init_switchable_interp_stats();
1561 /*Initialize the feed-forward activity masking.*/
1562 cpi->activity_avg = 90 << 12;
1564 cpi->frames_since_key = 8; // Sensible default for first frame.
1565 cpi->key_frame_frequency = cpi->oxcf.key_freq;
1566 cpi->this_key_frame_forced = 0;
1567 cpi->next_key_frame_forced = 0;
1569 cpi->source_alt_ref_pending = 0;
1570 cpi->source_alt_ref_active = 0;
1571 cpi->refresh_alt_ref_frame = 0;
1573 #if CONFIG_MULTIPLE_ARF
1574 // Turn multiple ARF usage on/off. This is a quick hack for the initial test
1575 // version. It should eventually be set via the codec API.
1576 cpi->multi_arf_enabled = 1;
1578 if (cpi->multi_arf_enabled) {
1579 cpi->sequence_number = 0;
1580 cpi->frame_coding_order_period = 0;
1581 vp9_zero(cpi->frame_coding_order);
1582 vp9_zero(cpi->arf_buffer_idx);
1586 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1587 #if CONFIG_INTERNAL_STATS
1588 cpi->b_calculate_ssimg = 0;
1593 if (cpi->b_calculate_psnr) {
1594 cpi->total_sq_error = 0.0;
1595 cpi->total_sq_error2 = 0.0;
1600 cpi->totalp_y = 0.0;
1601 cpi->totalp_u = 0.0;
1602 cpi->totalp_v = 0.0;
1604 cpi->tot_recode_hits = 0;
1605 cpi->summed_quality = 0;
1606 cpi->summed_weights = 0;
1607 cpi->summedp_quality = 0;
1608 cpi->summedp_weights = 0;
1611 if (cpi->b_calculate_ssimg) {
1612 cpi->total_ssimg_y = 0;
1613 cpi->total_ssimg_u = 0;
1614 cpi->total_ssimg_v = 0;
1615 cpi->total_ssimg_all = 0;
1620 cpi->first_time_stamp_ever = INT64_MAX;
1622 cpi->rc.frames_till_gf_update_due = 0;
1623 cpi->rc.key_frame_count = 1;
1625 cpi->rc.ni_av_qi = cpi->oxcf.worst_allowed_q;
1626 cpi->rc.ni_tot_qi = 0;
1627 cpi->rc.ni_frames = 0;
1628 cpi->rc.tot_q = 0.0;
1629 cpi->rc.avg_q = vp9_convert_qindex_to_q(cpi->oxcf.worst_allowed_q);
1631 cpi->rc.rate_correction_factor = 1.0;
1632 cpi->rc.key_frame_rate_correction_factor = 1.0;
1633 cpi->rc.gf_rate_correction_factor = 1.0;
1634 cpi->twopass.est_max_qcorrection_factor = 1.0;
1636 cal_nmvjointsadcost(cpi->mb.nmvjointsadcost);
1637 cpi->mb.nmvcost[0] = &cpi->mb.nmvcosts[0][MV_MAX];
1638 cpi->mb.nmvcost[1] = &cpi->mb.nmvcosts[1][MV_MAX];
1639 cpi->mb.nmvsadcost[0] = &cpi->mb.nmvsadcosts[0][MV_MAX];
1640 cpi->mb.nmvsadcost[1] = &cpi->mb.nmvsadcosts[1][MV_MAX];
1641 cal_nmvsadcosts(cpi->mb.nmvsadcost);
1643 cpi->mb.nmvcost_hp[0] = &cpi->mb.nmvcosts_hp[0][MV_MAX];
1644 cpi->mb.nmvcost_hp[1] = &cpi->mb.nmvcosts_hp[1][MV_MAX];
1645 cpi->mb.nmvsadcost_hp[0] = &cpi->mb.nmvsadcosts_hp[0][MV_MAX];
1646 cpi->mb.nmvsadcost_hp[1] = &cpi->mb.nmvsadcosts_hp[1][MV_MAX];
1647 cal_nmvsadcosts_hp(cpi->mb.nmvsadcost_hp);
1649 for (i = 0; i < KEY_FRAME_CONTEXT; i++)
1650 cpi->rc.prior_key_frame_distance[i] = (int)cpi->output_framerate;
1652 #ifdef OUTPUT_YUV_SRC
1653 yuv_file = fopen("bd.yuv", "ab");
1655 #ifdef OUTPUT_YUV_REC
1656 yuv_rec_file = fopen("rec.yuv", "wb");
1660 framepsnr = fopen("framepsnr.stt", "a");
1661 kf_list = fopen("kf_list.stt", "w");
1664 cpi->output_pkt_list = oxcf->output_pkt_list;
1666 cpi->enable_encode_breakout = 1;
1668 if (cpi->pass == 1) {
1669 vp9_init_first_pass(cpi);
1670 } else if (cpi->pass == 2) {
1671 size_t packet_sz = sizeof(FIRSTPASS_STATS);
1672 int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
1674 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1675 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1676 cpi->twopass.stats_in_end = (void *)((char *)cpi->twopass.stats_in
1677 + (packets - 1) * packet_sz);
1678 vp9_init_second_pass(cpi);
1681 vp9_set_speed_features(cpi);
1683 // Default rd threshold factors for mode selection
1684 for (i = 0; i < BLOCK_SIZES; ++i) {
1685 for (j = 0; j < MAX_MODES; ++j)
1686 cpi->rd_thresh_freq_fact[i][j] = 32;
1687 for (j = 0; j < MAX_REFS; ++j)
1688 cpi->rd_thresh_freq_sub8x8[i][j] = 32;
1691 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SVFHH, SVFHV, SVFHHV, \
1692 SDX3F, SDX8F, SDX4DF)\
1693 cpi->fn_ptr[BT].sdf = SDF; \
1694 cpi->fn_ptr[BT].sdaf = SDAF; \
1695 cpi->fn_ptr[BT].vf = VF; \
1696 cpi->fn_ptr[BT].svf = SVF; \
1697 cpi->fn_ptr[BT].svaf = SVAF; \
1698 cpi->fn_ptr[BT].svf_halfpix_h = SVFHH; \
1699 cpi->fn_ptr[BT].svf_halfpix_v = SVFHV; \
1700 cpi->fn_ptr[BT].svf_halfpix_hv = SVFHHV; \
1701 cpi->fn_ptr[BT].sdx3f = SDX3F; \
1702 cpi->fn_ptr[BT].sdx8f = SDX8F; \
1703 cpi->fn_ptr[BT].sdx4df = SDX4DF;
1705 BFP(BLOCK_32X16, vp9_sad32x16, vp9_sad32x16_avg,
1706 vp9_variance32x16, vp9_sub_pixel_variance32x16,
1707 vp9_sub_pixel_avg_variance32x16, NULL, NULL,
1711 BFP(BLOCK_16X32, vp9_sad16x32, vp9_sad16x32_avg,
1712 vp9_variance16x32, vp9_sub_pixel_variance16x32,
1713 vp9_sub_pixel_avg_variance16x32, NULL, NULL,
1717 BFP(BLOCK_64X32, vp9_sad64x32, vp9_sad64x32_avg,
1718 vp9_variance64x32, vp9_sub_pixel_variance64x32,
1719 vp9_sub_pixel_avg_variance64x32, NULL, NULL,
1723 BFP(BLOCK_32X64, vp9_sad32x64, vp9_sad32x64_avg,
1724 vp9_variance32x64, vp9_sub_pixel_variance32x64,
1725 vp9_sub_pixel_avg_variance32x64, NULL, NULL,
1729 BFP(BLOCK_32X32, vp9_sad32x32, vp9_sad32x32_avg,
1730 vp9_variance32x32, vp9_sub_pixel_variance32x32,
1731 vp9_sub_pixel_avg_variance32x32, vp9_variance_halfpixvar32x32_h,
1732 vp9_variance_halfpixvar32x32_v,
1733 vp9_variance_halfpixvar32x32_hv, vp9_sad32x32x3, vp9_sad32x32x8,
1736 BFP(BLOCK_64X64, vp9_sad64x64, vp9_sad64x64_avg,
1737 vp9_variance64x64, vp9_sub_pixel_variance64x64,
1738 vp9_sub_pixel_avg_variance64x64, vp9_variance_halfpixvar64x64_h,
1739 vp9_variance_halfpixvar64x64_v,
1740 vp9_variance_halfpixvar64x64_hv, vp9_sad64x64x3, vp9_sad64x64x8,
1743 BFP(BLOCK_16X16, vp9_sad16x16, vp9_sad16x16_avg,
1744 vp9_variance16x16, vp9_sub_pixel_variance16x16,
1745 vp9_sub_pixel_avg_variance16x16, vp9_variance_halfpixvar16x16_h,
1746 vp9_variance_halfpixvar16x16_v,
1747 vp9_variance_halfpixvar16x16_hv, vp9_sad16x16x3, vp9_sad16x16x8,
1750 BFP(BLOCK_16X8, vp9_sad16x8, vp9_sad16x8_avg,
1751 vp9_variance16x8, vp9_sub_pixel_variance16x8,
1752 vp9_sub_pixel_avg_variance16x8, NULL, NULL, NULL,
1753 vp9_sad16x8x3, vp9_sad16x8x8, vp9_sad16x8x4d)
1755 BFP(BLOCK_8X16, vp9_sad8x16, vp9_sad8x16_avg,
1756 vp9_variance8x16, vp9_sub_pixel_variance8x16,
1757 vp9_sub_pixel_avg_variance8x16, NULL, NULL, NULL,
1758 vp9_sad8x16x3, vp9_sad8x16x8, vp9_sad8x16x4d)
1760 BFP(BLOCK_8X8, vp9_sad8x8, vp9_sad8x8_avg,
1761 vp9_variance8x8, vp9_sub_pixel_variance8x8,
1762 vp9_sub_pixel_avg_variance8x8, NULL, NULL, NULL,
1763 vp9_sad8x8x3, vp9_sad8x8x8, vp9_sad8x8x4d)
1765 BFP(BLOCK_8X4, vp9_sad8x4, vp9_sad8x4_avg,
1766 vp9_variance8x4, vp9_sub_pixel_variance8x4,
1767 vp9_sub_pixel_avg_variance8x4, NULL, NULL,
1768 NULL, NULL, vp9_sad8x4x8,
1771 BFP(BLOCK_4X8, vp9_sad4x8, vp9_sad4x8_avg,
1772 vp9_variance4x8, vp9_sub_pixel_variance4x8,
1773 vp9_sub_pixel_avg_variance4x8, NULL, NULL,
1774 NULL, NULL, vp9_sad4x8x8,
1777 BFP(BLOCK_4X4, vp9_sad4x4, vp9_sad4x4_avg,
1778 vp9_variance4x4, vp9_sub_pixel_variance4x4,
1779 vp9_sub_pixel_avg_variance4x4, NULL, NULL, NULL,
1780 vp9_sad4x4x3, vp9_sad4x4x8, vp9_sad4x4x4d)
1782 cpi->full_search_sad = vp9_full_search_sad;
1783 cpi->diamond_search_sad = vp9_diamond_search_sad;
1784 cpi->refining_search_sad = vp9_refining_search_sad;
1786 // make sure frame 1 is okay
1787 cpi->error_bins[0] = cpi->common.MBs;
1789 /* vp9_init_quantizer() is first called here. Add check in
1790 * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
1791 * called later when needed. This will avoid unnecessary calls of
1792 * vp9_init_quantizer() for every frame.
1794 vp9_init_quantizer(cpi);
1796 vp9_loop_filter_init(cm);
1798 cpi->common.error.setjmp = 0;
1800 vp9_zero(cpi->y_uv_mode_count);
1802 #ifdef MODE_TEST_HIT_STATS
1803 vp9_zero(cpi->mode_test_hits);
1806 return (VP9_PTR) cpi;
1809 void vp9_remove_compressor(VP9_PTR *ptr) {
1810 VP9_COMP *cpi = (VP9_COMP *)(*ptr);
1816 if (cpi && (cpi->common.current_video_frame > 0)) {
1817 if (cpi->pass == 2) {
1818 vp9_end_second_pass(cpi);
1822 if (cpi->pass != 1) {
1823 write_tx_count_stats();
1824 write_switchable_interp_stats();
1828 #if CONFIG_INTERNAL_STATS
1830 vp9_clear_system_state();
1832 // printf("\n8x8-4x4:%d-%d\n", cpi->t8x8_count, cpi->t4x4_count);
1833 if (cpi->pass != 1) {
1834 FILE *f = fopen("opsnr.stt", "a");
1835 double time_encoded = (cpi->last_end_time_stamp_seen
1836 - cpi->first_time_stamp_ever) / 10000000.000;
1837 double total_encode_time = (cpi->time_receive_data +
1838 cpi->time_compress_data) / 1000.000;
1839 double dr = (double)cpi->bytes * (double) 8 / (double)1000
1842 if (cpi->b_calculate_psnr) {
1843 YV12_BUFFER_CONFIG *lst_yv12 =
1844 &cpi->common.yv12_fb[cpi->common.ref_frame_map[cpi->lst_fb_idx]];
1845 double samples = 3.0 / 2 * cpi->count *
1846 lst_yv12->y_width * lst_yv12->y_height;
1847 double total_psnr = vp9_mse2psnr(samples, 255.0, cpi->total_sq_error);
1848 double total_psnr2 = vp9_mse2psnr(samples, 255.0, cpi->total_sq_error2);
1849 double total_ssim = 100 * pow(cpi->summed_quality /
1850 cpi->summed_weights, 8.0);
1851 double total_ssimp = 100 * pow(cpi->summedp_quality /
1852 cpi->summedp_weights, 8.0);
1854 fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
1855 "VPXSSIM\tVPSSIMP\t Time(ms)\n");
1856 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",
1857 dr, cpi->total / cpi->count, total_psnr,
1858 cpi->totalp / cpi->count, total_psnr2, total_ssim, total_ssimp,
1862 if (cpi->b_calculate_ssimg) {
1863 fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t Time(ms)\n");
1864 fprintf(f, "%7.2f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
1865 cpi->total_ssimg_y / cpi->count,
1866 cpi->total_ssimg_u / cpi->count,
1867 cpi->total_ssimg_v / cpi->count,
1868 cpi->total_ssimg_all / cpi->count, total_encode_time);
1876 #ifdef MODE_TEST_HIT_STATS
1877 if (cpi->pass != 1) {
1878 double norm_per_pixel_mode_tests = 0;
1879 double norm_counts[BLOCK_SIZES];
1882 int norm_factors[BLOCK_SIZES] =
1883 {256, 128, 128, 64, 32, 32, 16, 8, 8, 4, 2, 2, 1};
1884 FILE *f = fopen("mode_hit_stats.stt", "a");
1886 // On average, how many mode tests do we do
1887 for (i = 0; i < BLOCK_SIZES; ++i) {
1888 norm_counts[i] = (double)cpi->mode_test_hits[i] /
1889 (double)norm_factors[i];
1890 norm_per_pixel_mode_tests += norm_counts[i];
1892 // Convert to a number per 64x64 and per frame
1893 sb64_per_frame = ((cpi->common.height + 63) / 64) *
1894 ((cpi->common.width + 63) / 64);
1895 norm_per_pixel_mode_tests =
1896 norm_per_pixel_mode_tests /
1897 (double)(cpi->common.current_video_frame * sb64_per_frame);
1899 fprintf(f, "%6.4f\n", norm_per_pixel_mode_tests);
1904 #ifdef ENTROPY_STATS
1907 FILE *fmode = fopen("vp9_modecontext.c", "w");
1909 fprintf(fmode, "\n#include \"vp9_entropymode.h\"\n\n");
1910 fprintf(fmode, "const unsigned int vp9_kf_default_bmode_counts ");
1911 fprintf(fmode, "[INTRA_MODES][INTRA_MODES]"
1912 "[INTRA_MODES] =\n{\n");
1914 for (i = 0; i < INTRA_MODES; i++) {
1915 fprintf(fmode, " { // Above Mode : %d\n", i);
1917 for (j = 0; j < INTRA_MODES; j++) {
1918 fprintf(fmode, " {");
1920 for (k = 0; k < INTRA_MODES; k++) {
1921 if (!intra_mode_stats[i][j][k])
1922 fprintf(fmode, " %5d, ", 1);
1924 fprintf(fmode, " %5d, ", intra_mode_stats[i][j][k]);
1927 fprintf(fmode, "}, // left_mode %d\n", j);
1930 fprintf(fmode, " },\n");
1933 fprintf(fmode, "};\n");
1939 #if defined(SECTIONBITS_OUTPUT)
1943 FILE *f = fopen("tokenbits.stt", "a");
1945 for (i = 0; i < 28; i++)
1946 fprintf(f, "%8d", (int)(Sectionbits[i] / 256));
1956 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
1957 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
1958 printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
1959 cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
1960 cpi->time_compress_data / 1000,
1961 (cpi->time_receive_data + cpi->time_compress_data) / 1000);
1966 free_pick_mode_context(&cpi->mb);
1967 dealloc_compressor_data(cpi);
1968 vpx_free(cpi->mb.ss);
1971 for (i = 0; i < sizeof(cpi->mbgraph_stats) /
1972 sizeof(cpi->mbgraph_stats[0]); ++i) {
1973 vpx_free(cpi->mbgraph_stats[i].mb_stats);
1976 vp9_remove_common(&cpi->common);
1980 #ifdef OUTPUT_YUV_SRC
1983 #ifdef OUTPUT_YUV_REC
1984 fclose(yuv_rec_file);
2002 static uint64_t calc_plane_error(uint8_t *orig, int orig_stride,
2003 uint8_t *recon, int recon_stride,
2004 unsigned int cols, unsigned int rows) {
2005 unsigned int row, col;
2006 uint64_t total_sse = 0;
2009 for (row = 0; row + 16 <= rows; row += 16) {
2010 for (col = 0; col + 16 <= cols; col += 16) {
2013 vp9_mse16x16(orig + col, orig_stride, recon + col, recon_stride, &sse);
2017 /* Handle odd-sized width */
2019 unsigned int border_row, border_col;
2020 uint8_t *border_orig = orig;
2021 uint8_t *border_recon = recon;
2023 for (border_row = 0; border_row < 16; border_row++) {
2024 for (border_col = col; border_col < cols; border_col++) {
2025 diff = border_orig[border_col] - border_recon[border_col];
2026 total_sse += diff * diff;
2029 border_orig += orig_stride;
2030 border_recon += recon_stride;
2034 orig += orig_stride * 16;
2035 recon += recon_stride * 16;
2038 /* Handle odd-sized height */
2039 for (; row < rows; row++) {
2040 for (col = 0; col < cols; col++) {
2041 diff = orig[col] - recon[col];
2042 total_sse += diff * diff;
2045 orig += orig_stride;
2046 recon += recon_stride;
2053 static void generate_psnr_packet(VP9_COMP *cpi) {
2054 YV12_BUFFER_CONFIG *orig = cpi->Source;
2055 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
2056 struct vpx_codec_cx_pkt pkt;
2059 unsigned int width = orig->y_crop_width;
2060 unsigned int height = orig->y_crop_height;
2062 pkt.kind = VPX_CODEC_PSNR_PKT;
2063 sse = calc_plane_error(orig->y_buffer, orig->y_stride,
2064 recon->y_buffer, recon->y_stride,
2066 pkt.data.psnr.sse[0] = sse;
2067 pkt.data.psnr.sse[1] = sse;
2068 pkt.data.psnr.samples[0] = width * height;
2069 pkt.data.psnr.samples[1] = width * height;
2071 width = orig->uv_crop_width;
2072 height = orig->uv_crop_height;
2074 sse = calc_plane_error(orig->u_buffer, orig->uv_stride,
2075 recon->u_buffer, recon->uv_stride,
2077 pkt.data.psnr.sse[0] += sse;
2078 pkt.data.psnr.sse[2] = sse;
2079 pkt.data.psnr.samples[0] += width * height;
2080 pkt.data.psnr.samples[2] = width * height;
2082 sse = calc_plane_error(orig->v_buffer, orig->uv_stride,
2083 recon->v_buffer, recon->uv_stride,
2085 pkt.data.psnr.sse[0] += sse;
2086 pkt.data.psnr.sse[3] = sse;
2087 pkt.data.psnr.samples[0] += width * height;
2088 pkt.data.psnr.samples[3] = width * height;
2090 for (i = 0; i < 4; i++)
2091 pkt.data.psnr.psnr[i] = vp9_mse2psnr(pkt.data.psnr.samples[i], 255.0,
2092 (double)pkt.data.psnr.sse[i]);
2094 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2098 int vp9_use_as_reference(VP9_PTR ptr, int ref_frame_flags) {
2099 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2101 if (ref_frame_flags > 7)
2104 cpi->ref_frame_flags = ref_frame_flags;
2107 int vp9_update_reference(VP9_PTR ptr, int ref_frame_flags) {
2108 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2110 if (ref_frame_flags > 7)
2113 cpi->refresh_golden_frame = 0;
2114 cpi->refresh_alt_ref_frame = 0;
2115 cpi->refresh_last_frame = 0;
2117 if (ref_frame_flags & VP9_LAST_FLAG)
2118 cpi->refresh_last_frame = 1;
2120 if (ref_frame_flags & VP9_GOLD_FLAG)
2121 cpi->refresh_golden_frame = 1;
2123 if (ref_frame_flags & VP9_ALT_FLAG)
2124 cpi->refresh_alt_ref_frame = 1;
2129 int vp9_copy_reference_enc(VP9_PTR ptr, VP9_REFFRAME ref_frame_flag,
2130 YV12_BUFFER_CONFIG *sd) {
2131 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2132 VP9_COMMON *cm = &cpi->common;
2135 if (ref_frame_flag == VP9_LAST_FLAG)
2136 ref_fb_idx = cm->ref_frame_map[cpi->lst_fb_idx];
2137 else if (ref_frame_flag == VP9_GOLD_FLAG)
2138 ref_fb_idx = cm->ref_frame_map[cpi->gld_fb_idx];
2139 else if (ref_frame_flag == VP9_ALT_FLAG)
2140 ref_fb_idx = cm->ref_frame_map[cpi->alt_fb_idx];
2144 vp8_yv12_copy_frame(&cm->yv12_fb[ref_fb_idx], sd);
2149 int vp9_get_reference_enc(VP9_PTR ptr, int index, YV12_BUFFER_CONFIG **fb) {
2150 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2151 VP9_COMMON *cm = &cpi->common;
2153 if (index < 0 || index >= NUM_REF_FRAMES)
2156 *fb = &cm->yv12_fb[cm->ref_frame_map[index]];
2160 int vp9_set_reference_enc(VP9_PTR ptr, VP9_REFFRAME ref_frame_flag,
2161 YV12_BUFFER_CONFIG *sd) {
2162 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2163 VP9_COMMON *cm = &cpi->common;
2167 if (ref_frame_flag == VP9_LAST_FLAG)
2168 ref_fb_idx = cm->ref_frame_map[cpi->lst_fb_idx];
2169 else if (ref_frame_flag == VP9_GOLD_FLAG)
2170 ref_fb_idx = cm->ref_frame_map[cpi->gld_fb_idx];
2171 else if (ref_frame_flag == VP9_ALT_FLAG)
2172 ref_fb_idx = cm->ref_frame_map[cpi->alt_fb_idx];
2176 vp8_yv12_copy_frame(sd, &cm->yv12_fb[ref_fb_idx]);
2180 int vp9_update_entropy(VP9_PTR comp, int update) {
2181 ((VP9_COMP *)comp)->common.refresh_frame_context = update;
2186 #ifdef OUTPUT_YUV_SRC
2187 void vp9_write_yuv_frame(YV12_BUFFER_CONFIG *s) {
2188 uint8_t *src = s->y_buffer;
2189 int h = s->y_height;
2192 fwrite(src, s->y_width, 1, yuv_file);
2200 fwrite(src, s->uv_width, 1, yuv_file);
2201 src += s->uv_stride;
2208 fwrite(src, s->uv_width, 1, yuv_file);
2209 src += s->uv_stride;
2214 #ifdef OUTPUT_YUV_REC
2215 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
2216 YV12_BUFFER_CONFIG *s = cm->frame_to_show;
2217 uint8_t *src = s->y_buffer;
2221 fwrite(src, s->y_width, 1, yuv_rec_file);
2229 fwrite(src, s->uv_width, 1, yuv_rec_file);
2230 src += s->uv_stride;
2237 fwrite(src, s->uv_width, 1, yuv_rec_file);
2238 src += s->uv_stride;
2242 if (s->alpha_buffer) {
2243 src = s->alpha_buffer;
2244 h = s->alpha_height;
2246 fwrite(src, s->alpha_width, 1, yuv_rec_file);
2247 src += s->alpha_stride;
2252 fflush(yuv_rec_file);
2256 static void scale_and_extend_frame(YV12_BUFFER_CONFIG *src_fb,
2257 YV12_BUFFER_CONFIG *dst_fb) {
2258 const int in_w = src_fb->y_crop_width;
2259 const int in_h = src_fb->y_crop_height;
2260 const int out_w = dst_fb->y_crop_width;
2261 const int out_h = dst_fb->y_crop_height;
2264 uint8_t *srcs[4] = {src_fb->y_buffer, src_fb->u_buffer, src_fb->v_buffer,
2265 src_fb->alpha_buffer};
2266 int src_strides[4] = {src_fb->y_stride, src_fb->uv_stride, src_fb->uv_stride,
2267 src_fb->alpha_stride};
2269 uint8_t *dsts[4] = {dst_fb->y_buffer, dst_fb->u_buffer, dst_fb->v_buffer,
2270 dst_fb->alpha_buffer};
2271 int dst_strides[4] = {dst_fb->y_stride, dst_fb->uv_stride, dst_fb->uv_stride,
2272 dst_fb->alpha_stride};
2274 for (y = 0; y < out_h; y += 16) {
2275 for (x = 0; x < out_w; x += 16) {
2276 for (i = 0; i < MAX_MB_PLANE; ++i) {
2277 const int factor = i == 0 ? 1 : 2;
2278 const int x_q4 = x * (16 / factor) * in_w / out_w;
2279 const int y_q4 = y * (16 / factor) * in_h / out_h;
2280 const int src_stride = src_strides[i];
2281 const int dst_stride = dst_strides[i];
2282 uint8_t *src = srcs[i] + y / factor * in_h / out_h * src_stride +
2283 x / factor * in_w / out_w;
2284 uint8_t *dst = dsts[i] + y / factor * dst_stride + x / factor;
2286 vp9_convolve8(src, src_stride, dst, dst_stride,
2287 vp9_sub_pel_filters_8[x_q4 & 0xf], 16 * in_w / out_w,
2288 vp9_sub_pel_filters_8[y_q4 & 0xf], 16 * in_h / out_h,
2289 16 / factor, 16 / factor);
2294 vp8_yv12_extend_frame_borders(dst_fb);
2298 static void update_alt_ref_frame_stats(VP9_COMP *cpi) {
2299 // this frame refreshes means next frames don't unless specified by user
2300 cpi->rc.frames_since_golden = 0;
2302 #if CONFIG_MULTIPLE_ARF
2303 if (!cpi->multi_arf_enabled)
2305 // Clear the alternate reference update pending flag.
2306 cpi->source_alt_ref_pending = 0;
2308 // Set the alternate reference frame active flag
2309 cpi->source_alt_ref_active = 1;
2311 static void update_golden_frame_stats(VP9_COMP *cpi) {
2312 // Update the Golden frame usage counts.
2313 if (cpi->refresh_golden_frame) {
2314 // this frame refreshes means next frames don't unless specified by user
2315 cpi->refresh_golden_frame = 0;
2316 cpi->rc.frames_since_golden = 0;
2318 // ******** Fixed Q test code only ************
2319 // If we are going to use the ALT reference for the next group of frames
2320 // set a flag to say so.
2321 if (cpi->oxcf.fixed_q >= 0 &&
2322 cpi->oxcf.play_alternate && !cpi->refresh_alt_ref_frame) {
2323 cpi->source_alt_ref_pending = 1;
2324 cpi->rc.frames_till_gf_update_due = cpi->rc.baseline_gf_interval;
2326 // TODO(ivan): For SVC encoder, GF automatic update is disabled by using
2327 // a large GF_interval.
2329 cpi->rc.frames_till_gf_update_due = INT_MAX;
2333 if (!cpi->source_alt_ref_pending)
2334 cpi->source_alt_ref_active = 0;
2336 // Decrement count down till next gf
2337 if (cpi->rc.frames_till_gf_update_due > 0)
2338 cpi->rc.frames_till_gf_update_due--;
2340 } else if (!cpi->refresh_alt_ref_frame) {
2341 // Decrement count down till next gf
2342 if (cpi->rc.frames_till_gf_update_due > 0)
2343 cpi->rc.frames_till_gf_update_due--;
2345 if (cpi->frames_till_alt_ref_frame)
2346 cpi->frames_till_alt_ref_frame--;
2348 cpi->rc.frames_since_golden++;
2352 static int find_fp_qindex() {
2355 for (i = 0; i < QINDEX_RANGE; i++) {
2356 if (vp9_convert_qindex_to_q(i) >= 30.0) {
2361 if (i == QINDEX_RANGE)
2367 static void Pass1Encode(VP9_COMP *cpi, unsigned long *size, unsigned char *dest,
2368 unsigned int *frame_flags) {
2373 vp9_set_quantizer(cpi, find_fp_qindex());
2374 vp9_first_pass(cpi);
2377 #define WRITE_RECON_BUFFER 0
2378 #if WRITE_RECON_BUFFER
2379 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame) {
2384 snprintf(filename, sizeof(filename), "cx\\y%04d.raw", this_frame);
2385 yframe = fopen(filename, "wb");
2387 for (i = 0; i < frame->y_height; i++)
2388 fwrite(frame->y_buffer + i * frame->y_stride,
2389 frame->y_width, 1, yframe);
2392 snprintf(filename, sizeof(filename), "cx\\u%04d.raw", this_frame);
2393 yframe = fopen(filename, "wb");
2395 for (i = 0; i < frame->uv_height; i++)
2396 fwrite(frame->u_buffer + i * frame->uv_stride,
2397 frame->uv_width, 1, yframe);
2400 snprintf(filename, sizeof(filename), "cx\\v%04d.raw", this_frame);
2401 yframe = fopen(filename, "wb");
2403 for (i = 0; i < frame->uv_height; i++)
2404 fwrite(frame->v_buffer + i * frame->uv_stride,
2405 frame->uv_width, 1, yframe);
2411 static double compute_edge_pixel_proportion(YV12_BUFFER_CONFIG *frame) {
2412 #define EDGE_THRESH 128
2414 int num_edge_pels = 0;
2415 int num_pels = (frame->y_height - 2) * (frame->y_width - 2);
2416 uint8_t *prev = frame->y_buffer + 1;
2417 uint8_t *curr = frame->y_buffer + 1 + frame->y_stride;
2418 uint8_t *next = frame->y_buffer + 1 + 2 * frame->y_stride;
2419 for (i = 1; i < frame->y_height - 1; i++) {
2420 for (j = 1; j < frame->y_width - 1; j++) {
2421 /* Sobel hor and ver gradients */
2422 int v = 2 * (curr[1] - curr[-1]) + (prev[1] - prev[-1]) +
2423 (next[1] - next[-1]);
2424 int h = 2 * (prev[0] - next[0]) + (prev[1] - next[1]) +
2425 (prev[-1] - next[-1]);
2426 h = (h < 0 ? -h : h);
2427 v = (v < 0 ? -v : v);
2428 if (h > EDGE_THRESH || v > EDGE_THRESH)
2434 curr += frame->y_stride - frame->y_width + 2;
2435 prev += frame->y_stride - frame->y_width + 2;
2436 next += frame->y_stride - frame->y_width + 2;
2438 return (double)num_edge_pels / num_pels;
2441 // Function to test for conditions that indicate we should loop
2442 // back and recode a frame.
2443 static int recode_loop_test(VP9_COMP *cpi,
2444 int high_limit, int low_limit,
2445 int q, int maxq, int minq) {
2446 int force_recode = 0;
2447 VP9_COMMON *cm = &cpi->common;
2449 // Is frame recode allowed at all
2450 // Yes if either recode mode 1 is selected or mode two is selected
2451 // and the frame is a key frame. golden frame or alt_ref_frame
2452 if ((cpi->sf.recode_loop == 1) ||
2453 ((cpi->sf.recode_loop == 2) &&
2454 ((cm->frame_type == KEY_FRAME) ||
2455 cpi->refresh_golden_frame ||
2456 cpi->refresh_alt_ref_frame))) {
2457 // General over and under shoot tests
2458 if (((cpi->rc.projected_frame_size > high_limit) && (q < maxq)) ||
2459 ((cpi->rc.projected_frame_size < low_limit) && (q > minq))) {
2461 } else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
2462 // Deal with frame undershoot and whether or not we are
2463 // below the automatically set cq level.
2464 if (q > cpi->cq_target_quality &&
2465 cpi->rc.projected_frame_size <
2466 ((cpi->rc.this_frame_target * 7) >> 3)) {
2468 } else if (q > cpi->oxcf.cq_level &&
2469 cpi->rc.projected_frame_size < cpi->rc.min_frame_bandwidth &&
2470 cpi->rc.active_best_quality > cpi->oxcf.cq_level) {
2471 // Severe undershoot and between auto and user cq level
2473 cpi->rc.active_best_quality = cpi->oxcf.cq_level;
2478 return force_recode;
2481 static void update_reference_frames(VP9_COMP * const cpi) {
2482 VP9_COMMON * const cm = &cpi->common;
2484 // At this point the new frame has been encoded.
2485 // If any buffer copy / swapping is signaled it should be done here.
2486 if (cm->frame_type == KEY_FRAME) {
2487 ref_cnt_fb(cm->fb_idx_ref_cnt,
2488 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2489 ref_cnt_fb(cm->fb_idx_ref_cnt,
2490 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2492 #if CONFIG_MULTIPLE_ARF
2493 else if (!cpi->multi_arf_enabled && cpi->refresh_golden_frame &&
2494 !cpi->refresh_alt_ref_frame) {
2496 else if (cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame &&
2499 /* Preserve the previously existing golden frame and update the frame in
2500 * the alt ref slot instead. This is highly specific to the current use of
2501 * alt-ref as a forward reference, and this needs to be generalized as
2502 * other uses are implemented (like RTC/temporal scaling)
2504 * The update to the buffer in the alt ref slot was signaled in
2505 * vp9_pack_bitstream(), now swap the buffer pointers so that it's treated
2506 * as the golden frame next time.
2510 ref_cnt_fb(cm->fb_idx_ref_cnt,
2511 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2513 tmp = cpi->alt_fb_idx;
2514 cpi->alt_fb_idx = cpi->gld_fb_idx;
2515 cpi->gld_fb_idx = tmp;
2516 } else { /* For non key/golden frames */
2517 if (cpi->refresh_alt_ref_frame) {
2518 int arf_idx = cpi->alt_fb_idx;
2519 #if CONFIG_MULTIPLE_ARF
2520 if (cpi->multi_arf_enabled) {
2521 arf_idx = cpi->arf_buffer_idx[cpi->sequence_number + 1];
2524 ref_cnt_fb(cm->fb_idx_ref_cnt,
2525 &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
2528 if (cpi->refresh_golden_frame) {
2529 ref_cnt_fb(cm->fb_idx_ref_cnt,
2530 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2534 if (cpi->refresh_last_frame) {
2535 ref_cnt_fb(cm->fb_idx_ref_cnt,
2536 &cm->ref_frame_map[cpi->lst_fb_idx], cm->new_fb_idx);
2540 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
2541 MACROBLOCKD *xd = &cpi->mb.e_mbd;
2542 struct loopfilter *lf = &cm->lf;
2544 lf->filter_level = 0;
2546 struct vpx_usec_timer timer;
2548 vp9_clear_system_state();
2550 vpx_usec_timer_start(&timer);
2552 vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.use_fast_lpf_pick);
2554 vpx_usec_timer_mark(&timer);
2555 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
2558 if (lf->filter_level > 0) {
2559 vp9_set_alt_lf_level(cpi, lf->filter_level);
2560 vp9_loop_filter_frame(cm, xd, lf->filter_level, 0, 0);
2563 vp9_extend_frame_inner_borders(cm->frame_to_show,
2564 cm->subsampling_x, cm->subsampling_y);
2567 static void scale_references(VP9_COMP *cpi) {
2568 VP9_COMMON *cm = &cpi->common;
2570 int refs[ALLOWED_REFS_PER_FRAME] = {cpi->lst_fb_idx, cpi->gld_fb_idx,
2573 for (i = 0; i < 3; i++) {
2574 YV12_BUFFER_CONFIG *ref = &cm->yv12_fb[cm->ref_frame_map[refs[i]]];
2576 if (ref->y_crop_width != cm->width ||
2577 ref->y_crop_height != cm->height) {
2578 int new_fb = get_free_fb(cm);
2580 vp9_realloc_frame_buffer(&cm->yv12_fb[new_fb],
2581 cm->width, cm->height,
2582 cm->subsampling_x, cm->subsampling_y,
2584 scale_and_extend_frame(ref, &cm->yv12_fb[new_fb]);
2585 cpi->scaled_ref_idx[i] = new_fb;
2587 cpi->scaled_ref_idx[i] = cm->ref_frame_map[refs[i]];
2588 cm->fb_idx_ref_cnt[cm->ref_frame_map[refs[i]]]++;
2593 static void release_scaled_references(VP9_COMP *cpi) {
2594 VP9_COMMON *cm = &cpi->common;
2597 for (i = 0; i < 3; i++)
2598 cm->fb_idx_ref_cnt[cpi->scaled_ref_idx[i]]--;
2601 static void full_to_model_count(unsigned int *model_count,
2602 unsigned int *full_count) {
2604 model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
2605 model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
2606 model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
2607 for (n = THREE_TOKEN; n < DCT_EOB_TOKEN; ++n)
2608 model_count[TWO_TOKEN] += full_count[n];
2609 model_count[DCT_EOB_MODEL_TOKEN] = full_count[DCT_EOB_TOKEN];
2612 static void full_to_model_counts(
2613 vp9_coeff_count_model *model_count, vp9_coeff_count *full_count) {
2615 for (i = 0; i < BLOCK_TYPES; ++i)
2616 for (j = 0; j < REF_TYPES; ++j)
2617 for (k = 0; k < COEF_BANDS; ++k)
2618 for (l = 0; l < PREV_COEF_CONTEXTS; ++l) {
2619 if (l >= 3 && k == 0)
2621 full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
2625 #if 0 && CONFIG_INTERNAL_STATS
2626 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
2627 VP9_COMMON *const cm = &cpi->common;
2628 FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
2631 vp9_clear_system_state(); // __asm emms;
2633 recon_err = vp9_calc_ss_err(cpi->Source, get_frame_new_buffer(cm));
2635 if (cpi->twopass.total_left_stats.coded_error != 0.0)
2636 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %10d"
2637 "%7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f"
2638 "%6d %6d %5d %5d %5d %8.2f %10d %10.3f"
2639 "%10.3f %8d %10d %10d %10d\n",
2640 cpi->common.current_video_frame, cpi->rc.this_frame_target,
2641 cpi->rc.projected_frame_size, 0,
2642 (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
2643 (int)cpi->rc.total_target_vs_actual,
2644 (int)(cpi->oxcf.starting_buffer_level - cpi->rc.bits_off_target),
2645 (int)cpi->rc.total_actual_bits, cm->base_qindex,
2646 vp9_convert_qindex_to_q(cm->base_qindex),
2647 (double)vp9_dc_quant(cm->base_qindex, 0) / 4.0,
2648 vp9_convert_qindex_to_q(cpi->rc.active_best_quality),
2649 vp9_convert_qindex_to_q(cpi->rc.active_worst_quality), cpi->rc.avg_q,
2650 vp9_convert_qindex_to_q(cpi->rc.ni_av_qi),
2651 vp9_convert_qindex_to_q(cpi->cq_target_quality),
2652 cpi->refresh_last_frame, cpi->refresh_golden_frame,
2653 cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
2654 cpi->twopass.est_max_qcorrection_factor, (int)cpi->twopass.bits_left,
2655 cpi->twopass.total_left_stats.coded_error,
2656 (double)cpi->twopass.bits_left /
2657 (1 + cpi->twopass.total_left_stats.coded_error),
2658 cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
2659 cpi->kf_zeromotion_pct);
2664 FILE *const fmodes = fopen("Modes.stt", "a");
2667 fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
2668 cm->frame_type, cpi->refresh_golden_frame,
2669 cpi->refresh_alt_ref_frame);
2671 for (i = 0; i < MAX_MODES; ++i)
2672 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
2673 for (i = 0; i < MAX_REFS; ++i)
2674 fprintf(fmodes, "%5d ", cpi->sub8x8_mode_chosen_counts[i]);
2676 fprintf(fmodes, "\n");
2683 static void encode_with_recode_loop(VP9_COMP *cpi,
2684 unsigned long *size,
2689 int frame_over_shoot_limit,
2690 int frame_under_shoot_limit) {
2691 VP9_COMMON *const cm = &cpi->common;
2694 int overshoot_seen = 0;
2695 int undershoot_seen = 0;
2696 int q_low = bottom_index, q_high = top_index;
2698 vp9_clear_system_state(); // __asm emms;
2700 vp9_set_quantizer(cpi, q);
2702 if (loop_count == 0) {
2703 // Set up entropy context depending on frame type. The decoder mandates
2704 // the use of the default context, index 0, for keyframes and inter
2705 // frames where the error_resilient_mode or intra_only flag is set. For
2706 // other inter-frames the encoder currently uses only two contexts;
2707 // context 1 for ALTREF frames and context 0 for the others.
2708 if (cm->frame_type == KEY_FRAME) {
2709 vp9_setup_key_frame(cpi);
2711 if (!cm->intra_only && !cm->error_resilient_mode) {
2712 cpi->common.frame_context_idx = cpi->refresh_alt_ref_frame;
2714 vp9_setup_inter_frame(cpi);
2718 // Variance adaptive and in frame q adjustment experiments are mutually
2720 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
2721 vp9_vaq_frame_setup(cpi);
2722 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
2723 setup_in_frame_q_adj(cpi);
2726 // transform / motion compensation build reconstruction frame
2728 vp9_encode_frame(cpi);
2730 // Update the skip mb flag probabilities based on the distribution
2731 // seen in the last encoder iteration.
2732 // update_base_skip_probs(cpi);
2734 vp9_clear_system_state(); // __asm emms;
2736 // Dummy pack of the bitstream using up to date stats to get an
2737 // accurate estimate of output frame size to determine if we need
2739 vp9_save_coding_context(cpi);
2740 cpi->dummy_packing = 1;
2741 vp9_pack_bitstream(cpi, dest, size);
2742 cpi->rc.projected_frame_size = (*size) << 3;
2743 vp9_restore_coding_context(cpi);
2745 if (frame_over_shoot_limit == 0)
2746 frame_over_shoot_limit = 1;
2748 if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
2751 // Special case handling for forced key frames
2752 if ((cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced) {
2754 int kf_err = vp9_calc_ss_err(cpi->Source, get_frame_new_buffer(cm));
2756 int high_err_target = cpi->ambient_err;
2757 int low_err_target = cpi->ambient_err >> 1;
2759 // Prevent possible divide by zero error below for perfect KF
2762 // The key frame is not good enough or we can afford
2763 // to make it better without undue risk of popping.
2764 if ((kf_err > high_err_target &&
2765 cpi->rc.projected_frame_size <= frame_over_shoot_limit) ||
2766 (kf_err > low_err_target &&
2767 cpi->rc.projected_frame_size <= frame_under_shoot_limit)) {
2769 q_high = q > q_low ? q - 1 : q_low;
2772 q = (q * high_err_target) / kf_err;
2773 q = MIN(q, (q_high + q_low) >> 1);
2774 } else if (kf_err < low_err_target &&
2775 cpi->rc.projected_frame_size >= frame_under_shoot_limit) {
2776 // The key frame is much better than the previous frame
2778 q_low = q < q_high ? q + 1 : q_high;
2781 q = (q * low_err_target) / kf_err;
2782 q = MIN(q, (q_high + q_low + 1) >> 1);
2785 // Clamp Q to upper and lower limits:
2786 q = clamp(q, q_low, q_high);
2789 } else if (recode_loop_test(
2790 cpi, frame_over_shoot_limit, frame_under_shoot_limit,
2791 q, top_index, bottom_index)) {
2792 // Is the projected frame size out of range and are we allowed
2793 // to attempt to recode.
2797 // Frame size out of permitted range:
2798 // Update correction factor & compute new Q to try...
2800 // Frame is too large
2801 if (cpi->rc.projected_frame_size > cpi->rc.this_frame_target) {
2802 // Raise Qlow as to at least the current value
2803 q_low = q < q_high ? q + 1 : q_high;
2805 if (undershoot_seen || loop_count > 1) {
2806 // Update rate_correction_factor unless
2807 vp9_update_rate_correction_factors(cpi, 1);
2809 q = (q_high + q_low + 1) / 2;
2811 // Update rate_correction_factor unless
2812 vp9_update_rate_correction_factors(cpi, 0);
2814 q = vp9_regulate_q(cpi, cpi->rc.this_frame_target);
2816 while (q < q_low && retries < 10) {
2817 vp9_update_rate_correction_factors(cpi, 0);
2818 q = vp9_regulate_q(cpi, cpi->rc.this_frame_target);
2825 // Frame is too small
2826 q_high = q > q_low ? q - 1 : q_low;
2828 if (overshoot_seen || loop_count > 1) {
2829 // Update rate_correction_factor unless
2830 // cpi->rc.active_worst_quality has changed.
2831 vp9_update_rate_correction_factors(cpi, 1);
2833 q = (q_high + q_low) / 2;
2835 // Update rate_correction_factor unless
2836 // cpi->rc.active_worst_quality has changed.
2837 vp9_update_rate_correction_factors(cpi, 0);
2839 q = vp9_regulate_q(cpi, cpi->rc.this_frame_target);
2841 // Special case reset for qlow for constrained quality.
2842 // This should only trigger where there is very substantial
2843 // undershoot on a frame and the auto cq level is above
2844 // the user passsed in value.
2845 if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY && q < q_low) {
2849 while (q > q_high && retries < 10) {
2850 vp9_update_rate_correction_factors(cpi, 0);
2851 q = vp9_regulate_q(cpi, cpi->rc.this_frame_target);
2856 undershoot_seen = 1;
2859 // Clamp Q to upper and lower limits:
2860 q = clamp(q, q_low, q_high);
2868 if (cpi->is_src_frame_alt_ref)
2874 #if CONFIG_INTERNAL_STATS
2875 cpi->tot_recode_hits++;
2881 static void encode_frame_to_data_rate(VP9_COMP *cpi,
2882 unsigned long *size,
2884 unsigned int *frame_flags) {
2885 VP9_COMMON *const cm = &cpi->common;
2888 int frame_over_shoot_limit;
2889 int frame_under_shoot_limit;
2894 SPEED_FEATURES *const sf = &cpi->sf;
2895 unsigned int max_mv_def = MIN(cpi->common.width, cpi->common.height);
2896 struct segmentation *const seg = &cm->seg;
2898 /* Scale the source buffer, if required. */
2899 if (cm->mi_cols * 8 != cpi->un_scaled_source->y_width ||
2900 cm->mi_rows * 8 != cpi->un_scaled_source->y_height) {
2901 scale_and_extend_frame(cpi->un_scaled_source, &cpi->scaled_source);
2902 cpi->Source = &cpi->scaled_source;
2904 cpi->Source = cpi->un_scaled_source;
2906 scale_references(cpi);
2908 // Clear down mmx registers to allow floating point in what follows.
2909 vp9_clear_system_state();
2911 // For an alt ref frame in 2 pass we skip the call to the second
2912 // pass function that sets the target bandwidth so we must set it here.
2913 if (cpi->refresh_alt_ref_frame) {
2914 // Set a per frame bit target for the alt ref frame.
2915 cpi->rc.per_frame_bandwidth = cpi->twopass.gf_bits;
2916 // Set a per second target bitrate.
2917 cpi->target_bandwidth = (int)(cpi->twopass.gf_bits * cpi->output_framerate);
2920 // Clear zbin over-quant value and mode boost values.
2921 cpi->zbin_mode_boost = 0;
2923 // Enable or disable mode based tweaking of the zbin.
2924 // For 2 pass only used where GF/ARF prediction quality
2925 // is above a threshold.
2926 cpi->zbin_mode_boost = 0;
2927 cpi->zbin_mode_boost_enabled = 0;
2929 // Current default encoder behavior for the altref sign bias.
2930 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = cpi->source_alt_ref_active;
2932 // Check to see if a key frame is signaled.
2933 // For two pass with auto key frame enabled cm->frame_type may already be
2934 // set, but not for one pass.
2935 if ((cm->current_video_frame == 0) ||
2936 (cm->frame_flags & FRAMEFLAGS_KEY) ||
2937 (cpi->oxcf.auto_key && (cpi->frames_since_key %
2938 cpi->key_frame_frequency == 0))) {
2939 // Set frame type to key frame for the force key frame, if we exceed the
2940 // maximum distance in an automatic keyframe selection or for the first
2942 cm->frame_type = KEY_FRAME;
2945 // Set default state for segment based loop filter update flags.
2946 cm->lf.mode_ref_delta_update = 0;
2948 // Initialize cpi->mv_step_param to default based on max resolution.
2949 cpi->mv_step_param = vp9_init_search_range(cpi, max_mv_def);
2950 // Initialize cpi->max_mv_magnitude and cpi->mv_step_param if appropriate.
2951 if (sf->auto_mv_step_size) {
2952 if (frame_is_intra_only(&cpi->common)) {
2953 // Initialize max_mv_magnitude for use in the first INTER frame
2954 // after a key/intra-only frame.
2955 cpi->max_mv_magnitude = max_mv_def;
2958 // Allow mv_steps to correspond to twice the max mv magnitude found
2959 // in the previous frame, capped by the default max_mv_magnitude based
2961 cpi->mv_step_param = vp9_init_search_range(
2962 cpi, MIN(max_mv_def, 2 * cpi->max_mv_magnitude));
2963 cpi->max_mv_magnitude = 0;
2967 // Set various flags etc to special state if it is a key frame.
2968 if (frame_is_intra_only(cm)) {
2969 vp9_setup_key_frame(cpi);
2970 // Reset the loop filter deltas and segmentation map.
2973 // If segmentation is enabled force a map update for key frames.
2975 seg->update_map = 1;
2976 seg->update_data = 1;
2979 // The alternate reference frame cannot be active for a key frame.
2980 cpi->source_alt_ref_active = 0;
2982 cm->error_resilient_mode = (cpi->oxcf.error_resilient_mode != 0);
2983 cm->frame_parallel_decoding_mode =
2984 (cpi->oxcf.frame_parallel_decoding_mode != 0);
2985 if (cm->error_resilient_mode) {
2986 cm->frame_parallel_decoding_mode = 1;
2987 cm->reset_frame_context = 0;
2988 cm->refresh_frame_context = 0;
2989 } else if (cm->intra_only) {
2990 // Only reset the current context.
2991 cm->reset_frame_context = 2;
2995 // Configure experimental use of segmentation for enhanced coding of
2996 // static regions if indicated.
2997 // Only allowed in second pass of two pass (as requires lagged coding)
2998 // and if the relevant speed feature flag is set.
2999 if ((cpi->pass == 2) && (cpi->sf.static_segmentation)) {
3000 configure_static_seg_features(cpi);
3003 // Decide how big to make the frame.
3004 vp9_pick_frame_size(cpi);
3006 vp9_clear_system_state();
3008 q = vp9_pick_q_and_adjust_q_bounds(cpi, &bottom_index, &top_index);
3010 vp9_compute_frame_size_bounds(cpi, &frame_under_shoot_limit,
3011 &frame_over_shoot_limit);
3013 #if CONFIG_MULTIPLE_ARF
3014 // Force the quantizer determined by the coding order pattern.
3015 if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
3016 cpi->oxcf.end_usage != USAGE_CONSTANT_QUALITY) {
3018 double current_q = vp9_convert_qindex_to_q(cpi->rc.active_worst_quality);
3019 int level = cpi->this_frame_weight;
3022 // Set quantizer steps at 10% increments.
3023 new_q = current_q * (1.0 - (0.2 * (cpi->max_arf_level - level)));
3024 q = cpi->rc.active_worst_quality +
3025 vp9_compute_qdelta(cpi, current_q, new_q);
3030 printf("frame:%d q:%d\n", cm->current_video_frame, q);
3034 vp9_zero(cpi->rd_tx_select_threshes);
3036 if (!frame_is_intra_only(cm)) {
3037 cm->mcomp_filter_type = DEFAULT_INTERP_FILTER;
3038 /* TODO: Decide this more intelligently */
3039 cm->allow_high_precision_mv = q < HIGH_PRECISION_MV_QTHRESH;
3043 #if CONFIG_VP9_POSTPROC
3044 if (cpi->oxcf.noise_sensitivity > 0) {
3046 switch (cpi->oxcf.noise_sensitivity) {
3064 vp9_denoise(cpi->Source, cpi->Source, l);
3068 #ifdef OUTPUT_YUV_SRC
3069 vp9_write_yuv_frame(cpi->Source);
3072 encode_with_recode_loop(cpi,
3078 frame_over_shoot_limit,
3079 frame_under_shoot_limit);
3081 // Special case code to reduce pulsing when key frames are forced at a
3082 // fixed interval. Note the reconstruction error if it is the frame before
3083 // the force key frame
3084 if (cpi->next_key_frame_forced && (cpi->twopass.frames_to_key == 0)) {
3085 cpi->ambient_err = vp9_calc_ss_err(cpi->Source, get_frame_new_buffer(cm));
3088 if (cm->frame_type == KEY_FRAME)
3089 cpi->refresh_last_frame = 1;
3091 cm->frame_to_show = get_frame_new_buffer(cm);
3093 #if WRITE_RECON_BUFFER
3095 write_cx_frame_to_file(cm->frame_to_show,
3096 cm->current_video_frame);
3098 write_cx_frame_to_file(cm->frame_to_show,
3099 cm->current_video_frame + 1000);
3102 // Pick the loop filter level for the frame.
3103 loopfilter_frame(cpi, cm);
3105 #if WRITE_RECON_BUFFER
3107 write_cx_frame_to_file(cm->frame_to_show,
3108 cm->current_video_frame + 2000);
3110 write_cx_frame_to_file(cm->frame_to_show,
3111 cm->current_video_frame + 3000);
3114 // build the bitstream
3115 cpi->dummy_packing = 0;
3116 vp9_pack_bitstream(cpi, dest, size);
3118 if (cm->seg.update_map)
3119 update_reference_segmentation_map(cpi);
3121 release_scaled_references(cpi);
3122 update_reference_frames(cpi);
3124 for (t = TX_4X4; t <= TX_32X32; t++)
3125 full_to_model_counts(cpi->common.counts.coef[t],
3126 cpi->coef_counts[t]);
3127 if (!cpi->common.error_resilient_mode &&
3128 !cpi->common.frame_parallel_decoding_mode) {
3129 vp9_adapt_coef_probs(&cpi->common);
3132 if (!frame_is_intra_only(&cpi->common)) {
3133 FRAME_COUNTS *counts = &cpi->common.counts;
3135 vp9_copy(counts->y_mode, cpi->y_mode_count);
3136 vp9_copy(counts->uv_mode, cpi->y_uv_mode_count);
3137 vp9_copy(counts->intra_inter, cpi->intra_inter_count);
3138 vp9_copy(counts->comp_inter, cpi->comp_inter_count);
3139 vp9_copy(counts->single_ref, cpi->single_ref_count);
3140 vp9_copy(counts->comp_ref, cpi->comp_ref_count);
3141 counts->mv = cpi->NMVcount;
3142 if (!cpi->common.error_resilient_mode &&
3143 !cpi->common.frame_parallel_decoding_mode) {
3144 vp9_adapt_mode_probs(&cpi->common);
3145 vp9_adapt_mv_probs(&cpi->common, cpi->common.allow_high_precision_mv);
3149 #ifdef ENTROPY_STATS
3150 vp9_update_mode_context_stats(cpi);
3153 /* Move storing frame_type out of the above loop since it is also
3154 * needed in motion search besides loopfilter */
3155 cm->last_frame_type = cm->frame_type;
3157 // Update rate control heuristics
3158 cpi->rc.projected_frame_size = (*size) << 3;
3160 // Post encode loop adjustment of Q prediction.
3161 vp9_update_rate_correction_factors(
3162 cpi, (cpi->sf.recode_loop ||
3163 cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) ? 2 : 0);
3166 cpi->rc.last_q[cm->frame_type] = cm->base_qindex;
3168 // Keep record of last boosted (KF/KF/ARF) Q value.
3169 // If the current frame is coded at a lower Q then we also update it.
3170 // If all mbs in this group are skipped only update if the Q value is
3171 // better than that already stored.
3172 // This is used to help set quality in forced key frames to reduce popping
3173 if ((cm->base_qindex < cpi->rc.last_boosted_qindex) ||
3174 ((cpi->static_mb_pct < 100) &&
3175 ((cm->frame_type == KEY_FRAME) ||
3176 cpi->refresh_alt_ref_frame ||
3177 (cpi->refresh_golden_frame && !cpi->is_src_frame_alt_ref)))) {
3178 cpi->rc.last_boosted_qindex = cm->base_qindex;
3181 if (cm->frame_type == KEY_FRAME) {
3182 vp9_adjust_key_frame_context(cpi);
3185 // Keep a record of ambient average Q.
3186 if (cm->frame_type != KEY_FRAME)
3187 cpi->rc.avg_frame_qindex = (2 + 3 * cpi->rc.avg_frame_qindex +
3188 cm->base_qindex) >> 2;
3190 // Keep a record from which we can calculate the average Q excluding GF
3191 // updates and key frames.
3192 if (cm->frame_type != KEY_FRAME &&
3193 !cpi->refresh_golden_frame &&
3194 !cpi->refresh_alt_ref_frame) {
3195 cpi->rc.ni_frames++;
3196 cpi->rc.tot_q += vp9_convert_qindex_to_q(q);
3197 cpi->rc.avg_q = cpi->rc.tot_q / (double)cpi->rc.ni_frames;
3199 // Calculate the average Q for normal inter frames (not key or GFU frames).
3200 cpi->rc.ni_tot_qi += q;
3201 cpi->rc.ni_av_qi = cpi->rc.ni_tot_qi / cpi->rc.ni_frames;
3204 // Update the buffer level variable.
3205 // Non-viewable frames are a special case and are treated as pure overhead.
3206 if (!cm->show_frame)
3207 cpi->rc.bits_off_target -= cpi->rc.projected_frame_size;
3209 cpi->rc.bits_off_target += cpi->rc.av_per_frame_bandwidth -
3210 cpi->rc.projected_frame_size;
3212 // Clip the buffer level at the maximum buffer size
3213 if (cpi->rc.bits_off_target > cpi->oxcf.maximum_buffer_size)
3214 cpi->rc.bits_off_target = cpi->oxcf.maximum_buffer_size;
3216 // Rolling monitors of whether we are over or underspending used to help
3217 // regulate min and Max Q in two pass.
3218 if (cm->frame_type != KEY_FRAME) {
3219 cpi->rc.rolling_target_bits =
3220 ((cpi->rc.rolling_target_bits * 3) +
3221 cpi->rc.this_frame_target + 2) / 4;
3222 cpi->rc.rolling_actual_bits =
3223 ((cpi->rc.rolling_actual_bits * 3) +
3224 cpi->rc.projected_frame_size + 2) / 4;
3225 cpi->rc.long_rolling_target_bits =
3226 ((cpi->rc.long_rolling_target_bits * 31) +
3227 cpi->rc.this_frame_target + 16) / 32;
3228 cpi->rc.long_rolling_actual_bits =
3229 ((cpi->rc.long_rolling_actual_bits * 31) +
3230 cpi->rc.projected_frame_size + 16) / 32;
3233 // Actual bits spent
3234 cpi->rc.total_actual_bits += cpi->rc.projected_frame_size;
3237 cpi->rc.total_target_vs_actual += (cpi->rc.this_frame_target -
3238 cpi->rc.projected_frame_size);
3240 cpi->rc.buffer_level = cpi->rc.bits_off_target;
3242 #ifndef DISABLE_RC_LONG_TERM_MEM
3243 // Update bits left to the kf and gf groups to account for overshoot or
3244 // undershoot on these frames
3245 if (cm->frame_type == KEY_FRAME) {
3246 cpi->twopass.kf_group_bits += cpi->rc.this_frame_target -
3247 cpi->rc.projected_frame_size;
3249 cpi->twopass.kf_group_bits = MAX(cpi->twopass.kf_group_bits, 0);
3250 } else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) {
3251 cpi->twopass.gf_group_bits += cpi->rc.this_frame_target -
3252 cpi->rc.projected_frame_size;
3254 cpi->twopass.gf_group_bits = MAX(cpi->twopass.gf_group_bits, 0);
3259 output_frame_level_debug_stats(cpi);
3261 if (cpi->refresh_golden_frame == 1)
3262 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
3264 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_GOLDEN;
3266 if (cpi->refresh_alt_ref_frame == 1)
3267 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
3269 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_ALTREF;
3272 if (cpi->refresh_last_frame & cpi->refresh_golden_frame)
3273 cpi->gold_is_last = 1;
3274 else if (cpi->refresh_last_frame ^ cpi->refresh_golden_frame)
3275 cpi->gold_is_last = 0;
3277 if (cpi->refresh_last_frame & cpi->refresh_alt_ref_frame)
3278 cpi->alt_is_last = 1;
3279 else if (cpi->refresh_last_frame ^ cpi->refresh_alt_ref_frame)
3280 cpi->alt_is_last = 0;
3282 if (cpi->refresh_alt_ref_frame & cpi->refresh_golden_frame)
3283 cpi->gold_is_alt = 1;
3284 else if (cpi->refresh_alt_ref_frame ^ cpi->refresh_golden_frame)
3285 cpi->gold_is_alt = 0;
3287 cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
3289 if (cpi->gold_is_last)
3290 cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
3292 if (cpi->alt_is_last)
3293 cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
3295 if (cpi->gold_is_alt)
3296 cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
3298 if (cpi->oxcf.play_alternate && cpi->refresh_alt_ref_frame
3299 && (cm->frame_type != KEY_FRAME))
3300 // Update the alternate reference frame stats as appropriate.
3301 update_alt_ref_frame_stats(cpi);
3303 // Update the Golden frame stats as appropriate.
3304 update_golden_frame_stats(cpi);
3306 if (cm->frame_type == KEY_FRAME) {
3307 // Tell the caller that the frame was coded as a key frame
3308 *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
3310 #if CONFIG_MULTIPLE_ARF
3311 // Reset the sequence number.
3312 if (cpi->multi_arf_enabled) {
3313 cpi->sequence_number = 0;
3314 cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
3315 cpi->new_frame_coding_order_period = -1;
3319 // As this frame is a key frame the next defaults to an inter frame.
3320 cm->frame_type = INTER_FRAME;
3322 *frame_flags = cm->frame_flags&~FRAMEFLAGS_KEY;
3324 #if CONFIG_MULTIPLE_ARF
3325 /* Increment position in the coded frame sequence. */
3326 if (cpi->multi_arf_enabled) {
3327 ++cpi->sequence_number;
3328 if (cpi->sequence_number >= cpi->frame_coding_order_period) {
3329 cpi->sequence_number = 0;
3330 cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
3331 cpi->new_frame_coding_order_period = -1;
3333 cpi->this_frame_weight = cpi->arf_weight[cpi->sequence_number];
3334 assert(cpi->this_frame_weight >= 0);
3339 // Clear the one shot update flags for segmentation map and mode/ref loop
3341 cm->seg.update_map = 0;
3342 cm->seg.update_data = 0;
3343 cm->lf.mode_ref_delta_update = 0;
3345 // keep track of the last coded dimensions
3346 cm->last_width = cm->width;
3347 cm->last_height = cm->height;
3349 // reset to normal state now that we are done.
3350 cm->last_show_frame = cm->show_frame;
3351 if (cm->show_frame) {
3352 // current mip will be the prev_mip for the next frame
3353 MODE_INFO *temp = cm->prev_mip;
3354 MODE_INFO **temp2 = cm->prev_mi_grid_base;
3355 cm->prev_mip = cm->mip;
3357 cm->prev_mi_grid_base = cm->mi_grid_base;
3358 cm->mi_grid_base = temp2;
3360 // update the upper left visible macroblock ptrs
3361 cm->mi = cm->mip + cm->mode_info_stride + 1;
3362 cm->mi_grid_visible = cm->mi_grid_base + cm->mode_info_stride + 1;
3364 cpi->mb.e_mbd.mi_8x8 = cm->mi_grid_visible;
3365 cpi->mb.e_mbd.mi_8x8[0] = cm->mi;
3367 // Don't increment frame counters if this was an altref buffer
3368 // update not a real frame
3369 ++cm->current_video_frame;
3370 ++cpi->frames_since_key;
3373 cm->prev_mi = cm->prev_mip + cm->mode_info_stride + 1;
3374 cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mode_info_stride + 1;
3377 static void Pass2Encode(VP9_COMP *cpi, unsigned long *size,
3378 unsigned char *dest, unsigned int *frame_flags) {
3379 cpi->enable_encode_breakout = 1;
3381 if (!cpi->refresh_alt_ref_frame)
3382 vp9_second_pass(cpi);
3384 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3385 // vp9_print_modes_and_motion_vectors(&cpi->common, "encode.stt");
3386 #ifdef DISABLE_RC_LONG_TERM_MEM
3387 cpi->twopass.bits_left -= cpi->rc.this_frame_target;
3389 cpi->twopass.bits_left -= 8 * *size;
3392 if (!cpi->refresh_alt_ref_frame) {
3393 double lower_bounds_min_rate = FRAME_OVERHEAD_BITS * cpi->oxcf.framerate;
3394 double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth
3395 * cpi->oxcf.two_pass_vbrmin_section
3398 if (two_pass_min_rate < lower_bounds_min_rate)
3399 two_pass_min_rate = lower_bounds_min_rate;
3401 cpi->twopass.bits_left += (int64_t)(two_pass_min_rate
3402 / cpi->oxcf.framerate);
3406 static void check_initial_width(VP9_COMP *cpi, YV12_BUFFER_CONFIG *sd) {
3407 VP9_COMMON *cm = &cpi->common;
3408 if (!cpi->initial_width) {
3409 // TODO(jkoleszar): Support 1/4 subsampling?
3410 cm->subsampling_x = (sd != NULL) && sd->uv_width < sd->y_width;
3411 cm->subsampling_y = (sd != NULL) && sd->uv_height < sd->y_height;
3412 alloc_raw_frame_buffers(cpi);
3414 cpi->initial_width = cm->width;
3415 cpi->initial_height = cm->height;
3420 int vp9_receive_raw_frame(VP9_PTR ptr, unsigned int frame_flags,
3421 YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
3423 VP9_COMP *cpi = (VP9_COMP *) ptr;
3424 struct vpx_usec_timer timer;
3427 check_initial_width(cpi, sd);
3428 vpx_usec_timer_start(&timer);
3429 if (vp9_lookahead_push(cpi->lookahead, sd, time_stamp, end_time, frame_flags,
3430 cpi->active_map_enabled ? cpi->active_map : NULL))
3432 vpx_usec_timer_mark(&timer);
3433 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
3439 static int frame_is_reference(const VP9_COMP *cpi) {
3440 const VP9_COMMON *cm = &cpi->common;
3442 return cm->frame_type == KEY_FRAME ||
3443 cpi->refresh_last_frame ||
3444 cpi->refresh_golden_frame ||
3445 cpi->refresh_alt_ref_frame ||
3446 cm->refresh_frame_context ||
3447 cm->lf.mode_ref_delta_update ||
3448 cm->seg.update_map ||
3449 cm->seg.update_data;
3452 #if CONFIG_MULTIPLE_ARF
3453 int is_next_frame_arf(VP9_COMP *cpi) {
3454 // Negative entry in frame_coding_order indicates an ARF at this position.
3455 return cpi->frame_coding_order[cpi->sequence_number + 1] < 0 ? 1 : 0;
3459 int vp9_get_compressed_data(VP9_PTR ptr, unsigned int *frame_flags,
3460 unsigned long *size, unsigned char *dest,
3461 int64_t *time_stamp, int64_t *time_end, int flush) {
3462 VP9_COMP *cpi = (VP9_COMP *) ptr;
3463 VP9_COMMON *cm = &cpi->common;
3464 struct vpx_usec_timer cmptimer;
3465 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
3467 // FILE *fp_out = fopen("enc_frame_type.txt", "a");
3472 vpx_usec_timer_start(&cmptimer);
3476 cpi->common.allow_high_precision_mv = ALTREF_HIGH_PRECISION_MV;
3479 // Should we code an alternate reference frame.
3480 if (cpi->oxcf.play_alternate && cpi->source_alt_ref_pending) {
3483 #if CONFIG_MULTIPLE_ARF
3484 assert(!cpi->multi_arf_enabled ||
3485 cpi->frame_coding_order[cpi->sequence_number] < 0);
3487 if (cpi->multi_arf_enabled && (cpi->pass == 2))
3488 frames_to_arf = (-cpi->frame_coding_order[cpi->sequence_number])
3489 - cpi->next_frame_in_order;
3492 frames_to_arf = cpi->rc.frames_till_gf_update_due;
3494 assert(frames_to_arf < cpi->twopass.frames_to_key);
3496 if ((cpi->source = vp9_lookahead_peek(cpi->lookahead, frames_to_arf))) {
3497 #if CONFIG_MULTIPLE_ARF
3498 cpi->alt_ref_source[cpi->arf_buffered] = cpi->source;
3500 cpi->alt_ref_source = cpi->source;
3503 if (cpi->oxcf.arnr_max_frames > 0) {
3504 // Produce the filtered ARF frame.
3505 // TODO(agrange) merge these two functions.
3506 configure_arnr_filter(cpi, cm->current_video_frame + frames_to_arf,
3508 vp9_temporal_filter_prepare(cpi, frames_to_arf);
3509 vp9_extend_frame_borders(&cpi->alt_ref_buffer,
3510 cm->subsampling_x, cm->subsampling_y);
3511 force_src_buffer = &cpi->alt_ref_buffer;
3515 cpi->refresh_alt_ref_frame = 1;
3516 cpi->refresh_golden_frame = 0;
3517 cpi->refresh_last_frame = 0;
3518 cpi->is_src_frame_alt_ref = 0;
3520 // TODO(agrange) This needs to vary depending on where the next ARF is.
3521 cpi->frames_till_alt_ref_frame = frames_to_arf;
3523 #if CONFIG_MULTIPLE_ARF
3524 if (!cpi->multi_arf_enabled)
3526 cpi->source_alt_ref_pending = 0; // Clear Pending altf Ref flag.
3531 #if CONFIG_MULTIPLE_ARF
3534 if ((cpi->source = vp9_lookahead_pop(cpi->lookahead, flush))) {
3538 #if CONFIG_MULTIPLE_ARF
3539 // Is this frame the ARF overlay.
3540 cpi->is_src_frame_alt_ref = 0;
3541 for (i = 0; i < cpi->arf_buffered; ++i) {
3542 if (cpi->source == cpi->alt_ref_source[i]) {
3543 cpi->is_src_frame_alt_ref = 1;
3544 cpi->refresh_golden_frame = 1;
3549 cpi->is_src_frame_alt_ref = cpi->alt_ref_source
3550 && (cpi->source == cpi->alt_ref_source);
3552 if (cpi->is_src_frame_alt_ref) {
3553 // Current frame is an ARF overlay frame.
3554 #if CONFIG_MULTIPLE_ARF
3555 cpi->alt_ref_source[i] = NULL;
3557 cpi->alt_ref_source = NULL;
3559 // Don't refresh the last buffer for an ARF overlay frame. It will
3560 // become the GF so preserve last as an alternative prediction option.
3561 cpi->refresh_last_frame = 0;
3563 #if CONFIG_MULTIPLE_ARF
3564 ++cpi->next_frame_in_order;
3570 cpi->un_scaled_source = cpi->Source = force_src_buffer ? force_src_buffer
3571 : &cpi->source->img;
3572 *time_stamp = cpi->source->ts_start;
3573 *time_end = cpi->source->ts_end;
3574 *frame_flags = cpi->source->flags;
3576 // fprintf(fp_out, " Frame:%d", cm->current_video_frame);
3577 #if CONFIG_MULTIPLE_ARF
3578 if (cpi->multi_arf_enabled) {
3579 // fprintf(fp_out, " seq_no:%d this_frame_weight:%d",
3580 // cpi->sequence_number, cpi->this_frame_weight);
3582 // fprintf(fp_out, "\n");
3585 // fprintf(fp_out, "\n");
3588 #if CONFIG_MULTIPLE_ARF
3589 if ((cm->frame_type != KEY_FRAME) && (cpi->pass == 2))
3590 cpi->source_alt_ref_pending = is_next_frame_arf(cpi);
3594 if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done) {
3595 vp9_end_first_pass(cpi); /* get last stats packet */
3596 cpi->twopass.first_pass_done = 1;
3603 if (cpi->source->ts_start < cpi->first_time_stamp_ever) {
3604 cpi->first_time_stamp_ever = cpi->source->ts_start;
3605 cpi->last_end_time_stamp_seen = cpi->source->ts_start;
3608 // adjust frame rates based on timestamps given
3609 if (!cpi->refresh_alt_ref_frame) {
3610 int64_t this_duration;
3613 if (cpi->source->ts_start == cpi->first_time_stamp_ever) {
3614 this_duration = cpi->source->ts_end - cpi->source->ts_start;
3617 int64_t last_duration = cpi->last_end_time_stamp_seen
3618 - cpi->last_time_stamp_seen;
3620 this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
3622 // do a step update if the duration changes by 10%
3624 step = (int)((this_duration - last_duration) * 10 / last_duration);
3627 if (this_duration) {
3629 vp9_new_framerate(cpi, 10000000.0 / this_duration);
3631 // Average this frame's rate into the last second's average
3632 // frame rate. If we haven't seen 1 second yet, then average
3633 // over the whole interval seen.
3634 const double interval = MIN((double)(cpi->source->ts_end
3635 - cpi->first_time_stamp_ever), 10000000.0);
3636 double avg_duration = 10000000.0 / cpi->oxcf.framerate;
3637 avg_duration *= (interval - avg_duration + this_duration);
3638 avg_duration /= interval;
3640 vp9_new_framerate(cpi, 10000000.0 / avg_duration);
3644 cpi->last_time_stamp_seen = cpi->source->ts_start;
3645 cpi->last_end_time_stamp_seen = cpi->source->ts_end;
3648 // start with a 0 size frame
3651 // Clear down mmx registers
3652 vp9_clear_system_state(); // __asm emms;
3654 /* find a free buffer for the new frame, releasing the reference previously
3657 cm->fb_idx_ref_cnt[cm->new_fb_idx]--;
3658 cm->new_fb_idx = get_free_fb(cm);
3660 #if CONFIG_MULTIPLE_ARF
3661 /* Set up the correct ARF frame. */
3662 if (cpi->refresh_alt_ref_frame) {
3663 ++cpi->arf_buffered;
3665 if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
3667 cpi->alt_fb_idx = cpi->arf_buffer_idx[cpi->sequence_number];
3671 /* Get the mapping of L/G/A to the reference buffer pool */
3672 cm->active_ref_idx[0] = cm->ref_frame_map[cpi->lst_fb_idx];
3673 cm->active_ref_idx[1] = cm->ref_frame_map[cpi->gld_fb_idx];
3674 cm->active_ref_idx[2] = cm->ref_frame_map[cpi->alt_fb_idx];
3676 #if 0 // CONFIG_MULTIPLE_ARF
3677 if (cpi->multi_arf_enabled) {
3678 fprintf(fp_out, " idx(%d, %d, %d, %d) active(%d, %d, %d)",
3679 cpi->lst_fb_idx, cpi->gld_fb_idx, cpi->alt_fb_idx, cm->new_fb_idx,
3680 cm->active_ref_idx[0], cm->active_ref_idx[1], cm->active_ref_idx[2]);
3681 if (cpi->refresh_alt_ref_frame)
3682 fprintf(fp_out, " type:ARF");
3683 if (cpi->is_src_frame_alt_ref)
3684 fprintf(fp_out, " type:OVERLAY[%d]", cpi->alt_fb_idx);
3685 fprintf(fp_out, "\n");
3689 cm->frame_type = INTER_FRAME;
3690 cm->frame_flags = *frame_flags;
3692 // Reset the frame pointers to the current frame size
3693 vp9_realloc_frame_buffer(get_frame_new_buffer(cm),
3694 cm->width, cm->height,
3695 cm->subsampling_x, cm->subsampling_y,
3698 // Calculate scaling factors for each of the 3 available references
3699 for (i = 0; i < ALLOWED_REFS_PER_FRAME; ++i) {
3700 vp9_setup_scale_factors(cm, i);
3701 if (vp9_is_scaled(&cm->active_ref_scale_comm[i]))
3702 vp9_extend_frame_borders(&cm->yv12_fb[cm->active_ref_idx[i]],
3703 cm->subsampling_x, cm->subsampling_y);
3706 vp9_setup_interp_filters(&cpi->mb.e_mbd, DEFAULT_INTERP_FILTER, cm);
3708 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3712 if (cpi->pass == 1) {
3713 Pass1Encode(cpi, size, dest, frame_flags);
3714 } else if (cpi->pass == 2) {
3715 Pass2Encode(cpi, size, dest, frame_flags);
3717 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3720 if (cm->refresh_frame_context)
3721 cm->frame_contexts[cm->frame_context_idx] = cm->fc;
3724 // if its a dropped frame honor the requests on subsequent frames
3725 cpi->droppable = !frame_is_reference(cpi);
3727 // return to normal state
3728 cm->reset_frame_context = 0;
3729 cm->refresh_frame_context = 1;
3730 cpi->refresh_alt_ref_frame = 0;
3731 cpi->refresh_golden_frame = 0;
3732 cpi->refresh_last_frame = 1;
3733 cm->frame_type = INTER_FRAME;
3736 vpx_usec_timer_mark(&cmptimer);
3737 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
3739 if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
3740 generate_psnr_packet(cpi);
3742 #if CONFIG_INTERNAL_STATS
3744 if (cpi->pass != 1) {
3745 cpi->bytes += *size;
3747 if (cm->show_frame) {
3750 if (cpi->b_calculate_psnr) {
3753 YV12_BUFFER_CONFIG *orig = cpi->Source;
3754 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
3755 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
3756 int y_samples = orig->y_height * orig->y_width;
3757 int uv_samples = orig->uv_height * orig->uv_width;
3758 int t_samples = y_samples + 2 * uv_samples;
3761 ye = (double)calc_plane_error(orig->y_buffer, orig->y_stride,
3762 recon->y_buffer, recon->y_stride,
3763 orig->y_crop_width, orig->y_crop_height);
3765 ue = (double)calc_plane_error(orig->u_buffer, orig->uv_stride,
3766 recon->u_buffer, recon->uv_stride,
3767 orig->uv_crop_width, orig->uv_crop_height);
3769 ve = (double)calc_plane_error(orig->v_buffer, orig->uv_stride,
3770 recon->v_buffer, recon->uv_stride,
3771 orig->uv_crop_width, orig->uv_crop_height);
3773 sq_error = ye + ue + ve;
3775 frame_psnr = vp9_mse2psnr(t_samples, 255.0, sq_error);
3777 cpi->total_y += vp9_mse2psnr(y_samples, 255.0, ye);
3778 cpi->total_u += vp9_mse2psnr(uv_samples, 255.0, ue);
3779 cpi->total_v += vp9_mse2psnr(uv_samples, 255.0, ve);
3780 cpi->total_sq_error += sq_error;
3781 cpi->total += frame_psnr;
3783 double frame_psnr2, frame_ssim2 = 0;
3785 #if CONFIG_VP9_POSTPROC
3786 vp9_deblock(cm->frame_to_show, &cm->post_proc_buffer,
3787 cm->lf.filter_level * 10 / 6);
3789 vp9_clear_system_state();
3791 ye = (double)calc_plane_error(orig->y_buffer, orig->y_stride,
3792 pp->y_buffer, pp->y_stride,
3793 orig->y_crop_width, orig->y_crop_height);
3795 ue = (double)calc_plane_error(orig->u_buffer, orig->uv_stride,
3796 pp->u_buffer, pp->uv_stride,
3797 orig->uv_crop_width, orig->uv_crop_height);
3799 ve = (double)calc_plane_error(orig->v_buffer, orig->uv_stride,
3800 pp->v_buffer, pp->uv_stride,
3801 orig->uv_crop_width, orig->uv_crop_height);
3803 sq_error = ye + ue + ve;
3805 frame_psnr2 = vp9_mse2psnr(t_samples, 255.0, sq_error);
3807 cpi->totalp_y += vp9_mse2psnr(y_samples, 255.0, ye);
3808 cpi->totalp_u += vp9_mse2psnr(uv_samples, 255.0, ue);
3809 cpi->totalp_v += vp9_mse2psnr(uv_samples, 255.0, ve);
3810 cpi->total_sq_error2 += sq_error;
3811 cpi->totalp += frame_psnr2;
3813 frame_ssim2 = vp9_calc_ssim(cpi->Source,
3816 cpi->summed_quality += frame_ssim2 * weight;
3817 cpi->summed_weights += weight;
3819 frame_ssim2 = vp9_calc_ssim(cpi->Source,
3820 &cm->post_proc_buffer, 1, &weight);
3822 cpi->summedp_quality += frame_ssim2 * weight;
3823 cpi->summedp_weights += weight;
3826 FILE *f = fopen("q_used.stt", "a");
3827 fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
3828 cpi->common.current_video_frame, y2, u2, v2,
3829 frame_psnr2, frame_ssim2);
3836 if (cpi->b_calculate_ssimg) {
3837 double y, u, v, frame_all;
3838 frame_all = vp9_calc_ssimg(cpi->Source, cm->frame_to_show,
3840 cpi->total_ssimg_y += y;
3841 cpi->total_ssimg_u += u;
3842 cpi->total_ssimg_v += v;
3843 cpi->total_ssimg_all += frame_all;
3853 int vp9_get_preview_raw_frame(VP9_PTR comp, YV12_BUFFER_CONFIG *dest,
3854 vp9_ppflags_t *flags) {
3855 VP9_COMP *cpi = (VP9_COMP *) comp;
3857 if (!cpi->common.show_frame) {
3861 #if CONFIG_VP9_POSTPROC
3862 ret = vp9_post_proc_frame(&cpi->common, dest, flags);
3865 if (cpi->common.frame_to_show) {
3866 *dest = *cpi->common.frame_to_show;
3867 dest->y_width = cpi->common.width;
3868 dest->y_height = cpi->common.height;
3869 dest->uv_height = cpi->common.height / 2;
3875 #endif // !CONFIG_VP9_POSTPROC
3876 vp9_clear_system_state();
3881 int vp9_set_roimap(VP9_PTR comp, unsigned char *map, unsigned int rows,
3882 unsigned int cols, int delta_q[MAX_SEGMENTS],
3883 int delta_lf[MAX_SEGMENTS],
3884 unsigned int threshold[MAX_SEGMENTS]) {
3885 VP9_COMP *cpi = (VP9_COMP *) comp;
3886 signed char feature_data[SEG_LVL_MAX][MAX_SEGMENTS];
3887 struct segmentation *seg = &cpi->common.seg;
3890 if (cpi->common.mb_rows != rows || cpi->common.mb_cols != cols)
3894 vp9_disable_segmentation((VP9_PTR)cpi);
3898 // Set the segmentation Map
3899 vp9_set_segmentation_map((VP9_PTR)cpi, map);
3901 // Activate segmentation.
3902 vp9_enable_segmentation((VP9_PTR)cpi);
3904 // Set up the quant, LF and breakout threshold segment data
3905 for (i = 0; i < MAX_SEGMENTS; i++) {
3906 feature_data[SEG_LVL_ALT_Q][i] = delta_q[i];
3907 feature_data[SEG_LVL_ALT_LF][i] = delta_lf[i];
3908 cpi->segment_encode_breakout[i] = threshold[i];
3911 // Enable the loop and quant changes in the feature mask
3912 for (i = 0; i < MAX_SEGMENTS; i++) {
3914 vp9_enable_segfeature(seg, i, SEG_LVL_ALT_Q);
3916 vp9_disable_segfeature(seg, i, SEG_LVL_ALT_Q);
3919 vp9_enable_segfeature(seg, i, SEG_LVL_ALT_LF);
3921 vp9_disable_segfeature(seg, i, SEG_LVL_ALT_LF);
3924 // Initialize the feature data structure
3925 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
3926 vp9_set_segment_data((VP9_PTR)cpi, &feature_data[0][0], SEGMENT_DELTADATA);
3931 int vp9_set_active_map(VP9_PTR comp, unsigned char *map,
3932 unsigned int rows, unsigned int cols) {
3933 VP9_COMP *cpi = (VP9_COMP *) comp;
3935 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
3937 vpx_memcpy(cpi->active_map, map, rows * cols);
3938 cpi->active_map_enabled = 1;
3940 cpi->active_map_enabled = 0;
3945 // cpi->active_map_enabled = 0;
3950 int vp9_set_internal_size(VP9_PTR comp,
3951 VPX_SCALING horiz_mode, VPX_SCALING vert_mode) {
3952 VP9_COMP *cpi = (VP9_COMP *) comp;
3953 VP9_COMMON *cm = &cpi->common;
3954 int hr = 0, hs = 0, vr = 0, vs = 0;
3956 if (horiz_mode > ONETWO || vert_mode > ONETWO)
3959 Scale2Ratio(horiz_mode, &hr, &hs);
3960 Scale2Ratio(vert_mode, &vr, &vs);
3962 // always go to the next whole number
3963 cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
3964 cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
3966 assert(cm->width <= cpi->initial_width);
3967 assert(cm->height <= cpi->initial_height);
3968 update_frame_size(cpi);
3972 int vp9_set_size_literal(VP9_PTR comp, unsigned int width,
3973 unsigned int height) {
3974 VP9_COMP *cpi = (VP9_COMP *)comp;
3975 VP9_COMMON *cm = &cpi->common;
3977 check_initial_width(cpi, NULL);
3981 if (cm->width * 5 < cpi->initial_width) {
3982 cm->width = cpi->initial_width / 5 + 1;
3983 printf("Warning: Desired width too small, changed to %d \n", cm->width);
3985 if (cm->width > cpi->initial_width) {
3986 cm->width = cpi->initial_width;
3987 printf("Warning: Desired width too large, changed to %d \n", cm->width);
3992 cm->height = height;
3993 if (cm->height * 5 < cpi->initial_height) {
3994 cm->height = cpi->initial_height / 5 + 1;
3995 printf("Warning: Desired height too small, changed to %d \n", cm->height);
3997 if (cm->height > cpi->initial_height) {
3998 cm->height = cpi->initial_height;
3999 printf("Warning: Desired height too large, changed to %d \n", cm->height);
4003 assert(cm->width <= cpi->initial_width);
4004 assert(cm->height <= cpi->initial_height);
4005 update_frame_size(cpi);
4009 void vp9_set_svc(VP9_PTR comp, int use_svc) {
4010 VP9_COMP *cpi = (VP9_COMP *)comp;
4011 cpi->use_svc = use_svc;
4015 int vp9_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest) {
4019 uint8_t *src = source->y_buffer;
4020 uint8_t *dst = dest->y_buffer;
4022 // Loop through the Y plane raw and reconstruction data summing
4023 // (square differences)
4024 for (i = 0; i < source->y_height; i += 16) {
4025 for (j = 0; j < source->y_width; j += 16) {
4027 total += vp9_mse16x16(src + j, source->y_stride, dst + j, dest->y_stride,
4031 src += 16 * source->y_stride;
4032 dst += 16 * dest->y_stride;
4039 int vp9_get_quantizer(VP9_PTR c) {
4040 return ((VP9_COMP *)c)->common.base_qindex;