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.
12 #include "vpx_config.h"
13 #include "vp9/common/vp9_filter.h"
14 #include "vp9/common/vp9_onyxc_int.h"
15 #include "vp9/common/vp9_reconinter.h"
16 #include "vp9/encoder/vp9_onyx_int.h"
17 #include "vp9/common/vp9_systemdependent.h"
18 #include "vp9/encoder/vp9_quantize.h"
19 #include "vp9/common/vp9_alloccommon.h"
20 #include "vp9/encoder/vp9_mcomp.h"
21 #include "vp9/encoder/vp9_firstpass.h"
22 #include "vp9/encoder/vp9_psnr.h"
23 #include "vpx_scale/vpx_scale.h"
24 #include "vp9/common/vp9_extend.h"
25 #include "vp9/encoder/vp9_ratectrl.h"
26 #include "vp9/common/vp9_quant_common.h"
27 #include "vp9/common/vp9_tile_common.h"
28 #include "vp9/encoder/vp9_segmentation.h"
29 #include "./vp9_rtcd.h"
30 #include "./vpx_scale_rtcd.h"
31 #if CONFIG_VP9_POSTPROC
32 #include "vp9/common/vp9_postproc.h"
34 #include "vpx_mem/vpx_mem.h"
35 #include "vpx_ports/vpx_timer.h"
37 #include "vp9/common/vp9_seg_common.h"
38 #include "vp9/encoder/vp9_mbgraph.h"
39 #include "vp9/common/vp9_pred_common.h"
40 #include "vp9/encoder/vp9_rdopt.h"
41 #include "vp9/encoder/vp9_bitstream.h"
42 #include "vp9/encoder/vp9_picklpf.h"
43 #include "vp9/common/vp9_mvref_common.h"
44 #include "vp9/encoder/vp9_temporal_filter.h"
50 extern void print_tree_update_probs();
52 static void set_default_lf_deltas(struct loopfilter *lf);
54 #define DEFAULT_INTERP_FILTER SWITCHABLE
56 #define SHARP_FILTER_QTHRESH 0 /* Q threshold for 8-tap sharp filter */
58 #define ALTREF_HIGH_PRECISION_MV 1 /* whether to use high precision mv
59 for altref computation */
60 #define HIGH_PRECISION_MV_QTHRESH 200 /* Q threshold for use of high precision
61 mv. Choose a very high value for
62 now so that HIGH_PRECISION is always
65 #if CONFIG_INTERNAL_STATS
68 extern double vp9_calc_ssim(YV12_BUFFER_CONFIG *source,
69 YV12_BUFFER_CONFIG *dest, int lumamask,
73 extern double vp9_calc_ssimg(YV12_BUFFER_CONFIG *source,
74 YV12_BUFFER_CONFIG *dest, double *ssim_y,
75 double *ssim_u, double *ssim_v);
80 // #define OUTPUT_YUV_REC
97 extern int intra_mode_stats[INTRA_MODES]
103 extern void init_tx_count_stats();
104 extern void write_tx_count_stats();
105 extern void init_switchable_interp_stats();
106 extern void write_switchable_interp_stats();
110 unsigned int frames_at_speed[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
113 #if defined(SECTIONBITS_OUTPUT)
114 extern unsigned __int64 Sectionbits[500];
117 extern void vp9_init_quantizer(VP9_COMP *cpi);
119 // Tables relating active max Q to active min Q
120 static int kf_low_motion_minq[QINDEX_RANGE];
121 static int kf_high_motion_minq[QINDEX_RANGE];
122 static int gf_low_motion_minq[QINDEX_RANGE];
123 static int gf_high_motion_minq[QINDEX_RANGE];
124 static int inter_minq[QINDEX_RANGE];
125 static int afq_low_motion_minq[QINDEX_RANGE];
126 static int afq_high_motion_minq[QINDEX_RANGE];
128 static INLINE void Scale2Ratio(int mode, int *hr, int *hs) {
154 // Functions to compute the active minq lookup table entries based on a
155 // formulaic approach to facilitate easier adjustment of the Q tables.
156 // The formulae were derived from computing a 3rd order polynomial best
157 // fit to the original data (after plotting real maxq vs minq (not q index))
158 static int calculate_minq_index(double maxq,
159 double x3, double x2, double x1, double c) {
161 const double minqtarget = MIN(((x3 * maxq + x2) * maxq + x1) * maxq + c,
164 // Special case handling to deal with the step from q2.0
165 // down to lossless mode represented by q 1.0.
166 if (minqtarget <= 2.0)
169 for (i = 0; i < QINDEX_RANGE; i++) {
170 if (minqtarget <= vp9_convert_qindex_to_q(i))
174 return QINDEX_RANGE - 1;
177 static void init_minq_luts(void) {
180 for (i = 0; i < QINDEX_RANGE; i++) {
181 const double maxq = vp9_convert_qindex_to_q(i);
184 kf_low_motion_minq[i] = calculate_minq_index(maxq,
189 kf_high_motion_minq[i] = calculate_minq_index(maxq,
195 gf_low_motion_minq[i] = calculate_minq_index(maxq,
200 gf_high_motion_minq[i] = calculate_minq_index(maxq,
205 inter_minq[i] = calculate_minq_index(maxq,
210 afq_low_motion_minq[i] = calculate_minq_index(maxq,
215 afq_high_motion_minq[i] = calculate_minq_index(maxq,
223 static void set_mvcost(MACROBLOCK *mb) {
224 if (mb->e_mbd.allow_high_precision_mv) {
225 mb->mvcost = mb->nmvcost_hp;
226 mb->mvsadcost = mb->nmvsadcost_hp;
228 mb->mvcost = mb->nmvcost;
229 mb->mvsadcost = mb->nmvsadcost;
233 void vp9_initialize_enc() {
234 static int init_done = 0;
237 vp9_initialize_common();
238 vp9_tokenize_initialize();
239 vp9_init_quant_tables();
242 // init_base_skip_probs();
247 static void setup_features(VP9_COMMON *cm) {
248 struct loopfilter *const lf = &cm->lf;
249 struct segmentation *const seg = &cm->seg;
251 // Set up default state for MB feature flags
255 seg->update_data = 0;
256 vpx_memset(seg->tree_probs, 255, sizeof(seg->tree_probs));
258 vp9_clearall_segfeatures(seg);
260 lf->mode_ref_delta_enabled = 0;
261 lf->mode_ref_delta_update = 0;
262 vp9_zero(lf->ref_deltas);
263 vp9_zero(lf->mode_deltas);
264 vp9_zero(lf->last_ref_deltas);
265 vp9_zero(lf->last_mode_deltas);
267 set_default_lf_deltas(lf);
270 static void dealloc_compressor_data(VP9_COMP *cpi) {
271 // Delete sementation map
272 vpx_free(cpi->segmentation_map);
273 cpi->segmentation_map = 0;
274 vpx_free(cpi->common.last_frame_seg_map);
275 cpi->common.last_frame_seg_map = 0;
276 vpx_free(cpi->coding_context.last_frame_seg_map_copy);
277 cpi->coding_context.last_frame_seg_map_copy = 0;
279 vpx_free(cpi->active_map);
282 vp9_free_frame_buffers(&cpi->common);
284 vp9_free_frame_buffer(&cpi->last_frame_uf);
285 vp9_free_frame_buffer(&cpi->scaled_source);
286 vp9_free_frame_buffer(&cpi->alt_ref_buffer);
287 vp9_lookahead_destroy(cpi->lookahead);
292 // Activity mask based per mb zbin adjustments
293 vpx_free(cpi->mb_activity_map);
294 cpi->mb_activity_map = 0;
295 vpx_free(cpi->mb_norm_activity_map);
296 cpi->mb_norm_activity_map = 0;
298 vpx_free(cpi->mb.pip);
302 // Computes a q delta (in "q index" terms) to get from a starting q value
305 static int compute_qdelta(VP9_COMP *cpi, double qstart, double qtarget) {
307 int start_index = cpi->worst_quality;
308 int target_index = cpi->worst_quality;
310 // Convert the average q value to an index.
311 for (i = cpi->best_quality; i < cpi->worst_quality; i++) {
313 if (vp9_convert_qindex_to_q(i) >= qstart)
317 // Convert the q target to an index
318 for (i = cpi->best_quality; i < cpi->worst_quality; i++) {
320 if (vp9_convert_qindex_to_q(i) >= qtarget)
324 return target_index - start_index;
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->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 = compute_qdelta(cpi, cpi->avg_q, (cpi->avg_q * 0.875));
370 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, (qi_delta - 2));
371 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
373 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
374 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
376 // Where relevant assume segment data is delta data
377 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->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 = compute_qdelta(cpi, cpi->avg_q,
392 (cpi->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;
451 void vp9_update_mode_context_stats(VP9_COMP *cpi) {
452 VP9_COMMON *cm = &cpi->common;
454 unsigned int (*inter_mode_counts)[INTER_MODES - 1][2] =
455 cm->fc.inter_mode_counts;
456 int64_t (*mv_ref_stats)[INTER_MODES - 1][2] = cpi->mv_ref_stats;
459 // Read the past stats counters
460 f = fopen("mode_context.bin", "rb");
462 vpx_memset(cpi->mv_ref_stats, 0, sizeof(cpi->mv_ref_stats));
464 fread(cpi->mv_ref_stats, sizeof(cpi->mv_ref_stats), 1, f);
468 // Add in the values for this frame
469 for (i = 0; i < INTER_MODE_CONTEXTS; i++) {
470 for (j = 0; j < INTER_MODES - 1; j++) {
471 mv_ref_stats[i][j][0] += (int64_t)inter_mode_counts[i][j][0];
472 mv_ref_stats[i][j][1] += (int64_t)inter_mode_counts[i][j][1];
476 // Write back the accumulated stats
477 f = fopen("mode_context.bin", "wb");
478 fwrite(cpi->mv_ref_stats, sizeof(cpi->mv_ref_stats), 1, f);
482 void print_mode_context(VP9_COMP *cpi) {
483 FILE *f = fopen("vp9_modecont.c", "a");
486 fprintf(f, "#include \"vp9_entropy.h\"\n");
489 "const int inter_mode_probs[INTER_MODE_CONTEXTS][INTER_MODES - 1] =");
491 for (j = 0; j < INTER_MODE_CONTEXTS; j++) {
492 fprintf(f, " {/* %d */ ", j);
494 for (i = 0; i < INTER_MODES - 1; i++) {
496 int64_t count = cpi->mv_ref_stats[j][i][0] + cpi->mv_ref_stats[j][i][1];
498 this_prob = ((cpi->mv_ref_stats[j][i][0] * 256) + (count >> 1)) / count;
503 fprintf(f, "%5d, ", this_prob);
511 #endif // ENTROPY_STATS
513 // DEBUG: Print out the segment id of each MB in the current frame.
514 static void print_seg_map(VP9_COMP *cpi) {
515 VP9_COMMON *cm = &cpi->common;
518 FILE *statsfile = fopen("segmap.stt", "a");
520 fprintf(statsfile, "%10d\n", cm->current_video_frame);
522 for (row = 0; row < cpi->common.mi_rows; row++) {
523 for (col = 0; col < cpi->common.mi_cols; col++) {
524 fprintf(statsfile, "%10d", cpi->segmentation_map[map_index]);
527 fprintf(statsfile, "\n");
529 fprintf(statsfile, "\n");
534 static void update_reference_segmentation_map(VP9_COMP *cpi) {
535 VP9_COMMON *const cm = &cpi->common;
537 MODE_INFO **mi_8x8, **mi_8x8_ptr = cm->mi_grid_visible;
538 uint8_t *cache_ptr = cm->last_frame_seg_map, *cache;
540 for (row = 0; row < cm->mi_rows; row++) {
543 for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
544 cache[0] = mi_8x8[0]->mbmi.segment_id;
545 mi_8x8_ptr += cm->mode_info_stride;
546 cache_ptr += cm->mi_cols;
550 static void set_default_lf_deltas(struct loopfilter *lf) {
551 lf->mode_ref_delta_enabled = 1;
552 lf->mode_ref_delta_update = 1;
554 vp9_zero(lf->ref_deltas);
555 vp9_zero(lf->mode_deltas);
557 // Test of ref frame deltas
558 lf->ref_deltas[INTRA_FRAME] = 2;
559 lf->ref_deltas[LAST_FRAME] = 0;
560 lf->ref_deltas[GOLDEN_FRAME] = -2;
561 lf->ref_deltas[ALTREF_FRAME] = -2;
563 lf->mode_deltas[0] = 0; // Zero
564 lf->mode_deltas[1] = 0; // New mv
567 static void set_rd_speed_thresholds(VP9_COMP *cpi, int mode) {
568 SPEED_FEATURES *sf = &cpi->sf;
571 // Set baseline threshold values
572 for (i = 0; i < MAX_MODES; ++i)
573 sf->thresh_mult[i] = mode == 0 ? -500 : 0;
575 sf->thresh_mult[THR_NEARESTMV] = 0;
576 sf->thresh_mult[THR_NEARESTG] = 0;
577 sf->thresh_mult[THR_NEARESTA] = 0;
579 sf->thresh_mult[THR_DC] += 1000;
581 sf->thresh_mult[THR_NEWMV] += 1000;
582 sf->thresh_mult[THR_NEWA] += 1000;
583 sf->thresh_mult[THR_NEWG] += 1000;
585 sf->thresh_mult[THR_NEARMV] += 1000;
586 sf->thresh_mult[THR_NEARA] += 1000;
587 sf->thresh_mult[THR_COMP_NEARESTLA] += 1000;
588 sf->thresh_mult[THR_COMP_NEARESTGA] += 1000;
590 sf->thresh_mult[THR_TM] += 1000;
592 sf->thresh_mult[THR_COMP_NEARLA] += 1500;
593 sf->thresh_mult[THR_COMP_NEWLA] += 2000;
594 sf->thresh_mult[THR_NEARG] += 1000;
595 sf->thresh_mult[THR_COMP_NEARGA] += 1500;
596 sf->thresh_mult[THR_COMP_NEWGA] += 2000;
598 sf->thresh_mult[THR_SPLITMV] += 2500;
599 sf->thresh_mult[THR_SPLITG] += 2500;
600 sf->thresh_mult[THR_SPLITA] += 2500;
601 sf->thresh_mult[THR_COMP_SPLITLA] += 4500;
602 sf->thresh_mult[THR_COMP_SPLITGA] += 4500;
604 sf->thresh_mult[THR_ZEROMV] += 2000;
605 sf->thresh_mult[THR_ZEROG] += 2000;
606 sf->thresh_mult[THR_ZEROA] += 2000;
607 sf->thresh_mult[THR_COMP_ZEROLA] += 2500;
608 sf->thresh_mult[THR_COMP_ZEROGA] += 2500;
610 sf->thresh_mult[THR_B_PRED] += 2500;
611 sf->thresh_mult[THR_H_PRED] += 2000;
612 sf->thresh_mult[THR_V_PRED] += 2000;
613 sf->thresh_mult[THR_D45_PRED ] += 2500;
614 sf->thresh_mult[THR_D135_PRED] += 2500;
615 sf->thresh_mult[THR_D117_PRED] += 2500;
616 sf->thresh_mult[THR_D153_PRED] += 2500;
617 sf->thresh_mult[THR_D207_PRED] += 2500;
618 sf->thresh_mult[THR_D63_PRED] += 2500;
620 /* disable frame modes if flags not set */
621 if (!(cpi->ref_frame_flags & VP9_LAST_FLAG)) {
622 sf->thresh_mult[THR_NEWMV ] = INT_MAX;
623 sf->thresh_mult[THR_NEARESTMV] = INT_MAX;
624 sf->thresh_mult[THR_ZEROMV ] = INT_MAX;
625 sf->thresh_mult[THR_NEARMV ] = INT_MAX;
626 sf->thresh_mult[THR_SPLITMV ] = INT_MAX;
628 if (!(cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
629 sf->thresh_mult[THR_NEARESTG ] = INT_MAX;
630 sf->thresh_mult[THR_ZEROG ] = INT_MAX;
631 sf->thresh_mult[THR_NEARG ] = INT_MAX;
632 sf->thresh_mult[THR_NEWG ] = INT_MAX;
633 sf->thresh_mult[THR_SPLITG ] = INT_MAX;
635 if (!(cpi->ref_frame_flags & VP9_ALT_FLAG)) {
636 sf->thresh_mult[THR_NEARESTA ] = INT_MAX;
637 sf->thresh_mult[THR_ZEROA ] = INT_MAX;
638 sf->thresh_mult[THR_NEARA ] = INT_MAX;
639 sf->thresh_mult[THR_NEWA ] = INT_MAX;
640 sf->thresh_mult[THR_SPLITA ] = INT_MAX;
643 if ((cpi->ref_frame_flags & (VP9_LAST_FLAG | VP9_ALT_FLAG)) !=
644 (VP9_LAST_FLAG | VP9_ALT_FLAG)) {
645 sf->thresh_mult[THR_COMP_ZEROLA ] = INT_MAX;
646 sf->thresh_mult[THR_COMP_NEARESTLA] = INT_MAX;
647 sf->thresh_mult[THR_COMP_NEARLA ] = INT_MAX;
648 sf->thresh_mult[THR_COMP_NEWLA ] = INT_MAX;
649 sf->thresh_mult[THR_COMP_SPLITLA ] = INT_MAX;
651 if ((cpi->ref_frame_flags & (VP9_GOLD_FLAG | VP9_ALT_FLAG)) !=
652 (VP9_GOLD_FLAG | VP9_ALT_FLAG)) {
653 sf->thresh_mult[THR_COMP_ZEROGA ] = INT_MAX;
654 sf->thresh_mult[THR_COMP_NEARESTGA] = INT_MAX;
655 sf->thresh_mult[THR_COMP_NEARGA ] = INT_MAX;
656 sf->thresh_mult[THR_COMP_NEWGA ] = INT_MAX;
657 sf->thresh_mult[THR_COMP_SPLITGA ] = INT_MAX;
660 if (sf->disable_splitmv == 1) {
661 sf->thresh_mult[THR_SPLITMV ] = INT_MAX;
662 sf->thresh_mult[THR_SPLITG ] = INT_MAX;
663 sf->thresh_mult[THR_SPLITA ] = INT_MAX;
665 sf->thresh_mult[THR_COMP_SPLITLA ] = INT_MAX;
666 sf->thresh_mult[THR_COMP_SPLITGA ] = INT_MAX;
670 void vp9_set_speed_features(VP9_COMP *cpi) {
671 SPEED_FEATURES *sf = &cpi->sf;
672 int mode = cpi->compressor_speed;
673 int speed = cpi->speed;
676 // Only modes 0 and 1 supported for now in experimental code basae
680 // Initialise default mode frequency sampling variables
681 for (i = 0; i < MAX_MODES; i ++) {
682 cpi->mode_check_freq[i] = 0;
683 cpi->mode_test_hit_counts[i] = 0;
684 cpi->mode_chosen_counts[i] = 0;
687 // best quality defaults
689 sf->search_method = NSTEP;
692 sf->subpel_search_method = SUBPEL_TREE;
693 sf->subpel_iters_per_step = 2;
694 sf->optimize_coefficients = !cpi->oxcf.lossless;
695 sf->reduce_first_step_size = 0;
696 sf->auto_mv_step_size = 0;
697 sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
698 sf->comp_inter_joint_search_thresh = BLOCK_4X4;
699 sf->adaptive_rd_thresh = 0;
700 sf->use_lastframe_partitioning = 0;
701 sf->tx_size_search_method = USE_FULL_RD;
702 sf->use_lp32x32fdct = 0;
703 sf->adaptive_motion_search = 0;
704 sf->use_avoid_tested_higherror = 0;
705 sf->reference_masking = 0;
706 sf->use_one_partition_size_always = 0;
707 sf->less_rectangular_check = 0;
708 sf->use_square_partition_only = 0;
709 sf->auto_min_max_partition_size = 0;
710 sf->max_partition_size = BLOCK_64X64;
711 sf->min_partition_size = BLOCK_4X4;
712 sf->adjust_partitioning_from_last_frame = 0;
713 sf->last_partitioning_redo_frequency = 4;
714 sf->disable_splitmv = 0;
715 sf->mode_search_skip_flags = 0;
716 sf->disable_split_var_thresh = 0;
717 sf->disable_filter_search_var_thresh = 0;
718 sf->intra_y_mode_mask = ALL_INTRA_MODES;
719 sf->intra_uv_mode_mask = ALL_INTRA_MODES;
720 sf->use_rd_breakout = 0;
721 sf->skip_encode_sb = 0;
722 sf->use_uv_intra_rd_estimate = 0;
723 sf->use_fast_lpf_pick = 0;
724 sf->use_fast_coef_updates = 0;
725 sf->using_small_partition_info = 0;
726 sf->mode_skip_start = MAX_MODES; // Mode index at which mode skip mask set
728 #if CONFIG_MULTIPLE_ARF
729 // Switch segmentation off.
730 sf->static_segmentation = 0;
732 sf->static_segmentation = 0;
736 case 0: // best quality mode
740 #if CONFIG_MULTIPLE_ARF
741 // Switch segmentation off.
742 sf->static_segmentation = 0;
744 sf->static_segmentation = 0;
746 sf->use_avoid_tested_higherror = 1;
747 sf->adaptive_rd_thresh = MIN((speed + 1), 4);
750 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
751 sf->less_rectangular_check = 1;
752 sf->tx_size_search_method = ((cpi->common.frame_type == KEY_FRAME ||
753 cpi->common.intra_only ||
754 cpi->common.show_frame == 0) ?
757 sf->use_square_partition_only = !(cpi->common.frame_type == KEY_FRAME ||
758 cpi->common.intra_only ||
759 cpi->common.show_frame == 0);
760 sf->disable_splitmv =
761 (MIN(cpi->common.width, cpi->common.height) >= 720)? 1 : 0;
762 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
763 FLAG_SKIP_INTRA_BESTINTER |
764 FLAG_SKIP_COMP_BESTINTRA |
765 FLAG_SKIP_INTRA_LOWVAR;
766 sf->use_uv_intra_rd_estimate = 1;
767 sf->use_rd_breakout = 1;
768 sf->skip_encode_sb = 1;
769 sf->use_lp32x32fdct = 1;
770 sf->adaptive_motion_search = 1;
771 sf->auto_mv_step_size = 1;
773 sf->auto_min_max_partition_size = 1;
774 // FIXME(jingning): temporarily turn off disable_split_var_thresh
775 // during refactoring process. will get this back after finishing
776 // the main framework of partition search type.
777 sf->disable_split_var_thresh = 0;
778 sf->disable_filter_search_var_thresh = 16;
780 sf->intra_y_mode_mask = INTRA_DC_TM_H_V;
781 sf->intra_uv_mode_mask = INTRA_DC_TM_H_V;
782 sf->use_fast_coef_updates = 1;
783 sf->mode_skip_start = 11;
786 sf->less_rectangular_check = 1;
787 sf->use_square_partition_only = 1;
788 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
789 sf->use_lastframe_partitioning = 1;
790 sf->adjust_partitioning_from_last_frame = 1;
791 sf->last_partitioning_redo_frequency = 3;
792 sf->tx_size_search_method = ((cpi->common.frame_type == KEY_FRAME ||
793 cpi->common.intra_only ||
794 cpi->common.show_frame == 0) ?
797 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
798 FLAG_SKIP_INTRA_BESTINTER |
799 FLAG_SKIP_COMP_BESTINTRA |
800 FLAG_SKIP_COMP_REFMISMATCH |
801 FLAG_SKIP_INTRA_LOWVAR |
802 FLAG_EARLY_TERMINATE;
803 sf->intra_y_mode_mask = INTRA_DC_TM;
804 sf->intra_uv_mode_mask = INTRA_DC_TM;
805 sf->use_uv_intra_rd_estimate = 1;
806 sf->use_rd_breakout = 1;
807 sf->skip_encode_sb = 1;
808 sf->use_lp32x32fdct = 1;
809 sf->adaptive_motion_search = 1;
810 sf->using_small_partition_info = 0;
811 sf->disable_splitmv =
812 (MIN(cpi->common.width, cpi->common.height) >= 720)? 1 : 0;
813 sf->auto_mv_step_size = 1;
814 sf->search_method = SQUARE;
815 sf->subpel_iters_per_step = 1;
816 sf->use_fast_lpf_pick = 1;
817 sf->auto_min_max_partition_size = 1;
818 sf->disable_split_var_thresh = 32;
819 sf->disable_filter_search_var_thresh = 32;
820 sf->use_fast_coef_updates = 2;
821 sf->mode_skip_start = 6;
824 sf->less_rectangular_check = 1;
825 sf->use_square_partition_only = 1;
826 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
827 sf->use_lastframe_partitioning = 1;
828 sf->adjust_partitioning_from_last_frame = 1;
829 sf->last_partitioning_redo_frequency = 3;
830 sf->tx_size_search_method = ((cpi->common.frame_type == KEY_FRAME ||
831 cpi->common.intra_only ||
832 cpi->common.show_frame == 0) ?
835 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
836 FLAG_SKIP_INTRA_BESTINTER |
837 FLAG_SKIP_COMP_BESTINTRA |
838 FLAG_SKIP_COMP_REFMISMATCH |
839 FLAG_SKIP_INTRA_LOWVAR |
840 FLAG_EARLY_TERMINATE;
841 sf->intra_y_mode_mask = INTRA_DC_ONLY;
842 sf->intra_uv_mode_mask = INTRA_DC_ONLY;
843 sf->use_uv_intra_rd_estimate = 1;
844 sf->use_rd_breakout = 1;
845 sf->skip_encode_sb = 1;
846 sf->use_lp32x32fdct = 1;
847 sf->adaptive_motion_search = 1;
848 sf->using_small_partition_info = 0;
849 sf->disable_splitmv = 1;
850 sf->auto_mv_step_size = 1;
851 sf->search_method = BIGDIA;
852 sf->subpel_iters_per_step = 1;
853 sf->use_fast_lpf_pick = 1;
854 sf->auto_min_max_partition_size = 1;
855 sf->disable_split_var_thresh = 64;
856 sf->disable_filter_search_var_thresh = 64;
857 sf->use_fast_coef_updates = 2;
858 sf->mode_skip_start = 6;
861 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
862 sf->use_one_partition_size_always = 1;
863 sf->always_this_block_size = BLOCK_16X16;
864 sf->tx_size_search_method = ((cpi->common.frame_type == KEY_FRAME ||
865 cpi->common.intra_only ||
866 cpi->common.show_frame == 0) ?
869 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
870 FLAG_SKIP_INTRA_BESTINTER |
871 FLAG_SKIP_COMP_BESTINTRA |
872 FLAG_SKIP_COMP_REFMISMATCH |
873 FLAG_SKIP_INTRA_LOWVAR |
874 FLAG_EARLY_TERMINATE;
875 sf->use_rd_breakout = 1;
876 sf->use_lp32x32fdct = 1;
877 sf->optimize_coefficients = 0;
878 sf->auto_mv_step_size = 1;
879 // sf->reduce_first_step_size = 1;
880 // sf->reference_masking = 1;
882 sf->disable_splitmv = 1;
883 sf->search_method = HEX;
884 sf->subpel_iters_per_step = 1;
885 sf->disable_split_var_thresh = 64;
886 sf->disable_filter_search_var_thresh = 96;
887 sf->intra_y_mode_mask = INTRA_DC_ONLY;
888 sf->intra_uv_mode_mask = INTRA_DC_ONLY;
889 sf->use_fast_coef_updates = 2;
890 sf->mode_skip_start = 6;
896 // Set rd thresholds based on mode and speed setting
897 set_rd_speed_thresholds(cpi, mode);
899 // Slow quant, dct and trellis not worthwhile for first pass
900 // so make sure they are always turned off.
901 if (cpi->pass == 1) {
902 sf->optimize_coefficients = 0;
905 cpi->mb.fwd_txm16x16 = vp9_short_fdct16x16;
906 cpi->mb.fwd_txm8x8 = vp9_short_fdct8x8;
907 cpi->mb.fwd_txm8x4 = vp9_short_fdct8x4;
908 cpi->mb.fwd_txm4x4 = vp9_short_fdct4x4;
909 if (cpi->oxcf.lossless || cpi->mb.e_mbd.lossless) {
910 cpi->mb.fwd_txm8x4 = vp9_short_walsh8x4;
911 cpi->mb.fwd_txm4x4 = vp9_short_walsh4x4;
914 cpi->mb.quantize_b_4x4 = vp9_regular_quantize_b_4x4;
916 if (cpi->sf.subpel_search_method == SUBPEL_ITERATIVE) {
917 cpi->find_fractional_mv_step = vp9_find_best_sub_pixel_iterative;
918 cpi->find_fractional_mv_step_comp = vp9_find_best_sub_pixel_comp_iterative;
919 } else if (cpi->sf.subpel_search_method == SUBPEL_TREE) {
920 cpi->find_fractional_mv_step = vp9_find_best_sub_pixel_tree;
921 cpi->find_fractional_mv_step_comp = vp9_find_best_sub_pixel_comp_tree;
924 cpi->mb.optimize = cpi->sf.optimize_coefficients == 1 && cpi->pass != 1;
927 frames_at_speed[cpi->speed]++;
931 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
932 VP9_COMMON *cm = &cpi->common;
934 cpi->lookahead = vp9_lookahead_init(cpi->oxcf.width, cpi->oxcf.height,
935 cm->subsampling_x, cm->subsampling_y,
936 cpi->oxcf.lag_in_frames);
938 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
939 "Failed to allocate lag buffers");
941 if (vp9_realloc_frame_buffer(&cpi->alt_ref_buffer,
942 cpi->oxcf.width, cpi->oxcf.height,
943 cm->subsampling_x, cm->subsampling_y,
945 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
946 "Failed to allocate altref buffer");
949 static int alloc_partition_data(VP9_COMP *cpi) {
950 vpx_free(cpi->mb.pip);
952 cpi->mb.pip = vpx_calloc(cpi->common.mode_info_stride *
953 (cpi->common.mi_rows + MI_BLOCK_SIZE),
954 sizeof(PARTITION_INFO));
958 cpi->mb.pi = cpi->mb.pip + cpi->common.mode_info_stride + 1;
963 void vp9_alloc_compressor_data(VP9_COMP *cpi) {
964 VP9_COMMON *cm = &cpi->common;
966 if (vp9_alloc_frame_buffers(cm, cm->width, cm->height))
967 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
968 "Failed to allocate frame buffers");
970 if (alloc_partition_data(cpi))
971 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
972 "Failed to allocate partition data");
974 if (vp9_alloc_frame_buffer(&cpi->last_frame_uf,
975 cm->width, cm->height,
976 cm->subsampling_x, cm->subsampling_y,
978 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
979 "Failed to allocate last frame buffer");
981 if (vp9_alloc_frame_buffer(&cpi->scaled_source,
982 cm->width, cm->height,
983 cm->subsampling_x, cm->subsampling_y,
985 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
986 "Failed to allocate scaled source buffer");
991 unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
993 CHECK_MEM_ERROR(cm, cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
996 // Data used for real time vc mode to see if gf needs refreshing
997 cpi->inter_zz_count = 0;
998 cpi->gf_bad_count = 0;
999 cpi->gf_update_recommended = 0;
1001 vpx_free(cpi->mb_activity_map);
1002 CHECK_MEM_ERROR(cm, cpi->mb_activity_map,
1003 vpx_calloc(sizeof(unsigned int),
1004 cm->mb_rows * cm->mb_cols));
1006 vpx_free(cpi->mb_norm_activity_map);
1007 CHECK_MEM_ERROR(cm, cpi->mb_norm_activity_map,
1008 vpx_calloc(sizeof(unsigned int),
1009 cm->mb_rows * cm->mb_cols));
1013 static void update_frame_size(VP9_COMP *cpi) {
1014 VP9_COMMON *cm = &cpi->common;
1016 vp9_update_frame_size(cm);
1018 // Update size of buffers local to this frame
1019 if (vp9_realloc_frame_buffer(&cpi->last_frame_uf,
1020 cm->width, cm->height,
1021 cm->subsampling_x, cm->subsampling_y,
1023 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1024 "Failed to reallocate last frame buffer");
1026 if (vp9_realloc_frame_buffer(&cpi->scaled_source,
1027 cm->width, cm->height,
1028 cm->subsampling_x, cm->subsampling_y,
1030 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1031 "Failed to reallocate scaled source buffer");
1034 int y_stride = cpi->scaled_source.y_stride;
1036 if (cpi->sf.search_method == NSTEP) {
1037 vp9_init3smotion_compensation(&cpi->mb, y_stride);
1038 } else if (cpi->sf.search_method == DIAMOND) {
1039 vp9_init_dsmotion_compensation(&cpi->mb, y_stride);
1045 // TODO perhaps change number of steps expose to outside world when setting
1046 // max and min limits. Also this will likely want refining for the extended Q
1049 // Table that converts 0-63 Q range values passed in outside to the Qindex
1050 // range used internally.
1051 static const int q_trans[] = {
1052 0, 4, 8, 12, 16, 20, 24, 28,
1053 32, 36, 40, 44, 48, 52, 56, 60,
1054 64, 68, 72, 76, 80, 84, 88, 92,
1055 96, 100, 104, 108, 112, 116, 120, 124,
1056 128, 132, 136, 140, 144, 148, 152, 156,
1057 160, 164, 168, 172, 176, 180, 184, 188,
1058 192, 196, 200, 204, 208, 212, 216, 220,
1059 224, 228, 232, 236, 240, 244, 249, 255,
1062 int vp9_reverse_trans(int x) {
1065 for (i = 0; i < 64; i++)
1066 if (q_trans[i] >= x)
1071 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
1072 if (framerate < 0.1)
1075 cpi->oxcf.framerate = framerate;
1076 cpi->output_framerate = cpi->oxcf.framerate;
1077 cpi->per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth / cpi->output_framerate);
1078 cpi->av_per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth / cpi->output_framerate);
1079 cpi->min_frame_bandwidth = (int)(cpi->av_per_frame_bandwidth * cpi->oxcf.two_pass_vbrmin_section / 100);
1082 cpi->min_frame_bandwidth = MAX(cpi->min_frame_bandwidth, FRAME_OVERHEAD_BITS);
1084 // Set Maximum gf/arf interval
1085 cpi->max_gf_interval = 16;
1087 // Extended interval for genuinely static scenes
1088 cpi->twopass.static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
1090 // Special conditions when alt ref frame enabled in lagged compress mode
1091 if (cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames) {
1092 if (cpi->max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1093 cpi->max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1095 if (cpi->twopass.static_scene_max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1096 cpi->twopass.static_scene_max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1099 if (cpi->max_gf_interval > cpi->twopass.static_scene_max_gf_interval)
1100 cpi->max_gf_interval = cpi->twopass.static_scene_max_gf_interval;
1103 static int64_t rescale(int val, int64_t num, int denom) {
1104 int64_t llnum = num;
1105 int64_t llden = denom;
1106 int64_t llval = val;
1108 return (llval * llnum / llden);
1111 static void set_tile_limits(VP9_COMP *cpi) {
1112 VP9_COMMON *const cm = &cpi->common;
1114 int min_log2_tile_cols, max_log2_tile_cols;
1115 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1117 cm->log2_tile_cols = clamp(cpi->oxcf.tile_columns,
1118 min_log2_tile_cols, max_log2_tile_cols);
1119 cm->log2_tile_rows = cpi->oxcf.tile_rows;
1122 static void init_config(VP9_PTR ptr, VP9_CONFIG *oxcf) {
1123 VP9_COMP *cpi = (VP9_COMP *)(ptr);
1124 VP9_COMMON *const cm = &cpi->common;
1130 cm->version = oxcf->version;
1132 cm->width = oxcf->width;
1133 cm->height = oxcf->height;
1134 cm->subsampling_x = 0;
1135 cm->subsampling_y = 0;
1136 vp9_alloc_compressor_data(cpi);
1138 // change includes all joint functionality
1139 vp9_change_config(ptr, oxcf);
1141 // Initialize active best and worst q and average q values.
1142 cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1143 cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1144 cpi->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
1146 // Initialise the starting buffer levels
1147 cpi->buffer_level = cpi->oxcf.starting_buffer_level;
1148 cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
1150 cpi->rolling_target_bits = cpi->av_per_frame_bandwidth;
1151 cpi->rolling_actual_bits = cpi->av_per_frame_bandwidth;
1152 cpi->long_rolling_target_bits = cpi->av_per_frame_bandwidth;
1153 cpi->long_rolling_actual_bits = cpi->av_per_frame_bandwidth;
1155 cpi->total_actual_bits = 0;
1156 cpi->total_target_vs_actual = 0;
1158 cpi->static_mb_pct = 0;
1160 cpi->lst_fb_idx = 0;
1161 cpi->gld_fb_idx = 1;
1162 cpi->alt_fb_idx = 2;
1164 cpi->current_layer = 0;
1167 set_tile_limits(cpi);
1169 cpi->fixed_divide[0] = 0;
1170 for (i = 1; i < 512; i++)
1171 cpi->fixed_divide[i] = 0x80000 / i;
1175 void vp9_change_config(VP9_PTR ptr, VP9_CONFIG *oxcf) {
1176 VP9_COMP *cpi = (VP9_COMP *)(ptr);
1177 VP9_COMMON *const cm = &cpi->common;
1182 if (cm->version != oxcf->version) {
1183 cm->version = oxcf->version;
1188 switch (cpi->oxcf.Mode) {
1189 // Real time and one pass deprecated in test code base
1190 case MODE_FIRSTPASS:
1192 cpi->compressor_speed = 1;
1195 case MODE_SECONDPASS:
1197 cpi->compressor_speed = 1;
1198 cpi->oxcf.cpu_used = clamp(cpi->oxcf.cpu_used, -5, 5);
1201 case MODE_SECONDPASS_BEST:
1203 cpi->compressor_speed = 0;
1207 cpi->oxcf.worst_allowed_q = q_trans[oxcf->worst_allowed_q];
1208 cpi->oxcf.best_allowed_q = q_trans[oxcf->best_allowed_q];
1209 cpi->oxcf.cq_level = q_trans[cpi->oxcf.cq_level];
1211 cpi->oxcf.lossless = oxcf->lossless;
1212 if (cpi->oxcf.lossless) {
1213 cpi->mb.e_mbd.inv_txm4x4_1_add = vp9_short_iwalsh4x4_1_add;
1214 cpi->mb.e_mbd.inv_txm4x4_add = vp9_short_iwalsh4x4_add;
1216 cpi->mb.e_mbd.inv_txm4x4_1_add = vp9_short_idct4x4_1_add;
1217 cpi->mb.e_mbd.inv_txm4x4_add = vp9_short_idct4x4_add;
1220 cpi->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1222 cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
1224 // cpi->use_golden_frame_only = 0;
1225 // cpi->use_last_frame_only = 0;
1226 cpi->refresh_golden_frame = 0;
1227 cpi->refresh_last_frame = 1;
1228 cm->refresh_frame_context = 1;
1229 cm->reset_frame_context = 0;
1232 cpi->mb.e_mbd.allow_high_precision_mv = 0; // Default mv precision adaptation
1233 set_mvcost(&cpi->mb);
1238 for (i = 0; i < MAX_SEGMENTS; i++)
1239 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1242 // At the moment the first order values may not be > MAXQ
1243 cpi->oxcf.fixed_q = MIN(cpi->oxcf.fixed_q, MAXQ);
1245 // local file playback mode == really big buffer
1246 if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK) {
1247 cpi->oxcf.starting_buffer_level = 60000;
1248 cpi->oxcf.optimal_buffer_level = 60000;
1249 cpi->oxcf.maximum_buffer_size = 240000;
1252 // Convert target bandwidth from Kbit/s to Bit/s
1253 cpi->oxcf.target_bandwidth *= 1000;
1255 cpi->oxcf.starting_buffer_level = rescale(cpi->oxcf.starting_buffer_level,
1256 cpi->oxcf.target_bandwidth, 1000);
1258 // Set or reset optimal and maximum buffer levels.
1259 if (cpi->oxcf.optimal_buffer_level == 0)
1260 cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
1262 cpi->oxcf.optimal_buffer_level = rescale(cpi->oxcf.optimal_buffer_level,
1263 cpi->oxcf.target_bandwidth, 1000);
1265 if (cpi->oxcf.maximum_buffer_size == 0)
1266 cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
1268 cpi->oxcf.maximum_buffer_size = rescale(cpi->oxcf.maximum_buffer_size,
1269 cpi->oxcf.target_bandwidth, 1000);
1271 // Set up frame rate and related parameters rate control values.
1272 vp9_new_framerate(cpi, cpi->oxcf.framerate);
1274 // Set absolute upper and lower quality limits
1275 cpi->worst_quality = cpi->oxcf.worst_allowed_q;
1276 cpi->best_quality = cpi->oxcf.best_allowed_q;
1278 // active values should only be modified if out of new range
1279 cpi->active_worst_quality = clamp(cpi->active_worst_quality,
1280 cpi->oxcf.best_allowed_q,
1281 cpi->oxcf.worst_allowed_q);
1283 cpi->active_best_quality = clamp(cpi->active_best_quality,
1284 cpi->oxcf.best_allowed_q,
1285 cpi->oxcf.worst_allowed_q);
1287 cpi->buffered_mode = cpi->oxcf.optimal_buffer_level > 0;
1289 cpi->cq_target_quality = cpi->oxcf.cq_level;
1291 cm->mcomp_filter_type = DEFAULT_INTERP_FILTER;
1293 cpi->target_bandwidth = cpi->oxcf.target_bandwidth;
1295 cm->display_width = cpi->oxcf.width;
1296 cm->display_height = cpi->oxcf.height;
1298 // VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs)
1299 cpi->oxcf.Sharpness = MIN(7, cpi->oxcf.Sharpness);
1301 cpi->common.lf.sharpness_level = cpi->oxcf.Sharpness;
1303 if (cpi->initial_width) {
1304 // Increasing the size of the frame beyond the first seen frame, or some
1305 // otherwise signalled maximum size, is not supported.
1306 // TODO(jkoleszar): exit gracefully.
1307 assert(cm->width <= cpi->initial_width);
1308 assert(cm->height <= cpi->initial_height);
1310 update_frame_size(cpi);
1312 if (cpi->oxcf.fixed_q >= 0) {
1313 cpi->last_q[0] = cpi->oxcf.fixed_q;
1314 cpi->last_q[1] = cpi->oxcf.fixed_q;
1315 cpi->last_boosted_qindex = cpi->oxcf.fixed_q;
1318 cpi->speed = cpi->oxcf.cpu_used;
1320 if (cpi->oxcf.lag_in_frames == 0) {
1321 // force to allowlag to 0 if lag_in_frames is 0;
1322 cpi->oxcf.allow_lag = 0;
1323 } else if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS) {
1324 // Limit on lag buffers as these are not currently dynamically allocated
1325 cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
1329 #if CONFIG_MULTIPLE_ARF
1330 vp9_zero(cpi->alt_ref_source);
1332 cpi->alt_ref_source = NULL;
1334 cpi->is_src_frame_alt_ref = 0;
1337 // Experimental RD Code
1338 cpi->frame_distortion = 0;
1339 cpi->last_frame_distortion = 0;
1342 set_tile_limits(cpi);
1345 #define M_LOG2_E 0.693147180559945309417
1346 #define log2f(x) (log (x) / (float) M_LOG2_E)
1348 static void cal_nmvjointsadcost(int *mvjointsadcost) {
1349 mvjointsadcost[0] = 600;
1350 mvjointsadcost[1] = 300;
1351 mvjointsadcost[2] = 300;
1352 mvjointsadcost[0] = 300;
1355 static void cal_nmvsadcosts(int *mvsadcost[2]) {
1358 mvsadcost[0][0] = 0;
1359 mvsadcost[1][0] = 0;
1362 double z = 256 * (2 * (log2f(8 * i) + .6));
1363 mvsadcost[0][i] = (int)z;
1364 mvsadcost[1][i] = (int)z;
1365 mvsadcost[0][-i] = (int)z;
1366 mvsadcost[1][-i] = (int)z;
1367 } while (++i <= MV_MAX);
1370 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
1373 mvsadcost[0][0] = 0;
1374 mvsadcost[1][0] = 0;
1377 double z = 256 * (2 * (log2f(8 * i) + .6));
1378 mvsadcost[0][i] = (int)z;
1379 mvsadcost[1][i] = (int)z;
1380 mvsadcost[0][-i] = (int)z;
1381 mvsadcost[1][-i] = (int)z;
1382 } while (++i <= MV_MAX);
1385 VP9_PTR vp9_create_compressor(VP9_CONFIG *oxcf) {
1395 cpi = ctx.cpi = vpx_memalign(32, sizeof(VP9_COMP));
1396 // Check that the CPI instance is valid
1404 if (setjmp(cm->error.jmp)) {
1405 VP9_PTR ptr = ctx.ptr;
1407 ctx.cpi->common.error.setjmp = 0;
1408 vp9_remove_compressor(&ptr);
1412 cm->error.setjmp = 1;
1414 CHECK_MEM_ERROR(cm, cpi->mb.ss, vpx_calloc(sizeof(search_site),
1415 (MAX_MVSEARCH_STEPS * 8) + 1));
1417 vp9_create_common(cm);
1419 init_config((VP9_PTR)cpi, oxcf);
1421 cm->current_video_frame = 0;
1422 cpi->kf_overspend_bits = 0;
1423 cpi->kf_bitrate_adjustment = 0;
1424 cpi->frames_till_gf_update_due = 0;
1425 cpi->gf_overspend_bits = 0;
1426 cpi->non_gf_bitrate_adjustment = 0;
1428 // Set reference frame sign bias for ALTREF frame to 1 (for now)
1429 cm->ref_frame_sign_bias[ALTREF_FRAME] = 1;
1431 cpi->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1433 cpi->gold_is_last = 0;
1434 cpi->alt_is_last = 0;
1435 cpi->gold_is_alt = 0;
1437 // Spatial scalability
1438 cpi->number_spatial_layers = oxcf->ss_number_layers;
1440 // Create the encoder segmentation map and set all entries to 0
1441 CHECK_MEM_ERROR(cm, cpi->segmentation_map,
1442 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1444 // And a place holder structure is the coding context
1445 // for use if we want to save and restore it
1446 CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
1447 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1449 CHECK_MEM_ERROR(cm, cpi->active_map, vpx_calloc(cm->MBs, 1));
1450 vpx_memset(cpi->active_map, 1, cm->MBs);
1451 cpi->active_map_enabled = 0;
1453 for (i = 0; i < (sizeof(cpi->mbgraph_stats) /
1454 sizeof(cpi->mbgraph_stats[0])); i++) {
1455 CHECK_MEM_ERROR(cm, cpi->mbgraph_stats[i].mb_stats,
1456 vpx_calloc(cm->MBs *
1457 sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
1460 #ifdef ENTROPY_STATS
1462 init_context_counters();
1466 init_tx_count_stats();
1467 init_switchable_interp_stats();
1470 /*Initialize the feed-forward activity masking.*/
1471 cpi->activity_avg = 90 << 12;
1473 cpi->frames_since_key = 8; // Give a sensible default for the first frame.
1474 cpi->key_frame_frequency = cpi->oxcf.key_freq;
1475 cpi->this_key_frame_forced = 0;
1476 cpi->next_key_frame_forced = 0;
1478 cpi->source_alt_ref_pending = 0;
1479 cpi->source_alt_ref_active = 0;
1480 cpi->refresh_alt_ref_frame = 0;
1482 #if CONFIG_MULTIPLE_ARF
1483 // Turn multiple ARF usage on/off. This is a quick hack for the initial test
1484 // version. It should eventually be set via the codec API.
1485 cpi->multi_arf_enabled = 1;
1487 if (cpi->multi_arf_enabled) {
1488 cpi->sequence_number = 0;
1489 cpi->frame_coding_order_period = 0;
1490 vp9_zero(cpi->frame_coding_order);
1491 vp9_zero(cpi->arf_buffer_idx);
1495 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1496 #if CONFIG_INTERNAL_STATS
1497 cpi->b_calculate_ssimg = 0;
1502 if (cpi->b_calculate_psnr) {
1503 cpi->total_sq_error = 0.0;
1504 cpi->total_sq_error2 = 0.0;
1509 cpi->totalp_y = 0.0;
1510 cpi->totalp_u = 0.0;
1511 cpi->totalp_v = 0.0;
1513 cpi->tot_recode_hits = 0;
1514 cpi->summed_quality = 0;
1515 cpi->summed_weights = 0;
1516 cpi->summedp_quality = 0;
1517 cpi->summedp_weights = 0;
1520 if (cpi->b_calculate_ssimg) {
1521 cpi->total_ssimg_y = 0;
1522 cpi->total_ssimg_u = 0;
1523 cpi->total_ssimg_v = 0;
1524 cpi->total_ssimg_all = 0;
1529 cpi->first_time_stamp_ever = INT64_MAX;
1531 cpi->frames_till_gf_update_due = 0;
1532 cpi->key_frame_count = 1;
1534 cpi->ni_av_qi = cpi->oxcf.worst_allowed_q;
1538 cpi->avg_q = vp9_convert_qindex_to_q(cpi->oxcf.worst_allowed_q);
1539 cpi->total_byte_count = 0;
1541 cpi->rate_correction_factor = 1.0;
1542 cpi->key_frame_rate_correction_factor = 1.0;
1543 cpi->gf_rate_correction_factor = 1.0;
1544 cpi->twopass.est_max_qcorrection_factor = 1.0;
1546 cal_nmvjointsadcost(cpi->mb.nmvjointsadcost);
1547 cpi->mb.nmvcost[0] = &cpi->mb.nmvcosts[0][MV_MAX];
1548 cpi->mb.nmvcost[1] = &cpi->mb.nmvcosts[1][MV_MAX];
1549 cpi->mb.nmvsadcost[0] = &cpi->mb.nmvsadcosts[0][MV_MAX];
1550 cpi->mb.nmvsadcost[1] = &cpi->mb.nmvsadcosts[1][MV_MAX];
1551 cal_nmvsadcosts(cpi->mb.nmvsadcost);
1553 cpi->mb.nmvcost_hp[0] = &cpi->mb.nmvcosts_hp[0][MV_MAX];
1554 cpi->mb.nmvcost_hp[1] = &cpi->mb.nmvcosts_hp[1][MV_MAX];
1555 cpi->mb.nmvsadcost_hp[0] = &cpi->mb.nmvsadcosts_hp[0][MV_MAX];
1556 cpi->mb.nmvsadcost_hp[1] = &cpi->mb.nmvsadcosts_hp[1][MV_MAX];
1557 cal_nmvsadcosts_hp(cpi->mb.nmvsadcost_hp);
1559 for (i = 0; i < KEY_FRAME_CONTEXT; i++)
1560 cpi->prior_key_frame_distance[i] = (int)cpi->output_framerate;
1562 #ifdef OUTPUT_YUV_SRC
1563 yuv_file = fopen("bd.yuv", "ab");
1565 #ifdef OUTPUT_YUV_REC
1566 yuv_rec_file = fopen("rec.yuv", "wb");
1570 framepsnr = fopen("framepsnr.stt", "a");
1571 kf_list = fopen("kf_list.stt", "w");
1574 cpi->output_pkt_list = oxcf->output_pkt_list;
1576 cpi->enable_encode_breakout = 1;
1578 if (cpi->pass == 1) {
1579 vp9_init_first_pass(cpi);
1580 } else if (cpi->pass == 2) {
1581 size_t packet_sz = sizeof(FIRSTPASS_STATS);
1582 int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
1584 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1585 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1586 cpi->twopass.stats_in_end = (void *)((char *)cpi->twopass.stats_in
1587 + (packets - 1) * packet_sz);
1588 vp9_init_second_pass(cpi);
1591 vp9_set_speed_features(cpi);
1593 // Default rd threshold factors for mode selection
1594 for (i = 0; i < BLOCK_SIZES; ++i)
1595 for (j = 0; j < MAX_MODES; ++j)
1596 cpi->rd_thresh_freq_fact[i][j] = 32;
1598 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SVFHH, SVFHV, SVFHHV, \
1599 SDX3F, SDX8F, SDX4DF)\
1600 cpi->fn_ptr[BT].sdf = SDF; \
1601 cpi->fn_ptr[BT].sdaf = SDAF; \
1602 cpi->fn_ptr[BT].vf = VF; \
1603 cpi->fn_ptr[BT].svf = SVF; \
1604 cpi->fn_ptr[BT].svaf = SVAF; \
1605 cpi->fn_ptr[BT].svf_halfpix_h = SVFHH; \
1606 cpi->fn_ptr[BT].svf_halfpix_v = SVFHV; \
1607 cpi->fn_ptr[BT].svf_halfpix_hv = SVFHHV; \
1608 cpi->fn_ptr[BT].sdx3f = SDX3F; \
1609 cpi->fn_ptr[BT].sdx8f = SDX8F; \
1610 cpi->fn_ptr[BT].sdx4df = SDX4DF;
1612 BFP(BLOCK_32X16, vp9_sad32x16, vp9_sad32x16_avg,
1613 vp9_variance32x16, vp9_sub_pixel_variance32x16,
1614 vp9_sub_pixel_avg_variance32x16, NULL, NULL,
1618 BFP(BLOCK_16X32, vp9_sad16x32, vp9_sad16x32_avg,
1619 vp9_variance16x32, vp9_sub_pixel_variance16x32,
1620 vp9_sub_pixel_avg_variance16x32, NULL, NULL,
1624 BFP(BLOCK_64X32, vp9_sad64x32, vp9_sad64x32_avg,
1625 vp9_variance64x32, vp9_sub_pixel_variance64x32,
1626 vp9_sub_pixel_avg_variance64x32, NULL, NULL,
1630 BFP(BLOCK_32X64, vp9_sad32x64, vp9_sad32x64_avg,
1631 vp9_variance32x64, vp9_sub_pixel_variance32x64,
1632 vp9_sub_pixel_avg_variance32x64, NULL, NULL,
1636 BFP(BLOCK_32X32, vp9_sad32x32, vp9_sad32x32_avg,
1637 vp9_variance32x32, vp9_sub_pixel_variance32x32,
1638 vp9_sub_pixel_avg_variance32x32, vp9_variance_halfpixvar32x32_h,
1639 vp9_variance_halfpixvar32x32_v,
1640 vp9_variance_halfpixvar32x32_hv, vp9_sad32x32x3, vp9_sad32x32x8,
1643 BFP(BLOCK_64X64, vp9_sad64x64, vp9_sad64x64_avg,
1644 vp9_variance64x64, vp9_sub_pixel_variance64x64,
1645 vp9_sub_pixel_avg_variance64x64, vp9_variance_halfpixvar64x64_h,
1646 vp9_variance_halfpixvar64x64_v,
1647 vp9_variance_halfpixvar64x64_hv, vp9_sad64x64x3, vp9_sad64x64x8,
1650 BFP(BLOCK_16X16, vp9_sad16x16, vp9_sad16x16_avg,
1651 vp9_variance16x16, vp9_sub_pixel_variance16x16,
1652 vp9_sub_pixel_avg_variance16x16, vp9_variance_halfpixvar16x16_h,
1653 vp9_variance_halfpixvar16x16_v,
1654 vp9_variance_halfpixvar16x16_hv, vp9_sad16x16x3, vp9_sad16x16x8,
1657 BFP(BLOCK_16X8, vp9_sad16x8, vp9_sad16x8_avg,
1658 vp9_variance16x8, vp9_sub_pixel_variance16x8,
1659 vp9_sub_pixel_avg_variance16x8, NULL, NULL, NULL,
1660 vp9_sad16x8x3, vp9_sad16x8x8, vp9_sad16x8x4d)
1662 BFP(BLOCK_8X16, vp9_sad8x16, vp9_sad8x16_avg,
1663 vp9_variance8x16, vp9_sub_pixel_variance8x16,
1664 vp9_sub_pixel_avg_variance8x16, NULL, NULL, NULL,
1665 vp9_sad8x16x3, vp9_sad8x16x8, vp9_sad8x16x4d)
1667 BFP(BLOCK_8X8, vp9_sad8x8, vp9_sad8x8_avg,
1668 vp9_variance8x8, vp9_sub_pixel_variance8x8,
1669 vp9_sub_pixel_avg_variance8x8, NULL, NULL, NULL,
1670 vp9_sad8x8x3, vp9_sad8x8x8, vp9_sad8x8x4d)
1672 BFP(BLOCK_8X4, vp9_sad8x4, vp9_sad8x4_avg,
1673 vp9_variance8x4, vp9_sub_pixel_variance8x4,
1674 vp9_sub_pixel_avg_variance8x4, NULL, NULL,
1675 NULL, NULL, vp9_sad8x4x8,
1678 BFP(BLOCK_4X8, vp9_sad4x8, vp9_sad4x8_avg,
1679 vp9_variance4x8, vp9_sub_pixel_variance4x8,
1680 vp9_sub_pixel_avg_variance4x8, NULL, NULL,
1681 NULL, NULL, vp9_sad4x8x8,
1684 BFP(BLOCK_4X4, vp9_sad4x4, vp9_sad4x4_avg,
1685 vp9_variance4x4, vp9_sub_pixel_variance4x4,
1686 vp9_sub_pixel_avg_variance4x4, NULL, NULL, NULL,
1687 vp9_sad4x4x3, vp9_sad4x4x8, vp9_sad4x4x4d)
1689 cpi->full_search_sad = vp9_full_search_sad;
1690 cpi->diamond_search_sad = vp9_diamond_search_sad;
1691 cpi->refining_search_sad = vp9_refining_search_sad;
1693 // make sure frame 1 is okay
1694 cpi->error_bins[0] = cpi->common.MBs;
1696 /* vp9_init_quantizer() is first called here. Add check in
1697 * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
1698 * called later when needed. This will avoid unnecessary calls of
1699 * vp9_init_quantizer() for every frame.
1701 vp9_init_quantizer(cpi);
1703 vp9_loop_filter_init(cm);
1705 cpi->common.error.setjmp = 0;
1707 vp9_zero(cpi->y_uv_mode_count)
1709 #ifdef MODE_TEST_HIT_STATS
1710 vp9_zero(cpi->mode_test_hits)
1713 return (VP9_PTR) cpi;
1716 void vp9_remove_compressor(VP9_PTR *ptr) {
1717 VP9_COMP *cpi = (VP9_COMP *)(*ptr);
1723 if (cpi && (cpi->common.current_video_frame > 0)) {
1724 if (cpi->pass == 2) {
1725 vp9_end_second_pass(cpi);
1728 #ifdef ENTROPY_STATS
1729 if (cpi->pass != 1) {
1730 print_context_counters();
1731 print_tree_update_probs();
1732 print_mode_context(cpi);
1737 if (cpi->pass != 1) {
1738 write_tx_count_stats();
1739 write_switchable_interp_stats();
1743 #if CONFIG_INTERNAL_STATS
1745 vp9_clear_system_state();
1747 // printf("\n8x8-4x4:%d-%d\n", cpi->t8x8_count, cpi->t4x4_count);
1748 if (cpi->pass != 1) {
1749 FILE *f = fopen("opsnr.stt", "a");
1750 double time_encoded = (cpi->last_end_time_stamp_seen
1751 - cpi->first_time_stamp_ever) / 10000000.000;
1752 double total_encode_time = (cpi->time_receive_data + cpi->time_compress_data) / 1000.000;
1753 double dr = (double)cpi->bytes * (double) 8 / (double)1000 / time_encoded;
1755 if (cpi->b_calculate_psnr) {
1756 YV12_BUFFER_CONFIG *lst_yv12 =
1757 &cpi->common.yv12_fb[cpi->common.ref_frame_map[cpi->lst_fb_idx]];
1758 double samples = 3.0 / 2 * cpi->count *
1759 lst_yv12->y_width * lst_yv12->y_height;
1760 double total_psnr = vp9_mse2psnr(samples, 255.0, cpi->total_sq_error);
1761 double total_psnr2 = vp9_mse2psnr(samples, 255.0, cpi->total_sq_error2);
1762 double total_ssim = 100 * pow(cpi->summed_quality /
1763 cpi->summed_weights, 8.0);
1764 double total_ssimp = 100 * pow(cpi->summedp_quality /
1765 cpi->summedp_weights, 8.0);
1767 fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
1768 "VPXSSIM\tVPSSIMP\t Time(ms)\n");
1769 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",
1770 dr, cpi->total / cpi->count, total_psnr,
1771 cpi->totalp / cpi->count, total_psnr2, total_ssim, total_ssimp,
1773 // fprintf(f, "%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%8.0f %10ld\n",
1774 // dr, cpi->total / cpi->count, total_psnr,
1775 // cpi->totalp / cpi->count, total_psnr2, total_ssim,
1776 // total_encode_time, cpi->tot_recode_hits);
1779 if (cpi->b_calculate_ssimg) {
1780 fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t Time(ms)\n");
1781 fprintf(f, "%7.2f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
1782 cpi->total_ssimg_y / cpi->count, cpi->total_ssimg_u / cpi->count,
1783 cpi->total_ssimg_v / cpi->count, cpi->total_ssimg_all / cpi->count, total_encode_time);
1784 // fprintf(f, "%7.3f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f %10ld\n", dr,
1785 // cpi->total_ssimg_y / cpi->count, cpi->total_ssimg_u / cpi->count,
1786 // cpi->total_ssimg_v / cpi->count, cpi->total_ssimg_all / cpi->count, total_encode_time, cpi->tot_recode_hits);
1794 #ifdef MODE_TEST_HIT_STATS
1795 if (cpi->pass != 1) {
1796 double norm_per_pixel_mode_tests = 0;
1797 double norm_counts[BLOCK_SIZES];
1800 int norm_factors[BLOCK_SIZES] =
1801 {256, 128, 128, 64, 32, 32, 16, 8, 8, 4, 2, 2, 1};
1802 FILE *f = fopen("mode_hit_stats.stt", "a");
1804 // On average, how many mode tests do we do
1805 for (i = 0; i < BLOCK_SIZES; ++i) {
1806 norm_counts[i] = (double)cpi->mode_test_hits[i] /
1807 (double)norm_factors[i];
1808 norm_per_pixel_mode_tests += norm_counts[i];
1810 // Convert to a number per 64x64 and per frame
1811 sb64_per_frame = ((cpi->common.height + 63) / 64) *
1812 ((cpi->common.width + 63) / 64);
1813 norm_per_pixel_mode_tests =
1814 norm_per_pixel_mode_tests /
1815 (double)(cpi->common.current_video_frame * sb64_per_frame);
1817 fprintf(f, "%6.4f\n", norm_per_pixel_mode_tests);
1822 #ifdef ENTROPY_STATS
1825 FILE *fmode = fopen("vp9_modecontext.c", "w");
1827 fprintf(fmode, "\n#include \"vp9_entropymode.h\"\n\n");
1828 fprintf(fmode, "const unsigned int vp9_kf_default_bmode_counts ");
1829 fprintf(fmode, "[INTRA_MODES][INTRA_MODES]"
1830 "[INTRA_MODES] =\n{\n");
1832 for (i = 0; i < INTRA_MODES; i++) {
1834 fprintf(fmode, " { // Above Mode : %d\n", i);
1836 for (j = 0; j < INTRA_MODES; j++) {
1838 fprintf(fmode, " {");
1840 for (k = 0; k < INTRA_MODES; k++) {
1841 if (!intra_mode_stats[i][j][k])
1842 fprintf(fmode, " %5d, ", 1);
1844 fprintf(fmode, " %5d, ", intra_mode_stats[i][j][k]);
1847 fprintf(fmode, "}, // left_mode %d\n", j);
1851 fprintf(fmode, " },\n");
1855 fprintf(fmode, "};\n");
1861 #if defined(SECTIONBITS_OUTPUT)
1865 FILE *f = fopen("tokenbits.stt", "a");
1867 for (i = 0; i < 28; i++)
1868 fprintf(f, "%8d", (int)(Sectionbits[i] / 256));
1878 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
1879 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
1880 printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
1881 cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
1882 cpi->time_compress_data / 1000,
1883 (cpi->time_receive_data + cpi->time_compress_data) / 1000);
1889 dealloc_compressor_data(cpi);
1890 vpx_free(cpi->mb.ss);
1893 for (i = 0; i < sizeof(cpi->mbgraph_stats) / sizeof(cpi->mbgraph_stats[0]); i++) {
1894 vpx_free(cpi->mbgraph_stats[i].mb_stats);
1897 vp9_remove_common(&cpi->common);
1901 #ifdef OUTPUT_YUV_SRC
1904 #ifdef OUTPUT_YUV_REC
1905 fclose(yuv_rec_file);
1924 static uint64_t calc_plane_error(uint8_t *orig, int orig_stride,
1925 uint8_t *recon, int recon_stride,
1926 unsigned int cols, unsigned int rows) {
1927 unsigned int row, col;
1928 uint64_t total_sse = 0;
1931 for (row = 0; row + 16 <= rows; row += 16) {
1932 for (col = 0; col + 16 <= cols; col += 16) {
1935 vp9_mse16x16(orig + col, orig_stride, recon + col, recon_stride, &sse);
1939 /* Handle odd-sized width */
1941 unsigned int border_row, border_col;
1942 uint8_t *border_orig = orig;
1943 uint8_t *border_recon = recon;
1945 for (border_row = 0; border_row < 16; border_row++) {
1946 for (border_col = col; border_col < cols; border_col++) {
1947 diff = border_orig[border_col] - border_recon[border_col];
1948 total_sse += diff * diff;
1951 border_orig += orig_stride;
1952 border_recon += recon_stride;
1956 orig += orig_stride * 16;
1957 recon += recon_stride * 16;
1960 /* Handle odd-sized height */
1961 for (; row < rows; row++) {
1962 for (col = 0; col < cols; col++) {
1963 diff = orig[col] - recon[col];
1964 total_sse += diff * diff;
1967 orig += orig_stride;
1968 recon += recon_stride;
1975 static void generate_psnr_packet(VP9_COMP *cpi) {
1976 YV12_BUFFER_CONFIG *orig = cpi->Source;
1977 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
1978 struct vpx_codec_cx_pkt pkt;
1981 unsigned int width = orig->y_crop_width;
1982 unsigned int height = orig->y_crop_height;
1984 pkt.kind = VPX_CODEC_PSNR_PKT;
1985 sse = calc_plane_error(orig->y_buffer, orig->y_stride,
1986 recon->y_buffer, recon->y_stride,
1988 pkt.data.psnr.sse[0] = sse;
1989 pkt.data.psnr.sse[1] = sse;
1990 pkt.data.psnr.samples[0] = width * height;
1991 pkt.data.psnr.samples[1] = width * height;
1993 width = orig->uv_crop_width;
1994 height = orig->uv_crop_height;
1996 sse = calc_plane_error(orig->u_buffer, orig->uv_stride,
1997 recon->u_buffer, recon->uv_stride,
1999 pkt.data.psnr.sse[0] += sse;
2000 pkt.data.psnr.sse[2] = sse;
2001 pkt.data.psnr.samples[0] += width * height;
2002 pkt.data.psnr.samples[2] = width * height;
2004 sse = calc_plane_error(orig->v_buffer, orig->uv_stride,
2005 recon->v_buffer, recon->uv_stride,
2007 pkt.data.psnr.sse[0] += sse;
2008 pkt.data.psnr.sse[3] = sse;
2009 pkt.data.psnr.samples[0] += width * height;
2010 pkt.data.psnr.samples[3] = width * height;
2012 for (i = 0; i < 4; i++)
2013 pkt.data.psnr.psnr[i] = vp9_mse2psnr(pkt.data.psnr.samples[i], 255.0,
2014 (double)pkt.data.psnr.sse[i]);
2016 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2020 int vp9_use_as_reference(VP9_PTR ptr, int ref_frame_flags) {
2021 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2023 if (ref_frame_flags > 7)
2026 cpi->ref_frame_flags = ref_frame_flags;
2029 int vp9_update_reference(VP9_PTR ptr, int ref_frame_flags) {
2030 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2032 if (ref_frame_flags > 7)
2035 cpi->refresh_golden_frame = 0;
2036 cpi->refresh_alt_ref_frame = 0;
2037 cpi->refresh_last_frame = 0;
2039 if (ref_frame_flags & VP9_LAST_FLAG)
2040 cpi->refresh_last_frame = 1;
2042 if (ref_frame_flags & VP9_GOLD_FLAG)
2043 cpi->refresh_golden_frame = 1;
2045 if (ref_frame_flags & VP9_ALT_FLAG)
2046 cpi->refresh_alt_ref_frame = 1;
2051 int vp9_copy_reference_enc(VP9_PTR ptr, VP9_REFFRAME ref_frame_flag,
2052 YV12_BUFFER_CONFIG *sd) {
2053 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2054 VP9_COMMON *cm = &cpi->common;
2057 if (ref_frame_flag == VP9_LAST_FLAG)
2058 ref_fb_idx = cm->ref_frame_map[cpi->lst_fb_idx];
2059 else if (ref_frame_flag == VP9_GOLD_FLAG)
2060 ref_fb_idx = cm->ref_frame_map[cpi->gld_fb_idx];
2061 else if (ref_frame_flag == VP9_ALT_FLAG)
2062 ref_fb_idx = cm->ref_frame_map[cpi->alt_fb_idx];
2066 vp8_yv12_copy_frame(&cm->yv12_fb[ref_fb_idx], sd);
2071 int vp9_get_reference_enc(VP9_PTR ptr, int index, YV12_BUFFER_CONFIG **fb) {
2072 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2073 VP9_COMMON *cm = &cpi->common;
2075 if (index < 0 || index >= NUM_REF_FRAMES)
2078 *fb = &cm->yv12_fb[cm->ref_frame_map[index]];
2082 int vp9_set_reference_enc(VP9_PTR ptr, VP9_REFFRAME ref_frame_flag,
2083 YV12_BUFFER_CONFIG *sd) {
2084 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2085 VP9_COMMON *cm = &cpi->common;
2089 if (ref_frame_flag == VP9_LAST_FLAG)
2090 ref_fb_idx = cm->ref_frame_map[cpi->lst_fb_idx];
2091 else if (ref_frame_flag == VP9_GOLD_FLAG)
2092 ref_fb_idx = cm->ref_frame_map[cpi->gld_fb_idx];
2093 else if (ref_frame_flag == VP9_ALT_FLAG)
2094 ref_fb_idx = cm->ref_frame_map[cpi->alt_fb_idx];
2098 vp8_yv12_copy_frame(sd, &cm->yv12_fb[ref_fb_idx]);
2102 int vp9_update_entropy(VP9_PTR comp, int update) {
2103 ((VP9_COMP *)comp)->common.refresh_frame_context = update;
2108 #ifdef OUTPUT_YUV_SRC
2109 void vp9_write_yuv_frame(YV12_BUFFER_CONFIG *s) {
2110 uint8_t *src = s->y_buffer;
2111 int h = s->y_height;
2114 fwrite(src, s->y_width, 1, yuv_file);
2122 fwrite(src, s->uv_width, 1, yuv_file);
2123 src += s->uv_stride;
2130 fwrite(src, s->uv_width, 1, yuv_file);
2131 src += s->uv_stride;
2136 #ifdef OUTPUT_YUV_REC
2137 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
2138 YV12_BUFFER_CONFIG *s = cm->frame_to_show;
2139 uint8_t *src = s->y_buffer;
2143 fwrite(src, s->y_width, 1, yuv_rec_file);
2151 fwrite(src, s->uv_width, 1, yuv_rec_file);
2152 src += s->uv_stride;
2159 fwrite(src, s->uv_width, 1, yuv_rec_file);
2160 src += s->uv_stride;
2164 if (s->alpha_buffer) {
2165 src = s->alpha_buffer;
2166 h = s->alpha_height;
2168 fwrite(src, s->alpha_width, 1, yuv_rec_file);
2169 src += s->alpha_stride;
2174 fflush(yuv_rec_file);
2178 static void scale_and_extend_frame(YV12_BUFFER_CONFIG *src_fb,
2179 YV12_BUFFER_CONFIG *dst_fb) {
2180 const int in_w = src_fb->y_crop_width;
2181 const int in_h = src_fb->y_crop_height;
2182 const int out_w = dst_fb->y_crop_width;
2183 const int out_h = dst_fb->y_crop_height;
2186 uint8_t *srcs[4] = {src_fb->y_buffer, src_fb->u_buffer, src_fb->v_buffer,
2187 src_fb->alpha_buffer};
2188 int src_strides[4] = {src_fb->y_stride, src_fb->uv_stride, src_fb->uv_stride,
2189 src_fb->alpha_stride};
2191 uint8_t *dsts[4] = {dst_fb->y_buffer, dst_fb->u_buffer, dst_fb->v_buffer,
2192 dst_fb->alpha_buffer};
2193 int dst_strides[4] = {dst_fb->y_stride, dst_fb->uv_stride, dst_fb->uv_stride,
2194 dst_fb->alpha_stride};
2196 for (y = 0; y < out_h; y += 16) {
2197 for (x = 0; x < out_w; x += 16) {
2198 for (i = 0; i < MAX_MB_PLANE; ++i) {
2199 const int factor = i == 0 ? 1 : 2;
2200 const int x_q4 = x * (16 / factor) * in_w / out_w;
2201 const int y_q4 = y * (16 / factor) * in_h / out_h;
2202 const int src_stride = src_strides[i];
2203 const int dst_stride = dst_strides[i];
2204 uint8_t *src = srcs[i] + y / factor * in_h / out_h * src_stride +
2205 x / factor * in_w / out_w;
2206 uint8_t *dst = dsts[i] + y / factor * dst_stride + x / factor;
2208 vp9_convolve8(src, src_stride, dst, dst_stride,
2209 vp9_sub_pel_filters_8[x_q4 & 0xf], 16 * in_w / out_w,
2210 vp9_sub_pel_filters_8[y_q4 & 0xf], 16 * in_h / out_h,
2211 16 / factor, 16 / factor);
2216 vp8_yv12_extend_frame_borders(dst_fb);
2220 static void update_alt_ref_frame_stats(VP9_COMP *cpi) {
2221 // this frame refreshes means next frames don't unless specified by user
2222 cpi->frames_since_golden = 0;
2224 #if CONFIG_MULTIPLE_ARF
2225 if (!cpi->multi_arf_enabled)
2227 // Clear the alternate reference update pending flag.
2228 cpi->source_alt_ref_pending = 0;
2230 // Set the alternate reference frame active flag
2231 cpi->source_alt_ref_active = 1;
2233 static void update_golden_frame_stats(VP9_COMP *cpi) {
2234 // Update the Golden frame usage counts.
2235 if (cpi->refresh_golden_frame) {
2236 // this frame refreshes means next frames don't unless specified by user
2237 cpi->refresh_golden_frame = 0;
2238 cpi->frames_since_golden = 0;
2240 // ******** Fixed Q test code only ************
2241 // If we are going to use the ALT reference for the next group of frames set a flag to say so.
2242 if (cpi->oxcf.fixed_q >= 0 &&
2243 cpi->oxcf.play_alternate && !cpi->refresh_alt_ref_frame) {
2244 cpi->source_alt_ref_pending = 1;
2245 cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
2247 // TODO(ivan): for SVC encoder, GF automatic update is disabled by using a
2248 // large GF_interval
2250 cpi->frames_till_gf_update_due = INT_MAX;
2254 if (!cpi->source_alt_ref_pending)
2255 cpi->source_alt_ref_active = 0;
2257 // Decrement count down till next gf
2258 if (cpi->frames_till_gf_update_due > 0)
2259 cpi->frames_till_gf_update_due--;
2261 } else if (!cpi->refresh_alt_ref_frame) {
2262 // Decrement count down till next gf
2263 if (cpi->frames_till_gf_update_due > 0)
2264 cpi->frames_till_gf_update_due--;
2266 if (cpi->frames_till_alt_ref_frame)
2267 cpi->frames_till_alt_ref_frame--;
2269 cpi->frames_since_golden++;
2273 static int find_fp_qindex() {
2276 for (i = 0; i < QINDEX_RANGE; i++) {
2277 if (vp9_convert_qindex_to_q(i) >= 30.0) {
2282 if (i == QINDEX_RANGE)
2288 static void Pass1Encode(VP9_COMP *cpi, unsigned long *size, unsigned char *dest, unsigned int *frame_flags) {
2294 vp9_set_quantizer(cpi, find_fp_qindex());
2295 vp9_first_pass(cpi);
2298 #define WRITE_RECON_BUFFER 0
2299 #if WRITE_RECON_BUFFER
2300 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame) {
2307 sprintf(filename, "cx\\y%04d.raw", this_frame);
2308 yframe = fopen(filename, "wb");
2310 for (i = 0; i < frame->y_height; i++)
2311 fwrite(frame->y_buffer + i * frame->y_stride,
2312 frame->y_width, 1, yframe);
2315 sprintf(filename, "cx\\u%04d.raw", this_frame);
2316 yframe = fopen(filename, "wb");
2318 for (i = 0; i < frame->uv_height; i++)
2319 fwrite(frame->u_buffer + i * frame->uv_stride,
2320 frame->uv_width, 1, yframe);
2323 sprintf(filename, "cx\\v%04d.raw", this_frame);
2324 yframe = fopen(filename, "wb");
2326 for (i = 0; i < frame->uv_height; i++)
2327 fwrite(frame->v_buffer + i * frame->uv_stride,
2328 frame->uv_width, 1, yframe);
2334 static double compute_edge_pixel_proportion(YV12_BUFFER_CONFIG *frame) {
2335 #define EDGE_THRESH 128
2337 int num_edge_pels = 0;
2338 int num_pels = (frame->y_height - 2) * (frame->y_width - 2);
2339 uint8_t *prev = frame->y_buffer + 1;
2340 uint8_t *curr = frame->y_buffer + 1 + frame->y_stride;
2341 uint8_t *next = frame->y_buffer + 1 + 2 * frame->y_stride;
2342 for (i = 1; i < frame->y_height - 1; i++) {
2343 for (j = 1; j < frame->y_width - 1; j++) {
2344 /* Sobel hor and ver gradients */
2345 int v = 2 * (curr[1] - curr[-1]) + (prev[1] - prev[-1]) + (next[1] - next[-1]);
2346 int h = 2 * (prev[0] - next[0]) + (prev[1] - next[1]) + (prev[-1] - next[-1]);
2347 h = (h < 0 ? -h : h);
2348 v = (v < 0 ? -v : v);
2349 if (h > EDGE_THRESH || v > EDGE_THRESH)
2355 curr += frame->y_stride - frame->y_width + 2;
2356 prev += frame->y_stride - frame->y_width + 2;
2357 next += frame->y_stride - frame->y_width + 2;
2359 return (double)num_edge_pels / num_pels;
2362 // Function to test for conditions that indicate we should loop
2363 // back and recode a frame.
2364 static int recode_loop_test(VP9_COMP *cpi,
2365 int high_limit, int low_limit,
2366 int q, int maxq, int minq) {
2367 int force_recode = 0;
2368 VP9_COMMON *cm = &cpi->common;
2370 // Is frame recode allowed at all
2371 // Yes if either recode mode 1 is selected or mode two is selected
2372 // and the frame is a key frame. golden frame or alt_ref_frame
2373 if ((cpi->sf.recode_loop == 1) ||
2374 ((cpi->sf.recode_loop == 2) &&
2375 ((cm->frame_type == KEY_FRAME) ||
2376 cpi->refresh_golden_frame ||
2377 cpi->refresh_alt_ref_frame))) {
2378 // General over and under shoot tests
2379 if (((cpi->projected_frame_size > high_limit) && (q < maxq)) ||
2380 ((cpi->projected_frame_size < low_limit) && (q > minq))) {
2383 // Special Constrained quality tests
2384 else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
2385 // Undershoot and below auto cq level
2386 if (q > cpi->cq_target_quality &&
2387 cpi->projected_frame_size < ((cpi->this_frame_target * 7) >> 3)) {
2389 } else if (q > cpi->oxcf.cq_level &&
2390 cpi->projected_frame_size < cpi->min_frame_bandwidth &&
2391 cpi->active_best_quality > cpi->oxcf.cq_level) {
2392 // Severe undershoot and between auto and user cq level
2394 cpi->active_best_quality = cpi->oxcf.cq_level;
2399 return force_recode;
2402 static void update_reference_frames(VP9_COMP * const cpi) {
2403 VP9_COMMON * const cm = &cpi->common;
2405 // At this point the new frame has been encoded.
2406 // If any buffer copy / swapping is signaled it should be done here.
2407 if (cm->frame_type == KEY_FRAME) {
2408 ref_cnt_fb(cm->fb_idx_ref_cnt,
2409 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2410 ref_cnt_fb(cm->fb_idx_ref_cnt,
2411 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2413 #if CONFIG_MULTIPLE_ARF
2414 else if (!cpi->multi_arf_enabled && cpi->refresh_golden_frame &&
2415 !cpi->refresh_alt_ref_frame) {
2417 else if (cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame &&
2420 /* Preserve the previously existing golden frame and update the frame in
2421 * the alt ref slot instead. This is highly specific to the current use of
2422 * alt-ref as a forward reference, and this needs to be generalized as
2423 * other uses are implemented (like RTC/temporal scaling)
2425 * The update to the buffer in the alt ref slot was signaled in
2426 * vp9_pack_bitstream(), now swap the buffer pointers so that it's treated
2427 * as the golden frame next time.
2431 ref_cnt_fb(cm->fb_idx_ref_cnt,
2432 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2434 tmp = cpi->alt_fb_idx;
2435 cpi->alt_fb_idx = cpi->gld_fb_idx;
2436 cpi->gld_fb_idx = tmp;
2437 } else { /* For non key/golden frames */
2438 if (cpi->refresh_alt_ref_frame) {
2439 int arf_idx = cpi->alt_fb_idx;
2440 #if CONFIG_MULTIPLE_ARF
2441 if (cpi->multi_arf_enabled) {
2442 arf_idx = cpi->arf_buffer_idx[cpi->sequence_number + 1];
2445 ref_cnt_fb(cm->fb_idx_ref_cnt,
2446 &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
2449 if (cpi->refresh_golden_frame) {
2450 ref_cnt_fb(cm->fb_idx_ref_cnt,
2451 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2455 if (cpi->refresh_last_frame) {
2456 ref_cnt_fb(cm->fb_idx_ref_cnt,
2457 &cm->ref_frame_map[cpi->lst_fb_idx], cm->new_fb_idx);
2461 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
2462 MACROBLOCKD *xd = &cpi->mb.e_mbd;
2463 struct loopfilter *lf = &cm->lf;
2465 lf->filter_level = 0;
2467 struct vpx_usec_timer timer;
2469 vp9_clear_system_state();
2471 vpx_usec_timer_start(&timer);
2473 vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.use_fast_lpf_pick);
2475 vpx_usec_timer_mark(&timer);
2476 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
2479 if (lf->filter_level > 0) {
2480 vp9_set_alt_lf_level(cpi, lf->filter_level);
2481 vp9_loop_filter_frame(cm, xd, lf->filter_level, 0, 0);
2484 vp9_extend_frame_inner_borders(cm->frame_to_show,
2485 cm->subsampling_x, cm->subsampling_y);
2488 static void scale_references(VP9_COMP *cpi) {
2489 VP9_COMMON *cm = &cpi->common;
2491 int refs[ALLOWED_REFS_PER_FRAME] = {cpi->lst_fb_idx, cpi->gld_fb_idx,
2494 for (i = 0; i < 3; i++) {
2495 YV12_BUFFER_CONFIG *ref = &cm->yv12_fb[cm->ref_frame_map[refs[i]]];
2497 if (ref->y_crop_width != cm->width ||
2498 ref->y_crop_height != cm->height) {
2499 int new_fb = get_free_fb(cm);
2501 vp9_realloc_frame_buffer(&cm->yv12_fb[new_fb],
2502 cm->width, cm->height,
2503 cm->subsampling_x, cm->subsampling_y,
2505 scale_and_extend_frame(ref, &cm->yv12_fb[new_fb]);
2506 cpi->scaled_ref_idx[i] = new_fb;
2508 cpi->scaled_ref_idx[i] = cm->ref_frame_map[refs[i]];
2509 cm->fb_idx_ref_cnt[cm->ref_frame_map[refs[i]]]++;
2514 static void release_scaled_references(VP9_COMP *cpi) {
2515 VP9_COMMON *cm = &cpi->common;
2518 for (i = 0; i < 3; i++)
2519 cm->fb_idx_ref_cnt[cpi->scaled_ref_idx[i]]--;
2522 static void full_to_model_count(unsigned int *model_count,
2523 unsigned int *full_count) {
2525 model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
2526 model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
2527 model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
2528 for (n = THREE_TOKEN; n < DCT_EOB_TOKEN; ++n)
2529 model_count[TWO_TOKEN] += full_count[n];
2530 model_count[DCT_EOB_MODEL_TOKEN] = full_count[DCT_EOB_TOKEN];
2533 static void full_to_model_counts(
2534 vp9_coeff_count_model *model_count, vp9_coeff_count *full_count) {
2536 for (i = 0; i < BLOCK_TYPES; ++i)
2537 for (j = 0; j < REF_TYPES; ++j)
2538 for (k = 0; k < COEF_BANDS; ++k)
2539 for (l = 0; l < PREV_COEF_CONTEXTS; ++l) {
2540 if (l >= 3 && k == 0)
2542 full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
2547 static void encode_frame_to_data_rate(VP9_COMP *cpi,
2548 unsigned long *size,
2549 unsigned char *dest,
2550 unsigned int *frame_flags) {
2551 VP9_COMMON *cm = &cpi->common;
2552 MACROBLOCKD *xd = &cpi->mb.e_mbd;
2555 int frame_over_shoot_limit;
2556 int frame_under_shoot_limit;
2566 int active_worst_qchanged = 0;
2568 int overshoot_seen = 0;
2569 int undershoot_seen = 0;
2571 SPEED_FEATURES *sf = &cpi->sf;
2572 unsigned int max_mv_def = MIN(cpi->common.width, cpi->common.height);
2573 struct segmentation *seg = &cm->seg;
2575 /* Scale the source buffer, if required */
2576 if (cm->mi_cols * 8 != cpi->un_scaled_source->y_width ||
2577 cm->mi_rows * 8 != cpi->un_scaled_source->y_height) {
2578 scale_and_extend_frame(cpi->un_scaled_source, &cpi->scaled_source);
2579 cpi->Source = &cpi->scaled_source;
2581 cpi->Source = cpi->un_scaled_source;
2584 scale_references(cpi);
2586 // Clear down mmx registers to allow floating point in what follows
2587 vp9_clear_system_state();
2590 // For an alt ref frame in 2 pass we skip the call to the second
2591 // pass function that sets the target bandwidth so must set it here
2592 if (cpi->refresh_alt_ref_frame) {
2593 // Per frame bit target for the alt ref frame
2594 cpi->per_frame_bandwidth = cpi->twopass.gf_bits;
2595 // per second target bitrate
2596 cpi->target_bandwidth = (int)(cpi->twopass.gf_bits *
2597 cpi->output_framerate);
2600 // Clear zbin over-quant value and mode boost values.
2601 cpi->zbin_mode_boost = 0;
2603 // Enable or disable mode based tweaking of the zbin
2604 // For 2 Pass Only used where GF/ARF prediction quality
2605 // is above a threshold
2606 cpi->zbin_mode_boost = 0;
2608 // if (cpi->oxcf.lossless)
2609 cpi->zbin_mode_boost_enabled = 0;
2611 // cpi->zbin_mode_boost_enabled = 1;
2613 // Current default encoder behaviour for the altref sign bias
2614 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = cpi->source_alt_ref_active;
2616 // Check to see if a key frame is signaled
2617 // For two pass with auto key frame enabled cm->frame_type may already be set, but not for one pass.
2618 if ((cm->current_video_frame == 0) ||
2619 (cm->frame_flags & FRAMEFLAGS_KEY) ||
2620 (cpi->oxcf.auto_key && (cpi->frames_since_key % cpi->key_frame_frequency == 0))) {
2621 // Key frame from VFW/auto-keyframe/first frame
2622 cm->frame_type = KEY_FRAME;
2625 // Set default state for segment based loop filter update flags
2626 cm->lf.mode_ref_delta_update = 0;
2628 // Initialize cpi->mv_step_param to default based on max resolution
2629 cpi->mv_step_param = vp9_init_search_range(cpi, max_mv_def);
2630 // Initialize cpi->max_mv_magnitude and cpi->mv_step_param if appropriate.
2631 if (sf->auto_mv_step_size) {
2632 if ((cpi->common.frame_type == KEY_FRAME) || cpi->common.intra_only) {
2633 // initialize max_mv_magnitude for use in the first INTER frame
2634 // after a key/intra-only frame
2635 cpi->max_mv_magnitude = max_mv_def;
2638 // allow mv_steps to correspond to twice the max mv magnitude found
2639 // in the previous frame, capped by the default max_mv_magnitude based
2641 cpi->mv_step_param = vp9_init_search_range(
2642 cpi, MIN(max_mv_def, 2 * cpi->max_mv_magnitude));
2643 cpi->max_mv_magnitude = 0;
2647 // Set various flags etc to special state if it is a key frame
2648 if (cm->frame_type == KEY_FRAME) {
2649 // Reset the loop filter deltas and segmentation map
2652 // If segmentation is enabled force a map update for key frames
2654 seg->update_map = 1;
2655 seg->update_data = 1;
2658 // The alternate reference frame cannot be active for a key frame
2659 cpi->source_alt_ref_active = 0;
2661 cm->error_resilient_mode = (cpi->oxcf.error_resilient_mode != 0);
2662 cm->frame_parallel_decoding_mode =
2663 (cpi->oxcf.frame_parallel_decoding_mode != 0);
2664 if (cm->error_resilient_mode) {
2665 cm->frame_parallel_decoding_mode = 1;
2666 cm->reset_frame_context = 0;
2667 cm->refresh_frame_context = 0;
2671 // Configure experimental use of segmentation for enhanced coding of
2672 // static regions if indicated.
2673 // Only allowed for now in second pass of two pass (as requires lagged coding)
2674 // and if the relevant speed feature flag is set.
2675 if ((cpi->pass == 2) && (cpi->sf.static_segmentation)) {
2676 configure_static_seg_features(cpi);
2679 // Decide how big to make the frame
2680 vp9_pick_frame_size(cpi);
2682 vp9_clear_system_state();
2684 // Set an active best quality and if necessary active worst quality
2685 q = cpi->active_worst_quality;
2687 if (cm->frame_type == KEY_FRAME) {
2688 #if !CONFIG_MULTIPLE_ARF
2689 // Special case for key frames forced because we have reached
2690 // the maximum key frame interval. Here force the Q to a range
2691 // based on the ambient Q to reduce the risk of popping
2692 if (cpi->this_key_frame_forced) {
2694 int qindex = cpi->last_boosted_qindex;
2695 double last_boosted_q = vp9_convert_qindex_to_q(qindex);
2697 delta_qindex = compute_qdelta(cpi, last_boosted_q,
2698 (last_boosted_q * 0.75));
2700 cpi->active_best_quality = MAX(qindex + delta_qindex,
2705 double q_adj_factor = 1.0;
2708 // Baseline value derived from cpi->active_worst_quality and kf boost
2709 if (cpi->kf_boost > high) {
2710 cpi->active_best_quality = kf_low_motion_minq[q];
2711 } else if (cpi->kf_boost < low) {
2712 cpi->active_best_quality = kf_high_motion_minq[q];
2714 const int gap = high - low;
2715 const int offset = high - cpi->kf_boost;
2716 const int qdiff = kf_high_motion_minq[q] - kf_low_motion_minq[q];
2717 const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
2719 cpi->active_best_quality = kf_low_motion_minq[q] + adjustment;
2722 // Allow somewhat lower kf minq with small image formats.
2723 if ((cm->width * cm->height) <= (352 * 288)) {
2724 q_adj_factor -= 0.25;
2727 // Make a further adjustment based on the kf zero motion measure.
2728 q_adj_factor += 0.05 - (0.001 * (double)cpi->kf_zeromotion_pct);
2730 // Convert the adjustment factor to a qindex delta
2731 // on active_best_quality.
2732 q_val = vp9_convert_qindex_to_q(cpi->active_best_quality);
2733 cpi->active_best_quality +=
2734 compute_qdelta(cpi, q_val, (q_val * q_adj_factor));
2738 // Force the KF quantizer to be 30% of the active_worst_quality.
2739 current_q = vp9_convert_qindex_to_q(cpi->active_worst_quality);
2740 cpi->active_best_quality = cpi->active_worst_quality
2741 + compute_qdelta(cpi, current_q, current_q * 0.3);
2743 } else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) {
2747 // Use the lower of cpi->active_worst_quality and recent
2748 // average Q as basis for GF/ARF Q limit unless last frame was
2750 if (cpi->frames_since_key > 1 &&
2751 cpi->avg_frame_qindex < cpi->active_worst_quality) {
2752 q = cpi->avg_frame_qindex;
2754 // For constrained quality dont allow Q less than the cq level
2755 if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY &&
2756 q < cpi->cq_target_quality) {
2757 q = cpi->cq_target_quality;
2759 if (cpi->gfu_boost > high) {
2760 cpi->active_best_quality = gf_low_motion_minq[q];
2761 } else if (cpi->gfu_boost < low) {
2762 cpi->active_best_quality = gf_high_motion_minq[q];
2764 const int gap = high - low;
2765 const int offset = high - cpi->gfu_boost;
2766 const int qdiff = gf_high_motion_minq[q] - gf_low_motion_minq[q];
2767 const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
2769 cpi->active_best_quality = gf_low_motion_minq[q] + adjustment;
2772 // Constrained quality use slightly lower active best.
2773 if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
2774 cpi->active_best_quality = cpi->active_best_quality * 15 / 16;
2776 // TODO(debargha): Refine the logic below
2777 if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
2778 if (!cpi->refresh_alt_ref_frame) {
2779 cpi->active_best_quality = cpi->cq_target_quality;
2781 if (cpi->frames_since_key > 1) {
2782 if (cpi->gfu_boost > high) {
2783 cpi->active_best_quality = afq_low_motion_minq[q];
2784 } else if (cpi->gfu_boost < low) {
2785 cpi->active_best_quality = afq_high_motion_minq[q];
2787 const int gap = high - low;
2788 const int offset = high - cpi->gfu_boost;
2789 const int qdiff = afq_high_motion_minq[q] - afq_low_motion_minq[q];
2790 const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
2792 cpi->active_best_quality = afq_low_motion_minq[q] + adjustment;
2798 if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
2799 cpi->active_best_quality = cpi->cq_target_quality;
2801 #ifdef ONE_SHOT_Q_ESTIMATE
2802 #ifdef STRICT_ONE_SHOT_Q
2803 cpi->active_best_quality = q;
2805 cpi->active_best_quality = inter_minq[q];
2808 cpi->active_best_quality = inter_minq[q];
2811 // For the constant/constrained quality mode we don't want
2812 // q to fall below the cq level.
2813 if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
2814 (cpi->active_best_quality < cpi->cq_target_quality)) {
2815 // If we are strongly undershooting the target rate in the last
2816 // frames then use the user passed in cq value not the auto
2818 if (cpi->rolling_actual_bits < cpi->min_frame_bandwidth)
2819 cpi->active_best_quality = cpi->oxcf.cq_level;
2821 cpi->active_best_quality = cpi->cq_target_quality;
2826 // Clip the active best and worst quality values to limits
2827 if (cpi->active_worst_quality > cpi->worst_quality)
2828 cpi->active_worst_quality = cpi->worst_quality;
2830 if (cpi->active_best_quality < cpi->best_quality)
2831 cpi->active_best_quality = cpi->best_quality;
2833 if (cpi->active_best_quality > cpi->worst_quality)
2834 cpi->active_best_quality = cpi->worst_quality;
2836 if (cpi->active_worst_quality < cpi->active_best_quality)
2837 cpi->active_worst_quality = cpi->active_best_quality;
2839 // Special case code to try and match quality with forced key frames
2840 if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
2841 q = cpi->active_best_quality;
2842 } else if ((cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced) {
2843 q = cpi->last_boosted_qindex;
2845 // Determine initial Q to try
2846 q = vp9_regulate_q(cpi, cpi->this_frame_target);
2849 vp9_compute_frame_size_bounds(cpi, &frame_under_shoot_limit,
2850 &frame_over_shoot_limit);
2852 #if CONFIG_MULTIPLE_ARF
2853 // Force the quantizer determined by the coding order pattern.
2854 if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
2855 cpi->oxcf.end_usage != USAGE_CONSTANT_QUALITY) {
2857 double current_q = vp9_convert_qindex_to_q(cpi->active_worst_quality);
2858 int level = cpi->this_frame_weight;
2861 // Set quantizer steps at 10% increments.
2862 new_q = current_q * (1.0 - (0.2 * (cpi->max_arf_level - level)));
2863 q = cpi->active_worst_quality + compute_qdelta(cpi, current_q, new_q);
2870 printf("frame:%d q:%d\n", cm->current_video_frame, q);
2873 // Limit Q range for the adaptive loop.
2874 bottom_index = cpi->active_best_quality;
2875 top_index = cpi->active_worst_quality;
2876 q_low = cpi->active_best_quality;
2877 q_high = cpi->active_worst_quality;
2878 #if CONFIG_MULTIPLE_ARF
2882 vp9_zero(cpi->rd_tx_select_threshes);
2884 if (cm->frame_type != KEY_FRAME) {
2885 cm->mcomp_filter_type = DEFAULT_INTERP_FILTER;
2886 /* TODO: Decide this more intelligently */
2887 xd->allow_high_precision_mv = q < HIGH_PRECISION_MV_QTHRESH;
2888 set_mvcost(&cpi->mb);
2891 #if CONFIG_VP9_POSTPROC
2893 if (cpi->oxcf.noise_sensitivity > 0) {
2896 switch (cpi->oxcf.noise_sensitivity) {
2915 vp9_denoise(cpi->Source, cpi->Source, l);
2920 #ifdef OUTPUT_YUV_SRC
2921 vp9_write_yuv_frame(cpi->Source);
2925 vp9_clear_system_state(); // __asm emms;
2927 vp9_set_quantizer(cpi, q);
2929 if (loop_count == 0) {
2931 // Set up entropy depending on frame type.
2932 if (cm->frame_type == KEY_FRAME) {
2933 /* Choose which entropy context to use. When using a forward reference
2934 * frame, it immediately follows the keyframe, and thus benefits from
2935 * using the same entropy context established by the keyframe.
2936 * Otherwise, use the default context 0.
2938 cm->frame_context_idx = cpi->oxcf.play_alternate;
2939 vp9_setup_key_frame(cpi);
2941 /* Choose which entropy context to use. Currently there are only two
2942 * contexts used, one for normal frames and one for alt ref frames.
2944 cpi->common.frame_context_idx = cpi->refresh_alt_ref_frame;
2945 vp9_setup_inter_frame(cpi);
2949 // transform / motion compensation build reconstruction frame
2951 vp9_encode_frame(cpi);
2953 // Update the skip mb flag probabilities based on the distribution
2954 // seen in the last encoder iteration.
2955 // update_base_skip_probs(cpi);
2957 vp9_clear_system_state(); // __asm emms;
2959 // Dummy pack of the bitstream using up to date stats to get an
2960 // accurate estimate of output frame size to determine if we need
2962 vp9_save_coding_context(cpi);
2963 cpi->dummy_packing = 1;
2964 vp9_pack_bitstream(cpi, dest, size);
2965 cpi->projected_frame_size = (*size) << 3;
2966 vp9_restore_coding_context(cpi);
2968 if (frame_over_shoot_limit == 0)
2969 frame_over_shoot_limit = 1;
2970 active_worst_qchanged = 0;
2972 // Special case handling for forced key frames
2973 if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
2976 if ((cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced) {
2978 int kf_err = vp9_calc_ss_err(cpi->Source,
2979 &cm->yv12_fb[cm->new_fb_idx]);
2981 int high_err_target = cpi->ambient_err;
2982 int low_err_target = cpi->ambient_err >> 1;
2984 // Prevent possible divide by zero error below for perfect KF
2987 // The key frame is not good enough or we can afford
2988 // to make it better without undue risk of popping.
2989 if ((kf_err > high_err_target &&
2990 cpi->projected_frame_size <= frame_over_shoot_limit) ||
2991 (kf_err > low_err_target &&
2992 cpi->projected_frame_size <= frame_under_shoot_limit)) {
2994 q_high = q > q_low ? q - 1 : q_low;
2997 q = (q * high_err_target) / kf_err;
2998 q = MIN(q, (q_high + q_low) >> 1);
2999 } else if (kf_err < low_err_target &&
3000 cpi->projected_frame_size >= frame_under_shoot_limit) {
3001 // The key frame is much better than the previous frame
3003 q_low = q < q_high ? q + 1 : q_high;
3006 q = (q * low_err_target) / kf_err;
3007 q = MIN(q, (q_high + q_low + 1) >> 1);
3010 // Clamp Q to upper and lower limits:
3011 q = clamp(q, q_low, q_high);
3014 } else if (recode_loop_test(
3015 cpi, frame_over_shoot_limit, frame_under_shoot_limit,
3016 q, top_index, bottom_index)) {
3017 // Is the projected frame size out of range and are we allowed
3018 // to attempt to recode.
3022 // Frame size out of permitted range:
3023 // Update correction factor & compute new Q to try...
3025 // Frame is too large
3026 if (cpi->projected_frame_size > cpi->this_frame_target) {
3027 // Raise Qlow as to at least the current value
3028 q_low = q < q_high ? q + 1 : q_high;
3030 if (undershoot_seen || loop_count > 1) {
3031 // Update rate_correction_factor unless
3032 // cpi->active_worst_quality has changed.
3033 if (!active_worst_qchanged)
3034 vp9_update_rate_correction_factors(cpi, 1);
3036 q = (q_high + q_low + 1) / 2;
3038 // Update rate_correction_factor unless
3039 // cpi->active_worst_quality has changed.
3040 if (!active_worst_qchanged)
3041 vp9_update_rate_correction_factors(cpi, 0);
3043 q = vp9_regulate_q(cpi, cpi->this_frame_target);
3045 while (q < q_low && retries < 10) {
3046 vp9_update_rate_correction_factors(cpi, 0);
3047 q = vp9_regulate_q(cpi, cpi->this_frame_target);
3054 // Frame is too small
3055 q_high = q > q_low ? q - 1 : q_low;
3057 if (overshoot_seen || loop_count > 1) {
3058 // Update rate_correction_factor unless
3059 // cpi->active_worst_quality has changed.
3060 if (!active_worst_qchanged)
3061 vp9_update_rate_correction_factors(cpi, 1);
3063 q = (q_high + q_low) / 2;
3065 // Update rate_correction_factor unless
3066 // cpi->active_worst_quality has changed.
3067 if (!active_worst_qchanged)
3068 vp9_update_rate_correction_factors(cpi, 0);
3070 q = vp9_regulate_q(cpi, cpi->this_frame_target);
3072 // Special case reset for qlow for constrained quality.
3073 // This should only trigger where there is very substantial
3074 // undershoot on a frame and the auto cq level is above
3075 // the user passsed in value.
3076 if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY && q < q_low) {
3080 while (q > q_high && retries < 10) {
3081 vp9_update_rate_correction_factors(cpi, 0);
3082 q = vp9_regulate_q(cpi, cpi->this_frame_target);
3087 undershoot_seen = 1;
3090 // Clamp Q to upper and lower limits:
3091 q = clamp(q, q_low, q_high);
3099 if (cpi->is_src_frame_alt_ref)
3105 #if CONFIG_INTERNAL_STATS
3106 cpi->tot_recode_hits++;
3111 // Special case code to reduce pulsing when key frames are forced at a
3112 // fixed interval. Note the reconstruction error if it is the frame before
3113 // the force key frame
3114 if (cpi->next_key_frame_forced && (cpi->twopass.frames_to_key == 0)) {
3115 cpi->ambient_err = vp9_calc_ss_err(cpi->Source,
3116 &cm->yv12_fb[cm->new_fb_idx]);
3119 if (cm->frame_type == KEY_FRAME)
3120 cpi->refresh_last_frame = 1;
3122 cm->frame_to_show = &cm->yv12_fb[cm->new_fb_idx];
3124 #if WRITE_RECON_BUFFER
3126 write_cx_frame_to_file(cm->frame_to_show,
3127 cm->current_video_frame);
3129 write_cx_frame_to_file(cm->frame_to_show,
3130 cm->current_video_frame + 1000);
3133 // Pick the loop filter level for the frame.
3134 loopfilter_frame(cpi, cm);
3136 #if WRITE_RECON_BUFFER
3138 write_cx_frame_to_file(cm->frame_to_show,
3139 cm->current_video_frame + 2000);
3141 write_cx_frame_to_file(cm->frame_to_show,
3142 cm->current_video_frame + 3000);
3145 // build the bitstream
3146 cpi->dummy_packing = 0;
3147 vp9_pack_bitstream(cpi, dest, size);
3149 if (cm->seg.update_map)
3150 update_reference_segmentation_map(cpi);
3152 release_scaled_references(cpi);
3153 update_reference_frames(cpi);
3155 for (t = TX_4X4; t <= TX_32X32; t++)
3156 full_to_model_counts(cpi->common.counts.coef[t],
3157 cpi->coef_counts[t]);
3158 if (!cpi->common.error_resilient_mode &&
3159 !cpi->common.frame_parallel_decoding_mode) {
3160 vp9_adapt_coef_probs(&cpi->common);
3163 if (cpi->common.frame_type != KEY_FRAME) {
3164 FRAME_COUNTS *counts = &cpi->common.counts;
3166 vp9_copy(counts->y_mode, cpi->y_mode_count);
3167 vp9_copy(counts->uv_mode, cpi->y_uv_mode_count);
3168 vp9_copy(counts->partition, cpi->partition_count);
3169 vp9_copy(counts->intra_inter, cpi->intra_inter_count);
3170 vp9_copy(counts->comp_inter, cpi->comp_inter_count);
3171 vp9_copy(counts->single_ref, cpi->single_ref_count);
3172 vp9_copy(counts->comp_ref, cpi->comp_ref_count);
3173 counts->mv = cpi->NMVcount;
3174 if (!cpi->common.error_resilient_mode &&
3175 !cpi->common.frame_parallel_decoding_mode) {
3176 vp9_adapt_mode_probs(&cpi->common);
3177 vp9_adapt_mv_probs(&cpi->common, cpi->mb.e_mbd.allow_high_precision_mv);
3181 #ifdef ENTROPY_STATS
3182 vp9_update_mode_context_stats(cpi);
3185 /* Move storing frame_type out of the above loop since it is also
3186 * needed in motion search besides loopfilter */
3187 cm->last_frame_type = cm->frame_type;
3189 // Update rate control heuristics
3190 cpi->total_byte_count += (*size);
3191 cpi->projected_frame_size = (*size) << 3;
3193 if (!active_worst_qchanged)
3194 vp9_update_rate_correction_factors(cpi, 2);
3196 cpi->last_q[cm->frame_type] = cm->base_qindex;
3198 // Keep record of last boosted (KF/KF/ARF) Q value.
3199 // If the current frame is coded at a lower Q then we also update it.
3200 // If all mbs in this group are skipped only update if the Q value is
3201 // better than that already stored.
3202 // This is used to help set quality in forced key frames to reduce popping
3203 if ((cm->base_qindex < cpi->last_boosted_qindex) ||
3204 ((cpi->static_mb_pct < 100) &&
3205 ((cm->frame_type == KEY_FRAME) ||
3206 cpi->refresh_alt_ref_frame ||
3207 (cpi->refresh_golden_frame && !cpi->is_src_frame_alt_ref)))) {
3208 cpi->last_boosted_qindex = cm->base_qindex;
3211 if (cm->frame_type == KEY_FRAME) {
3212 vp9_adjust_key_frame_context(cpi);
3215 // Keep a record of ambient average Q.
3216 if (cm->frame_type != KEY_FRAME)
3217 cpi->avg_frame_qindex = (2 + 3 * cpi->avg_frame_qindex + cm->base_qindex) >> 2;
3219 // Keep a record from which we can calculate the average Q excluding GF updates and key frames
3220 if (cm->frame_type != KEY_FRAME &&
3221 !cpi->refresh_golden_frame &&
3222 !cpi->refresh_alt_ref_frame) {
3224 cpi->tot_q += vp9_convert_qindex_to_q(q);
3225 cpi->avg_q = cpi->tot_q / (double)cpi->ni_frames;
3227 // Calculate the average Q for normal inter frames (not key or GFU frames).
3228 cpi->ni_tot_qi += q;
3229 cpi->ni_av_qi = cpi->ni_tot_qi / cpi->ni_frames;
3232 // Update the buffer level variable.
3233 // Non-viewable frames are a special case and are treated as pure overhead.
3234 if (!cm->show_frame)
3235 cpi->bits_off_target -= cpi->projected_frame_size;
3237 cpi->bits_off_target += cpi->av_per_frame_bandwidth - cpi->projected_frame_size;
3239 // Clip the buffer level at the maximum buffer size
3240 if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size)
3241 cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
3243 // Rolling monitors of whether we are over or underspending used to help
3244 // regulate min and Max Q in two pass.
3245 if (cm->frame_type != KEY_FRAME) {
3246 cpi->rolling_target_bits =
3247 ((cpi->rolling_target_bits * 3) + cpi->this_frame_target + 2) / 4;
3248 cpi->rolling_actual_bits =
3249 ((cpi->rolling_actual_bits * 3) + cpi->projected_frame_size + 2) / 4;
3250 cpi->long_rolling_target_bits =
3251 ((cpi->long_rolling_target_bits * 31) + cpi->this_frame_target + 16) / 32;
3252 cpi->long_rolling_actual_bits =
3253 ((cpi->long_rolling_actual_bits * 31) +
3254 cpi->projected_frame_size + 16) / 32;
3257 // Actual bits spent
3258 cpi->total_actual_bits += cpi->projected_frame_size;
3261 cpi->total_target_vs_actual += (cpi->this_frame_target - cpi->projected_frame_size);
3263 cpi->buffer_level = cpi->bits_off_target;
3265 // Update bits left to the kf and gf groups to account for overshoot or undershoot on these frames
3266 if (cm->frame_type == KEY_FRAME) {
3267 cpi->twopass.kf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
3269 cpi->twopass.kf_group_bits = MAX(cpi->twopass.kf_group_bits, 0);
3270 } else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) {
3271 cpi->twopass.gf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
3273 cpi->twopass.gf_group_bits = MAX(cpi->twopass.gf_group_bits, 0);
3276 // Update the skip mb flag probabilities based on the distribution seen
3278 // update_base_skip_probs(cpi);
3280 #if 0 // CONFIG_INTERNAL_STATS
3282 FILE *f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
3285 vp9_clear_system_state(); // __asm emms;
3287 recon_err = vp9_calc_ss_err(cpi->Source,
3288 &cm->yv12_fb[cm->new_fb_idx]);
3290 if (cpi->twopass.total_left_stats.coded_error != 0.0)
3291 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %10d"
3292 "%7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f"
3293 "%6d %6d %5d %5d %5d %8.2f %10d %10.3f"
3294 "%10.3f %8d %10d %10d %10d\n",
3295 cpi->common.current_video_frame, cpi->this_frame_target,
3296 cpi->projected_frame_size, 0, //loop_size_estimate,
3297 (cpi->projected_frame_size - cpi->this_frame_target),
3298 (int)cpi->total_target_vs_actual,
3299 (int)(cpi->oxcf.starting_buffer_level - cpi->bits_off_target),
3300 (int)cpi->total_actual_bits,
3302 vp9_convert_qindex_to_q(cm->base_qindex),
3303 (double)vp9_dc_quant(cm->base_qindex, 0) / 4.0,
3304 vp9_convert_qindex_to_q(cpi->active_best_quality),
3305 vp9_convert_qindex_to_q(cpi->active_worst_quality),
3307 vp9_convert_qindex_to_q(cpi->ni_av_qi),
3308 vp9_convert_qindex_to_q(cpi->cq_target_quality),
3309 cpi->refresh_last_frame,
3310 cpi->refresh_golden_frame, cpi->refresh_alt_ref_frame,
3311 cm->frame_type, cpi->gfu_boost,
3312 cpi->twopass.est_max_qcorrection_factor,
3313 (int)cpi->twopass.bits_left,
3314 cpi->twopass.total_left_stats.coded_error,
3315 (double)cpi->twopass.bits_left /
3316 cpi->twopass.total_left_stats.coded_error,
3317 cpi->tot_recode_hits, recon_err, cpi->kf_boost,
3318 cpi->kf_zeromotion_pct);
3320 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %10d"
3321 "%7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f"
3322 "%5d %5d %5d %8d %8d %8.2f %10d %10.3f"
3323 "%8d %10d %10d %10d\n",
3324 cpi->common.current_video_frame,
3325 cpi->this_frame_target, cpi->projected_frame_size,
3326 0, //loop_size_estimate,
3327 (cpi->projected_frame_size - cpi->this_frame_target),
3328 (int)cpi->total_target_vs_actual,
3329 (int)(cpi->oxcf.starting_buffer_level - cpi->bits_off_target),
3330 (int)cpi->total_actual_bits,
3332 vp9_convert_qindex_to_q(cm->base_qindex),
3333 (double)vp9_dc_quant(cm->base_qindex, 0) / 4.0,
3334 vp9_convert_qindex_to_q(cpi->active_best_quality),
3335 vp9_convert_qindex_to_q(cpi->active_worst_quality),
3337 vp9_convert_qindex_to_q(cpi->ni_av_qi),
3338 vp9_convert_qindex_to_q(cpi->cq_target_quality),
3339 cpi->refresh_last_frame,
3340 cpi->refresh_golden_frame, cpi->refresh_alt_ref_frame,
3341 cm->frame_type, cpi->gfu_boost,
3342 cpi->twopass.est_max_qcorrection_factor,
3343 (int)cpi->twopass.bits_left,
3344 cpi->twopass.total_left_stats.coded_error,
3345 cpi->tot_recode_hits, recon_err, cpi->kf_boost,
3346 cpi->kf_zeromotion_pct);
3351 FILE *fmodes = fopen("Modes.stt", "a");
3354 fprintf(fmodes, "%6d:%1d:%1d:%1d ",
3355 cpi->common.current_video_frame,
3356 cm->frame_type, cpi->refresh_golden_frame,
3357 cpi->refresh_alt_ref_frame);
3359 for (i = 0; i < MAX_MODES; i++)
3360 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
3362 fprintf(fmodes, "\n");
3371 // Debug stats for segment feature experiments.
3375 // If this was a kf or Gf note the Q
3376 if ((cm->frame_type == KEY_FRAME)
3377 || cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
3378 cm->last_kf_gf_q = cm->base_qindex;
3380 if (cpi->refresh_golden_frame == 1)
3381 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
3383 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_GOLDEN;
3385 if (cpi->refresh_alt_ref_frame == 1)
3386 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
3388 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_ALTREF;
3391 if (cpi->refresh_last_frame & cpi->refresh_golden_frame)
3392 cpi->gold_is_last = 1;
3393 else if (cpi->refresh_last_frame ^ cpi->refresh_golden_frame)
3394 cpi->gold_is_last = 0;
3396 if (cpi->refresh_last_frame & cpi->refresh_alt_ref_frame)
3397 cpi->alt_is_last = 1;
3398 else if (cpi->refresh_last_frame ^ cpi->refresh_alt_ref_frame)
3399 cpi->alt_is_last = 0;
3401 if (cpi->refresh_alt_ref_frame & cpi->refresh_golden_frame)
3402 cpi->gold_is_alt = 1;
3403 else if (cpi->refresh_alt_ref_frame ^ cpi->refresh_golden_frame)
3404 cpi->gold_is_alt = 0;
3406 cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
3408 if (cpi->gold_is_last)
3409 cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
3411 if (cpi->alt_is_last)
3412 cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
3414 if (cpi->gold_is_alt)
3415 cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
3417 if (cpi->oxcf.play_alternate && cpi->refresh_alt_ref_frame
3418 && (cm->frame_type != KEY_FRAME))
3419 // Update the alternate reference frame stats as appropriate.
3420 update_alt_ref_frame_stats(cpi);
3422 // Update the Golden frame stats as appropriate.
3423 update_golden_frame_stats(cpi);
3425 if (cm->frame_type == KEY_FRAME) {
3426 // Tell the caller that the frame was coded as a key frame
3427 *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
3429 #if CONFIG_MULTIPLE_ARF
3430 // Reset the sequence number.
3431 if (cpi->multi_arf_enabled) {
3432 cpi->sequence_number = 0;
3433 cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
3434 cpi->new_frame_coding_order_period = -1;
3438 // As this frame is a key frame the next defaults to an inter frame.
3439 cm->frame_type = INTER_FRAME;
3441 *frame_flags = cm->frame_flags&~FRAMEFLAGS_KEY;
3443 #if CONFIG_MULTIPLE_ARF
3444 /* Increment position in the coded frame sequence. */
3445 if (cpi->multi_arf_enabled) {
3446 ++cpi->sequence_number;
3447 if (cpi->sequence_number >= cpi->frame_coding_order_period) {
3448 cpi->sequence_number = 0;
3449 cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
3450 cpi->new_frame_coding_order_period = -1;
3452 cpi->this_frame_weight = cpi->arf_weight[cpi->sequence_number];
3453 assert(cpi->this_frame_weight >= 0);
3458 // Clear the one shot update flags for segmentation map and mode/ref loop filter deltas.
3459 cm->seg.update_map = 0;
3460 cm->seg.update_data = 0;
3461 cm->lf.mode_ref_delta_update = 0;
3463 // keep track of the last coded dimensions
3464 cm->last_width = cm->width;
3465 cm->last_height = cm->height;
3467 // reset to normal state now that we are done.
3468 cm->last_show_frame = cm->show_frame;
3469 if (cm->show_frame) {
3470 // current mip will be the prev_mip for the next frame
3471 MODE_INFO *temp = cm->prev_mip;
3472 MODE_INFO **temp2 = cm->prev_mi_grid_base;
3473 cm->prev_mip = cm->mip;
3475 cm->prev_mi_grid_base = cm->mi_grid_base;
3476 cm->mi_grid_base = temp2;
3478 // update the upper left visible macroblock ptrs
3479 cm->mi = cm->mip + cm->mode_info_stride + 1;
3480 cm->mi_grid_visible = cm->mi_grid_base + cm->mode_info_stride + 1;
3482 // Don't increment frame counters if this was an altref buffer
3483 // update not a real frame
3484 ++cm->current_video_frame;
3485 ++cpi->frames_since_key;
3488 cm->prev_mi = cm->prev_mip + cm->mode_info_stride + 1;
3489 cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mode_info_stride + 1;
3495 sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
3496 recon_file = fopen(filename, "wb");
3497 fwrite(cm->yv12_fb[cm->ref_frame_map[cpi->lst_fb_idx]].buffer_alloc,
3498 cm->yv12_fb[cm->ref_frame_map[cpi->lst_fb_idx]].frame_size,
3503 #ifdef OUTPUT_YUV_REC
3504 vp9_write_yuv_rec_frame(cm);
3509 static void Pass2Encode(VP9_COMP *cpi, unsigned long *size,
3510 unsigned char *dest, unsigned int *frame_flags) {
3512 cpi->enable_encode_breakout = 1;
3514 if (!cpi->refresh_alt_ref_frame)
3515 vp9_second_pass(cpi);
3517 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3518 // vp9_print_modes_and_motion_vectors(&cpi->common, "encode.stt");
3519 #ifdef DISABLE_RC_LONG_TERM_MEM
3520 cpi->twopass.bits_left -= cpi->this_frame_target;
3522 cpi->twopass.bits_left -= 8 * *size;
3525 if (!cpi->refresh_alt_ref_frame) {
3526 double lower_bounds_min_rate = FRAME_OVERHEAD_BITS * cpi->oxcf.framerate;
3527 double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth
3528 * cpi->oxcf.two_pass_vbrmin_section / 100);
3530 if (two_pass_min_rate < lower_bounds_min_rate)
3531 two_pass_min_rate = lower_bounds_min_rate;
3533 cpi->twopass.bits_left += (int64_t)(two_pass_min_rate / cpi->oxcf.framerate);
3537 static void check_initial_width(VP9_COMP *cpi, YV12_BUFFER_CONFIG *sd) {
3538 VP9_COMMON *cm = &cpi->common;
3539 if (!cpi->initial_width) {
3540 // TODO(jkoleszar): Support 1/4 subsampling?
3541 cm->subsampling_x = (sd != NULL) && sd->uv_width < sd->y_width;
3542 cm->subsampling_y = (sd != NULL) && sd->uv_height < sd->y_height;
3543 alloc_raw_frame_buffers(cpi);
3545 cpi->initial_width = cm->width;
3546 cpi->initial_height = cm->height;
3551 int vp9_receive_raw_frame(VP9_PTR ptr, unsigned int frame_flags,
3552 YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
3554 VP9_COMP *cpi = (VP9_COMP *) ptr;
3555 struct vpx_usec_timer timer;
3558 check_initial_width(cpi, sd);
3559 vpx_usec_timer_start(&timer);
3560 if (vp9_lookahead_push(cpi->lookahead, sd, time_stamp, end_time, frame_flags,
3561 cpi->active_map_enabled ? cpi->active_map : NULL))
3563 vpx_usec_timer_mark(&timer);
3564 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
3570 static int frame_is_reference(const VP9_COMP *cpi) {
3571 const VP9_COMMON *cm = &cpi->common;
3573 return cm->frame_type == KEY_FRAME ||
3574 cpi->refresh_last_frame ||
3575 cpi->refresh_golden_frame ||
3576 cpi->refresh_alt_ref_frame ||
3577 cm->refresh_frame_context ||
3578 cm->lf.mode_ref_delta_update ||
3579 cm->seg.update_map ||
3580 cm->seg.update_data;
3583 #if CONFIG_MULTIPLE_ARF
3584 int is_next_frame_arf(VP9_COMP *cpi) {
3585 // Negative entry in frame_coding_order indicates an ARF at this position.
3586 return cpi->frame_coding_order[cpi->sequence_number + 1] < 0 ? 1 : 0;
3590 int vp9_get_compressed_data(VP9_PTR ptr, unsigned int *frame_flags,
3591 unsigned long *size, unsigned char *dest,
3592 int64_t *time_stamp, int64_t *time_end, int flush) {
3593 VP9_COMP *cpi = (VP9_COMP *) ptr;
3594 VP9_COMMON *cm = &cpi->common;
3595 struct vpx_usec_timer cmptimer;
3596 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
3598 // FILE *fp_out = fopen("enc_frame_type.txt", "a");
3603 vpx_usec_timer_start(&cmptimer);
3607 cpi->mb.e_mbd.allow_high_precision_mv = ALTREF_HIGH_PRECISION_MV;
3608 set_mvcost(&cpi->mb);
3610 // Should we code an alternate reference frame.
3611 if (cpi->oxcf.play_alternate && cpi->source_alt_ref_pending) {
3614 #if CONFIG_MULTIPLE_ARF
3615 assert(!cpi->multi_arf_enabled ||
3616 cpi->frame_coding_order[cpi->sequence_number] < 0);
3618 if (cpi->multi_arf_enabled && (cpi->pass == 2))
3619 frames_to_arf = (-cpi->frame_coding_order[cpi->sequence_number])
3620 - cpi->next_frame_in_order;
3623 frames_to_arf = cpi->frames_till_gf_update_due;
3625 assert(frames_to_arf < cpi->twopass.frames_to_key);
3627 if ((cpi->source = vp9_lookahead_peek(cpi->lookahead, frames_to_arf))) {
3628 #if CONFIG_MULTIPLE_ARF
3629 cpi->alt_ref_source[cpi->arf_buffered] = cpi->source;
3631 cpi->alt_ref_source = cpi->source;
3634 if (cpi->oxcf.arnr_max_frames > 0) {
3635 // Produce the filtered ARF frame.
3636 // TODO(agrange) merge these two functions.
3637 configure_arnr_filter(cpi, cm->current_video_frame + frames_to_arf,
3639 vp9_temporal_filter_prepare(cpi, frames_to_arf);
3640 vp9_extend_frame_borders(&cpi->alt_ref_buffer,
3641 cm->subsampling_x, cm->subsampling_y);
3642 force_src_buffer = &cpi->alt_ref_buffer;
3647 cpi->refresh_alt_ref_frame = 1;
3648 cpi->refresh_golden_frame = 0;
3649 cpi->refresh_last_frame = 0;
3650 cpi->is_src_frame_alt_ref = 0;
3652 // TODO(agrange) This needs to vary depending on where the next ARF is.
3653 cpi->frames_till_alt_ref_frame = frames_to_arf;
3655 #if CONFIG_MULTIPLE_ARF
3656 if (!cpi->multi_arf_enabled)
3658 cpi->source_alt_ref_pending = 0; // Clear Pending altf Ref flag.
3663 #if CONFIG_MULTIPLE_ARF
3666 if ((cpi->source = vp9_lookahead_pop(cpi->lookahead, flush))) {
3669 #if CONFIG_MULTIPLE_ARF
3670 // Is this frame the ARF overlay.
3671 cpi->is_src_frame_alt_ref = 0;
3672 for (i = 0; i < cpi->arf_buffered; ++i) {
3673 if (cpi->source == cpi->alt_ref_source[i]) {
3674 cpi->is_src_frame_alt_ref = 1;
3675 cpi->refresh_golden_frame = 1;
3680 cpi->is_src_frame_alt_ref = cpi->alt_ref_source
3681 && (cpi->source == cpi->alt_ref_source);
3683 if (cpi->is_src_frame_alt_ref) {
3684 // Current frame is an ARF overlay frame.
3685 #if CONFIG_MULTIPLE_ARF
3686 cpi->alt_ref_source[i] = NULL;
3688 cpi->alt_ref_source = NULL;
3690 // Don't refresh the last buffer for an ARF overlay frame. It will
3691 // become the GF so preserve last as an alternative prediction option.
3692 cpi->refresh_last_frame = 0;
3694 #if CONFIG_MULTIPLE_ARF
3695 ++cpi->next_frame_in_order;
3701 cpi->un_scaled_source = cpi->Source = force_src_buffer ? force_src_buffer
3702 : &cpi->source->img;
3703 *time_stamp = cpi->source->ts_start;
3704 *time_end = cpi->source->ts_end;
3705 *frame_flags = cpi->source->flags;
3707 // fprintf(fp_out, " Frame:%d", cm->current_video_frame);
3708 #if CONFIG_MULTIPLE_ARF
3709 if (cpi->multi_arf_enabled) {
3710 // fprintf(fp_out, " seq_no:%d this_frame_weight:%d",
3711 // cpi->sequence_number, cpi->this_frame_weight);
3713 // fprintf(fp_out, "\n");
3716 // fprintf(fp_out, "\n");
3719 #if CONFIG_MULTIPLE_ARF
3720 if ((cm->frame_type != KEY_FRAME) && (cpi->pass == 2))
3721 cpi->source_alt_ref_pending = is_next_frame_arf(cpi);
3725 if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done) {
3726 vp9_end_first_pass(cpi); /* get last stats packet */
3727 cpi->twopass.first_pass_done = 1;
3734 if (cpi->source->ts_start < cpi->first_time_stamp_ever) {
3735 cpi->first_time_stamp_ever = cpi->source->ts_start;
3736 cpi->last_end_time_stamp_seen = cpi->source->ts_start;
3739 // adjust frame rates based on timestamps given
3740 if (!cpi->refresh_alt_ref_frame) {
3741 int64_t this_duration;
3744 if (cpi->source->ts_start == cpi->first_time_stamp_ever) {
3745 this_duration = cpi->source->ts_end - cpi->source->ts_start;
3748 int64_t last_duration = cpi->last_end_time_stamp_seen
3749 - cpi->last_time_stamp_seen;
3751 this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
3753 // do a step update if the duration changes by 10%
3755 step = (int)((this_duration - last_duration) * 10 / last_duration);
3758 if (this_duration) {
3760 vp9_new_framerate(cpi, 10000000.0 / this_duration);
3762 // Average this frame's rate into the last second's average
3763 // frame rate. If we haven't seen 1 second yet, then average
3764 // over the whole interval seen.
3765 const double interval = MIN((double)(cpi->source->ts_end
3766 - cpi->first_time_stamp_ever), 10000000.0);
3767 double avg_duration = 10000000.0 / cpi->oxcf.framerate;
3768 avg_duration *= (interval - avg_duration + this_duration);
3769 avg_duration /= interval;
3771 vp9_new_framerate(cpi, 10000000.0 / avg_duration);
3775 cpi->last_time_stamp_seen = cpi->source->ts_start;
3776 cpi->last_end_time_stamp_seen = cpi->source->ts_end;
3779 // start with a 0 size frame
3782 // Clear down mmx registers
3783 vp9_clear_system_state(); // __asm emms;
3785 /* find a free buffer for the new frame, releasing the reference previously
3788 cm->fb_idx_ref_cnt[cm->new_fb_idx]--;
3789 cm->new_fb_idx = get_free_fb(cm);
3791 #if CONFIG_MULTIPLE_ARF
3792 /* Set up the correct ARF frame. */
3793 if (cpi->refresh_alt_ref_frame) {
3794 ++cpi->arf_buffered;
3796 if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
3798 cpi->alt_fb_idx = cpi->arf_buffer_idx[cpi->sequence_number];
3802 /* Get the mapping of L/G/A to the reference buffer pool */
3803 cm->active_ref_idx[0] = cm->ref_frame_map[cpi->lst_fb_idx];
3804 cm->active_ref_idx[1] = cm->ref_frame_map[cpi->gld_fb_idx];
3805 cm->active_ref_idx[2] = cm->ref_frame_map[cpi->alt_fb_idx];
3807 #if 0 // CONFIG_MULTIPLE_ARF
3808 if (cpi->multi_arf_enabled) {
3809 fprintf(fp_out, " idx(%d, %d, %d, %d) active(%d, %d, %d)",
3810 cpi->lst_fb_idx, cpi->gld_fb_idx, cpi->alt_fb_idx, cm->new_fb_idx,
3811 cm->active_ref_idx[0], cm->active_ref_idx[1], cm->active_ref_idx[2]);
3812 if (cpi->refresh_alt_ref_frame)
3813 fprintf(fp_out, " type:ARF");
3814 if (cpi->is_src_frame_alt_ref)
3815 fprintf(fp_out, " type:OVERLAY[%d]", cpi->alt_fb_idx);
3816 fprintf(fp_out, "\n");
3820 cm->frame_type = INTER_FRAME;
3821 cm->frame_flags = *frame_flags;
3823 // Reset the frame pointers to the current frame size
3824 vp9_realloc_frame_buffer(&cm->yv12_fb[cm->new_fb_idx],
3825 cm->width, cm->height,
3826 cm->subsampling_x, cm->subsampling_y,
3829 // Calculate scaling factors for each of the 3 available references
3830 for (i = 0; i < ALLOWED_REFS_PER_FRAME; ++i)
3831 vp9_setup_scale_factors(cm, i);
3833 vp9_setup_interp_filters(&cpi->mb.e_mbd, DEFAULT_INTERP_FILTER, cm);
3835 if (cpi->pass == 1) {
3836 Pass1Encode(cpi, size, dest, frame_flags);
3837 } else if (cpi->pass == 2) {
3838 Pass2Encode(cpi, size, dest, frame_flags);
3840 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3843 if (cm->refresh_frame_context)
3844 cm->frame_contexts[cm->frame_context_idx] = cm->fc;
3847 // if its a dropped frame honor the requests on subsequent frames
3848 cpi->droppable = !frame_is_reference(cpi);
3850 // return to normal state
3851 cm->reset_frame_context = 0;
3852 cm->refresh_frame_context = 1;
3853 cpi->refresh_alt_ref_frame = 0;
3854 cpi->refresh_golden_frame = 0;
3855 cpi->refresh_last_frame = 1;
3856 cm->frame_type = INTER_FRAME;
3859 vpx_usec_timer_mark(&cmptimer);
3860 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
3862 if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
3863 generate_psnr_packet(cpi);
3865 #if CONFIG_INTERNAL_STATS
3867 if (cpi->pass != 1) {
3868 cpi->bytes += *size;
3870 if (cm->show_frame) {
3874 if (cpi->b_calculate_psnr) {
3877 YV12_BUFFER_CONFIG *orig = cpi->Source;
3878 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
3879 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
3880 int y_samples = orig->y_height * orig->y_width;
3881 int uv_samples = orig->uv_height * orig->uv_width;
3882 int t_samples = y_samples + 2 * uv_samples;
3885 ye = (double)calc_plane_error(orig->y_buffer, orig->y_stride,
3886 recon->y_buffer, recon->y_stride,
3887 orig->y_crop_width, orig->y_crop_height);
3889 ue = (double)calc_plane_error(orig->u_buffer, orig->uv_stride,
3890 recon->u_buffer, recon->uv_stride,
3891 orig->uv_crop_width, orig->uv_crop_height);
3893 ve = (double)calc_plane_error(orig->v_buffer, orig->uv_stride,
3894 recon->v_buffer, recon->uv_stride,
3895 orig->uv_crop_width, orig->uv_crop_height);
3897 sq_error = ye + ue + ve;
3899 frame_psnr = vp9_mse2psnr(t_samples, 255.0, sq_error);
3901 cpi->total_y += vp9_mse2psnr(y_samples, 255.0, ye);
3902 cpi->total_u += vp9_mse2psnr(uv_samples, 255.0, ue);
3903 cpi->total_v += vp9_mse2psnr(uv_samples, 255.0, ve);
3904 cpi->total_sq_error += sq_error;
3905 cpi->total += frame_psnr;
3907 double frame_psnr2, frame_ssim2 = 0;
3909 #if CONFIG_VP9_POSTPROC
3910 vp9_deblock(cm->frame_to_show, &cm->post_proc_buffer,
3911 cm->lf.filter_level * 10 / 6);
3913 vp9_clear_system_state();
3915 ye = (double)calc_plane_error(orig->y_buffer, orig->y_stride,
3916 pp->y_buffer, pp->y_stride,
3917 orig->y_crop_width, orig->y_crop_height);
3919 ue = (double)calc_plane_error(orig->u_buffer, orig->uv_stride,
3920 pp->u_buffer, pp->uv_stride,
3921 orig->uv_crop_width, orig->uv_crop_height);
3923 ve = (double)calc_plane_error(orig->v_buffer, orig->uv_stride,
3924 pp->v_buffer, pp->uv_stride,
3925 orig->uv_crop_width, orig->uv_crop_height);
3927 sq_error = ye + ue + ve;
3929 frame_psnr2 = vp9_mse2psnr(t_samples, 255.0, sq_error);
3931 cpi->totalp_y += vp9_mse2psnr(y_samples, 255.0, ye);
3932 cpi->totalp_u += vp9_mse2psnr(uv_samples, 255.0, ue);
3933 cpi->totalp_v += vp9_mse2psnr(uv_samples, 255.0, ve);
3934 cpi->total_sq_error2 += sq_error;
3935 cpi->totalp += frame_psnr2;
3937 frame_ssim2 = vp9_calc_ssim(cpi->Source,
3940 cpi->summed_quality += frame_ssim2 * weight;
3941 cpi->summed_weights += weight;
3943 frame_ssim2 = vp9_calc_ssim(cpi->Source,
3944 &cm->post_proc_buffer, 1, &weight);
3946 cpi->summedp_quality += frame_ssim2 * weight;
3947 cpi->summedp_weights += weight;
3950 FILE *f = fopen("q_used.stt", "a");
3951 fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
3952 cpi->common.current_video_frame, y2, u2, v2,
3953 frame_psnr2, frame_ssim2);
3960 if (cpi->b_calculate_ssimg) {
3961 double y, u, v, frame_all;
3962 frame_all = vp9_calc_ssimg(cpi->Source, cm->frame_to_show,
3964 cpi->total_ssimg_y += y;
3965 cpi->total_ssimg_u += u;
3966 cpi->total_ssimg_v += v;
3967 cpi->total_ssimg_all += frame_all;
3977 int vp9_get_preview_raw_frame(VP9_PTR comp, YV12_BUFFER_CONFIG *dest,
3978 vp9_ppflags_t *flags) {
3979 VP9_COMP *cpi = (VP9_COMP *) comp;
3981 if (!cpi->common.show_frame)
3985 #if CONFIG_VP9_POSTPROC
3986 ret = vp9_post_proc_frame(&cpi->common, dest, flags);
3989 if (cpi->common.frame_to_show) {
3990 *dest = *cpi->common.frame_to_show;
3991 dest->y_width = cpi->common.width;
3992 dest->y_height = cpi->common.height;
3993 dest->uv_height = cpi->common.height / 2;
3999 #endif // !CONFIG_VP9_POSTPROC
4000 vp9_clear_system_state();
4005 int vp9_set_roimap(VP9_PTR comp, unsigned char *map, unsigned int rows,
4006 unsigned int cols, int delta_q[MAX_SEGMENTS],
4007 int delta_lf[MAX_SEGMENTS],
4008 unsigned int threshold[MAX_SEGMENTS]) {
4009 VP9_COMP *cpi = (VP9_COMP *) comp;
4010 signed char feature_data[SEG_LVL_MAX][MAX_SEGMENTS];
4011 struct segmentation *seg = &cpi->common.seg;
4014 if (cpi->common.mb_rows != rows || cpi->common.mb_cols != cols)
4018 vp9_disable_segmentation((VP9_PTR)cpi);
4022 // Set the segmentation Map
4023 vp9_set_segmentation_map((VP9_PTR)cpi, map);
4025 // Activate segmentation.
4026 vp9_enable_segmentation((VP9_PTR)cpi);
4028 // Set up the quant, LF and breakout threshold segment data
4029 for (i = 0; i < MAX_SEGMENTS; i++) {
4030 feature_data[SEG_LVL_ALT_Q][i] = delta_q[i];
4031 feature_data[SEG_LVL_ALT_LF][i] = delta_lf[i];
4032 cpi->segment_encode_breakout[i] = threshold[i];
4035 // Enable the loop and quant changes in the feature mask
4036 for (i = 0; i < MAX_SEGMENTS; i++) {
4038 vp9_enable_segfeature(seg, i, SEG_LVL_ALT_Q);
4040 vp9_disable_segfeature(seg, i, SEG_LVL_ALT_Q);
4043 vp9_enable_segfeature(seg, i, SEG_LVL_ALT_LF);
4045 vp9_disable_segfeature(seg, i, SEG_LVL_ALT_LF);
4048 // Initialize the feature data structure
4049 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
4050 vp9_set_segment_data((VP9_PTR)cpi, &feature_data[0][0], SEGMENT_DELTADATA);
4055 int vp9_set_active_map(VP9_PTR comp, unsigned char *map,
4056 unsigned int rows, unsigned int cols) {
4057 VP9_COMP *cpi = (VP9_COMP *) comp;
4059 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
4061 vpx_memcpy(cpi->active_map, map, rows * cols);
4062 cpi->active_map_enabled = 1;
4064 cpi->active_map_enabled = 0;
4069 // cpi->active_map_enabled = 0;
4074 int vp9_set_internal_size(VP9_PTR comp,
4075 VPX_SCALING horiz_mode, VPX_SCALING vert_mode) {
4076 VP9_COMP *cpi = (VP9_COMP *) comp;
4077 VP9_COMMON *cm = &cpi->common;
4078 int hr = 0, hs = 0, vr = 0, vs = 0;
4080 if (horiz_mode > ONETWO || vert_mode > ONETWO)
4083 Scale2Ratio(horiz_mode, &hr, &hs);
4084 Scale2Ratio(vert_mode, &vr, &vs);
4086 // always go to the next whole number
4087 cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
4088 cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
4090 assert(cm->width <= cpi->initial_width);
4091 assert(cm->height <= cpi->initial_height);
4092 update_frame_size(cpi);
4096 int vp9_set_size_literal(VP9_PTR comp, unsigned int width,
4097 unsigned int height) {
4098 VP9_COMP *cpi = (VP9_COMP *)comp;
4099 VP9_COMMON *cm = &cpi->common;
4101 check_initial_width(cpi, NULL);
4105 if (cm->width * 5 < cpi->initial_width) {
4106 cm->width = cpi->initial_width / 5 + 1;
4107 printf("Warning: Desired width too small, changed to %d \n", cm->width);
4109 if (cm->width > cpi->initial_width) {
4110 cm->width = cpi->initial_width;
4111 printf("Warning: Desired width too large, changed to %d \n", cm->width);
4116 cm->height = height;
4117 if (cm->height * 5 < cpi->initial_height) {
4118 cm->height = cpi->initial_height / 5 + 1;
4119 printf("Warning: Desired height too small, changed to %d \n", cm->height);
4121 if (cm->height > cpi->initial_height) {
4122 cm->height = cpi->initial_height;
4123 printf("Warning: Desired height too large, changed to %d \n", cm->height);
4127 assert(cm->width <= cpi->initial_width);
4128 assert(cm->height <= cpi->initial_height);
4129 update_frame_size(cpi);
4133 int vp9_switch_layer(VP9_PTR comp, int layer) {
4134 VP9_COMP *cpi = (VP9_COMP *)comp;
4137 cpi->current_layer = layer;
4139 // Use buffer i for layer i LST
4140 cpi->lst_fb_idx = layer;
4142 // Use buffer i-1 for layer i Alt (Inter-layer prediction)
4143 if (layer != 0) cpi->alt_fb_idx = layer - 1;
4145 // Use the rest for Golden
4146 if (layer < 2 * cpi->number_spatial_layers - NUM_REF_FRAMES)
4147 cpi->gld_fb_idx = cpi->lst_fb_idx;
4149 cpi->gld_fb_idx = 2 * cpi->number_spatial_layers - 1 - layer;
4151 printf("Switching to layer %d:\n", layer);
4152 printf("Using references: LST/GLD/ALT [%d|%d|%d]\n", cpi->lst_fb_idx,
4153 cpi->gld_fb_idx, cpi->alt_fb_idx);
4155 printf("Switching layer not supported. Enable SVC first \n");
4160 void vp9_set_svc(VP9_PTR comp, int use_svc) {
4161 VP9_COMP *cpi = (VP9_COMP *)comp;
4162 cpi->use_svc = use_svc;
4163 if (cpi->use_svc) printf("Enabled SVC encoder \n");
4167 int vp9_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest) {
4171 uint8_t *src = source->y_buffer;
4172 uint8_t *dst = dest->y_buffer;
4174 // Loop through the Y plane raw and reconstruction data summing
4175 // (square differences)
4176 for (i = 0; i < source->y_height; i += 16) {
4177 for (j = 0; j < source->y_width; j += 16) {
4179 total += vp9_mse16x16(src + j, source->y_stride, dst + j, dest->y_stride,
4183 src += 16 * source->y_stride;
4184 dst += 16 * dest->y_stride;
4191 int vp9_get_quantizer(VP9_PTR c) {
4192 return ((VP9_COMP *)c)->common.base_qindex;