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->auto_min_max_partition_interval = 0;
711 sf->auto_min_max_partition_count = 0;
712 sf->max_partition_size = BLOCK_64X64;
713 sf->min_partition_size = BLOCK_4X4;
714 sf->adjust_partitioning_from_last_frame = 0;
715 sf->last_partitioning_redo_frequency = 4;
716 sf->disable_splitmv = 0;
717 sf->mode_search_skip_flags = 0;
718 sf->disable_split_var_thresh = 0;
719 sf->disable_filter_search_var_thresh = 0;
720 sf->intra_y_mode_mask = ALL_INTRA_MODES;
721 sf->intra_uv_mode_mask = ALL_INTRA_MODES;
722 sf->use_rd_breakout = 0;
723 sf->skip_encode_sb = 0;
724 sf->use_uv_intra_rd_estimate = 0;
725 sf->use_fast_lpf_pick = 0;
726 sf->use_fast_coef_updates = 0;
727 sf->using_small_partition_info = 0;
728 sf->mode_skip_start = MAX_MODES; // Mode index at which mode skip mask set
730 #if CONFIG_MULTIPLE_ARF
731 // Switch segmentation off.
732 sf->static_segmentation = 0;
734 sf->static_segmentation = 0;
738 case 0: // best quality mode
742 #if CONFIG_MULTIPLE_ARF
743 // Switch segmentation off.
744 sf->static_segmentation = 0;
746 sf->static_segmentation = 0;
748 sf->use_avoid_tested_higherror = 1;
749 sf->adaptive_rd_thresh = MIN((speed + 1), 4);
752 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
753 sf->less_rectangular_check = 1;
754 sf->tx_size_search_method = ((cpi->common.frame_type == KEY_FRAME ||
755 cpi->common.intra_only ||
756 cpi->common.show_frame == 0) ?
759 sf->use_square_partition_only = !(cpi->common.frame_type == KEY_FRAME ||
760 cpi->common.intra_only ||
761 cpi->common.show_frame == 0);
762 sf->disable_splitmv =
763 (MIN(cpi->common.width, cpi->common.height) >= 720)? 1 : 0;
764 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
765 FLAG_SKIP_INTRA_BESTINTER |
766 FLAG_SKIP_COMP_BESTINTRA |
767 FLAG_SKIP_INTRA_LOWVAR;
768 sf->use_uv_intra_rd_estimate = 1;
769 sf->use_rd_breakout = 1;
770 sf->skip_encode_sb = 1;
771 sf->use_lp32x32fdct = 1;
772 sf->adaptive_motion_search = 1;
773 sf->auto_mv_step_size = 1;
775 sf->auto_min_max_partition_size = 1;
776 sf->auto_min_max_partition_interval = 1;
777 // FIXME(jingning): temporarily turn off disable_split_var_thresh
778 // during refactoring process. will get this back after finishing
779 // the main framework of partition search type.
780 sf->disable_split_var_thresh = 0;
781 sf->disable_filter_search_var_thresh = 16;
783 sf->intra_y_mode_mask = INTRA_DC_TM_H_V;
784 sf->intra_uv_mode_mask = INTRA_DC_TM_H_V;
785 sf->use_fast_coef_updates = 1;
786 sf->mode_skip_start = 11;
789 sf->less_rectangular_check = 1;
790 sf->use_square_partition_only = 1;
791 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
792 sf->use_lastframe_partitioning = 1;
793 sf->adjust_partitioning_from_last_frame = 1;
794 sf->last_partitioning_redo_frequency = 3;
795 sf->tx_size_search_method = ((cpi->common.frame_type == KEY_FRAME ||
796 cpi->common.intra_only ||
797 cpi->common.show_frame == 0) ?
800 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
801 FLAG_SKIP_INTRA_BESTINTER |
802 FLAG_SKIP_COMP_BESTINTRA |
803 FLAG_SKIP_COMP_REFMISMATCH |
804 FLAG_SKIP_INTRA_LOWVAR |
805 FLAG_EARLY_TERMINATE;
806 sf->intra_y_mode_mask = INTRA_DC_TM;
807 sf->intra_uv_mode_mask = INTRA_DC_TM;
808 sf->use_uv_intra_rd_estimate = 1;
809 sf->use_rd_breakout = 1;
810 sf->skip_encode_sb = 1;
811 sf->use_lp32x32fdct = 1;
812 sf->adaptive_motion_search = 1;
813 sf->using_small_partition_info = 0;
814 sf->disable_splitmv =
815 (MIN(cpi->common.width, cpi->common.height) >= 720)? 1 : 0;
816 sf->auto_mv_step_size = 1;
817 sf->search_method = SQUARE;
818 sf->subpel_iters_per_step = 1;
819 sf->use_fast_lpf_pick = 1;
820 sf->auto_min_max_partition_size = 1;
821 sf->auto_min_max_partition_interval = 2;
822 sf->disable_split_var_thresh = 32;
823 sf->disable_filter_search_var_thresh = 32;
824 sf->use_fast_coef_updates = 2;
825 sf->mode_skip_start = 6;
828 sf->less_rectangular_check = 1;
829 sf->use_square_partition_only = 1;
830 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
831 sf->use_lastframe_partitioning = 1;
832 sf->adjust_partitioning_from_last_frame = 1;
833 sf->last_partitioning_redo_frequency = 3;
834 sf->tx_size_search_method = ((cpi->common.frame_type == KEY_FRAME ||
835 cpi->common.intra_only ||
836 cpi->common.show_frame == 0) ?
839 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
840 FLAG_SKIP_INTRA_BESTINTER |
841 FLAG_SKIP_COMP_BESTINTRA |
842 FLAG_SKIP_COMP_REFMISMATCH |
843 FLAG_SKIP_INTRA_LOWVAR |
844 FLAG_EARLY_TERMINATE;
845 sf->intra_y_mode_mask = INTRA_DC_ONLY;
846 sf->intra_uv_mode_mask = INTRA_DC_ONLY;
847 sf->use_uv_intra_rd_estimate = 1;
848 sf->use_rd_breakout = 1;
849 sf->skip_encode_sb = 1;
850 sf->use_lp32x32fdct = 1;
851 sf->adaptive_motion_search = 1;
852 sf->using_small_partition_info = 0;
853 sf->disable_splitmv = 1;
854 sf->auto_mv_step_size = 1;
855 sf->search_method = BIGDIA;
856 sf->subpel_iters_per_step = 1;
857 sf->use_fast_lpf_pick = 1;
858 sf->auto_min_max_partition_size = 1;
859 sf->auto_min_max_partition_interval = 2;
860 sf->disable_split_var_thresh = 64;
861 sf->disable_filter_search_var_thresh = 64;
862 sf->use_fast_coef_updates = 2;
863 sf->mode_skip_start = 6;
866 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
867 sf->use_one_partition_size_always = 1;
868 sf->always_this_block_size = BLOCK_16X16;
869 sf->tx_size_search_method = ((cpi->common.frame_type == KEY_FRAME ||
870 cpi->common.intra_only ||
871 cpi->common.show_frame == 0) ?
874 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
875 FLAG_SKIP_INTRA_BESTINTER |
876 FLAG_SKIP_COMP_BESTINTRA |
877 FLAG_SKIP_COMP_REFMISMATCH |
878 FLAG_SKIP_INTRA_LOWVAR |
879 FLAG_EARLY_TERMINATE;
880 sf->use_rd_breakout = 1;
881 sf->use_lp32x32fdct = 1;
882 sf->optimize_coefficients = 0;
883 sf->auto_mv_step_size = 1;
884 // sf->reduce_first_step_size = 1;
885 // sf->reference_masking = 1;
887 sf->disable_splitmv = 1;
888 sf->search_method = HEX;
889 sf->subpel_iters_per_step = 1;
890 sf->disable_split_var_thresh = 64;
891 sf->disable_filter_search_var_thresh = 96;
892 sf->intra_y_mode_mask = INTRA_DC_ONLY;
893 sf->intra_uv_mode_mask = INTRA_DC_ONLY;
894 sf->use_fast_coef_updates = 2;
895 sf->mode_skip_start = 6;
901 // Set rd thresholds based on mode and speed setting
902 set_rd_speed_thresholds(cpi, mode);
904 // Slow quant, dct and trellis not worthwhile for first pass
905 // so make sure they are always turned off.
906 if (cpi->pass == 1) {
907 sf->optimize_coefficients = 0;
910 cpi->mb.fwd_txm16x16 = vp9_short_fdct16x16;
911 cpi->mb.fwd_txm8x8 = vp9_short_fdct8x8;
912 cpi->mb.fwd_txm8x4 = vp9_short_fdct8x4;
913 cpi->mb.fwd_txm4x4 = vp9_short_fdct4x4;
914 if (cpi->oxcf.lossless || cpi->mb.e_mbd.lossless) {
915 cpi->mb.fwd_txm8x4 = vp9_short_walsh8x4;
916 cpi->mb.fwd_txm4x4 = vp9_short_walsh4x4;
919 cpi->mb.quantize_b_4x4 = vp9_regular_quantize_b_4x4;
921 if (cpi->sf.subpel_search_method == SUBPEL_ITERATIVE) {
922 cpi->find_fractional_mv_step = vp9_find_best_sub_pixel_iterative;
923 cpi->find_fractional_mv_step_comp = vp9_find_best_sub_pixel_comp_iterative;
924 } else if (cpi->sf.subpel_search_method == SUBPEL_TREE) {
925 cpi->find_fractional_mv_step = vp9_find_best_sub_pixel_tree;
926 cpi->find_fractional_mv_step_comp = vp9_find_best_sub_pixel_comp_tree;
929 cpi->mb.optimize = cpi->sf.optimize_coefficients == 1 && cpi->pass != 1;
932 frames_at_speed[cpi->speed]++;
936 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
937 VP9_COMMON *cm = &cpi->common;
939 cpi->lookahead = vp9_lookahead_init(cpi->oxcf.width, cpi->oxcf.height,
940 cm->subsampling_x, cm->subsampling_y,
941 cpi->oxcf.lag_in_frames);
943 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
944 "Failed to allocate lag buffers");
946 if (vp9_realloc_frame_buffer(&cpi->alt_ref_buffer,
947 cpi->oxcf.width, cpi->oxcf.height,
948 cm->subsampling_x, cm->subsampling_y,
950 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
951 "Failed to allocate altref buffer");
954 static int alloc_partition_data(VP9_COMP *cpi) {
955 vpx_free(cpi->mb.pip);
957 cpi->mb.pip = vpx_calloc(cpi->common.mode_info_stride *
958 (cpi->common.mi_rows + MI_BLOCK_SIZE),
959 sizeof(PARTITION_INFO));
963 cpi->mb.pi = cpi->mb.pip + cpi->common.mode_info_stride + 1;
968 void vp9_alloc_compressor_data(VP9_COMP *cpi) {
969 VP9_COMMON *cm = &cpi->common;
971 if (vp9_alloc_frame_buffers(cm, cm->width, cm->height))
972 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
973 "Failed to allocate frame buffers");
975 if (alloc_partition_data(cpi))
976 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
977 "Failed to allocate partition data");
979 if (vp9_alloc_frame_buffer(&cpi->last_frame_uf,
980 cm->width, cm->height,
981 cm->subsampling_x, cm->subsampling_y,
983 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
984 "Failed to allocate last frame buffer");
986 if (vp9_alloc_frame_buffer(&cpi->scaled_source,
987 cm->width, cm->height,
988 cm->subsampling_x, cm->subsampling_y,
990 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
991 "Failed to allocate scaled source buffer");
996 unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
998 CHECK_MEM_ERROR(cm, cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
1001 // Data used for real time vc mode to see if gf needs refreshing
1002 cpi->inter_zz_count = 0;
1003 cpi->gf_bad_count = 0;
1004 cpi->gf_update_recommended = 0;
1006 vpx_free(cpi->mb_activity_map);
1007 CHECK_MEM_ERROR(cm, cpi->mb_activity_map,
1008 vpx_calloc(sizeof(unsigned int),
1009 cm->mb_rows * cm->mb_cols));
1011 vpx_free(cpi->mb_norm_activity_map);
1012 CHECK_MEM_ERROR(cm, cpi->mb_norm_activity_map,
1013 vpx_calloc(sizeof(unsigned int),
1014 cm->mb_rows * cm->mb_cols));
1018 static void update_frame_size(VP9_COMP *cpi) {
1019 VP9_COMMON *cm = &cpi->common;
1021 vp9_update_frame_size(cm);
1023 // Update size of buffers local to this frame
1024 if (vp9_realloc_frame_buffer(&cpi->last_frame_uf,
1025 cm->width, cm->height,
1026 cm->subsampling_x, cm->subsampling_y,
1028 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1029 "Failed to reallocate last frame buffer");
1031 if (vp9_realloc_frame_buffer(&cpi->scaled_source,
1032 cm->width, cm->height,
1033 cm->subsampling_x, cm->subsampling_y,
1035 vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
1036 "Failed to reallocate scaled source buffer");
1039 int y_stride = cpi->scaled_source.y_stride;
1041 if (cpi->sf.search_method == NSTEP) {
1042 vp9_init3smotion_compensation(&cpi->mb, y_stride);
1043 } else if (cpi->sf.search_method == DIAMOND) {
1044 vp9_init_dsmotion_compensation(&cpi->mb, y_stride);
1050 // TODO perhaps change number of steps expose to outside world when setting
1051 // max and min limits. Also this will likely want refining for the extended Q
1054 // Table that converts 0-63 Q range values passed in outside to the Qindex
1055 // range used internally.
1056 static const int q_trans[] = {
1057 0, 4, 8, 12, 16, 20, 24, 28,
1058 32, 36, 40, 44, 48, 52, 56, 60,
1059 64, 68, 72, 76, 80, 84, 88, 92,
1060 96, 100, 104, 108, 112, 116, 120, 124,
1061 128, 132, 136, 140, 144, 148, 152, 156,
1062 160, 164, 168, 172, 176, 180, 184, 188,
1063 192, 196, 200, 204, 208, 212, 216, 220,
1064 224, 228, 232, 236, 240, 244, 249, 255,
1067 int vp9_reverse_trans(int x) {
1070 for (i = 0; i < 64; i++)
1071 if (q_trans[i] >= x)
1076 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
1077 if (framerate < 0.1)
1080 cpi->oxcf.framerate = framerate;
1081 cpi->output_framerate = cpi->oxcf.framerate;
1082 cpi->per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth / cpi->output_framerate);
1083 cpi->av_per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth / cpi->output_framerate);
1084 cpi->min_frame_bandwidth = (int)(cpi->av_per_frame_bandwidth * cpi->oxcf.two_pass_vbrmin_section / 100);
1087 cpi->min_frame_bandwidth = MAX(cpi->min_frame_bandwidth, FRAME_OVERHEAD_BITS);
1089 // Set Maximum gf/arf interval
1090 cpi->max_gf_interval = 16;
1092 // Extended interval for genuinely static scenes
1093 cpi->twopass.static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
1095 // Special conditions when alt ref frame enabled in lagged compress mode
1096 if (cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames) {
1097 if (cpi->max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1098 cpi->max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1100 if (cpi->twopass.static_scene_max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1101 cpi->twopass.static_scene_max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1104 if (cpi->max_gf_interval > cpi->twopass.static_scene_max_gf_interval)
1105 cpi->max_gf_interval = cpi->twopass.static_scene_max_gf_interval;
1108 static int64_t rescale(int val, int64_t num, int denom) {
1109 int64_t llnum = num;
1110 int64_t llden = denom;
1111 int64_t llval = val;
1113 return (llval * llnum / llden);
1116 static void set_tile_limits(VP9_COMP *cpi) {
1117 VP9_COMMON *const cm = &cpi->common;
1119 int min_log2_tile_cols, max_log2_tile_cols;
1120 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1122 cm->log2_tile_cols = clamp(cpi->oxcf.tile_columns,
1123 min_log2_tile_cols, max_log2_tile_cols);
1124 cm->log2_tile_rows = cpi->oxcf.tile_rows;
1127 static void init_config(VP9_PTR ptr, VP9_CONFIG *oxcf) {
1128 VP9_COMP *cpi = (VP9_COMP *)(ptr);
1129 VP9_COMMON *const cm = &cpi->common;
1135 cm->version = oxcf->version;
1137 cm->width = oxcf->width;
1138 cm->height = oxcf->height;
1139 cm->subsampling_x = 0;
1140 cm->subsampling_y = 0;
1141 vp9_alloc_compressor_data(cpi);
1143 // change includes all joint functionality
1144 vp9_change_config(ptr, oxcf);
1146 // Initialize active best and worst q and average q values.
1147 cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
1148 cpi->active_best_quality = cpi->oxcf.best_allowed_q;
1149 cpi->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
1151 // Initialise the starting buffer levels
1152 cpi->buffer_level = cpi->oxcf.starting_buffer_level;
1153 cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
1155 cpi->rolling_target_bits = cpi->av_per_frame_bandwidth;
1156 cpi->rolling_actual_bits = cpi->av_per_frame_bandwidth;
1157 cpi->long_rolling_target_bits = cpi->av_per_frame_bandwidth;
1158 cpi->long_rolling_actual_bits = cpi->av_per_frame_bandwidth;
1160 cpi->total_actual_bits = 0;
1161 cpi->total_target_vs_actual = 0;
1163 cpi->static_mb_pct = 0;
1165 cpi->lst_fb_idx = 0;
1166 cpi->gld_fb_idx = 1;
1167 cpi->alt_fb_idx = 2;
1169 cpi->current_layer = 0;
1172 set_tile_limits(cpi);
1174 cpi->fixed_divide[0] = 0;
1175 for (i = 1; i < 512; i++)
1176 cpi->fixed_divide[i] = 0x80000 / i;
1180 void vp9_change_config(VP9_PTR ptr, VP9_CONFIG *oxcf) {
1181 VP9_COMP *cpi = (VP9_COMP *)(ptr);
1182 VP9_COMMON *const cm = &cpi->common;
1187 if (cm->version != oxcf->version) {
1188 cm->version = oxcf->version;
1193 switch (cpi->oxcf.Mode) {
1194 // Real time and one pass deprecated in test code base
1195 case MODE_FIRSTPASS:
1197 cpi->compressor_speed = 1;
1200 case MODE_SECONDPASS:
1202 cpi->compressor_speed = 1;
1203 cpi->oxcf.cpu_used = clamp(cpi->oxcf.cpu_used, -5, 5);
1206 case MODE_SECONDPASS_BEST:
1208 cpi->compressor_speed = 0;
1212 cpi->oxcf.worst_allowed_q = q_trans[oxcf->worst_allowed_q];
1213 cpi->oxcf.best_allowed_q = q_trans[oxcf->best_allowed_q];
1214 cpi->oxcf.cq_level = q_trans[cpi->oxcf.cq_level];
1216 cpi->oxcf.lossless = oxcf->lossless;
1217 if (cpi->oxcf.lossless) {
1218 cpi->mb.e_mbd.inv_txm4x4_1_add = vp9_short_iwalsh4x4_1_add;
1219 cpi->mb.e_mbd.inv_txm4x4_add = vp9_short_iwalsh4x4_add;
1221 cpi->mb.e_mbd.inv_txm4x4_1_add = vp9_short_idct4x4_1_add;
1222 cpi->mb.e_mbd.inv_txm4x4_add = vp9_short_idct4x4_add;
1225 cpi->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1227 cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
1229 // cpi->use_golden_frame_only = 0;
1230 // cpi->use_last_frame_only = 0;
1231 cpi->refresh_golden_frame = 0;
1232 cpi->refresh_last_frame = 1;
1233 cm->refresh_frame_context = 1;
1234 cm->reset_frame_context = 0;
1237 cpi->mb.e_mbd.allow_high_precision_mv = 0; // Default mv precision adaptation
1238 set_mvcost(&cpi->mb);
1243 for (i = 0; i < MAX_SEGMENTS; i++)
1244 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1247 // At the moment the first order values may not be > MAXQ
1248 cpi->oxcf.fixed_q = MIN(cpi->oxcf.fixed_q, MAXQ);
1250 // local file playback mode == really big buffer
1251 if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK) {
1252 cpi->oxcf.starting_buffer_level = 60000;
1253 cpi->oxcf.optimal_buffer_level = 60000;
1254 cpi->oxcf.maximum_buffer_size = 240000;
1257 // Convert target bandwidth from Kbit/s to Bit/s
1258 cpi->oxcf.target_bandwidth *= 1000;
1260 cpi->oxcf.starting_buffer_level = rescale(cpi->oxcf.starting_buffer_level,
1261 cpi->oxcf.target_bandwidth, 1000);
1263 // Set or reset optimal and maximum buffer levels.
1264 if (cpi->oxcf.optimal_buffer_level == 0)
1265 cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
1267 cpi->oxcf.optimal_buffer_level = rescale(cpi->oxcf.optimal_buffer_level,
1268 cpi->oxcf.target_bandwidth, 1000);
1270 if (cpi->oxcf.maximum_buffer_size == 0)
1271 cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
1273 cpi->oxcf.maximum_buffer_size = rescale(cpi->oxcf.maximum_buffer_size,
1274 cpi->oxcf.target_bandwidth, 1000);
1276 // Set up frame rate and related parameters rate control values.
1277 vp9_new_framerate(cpi, cpi->oxcf.framerate);
1279 // Set absolute upper and lower quality limits
1280 cpi->worst_quality = cpi->oxcf.worst_allowed_q;
1281 cpi->best_quality = cpi->oxcf.best_allowed_q;
1283 // active values should only be modified if out of new range
1284 cpi->active_worst_quality = clamp(cpi->active_worst_quality,
1285 cpi->oxcf.best_allowed_q,
1286 cpi->oxcf.worst_allowed_q);
1288 cpi->active_best_quality = clamp(cpi->active_best_quality,
1289 cpi->oxcf.best_allowed_q,
1290 cpi->oxcf.worst_allowed_q);
1292 cpi->buffered_mode = cpi->oxcf.optimal_buffer_level > 0;
1294 cpi->cq_target_quality = cpi->oxcf.cq_level;
1296 cm->mcomp_filter_type = DEFAULT_INTERP_FILTER;
1298 cpi->target_bandwidth = cpi->oxcf.target_bandwidth;
1300 cm->display_width = cpi->oxcf.width;
1301 cm->display_height = cpi->oxcf.height;
1303 // VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs)
1304 cpi->oxcf.Sharpness = MIN(7, cpi->oxcf.Sharpness);
1306 cpi->common.lf.sharpness_level = cpi->oxcf.Sharpness;
1308 if (cpi->initial_width) {
1309 // Increasing the size of the frame beyond the first seen frame, or some
1310 // otherwise signalled maximum size, is not supported.
1311 // TODO(jkoleszar): exit gracefully.
1312 assert(cm->width <= cpi->initial_width);
1313 assert(cm->height <= cpi->initial_height);
1315 update_frame_size(cpi);
1317 if (cpi->oxcf.fixed_q >= 0) {
1318 cpi->last_q[0] = cpi->oxcf.fixed_q;
1319 cpi->last_q[1] = cpi->oxcf.fixed_q;
1320 cpi->last_boosted_qindex = cpi->oxcf.fixed_q;
1323 cpi->speed = cpi->oxcf.cpu_used;
1325 if (cpi->oxcf.lag_in_frames == 0) {
1326 // force to allowlag to 0 if lag_in_frames is 0;
1327 cpi->oxcf.allow_lag = 0;
1328 } else if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS) {
1329 // Limit on lag buffers as these are not currently dynamically allocated
1330 cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
1334 #if CONFIG_MULTIPLE_ARF
1335 vp9_zero(cpi->alt_ref_source);
1337 cpi->alt_ref_source = NULL;
1339 cpi->is_src_frame_alt_ref = 0;
1342 // Experimental RD Code
1343 cpi->frame_distortion = 0;
1344 cpi->last_frame_distortion = 0;
1347 set_tile_limits(cpi);
1350 #define M_LOG2_E 0.693147180559945309417
1351 #define log2f(x) (log (x) / (float) M_LOG2_E)
1353 static void cal_nmvjointsadcost(int *mvjointsadcost) {
1354 mvjointsadcost[0] = 600;
1355 mvjointsadcost[1] = 300;
1356 mvjointsadcost[2] = 300;
1357 mvjointsadcost[0] = 300;
1360 static void cal_nmvsadcosts(int *mvsadcost[2]) {
1363 mvsadcost[0][0] = 0;
1364 mvsadcost[1][0] = 0;
1367 double z = 256 * (2 * (log2f(8 * i) + .6));
1368 mvsadcost[0][i] = (int)z;
1369 mvsadcost[1][i] = (int)z;
1370 mvsadcost[0][-i] = (int)z;
1371 mvsadcost[1][-i] = (int)z;
1372 } while (++i <= MV_MAX);
1375 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
1378 mvsadcost[0][0] = 0;
1379 mvsadcost[1][0] = 0;
1382 double z = 256 * (2 * (log2f(8 * i) + .6));
1383 mvsadcost[0][i] = (int)z;
1384 mvsadcost[1][i] = (int)z;
1385 mvsadcost[0][-i] = (int)z;
1386 mvsadcost[1][-i] = (int)z;
1387 } while (++i <= MV_MAX);
1390 VP9_PTR vp9_create_compressor(VP9_CONFIG *oxcf) {
1400 cpi = ctx.cpi = vpx_memalign(32, sizeof(VP9_COMP));
1401 // Check that the CPI instance is valid
1409 if (setjmp(cm->error.jmp)) {
1410 VP9_PTR ptr = ctx.ptr;
1412 ctx.cpi->common.error.setjmp = 0;
1413 vp9_remove_compressor(&ptr);
1417 cm->error.setjmp = 1;
1419 CHECK_MEM_ERROR(cm, cpi->mb.ss, vpx_calloc(sizeof(search_site),
1420 (MAX_MVSEARCH_STEPS * 8) + 1));
1422 vp9_create_common(cm);
1424 init_config((VP9_PTR)cpi, oxcf);
1426 cm->current_video_frame = 0;
1427 cpi->kf_overspend_bits = 0;
1428 cpi->kf_bitrate_adjustment = 0;
1429 cpi->frames_till_gf_update_due = 0;
1430 cpi->gf_overspend_bits = 0;
1431 cpi->non_gf_bitrate_adjustment = 0;
1433 // Set reference frame sign bias for ALTREF frame to 1 (for now)
1434 cm->ref_frame_sign_bias[ALTREF_FRAME] = 1;
1436 cpi->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1438 cpi->gold_is_last = 0;
1439 cpi->alt_is_last = 0;
1440 cpi->gold_is_alt = 0;
1442 // Spatial scalability
1443 cpi->number_spatial_layers = oxcf->ss_number_layers;
1445 // Create the encoder segmentation map and set all entries to 0
1446 CHECK_MEM_ERROR(cm, cpi->segmentation_map,
1447 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1449 // And a place holder structure is the coding context
1450 // for use if we want to save and restore it
1451 CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
1452 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1454 CHECK_MEM_ERROR(cm, cpi->active_map, vpx_calloc(cm->MBs, 1));
1455 vpx_memset(cpi->active_map, 1, cm->MBs);
1456 cpi->active_map_enabled = 0;
1458 for (i = 0; i < (sizeof(cpi->mbgraph_stats) /
1459 sizeof(cpi->mbgraph_stats[0])); i++) {
1460 CHECK_MEM_ERROR(cm, cpi->mbgraph_stats[i].mb_stats,
1461 vpx_calloc(cm->MBs *
1462 sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
1465 #ifdef ENTROPY_STATS
1467 init_context_counters();
1471 init_tx_count_stats();
1472 init_switchable_interp_stats();
1475 /*Initialize the feed-forward activity masking.*/
1476 cpi->activity_avg = 90 << 12;
1478 cpi->frames_since_key = 8; // Give a sensible default for the first frame.
1479 cpi->key_frame_frequency = cpi->oxcf.key_freq;
1480 cpi->this_key_frame_forced = 0;
1481 cpi->next_key_frame_forced = 0;
1483 cpi->source_alt_ref_pending = 0;
1484 cpi->source_alt_ref_active = 0;
1485 cpi->refresh_alt_ref_frame = 0;
1487 #if CONFIG_MULTIPLE_ARF
1488 // Turn multiple ARF usage on/off. This is a quick hack for the initial test
1489 // version. It should eventually be set via the codec API.
1490 cpi->multi_arf_enabled = 1;
1492 if (cpi->multi_arf_enabled) {
1493 cpi->sequence_number = 0;
1494 cpi->frame_coding_order_period = 0;
1495 vp9_zero(cpi->frame_coding_order);
1496 vp9_zero(cpi->arf_buffer_idx);
1500 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1501 #if CONFIG_INTERNAL_STATS
1502 cpi->b_calculate_ssimg = 0;
1507 if (cpi->b_calculate_psnr) {
1508 cpi->total_sq_error = 0.0;
1509 cpi->total_sq_error2 = 0.0;
1514 cpi->totalp_y = 0.0;
1515 cpi->totalp_u = 0.0;
1516 cpi->totalp_v = 0.0;
1518 cpi->tot_recode_hits = 0;
1519 cpi->summed_quality = 0;
1520 cpi->summed_weights = 0;
1521 cpi->summedp_quality = 0;
1522 cpi->summedp_weights = 0;
1525 if (cpi->b_calculate_ssimg) {
1526 cpi->total_ssimg_y = 0;
1527 cpi->total_ssimg_u = 0;
1528 cpi->total_ssimg_v = 0;
1529 cpi->total_ssimg_all = 0;
1534 cpi->first_time_stamp_ever = INT64_MAX;
1536 cpi->frames_till_gf_update_due = 0;
1537 cpi->key_frame_count = 1;
1539 cpi->ni_av_qi = cpi->oxcf.worst_allowed_q;
1543 cpi->avg_q = vp9_convert_qindex_to_q(cpi->oxcf.worst_allowed_q);
1544 cpi->total_byte_count = 0;
1546 cpi->rate_correction_factor = 1.0;
1547 cpi->key_frame_rate_correction_factor = 1.0;
1548 cpi->gf_rate_correction_factor = 1.0;
1549 cpi->twopass.est_max_qcorrection_factor = 1.0;
1551 cal_nmvjointsadcost(cpi->mb.nmvjointsadcost);
1552 cpi->mb.nmvcost[0] = &cpi->mb.nmvcosts[0][MV_MAX];
1553 cpi->mb.nmvcost[1] = &cpi->mb.nmvcosts[1][MV_MAX];
1554 cpi->mb.nmvsadcost[0] = &cpi->mb.nmvsadcosts[0][MV_MAX];
1555 cpi->mb.nmvsadcost[1] = &cpi->mb.nmvsadcosts[1][MV_MAX];
1556 cal_nmvsadcosts(cpi->mb.nmvsadcost);
1558 cpi->mb.nmvcost_hp[0] = &cpi->mb.nmvcosts_hp[0][MV_MAX];
1559 cpi->mb.nmvcost_hp[1] = &cpi->mb.nmvcosts_hp[1][MV_MAX];
1560 cpi->mb.nmvsadcost_hp[0] = &cpi->mb.nmvsadcosts_hp[0][MV_MAX];
1561 cpi->mb.nmvsadcost_hp[1] = &cpi->mb.nmvsadcosts_hp[1][MV_MAX];
1562 cal_nmvsadcosts_hp(cpi->mb.nmvsadcost_hp);
1564 for (i = 0; i < KEY_FRAME_CONTEXT; i++)
1565 cpi->prior_key_frame_distance[i] = (int)cpi->output_framerate;
1567 #ifdef OUTPUT_YUV_SRC
1568 yuv_file = fopen("bd.yuv", "ab");
1570 #ifdef OUTPUT_YUV_REC
1571 yuv_rec_file = fopen("rec.yuv", "wb");
1575 framepsnr = fopen("framepsnr.stt", "a");
1576 kf_list = fopen("kf_list.stt", "w");
1579 cpi->output_pkt_list = oxcf->output_pkt_list;
1581 cpi->enable_encode_breakout = 1;
1583 if (cpi->pass == 1) {
1584 vp9_init_first_pass(cpi);
1585 } else if (cpi->pass == 2) {
1586 size_t packet_sz = sizeof(FIRSTPASS_STATS);
1587 int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
1589 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1590 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1591 cpi->twopass.stats_in_end = (void *)((char *)cpi->twopass.stats_in
1592 + (packets - 1) * packet_sz);
1593 vp9_init_second_pass(cpi);
1596 vp9_set_speed_features(cpi);
1598 // Default rd threshold factors for mode selection
1599 for (i = 0; i < BLOCK_SIZES; ++i)
1600 for (j = 0; j < MAX_MODES; ++j)
1601 cpi->rd_thresh_freq_fact[i][j] = 32;
1603 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SVFHH, SVFHV, SVFHHV, \
1604 SDX3F, SDX8F, SDX4DF)\
1605 cpi->fn_ptr[BT].sdf = SDF; \
1606 cpi->fn_ptr[BT].sdaf = SDAF; \
1607 cpi->fn_ptr[BT].vf = VF; \
1608 cpi->fn_ptr[BT].svf = SVF; \
1609 cpi->fn_ptr[BT].svaf = SVAF; \
1610 cpi->fn_ptr[BT].svf_halfpix_h = SVFHH; \
1611 cpi->fn_ptr[BT].svf_halfpix_v = SVFHV; \
1612 cpi->fn_ptr[BT].svf_halfpix_hv = SVFHHV; \
1613 cpi->fn_ptr[BT].sdx3f = SDX3F; \
1614 cpi->fn_ptr[BT].sdx8f = SDX8F; \
1615 cpi->fn_ptr[BT].sdx4df = SDX4DF;
1617 BFP(BLOCK_32X16, vp9_sad32x16, vp9_sad32x16_avg,
1618 vp9_variance32x16, vp9_sub_pixel_variance32x16,
1619 vp9_sub_pixel_avg_variance32x16, NULL, NULL,
1623 BFP(BLOCK_16X32, vp9_sad16x32, vp9_sad16x32_avg,
1624 vp9_variance16x32, vp9_sub_pixel_variance16x32,
1625 vp9_sub_pixel_avg_variance16x32, NULL, NULL,
1629 BFP(BLOCK_64X32, vp9_sad64x32, vp9_sad64x32_avg,
1630 vp9_variance64x32, vp9_sub_pixel_variance64x32,
1631 vp9_sub_pixel_avg_variance64x32, NULL, NULL,
1635 BFP(BLOCK_32X64, vp9_sad32x64, vp9_sad32x64_avg,
1636 vp9_variance32x64, vp9_sub_pixel_variance32x64,
1637 vp9_sub_pixel_avg_variance32x64, NULL, NULL,
1641 BFP(BLOCK_32X32, vp9_sad32x32, vp9_sad32x32_avg,
1642 vp9_variance32x32, vp9_sub_pixel_variance32x32,
1643 vp9_sub_pixel_avg_variance32x32, vp9_variance_halfpixvar32x32_h,
1644 vp9_variance_halfpixvar32x32_v,
1645 vp9_variance_halfpixvar32x32_hv, vp9_sad32x32x3, vp9_sad32x32x8,
1648 BFP(BLOCK_64X64, vp9_sad64x64, vp9_sad64x64_avg,
1649 vp9_variance64x64, vp9_sub_pixel_variance64x64,
1650 vp9_sub_pixel_avg_variance64x64, vp9_variance_halfpixvar64x64_h,
1651 vp9_variance_halfpixvar64x64_v,
1652 vp9_variance_halfpixvar64x64_hv, vp9_sad64x64x3, vp9_sad64x64x8,
1655 BFP(BLOCK_16X16, vp9_sad16x16, vp9_sad16x16_avg,
1656 vp9_variance16x16, vp9_sub_pixel_variance16x16,
1657 vp9_sub_pixel_avg_variance16x16, vp9_variance_halfpixvar16x16_h,
1658 vp9_variance_halfpixvar16x16_v,
1659 vp9_variance_halfpixvar16x16_hv, vp9_sad16x16x3, vp9_sad16x16x8,
1662 BFP(BLOCK_16X8, vp9_sad16x8, vp9_sad16x8_avg,
1663 vp9_variance16x8, vp9_sub_pixel_variance16x8,
1664 vp9_sub_pixel_avg_variance16x8, NULL, NULL, NULL,
1665 vp9_sad16x8x3, vp9_sad16x8x8, vp9_sad16x8x4d)
1667 BFP(BLOCK_8X16, vp9_sad8x16, vp9_sad8x16_avg,
1668 vp9_variance8x16, vp9_sub_pixel_variance8x16,
1669 vp9_sub_pixel_avg_variance8x16, NULL, NULL, NULL,
1670 vp9_sad8x16x3, vp9_sad8x16x8, vp9_sad8x16x4d)
1672 BFP(BLOCK_8X8, vp9_sad8x8, vp9_sad8x8_avg,
1673 vp9_variance8x8, vp9_sub_pixel_variance8x8,
1674 vp9_sub_pixel_avg_variance8x8, NULL, NULL, NULL,
1675 vp9_sad8x8x3, vp9_sad8x8x8, vp9_sad8x8x4d)
1677 BFP(BLOCK_8X4, vp9_sad8x4, vp9_sad8x4_avg,
1678 vp9_variance8x4, vp9_sub_pixel_variance8x4,
1679 vp9_sub_pixel_avg_variance8x4, NULL, NULL,
1680 NULL, NULL, vp9_sad8x4x8,
1683 BFP(BLOCK_4X8, vp9_sad4x8, vp9_sad4x8_avg,
1684 vp9_variance4x8, vp9_sub_pixel_variance4x8,
1685 vp9_sub_pixel_avg_variance4x8, NULL, NULL,
1686 NULL, NULL, vp9_sad4x8x8,
1689 BFP(BLOCK_4X4, vp9_sad4x4, vp9_sad4x4_avg,
1690 vp9_variance4x4, vp9_sub_pixel_variance4x4,
1691 vp9_sub_pixel_avg_variance4x4, NULL, NULL, NULL,
1692 vp9_sad4x4x3, vp9_sad4x4x8, vp9_sad4x4x4d)
1694 cpi->full_search_sad = vp9_full_search_sad;
1695 cpi->diamond_search_sad = vp9_diamond_search_sad;
1696 cpi->refining_search_sad = vp9_refining_search_sad;
1698 // make sure frame 1 is okay
1699 cpi->error_bins[0] = cpi->common.MBs;
1701 /* vp9_init_quantizer() is first called here. Add check in
1702 * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
1703 * called later when needed. This will avoid unnecessary calls of
1704 * vp9_init_quantizer() for every frame.
1706 vp9_init_quantizer(cpi);
1708 vp9_loop_filter_init(cm);
1710 cpi->common.error.setjmp = 0;
1712 vp9_zero(cpi->y_uv_mode_count)
1714 #ifdef MODE_TEST_HIT_STATS
1715 vp9_zero(cpi->mode_test_hits)
1718 return (VP9_PTR) cpi;
1721 void vp9_remove_compressor(VP9_PTR *ptr) {
1722 VP9_COMP *cpi = (VP9_COMP *)(*ptr);
1728 if (cpi && (cpi->common.current_video_frame > 0)) {
1729 if (cpi->pass == 2) {
1730 vp9_end_second_pass(cpi);
1733 #ifdef ENTROPY_STATS
1734 if (cpi->pass != 1) {
1735 print_context_counters();
1736 print_tree_update_probs();
1737 print_mode_context(cpi);
1742 if (cpi->pass != 1) {
1743 write_tx_count_stats();
1744 write_switchable_interp_stats();
1748 #if CONFIG_INTERNAL_STATS
1750 vp9_clear_system_state();
1752 // printf("\n8x8-4x4:%d-%d\n", cpi->t8x8_count, cpi->t4x4_count);
1753 if (cpi->pass != 1) {
1754 FILE *f = fopen("opsnr.stt", "a");
1755 double time_encoded = (cpi->last_end_time_stamp_seen
1756 - cpi->first_time_stamp_ever) / 10000000.000;
1757 double total_encode_time = (cpi->time_receive_data + cpi->time_compress_data) / 1000.000;
1758 double dr = (double)cpi->bytes * (double) 8 / (double)1000 / time_encoded;
1760 if (cpi->b_calculate_psnr) {
1761 YV12_BUFFER_CONFIG *lst_yv12 =
1762 &cpi->common.yv12_fb[cpi->common.ref_frame_map[cpi->lst_fb_idx]];
1763 double samples = 3.0 / 2 * cpi->count *
1764 lst_yv12->y_width * lst_yv12->y_height;
1765 double total_psnr = vp9_mse2psnr(samples, 255.0, cpi->total_sq_error);
1766 double total_psnr2 = vp9_mse2psnr(samples, 255.0, cpi->total_sq_error2);
1767 double total_ssim = 100 * pow(cpi->summed_quality /
1768 cpi->summed_weights, 8.0);
1769 double total_ssimp = 100 * pow(cpi->summedp_quality /
1770 cpi->summedp_weights, 8.0);
1772 fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
1773 "VPXSSIM\tVPSSIMP\t Time(ms)\n");
1774 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",
1775 dr, cpi->total / cpi->count, total_psnr,
1776 cpi->totalp / cpi->count, total_psnr2, total_ssim, total_ssimp,
1778 // fprintf(f, "%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%8.0f %10ld\n",
1779 // dr, cpi->total / cpi->count, total_psnr,
1780 // cpi->totalp / cpi->count, total_psnr2, total_ssim,
1781 // total_encode_time, cpi->tot_recode_hits);
1784 if (cpi->b_calculate_ssimg) {
1785 fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t Time(ms)\n");
1786 fprintf(f, "%7.2f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
1787 cpi->total_ssimg_y / cpi->count, cpi->total_ssimg_u / cpi->count,
1788 cpi->total_ssimg_v / cpi->count, cpi->total_ssimg_all / cpi->count, total_encode_time);
1789 // fprintf(f, "%7.3f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f %10ld\n", dr,
1790 // cpi->total_ssimg_y / cpi->count, cpi->total_ssimg_u / cpi->count,
1791 // cpi->total_ssimg_v / cpi->count, cpi->total_ssimg_all / cpi->count, total_encode_time, cpi->tot_recode_hits);
1799 #ifdef MODE_TEST_HIT_STATS
1800 if (cpi->pass != 1) {
1801 double norm_per_pixel_mode_tests = 0;
1802 double norm_counts[BLOCK_SIZES];
1805 int norm_factors[BLOCK_SIZES] =
1806 {256, 128, 128, 64, 32, 32, 16, 8, 8, 4, 2, 2, 1};
1807 FILE *f = fopen("mode_hit_stats.stt", "a");
1809 // On average, how many mode tests do we do
1810 for (i = 0; i < BLOCK_SIZES; ++i) {
1811 norm_counts[i] = (double)cpi->mode_test_hits[i] /
1812 (double)norm_factors[i];
1813 norm_per_pixel_mode_tests += norm_counts[i];
1815 // Convert to a number per 64x64 and per frame
1816 sb64_per_frame = ((cpi->common.height + 63) / 64) *
1817 ((cpi->common.width + 63) / 64);
1818 norm_per_pixel_mode_tests =
1819 norm_per_pixel_mode_tests /
1820 (double)(cpi->common.current_video_frame * sb64_per_frame);
1822 fprintf(f, "%6.4f\n", norm_per_pixel_mode_tests);
1827 #ifdef ENTROPY_STATS
1830 FILE *fmode = fopen("vp9_modecontext.c", "w");
1832 fprintf(fmode, "\n#include \"vp9_entropymode.h\"\n\n");
1833 fprintf(fmode, "const unsigned int vp9_kf_default_bmode_counts ");
1834 fprintf(fmode, "[INTRA_MODES][INTRA_MODES]"
1835 "[INTRA_MODES] =\n{\n");
1837 for (i = 0; i < INTRA_MODES; i++) {
1839 fprintf(fmode, " { // Above Mode : %d\n", i);
1841 for (j = 0; j < INTRA_MODES; j++) {
1843 fprintf(fmode, " {");
1845 for (k = 0; k < INTRA_MODES; k++) {
1846 if (!intra_mode_stats[i][j][k])
1847 fprintf(fmode, " %5d, ", 1);
1849 fprintf(fmode, " %5d, ", intra_mode_stats[i][j][k]);
1852 fprintf(fmode, "}, // left_mode %d\n", j);
1856 fprintf(fmode, " },\n");
1860 fprintf(fmode, "};\n");
1866 #if defined(SECTIONBITS_OUTPUT)
1870 FILE *f = fopen("tokenbits.stt", "a");
1872 for (i = 0; i < 28; i++)
1873 fprintf(f, "%8d", (int)(Sectionbits[i] / 256));
1883 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
1884 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
1885 printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
1886 cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
1887 cpi->time_compress_data / 1000,
1888 (cpi->time_receive_data + cpi->time_compress_data) / 1000);
1894 dealloc_compressor_data(cpi);
1895 vpx_free(cpi->mb.ss);
1898 for (i = 0; i < sizeof(cpi->mbgraph_stats) / sizeof(cpi->mbgraph_stats[0]); i++) {
1899 vpx_free(cpi->mbgraph_stats[i].mb_stats);
1902 vp9_remove_common(&cpi->common);
1906 #ifdef OUTPUT_YUV_SRC
1909 #ifdef OUTPUT_YUV_REC
1910 fclose(yuv_rec_file);
1929 static uint64_t calc_plane_error(uint8_t *orig, int orig_stride,
1930 uint8_t *recon, int recon_stride,
1931 unsigned int cols, unsigned int rows) {
1932 unsigned int row, col;
1933 uint64_t total_sse = 0;
1936 for (row = 0; row + 16 <= rows; row += 16) {
1937 for (col = 0; col + 16 <= cols; col += 16) {
1940 vp9_mse16x16(orig + col, orig_stride, recon + col, recon_stride, &sse);
1944 /* Handle odd-sized width */
1946 unsigned int border_row, border_col;
1947 uint8_t *border_orig = orig;
1948 uint8_t *border_recon = recon;
1950 for (border_row = 0; border_row < 16; border_row++) {
1951 for (border_col = col; border_col < cols; border_col++) {
1952 diff = border_orig[border_col] - border_recon[border_col];
1953 total_sse += diff * diff;
1956 border_orig += orig_stride;
1957 border_recon += recon_stride;
1961 orig += orig_stride * 16;
1962 recon += recon_stride * 16;
1965 /* Handle odd-sized height */
1966 for (; row < rows; row++) {
1967 for (col = 0; col < cols; col++) {
1968 diff = orig[col] - recon[col];
1969 total_sse += diff * diff;
1972 orig += orig_stride;
1973 recon += recon_stride;
1980 static void generate_psnr_packet(VP9_COMP *cpi) {
1981 YV12_BUFFER_CONFIG *orig = cpi->Source;
1982 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
1983 struct vpx_codec_cx_pkt pkt;
1986 unsigned int width = orig->y_crop_width;
1987 unsigned int height = orig->y_crop_height;
1989 pkt.kind = VPX_CODEC_PSNR_PKT;
1990 sse = calc_plane_error(orig->y_buffer, orig->y_stride,
1991 recon->y_buffer, recon->y_stride,
1993 pkt.data.psnr.sse[0] = sse;
1994 pkt.data.psnr.sse[1] = sse;
1995 pkt.data.psnr.samples[0] = width * height;
1996 pkt.data.psnr.samples[1] = width * height;
1998 width = orig->uv_crop_width;
1999 height = orig->uv_crop_height;
2001 sse = calc_plane_error(orig->u_buffer, orig->uv_stride,
2002 recon->u_buffer, recon->uv_stride,
2004 pkt.data.psnr.sse[0] += sse;
2005 pkt.data.psnr.sse[2] = sse;
2006 pkt.data.psnr.samples[0] += width * height;
2007 pkt.data.psnr.samples[2] = width * height;
2009 sse = calc_plane_error(orig->v_buffer, orig->uv_stride,
2010 recon->v_buffer, recon->uv_stride,
2012 pkt.data.psnr.sse[0] += sse;
2013 pkt.data.psnr.sse[3] = sse;
2014 pkt.data.psnr.samples[0] += width * height;
2015 pkt.data.psnr.samples[3] = width * height;
2017 for (i = 0; i < 4; i++)
2018 pkt.data.psnr.psnr[i] = vp9_mse2psnr(pkt.data.psnr.samples[i], 255.0,
2019 (double)pkt.data.psnr.sse[i]);
2021 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2025 int vp9_use_as_reference(VP9_PTR ptr, int ref_frame_flags) {
2026 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2028 if (ref_frame_flags > 7)
2031 cpi->ref_frame_flags = ref_frame_flags;
2034 int vp9_update_reference(VP9_PTR ptr, int ref_frame_flags) {
2035 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2037 if (ref_frame_flags > 7)
2040 cpi->refresh_golden_frame = 0;
2041 cpi->refresh_alt_ref_frame = 0;
2042 cpi->refresh_last_frame = 0;
2044 if (ref_frame_flags & VP9_LAST_FLAG)
2045 cpi->refresh_last_frame = 1;
2047 if (ref_frame_flags & VP9_GOLD_FLAG)
2048 cpi->refresh_golden_frame = 1;
2050 if (ref_frame_flags & VP9_ALT_FLAG)
2051 cpi->refresh_alt_ref_frame = 1;
2056 int vp9_copy_reference_enc(VP9_PTR ptr, VP9_REFFRAME ref_frame_flag,
2057 YV12_BUFFER_CONFIG *sd) {
2058 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2059 VP9_COMMON *cm = &cpi->common;
2062 if (ref_frame_flag == VP9_LAST_FLAG)
2063 ref_fb_idx = cm->ref_frame_map[cpi->lst_fb_idx];
2064 else if (ref_frame_flag == VP9_GOLD_FLAG)
2065 ref_fb_idx = cm->ref_frame_map[cpi->gld_fb_idx];
2066 else if (ref_frame_flag == VP9_ALT_FLAG)
2067 ref_fb_idx = cm->ref_frame_map[cpi->alt_fb_idx];
2071 vp8_yv12_copy_frame(&cm->yv12_fb[ref_fb_idx], sd);
2076 int vp9_get_reference_enc(VP9_PTR ptr, int index, YV12_BUFFER_CONFIG **fb) {
2077 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2078 VP9_COMMON *cm = &cpi->common;
2080 if (index < 0 || index >= NUM_REF_FRAMES)
2083 *fb = &cm->yv12_fb[cm->ref_frame_map[index]];
2087 int vp9_set_reference_enc(VP9_PTR ptr, VP9_REFFRAME ref_frame_flag,
2088 YV12_BUFFER_CONFIG *sd) {
2089 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2090 VP9_COMMON *cm = &cpi->common;
2094 if (ref_frame_flag == VP9_LAST_FLAG)
2095 ref_fb_idx = cm->ref_frame_map[cpi->lst_fb_idx];
2096 else if (ref_frame_flag == VP9_GOLD_FLAG)
2097 ref_fb_idx = cm->ref_frame_map[cpi->gld_fb_idx];
2098 else if (ref_frame_flag == VP9_ALT_FLAG)
2099 ref_fb_idx = cm->ref_frame_map[cpi->alt_fb_idx];
2103 vp8_yv12_copy_frame(sd, &cm->yv12_fb[ref_fb_idx]);
2107 int vp9_update_entropy(VP9_PTR comp, int update) {
2108 ((VP9_COMP *)comp)->common.refresh_frame_context = update;
2113 #ifdef OUTPUT_YUV_SRC
2114 void vp9_write_yuv_frame(YV12_BUFFER_CONFIG *s) {
2115 uint8_t *src = s->y_buffer;
2116 int h = s->y_height;
2119 fwrite(src, s->y_width, 1, yuv_file);
2127 fwrite(src, s->uv_width, 1, yuv_file);
2128 src += s->uv_stride;
2135 fwrite(src, s->uv_width, 1, yuv_file);
2136 src += s->uv_stride;
2141 #ifdef OUTPUT_YUV_REC
2142 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
2143 YV12_BUFFER_CONFIG *s = cm->frame_to_show;
2144 uint8_t *src = s->y_buffer;
2148 fwrite(src, s->y_width, 1, yuv_rec_file);
2156 fwrite(src, s->uv_width, 1, yuv_rec_file);
2157 src += s->uv_stride;
2164 fwrite(src, s->uv_width, 1, yuv_rec_file);
2165 src += s->uv_stride;
2169 if (s->alpha_buffer) {
2170 src = s->alpha_buffer;
2171 h = s->alpha_height;
2173 fwrite(src, s->alpha_width, 1, yuv_rec_file);
2174 src += s->alpha_stride;
2179 fflush(yuv_rec_file);
2183 static void scale_and_extend_frame(YV12_BUFFER_CONFIG *src_fb,
2184 YV12_BUFFER_CONFIG *dst_fb) {
2185 const int in_w = src_fb->y_crop_width;
2186 const int in_h = src_fb->y_crop_height;
2187 const int out_w = dst_fb->y_crop_width;
2188 const int out_h = dst_fb->y_crop_height;
2191 uint8_t *srcs[4] = {src_fb->y_buffer, src_fb->u_buffer, src_fb->v_buffer,
2192 src_fb->alpha_buffer};
2193 int src_strides[4] = {src_fb->y_stride, src_fb->uv_stride, src_fb->uv_stride,
2194 src_fb->alpha_stride};
2196 uint8_t *dsts[4] = {dst_fb->y_buffer, dst_fb->u_buffer, dst_fb->v_buffer,
2197 dst_fb->alpha_buffer};
2198 int dst_strides[4] = {dst_fb->y_stride, dst_fb->uv_stride, dst_fb->uv_stride,
2199 dst_fb->alpha_stride};
2201 for (y = 0; y < out_h; y += 16) {
2202 for (x = 0; x < out_w; x += 16) {
2203 for (i = 0; i < MAX_MB_PLANE; ++i) {
2204 const int factor = i == 0 ? 1 : 2;
2205 const int x_q4 = x * (16 / factor) * in_w / out_w;
2206 const int y_q4 = y * (16 / factor) * in_h / out_h;
2207 const int src_stride = src_strides[i];
2208 const int dst_stride = dst_strides[i];
2209 uint8_t *src = srcs[i] + y / factor * in_h / out_h * src_stride +
2210 x / factor * in_w / out_w;
2211 uint8_t *dst = dsts[i] + y / factor * dst_stride + x / factor;
2213 vp9_convolve8(src, src_stride, dst, dst_stride,
2214 vp9_sub_pel_filters_8[x_q4 & 0xf], 16 * in_w / out_w,
2215 vp9_sub_pel_filters_8[y_q4 & 0xf], 16 * in_h / out_h,
2216 16 / factor, 16 / factor);
2221 vp8_yv12_extend_frame_borders(dst_fb);
2225 static void update_alt_ref_frame_stats(VP9_COMP *cpi) {
2226 // this frame refreshes means next frames don't unless specified by user
2227 cpi->frames_since_golden = 0;
2229 #if CONFIG_MULTIPLE_ARF
2230 if (!cpi->multi_arf_enabled)
2232 // Clear the alternate reference update pending flag.
2233 cpi->source_alt_ref_pending = 0;
2235 // Set the alternate reference frame active flag
2236 cpi->source_alt_ref_active = 1;
2238 static void update_golden_frame_stats(VP9_COMP *cpi) {
2239 // Update the Golden frame usage counts.
2240 if (cpi->refresh_golden_frame) {
2241 // this frame refreshes means next frames don't unless specified by user
2242 cpi->refresh_golden_frame = 0;
2243 cpi->frames_since_golden = 0;
2245 // ******** Fixed Q test code only ************
2246 // If we are going to use the ALT reference for the next group of frames set a flag to say so.
2247 if (cpi->oxcf.fixed_q >= 0 &&
2248 cpi->oxcf.play_alternate && !cpi->refresh_alt_ref_frame) {
2249 cpi->source_alt_ref_pending = 1;
2250 cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
2252 // TODO(ivan): for SVC encoder, GF automatic update is disabled by using a
2253 // large GF_interval
2255 cpi->frames_till_gf_update_due = INT_MAX;
2259 if (!cpi->source_alt_ref_pending)
2260 cpi->source_alt_ref_active = 0;
2262 // Decrement count down till next gf
2263 if (cpi->frames_till_gf_update_due > 0)
2264 cpi->frames_till_gf_update_due--;
2266 } else if (!cpi->refresh_alt_ref_frame) {
2267 // Decrement count down till next gf
2268 if (cpi->frames_till_gf_update_due > 0)
2269 cpi->frames_till_gf_update_due--;
2271 if (cpi->frames_till_alt_ref_frame)
2272 cpi->frames_till_alt_ref_frame--;
2274 cpi->frames_since_golden++;
2278 static int find_fp_qindex() {
2281 for (i = 0; i < QINDEX_RANGE; i++) {
2282 if (vp9_convert_qindex_to_q(i) >= 30.0) {
2287 if (i == QINDEX_RANGE)
2293 static void Pass1Encode(VP9_COMP *cpi, unsigned long *size, unsigned char *dest, unsigned int *frame_flags) {
2299 vp9_set_quantizer(cpi, find_fp_qindex());
2300 vp9_first_pass(cpi);
2303 #define WRITE_RECON_BUFFER 0
2304 #if WRITE_RECON_BUFFER
2305 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame) {
2312 sprintf(filename, "cx\\y%04d.raw", this_frame);
2313 yframe = fopen(filename, "wb");
2315 for (i = 0; i < frame->y_height; i++)
2316 fwrite(frame->y_buffer + i * frame->y_stride,
2317 frame->y_width, 1, yframe);
2320 sprintf(filename, "cx\\u%04d.raw", this_frame);
2321 yframe = fopen(filename, "wb");
2323 for (i = 0; i < frame->uv_height; i++)
2324 fwrite(frame->u_buffer + i * frame->uv_stride,
2325 frame->uv_width, 1, yframe);
2328 sprintf(filename, "cx\\v%04d.raw", this_frame);
2329 yframe = fopen(filename, "wb");
2331 for (i = 0; i < frame->uv_height; i++)
2332 fwrite(frame->v_buffer + i * frame->uv_stride,
2333 frame->uv_width, 1, yframe);
2339 static double compute_edge_pixel_proportion(YV12_BUFFER_CONFIG *frame) {
2340 #define EDGE_THRESH 128
2342 int num_edge_pels = 0;
2343 int num_pels = (frame->y_height - 2) * (frame->y_width - 2);
2344 uint8_t *prev = frame->y_buffer + 1;
2345 uint8_t *curr = frame->y_buffer + 1 + frame->y_stride;
2346 uint8_t *next = frame->y_buffer + 1 + 2 * frame->y_stride;
2347 for (i = 1; i < frame->y_height - 1; i++) {
2348 for (j = 1; j < frame->y_width - 1; j++) {
2349 /* Sobel hor and ver gradients */
2350 int v = 2 * (curr[1] - curr[-1]) + (prev[1] - prev[-1]) + (next[1] - next[-1]);
2351 int h = 2 * (prev[0] - next[0]) + (prev[1] - next[1]) + (prev[-1] - next[-1]);
2352 h = (h < 0 ? -h : h);
2353 v = (v < 0 ? -v : v);
2354 if (h > EDGE_THRESH || v > EDGE_THRESH)
2360 curr += frame->y_stride - frame->y_width + 2;
2361 prev += frame->y_stride - frame->y_width + 2;
2362 next += frame->y_stride - frame->y_width + 2;
2364 return (double)num_edge_pels / num_pels;
2367 // Function to test for conditions that indicate we should loop
2368 // back and recode a frame.
2369 static int recode_loop_test(VP9_COMP *cpi,
2370 int high_limit, int low_limit,
2371 int q, int maxq, int minq) {
2372 int force_recode = 0;
2373 VP9_COMMON *cm = &cpi->common;
2375 // Is frame recode allowed at all
2376 // Yes if either recode mode 1 is selected or mode two is selected
2377 // and the frame is a key frame. golden frame or alt_ref_frame
2378 if ((cpi->sf.recode_loop == 1) ||
2379 ((cpi->sf.recode_loop == 2) &&
2380 ((cm->frame_type == KEY_FRAME) ||
2381 cpi->refresh_golden_frame ||
2382 cpi->refresh_alt_ref_frame))) {
2383 // General over and under shoot tests
2384 if (((cpi->projected_frame_size > high_limit) && (q < maxq)) ||
2385 ((cpi->projected_frame_size < low_limit) && (q > minq))) {
2388 // Special Constrained quality tests
2389 else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
2390 // Undershoot and below auto cq level
2391 if (q > cpi->cq_target_quality &&
2392 cpi->projected_frame_size < ((cpi->this_frame_target * 7) >> 3)) {
2394 } else if (q > cpi->oxcf.cq_level &&
2395 cpi->projected_frame_size < cpi->min_frame_bandwidth &&
2396 cpi->active_best_quality > cpi->oxcf.cq_level) {
2397 // Severe undershoot and between auto and user cq level
2399 cpi->active_best_quality = cpi->oxcf.cq_level;
2404 return force_recode;
2407 static void update_reference_frames(VP9_COMP * const cpi) {
2408 VP9_COMMON * const cm = &cpi->common;
2410 // At this point the new frame has been encoded.
2411 // If any buffer copy / swapping is signaled it should be done here.
2412 if (cm->frame_type == KEY_FRAME) {
2413 ref_cnt_fb(cm->fb_idx_ref_cnt,
2414 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2415 ref_cnt_fb(cm->fb_idx_ref_cnt,
2416 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2418 #if CONFIG_MULTIPLE_ARF
2419 else if (!cpi->multi_arf_enabled && cpi->refresh_golden_frame &&
2420 !cpi->refresh_alt_ref_frame) {
2422 else if (cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame &&
2425 /* Preserve the previously existing golden frame and update the frame in
2426 * the alt ref slot instead. This is highly specific to the current use of
2427 * alt-ref as a forward reference, and this needs to be generalized as
2428 * other uses are implemented (like RTC/temporal scaling)
2430 * The update to the buffer in the alt ref slot was signaled in
2431 * vp9_pack_bitstream(), now swap the buffer pointers so that it's treated
2432 * as the golden frame next time.
2436 ref_cnt_fb(cm->fb_idx_ref_cnt,
2437 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2439 tmp = cpi->alt_fb_idx;
2440 cpi->alt_fb_idx = cpi->gld_fb_idx;
2441 cpi->gld_fb_idx = tmp;
2442 } else { /* For non key/golden frames */
2443 if (cpi->refresh_alt_ref_frame) {
2444 int arf_idx = cpi->alt_fb_idx;
2445 #if CONFIG_MULTIPLE_ARF
2446 if (cpi->multi_arf_enabled) {
2447 arf_idx = cpi->arf_buffer_idx[cpi->sequence_number + 1];
2450 ref_cnt_fb(cm->fb_idx_ref_cnt,
2451 &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
2454 if (cpi->refresh_golden_frame) {
2455 ref_cnt_fb(cm->fb_idx_ref_cnt,
2456 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2460 if (cpi->refresh_last_frame) {
2461 ref_cnt_fb(cm->fb_idx_ref_cnt,
2462 &cm->ref_frame_map[cpi->lst_fb_idx], cm->new_fb_idx);
2466 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
2467 MACROBLOCKD *xd = &cpi->mb.e_mbd;
2468 struct loopfilter *lf = &cm->lf;
2470 lf->filter_level = 0;
2472 struct vpx_usec_timer timer;
2474 vp9_clear_system_state();
2476 vpx_usec_timer_start(&timer);
2478 vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.use_fast_lpf_pick);
2480 vpx_usec_timer_mark(&timer);
2481 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
2484 if (lf->filter_level > 0) {
2485 vp9_set_alt_lf_level(cpi, lf->filter_level);
2486 vp9_loop_filter_frame(cm, xd, lf->filter_level, 0, 0);
2489 vp9_extend_frame_inner_borders(cm->frame_to_show,
2490 cm->subsampling_x, cm->subsampling_y);
2493 static void scale_references(VP9_COMP *cpi) {
2494 VP9_COMMON *cm = &cpi->common;
2496 int refs[ALLOWED_REFS_PER_FRAME] = {cpi->lst_fb_idx, cpi->gld_fb_idx,
2499 for (i = 0; i < 3; i++) {
2500 YV12_BUFFER_CONFIG *ref = &cm->yv12_fb[cm->ref_frame_map[refs[i]]];
2502 if (ref->y_crop_width != cm->width ||
2503 ref->y_crop_height != cm->height) {
2504 int new_fb = get_free_fb(cm);
2506 vp9_realloc_frame_buffer(&cm->yv12_fb[new_fb],
2507 cm->width, cm->height,
2508 cm->subsampling_x, cm->subsampling_y,
2510 scale_and_extend_frame(ref, &cm->yv12_fb[new_fb]);
2511 cpi->scaled_ref_idx[i] = new_fb;
2513 cpi->scaled_ref_idx[i] = cm->ref_frame_map[refs[i]];
2514 cm->fb_idx_ref_cnt[cm->ref_frame_map[refs[i]]]++;
2519 static void release_scaled_references(VP9_COMP *cpi) {
2520 VP9_COMMON *cm = &cpi->common;
2523 for (i = 0; i < 3; i++)
2524 cm->fb_idx_ref_cnt[cpi->scaled_ref_idx[i]]--;
2527 static void full_to_model_count(unsigned int *model_count,
2528 unsigned int *full_count) {
2530 model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
2531 model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
2532 model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
2533 for (n = THREE_TOKEN; n < DCT_EOB_TOKEN; ++n)
2534 model_count[TWO_TOKEN] += full_count[n];
2535 model_count[DCT_EOB_MODEL_TOKEN] = full_count[DCT_EOB_TOKEN];
2538 static void full_to_model_counts(
2539 vp9_coeff_count_model *model_count, vp9_coeff_count *full_count) {
2541 for (i = 0; i < BLOCK_TYPES; ++i)
2542 for (j = 0; j < REF_TYPES; ++j)
2543 for (k = 0; k < COEF_BANDS; ++k)
2544 for (l = 0; l < PREV_COEF_CONTEXTS; ++l) {
2545 if (l >= 3 && k == 0)
2547 full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
2552 static void encode_frame_to_data_rate(VP9_COMP *cpi,
2553 unsigned long *size,
2554 unsigned char *dest,
2555 unsigned int *frame_flags) {
2556 VP9_COMMON *cm = &cpi->common;
2557 MACROBLOCKD *xd = &cpi->mb.e_mbd;
2560 int frame_over_shoot_limit;
2561 int frame_under_shoot_limit;
2571 int active_worst_qchanged = 0;
2573 int overshoot_seen = 0;
2574 int undershoot_seen = 0;
2576 SPEED_FEATURES *sf = &cpi->sf;
2577 unsigned int max_mv_def = MIN(cpi->common.width, cpi->common.height);
2578 struct segmentation *seg = &cm->seg;
2580 /* Scale the source buffer, if required */
2581 if (cm->mi_cols * 8 != cpi->un_scaled_source->y_width ||
2582 cm->mi_rows * 8 != cpi->un_scaled_source->y_height) {
2583 scale_and_extend_frame(cpi->un_scaled_source, &cpi->scaled_source);
2584 cpi->Source = &cpi->scaled_source;
2586 cpi->Source = cpi->un_scaled_source;
2589 scale_references(cpi);
2591 // Clear down mmx registers to allow floating point in what follows
2592 vp9_clear_system_state();
2595 // For an alt ref frame in 2 pass we skip the call to the second
2596 // pass function that sets the target bandwidth so must set it here
2597 if (cpi->refresh_alt_ref_frame) {
2598 // Per frame bit target for the alt ref frame
2599 cpi->per_frame_bandwidth = cpi->twopass.gf_bits;
2600 // per second target bitrate
2601 cpi->target_bandwidth = (int)(cpi->twopass.gf_bits *
2602 cpi->output_framerate);
2605 // Clear zbin over-quant value and mode boost values.
2606 cpi->zbin_mode_boost = 0;
2608 // Enable or disable mode based tweaking of the zbin
2609 // For 2 Pass Only used where GF/ARF prediction quality
2610 // is above a threshold
2611 cpi->zbin_mode_boost = 0;
2613 // if (cpi->oxcf.lossless)
2614 cpi->zbin_mode_boost_enabled = 0;
2616 // cpi->zbin_mode_boost_enabled = 1;
2618 // Current default encoder behaviour for the altref sign bias
2619 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = cpi->source_alt_ref_active;
2621 // Check to see if a key frame is signaled
2622 // For two pass with auto key frame enabled cm->frame_type may already be set, but not for one pass.
2623 if ((cm->current_video_frame == 0) ||
2624 (cm->frame_flags & FRAMEFLAGS_KEY) ||
2625 (cpi->oxcf.auto_key && (cpi->frames_since_key % cpi->key_frame_frequency == 0))) {
2626 // Key frame from VFW/auto-keyframe/first frame
2627 cm->frame_type = KEY_FRAME;
2630 // Set default state for segment based loop filter update flags
2631 cm->lf.mode_ref_delta_update = 0;
2633 // Initialize cpi->mv_step_param to default based on max resolution
2634 cpi->mv_step_param = vp9_init_search_range(cpi, max_mv_def);
2635 // Initialize cpi->max_mv_magnitude and cpi->mv_step_param if appropriate.
2636 if (sf->auto_mv_step_size) {
2637 if ((cpi->common.frame_type == KEY_FRAME) || cpi->common.intra_only) {
2638 // initialize max_mv_magnitude for use in the first INTER frame
2639 // after a key/intra-only frame
2640 cpi->max_mv_magnitude = max_mv_def;
2643 // allow mv_steps to correspond to twice the max mv magnitude found
2644 // in the previous frame, capped by the default max_mv_magnitude based
2646 cpi->mv_step_param = vp9_init_search_range(
2647 cpi, MIN(max_mv_def, 2 * cpi->max_mv_magnitude));
2648 cpi->max_mv_magnitude = 0;
2652 // Set various flags etc to special state if it is a key frame
2653 if (cm->frame_type == KEY_FRAME) {
2654 // Reset the loop filter deltas and segmentation map
2657 // If segmentation is enabled force a map update for key frames
2659 seg->update_map = 1;
2660 seg->update_data = 1;
2663 // The alternate reference frame cannot be active for a key frame
2664 cpi->source_alt_ref_active = 0;
2666 cm->error_resilient_mode = (cpi->oxcf.error_resilient_mode != 0);
2667 cm->frame_parallel_decoding_mode =
2668 (cpi->oxcf.frame_parallel_decoding_mode != 0);
2669 if (cm->error_resilient_mode) {
2670 cm->frame_parallel_decoding_mode = 1;
2671 cm->reset_frame_context = 0;
2672 cm->refresh_frame_context = 0;
2676 // Configure experimental use of segmentation for enhanced coding of
2677 // static regions if indicated.
2678 // Only allowed for now in second pass of two pass (as requires lagged coding)
2679 // and if the relevant speed feature flag is set.
2680 if ((cpi->pass == 2) && (cpi->sf.static_segmentation)) {
2681 configure_static_seg_features(cpi);
2684 // Decide how big to make the frame
2685 vp9_pick_frame_size(cpi);
2687 vp9_clear_system_state();
2689 // Set an active best quality and if necessary active worst quality
2690 q = cpi->active_worst_quality;
2692 if (cm->frame_type == KEY_FRAME) {
2693 #if !CONFIG_MULTIPLE_ARF
2694 // Special case for key frames forced because we have reached
2695 // the maximum key frame interval. Here force the Q to a range
2696 // based on the ambient Q to reduce the risk of popping
2697 if (cpi->this_key_frame_forced) {
2699 int qindex = cpi->last_boosted_qindex;
2700 double last_boosted_q = vp9_convert_qindex_to_q(qindex);
2702 delta_qindex = compute_qdelta(cpi, last_boosted_q,
2703 (last_boosted_q * 0.75));
2705 cpi->active_best_quality = MAX(qindex + delta_qindex,
2710 double q_adj_factor = 1.0;
2713 // Baseline value derived from cpi->active_worst_quality and kf boost
2714 if (cpi->kf_boost > high) {
2715 cpi->active_best_quality = kf_low_motion_minq[q];
2716 } else if (cpi->kf_boost < low) {
2717 cpi->active_best_quality = kf_high_motion_minq[q];
2719 const int gap = high - low;
2720 const int offset = high - cpi->kf_boost;
2721 const int qdiff = kf_high_motion_minq[q] - kf_low_motion_minq[q];
2722 const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
2724 cpi->active_best_quality = kf_low_motion_minq[q] + adjustment;
2727 // Allow somewhat lower kf minq with small image formats.
2728 if ((cm->width * cm->height) <= (352 * 288)) {
2729 q_adj_factor -= 0.25;
2732 // Make a further adjustment based on the kf zero motion measure.
2733 q_adj_factor += 0.05 - (0.001 * (double)cpi->kf_zeromotion_pct);
2735 // Convert the adjustment factor to a qindex delta
2736 // on active_best_quality.
2737 q_val = vp9_convert_qindex_to_q(cpi->active_best_quality);
2738 cpi->active_best_quality +=
2739 compute_qdelta(cpi, q_val, (q_val * q_adj_factor));
2743 // Force the KF quantizer to be 30% of the active_worst_quality.
2744 current_q = vp9_convert_qindex_to_q(cpi->active_worst_quality);
2745 cpi->active_best_quality = cpi->active_worst_quality
2746 + compute_qdelta(cpi, current_q, current_q * 0.3);
2748 } else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) {
2752 // Use the lower of cpi->active_worst_quality and recent
2753 // average Q as basis for GF/ARF Q limit unless last frame was
2755 if (cpi->frames_since_key > 1 &&
2756 cpi->avg_frame_qindex < cpi->active_worst_quality) {
2757 q = cpi->avg_frame_qindex;
2759 // For constrained quality dont allow Q less than the cq level
2760 if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY &&
2761 q < cpi->cq_target_quality) {
2762 q = cpi->cq_target_quality;
2764 if (cpi->gfu_boost > high) {
2765 cpi->active_best_quality = gf_low_motion_minq[q];
2766 } else if (cpi->gfu_boost < low) {
2767 cpi->active_best_quality = gf_high_motion_minq[q];
2769 const int gap = high - low;
2770 const int offset = high - cpi->gfu_boost;
2771 const int qdiff = gf_high_motion_minq[q] - gf_low_motion_minq[q];
2772 const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
2774 cpi->active_best_quality = gf_low_motion_minq[q] + adjustment;
2777 // Constrained quality use slightly lower active best.
2778 if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
2779 cpi->active_best_quality = cpi->active_best_quality * 15 / 16;
2781 // TODO(debargha): Refine the logic below
2782 if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
2783 if (!cpi->refresh_alt_ref_frame) {
2784 cpi->active_best_quality = cpi->cq_target_quality;
2786 if (cpi->frames_since_key > 1) {
2787 if (cpi->gfu_boost > high) {
2788 cpi->active_best_quality = afq_low_motion_minq[q];
2789 } else if (cpi->gfu_boost < low) {
2790 cpi->active_best_quality = afq_high_motion_minq[q];
2792 const int gap = high - low;
2793 const int offset = high - cpi->gfu_boost;
2794 const int qdiff = afq_high_motion_minq[q] - afq_low_motion_minq[q];
2795 const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
2797 cpi->active_best_quality = afq_low_motion_minq[q] + adjustment;
2803 if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
2804 cpi->active_best_quality = cpi->cq_target_quality;
2806 #ifdef ONE_SHOT_Q_ESTIMATE
2807 #ifdef STRICT_ONE_SHOT_Q
2808 cpi->active_best_quality = q;
2810 cpi->active_best_quality = inter_minq[q];
2813 cpi->active_best_quality = inter_minq[q];
2816 // For the constant/constrained quality mode we don't want
2817 // q to fall below the cq level.
2818 if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
2819 (cpi->active_best_quality < cpi->cq_target_quality)) {
2820 // If we are strongly undershooting the target rate in the last
2821 // frames then use the user passed in cq value not the auto
2823 if (cpi->rolling_actual_bits < cpi->min_frame_bandwidth)
2824 cpi->active_best_quality = cpi->oxcf.cq_level;
2826 cpi->active_best_quality = cpi->cq_target_quality;
2831 // Clip the active best and worst quality values to limits
2832 if (cpi->active_worst_quality > cpi->worst_quality)
2833 cpi->active_worst_quality = cpi->worst_quality;
2835 if (cpi->active_best_quality < cpi->best_quality)
2836 cpi->active_best_quality = cpi->best_quality;
2838 if (cpi->active_best_quality > cpi->worst_quality)
2839 cpi->active_best_quality = cpi->worst_quality;
2841 if (cpi->active_worst_quality < cpi->active_best_quality)
2842 cpi->active_worst_quality = cpi->active_best_quality;
2844 // Special case code to try and match quality with forced key frames
2845 if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
2846 q = cpi->active_best_quality;
2847 } else if ((cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced) {
2848 q = cpi->last_boosted_qindex;
2850 // Determine initial Q to try
2851 q = vp9_regulate_q(cpi, cpi->this_frame_target);
2854 vp9_compute_frame_size_bounds(cpi, &frame_under_shoot_limit,
2855 &frame_over_shoot_limit);
2857 #if CONFIG_MULTIPLE_ARF
2858 // Force the quantizer determined by the coding order pattern.
2859 if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
2860 cpi->oxcf.end_usage != USAGE_CONSTANT_QUALITY) {
2862 double current_q = vp9_convert_qindex_to_q(cpi->active_worst_quality);
2863 int level = cpi->this_frame_weight;
2866 // Set quantizer steps at 10% increments.
2867 new_q = current_q * (1.0 - (0.2 * (cpi->max_arf_level - level)));
2868 q = cpi->active_worst_quality + compute_qdelta(cpi, current_q, new_q);
2875 printf("frame:%d q:%d\n", cm->current_video_frame, q);
2878 // Limit Q range for the adaptive loop.
2879 bottom_index = cpi->active_best_quality;
2880 top_index = cpi->active_worst_quality;
2881 q_low = cpi->active_best_quality;
2882 q_high = cpi->active_worst_quality;
2883 #if CONFIG_MULTIPLE_ARF
2887 vp9_zero(cpi->rd_tx_select_threshes);
2889 if (cm->frame_type != KEY_FRAME) {
2890 cm->mcomp_filter_type = DEFAULT_INTERP_FILTER;
2891 /* TODO: Decide this more intelligently */
2892 xd->allow_high_precision_mv = q < HIGH_PRECISION_MV_QTHRESH;
2893 set_mvcost(&cpi->mb);
2896 #if CONFIG_VP9_POSTPROC
2898 if (cpi->oxcf.noise_sensitivity > 0) {
2901 switch (cpi->oxcf.noise_sensitivity) {
2920 vp9_denoise(cpi->Source, cpi->Source, l);
2925 #ifdef OUTPUT_YUV_SRC
2926 vp9_write_yuv_frame(cpi->Source);
2930 vp9_clear_system_state(); // __asm emms;
2932 vp9_set_quantizer(cpi, q);
2934 if (loop_count == 0) {
2936 // Set up entropy depending on frame type.
2937 if (cm->frame_type == KEY_FRAME) {
2938 /* Choose which entropy context to use. When using a forward reference
2939 * frame, it immediately follows the keyframe, and thus benefits from
2940 * using the same entropy context established by the keyframe.
2941 * Otherwise, use the default context 0.
2943 cm->frame_context_idx = cpi->oxcf.play_alternate;
2944 vp9_setup_key_frame(cpi);
2946 /* Choose which entropy context to use. Currently there are only two
2947 * contexts used, one for normal frames and one for alt ref frames.
2949 cpi->common.frame_context_idx = cpi->refresh_alt_ref_frame;
2950 vp9_setup_inter_frame(cpi);
2954 // transform / motion compensation build reconstruction frame
2956 vp9_encode_frame(cpi);
2958 // Update the skip mb flag probabilities based on the distribution
2959 // seen in the last encoder iteration.
2960 // update_base_skip_probs(cpi);
2962 vp9_clear_system_state(); // __asm emms;
2964 // Dummy pack of the bitstream using up to date stats to get an
2965 // accurate estimate of output frame size to determine if we need
2967 vp9_save_coding_context(cpi);
2968 cpi->dummy_packing = 1;
2969 vp9_pack_bitstream(cpi, dest, size);
2970 cpi->projected_frame_size = (*size) << 3;
2971 vp9_restore_coding_context(cpi);
2973 if (frame_over_shoot_limit == 0)
2974 frame_over_shoot_limit = 1;
2975 active_worst_qchanged = 0;
2977 // Special case handling for forced key frames
2978 if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
2981 if ((cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced) {
2983 int kf_err = vp9_calc_ss_err(cpi->Source,
2984 &cm->yv12_fb[cm->new_fb_idx]);
2986 int high_err_target = cpi->ambient_err;
2987 int low_err_target = cpi->ambient_err >> 1;
2989 // Prevent possible divide by zero error below for perfect KF
2992 // The key frame is not good enough or we can afford
2993 // to make it better without undue risk of popping.
2994 if ((kf_err > high_err_target &&
2995 cpi->projected_frame_size <= frame_over_shoot_limit) ||
2996 (kf_err > low_err_target &&
2997 cpi->projected_frame_size <= frame_under_shoot_limit)) {
2999 q_high = q > q_low ? q - 1 : q_low;
3002 q = (q * high_err_target) / kf_err;
3003 q = MIN(q, (q_high + q_low) >> 1);
3004 } else if (kf_err < low_err_target &&
3005 cpi->projected_frame_size >= frame_under_shoot_limit) {
3006 // The key frame is much better than the previous frame
3008 q_low = q < q_high ? q + 1 : q_high;
3011 q = (q * low_err_target) / kf_err;
3012 q = MIN(q, (q_high + q_low + 1) >> 1);
3015 // Clamp Q to upper and lower limits:
3016 q = clamp(q, q_low, q_high);
3019 } else if (recode_loop_test(
3020 cpi, frame_over_shoot_limit, frame_under_shoot_limit,
3021 q, top_index, bottom_index)) {
3022 // Is the projected frame size out of range and are we allowed
3023 // to attempt to recode.
3027 // Frame size out of permitted range:
3028 // Update correction factor & compute new Q to try...
3030 // Frame is too large
3031 if (cpi->projected_frame_size > cpi->this_frame_target) {
3032 // Raise Qlow as to at least the current value
3033 q_low = q < q_high ? q + 1 : q_high;
3035 if (undershoot_seen || loop_count > 1) {
3036 // Update rate_correction_factor unless
3037 // cpi->active_worst_quality has changed.
3038 if (!active_worst_qchanged)
3039 vp9_update_rate_correction_factors(cpi, 1);
3041 q = (q_high + q_low + 1) / 2;
3043 // Update rate_correction_factor unless
3044 // cpi->active_worst_quality has changed.
3045 if (!active_worst_qchanged)
3046 vp9_update_rate_correction_factors(cpi, 0);
3048 q = vp9_regulate_q(cpi, cpi->this_frame_target);
3050 while (q < q_low && retries < 10) {
3051 vp9_update_rate_correction_factors(cpi, 0);
3052 q = vp9_regulate_q(cpi, cpi->this_frame_target);
3059 // Frame is too small
3060 q_high = q > q_low ? q - 1 : q_low;
3062 if (overshoot_seen || loop_count > 1) {
3063 // Update rate_correction_factor unless
3064 // cpi->active_worst_quality has changed.
3065 if (!active_worst_qchanged)
3066 vp9_update_rate_correction_factors(cpi, 1);
3068 q = (q_high + q_low) / 2;
3070 // Update rate_correction_factor unless
3071 // cpi->active_worst_quality has changed.
3072 if (!active_worst_qchanged)
3073 vp9_update_rate_correction_factors(cpi, 0);
3075 q = vp9_regulate_q(cpi, cpi->this_frame_target);
3077 // Special case reset for qlow for constrained quality.
3078 // This should only trigger where there is very substantial
3079 // undershoot on a frame and the auto cq level is above
3080 // the user passsed in value.
3081 if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY && q < q_low) {
3085 while (q > q_high && retries < 10) {
3086 vp9_update_rate_correction_factors(cpi, 0);
3087 q = vp9_regulate_q(cpi, cpi->this_frame_target);
3092 undershoot_seen = 1;
3095 // Clamp Q to upper and lower limits:
3096 q = clamp(q, q_low, q_high);
3104 if (cpi->is_src_frame_alt_ref)
3110 #if CONFIG_INTERNAL_STATS
3111 cpi->tot_recode_hits++;
3116 // Special case code to reduce pulsing when key frames are forced at a
3117 // fixed interval. Note the reconstruction error if it is the frame before
3118 // the force key frame
3119 if (cpi->next_key_frame_forced && (cpi->twopass.frames_to_key == 0)) {
3120 cpi->ambient_err = vp9_calc_ss_err(cpi->Source,
3121 &cm->yv12_fb[cm->new_fb_idx]);
3124 if (cm->frame_type == KEY_FRAME)
3125 cpi->refresh_last_frame = 1;
3127 cm->frame_to_show = &cm->yv12_fb[cm->new_fb_idx];
3129 #if WRITE_RECON_BUFFER
3131 write_cx_frame_to_file(cm->frame_to_show,
3132 cm->current_video_frame);
3134 write_cx_frame_to_file(cm->frame_to_show,
3135 cm->current_video_frame + 1000);
3138 // Pick the loop filter level for the frame.
3139 loopfilter_frame(cpi, cm);
3141 #if WRITE_RECON_BUFFER
3143 write_cx_frame_to_file(cm->frame_to_show,
3144 cm->current_video_frame + 2000);
3146 write_cx_frame_to_file(cm->frame_to_show,
3147 cm->current_video_frame + 3000);
3150 // build the bitstream
3151 cpi->dummy_packing = 0;
3152 vp9_pack_bitstream(cpi, dest, size);
3154 if (cm->seg.update_map)
3155 update_reference_segmentation_map(cpi);
3157 release_scaled_references(cpi);
3158 update_reference_frames(cpi);
3160 for (t = TX_4X4; t <= TX_32X32; t++)
3161 full_to_model_counts(cpi->common.counts.coef[t],
3162 cpi->coef_counts[t]);
3163 if (!cpi->common.error_resilient_mode &&
3164 !cpi->common.frame_parallel_decoding_mode) {
3165 vp9_adapt_coef_probs(&cpi->common);
3168 if (cpi->common.frame_type != KEY_FRAME) {
3169 FRAME_COUNTS *counts = &cpi->common.counts;
3171 vp9_copy(counts->y_mode, cpi->y_mode_count);
3172 vp9_copy(counts->uv_mode, cpi->y_uv_mode_count);
3173 vp9_copy(counts->partition, cpi->partition_count);
3174 vp9_copy(counts->intra_inter, cpi->intra_inter_count);
3175 vp9_copy(counts->comp_inter, cpi->comp_inter_count);
3176 vp9_copy(counts->single_ref, cpi->single_ref_count);
3177 vp9_copy(counts->comp_ref, cpi->comp_ref_count);
3178 counts->mv = cpi->NMVcount;
3179 if (!cpi->common.error_resilient_mode &&
3180 !cpi->common.frame_parallel_decoding_mode) {
3181 vp9_adapt_mode_probs(&cpi->common);
3182 vp9_adapt_mv_probs(&cpi->common, cpi->mb.e_mbd.allow_high_precision_mv);
3186 #ifdef ENTROPY_STATS
3187 vp9_update_mode_context_stats(cpi);
3190 /* Move storing frame_type out of the above loop since it is also
3191 * needed in motion search besides loopfilter */
3192 cm->last_frame_type = cm->frame_type;
3194 // Update rate control heuristics
3195 cpi->total_byte_count += (*size);
3196 cpi->projected_frame_size = (*size) << 3;
3198 if (!active_worst_qchanged)
3199 vp9_update_rate_correction_factors(cpi, 2);
3201 cpi->last_q[cm->frame_type] = cm->base_qindex;
3203 // Keep record of last boosted (KF/KF/ARF) Q value.
3204 // If the current frame is coded at a lower Q then we also update it.
3205 // If all mbs in this group are skipped only update if the Q value is
3206 // better than that already stored.
3207 // This is used to help set quality in forced key frames to reduce popping
3208 if ((cm->base_qindex < cpi->last_boosted_qindex) ||
3209 ((cpi->static_mb_pct < 100) &&
3210 ((cm->frame_type == KEY_FRAME) ||
3211 cpi->refresh_alt_ref_frame ||
3212 (cpi->refresh_golden_frame && !cpi->is_src_frame_alt_ref)))) {
3213 cpi->last_boosted_qindex = cm->base_qindex;
3216 if (cm->frame_type == KEY_FRAME) {
3217 vp9_adjust_key_frame_context(cpi);
3220 // Keep a record of ambient average Q.
3221 if (cm->frame_type != KEY_FRAME)
3222 cpi->avg_frame_qindex = (2 + 3 * cpi->avg_frame_qindex + cm->base_qindex) >> 2;
3224 // Keep a record from which we can calculate the average Q excluding GF updates and key frames
3225 if (cm->frame_type != KEY_FRAME &&
3226 !cpi->refresh_golden_frame &&
3227 !cpi->refresh_alt_ref_frame) {
3229 cpi->tot_q += vp9_convert_qindex_to_q(q);
3230 cpi->avg_q = cpi->tot_q / (double)cpi->ni_frames;
3232 // Calculate the average Q for normal inter frames (not key or GFU frames).
3233 cpi->ni_tot_qi += q;
3234 cpi->ni_av_qi = cpi->ni_tot_qi / cpi->ni_frames;
3237 // Update the buffer level variable.
3238 // Non-viewable frames are a special case and are treated as pure overhead.
3239 if (!cm->show_frame)
3240 cpi->bits_off_target -= cpi->projected_frame_size;
3242 cpi->bits_off_target += cpi->av_per_frame_bandwidth - cpi->projected_frame_size;
3244 // Clip the buffer level at the maximum buffer size
3245 if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size)
3246 cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
3248 // Rolling monitors of whether we are over or underspending used to help
3249 // regulate min and Max Q in two pass.
3250 if (cm->frame_type != KEY_FRAME) {
3251 cpi->rolling_target_bits =
3252 ((cpi->rolling_target_bits * 3) + cpi->this_frame_target + 2) / 4;
3253 cpi->rolling_actual_bits =
3254 ((cpi->rolling_actual_bits * 3) + cpi->projected_frame_size + 2) / 4;
3255 cpi->long_rolling_target_bits =
3256 ((cpi->long_rolling_target_bits * 31) + cpi->this_frame_target + 16) / 32;
3257 cpi->long_rolling_actual_bits =
3258 ((cpi->long_rolling_actual_bits * 31) +
3259 cpi->projected_frame_size + 16) / 32;
3262 // Actual bits spent
3263 cpi->total_actual_bits += cpi->projected_frame_size;
3266 cpi->total_target_vs_actual += (cpi->this_frame_target - cpi->projected_frame_size);
3268 cpi->buffer_level = cpi->bits_off_target;
3270 // Update bits left to the kf and gf groups to account for overshoot or undershoot on these frames
3271 if (cm->frame_type == KEY_FRAME) {
3272 cpi->twopass.kf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
3274 cpi->twopass.kf_group_bits = MAX(cpi->twopass.kf_group_bits, 0);
3275 } else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) {
3276 cpi->twopass.gf_group_bits += cpi->this_frame_target - cpi->projected_frame_size;
3278 cpi->twopass.gf_group_bits = MAX(cpi->twopass.gf_group_bits, 0);
3281 // Update the skip mb flag probabilities based on the distribution seen
3283 // update_base_skip_probs(cpi);
3285 #if 0 // CONFIG_INTERNAL_STATS
3287 FILE *f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
3290 vp9_clear_system_state(); // __asm emms;
3292 recon_err = vp9_calc_ss_err(cpi->Source,
3293 &cm->yv12_fb[cm->new_fb_idx]);
3295 if (cpi->twopass.total_left_stats.coded_error != 0.0)
3296 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %10d"
3297 "%7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f"
3298 "%6d %6d %5d %5d %5d %8.2f %10d %10.3f"
3299 "%10.3f %8d %10d %10d %10d\n",
3300 cpi->common.current_video_frame, cpi->this_frame_target,
3301 cpi->projected_frame_size, 0, //loop_size_estimate,
3302 (cpi->projected_frame_size - cpi->this_frame_target),
3303 (int)cpi->total_target_vs_actual,
3304 (int)(cpi->oxcf.starting_buffer_level - cpi->bits_off_target),
3305 (int)cpi->total_actual_bits,
3307 vp9_convert_qindex_to_q(cm->base_qindex),
3308 (double)vp9_dc_quant(cm->base_qindex, 0) / 4.0,
3309 vp9_convert_qindex_to_q(cpi->active_best_quality),
3310 vp9_convert_qindex_to_q(cpi->active_worst_quality),
3312 vp9_convert_qindex_to_q(cpi->ni_av_qi),
3313 vp9_convert_qindex_to_q(cpi->cq_target_quality),
3314 cpi->refresh_last_frame,
3315 cpi->refresh_golden_frame, cpi->refresh_alt_ref_frame,
3316 cm->frame_type, cpi->gfu_boost,
3317 cpi->twopass.est_max_qcorrection_factor,
3318 (int)cpi->twopass.bits_left,
3319 cpi->twopass.total_left_stats.coded_error,
3320 (double)cpi->twopass.bits_left /
3321 cpi->twopass.total_left_stats.coded_error,
3322 cpi->tot_recode_hits, recon_err, cpi->kf_boost,
3323 cpi->kf_zeromotion_pct);
3325 fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %10d"
3326 "%7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f"
3327 "%5d %5d %5d %8d %8d %8.2f %10d %10.3f"
3328 "%8d %10d %10d %10d\n",
3329 cpi->common.current_video_frame,
3330 cpi->this_frame_target, cpi->projected_frame_size,
3331 0, //loop_size_estimate,
3332 (cpi->projected_frame_size - cpi->this_frame_target),
3333 (int)cpi->total_target_vs_actual,
3334 (int)(cpi->oxcf.starting_buffer_level - cpi->bits_off_target),
3335 (int)cpi->total_actual_bits,
3337 vp9_convert_qindex_to_q(cm->base_qindex),
3338 (double)vp9_dc_quant(cm->base_qindex, 0) / 4.0,
3339 vp9_convert_qindex_to_q(cpi->active_best_quality),
3340 vp9_convert_qindex_to_q(cpi->active_worst_quality),
3342 vp9_convert_qindex_to_q(cpi->ni_av_qi),
3343 vp9_convert_qindex_to_q(cpi->cq_target_quality),
3344 cpi->refresh_last_frame,
3345 cpi->refresh_golden_frame, cpi->refresh_alt_ref_frame,
3346 cm->frame_type, cpi->gfu_boost,
3347 cpi->twopass.est_max_qcorrection_factor,
3348 (int)cpi->twopass.bits_left,
3349 cpi->twopass.total_left_stats.coded_error,
3350 cpi->tot_recode_hits, recon_err, cpi->kf_boost,
3351 cpi->kf_zeromotion_pct);
3356 FILE *fmodes = fopen("Modes.stt", "a");
3359 fprintf(fmodes, "%6d:%1d:%1d:%1d ",
3360 cpi->common.current_video_frame,
3361 cm->frame_type, cpi->refresh_golden_frame,
3362 cpi->refresh_alt_ref_frame);
3364 for (i = 0; i < MAX_MODES; i++)
3365 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
3367 fprintf(fmodes, "\n");
3376 // Debug stats for segment feature experiments.
3380 // If this was a kf or Gf note the Q
3381 if ((cm->frame_type == KEY_FRAME)
3382 || cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)
3383 cm->last_kf_gf_q = cm->base_qindex;
3385 if (cpi->refresh_golden_frame == 1)
3386 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
3388 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_GOLDEN;
3390 if (cpi->refresh_alt_ref_frame == 1)
3391 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
3393 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_ALTREF;
3396 if (cpi->refresh_last_frame & cpi->refresh_golden_frame)
3397 cpi->gold_is_last = 1;
3398 else if (cpi->refresh_last_frame ^ cpi->refresh_golden_frame)
3399 cpi->gold_is_last = 0;
3401 if (cpi->refresh_last_frame & cpi->refresh_alt_ref_frame)
3402 cpi->alt_is_last = 1;
3403 else if (cpi->refresh_last_frame ^ cpi->refresh_alt_ref_frame)
3404 cpi->alt_is_last = 0;
3406 if (cpi->refresh_alt_ref_frame & cpi->refresh_golden_frame)
3407 cpi->gold_is_alt = 1;
3408 else if (cpi->refresh_alt_ref_frame ^ cpi->refresh_golden_frame)
3409 cpi->gold_is_alt = 0;
3411 cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
3413 if (cpi->gold_is_last)
3414 cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
3416 if (cpi->alt_is_last)
3417 cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
3419 if (cpi->gold_is_alt)
3420 cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
3422 if (cpi->oxcf.play_alternate && cpi->refresh_alt_ref_frame
3423 && (cm->frame_type != KEY_FRAME))
3424 // Update the alternate reference frame stats as appropriate.
3425 update_alt_ref_frame_stats(cpi);
3427 // Update the Golden frame stats as appropriate.
3428 update_golden_frame_stats(cpi);
3430 if (cm->frame_type == KEY_FRAME) {
3431 // Tell the caller that the frame was coded as a key frame
3432 *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
3434 #if CONFIG_MULTIPLE_ARF
3435 // Reset the sequence number.
3436 if (cpi->multi_arf_enabled) {
3437 cpi->sequence_number = 0;
3438 cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
3439 cpi->new_frame_coding_order_period = -1;
3443 // As this frame is a key frame the next defaults to an inter frame.
3444 cm->frame_type = INTER_FRAME;
3446 *frame_flags = cm->frame_flags&~FRAMEFLAGS_KEY;
3448 #if CONFIG_MULTIPLE_ARF
3449 /* Increment position in the coded frame sequence. */
3450 if (cpi->multi_arf_enabled) {
3451 ++cpi->sequence_number;
3452 if (cpi->sequence_number >= cpi->frame_coding_order_period) {
3453 cpi->sequence_number = 0;
3454 cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
3455 cpi->new_frame_coding_order_period = -1;
3457 cpi->this_frame_weight = cpi->arf_weight[cpi->sequence_number];
3458 assert(cpi->this_frame_weight >= 0);
3463 // Clear the one shot update flags for segmentation map and mode/ref loop filter deltas.
3464 cm->seg.update_map = 0;
3465 cm->seg.update_data = 0;
3466 cm->lf.mode_ref_delta_update = 0;
3468 // keep track of the last coded dimensions
3469 cm->last_width = cm->width;
3470 cm->last_height = cm->height;
3472 // reset to normal state now that we are done.
3473 cm->last_show_frame = cm->show_frame;
3474 if (cm->show_frame) {
3475 // current mip will be the prev_mip for the next frame
3476 MODE_INFO *temp = cm->prev_mip;
3477 MODE_INFO **temp2 = cm->prev_mi_grid_base;
3478 cm->prev_mip = cm->mip;
3480 cm->prev_mi_grid_base = cm->mi_grid_base;
3481 cm->mi_grid_base = temp2;
3483 // update the upper left visible macroblock ptrs
3484 cm->mi = cm->mip + cm->mode_info_stride + 1;
3485 cm->mi_grid_visible = cm->mi_grid_base + cm->mode_info_stride + 1;
3487 // Don't increment frame counters if this was an altref buffer
3488 // update not a real frame
3489 ++cm->current_video_frame;
3490 ++cpi->frames_since_key;
3493 cm->prev_mi = cm->prev_mip + cm->mode_info_stride + 1;
3494 cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mode_info_stride + 1;
3500 sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
3501 recon_file = fopen(filename, "wb");
3502 fwrite(cm->yv12_fb[cm->ref_frame_map[cpi->lst_fb_idx]].buffer_alloc,
3503 cm->yv12_fb[cm->ref_frame_map[cpi->lst_fb_idx]].frame_size,
3508 #ifdef OUTPUT_YUV_REC
3509 vp9_write_yuv_rec_frame(cm);
3514 static void Pass2Encode(VP9_COMP *cpi, unsigned long *size,
3515 unsigned char *dest, unsigned int *frame_flags) {
3517 cpi->enable_encode_breakout = 1;
3519 if (!cpi->refresh_alt_ref_frame)
3520 vp9_second_pass(cpi);
3522 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3523 // vp9_print_modes_and_motion_vectors(&cpi->common, "encode.stt");
3524 #ifdef DISABLE_RC_LONG_TERM_MEM
3525 cpi->twopass.bits_left -= cpi->this_frame_target;
3527 cpi->twopass.bits_left -= 8 * *size;
3530 if (!cpi->refresh_alt_ref_frame) {
3531 double lower_bounds_min_rate = FRAME_OVERHEAD_BITS * cpi->oxcf.framerate;
3532 double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth
3533 * cpi->oxcf.two_pass_vbrmin_section / 100);
3535 if (two_pass_min_rate < lower_bounds_min_rate)
3536 two_pass_min_rate = lower_bounds_min_rate;
3538 cpi->twopass.bits_left += (int64_t)(two_pass_min_rate / cpi->oxcf.framerate);
3542 static void check_initial_width(VP9_COMP *cpi, YV12_BUFFER_CONFIG *sd) {
3543 VP9_COMMON *cm = &cpi->common;
3544 if (!cpi->initial_width) {
3545 // TODO(jkoleszar): Support 1/4 subsampling?
3546 cm->subsampling_x = (sd != NULL) && sd->uv_width < sd->y_width;
3547 cm->subsampling_y = (sd != NULL) && sd->uv_height < sd->y_height;
3548 alloc_raw_frame_buffers(cpi);
3550 cpi->initial_width = cm->width;
3551 cpi->initial_height = cm->height;
3556 int vp9_receive_raw_frame(VP9_PTR ptr, unsigned int frame_flags,
3557 YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
3559 VP9_COMP *cpi = (VP9_COMP *) ptr;
3560 struct vpx_usec_timer timer;
3563 check_initial_width(cpi, sd);
3564 vpx_usec_timer_start(&timer);
3565 if (vp9_lookahead_push(cpi->lookahead, sd, time_stamp, end_time, frame_flags,
3566 cpi->active_map_enabled ? cpi->active_map : NULL))
3568 vpx_usec_timer_mark(&timer);
3569 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
3575 static int frame_is_reference(const VP9_COMP *cpi) {
3576 const VP9_COMMON *cm = &cpi->common;
3578 return cm->frame_type == KEY_FRAME ||
3579 cpi->refresh_last_frame ||
3580 cpi->refresh_golden_frame ||
3581 cpi->refresh_alt_ref_frame ||
3582 cm->refresh_frame_context ||
3583 cm->lf.mode_ref_delta_update ||
3584 cm->seg.update_map ||
3585 cm->seg.update_data;
3588 #if CONFIG_MULTIPLE_ARF
3589 int is_next_frame_arf(VP9_COMP *cpi) {
3590 // Negative entry in frame_coding_order indicates an ARF at this position.
3591 return cpi->frame_coding_order[cpi->sequence_number + 1] < 0 ? 1 : 0;
3595 int vp9_get_compressed_data(VP9_PTR ptr, unsigned int *frame_flags,
3596 unsigned long *size, unsigned char *dest,
3597 int64_t *time_stamp, int64_t *time_end, int flush) {
3598 VP9_COMP *cpi = (VP9_COMP *) ptr;
3599 VP9_COMMON *cm = &cpi->common;
3600 struct vpx_usec_timer cmptimer;
3601 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
3603 // FILE *fp_out = fopen("enc_frame_type.txt", "a");
3608 vpx_usec_timer_start(&cmptimer);
3612 cpi->mb.e_mbd.allow_high_precision_mv = ALTREF_HIGH_PRECISION_MV;
3613 set_mvcost(&cpi->mb);
3615 // Should we code an alternate reference frame.
3616 if (cpi->oxcf.play_alternate && cpi->source_alt_ref_pending) {
3619 #if CONFIG_MULTIPLE_ARF
3620 assert(!cpi->multi_arf_enabled ||
3621 cpi->frame_coding_order[cpi->sequence_number] < 0);
3623 if (cpi->multi_arf_enabled && (cpi->pass == 2))
3624 frames_to_arf = (-cpi->frame_coding_order[cpi->sequence_number])
3625 - cpi->next_frame_in_order;
3628 frames_to_arf = cpi->frames_till_gf_update_due;
3630 assert(frames_to_arf < cpi->twopass.frames_to_key);
3632 if ((cpi->source = vp9_lookahead_peek(cpi->lookahead, frames_to_arf))) {
3633 #if CONFIG_MULTIPLE_ARF
3634 cpi->alt_ref_source[cpi->arf_buffered] = cpi->source;
3636 cpi->alt_ref_source = cpi->source;
3639 if (cpi->oxcf.arnr_max_frames > 0) {
3640 // Produce the filtered ARF frame.
3641 // TODO(agrange) merge these two functions.
3642 configure_arnr_filter(cpi, cm->current_video_frame + frames_to_arf,
3644 vp9_temporal_filter_prepare(cpi, frames_to_arf);
3645 vp9_extend_frame_borders(&cpi->alt_ref_buffer,
3646 cm->subsampling_x, cm->subsampling_y);
3647 force_src_buffer = &cpi->alt_ref_buffer;
3652 cpi->refresh_alt_ref_frame = 1;
3653 cpi->refresh_golden_frame = 0;
3654 cpi->refresh_last_frame = 0;
3655 cpi->is_src_frame_alt_ref = 0;
3657 // TODO(agrange) This needs to vary depending on where the next ARF is.
3658 cpi->frames_till_alt_ref_frame = frames_to_arf;
3660 #if CONFIG_MULTIPLE_ARF
3661 if (!cpi->multi_arf_enabled)
3663 cpi->source_alt_ref_pending = 0; // Clear Pending altf Ref flag.
3668 #if CONFIG_MULTIPLE_ARF
3671 if ((cpi->source = vp9_lookahead_pop(cpi->lookahead, flush))) {
3674 #if CONFIG_MULTIPLE_ARF
3675 // Is this frame the ARF overlay.
3676 cpi->is_src_frame_alt_ref = 0;
3677 for (i = 0; i < cpi->arf_buffered; ++i) {
3678 if (cpi->source == cpi->alt_ref_source[i]) {
3679 cpi->is_src_frame_alt_ref = 1;
3680 cpi->refresh_golden_frame = 1;
3685 cpi->is_src_frame_alt_ref = cpi->alt_ref_source
3686 && (cpi->source == cpi->alt_ref_source);
3688 if (cpi->is_src_frame_alt_ref) {
3689 // Current frame is an ARF overlay frame.
3690 #if CONFIG_MULTIPLE_ARF
3691 cpi->alt_ref_source[i] = NULL;
3693 cpi->alt_ref_source = NULL;
3695 // Don't refresh the last buffer for an ARF overlay frame. It will
3696 // become the GF so preserve last as an alternative prediction option.
3697 cpi->refresh_last_frame = 0;
3699 #if CONFIG_MULTIPLE_ARF
3700 ++cpi->next_frame_in_order;
3706 cpi->un_scaled_source = cpi->Source = force_src_buffer ? force_src_buffer
3707 : &cpi->source->img;
3708 *time_stamp = cpi->source->ts_start;
3709 *time_end = cpi->source->ts_end;
3710 *frame_flags = cpi->source->flags;
3712 // fprintf(fp_out, " Frame:%d", cm->current_video_frame);
3713 #if CONFIG_MULTIPLE_ARF
3714 if (cpi->multi_arf_enabled) {
3715 // fprintf(fp_out, " seq_no:%d this_frame_weight:%d",
3716 // cpi->sequence_number, cpi->this_frame_weight);
3718 // fprintf(fp_out, "\n");
3721 // fprintf(fp_out, "\n");
3724 #if CONFIG_MULTIPLE_ARF
3725 if ((cm->frame_type != KEY_FRAME) && (cpi->pass == 2))
3726 cpi->source_alt_ref_pending = is_next_frame_arf(cpi);
3730 if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done) {
3731 vp9_end_first_pass(cpi); /* get last stats packet */
3732 cpi->twopass.first_pass_done = 1;
3739 if (cpi->source->ts_start < cpi->first_time_stamp_ever) {
3740 cpi->first_time_stamp_ever = cpi->source->ts_start;
3741 cpi->last_end_time_stamp_seen = cpi->source->ts_start;
3744 // adjust frame rates based on timestamps given
3745 if (!cpi->refresh_alt_ref_frame) {
3746 int64_t this_duration;
3749 if (cpi->source->ts_start == cpi->first_time_stamp_ever) {
3750 this_duration = cpi->source->ts_end - cpi->source->ts_start;
3753 int64_t last_duration = cpi->last_end_time_stamp_seen
3754 - cpi->last_time_stamp_seen;
3756 this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
3758 // do a step update if the duration changes by 10%
3760 step = (int)((this_duration - last_duration) * 10 / last_duration);
3763 if (this_duration) {
3765 vp9_new_framerate(cpi, 10000000.0 / this_duration);
3767 // Average this frame's rate into the last second's average
3768 // frame rate. If we haven't seen 1 second yet, then average
3769 // over the whole interval seen.
3770 const double interval = MIN((double)(cpi->source->ts_end
3771 - cpi->first_time_stamp_ever), 10000000.0);
3772 double avg_duration = 10000000.0 / cpi->oxcf.framerate;
3773 avg_duration *= (interval - avg_duration + this_duration);
3774 avg_duration /= interval;
3776 vp9_new_framerate(cpi, 10000000.0 / avg_duration);
3780 cpi->last_time_stamp_seen = cpi->source->ts_start;
3781 cpi->last_end_time_stamp_seen = cpi->source->ts_end;
3784 // start with a 0 size frame
3787 // Clear down mmx registers
3788 vp9_clear_system_state(); // __asm emms;
3790 /* find a free buffer for the new frame, releasing the reference previously
3793 cm->fb_idx_ref_cnt[cm->new_fb_idx]--;
3794 cm->new_fb_idx = get_free_fb(cm);
3796 #if CONFIG_MULTIPLE_ARF
3797 /* Set up the correct ARF frame. */
3798 if (cpi->refresh_alt_ref_frame) {
3799 ++cpi->arf_buffered;
3801 if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
3803 cpi->alt_fb_idx = cpi->arf_buffer_idx[cpi->sequence_number];
3807 /* Get the mapping of L/G/A to the reference buffer pool */
3808 cm->active_ref_idx[0] = cm->ref_frame_map[cpi->lst_fb_idx];
3809 cm->active_ref_idx[1] = cm->ref_frame_map[cpi->gld_fb_idx];
3810 cm->active_ref_idx[2] = cm->ref_frame_map[cpi->alt_fb_idx];
3812 #if 0 // CONFIG_MULTIPLE_ARF
3813 if (cpi->multi_arf_enabled) {
3814 fprintf(fp_out, " idx(%d, %d, %d, %d) active(%d, %d, %d)",
3815 cpi->lst_fb_idx, cpi->gld_fb_idx, cpi->alt_fb_idx, cm->new_fb_idx,
3816 cm->active_ref_idx[0], cm->active_ref_idx[1], cm->active_ref_idx[2]);
3817 if (cpi->refresh_alt_ref_frame)
3818 fprintf(fp_out, " type:ARF");
3819 if (cpi->is_src_frame_alt_ref)
3820 fprintf(fp_out, " type:OVERLAY[%d]", cpi->alt_fb_idx);
3821 fprintf(fp_out, "\n");
3825 cm->frame_type = INTER_FRAME;
3826 cm->frame_flags = *frame_flags;
3828 // Reset the frame pointers to the current frame size
3829 vp9_realloc_frame_buffer(&cm->yv12_fb[cm->new_fb_idx],
3830 cm->width, cm->height,
3831 cm->subsampling_x, cm->subsampling_y,
3834 // Calculate scaling factors for each of the 3 available references
3835 for (i = 0; i < ALLOWED_REFS_PER_FRAME; ++i)
3836 vp9_setup_scale_factors(cm, i);
3838 vp9_setup_interp_filters(&cpi->mb.e_mbd, DEFAULT_INTERP_FILTER, cm);
3840 if (cpi->pass == 1) {
3841 Pass1Encode(cpi, size, dest, frame_flags);
3842 } else if (cpi->pass == 2) {
3843 Pass2Encode(cpi, size, dest, frame_flags);
3845 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3848 if (cm->refresh_frame_context)
3849 cm->frame_contexts[cm->frame_context_idx] = cm->fc;
3852 // if its a dropped frame honor the requests on subsequent frames
3853 cpi->droppable = !frame_is_reference(cpi);
3855 // return to normal state
3856 cm->reset_frame_context = 0;
3857 cm->refresh_frame_context = 1;
3858 cpi->refresh_alt_ref_frame = 0;
3859 cpi->refresh_golden_frame = 0;
3860 cpi->refresh_last_frame = 1;
3861 cm->frame_type = INTER_FRAME;
3864 vpx_usec_timer_mark(&cmptimer);
3865 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
3867 if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
3868 generate_psnr_packet(cpi);
3870 #if CONFIG_INTERNAL_STATS
3872 if (cpi->pass != 1) {
3873 cpi->bytes += *size;
3875 if (cm->show_frame) {
3879 if (cpi->b_calculate_psnr) {
3882 YV12_BUFFER_CONFIG *orig = cpi->Source;
3883 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
3884 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
3885 int y_samples = orig->y_height * orig->y_width;
3886 int uv_samples = orig->uv_height * orig->uv_width;
3887 int t_samples = y_samples + 2 * uv_samples;
3890 ye = (double)calc_plane_error(orig->y_buffer, orig->y_stride,
3891 recon->y_buffer, recon->y_stride,
3892 orig->y_crop_width, orig->y_crop_height);
3894 ue = (double)calc_plane_error(orig->u_buffer, orig->uv_stride,
3895 recon->u_buffer, recon->uv_stride,
3896 orig->uv_crop_width, orig->uv_crop_height);
3898 ve = (double)calc_plane_error(orig->v_buffer, orig->uv_stride,
3899 recon->v_buffer, recon->uv_stride,
3900 orig->uv_crop_width, orig->uv_crop_height);
3902 sq_error = ye + ue + ve;
3904 frame_psnr = vp9_mse2psnr(t_samples, 255.0, sq_error);
3906 cpi->total_y += vp9_mse2psnr(y_samples, 255.0, ye);
3907 cpi->total_u += vp9_mse2psnr(uv_samples, 255.0, ue);
3908 cpi->total_v += vp9_mse2psnr(uv_samples, 255.0, ve);
3909 cpi->total_sq_error += sq_error;
3910 cpi->total += frame_psnr;
3912 double frame_psnr2, frame_ssim2 = 0;
3914 #if CONFIG_VP9_POSTPROC
3915 vp9_deblock(cm->frame_to_show, &cm->post_proc_buffer,
3916 cm->lf.filter_level * 10 / 6);
3918 vp9_clear_system_state();
3920 ye = (double)calc_plane_error(orig->y_buffer, orig->y_stride,
3921 pp->y_buffer, pp->y_stride,
3922 orig->y_crop_width, orig->y_crop_height);
3924 ue = (double)calc_plane_error(orig->u_buffer, orig->uv_stride,
3925 pp->u_buffer, pp->uv_stride,
3926 orig->uv_crop_width, orig->uv_crop_height);
3928 ve = (double)calc_plane_error(orig->v_buffer, orig->uv_stride,
3929 pp->v_buffer, pp->uv_stride,
3930 orig->uv_crop_width, orig->uv_crop_height);
3932 sq_error = ye + ue + ve;
3934 frame_psnr2 = vp9_mse2psnr(t_samples, 255.0, sq_error);
3936 cpi->totalp_y += vp9_mse2psnr(y_samples, 255.0, ye);
3937 cpi->totalp_u += vp9_mse2psnr(uv_samples, 255.0, ue);
3938 cpi->totalp_v += vp9_mse2psnr(uv_samples, 255.0, ve);
3939 cpi->total_sq_error2 += sq_error;
3940 cpi->totalp += frame_psnr2;
3942 frame_ssim2 = vp9_calc_ssim(cpi->Source,
3945 cpi->summed_quality += frame_ssim2 * weight;
3946 cpi->summed_weights += weight;
3948 frame_ssim2 = vp9_calc_ssim(cpi->Source,
3949 &cm->post_proc_buffer, 1, &weight);
3951 cpi->summedp_quality += frame_ssim2 * weight;
3952 cpi->summedp_weights += weight;
3955 FILE *f = fopen("q_used.stt", "a");
3956 fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
3957 cpi->common.current_video_frame, y2, u2, v2,
3958 frame_psnr2, frame_ssim2);
3965 if (cpi->b_calculate_ssimg) {
3966 double y, u, v, frame_all;
3967 frame_all = vp9_calc_ssimg(cpi->Source, cm->frame_to_show,
3969 cpi->total_ssimg_y += y;
3970 cpi->total_ssimg_u += u;
3971 cpi->total_ssimg_v += v;
3972 cpi->total_ssimg_all += frame_all;
3982 int vp9_get_preview_raw_frame(VP9_PTR comp, YV12_BUFFER_CONFIG *dest,
3983 vp9_ppflags_t *flags) {
3984 VP9_COMP *cpi = (VP9_COMP *) comp;
3986 if (!cpi->common.show_frame)
3990 #if CONFIG_VP9_POSTPROC
3991 ret = vp9_post_proc_frame(&cpi->common, dest, flags);
3994 if (cpi->common.frame_to_show) {
3995 *dest = *cpi->common.frame_to_show;
3996 dest->y_width = cpi->common.width;
3997 dest->y_height = cpi->common.height;
3998 dest->uv_height = cpi->common.height / 2;
4004 #endif // !CONFIG_VP9_POSTPROC
4005 vp9_clear_system_state();
4010 int vp9_set_roimap(VP9_PTR comp, unsigned char *map, unsigned int rows,
4011 unsigned int cols, int delta_q[MAX_SEGMENTS],
4012 int delta_lf[MAX_SEGMENTS],
4013 unsigned int threshold[MAX_SEGMENTS]) {
4014 VP9_COMP *cpi = (VP9_COMP *) comp;
4015 signed char feature_data[SEG_LVL_MAX][MAX_SEGMENTS];
4016 struct segmentation *seg = &cpi->common.seg;
4019 if (cpi->common.mb_rows != rows || cpi->common.mb_cols != cols)
4023 vp9_disable_segmentation((VP9_PTR)cpi);
4027 // Set the segmentation Map
4028 vp9_set_segmentation_map((VP9_PTR)cpi, map);
4030 // Activate segmentation.
4031 vp9_enable_segmentation((VP9_PTR)cpi);
4033 // Set up the quant, LF and breakout threshold segment data
4034 for (i = 0; i < MAX_SEGMENTS; i++) {
4035 feature_data[SEG_LVL_ALT_Q][i] = delta_q[i];
4036 feature_data[SEG_LVL_ALT_LF][i] = delta_lf[i];
4037 cpi->segment_encode_breakout[i] = threshold[i];
4040 // Enable the loop and quant changes in the feature mask
4041 for (i = 0; i < MAX_SEGMENTS; i++) {
4043 vp9_enable_segfeature(seg, i, SEG_LVL_ALT_Q);
4045 vp9_disable_segfeature(seg, i, SEG_LVL_ALT_Q);
4048 vp9_enable_segfeature(seg, i, SEG_LVL_ALT_LF);
4050 vp9_disable_segfeature(seg, i, SEG_LVL_ALT_LF);
4053 // Initialize the feature data structure
4054 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
4055 vp9_set_segment_data((VP9_PTR)cpi, &feature_data[0][0], SEGMENT_DELTADATA);
4060 int vp9_set_active_map(VP9_PTR comp, unsigned char *map,
4061 unsigned int rows, unsigned int cols) {
4062 VP9_COMP *cpi = (VP9_COMP *) comp;
4064 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
4066 vpx_memcpy(cpi->active_map, map, rows * cols);
4067 cpi->active_map_enabled = 1;
4069 cpi->active_map_enabled = 0;
4074 // cpi->active_map_enabled = 0;
4079 int vp9_set_internal_size(VP9_PTR comp,
4080 VPX_SCALING horiz_mode, VPX_SCALING vert_mode) {
4081 VP9_COMP *cpi = (VP9_COMP *) comp;
4082 VP9_COMMON *cm = &cpi->common;
4083 int hr = 0, hs = 0, vr = 0, vs = 0;
4085 if (horiz_mode > ONETWO || vert_mode > ONETWO)
4088 Scale2Ratio(horiz_mode, &hr, &hs);
4089 Scale2Ratio(vert_mode, &vr, &vs);
4091 // always go to the next whole number
4092 cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
4093 cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
4095 assert(cm->width <= cpi->initial_width);
4096 assert(cm->height <= cpi->initial_height);
4097 update_frame_size(cpi);
4101 int vp9_set_size_literal(VP9_PTR comp, unsigned int width,
4102 unsigned int height) {
4103 VP9_COMP *cpi = (VP9_COMP *)comp;
4104 VP9_COMMON *cm = &cpi->common;
4106 check_initial_width(cpi, NULL);
4110 if (cm->width * 5 < cpi->initial_width) {
4111 cm->width = cpi->initial_width / 5 + 1;
4112 printf("Warning: Desired width too small, changed to %d \n", cm->width);
4114 if (cm->width > cpi->initial_width) {
4115 cm->width = cpi->initial_width;
4116 printf("Warning: Desired width too large, changed to %d \n", cm->width);
4121 cm->height = height;
4122 if (cm->height * 5 < cpi->initial_height) {
4123 cm->height = cpi->initial_height / 5 + 1;
4124 printf("Warning: Desired height too small, changed to %d \n", cm->height);
4126 if (cm->height > cpi->initial_height) {
4127 cm->height = cpi->initial_height;
4128 printf("Warning: Desired height too large, changed to %d \n", cm->height);
4132 assert(cm->width <= cpi->initial_width);
4133 assert(cm->height <= cpi->initial_height);
4134 update_frame_size(cpi);
4138 int vp9_switch_layer(VP9_PTR comp, int layer) {
4139 VP9_COMP *cpi = (VP9_COMP *)comp;
4142 cpi->current_layer = layer;
4144 // Use buffer i for layer i LST
4145 cpi->lst_fb_idx = layer;
4147 // Use buffer i-1 for layer i Alt (Inter-layer prediction)
4148 if (layer != 0) cpi->alt_fb_idx = layer - 1;
4150 // Use the rest for Golden
4151 if (layer < 2 * cpi->number_spatial_layers - NUM_REF_FRAMES)
4152 cpi->gld_fb_idx = cpi->lst_fb_idx;
4154 cpi->gld_fb_idx = 2 * cpi->number_spatial_layers - 1 - layer;
4156 printf("Switching to layer %d:\n", layer);
4157 printf("Using references: LST/GLD/ALT [%d|%d|%d]\n", cpi->lst_fb_idx,
4158 cpi->gld_fb_idx, cpi->alt_fb_idx);
4160 printf("Switching layer not supported. Enable SVC first \n");
4165 void vp9_set_svc(VP9_PTR comp, int use_svc) {
4166 VP9_COMP *cpi = (VP9_COMP *)comp;
4167 cpi->use_svc = use_svc;
4168 if (cpi->use_svc) printf("Enabled SVC encoder \n");
4172 int vp9_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest) {
4176 uint8_t *src = source->y_buffer;
4177 uint8_t *dst = dest->y_buffer;
4179 // Loop through the Y plane raw and reconstruction data summing
4180 // (square differences)
4181 for (i = 0; i < source->y_height; i += 16) {
4182 for (j = 0; j < source->y_width; j += 16) {
4184 total += vp9_mse16x16(src + j, source->y_stride, dst + j, dest->y_stride,
4188 src += 16 * source->y_stride;
4189 dst += 16 * dest->y_stride;
4196 int vp9_get_quantizer(VP9_PTR c) {
4197 return ((VP9_COMP *)c)->common.base_qindex;