2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
15 #include "./vpx_config.h"
16 #include "./vpx_scale_rtcd.h"
18 #include "vp9/common/vp9_alloccommon.h"
19 #include "vp9/common/vp9_filter.h"
20 #include "vp9/common/vp9_idct.h"
21 #if CONFIG_VP9_POSTPROC
22 #include "vp9/common/vp9_postproc.h"
24 #include "vp9/common/vp9_reconinter.h"
25 #include "vp9/common/vp9_systemdependent.h"
26 #include "vp9/common/vp9_tile_common.h"
28 #include "vp9/encoder/vp9_encodemv.h"
29 #include "vp9/encoder/vp9_firstpass.h"
30 #include "vp9/encoder/vp9_mbgraph.h"
31 #include "vp9/encoder/vp9_onyx_int.h"
32 #include "vp9/encoder/vp9_picklpf.h"
33 #include "vp9/encoder/vp9_psnr.h"
34 #include "vp9/encoder/vp9_ratectrl.h"
35 #include "vp9/encoder/vp9_rdopt.h"
36 #include "vp9/encoder/vp9_segmentation.h"
37 #include "vp9/encoder/vp9_temporal_filter.h"
38 #include "vp9/encoder/vp9_vaq.h"
40 #include "vpx_ports/vpx_timer.h"
42 void vp9_entropy_mode_init();
43 void vp9_coef_tree_initialize();
45 #define DEFAULT_INTERP_FILTER SWITCHABLE
47 #define SHARP_FILTER_QTHRESH 0 /* Q threshold for 8-tap sharp filter */
49 #define ALTREF_HIGH_PRECISION_MV 1 // Whether to use high precision mv
50 // for altref computation.
51 #define HIGH_PRECISION_MV_QTHRESH 200 // Q threshold for high precision
52 // mv. Choose a very high value for
53 // now so that HIGH_PRECISION is always
56 // Masks for partially or completely disabling split mode
57 #define DISABLE_ALL_SPLIT 0x3F
58 #define DISABLE_ALL_INTER_SPLIT 0x1F
59 #define DISABLE_COMPOUND_SPLIT 0x18
60 #define LAST_AND_INTRA_SPLIT_ONLY 0x1E
62 // Max rate target for 1080P and below encodes under normal circumstances
63 // (1920 * 1080 / (16 * 16)) * MAX_MB_RATE bits per MB
64 #define MAX_MB_RATE 250
65 #define MAXRATE_1080P 2025000
67 #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 void init_tx_count_stats();
98 extern void write_tx_count_stats();
99 extern void init_switchable_interp_stats();
100 extern void write_switchable_interp_stats();
104 unsigned int frames_at_speed[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
108 #if defined(SECTIONBITS_OUTPUT)
109 extern unsigned __int64 Sectionbits[500];
112 extern void vp9_init_quantizer(VP9_COMP *cpi);
114 static const double in_frame_q_adj_ratio[MAX_SEGMENTS] =
115 {1.0, 1.5, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0};
117 static INLINE void Scale2Ratio(int mode, int *hr, int *hs) {
143 static void set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv) {
144 MACROBLOCK *const mb = &cpi->mb;
145 cpi->common.allow_high_precision_mv = allow_high_precision_mv;
146 if (cpi->common.allow_high_precision_mv) {
147 mb->mvcost = mb->nmvcost_hp;
148 mb->mvsadcost = mb->nmvsadcost_hp;
150 mb->mvcost = mb->nmvcost;
151 mb->mvsadcost = mb->nmvsadcost;
155 void vp9_initialize_enc() {
156 static int init_done = 0;
159 vp9_initialize_common();
160 vp9_coef_tree_initialize();
161 vp9_tokenize_initialize();
162 vp9_init_quant_tables();
164 vp9_rc_init_minq_luts();
165 // init_base_skip_probs();
166 vp9_entropy_mv_init();
167 vp9_entropy_mode_init();
172 static void dealloc_compressor_data(VP9_COMP *cpi) {
173 // Delete sementation map
174 vpx_free(cpi->segmentation_map);
175 cpi->segmentation_map = 0;
176 vpx_free(cpi->common.last_frame_seg_map);
177 cpi->common.last_frame_seg_map = 0;
178 vpx_free(cpi->coding_context.last_frame_seg_map_copy);
179 cpi->coding_context.last_frame_seg_map_copy = 0;
181 vpx_free(cpi->complexity_map);
182 cpi->complexity_map = 0;
183 vpx_free(cpi->active_map);
186 vp9_free_frame_buffers(&cpi->common);
188 vp9_free_frame_buffer(&cpi->last_frame_uf);
189 vp9_free_frame_buffer(&cpi->scaled_source);
190 vp9_free_frame_buffer(&cpi->alt_ref_buffer);
191 vp9_lookahead_destroy(cpi->lookahead);
196 // Activity mask based per mb zbin adjustments
197 vpx_free(cpi->mb_activity_map);
198 cpi->mb_activity_map = 0;
199 vpx_free(cpi->mb_norm_activity_map);
200 cpi->mb_norm_activity_map = 0;
202 vpx_free(cpi->above_context[0]);
203 cpi->above_context[0] = NULL;
205 vpx_free(cpi->above_seg_context);
206 cpi->above_seg_context = NULL;
209 // Computes a q delta (in "q index" terms) to get from a starting q value
212 int vp9_compute_qdelta(const VP9_COMP *cpi, double qstart, double qtarget) {
214 int start_index = cpi->rc.worst_quality;
215 int target_index = cpi->rc.worst_quality;
217 // Convert the average q value to an index.
218 for (i = cpi->rc.best_quality; i < cpi->rc.worst_quality; i++) {
220 if (vp9_convert_qindex_to_q(i) >= qstart)
224 // Convert the q target to an index
225 for (i = cpi->rc.best_quality; i < cpi->rc.worst_quality; i++) {
227 if (vp9_convert_qindex_to_q(i) >= qtarget)
231 return target_index - start_index;
234 // Computes a q delta (in "q index" terms) to get from a starting q value
235 // to a value that should equate to thegiven rate ratio.
237 int vp9_compute_qdelta_by_rate(VP9_COMP *cpi,
238 double base_q_index, double rate_target_ratio) {
240 int base_bits_per_mb;
241 int target_bits_per_mb;
242 int target_index = cpi->rc.worst_quality;
244 // Make SURE use of floating point in this function is safe.
245 vp9_clear_system_state();
247 // Look up the current projected bits per block for the base index
248 base_bits_per_mb = vp9_rc_bits_per_mb(cpi->common.frame_type,
251 // Find the target bits per mb based on the base value and given ratio.
252 target_bits_per_mb = rate_target_ratio * base_bits_per_mb;
254 // Convert the q target to an index
255 for (i = cpi->rc.best_quality; i < cpi->rc.worst_quality; i++) {
257 if (vp9_rc_bits_per_mb(cpi->common.frame_type,
258 i, 1.0) <= target_bits_per_mb )
262 return target_index - base_q_index;
265 // This function sets up a set of segments with delta Q values around
266 // the baseline frame quantizer.
267 static void setup_in_frame_q_adj(VP9_COMP *cpi) {
268 VP9_COMMON *cm = &cpi->common;
269 struct segmentation *seg = &cm->seg;
274 // Make SURE use of floating point in this function is safe.
275 vp9_clear_system_state();
277 if (cm->frame_type == KEY_FRAME ||
278 cpi->refresh_alt_ref_frame ||
279 (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref)) {
280 // Clear down the segment map
281 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
283 // Clear down the complexity map used for rd
284 vpx_memset(cpi->complexity_map, 0, cm->mi_rows * cm->mi_cols);
286 // Enable segmentation
287 vp9_enable_segmentation((VP9_PTR)cpi);
288 vp9_clearall_segfeatures(seg);
290 // Select delta coding method
291 seg->abs_delta = SEGMENT_DELTADATA;
293 // Segment 0 "Q" feature is disabled so it defaults to the baseline Q
294 vp9_disable_segfeature(seg, 0, SEG_LVL_ALT_Q);
296 // Use some of the segments for in frame Q adjustment
297 for (segment = 1; segment < 3; segment++) {
299 vp9_compute_qdelta_by_rate(cpi, cm->base_qindex,
300 in_frame_q_adj_ratio[segment]);
301 vp9_enable_segfeature(seg, segment, SEG_LVL_ALT_Q);
302 vp9_set_segdata(seg, segment, SEG_LVL_ALT_Q, qindex_delta);
306 static void configure_static_seg_features(VP9_COMP *cpi) {
307 VP9_COMMON *cm = &cpi->common;
308 struct segmentation *seg = &cm->seg;
310 int high_q = (int)(cpi->rc.avg_q > 48.0);
313 // Disable and clear down for KF
314 if (cm->frame_type == KEY_FRAME) {
315 // Clear down the global segmentation map
316 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
318 seg->update_data = 0;
319 cpi->static_mb_pct = 0;
321 // Disable segmentation
322 vp9_disable_segmentation((VP9_PTR)cpi);
324 // Clear down the segment features.
325 vp9_clearall_segfeatures(seg);
326 } else if (cpi->refresh_alt_ref_frame) {
327 // If this is an alt ref frame
328 // Clear down the global segmentation map
329 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
331 seg->update_data = 0;
332 cpi->static_mb_pct = 0;
334 // Disable segmentation and individual segment features by default
335 vp9_disable_segmentation((VP9_PTR)cpi);
336 vp9_clearall_segfeatures(seg);
338 // Scan frames from current to arf frame.
339 // This function re-enables segmentation if appropriate.
340 vp9_update_mbgraph_stats(cpi);
342 // If segmentation was enabled set those features needed for the
346 seg->update_data = 1;
348 qi_delta = vp9_compute_qdelta(
349 cpi, cpi->rc.avg_q, (cpi->rc.avg_q * 0.875));
350 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, (qi_delta - 2));
351 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
353 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
354 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
356 // Where relevant assume segment data is delta data
357 seg->abs_delta = SEGMENT_DELTADATA;
359 } else if (seg->enabled) {
360 // All other frames if segmentation has been enabled
362 // First normal frame in a valid gf or alt ref group
363 if (cpi->rc.frames_since_golden == 0) {
364 // Set up segment features for normal frames in an arf group
365 if (cpi->rc.source_alt_ref_active) {
367 seg->update_data = 1;
368 seg->abs_delta = SEGMENT_DELTADATA;
370 qi_delta = vp9_compute_qdelta(cpi, cpi->rc.avg_q,
371 (cpi->rc.avg_q * 1.125));
372 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, (qi_delta + 2));
373 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
375 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
376 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
378 // Segment coding disabled for compred testing
379 if (high_q || (cpi->static_mb_pct == 100)) {
380 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
381 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
382 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
385 // Disable segmentation and clear down features if alt ref
386 // is not active for this group
388 vp9_disable_segmentation((VP9_PTR)cpi);
390 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
393 seg->update_data = 0;
395 vp9_clearall_segfeatures(seg);
397 } else if (cpi->rc.is_src_frame_alt_ref) {
398 // Special case where we are coding over the top of a previous
400 // Segment coding disabled for compred testing
402 // Enable ref frame features for segment 0 as well
403 vp9_enable_segfeature(seg, 0, SEG_LVL_REF_FRAME);
404 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
406 // All mbs should use ALTREF_FRAME
407 vp9_clear_segdata(seg, 0, SEG_LVL_REF_FRAME);
408 vp9_set_segdata(seg, 0, SEG_LVL_REF_FRAME, ALTREF_FRAME);
409 vp9_clear_segdata(seg, 1, SEG_LVL_REF_FRAME);
410 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
412 // Skip all MBs if high Q (0,0 mv and skip coeffs)
414 vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
415 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
417 // Enable data update
418 seg->update_data = 1;
422 // No updates.. leave things as they are.
424 seg->update_data = 0;
429 // DEBUG: Print out the segment id of each MB in the current frame.
430 static void print_seg_map(VP9_COMP *cpi) {
431 VP9_COMMON *cm = &cpi->common;
434 FILE *statsfile = fopen("segmap.stt", "a");
436 fprintf(statsfile, "%10d\n", cm->current_video_frame);
438 for (row = 0; row < cpi->common.mi_rows; row++) {
439 for (col = 0; col < cpi->common.mi_cols; col++) {
440 fprintf(statsfile, "%10d", cpi->segmentation_map[map_index]);
443 fprintf(statsfile, "\n");
445 fprintf(statsfile, "\n");
450 static void update_reference_segmentation_map(VP9_COMP *cpi) {
451 VP9_COMMON *const cm = &cpi->common;
453 MODE_INFO **mi_8x8, **mi_8x8_ptr = cm->mi_grid_visible;
454 uint8_t *cache_ptr = cm->last_frame_seg_map, *cache;
456 for (row = 0; row < cm->mi_rows; row++) {
459 for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
460 cache[0] = mi_8x8[0]->mbmi.segment_id;
461 mi_8x8_ptr += cm->mode_info_stride;
462 cache_ptr += cm->mi_cols;
466 static void set_rd_speed_thresholds(VP9_COMP *cpi, int mode) {
467 SPEED_FEATURES *sf = &cpi->sf;
470 // Set baseline threshold values
471 for (i = 0; i < MAX_MODES; ++i)
472 sf->thresh_mult[i] = mode == 0 ? -500 : 0;
474 sf->thresh_mult[THR_NEARESTMV] = 0;
475 sf->thresh_mult[THR_NEARESTG] = 0;
476 sf->thresh_mult[THR_NEARESTA] = 0;
478 sf->thresh_mult[THR_DC] += 1000;
480 sf->thresh_mult[THR_NEWMV] += 1000;
481 sf->thresh_mult[THR_NEWA] += 1000;
482 sf->thresh_mult[THR_NEWG] += 1000;
484 sf->thresh_mult[THR_NEARMV] += 1000;
485 sf->thresh_mult[THR_NEARA] += 1000;
486 sf->thresh_mult[THR_COMP_NEARESTLA] += 1000;
487 sf->thresh_mult[THR_COMP_NEARESTGA] += 1000;
489 sf->thresh_mult[THR_TM] += 1000;
491 sf->thresh_mult[THR_COMP_NEARLA] += 1500;
492 sf->thresh_mult[THR_COMP_NEWLA] += 2000;
493 sf->thresh_mult[THR_NEARG] += 1000;
494 sf->thresh_mult[THR_COMP_NEARGA] += 1500;
495 sf->thresh_mult[THR_COMP_NEWGA] += 2000;
497 sf->thresh_mult[THR_ZEROMV] += 2000;
498 sf->thresh_mult[THR_ZEROG] += 2000;
499 sf->thresh_mult[THR_ZEROA] += 2000;
500 sf->thresh_mult[THR_COMP_ZEROLA] += 2500;
501 sf->thresh_mult[THR_COMP_ZEROGA] += 2500;
503 sf->thresh_mult[THR_H_PRED] += 2000;
504 sf->thresh_mult[THR_V_PRED] += 2000;
505 sf->thresh_mult[THR_D45_PRED ] += 2500;
506 sf->thresh_mult[THR_D135_PRED] += 2500;
507 sf->thresh_mult[THR_D117_PRED] += 2500;
508 sf->thresh_mult[THR_D153_PRED] += 2500;
509 sf->thresh_mult[THR_D207_PRED] += 2500;
510 sf->thresh_mult[THR_D63_PRED] += 2500;
512 /* disable frame modes if flags not set */
513 if (!(cpi->ref_frame_flags & VP9_LAST_FLAG)) {
514 sf->thresh_mult[THR_NEWMV ] = INT_MAX;
515 sf->thresh_mult[THR_NEARESTMV] = INT_MAX;
516 sf->thresh_mult[THR_ZEROMV ] = INT_MAX;
517 sf->thresh_mult[THR_NEARMV ] = INT_MAX;
519 if (!(cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
520 sf->thresh_mult[THR_NEARESTG ] = INT_MAX;
521 sf->thresh_mult[THR_ZEROG ] = INT_MAX;
522 sf->thresh_mult[THR_NEARG ] = INT_MAX;
523 sf->thresh_mult[THR_NEWG ] = INT_MAX;
525 if (!(cpi->ref_frame_flags & VP9_ALT_FLAG)) {
526 sf->thresh_mult[THR_NEARESTA ] = INT_MAX;
527 sf->thresh_mult[THR_ZEROA ] = INT_MAX;
528 sf->thresh_mult[THR_NEARA ] = INT_MAX;
529 sf->thresh_mult[THR_NEWA ] = INT_MAX;
532 if ((cpi->ref_frame_flags & (VP9_LAST_FLAG | VP9_ALT_FLAG)) !=
533 (VP9_LAST_FLAG | VP9_ALT_FLAG)) {
534 sf->thresh_mult[THR_COMP_ZEROLA ] = INT_MAX;
535 sf->thresh_mult[THR_COMP_NEARESTLA] = INT_MAX;
536 sf->thresh_mult[THR_COMP_NEARLA ] = INT_MAX;
537 sf->thresh_mult[THR_COMP_NEWLA ] = INT_MAX;
539 if ((cpi->ref_frame_flags & (VP9_GOLD_FLAG | VP9_ALT_FLAG)) !=
540 (VP9_GOLD_FLAG | VP9_ALT_FLAG)) {
541 sf->thresh_mult[THR_COMP_ZEROGA ] = INT_MAX;
542 sf->thresh_mult[THR_COMP_NEARESTGA] = INT_MAX;
543 sf->thresh_mult[THR_COMP_NEARGA ] = INT_MAX;
544 sf->thresh_mult[THR_COMP_NEWGA ] = INT_MAX;
548 static void set_rd_speed_thresholds_sub8x8(VP9_COMP *cpi, int mode) {
549 SPEED_FEATURES *sf = &cpi->sf;
552 for (i = 0; i < MAX_REFS; ++i)
553 sf->thresh_mult_sub8x8[i] = mode == 0 ? -500 : 0;
555 sf->thresh_mult_sub8x8[THR_LAST] += 2500;
556 sf->thresh_mult_sub8x8[THR_GOLD] += 2500;
557 sf->thresh_mult_sub8x8[THR_ALTR] += 2500;
558 sf->thresh_mult_sub8x8[THR_INTRA] += 2500;
559 sf->thresh_mult_sub8x8[THR_COMP_LA] += 4500;
560 sf->thresh_mult_sub8x8[THR_COMP_GA] += 4500;
562 // Check for masked out split cases.
563 for (i = 0; i < MAX_REFS; i++) {
564 if (sf->disable_split_mask & (1 << i))
565 sf->thresh_mult_sub8x8[i] = INT_MAX;
568 // disable mode test if frame flag is not set
569 if (!(cpi->ref_frame_flags & VP9_LAST_FLAG))
570 sf->thresh_mult_sub8x8[THR_LAST] = INT_MAX;
571 if (!(cpi->ref_frame_flags & VP9_GOLD_FLAG))
572 sf->thresh_mult_sub8x8[THR_GOLD] = INT_MAX;
573 if (!(cpi->ref_frame_flags & VP9_ALT_FLAG))
574 sf->thresh_mult_sub8x8[THR_ALTR] = INT_MAX;
575 if ((cpi->ref_frame_flags & (VP9_LAST_FLAG | VP9_ALT_FLAG)) !=
576 (VP9_LAST_FLAG | VP9_ALT_FLAG))
577 sf->thresh_mult_sub8x8[THR_COMP_LA] = INT_MAX;
578 if ((cpi->ref_frame_flags & (VP9_GOLD_FLAG | VP9_ALT_FLAG)) !=
579 (VP9_GOLD_FLAG | VP9_ALT_FLAG))
580 sf->thresh_mult_sub8x8[THR_COMP_GA] = INT_MAX;
583 static void set_good_speed_feature(VP9_COMMON *cm,
587 sf->adaptive_rd_thresh = 1;
588 sf->recode_loop = (speed < 1);
590 sf->use_square_partition_only = !frame_is_intra_only(cm);
591 sf->less_rectangular_check = 1;
592 sf->tx_size_search_method = frame_is_intra_only(cm)
593 ? USE_FULL_RD : USE_LARGESTALL;
595 if (MIN(cm->width, cm->height) >= 720)
596 sf->disable_split_mask = cm->show_frame ?
597 DISABLE_ALL_SPLIT : DISABLE_ALL_INTER_SPLIT;
599 sf->disable_split_mask = DISABLE_COMPOUND_SPLIT;
601 sf->use_rd_breakout = 1;
602 sf->adaptive_motion_search = 1;
603 sf->adaptive_pred_filter_type = 1;
604 sf->auto_mv_step_size = 1;
605 sf->adaptive_rd_thresh = 2;
607 sf->intra_y_mode_mask[TX_32X32] = INTRA_DC_H_V;
608 sf->intra_uv_mode_mask[TX_32X32] = INTRA_DC_H_V;
609 sf->intra_uv_mode_mask[TX_16X16] = INTRA_DC_H_V;
612 sf->use_square_partition_only = !frame_is_intra_only(cm);
613 sf->less_rectangular_check = 1;
614 sf->tx_size_search_method = frame_is_intra_only(cm)
615 ? USE_FULL_RD : USE_LARGESTALL;
617 if (MIN(cm->width, cm->height) >= 720)
618 sf->disable_split_mask = cm->show_frame ?
619 DISABLE_ALL_SPLIT : DISABLE_ALL_INTER_SPLIT;
621 sf->disable_split_mask = LAST_AND_INTRA_SPLIT_ONLY;
623 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
624 FLAG_SKIP_INTRA_BESTINTER |
625 FLAG_SKIP_COMP_BESTINTRA |
626 FLAG_SKIP_INTRA_LOWVAR;
627 sf->use_rd_breakout = 1;
628 sf->adaptive_motion_search = 1;
629 sf->adaptive_pred_filter_type = 2;
630 sf->reference_masking = 1;
631 sf->auto_mv_step_size = 1;
633 sf->disable_filter_search_var_thresh = 50;
634 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
636 sf->auto_min_max_partition_size = 1;
637 sf->use_lastframe_partitioning = LAST_FRAME_PARTITION_LOW_MOTION;
638 sf->adjust_partitioning_from_last_frame = 1;
639 sf->last_partitioning_redo_frequency = 3;
641 sf->adaptive_rd_thresh = 2;
643 sf->use_lp32x32fdct = 1;
644 sf->mode_skip_start = 11;
645 sf->intra_y_mode_mask[TX_32X32] = INTRA_DC_H_V;
646 sf->intra_y_mode_mask[TX_16X16] = INTRA_DC_H_V;
647 sf->intra_uv_mode_mask[TX_32X32] = INTRA_DC_H_V;
648 sf->intra_uv_mode_mask[TX_16X16] = INTRA_DC_H_V;
651 sf->use_square_partition_only = 1;
652 sf->tx_size_search_method = USE_LARGESTALL;
654 if (MIN(cm->width, cm->height) >= 720)
655 sf->disable_split_mask = DISABLE_ALL_SPLIT;
657 sf->disable_split_mask = DISABLE_ALL_INTER_SPLIT;
659 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
660 FLAG_SKIP_INTRA_BESTINTER |
661 FLAG_SKIP_COMP_BESTINTRA |
662 FLAG_SKIP_INTRA_LOWVAR;
664 sf->use_rd_breakout = 1;
665 sf->adaptive_motion_search = 1;
666 sf->adaptive_pred_filter_type = 2;
667 sf->reference_masking = 1;
668 sf->auto_mv_step_size = 1;
670 sf->disable_filter_search_var_thresh = 100;
671 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
673 sf->auto_min_max_partition_size = 1;
674 sf->use_lastframe_partitioning = LAST_FRAME_PARTITION_ALL;
675 sf->adjust_partitioning_from_last_frame = 1;
676 sf->last_partitioning_redo_frequency = 3;
678 sf->use_uv_intra_rd_estimate = 1;
679 sf->skip_encode_sb = 1;
680 sf->use_lp32x32fdct = 1;
681 sf->subpel_iters_per_step = 1;
682 sf->use_fast_coef_updates = 2;
684 sf->adaptive_rd_thresh = 4;
685 sf->mode_skip_start = 6;
688 sf->use_square_partition_only = 1;
689 sf->tx_size_search_method = USE_LARGESTALL;
690 sf->disable_split_mask = DISABLE_ALL_SPLIT;
692 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
693 FLAG_SKIP_INTRA_BESTINTER |
694 FLAG_SKIP_COMP_BESTINTRA |
695 FLAG_SKIP_COMP_REFMISMATCH |
696 FLAG_SKIP_INTRA_LOWVAR |
697 FLAG_EARLY_TERMINATE;
699 sf->use_rd_breakout = 1;
700 sf->adaptive_motion_search = 1;
701 sf->adaptive_pred_filter_type = 2;
702 sf->reference_masking = 1;
703 sf->auto_mv_step_size = 1;
705 sf->disable_filter_search_var_thresh = 200;
706 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
708 sf->auto_min_max_partition_size = 1;
709 sf->use_lastframe_partitioning = LAST_FRAME_PARTITION_ALL;
710 sf->adjust_partitioning_from_last_frame = 1;
711 sf->last_partitioning_redo_frequency = 3;
713 sf->use_uv_intra_rd_estimate = 1;
714 sf->skip_encode_sb = 1;
715 sf->use_lp32x32fdct = 1;
716 sf->subpel_iters_per_step = 1;
717 sf->use_fast_coef_updates = 2;
719 sf->adaptive_rd_thresh = 4;
720 sf->mode_skip_start = 6;
723 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
724 sf->use_one_partition_size_always = 1;
725 sf->always_this_block_size = BLOCK_16X16;
726 sf->tx_size_search_method = frame_is_intra_only(cm) ?
727 USE_FULL_RD : USE_LARGESTALL;
728 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
729 FLAG_SKIP_INTRA_BESTINTER |
730 FLAG_SKIP_COMP_BESTINTRA |
731 FLAG_SKIP_COMP_REFMISMATCH |
732 FLAG_SKIP_INTRA_LOWVAR |
733 FLAG_EARLY_TERMINATE;
734 sf->use_rd_breakout = 1;
735 sf->use_lp32x32fdct = 1;
736 sf->optimize_coefficients = 0;
737 sf->auto_mv_step_size = 1;
738 sf->reference_masking = 1;
740 sf->disable_split_mask = DISABLE_ALL_SPLIT;
741 sf->search_method = HEX;
742 sf->subpel_iters_per_step = 1;
743 sf->disable_split_var_thresh = 64;
744 sf->disable_filter_search_var_thresh = 500;
745 for (i = 0; i < TX_SIZES; i++) {
746 sf->intra_y_mode_mask[i] = INTRA_DC_ONLY;
747 sf->intra_uv_mode_mask[i] = INTRA_DC_ONLY;
749 sf->use_fast_coef_updates = 2;
750 sf->adaptive_rd_thresh = 4;
751 sf->mode_skip_start = 6;
754 static void set_rt_speed_feature(VP9_COMMON *cm,
757 sf->static_segmentation = 0;
758 sf->adaptive_rd_thresh = 1;
759 sf->recode_loop = (speed < 1);
761 sf->use_square_partition_only = !frame_is_intra_only(cm);
762 sf->less_rectangular_check = 1;
763 sf->tx_size_search_method =
764 frame_is_intra_only(cm) ? USE_FULL_RD : USE_LARGESTALL;
766 if (MIN(cm->width, cm->height) >= 720)
767 sf->disable_split_mask = cm->show_frame ?
768 DISABLE_ALL_SPLIT : DISABLE_ALL_INTER_SPLIT;
770 sf->disable_split_mask = DISABLE_COMPOUND_SPLIT;
772 sf->use_rd_breakout = 1;
773 sf->adaptive_motion_search = 1;
774 sf->adaptive_pred_filter_type = 1;
775 sf->auto_mv_step_size = 1;
776 sf->adaptive_rd_thresh = 2;
778 sf->intra_y_mode_mask[TX_32X32] = INTRA_DC_H_V;
779 sf->intra_uv_mode_mask[TX_32X32] = INTRA_DC_H_V;
780 sf->intra_uv_mode_mask[TX_16X16] = INTRA_DC_H_V;
783 sf->use_square_partition_only = !frame_is_intra_only(cm);
784 sf->less_rectangular_check = 1;
785 sf->tx_size_search_method =
786 frame_is_intra_only(cm) ? USE_FULL_RD : USE_LARGESTALL;
788 if (MIN(cm->width, cm->height) >= 720)
789 sf->disable_split_mask = cm->show_frame ?
790 DISABLE_ALL_SPLIT : DISABLE_ALL_INTER_SPLIT;
792 sf->disable_split_mask = LAST_AND_INTRA_SPLIT_ONLY;
794 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH
795 | FLAG_SKIP_INTRA_BESTINTER | FLAG_SKIP_COMP_BESTINTRA
796 | FLAG_SKIP_INTRA_LOWVAR;
798 sf->use_rd_breakout = 1;
799 sf->adaptive_motion_search = 1;
800 sf->adaptive_pred_filter_type = 2;
801 sf->auto_mv_step_size = 1;
802 sf->reference_masking = 1;
804 sf->disable_filter_search_var_thresh = 50;
805 sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
807 sf->auto_min_max_partition_size = 1;
808 sf->use_lastframe_partitioning = LAST_FRAME_PARTITION_LOW_MOTION;
809 sf->adjust_partitioning_from_last_frame = 1;
810 sf->last_partitioning_redo_frequency = 3;
812 sf->adaptive_rd_thresh = 2;
814 sf->use_lp32x32fdct = 1;
815 sf->mode_skip_start = 11;
816 sf->intra_y_mode_mask[TX_32X32] = INTRA_DC_H_V;
817 sf->intra_y_mode_mask[TX_16X16] = INTRA_DC_H_V;
818 sf->intra_uv_mode_mask[TX_32X32] = INTRA_DC_H_V;
819 sf->intra_uv_mode_mask[TX_16X16] = INTRA_DC_H_V;
822 sf->use_square_partition_only = 1;
823 sf->tx_size_search_method = USE_LARGESTALL;
825 if (MIN(cm->width, cm->height) >= 720)
826 sf->disable_split_mask = DISABLE_ALL_SPLIT;
828 sf->disable_split_mask = DISABLE_ALL_INTER_SPLIT;
830 sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH
831 | FLAG_SKIP_INTRA_BESTINTER | FLAG_SKIP_COMP_BESTINTRA
832 | FLAG_SKIP_INTRA_LOWVAR;
834 sf->disable_filter_search_var_thresh = 100;
835 sf->use_lastframe_partitioning = LAST_FRAME_PARTITION_ALL;
836 sf->use_uv_intra_rd_estimate = 1;
837 sf->skip_encode_sb = 1;
838 sf->subpel_iters_per_step = 1;
839 sf->use_fast_coef_updates = 2;
840 sf->adaptive_rd_thresh = 4;
841 sf->mode_skip_start = 6;
844 sf->optimize_coefficients = 0;
848 sf->disable_split_mask = DISABLE_ALL_SPLIT;
849 for (i = 0; i < TX_SIZES; i++) {
850 sf->intra_y_mode_mask[i] = INTRA_DC_H_V;
851 sf->intra_uv_mode_mask[i] = INTRA_DC_ONLY;
856 void vp9_set_speed_features(VP9_COMP *cpi) {
857 SPEED_FEATURES *sf = &cpi->sf;
858 VP9_COMMON *cm = &cpi->common;
859 int mode = cpi->compressor_speed;
860 int speed = cpi->speed;
863 // Convert negative speed to positive
867 for (i = 0; i < MAX_MODES; ++i)
868 cpi->mode_chosen_counts[i] = 0;
870 // best quality defaults
872 sf->search_method = NSTEP;
874 sf->subpel_search_method = SUBPEL_TREE;
875 sf->subpel_iters_per_step = 2;
876 sf->optimize_coefficients = !cpi->oxcf.lossless;
877 sf->reduce_first_step_size = 0;
878 sf->auto_mv_step_size = 0;
879 sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
880 sf->comp_inter_joint_search_thresh = BLOCK_4X4;
881 sf->adaptive_rd_thresh = 0;
882 sf->use_lastframe_partitioning = LAST_FRAME_PARTITION_OFF;
883 sf->tx_size_search_method = USE_FULL_RD;
884 sf->use_lp32x32fdct = 0;
885 sf->adaptive_motion_search = 0;
886 sf->adaptive_pred_filter_type = 0;
887 sf->reference_masking = 0;
888 sf->use_one_partition_size_always = 0;
889 sf->less_rectangular_check = 0;
890 sf->use_square_partition_only = 0;
891 sf->auto_min_max_partition_size = 0;
892 sf->max_partition_size = BLOCK_64X64;
893 sf->min_partition_size = BLOCK_4X4;
894 sf->adjust_partitioning_from_last_frame = 0;
895 sf->last_partitioning_redo_frequency = 4;
896 sf->disable_split_mask = 0;
897 sf->mode_search_skip_flags = 0;
898 sf->disable_split_var_thresh = 0;
899 sf->disable_filter_search_var_thresh = 0;
900 for (i = 0; i < TX_SIZES; i++) {
901 sf->intra_y_mode_mask[i] = ALL_INTRA_MODES;
902 sf->intra_uv_mode_mask[i] = ALL_INTRA_MODES;
904 sf->use_rd_breakout = 0;
905 sf->skip_encode_sb = 0;
906 sf->use_uv_intra_rd_estimate = 0;
907 sf->use_fast_lpf_pick = 0;
908 sf->use_fast_coef_updates = 0;
909 sf->using_small_partition_info = 0;
910 sf->mode_skip_start = MAX_MODES; // Mode index at which mode skip mask set
913 case 0: // This is the best quality mode.
914 cpi->diamond_search_sad = vp9_full_range_search;
917 set_good_speed_feature(cm, sf, speed);
921 set_rt_speed_feature(cm, sf, speed);
925 // Set rd thresholds based on mode and speed setting
926 set_rd_speed_thresholds(cpi, mode);
927 set_rd_speed_thresholds_sub8x8(cpi, mode);
929 // Slow quant, dct and trellis not worthwhile for first pass
930 // so make sure they are always turned off.
931 if (cpi->pass == 1) {
932 sf->optimize_coefficients = 0;
935 // No recode for 1 pass.
936 if (cpi->pass == 0) {
938 sf->optimize_coefficients = 0;
941 cpi->mb.fwd_txm4x4 = vp9_fdct4x4;
942 if (cpi->oxcf.lossless || cpi->mb.e_mbd.lossless) {
943 cpi->mb.fwd_txm4x4 = vp9_fwht4x4;
946 if (cpi->sf.subpel_search_method == SUBPEL_TREE) {
947 cpi->find_fractional_mv_step = vp9_find_best_sub_pixel_tree;
948 cpi->find_fractional_mv_step_comp = vp9_find_best_sub_pixel_comp_tree;
951 cpi->mb.optimize = cpi->sf.optimize_coefficients == 1 && cpi->pass != 1;
954 frames_at_speed[cpi->speed]++;
958 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
959 VP9_COMMON *cm = &cpi->common;
961 cpi->lookahead = vp9_lookahead_init(cpi->oxcf.width, cpi->oxcf.height,
962 cm->subsampling_x, cm->subsampling_y,
963 cpi->oxcf.lag_in_frames);
965 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
966 "Failed to allocate lag buffers");
968 if (vp9_realloc_frame_buffer(&cpi->alt_ref_buffer,
969 cpi->oxcf.width, cpi->oxcf.height,
970 cm->subsampling_x, cm->subsampling_y,
971 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
972 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
973 "Failed to allocate altref buffer");
976 void vp9_alloc_compressor_data(VP9_COMP *cpi) {
977 VP9_COMMON *cm = &cpi->common;
979 if (vp9_alloc_frame_buffers(cm, cm->width, cm->height))
980 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
981 "Failed to allocate frame buffers");
983 if (vp9_alloc_frame_buffer(&cpi->last_frame_uf,
984 cm->width, cm->height,
985 cm->subsampling_x, cm->subsampling_y,
986 VP9_ENC_BORDER_IN_PIXELS))
987 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
988 "Failed to allocate last frame buffer");
990 if (vp9_alloc_frame_buffer(&cpi->scaled_source,
991 cm->width, cm->height,
992 cm->subsampling_x, cm->subsampling_y,
993 VP9_ENC_BORDER_IN_PIXELS))
994 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
995 "Failed to allocate scaled source buffer");
1000 unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
1002 CHECK_MEM_ERROR(cm, cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
1005 vpx_free(cpi->mb_activity_map);
1006 CHECK_MEM_ERROR(cm, cpi->mb_activity_map,
1007 vpx_calloc(sizeof(unsigned int),
1008 cm->mb_rows * cm->mb_cols));
1010 vpx_free(cpi->mb_norm_activity_map);
1011 CHECK_MEM_ERROR(cm, cpi->mb_norm_activity_map,
1012 vpx_calloc(sizeof(unsigned int),
1013 cm->mb_rows * cm->mb_cols));
1015 // 2 contexts per 'mi unit', so that we have one context per 4x4 txfm
1016 // block where mi unit size is 8x8.
1017 vpx_free(cpi->above_context[0]);
1018 CHECK_MEM_ERROR(cm, cpi->above_context[0],
1019 vpx_calloc(2 * mi_cols_aligned_to_sb(cm->mi_cols) *
1021 sizeof(*cpi->above_context[0])));
1023 vpx_free(cpi->above_seg_context);
1024 CHECK_MEM_ERROR(cm, cpi->above_seg_context,
1025 vpx_calloc(mi_cols_aligned_to_sb(cm->mi_cols),
1026 sizeof(*cpi->above_seg_context)));
1030 static void update_frame_size(VP9_COMP *cpi) {
1031 VP9_COMMON *cm = &cpi->common;
1033 vp9_update_frame_size(cm);
1035 // Update size of buffers local to this frame
1036 if (vp9_realloc_frame_buffer(&cpi->last_frame_uf,
1037 cm->width, cm->height,
1038 cm->subsampling_x, cm->subsampling_y,
1039 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
1040 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1041 "Failed to reallocate last frame buffer");
1043 if (vp9_realloc_frame_buffer(&cpi->scaled_source,
1044 cm->width, cm->height,
1045 cm->subsampling_x, cm->subsampling_y,
1046 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
1047 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1048 "Failed to reallocate scaled source buffer");
1051 int y_stride = cpi->scaled_source.y_stride;
1053 if (cpi->sf.search_method == NSTEP) {
1054 vp9_init3smotion_compensation(&cpi->mb, y_stride);
1055 } else if (cpi->sf.search_method == DIAMOND) {
1056 vp9_init_dsmotion_compensation(&cpi->mb, y_stride);
1062 for (i = 1; i < MAX_MB_PLANE; ++i) {
1063 cpi->above_context[i] = cpi->above_context[0] +
1064 i * sizeof(*cpi->above_context[0]) * 2 *
1065 mi_cols_aligned_to_sb(cm->mi_cols);
1071 // Table that converts 0-63 Q range values passed in outside to the Qindex
1072 // range used internally.
1073 static const int q_trans[] = {
1074 0, 4, 8, 12, 16, 20, 24, 28,
1075 32, 36, 40, 44, 48, 52, 56, 60,
1076 64, 68, 72, 76, 80, 84, 88, 92,
1077 96, 100, 104, 108, 112, 116, 120, 124,
1078 128, 132, 136, 140, 144, 148, 152, 156,
1079 160, 164, 168, 172, 176, 180, 184, 188,
1080 192, 196, 200, 204, 208, 212, 216, 220,
1081 224, 228, 232, 236, 240, 244, 249, 255,
1084 int vp9_reverse_trans(int x) {
1087 for (i = 0; i < 64; i++)
1088 if (q_trans[i] >= x)
1094 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
1095 VP9_COMMON *const cm = &cpi->common;
1096 int64_t vbr_max_bits;
1098 if (framerate < 0.1)
1101 cpi->oxcf.framerate = framerate;
1102 cpi->output_framerate = cpi->oxcf.framerate;
1103 cpi->rc.per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth
1104 / cpi->output_framerate);
1105 cpi->rc.av_per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth
1106 / cpi->output_framerate);
1107 cpi->rc.min_frame_bandwidth = (int)(cpi->rc.av_per_frame_bandwidth *
1108 cpi->oxcf.two_pass_vbrmin_section / 100);
1111 cpi->rc.min_frame_bandwidth = MAX(cpi->rc.min_frame_bandwidth,
1112 FRAME_OVERHEAD_BITS);
1114 // A maximum bitrate for a frame is defined.
1115 // The baseline for this aligns with HW implementations that
1116 // can support decode of 1080P content up to a bitrate of MAX_MB_RATE bits
1117 // per 16x16 MB (averaged over a frame). However this limit is extended if
1118 // a very high rate is given on the command line or the the rate cannnot
1119 // be acheived because of a user specificed max q (e.g. when the user
1120 // specifies lossless encode.
1122 vbr_max_bits = ((int64_t)cpi->rc.av_per_frame_bandwidth *
1123 (int64_t)cpi->oxcf.two_pass_vbrmax_section) / 100;
1124 cpi->rc.max_frame_bandwidth =
1125 MAX(MAX((cm->MBs * MAX_MB_RATE), MAXRATE_1080P), vbr_max_bits);
1127 // Set Maximum gf/arf interval
1128 cpi->rc.max_gf_interval = 16;
1130 // Extended interval for genuinely static scenes
1131 cpi->twopass.static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
1133 // Special conditions when alt ref frame enabled in lagged compress mode
1134 if (cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames) {
1135 if (cpi->rc.max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1136 cpi->rc.max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1138 if (cpi->twopass.static_scene_max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1139 cpi->twopass.static_scene_max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1142 if (cpi->rc.max_gf_interval > cpi->twopass.static_scene_max_gf_interval)
1143 cpi->rc.max_gf_interval = cpi->twopass.static_scene_max_gf_interval;
1146 static int64_t rescale(int val, int64_t num, int denom) {
1147 int64_t llnum = num;
1148 int64_t llden = denom;
1149 int64_t llval = val;
1151 return (llval * llnum / llden);
1154 static void set_tile_limits(VP9_COMP *cpi) {
1155 VP9_COMMON *const cm = &cpi->common;
1157 int min_log2_tile_cols, max_log2_tile_cols;
1158 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1160 cm->log2_tile_cols = clamp(cpi->oxcf.tile_columns,
1161 min_log2_tile_cols, max_log2_tile_cols);
1162 cm->log2_tile_rows = cpi->oxcf.tile_rows;
1165 static void init_config(VP9_PTR ptr, VP9_CONFIG *oxcf) {
1166 VP9_COMP *cpi = (VP9_COMP *)(ptr);
1167 VP9_COMMON *const cm = &cpi->common;
1172 cm->version = oxcf->version;
1174 cm->width = oxcf->width;
1175 cm->height = oxcf->height;
1176 cm->subsampling_x = 0;
1177 cm->subsampling_y = 0;
1178 vp9_alloc_compressor_data(cpi);
1180 // change includes all joint functionality
1181 vp9_change_config(ptr, oxcf);
1183 // Initialize active best and worst q and average q values.
1184 cpi->rc.active_worst_quality = cpi->oxcf.worst_allowed_q;
1186 if (cpi->pass == 0 && cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
1187 cpi->rc.avg_frame_qindex[0] = cpi->oxcf.worst_allowed_q;
1188 cpi->rc.avg_frame_qindex[1] = cpi->oxcf.worst_allowed_q;
1189 cpi->rc.avg_frame_qindex[2] = cpi->oxcf.worst_allowed_q;
1191 cpi->rc.avg_frame_qindex[0] = (cpi->oxcf.worst_allowed_q +
1192 cpi->oxcf.best_allowed_q) / 2;
1193 cpi->rc.avg_frame_qindex[1] = (cpi->oxcf.worst_allowed_q +
1194 cpi->oxcf.best_allowed_q) / 2;
1195 cpi->rc.avg_frame_qindex[2] = (cpi->oxcf.worst_allowed_q +
1196 cpi->oxcf.best_allowed_q) / 2;
1198 cpi->rc.last_q[0] = cpi->oxcf.best_allowed_q;
1199 cpi->rc.last_q[1] = cpi->oxcf.best_allowed_q;
1200 cpi->rc.last_q[2] = cpi->oxcf.best_allowed_q;
1202 // Initialise the starting buffer levels
1203 cpi->rc.buffer_level = cpi->oxcf.starting_buffer_level;
1204 cpi->rc.bits_off_target = cpi->oxcf.starting_buffer_level;
1206 cpi->rc.rolling_target_bits = cpi->rc.av_per_frame_bandwidth;
1207 cpi->rc.rolling_actual_bits = cpi->rc.av_per_frame_bandwidth;
1208 cpi->rc.long_rolling_target_bits = cpi->rc.av_per_frame_bandwidth;
1209 cpi->rc.long_rolling_actual_bits = cpi->rc.av_per_frame_bandwidth;
1211 cpi->rc.total_actual_bits = 0;
1212 cpi->rc.total_target_vs_actual = 0;
1214 cpi->static_mb_pct = 0;
1216 cpi->lst_fb_idx = 0;
1217 cpi->gld_fb_idx = 1;
1218 cpi->alt_fb_idx = 2;
1220 cpi->current_layer = 0;
1223 set_tile_limits(cpi);
1225 cpi->fixed_divide[0] = 0;
1226 for (i = 1; i < 512; i++)
1227 cpi->fixed_divide[i] = 0x80000 / i;
1231 void vp9_change_config(VP9_PTR ptr, VP9_CONFIG *oxcf) {
1232 VP9_COMP *cpi = (VP9_COMP *)(ptr);
1233 VP9_COMMON *const cm = &cpi->common;
1238 if (cm->version != oxcf->version) {
1239 cm->version = oxcf->version;
1244 switch (cpi->oxcf.mode) {
1245 // Real time and one pass deprecated in test code base
1246 case MODE_GOODQUALITY:
1248 cpi->compressor_speed = 2;
1249 cpi->oxcf.cpu_used = clamp(cpi->oxcf.cpu_used, -5, 5);
1252 case MODE_FIRSTPASS:
1254 cpi->compressor_speed = 1;
1257 case MODE_SECONDPASS:
1259 cpi->compressor_speed = 1;
1260 cpi->oxcf.cpu_used = clamp(cpi->oxcf.cpu_used, -5, 5);
1263 case MODE_SECONDPASS_BEST:
1265 cpi->compressor_speed = 0;
1269 cpi->oxcf.worst_allowed_q = q_trans[oxcf->worst_allowed_q];
1270 cpi->oxcf.best_allowed_q = q_trans[oxcf->best_allowed_q];
1271 cpi->oxcf.cq_level = q_trans[cpi->oxcf.cq_level];
1273 cpi->oxcf.lossless = oxcf->lossless;
1274 cpi->mb.e_mbd.itxm_add = cpi->oxcf.lossless ? vp9_iwht4x4_add
1276 cpi->rc.baseline_gf_interval = DEFAULT_GF_INTERVAL;
1278 cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
1280 cpi->refresh_golden_frame = 0;
1281 cpi->refresh_last_frame = 1;
1282 cm->refresh_frame_context = 1;
1283 cm->reset_frame_context = 0;
1285 vp9_reset_segment_features(&cm->seg);
1286 set_high_precision_mv(cpi, 0);
1291 for (i = 0; i < MAX_SEGMENTS; i++)
1292 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1295 // local file playback mode == really big buffer
1296 if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK) {
1297 cpi->oxcf.starting_buffer_level = 60000;
1298 cpi->oxcf.optimal_buffer_level = 60000;
1299 cpi->oxcf.maximum_buffer_size = 240000;
1302 // Convert target bandwidth from Kbit/s to Bit/s
1303 cpi->oxcf.target_bandwidth *= 1000;
1305 cpi->oxcf.starting_buffer_level = rescale(cpi->oxcf.starting_buffer_level,
1306 cpi->oxcf.target_bandwidth, 1000);
1308 // Set or reset optimal and maximum buffer levels.
1309 if (cpi->oxcf.optimal_buffer_level == 0)
1310 cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
1312 cpi->oxcf.optimal_buffer_level = rescale(cpi->oxcf.optimal_buffer_level,
1313 cpi->oxcf.target_bandwidth, 1000);
1315 if (cpi->oxcf.maximum_buffer_size == 0)
1316 cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
1318 cpi->oxcf.maximum_buffer_size = rescale(cpi->oxcf.maximum_buffer_size,
1319 cpi->oxcf.target_bandwidth, 1000);
1320 // Under a configuration change, where maximum_buffer_size may change,
1321 // keep buffer level clipped to the maximum allowed buffer size.
1322 if (cpi->rc.bits_off_target > cpi->oxcf.maximum_buffer_size) {
1323 cpi->rc.bits_off_target = cpi->oxcf.maximum_buffer_size;
1324 cpi->rc.buffer_level = cpi->rc.bits_off_target;
1327 // Set up frame rate and related parameters rate control values.
1328 vp9_new_framerate(cpi, cpi->oxcf.framerate);
1330 // Set absolute upper and lower quality limits
1331 cpi->rc.worst_quality = cpi->oxcf.worst_allowed_q;
1332 cpi->rc.best_quality = cpi->oxcf.best_allowed_q;
1334 // active values should only be modified if out of new range
1335 cpi->rc.active_worst_quality = clamp(cpi->rc.active_worst_quality,
1336 cpi->rc.best_quality,
1337 cpi->rc.worst_quality);
1339 cpi->cq_target_quality = cpi->oxcf.cq_level;
1341 cm->mcomp_filter_type = DEFAULT_INTERP_FILTER;
1343 cpi->target_bandwidth = cpi->oxcf.target_bandwidth;
1345 cm->display_width = cpi->oxcf.width;
1346 cm->display_height = cpi->oxcf.height;
1348 // VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs)
1349 cpi->oxcf.sharpness = MIN(7, cpi->oxcf.sharpness);
1351 cpi->common.lf.sharpness_level = cpi->oxcf.sharpness;
1353 if (cpi->initial_width) {
1354 // Increasing the size of the frame beyond the first seen frame, or some
1355 // otherwise signalled maximum size, is not supported.
1356 // TODO(jkoleszar): exit gracefully.
1357 assert(cm->width <= cpi->initial_width);
1358 assert(cm->height <= cpi->initial_height);
1360 update_frame_size(cpi);
1362 cpi->speed = cpi->oxcf.cpu_used;
1364 if (cpi->oxcf.lag_in_frames == 0) {
1365 // force to allowlag to 0 if lag_in_frames is 0;
1366 cpi->oxcf.allow_lag = 0;
1367 } else if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS) {
1368 // Limit on lag buffers as these are not currently dynamically allocated
1369 cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
1373 #if CONFIG_MULTIPLE_ARF
1374 vp9_zero(cpi->alt_ref_source);
1376 cpi->alt_ref_source = NULL;
1378 cpi->rc.is_src_frame_alt_ref = 0;
1381 // Experimental RD Code
1382 cpi->frame_distortion = 0;
1383 cpi->last_frame_distortion = 0;
1386 set_tile_limits(cpi);
1388 cpi->ext_refresh_frame_flags_pending = 0;
1389 cpi->ext_refresh_frame_context_pending = 0;
1392 #define M_LOG2_E 0.693147180559945309417
1393 #define log2f(x) (log (x) / (float) M_LOG2_E)
1395 static void cal_nmvjointsadcost(int *mvjointsadcost) {
1396 mvjointsadcost[0] = 600;
1397 mvjointsadcost[1] = 300;
1398 mvjointsadcost[2] = 300;
1399 mvjointsadcost[0] = 300;
1402 static void cal_nmvsadcosts(int *mvsadcost[2]) {
1405 mvsadcost[0][0] = 0;
1406 mvsadcost[1][0] = 0;
1409 double z = 256 * (2 * (log2f(8 * i) + .6));
1410 mvsadcost[0][i] = (int)z;
1411 mvsadcost[1][i] = (int)z;
1412 mvsadcost[0][-i] = (int)z;
1413 mvsadcost[1][-i] = (int)z;
1414 } while (++i <= MV_MAX);
1417 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
1420 mvsadcost[0][0] = 0;
1421 mvsadcost[1][0] = 0;
1424 double z = 256 * (2 * (log2f(8 * i) + .6));
1425 mvsadcost[0][i] = (int)z;
1426 mvsadcost[1][i] = (int)z;
1427 mvsadcost[0][-i] = (int)z;
1428 mvsadcost[1][-i] = (int)z;
1429 } while (++i <= MV_MAX);
1432 static void alloc_mode_context(VP9_COMMON *cm, int num_4x4_blk,
1433 PICK_MODE_CONTEXT *ctx) {
1434 int num_pix = num_4x4_blk << 4;
1436 ctx->num_4x4_blk = num_4x4_blk;
1437 CHECK_MEM_ERROR(cm, ctx->zcoeff_blk,
1438 vpx_calloc(num_4x4_blk, sizeof(uint8_t)));
1439 for (i = 0; i < MAX_MB_PLANE; ++i) {
1440 for (k = 0; k < 3; ++k) {
1441 CHECK_MEM_ERROR(cm, ctx->coeff[i][k],
1442 vpx_memalign(16, num_pix * sizeof(int16_t)));
1443 CHECK_MEM_ERROR(cm, ctx->qcoeff[i][k],
1444 vpx_memalign(16, num_pix * sizeof(int16_t)));
1445 CHECK_MEM_ERROR(cm, ctx->dqcoeff[i][k],
1446 vpx_memalign(16, num_pix * sizeof(int16_t)));
1447 CHECK_MEM_ERROR(cm, ctx->eobs[i][k],
1448 vpx_memalign(16, num_pix * sizeof(uint16_t)));
1449 ctx->coeff_pbuf[i][k] = ctx->coeff[i][k];
1450 ctx->qcoeff_pbuf[i][k] = ctx->qcoeff[i][k];
1451 ctx->dqcoeff_pbuf[i][k] = ctx->dqcoeff[i][k];
1452 ctx->eobs_pbuf[i][k] = ctx->eobs[i][k];
1457 static void free_mode_context(PICK_MODE_CONTEXT *ctx) {
1459 vpx_free(ctx->zcoeff_blk);
1460 ctx->zcoeff_blk = 0;
1461 for (i = 0; i < MAX_MB_PLANE; ++i) {
1462 for (k = 0; k < 3; ++k) {
1463 vpx_free(ctx->coeff[i][k]);
1464 ctx->coeff[i][k] = 0;
1465 vpx_free(ctx->qcoeff[i][k]);
1466 ctx->qcoeff[i][k] = 0;
1467 vpx_free(ctx->dqcoeff[i][k]);
1468 ctx->dqcoeff[i][k] = 0;
1469 vpx_free(ctx->eobs[i][k]);
1470 ctx->eobs[i][k] = 0;
1475 static void init_pick_mode_context(VP9_COMP *cpi) {
1477 VP9_COMMON *const cm = &cpi->common;
1478 MACROBLOCK *const x = &cpi->mb;
1481 for (i = 0; i < BLOCK_SIZES; ++i) {
1482 const int num_4x4_w = num_4x4_blocks_wide_lookup[i];
1483 const int num_4x4_h = num_4x4_blocks_high_lookup[i];
1484 const int num_4x4_blk = MAX(4, num_4x4_w * num_4x4_h);
1485 if (i < BLOCK_16X16) {
1486 for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1487 for (x->mb_index = 0; x->mb_index < 4; ++x->mb_index) {
1488 for (x->b_index = 0; x->b_index < 16 / num_4x4_blk; ++x->b_index) {
1489 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1490 alloc_mode_context(cm, num_4x4_blk, ctx);
1494 } else if (i < BLOCK_32X32) {
1495 for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1496 for (x->mb_index = 0; x->mb_index < 64 / num_4x4_blk; ++x->mb_index) {
1497 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1498 ctx->num_4x4_blk = num_4x4_blk;
1499 alloc_mode_context(cm, num_4x4_blk, ctx);
1502 } else if (i < BLOCK_64X64) {
1503 for (x->sb_index = 0; x->sb_index < 256 / num_4x4_blk; ++x->sb_index) {
1504 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1505 ctx->num_4x4_blk = num_4x4_blk;
1506 alloc_mode_context(cm, num_4x4_blk, ctx);
1509 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1510 ctx->num_4x4_blk = num_4x4_blk;
1511 alloc_mode_context(cm, num_4x4_blk, ctx);
1516 static void free_pick_mode_context(MACROBLOCK *x) {
1519 for (i = 0; i < BLOCK_SIZES; ++i) {
1520 const int num_4x4_w = num_4x4_blocks_wide_lookup[i];
1521 const int num_4x4_h = num_4x4_blocks_high_lookup[i];
1522 const int num_4x4_blk = MAX(4, num_4x4_w * num_4x4_h);
1523 if (i < BLOCK_16X16) {
1524 for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1525 for (x->mb_index = 0; x->mb_index < 4; ++x->mb_index) {
1526 for (x->b_index = 0; x->b_index < 16 / num_4x4_blk; ++x->b_index) {
1527 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1528 free_mode_context(ctx);
1532 } else if (i < BLOCK_32X32) {
1533 for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1534 for (x->mb_index = 0; x->mb_index < 64 / num_4x4_blk; ++x->mb_index) {
1535 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1536 free_mode_context(ctx);
1539 } else if (i < BLOCK_64X64) {
1540 for (x->sb_index = 0; x->sb_index < 256 / num_4x4_blk; ++x->sb_index) {
1541 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1542 free_mode_context(ctx);
1545 PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1546 free_mode_context(ctx);
1551 VP9_PTR vp9_create_compressor(VP9_CONFIG *oxcf) {
1561 cpi = ctx.cpi = vpx_memalign(32, sizeof(VP9_COMP));
1562 // Check that the CPI instance is valid
1570 if (setjmp(cm->error.jmp)) {
1571 VP9_PTR ptr = ctx.ptr;
1573 ctx.cpi->common.error.setjmp = 0;
1574 vp9_remove_compressor(&ptr);
1578 cm->error.setjmp = 1;
1580 CHECK_MEM_ERROR(cm, cpi->mb.ss, vpx_calloc(sizeof(search_site),
1581 (MAX_MVSEARCH_STEPS * 8) + 1));
1583 vp9_create_common(cm);
1585 init_config((VP9_PTR)cpi, oxcf);
1587 init_pick_mode_context(cpi);
1589 cm->current_video_frame = 0;
1591 // Set reference frame sign bias for ALTREF frame to 1 (for now)
1592 cm->ref_frame_sign_bias[ALTREF_FRAME] = 1;
1594 cpi->rc.baseline_gf_interval = DEFAULT_GF_INTERVAL;
1596 cpi->gold_is_last = 0;
1597 cpi->alt_is_last = 0;
1598 cpi->gold_is_alt = 0;
1600 // Spatial scalability
1601 cpi->number_spatial_layers = oxcf->ss_number_layers;
1603 // Create the encoder segmentation map and set all entries to 0
1604 CHECK_MEM_ERROR(cm, cpi->segmentation_map,
1605 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1607 // Create a complexity map used for rd adjustment
1608 CHECK_MEM_ERROR(cm, cpi->complexity_map,
1609 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1612 // And a place holder structure is the coding context
1613 // for use if we want to save and restore it
1614 CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
1615 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1617 CHECK_MEM_ERROR(cm, cpi->active_map, vpx_calloc(cm->MBs, 1));
1618 vpx_memset(cpi->active_map, 1, cm->MBs);
1619 cpi->active_map_enabled = 0;
1621 for (i = 0; i < (sizeof(cpi->mbgraph_stats) /
1622 sizeof(cpi->mbgraph_stats[0])); i++) {
1623 CHECK_MEM_ERROR(cm, cpi->mbgraph_stats[i].mb_stats,
1624 vpx_calloc(cm->MBs *
1625 sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
1628 #ifdef ENTROPY_STATS
1630 init_context_counters();
1634 init_tx_count_stats();
1635 init_switchable_interp_stats();
1638 /*Initialize the feed-forward activity masking.*/
1639 cpi->activity_avg = 90 << 12;
1640 cpi->key_frame_frequency = cpi->oxcf.key_freq;
1642 cpi->rc.frames_since_key = 8; // Sensible default for first frame.
1643 cpi->rc.this_key_frame_forced = 0;
1644 cpi->rc.next_key_frame_forced = 0;
1646 cpi->rc.source_alt_ref_pending = 0;
1647 cpi->rc.source_alt_ref_active = 0;
1648 cpi->refresh_alt_ref_frame = 0;
1650 #if CONFIG_MULTIPLE_ARF
1651 // Turn multiple ARF usage on/off. This is a quick hack for the initial test
1652 // version. It should eventually be set via the codec API.
1653 cpi->multi_arf_enabled = 1;
1655 if (cpi->multi_arf_enabled) {
1656 cpi->sequence_number = 0;
1657 cpi->frame_coding_order_period = 0;
1658 vp9_zero(cpi->frame_coding_order);
1659 vp9_zero(cpi->arf_buffer_idx);
1663 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1664 #if CONFIG_INTERNAL_STATS
1665 cpi->b_calculate_ssimg = 0;
1670 if (cpi->b_calculate_psnr) {
1675 cpi->total_sq_error = 0;
1676 cpi->total_samples = 0;
1678 cpi->totalp_y = 0.0;
1679 cpi->totalp_u = 0.0;
1680 cpi->totalp_v = 0.0;
1682 cpi->totalp_sq_error = 0;
1683 cpi->totalp_samples = 0;
1685 cpi->tot_recode_hits = 0;
1686 cpi->summed_quality = 0;
1687 cpi->summed_weights = 0;
1688 cpi->summedp_quality = 0;
1689 cpi->summedp_weights = 0;
1692 if (cpi->b_calculate_ssimg) {
1693 cpi->total_ssimg_y = 0;
1694 cpi->total_ssimg_u = 0;
1695 cpi->total_ssimg_v = 0;
1696 cpi->total_ssimg_all = 0;
1701 cpi->first_time_stamp_ever = INT64_MAX;
1703 cpi->rc.frames_till_gf_update_due = 0;
1705 cpi->rc.ni_av_qi = cpi->oxcf.worst_allowed_q;
1706 cpi->rc.ni_tot_qi = 0;
1707 cpi->rc.ni_frames = 0;
1708 cpi->rc.tot_q = 0.0;
1709 cpi->rc.avg_q = vp9_convert_qindex_to_q(cpi->oxcf.worst_allowed_q);
1711 cpi->rc.rate_correction_factor = 1.0;
1712 cpi->rc.key_frame_rate_correction_factor = 1.0;
1713 cpi->rc.gf_rate_correction_factor = 1.0;
1715 cal_nmvjointsadcost(cpi->mb.nmvjointsadcost);
1716 cpi->mb.nmvcost[0] = &cpi->mb.nmvcosts[0][MV_MAX];
1717 cpi->mb.nmvcost[1] = &cpi->mb.nmvcosts[1][MV_MAX];
1718 cpi->mb.nmvsadcost[0] = &cpi->mb.nmvsadcosts[0][MV_MAX];
1719 cpi->mb.nmvsadcost[1] = &cpi->mb.nmvsadcosts[1][MV_MAX];
1720 cal_nmvsadcosts(cpi->mb.nmvsadcost);
1722 cpi->mb.nmvcost_hp[0] = &cpi->mb.nmvcosts_hp[0][MV_MAX];
1723 cpi->mb.nmvcost_hp[1] = &cpi->mb.nmvcosts_hp[1][MV_MAX];
1724 cpi->mb.nmvsadcost_hp[0] = &cpi->mb.nmvsadcosts_hp[0][MV_MAX];
1725 cpi->mb.nmvsadcost_hp[1] = &cpi->mb.nmvsadcosts_hp[1][MV_MAX];
1726 cal_nmvsadcosts_hp(cpi->mb.nmvsadcost_hp);
1728 #ifdef OUTPUT_YUV_SRC
1729 yuv_file = fopen("bd.yuv", "ab");
1731 #ifdef OUTPUT_YUV_REC
1732 yuv_rec_file = fopen("rec.yuv", "wb");
1736 framepsnr = fopen("framepsnr.stt", "a");
1737 kf_list = fopen("kf_list.stt", "w");
1740 cpi->output_pkt_list = oxcf->output_pkt_list;
1742 cpi->enable_encode_breakout = 1;
1744 if (cpi->pass == 1) {
1745 vp9_init_first_pass(cpi);
1746 } else if (cpi->pass == 2) {
1747 size_t packet_sz = sizeof(FIRSTPASS_STATS);
1748 int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
1750 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1751 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1752 cpi->twopass.stats_in_end = (void *)((char *)cpi->twopass.stats_in
1753 + (packets - 1) * packet_sz);
1754 vp9_init_second_pass(cpi);
1757 vp9_set_speed_features(cpi);
1759 // Default rd threshold factors for mode selection
1760 for (i = 0; i < BLOCK_SIZES; ++i) {
1761 for (j = 0; j < MAX_MODES; ++j)
1762 cpi->rd_thresh_freq_fact[i][j] = 32;
1763 for (j = 0; j < MAX_REFS; ++j)
1764 cpi->rd_thresh_freq_sub8x8[i][j] = 32;
1767 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SVFHH, SVFHV, SVFHHV, \
1768 SDX3F, SDX8F, SDX4DF)\
1769 cpi->fn_ptr[BT].sdf = SDF; \
1770 cpi->fn_ptr[BT].sdaf = SDAF; \
1771 cpi->fn_ptr[BT].vf = VF; \
1772 cpi->fn_ptr[BT].svf = SVF; \
1773 cpi->fn_ptr[BT].svaf = SVAF; \
1774 cpi->fn_ptr[BT].svf_halfpix_h = SVFHH; \
1775 cpi->fn_ptr[BT].svf_halfpix_v = SVFHV; \
1776 cpi->fn_ptr[BT].svf_halfpix_hv = SVFHHV; \
1777 cpi->fn_ptr[BT].sdx3f = SDX3F; \
1778 cpi->fn_ptr[BT].sdx8f = SDX8F; \
1779 cpi->fn_ptr[BT].sdx4df = SDX4DF;
1781 BFP(BLOCK_32X16, vp9_sad32x16, vp9_sad32x16_avg,
1782 vp9_variance32x16, vp9_sub_pixel_variance32x16,
1783 vp9_sub_pixel_avg_variance32x16, NULL, NULL,
1787 BFP(BLOCK_16X32, vp9_sad16x32, vp9_sad16x32_avg,
1788 vp9_variance16x32, vp9_sub_pixel_variance16x32,
1789 vp9_sub_pixel_avg_variance16x32, NULL, NULL,
1793 BFP(BLOCK_64X32, vp9_sad64x32, vp9_sad64x32_avg,
1794 vp9_variance64x32, vp9_sub_pixel_variance64x32,
1795 vp9_sub_pixel_avg_variance64x32, NULL, NULL,
1799 BFP(BLOCK_32X64, vp9_sad32x64, vp9_sad32x64_avg,
1800 vp9_variance32x64, vp9_sub_pixel_variance32x64,
1801 vp9_sub_pixel_avg_variance32x64, NULL, NULL,
1805 BFP(BLOCK_32X32, vp9_sad32x32, vp9_sad32x32_avg,
1806 vp9_variance32x32, vp9_sub_pixel_variance32x32,
1807 vp9_sub_pixel_avg_variance32x32, vp9_variance_halfpixvar32x32_h,
1808 vp9_variance_halfpixvar32x32_v,
1809 vp9_variance_halfpixvar32x32_hv, vp9_sad32x32x3, vp9_sad32x32x8,
1812 BFP(BLOCK_64X64, vp9_sad64x64, vp9_sad64x64_avg,
1813 vp9_variance64x64, vp9_sub_pixel_variance64x64,
1814 vp9_sub_pixel_avg_variance64x64, vp9_variance_halfpixvar64x64_h,
1815 vp9_variance_halfpixvar64x64_v,
1816 vp9_variance_halfpixvar64x64_hv, vp9_sad64x64x3, vp9_sad64x64x8,
1819 BFP(BLOCK_16X16, vp9_sad16x16, vp9_sad16x16_avg,
1820 vp9_variance16x16, vp9_sub_pixel_variance16x16,
1821 vp9_sub_pixel_avg_variance16x16, vp9_variance_halfpixvar16x16_h,
1822 vp9_variance_halfpixvar16x16_v,
1823 vp9_variance_halfpixvar16x16_hv, vp9_sad16x16x3, vp9_sad16x16x8,
1826 BFP(BLOCK_16X8, vp9_sad16x8, vp9_sad16x8_avg,
1827 vp9_variance16x8, vp9_sub_pixel_variance16x8,
1828 vp9_sub_pixel_avg_variance16x8, NULL, NULL, NULL,
1829 vp9_sad16x8x3, vp9_sad16x8x8, vp9_sad16x8x4d)
1831 BFP(BLOCK_8X16, vp9_sad8x16, vp9_sad8x16_avg,
1832 vp9_variance8x16, vp9_sub_pixel_variance8x16,
1833 vp9_sub_pixel_avg_variance8x16, NULL, NULL, NULL,
1834 vp9_sad8x16x3, vp9_sad8x16x8, vp9_sad8x16x4d)
1836 BFP(BLOCK_8X8, vp9_sad8x8, vp9_sad8x8_avg,
1837 vp9_variance8x8, vp9_sub_pixel_variance8x8,
1838 vp9_sub_pixel_avg_variance8x8, NULL, NULL, NULL,
1839 vp9_sad8x8x3, vp9_sad8x8x8, vp9_sad8x8x4d)
1841 BFP(BLOCK_8X4, vp9_sad8x4, vp9_sad8x4_avg,
1842 vp9_variance8x4, vp9_sub_pixel_variance8x4,
1843 vp9_sub_pixel_avg_variance8x4, NULL, NULL,
1844 NULL, NULL, vp9_sad8x4x8,
1847 BFP(BLOCK_4X8, vp9_sad4x8, vp9_sad4x8_avg,
1848 vp9_variance4x8, vp9_sub_pixel_variance4x8,
1849 vp9_sub_pixel_avg_variance4x8, NULL, NULL,
1850 NULL, NULL, vp9_sad4x8x8,
1853 BFP(BLOCK_4X4, vp9_sad4x4, vp9_sad4x4_avg,
1854 vp9_variance4x4, vp9_sub_pixel_variance4x4,
1855 vp9_sub_pixel_avg_variance4x4, NULL, NULL, NULL,
1856 vp9_sad4x4x3, vp9_sad4x4x8, vp9_sad4x4x4d)
1858 cpi->full_search_sad = vp9_full_search_sad;
1859 cpi->diamond_search_sad = vp9_diamond_search_sad;
1860 cpi->refining_search_sad = vp9_refining_search_sad;
1862 /* vp9_init_quantizer() is first called here. Add check in
1863 * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
1864 * called later when needed. This will avoid unnecessary calls of
1865 * vp9_init_quantizer() for every frame.
1867 vp9_init_quantizer(cpi);
1869 vp9_loop_filter_init(cm);
1871 cm->error.setjmp = 0;
1873 vp9_zero(cpi->common.counts.uv_mode);
1875 #ifdef MODE_TEST_HIT_STATS
1876 vp9_zero(cpi->mode_test_hits);
1879 return (VP9_PTR) cpi;
1882 void vp9_remove_compressor(VP9_PTR *ptr) {
1883 VP9_COMP *cpi = (VP9_COMP *)(*ptr);
1889 if (cpi && (cpi->common.current_video_frame > 0)) {
1890 if (cpi->pass == 2) {
1891 vp9_end_second_pass(cpi);
1895 if (cpi->pass != 1) {
1896 write_tx_count_stats();
1897 write_switchable_interp_stats();
1901 #if CONFIG_INTERNAL_STATS
1903 vp9_clear_system_state();
1905 // printf("\n8x8-4x4:%d-%d\n", cpi->t8x8_count, cpi->t4x4_count);
1906 if (cpi->pass != 1) {
1907 FILE *f = fopen("opsnr.stt", "a");
1908 double time_encoded = (cpi->last_end_time_stamp_seen
1909 - cpi->first_time_stamp_ever) / 10000000.000;
1910 double total_encode_time = (cpi->time_receive_data +
1911 cpi->time_compress_data) / 1000.000;
1912 double dr = (double)cpi->bytes * (double) 8 / (double)1000
1915 if (cpi->b_calculate_psnr) {
1916 const double total_psnr = vp9_mse2psnr(cpi->total_samples, 255.0,
1917 cpi->total_sq_error);
1918 const double totalp_psnr = vp9_mse2psnr(cpi->totalp_samples, 255.0,
1919 cpi->totalp_sq_error);
1920 const double total_ssim = 100 * pow(cpi->summed_quality /
1921 cpi->summed_weights, 8.0);
1922 const double totalp_ssim = 100 * pow(cpi->summedp_quality /
1923 cpi->summedp_weights, 8.0);
1925 fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
1926 "VPXSSIM\tVPSSIMP\t Time(ms)\n");
1927 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",
1928 dr, cpi->total / cpi->count, total_psnr,
1929 cpi->totalp / cpi->count, totalp_psnr, total_ssim, totalp_ssim,
1933 if (cpi->b_calculate_ssimg) {
1934 fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t Time(ms)\n");
1935 fprintf(f, "%7.2f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
1936 cpi->total_ssimg_y / cpi->count,
1937 cpi->total_ssimg_u / cpi->count,
1938 cpi->total_ssimg_v / cpi->count,
1939 cpi->total_ssimg_all / cpi->count, total_encode_time);
1947 #ifdef MODE_TEST_HIT_STATS
1948 if (cpi->pass != 1) {
1949 double norm_per_pixel_mode_tests = 0;
1950 double norm_counts[BLOCK_SIZES];
1953 int norm_factors[BLOCK_SIZES] =
1954 {256, 128, 128, 64, 32, 32, 16, 8, 8, 4, 2, 2, 1};
1955 FILE *f = fopen("mode_hit_stats.stt", "a");
1957 // On average, how many mode tests do we do
1958 for (i = 0; i < BLOCK_SIZES; ++i) {
1959 norm_counts[i] = (double)cpi->mode_test_hits[i] /
1960 (double)norm_factors[i];
1961 norm_per_pixel_mode_tests += norm_counts[i];
1963 // Convert to a number per 64x64 and per frame
1964 sb64_per_frame = ((cpi->common.height + 63) / 64) *
1965 ((cpi->common.width + 63) / 64);
1966 norm_per_pixel_mode_tests =
1967 norm_per_pixel_mode_tests /
1968 (double)(cpi->common.current_video_frame * sb64_per_frame);
1970 fprintf(f, "%6.4f\n", norm_per_pixel_mode_tests);
1975 #if defined(SECTIONBITS_OUTPUT)
1979 FILE *f = fopen("tokenbits.stt", "a");
1981 for (i = 0; i < 28; i++)
1982 fprintf(f, "%8d", (int)(Sectionbits[i] / 256));
1992 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
1993 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
1994 printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
1995 cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
1996 cpi->time_compress_data / 1000,
1997 (cpi->time_receive_data + cpi->time_compress_data) / 1000);
2002 free_pick_mode_context(&cpi->mb);
2003 dealloc_compressor_data(cpi);
2004 vpx_free(cpi->mb.ss);
2007 for (i = 0; i < sizeof(cpi->mbgraph_stats) /
2008 sizeof(cpi->mbgraph_stats[0]); ++i) {
2009 vpx_free(cpi->mbgraph_stats[i].mb_stats);
2012 vp9_remove_common(&cpi->common);
2016 #ifdef OUTPUT_YUV_SRC
2019 #ifdef OUTPUT_YUV_REC
2020 fclose(yuv_rec_file);
2038 static uint64_t calc_plane_error(const uint8_t *orig, int orig_stride,
2039 const uint8_t *recon, int recon_stride,
2040 unsigned int cols, unsigned int rows) {
2041 unsigned int row, col;
2042 uint64_t total_sse = 0;
2045 for (row = 0; row + 16 <= rows; row += 16) {
2046 for (col = 0; col + 16 <= cols; col += 16) {
2049 vp9_mse16x16(orig + col, orig_stride, recon + col, recon_stride, &sse);
2053 /* Handle odd-sized width */
2055 unsigned int border_row, border_col;
2056 const uint8_t *border_orig = orig;
2057 const uint8_t *border_recon = recon;
2059 for (border_row = 0; border_row < 16; border_row++) {
2060 for (border_col = col; border_col < cols; border_col++) {
2061 diff = border_orig[border_col] - border_recon[border_col];
2062 total_sse += diff * diff;
2065 border_orig += orig_stride;
2066 border_recon += recon_stride;
2070 orig += orig_stride * 16;
2071 recon += recon_stride * 16;
2074 /* Handle odd-sized height */
2075 for (; row < rows; row++) {
2076 for (col = 0; col < cols; col++) {
2077 diff = orig[col] - recon[col];
2078 total_sse += diff * diff;
2081 orig += orig_stride;
2082 recon += recon_stride;
2089 double psnr[4]; // total/y/u/v
2090 uint64_t sse[4]; // total/y/u/v
2091 uint32_t samples[4]; // total/y/u/v
2094 static void calc_psnr(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b,
2096 const int widths[3] = {a->y_width, a->uv_width, a->uv_width };
2097 const int heights[3] = {a->y_height, a->uv_height, a->uv_height};
2098 const uint8_t *a_planes[3] = {a->y_buffer, a->u_buffer, a->v_buffer };
2099 const int a_strides[3] = {a->y_stride, a->uv_stride, a->uv_stride};
2100 const uint8_t *b_planes[3] = {b->y_buffer, b->u_buffer, b->v_buffer };
2101 const int b_strides[3] = {b->y_stride, b->uv_stride, b->uv_stride};
2103 uint64_t total_sse = 0;
2104 uint32_t total_samples = 0;
2106 for (i = 0; i < 3; ++i) {
2107 const int w = widths[i];
2108 const int h = heights[i];
2109 const uint32_t samples = w * h;
2110 const double sse = calc_plane_error(a_planes[i], a_strides[i],
2111 b_planes[i], b_strides[i],
2113 psnr->sse[1 + i] = sse;
2114 psnr->samples[1 + i] = samples;
2115 psnr->psnr[1 + i] = vp9_mse2psnr(samples, 255.0, sse);
2118 total_samples += samples;
2121 psnr->sse[0] = total_sse;
2122 psnr->samples[0] = total_samples;
2123 psnr->psnr[0] = vp9_mse2psnr(total_samples, 255.0, total_sse);
2126 static void generate_psnr_packet(VP9_COMP *cpi) {
2127 struct vpx_codec_cx_pkt pkt;
2130 calc_psnr(cpi->Source, cpi->common.frame_to_show, &psnr);
2131 for (i = 0; i < 4; ++i) {
2132 pkt.data.psnr.samples[i] = psnr.samples[i];
2133 pkt.data.psnr.sse[i] = psnr.sse[i];
2134 pkt.data.psnr.psnr[i] = psnr.psnr[i];
2136 pkt.kind = VPX_CODEC_PSNR_PKT;
2137 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2140 int vp9_use_as_reference(VP9_PTR ptr, int ref_frame_flags) {
2141 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2143 if (ref_frame_flags > 7)
2146 cpi->ref_frame_flags = ref_frame_flags;
2150 int vp9_update_reference(VP9_PTR ptr, int ref_frame_flags) {
2151 VP9_COMP *cpi = (VP9_COMP *)(ptr);
2153 if (ref_frame_flags > 7)
2156 cpi->ext_refresh_golden_frame = 0;
2157 cpi->ext_refresh_alt_ref_frame = 0;
2158 cpi->ext_refresh_last_frame = 0;
2160 if (ref_frame_flags & VP9_LAST_FLAG)
2161 cpi->ext_refresh_last_frame = 1;
2163 if (ref_frame_flags & VP9_GOLD_FLAG)
2164 cpi->ext_refresh_golden_frame = 1;
2166 if (ref_frame_flags & VP9_ALT_FLAG)
2167 cpi->ext_refresh_alt_ref_frame = 1;
2169 cpi->ext_refresh_frame_flags_pending = 1;
2173 static YV12_BUFFER_CONFIG *get_vp9_ref_frame_buffer(VP9_COMP *cpi,
2174 VP9_REFFRAME ref_frame_flag) {
2175 MV_REFERENCE_FRAME ref_frame = NONE;
2176 if (ref_frame_flag == VP9_LAST_FLAG)
2177 ref_frame = LAST_FRAME;
2178 else if (ref_frame_flag == VP9_GOLD_FLAG)
2179 ref_frame = GOLDEN_FRAME;
2180 else if (ref_frame_flag == VP9_ALT_FLAG)
2181 ref_frame = ALTREF_FRAME;
2183 return ref_frame == NONE ? NULL : get_ref_frame_buffer(cpi, ref_frame);
2186 int vp9_copy_reference_enc(VP9_PTR ptr, VP9_REFFRAME ref_frame_flag,
2187 YV12_BUFFER_CONFIG *sd) {
2188 VP9_COMP *const cpi = (VP9_COMP *)ptr;
2189 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2191 vp8_yv12_copy_frame(cfg, sd);
2198 int vp9_get_reference_enc(VP9_PTR ptr, int index, YV12_BUFFER_CONFIG **fb) {
2199 VP9_COMP *cpi = (VP9_COMP *)ptr;
2200 VP9_COMMON *cm = &cpi->common;
2202 if (index < 0 || index >= REF_FRAMES)
2205 *fb = &cm->yv12_fb[cm->ref_frame_map[index]];
2209 int vp9_set_reference_enc(VP9_PTR ptr, VP9_REFFRAME ref_frame_flag,
2210 YV12_BUFFER_CONFIG *sd) {
2211 VP9_COMP *cpi = (VP9_COMP *)ptr;
2212 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
2214 vp8_yv12_copy_frame(sd, cfg);
2221 int vp9_update_entropy(VP9_PTR comp, int update) {
2222 ((VP9_COMP *)comp)->ext_refresh_frame_context = update;
2223 ((VP9_COMP *)comp)->ext_refresh_frame_context_pending = 1;
2228 #ifdef OUTPUT_YUV_SRC
2229 void vp9_write_yuv_frame(YV12_BUFFER_CONFIG *s) {
2230 uint8_t *src = s->y_buffer;
2231 int h = s->y_height;
2234 fwrite(src, s->y_width, 1, yuv_file);
2242 fwrite(src, s->uv_width, 1, yuv_file);
2243 src += s->uv_stride;
2250 fwrite(src, s->uv_width, 1, yuv_file);
2251 src += s->uv_stride;
2256 #ifdef OUTPUT_YUV_REC
2257 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
2258 YV12_BUFFER_CONFIG *s = cm->frame_to_show;
2259 uint8_t *src = s->y_buffer;
2263 fwrite(src, s->y_width, 1, yuv_rec_file);
2271 fwrite(src, s->uv_width, 1, yuv_rec_file);
2272 src += s->uv_stride;
2279 fwrite(src, s->uv_width, 1, yuv_rec_file);
2280 src += s->uv_stride;
2284 if (s->alpha_buffer) {
2285 src = s->alpha_buffer;
2286 h = s->alpha_height;
2288 fwrite(src, s->alpha_width, 1, yuv_rec_file);
2289 src += s->alpha_stride;
2294 fflush(yuv_rec_file);
2298 static void scale_and_extend_frame(YV12_BUFFER_CONFIG *src_fb,
2299 YV12_BUFFER_CONFIG *dst_fb) {
2300 const int in_w = src_fb->y_crop_width;
2301 const int in_h = src_fb->y_crop_height;
2302 const int out_w = dst_fb->y_crop_width;
2303 const int out_h = dst_fb->y_crop_height;
2306 uint8_t *srcs[4] = {src_fb->y_buffer, src_fb->u_buffer, src_fb->v_buffer,
2307 src_fb->alpha_buffer};
2308 int src_strides[4] = {src_fb->y_stride, src_fb->uv_stride, src_fb->uv_stride,
2309 src_fb->alpha_stride};
2311 uint8_t *dsts[4] = {dst_fb->y_buffer, dst_fb->u_buffer, dst_fb->v_buffer,
2312 dst_fb->alpha_buffer};
2313 int dst_strides[4] = {dst_fb->y_stride, dst_fb->uv_stride, dst_fb->uv_stride,
2314 dst_fb->alpha_stride};
2316 for (y = 0; y < out_h; y += 16) {
2317 for (x = 0; x < out_w; x += 16) {
2318 for (i = 0; i < MAX_MB_PLANE; ++i) {
2319 const int factor = i == 0 ? 1 : 2;
2320 const int x_q4 = x * (16 / factor) * in_w / out_w;
2321 const int y_q4 = y * (16 / factor) * in_h / out_h;
2322 const int src_stride = src_strides[i];
2323 const int dst_stride = dst_strides[i];
2324 uint8_t *src = srcs[i] + y / factor * in_h / out_h * src_stride +
2325 x / factor * in_w / out_w;
2326 uint8_t *dst = dsts[i] + y / factor * dst_stride + x / factor;
2328 vp9_convolve8(src, src_stride, dst, dst_stride,
2329 vp9_sub_pel_filters_8[x_q4 & 0xf], 16 * in_w / out_w,
2330 vp9_sub_pel_filters_8[y_q4 & 0xf], 16 * in_h / out_h,
2331 16 / factor, 16 / factor);
2336 vp8_yv12_extend_frame_borders(dst_fb);
2339 static int find_fp_qindex() {
2342 for (i = 0; i < QINDEX_RANGE; i++) {
2343 if (vp9_convert_qindex_to_q(i) >= 30.0) {
2348 if (i == QINDEX_RANGE)
2354 #define WRITE_RECON_BUFFER 0
2355 #if WRITE_RECON_BUFFER
2356 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame) {
2361 snprintf(filename, sizeof(filename), "cx\\y%04d.raw", this_frame);
2362 yframe = fopen(filename, "wb");
2364 for (i = 0; i < frame->y_height; i++)
2365 fwrite(frame->y_buffer + i * frame->y_stride,
2366 frame->y_width, 1, yframe);
2369 snprintf(filename, sizeof(filename), "cx\\u%04d.raw", this_frame);
2370 yframe = fopen(filename, "wb");
2372 for (i = 0; i < frame->uv_height; i++)
2373 fwrite(frame->u_buffer + i * frame->uv_stride,
2374 frame->uv_width, 1, yframe);
2377 snprintf(filename, sizeof(filename), "cx\\v%04d.raw", this_frame);
2378 yframe = fopen(filename, "wb");
2380 for (i = 0; i < frame->uv_height; i++)
2381 fwrite(frame->v_buffer + i * frame->uv_stride,
2382 frame->uv_width, 1, yframe);
2388 static double compute_edge_pixel_proportion(YV12_BUFFER_CONFIG *frame) {
2389 #define EDGE_THRESH 128
2391 int num_edge_pels = 0;
2392 int num_pels = (frame->y_height - 2) * (frame->y_width - 2);
2393 uint8_t *prev = frame->y_buffer + 1;
2394 uint8_t *curr = frame->y_buffer + 1 + frame->y_stride;
2395 uint8_t *next = frame->y_buffer + 1 + 2 * frame->y_stride;
2396 for (i = 1; i < frame->y_height - 1; i++) {
2397 for (j = 1; j < frame->y_width - 1; j++) {
2398 /* Sobel hor and ver gradients */
2399 int v = 2 * (curr[1] - curr[-1]) + (prev[1] - prev[-1]) +
2400 (next[1] - next[-1]);
2401 int h = 2 * (prev[0] - next[0]) + (prev[1] - next[1]) +
2402 (prev[-1] - next[-1]);
2403 h = (h < 0 ? -h : h);
2404 v = (v < 0 ? -v : v);
2405 if (h > EDGE_THRESH || v > EDGE_THRESH)
2411 curr += frame->y_stride - frame->y_width + 2;
2412 prev += frame->y_stride - frame->y_width + 2;
2413 next += frame->y_stride - frame->y_width + 2;
2415 return (double)num_edge_pels / num_pels;
2418 // Function to test for conditions that indicate we should loop
2419 // back and recode a frame.
2420 static int recode_loop_test(VP9_COMP *cpi,
2421 int high_limit, int low_limit,
2422 int q, int maxq, int minq) {
2423 int force_recode = 0;
2424 VP9_COMMON *cm = &cpi->common;
2426 // Special case trap if maximum allowed frame size exceeded.
2427 if (cpi->rc.projected_frame_size > cpi->rc.max_frame_bandwidth) {
2430 // Is frame recode allowed.
2431 // Yes if either recode mode 1 is selected or mode 2 is selected
2432 // and the frame is a key frame, golden frame or alt_ref_frame
2433 } else if ((cpi->sf.recode_loop == 1) ||
2434 ((cpi->sf.recode_loop == 2) &&
2435 ((cm->frame_type == KEY_FRAME) ||
2436 cpi->refresh_golden_frame ||
2437 cpi->refresh_alt_ref_frame))) {
2438 // General over and under shoot tests
2439 if (((cpi->rc.projected_frame_size > high_limit) && (q < maxq)) ||
2440 ((cpi->rc.projected_frame_size < low_limit) && (q > minq))) {
2442 } else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
2443 // Deal with frame undershoot and whether or not we are
2444 // below the automatically set cq level.
2445 if (q > cpi->cq_target_quality &&
2446 cpi->rc.projected_frame_size <
2447 ((cpi->rc.this_frame_target * 7) >> 3)) {
2452 return force_recode;
2455 static void update_reference_frames(VP9_COMP * const cpi) {
2456 VP9_COMMON * const cm = &cpi->common;
2458 // At this point the new frame has been encoded.
2459 // If any buffer copy / swapping is signaled it should be done here.
2460 if (cm->frame_type == KEY_FRAME) {
2461 ref_cnt_fb(cm->fb_idx_ref_cnt,
2462 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2463 ref_cnt_fb(cm->fb_idx_ref_cnt,
2464 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2466 #if CONFIG_MULTIPLE_ARF
2467 else if (!cpi->multi_arf_enabled && cpi->refresh_golden_frame &&
2468 !cpi->refresh_alt_ref_frame) {
2470 else if (cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame &&
2473 /* Preserve the previously existing golden frame and update the frame in
2474 * the alt ref slot instead. This is highly specific to the current use of
2475 * alt-ref as a forward reference, and this needs to be generalized as
2476 * other uses are implemented (like RTC/temporal scaling)
2478 * The update to the buffer in the alt ref slot was signaled in
2479 * vp9_pack_bitstream(), now swap the buffer pointers so that it's treated
2480 * as the golden frame next time.
2484 ref_cnt_fb(cm->fb_idx_ref_cnt,
2485 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2487 tmp = cpi->alt_fb_idx;
2488 cpi->alt_fb_idx = cpi->gld_fb_idx;
2489 cpi->gld_fb_idx = tmp;
2490 } else { /* For non key/golden frames */
2491 if (cpi->refresh_alt_ref_frame) {
2492 int arf_idx = cpi->alt_fb_idx;
2493 #if CONFIG_MULTIPLE_ARF
2494 if (cpi->multi_arf_enabled) {
2495 arf_idx = cpi->arf_buffer_idx[cpi->sequence_number + 1];
2498 ref_cnt_fb(cm->fb_idx_ref_cnt,
2499 &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
2502 if (cpi->refresh_golden_frame) {
2503 ref_cnt_fb(cm->fb_idx_ref_cnt,
2504 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2508 if (cpi->refresh_last_frame) {
2509 ref_cnt_fb(cm->fb_idx_ref_cnt,
2510 &cm->ref_frame_map[cpi->lst_fb_idx], cm->new_fb_idx);
2514 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
2515 MACROBLOCKD *xd = &cpi->mb.e_mbd;
2516 struct loopfilter *lf = &cm->lf;
2518 lf->filter_level = 0;
2520 struct vpx_usec_timer timer;
2522 vp9_clear_system_state();
2524 vpx_usec_timer_start(&timer);
2526 vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.use_fast_lpf_pick);
2528 vpx_usec_timer_mark(&timer);
2529 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
2532 if (lf->filter_level > 0) {
2533 vp9_set_alt_lf_level(cpi, lf->filter_level);
2534 vp9_loop_filter_frame(cm, xd, lf->filter_level, 0, 0);
2537 vp9_extend_frame_inner_borders(cm->frame_to_show,
2538 cm->subsampling_x, cm->subsampling_y);
2541 static void scale_references(VP9_COMP *cpi) {
2542 VP9_COMMON *cm = &cpi->common;
2543 MV_REFERENCE_FRAME ref_frame;
2545 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2546 const int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, ref_frame)];
2547 YV12_BUFFER_CONFIG *ref = &cm->yv12_fb[idx];
2549 if (ref->y_crop_width != cm->width ||
2550 ref->y_crop_height != cm->height) {
2551 const int new_fb = get_free_fb(cm);
2552 vp9_realloc_frame_buffer(&cm->yv12_fb[new_fb],
2553 cm->width, cm->height,
2554 cm->subsampling_x, cm->subsampling_y,
2555 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL);
2556 scale_and_extend_frame(ref, &cm->yv12_fb[new_fb]);
2557 cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
2559 cpi->scaled_ref_idx[ref_frame - 1] = idx;
2560 cm->fb_idx_ref_cnt[idx]++;
2565 static void release_scaled_references(VP9_COMP *cpi) {
2566 VP9_COMMON *cm = &cpi->common;
2569 for (i = 0; i < 3; i++)
2570 cm->fb_idx_ref_cnt[cpi->scaled_ref_idx[i]]--;
2573 static void full_to_model_count(unsigned int *model_count,
2574 unsigned int *full_count) {
2576 model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
2577 model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
2578 model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
2579 for (n = THREE_TOKEN; n < EOB_TOKEN; ++n)
2580 model_count[TWO_TOKEN] += full_count[n];
2581 model_count[EOB_MODEL_TOKEN] = full_count[EOB_TOKEN];
2584 static void full_to_model_counts(vp9_coeff_count_model *model_count,
2585 vp9_coeff_count *full_count) {
2588 for (i = 0; i < PLANE_TYPES; ++i)
2589 for (j = 0; j < REF_TYPES; ++j)
2590 for (k = 0; k < COEF_BANDS; ++k)
2591 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
2592 full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
2595 #if 0 && CONFIG_INTERNAL_STATS
2596 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
2597 VP9_COMMON *const cm = &cpi->common;
2598 FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
2601 vp9_clear_system_state(); // __asm emms;
2603 recon_err = vp9_calc_ss_err(cpi->Source, get_frame_new_buffer(cm));
2605 if (cpi->twopass.total_left_stats.coded_error != 0.0)
2606 fprintf(f, "%10u %10d %10d %10d %10d %10d "
2607 "%10"PRId64" %10"PRId64" %10d "
2608 "%7.2lf %7.2lf %7.2lf %7.2lf %7.2lf %7.2lf"
2609 "%6d %6d %5d %5d %5d "
2610 "%10"PRId64" %10.3lf"
2611 "%10lf %8u %10d %10d %10d\n",
2612 cpi->common.current_video_frame, cpi->rc.this_frame_target,
2613 cpi->rc.projected_frame_size,
2614 cpi->rc.projected_frame_size / cpi->common.MBs,
2615 (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
2616 cpi->rc.total_target_vs_actual,
2617 (cpi->oxcf.starting_buffer_level - cpi->rc.bits_off_target),
2618 cpi->rc.total_actual_bits, cm->base_qindex,
2619 vp9_convert_qindex_to_q(cm->base_qindex),
2620 (double)vp9_dc_quant(cm->base_qindex, 0) / 4.0,
2621 vp9_convert_qindex_to_q(cpi->rc.active_worst_quality), cpi->rc.avg_q,
2622 vp9_convert_qindex_to_q(cpi->rc.ni_av_qi),
2623 vp9_convert_qindex_to_q(cpi->cq_target_quality),
2624 cpi->refresh_last_frame, cpi->refresh_golden_frame,
2625 cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
2626 cpi->twopass.bits_left,
2627 cpi->twopass.total_left_stats.coded_error,
2628 cpi->twopass.bits_left /
2629 (1 + cpi->twopass.total_left_stats.coded_error),
2630 cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
2631 cpi->twopass.kf_zeromotion_pct);
2636 FILE *const fmodes = fopen("Modes.stt", "a");
2639 fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
2640 cm->frame_type, cpi->refresh_golden_frame,
2641 cpi->refresh_alt_ref_frame);
2643 for (i = 0; i < MAX_MODES; ++i)
2644 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
2645 for (i = 0; i < MAX_REFS; ++i)
2646 fprintf(fmodes, "%5d ", cpi->sub8x8_mode_chosen_counts[i]);
2648 fprintf(fmodes, "\n");
2655 static void encode_with_recode_loop(VP9_COMP *cpi,
2661 int frame_over_shoot_limit,
2662 int frame_under_shoot_limit) {
2663 VP9_COMMON *const cm = &cpi->common;
2666 int overshoot_seen = 0;
2667 int undershoot_seen = 0;
2668 int q_low = bottom_index, q_high = top_index;
2671 vp9_clear_system_state(); // __asm emms;
2673 vp9_set_quantizer(cpi, *q);
2675 if (loop_count == 0) {
2676 // Set up entropy context depending on frame type. The decoder mandates
2677 // the use of the default context, index 0, for keyframes and inter
2678 // frames where the error_resilient_mode or intra_only flag is set. For
2679 // other inter-frames the encoder currently uses only two contexts;
2680 // context 1 for ALTREF frames and context 0 for the others.
2681 if (cm->frame_type == KEY_FRAME) {
2682 vp9_setup_key_frame(cpi);
2684 if (!cm->intra_only && !cm->error_resilient_mode) {
2685 cpi->common.frame_context_idx = cpi->refresh_alt_ref_frame;
2687 vp9_setup_inter_frame(cpi);
2691 // Variance adaptive and in frame q adjustment experiments are mutually
2693 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
2694 vp9_vaq_frame_setup(cpi);
2695 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
2696 setup_in_frame_q_adj(cpi);
2699 // transform / motion compensation build reconstruction frame
2701 vp9_encode_frame(cpi);
2703 // Update the skip mb flag probabilities based on the distribution
2704 // seen in the last encoder iteration.
2705 // update_base_skip_probs(cpi);
2707 vp9_clear_system_state(); // __asm emms;
2709 // Dummy pack of the bitstream using up to date stats to get an
2710 // accurate estimate of output frame size to determine if we need
2712 if (cpi->sf.recode_loop != 0) {
2713 vp9_save_coding_context(cpi);
2714 cpi->dummy_packing = 1;
2715 vp9_pack_bitstream(cpi, dest, size);
2716 cpi->rc.projected_frame_size = (*size) << 3;
2717 vp9_restore_coding_context(cpi);
2719 if (frame_over_shoot_limit == 0)
2720 frame_over_shoot_limit = 1;
2723 if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
2726 if ((cm->frame_type == KEY_FRAME) &&
2727 cpi->rc.this_key_frame_forced &&
2728 (cpi->rc.projected_frame_size < cpi->rc.max_frame_bandwidth)) {
2730 int kf_err = vp9_calc_ss_err(cpi->Source, get_frame_new_buffer(cm));
2732 int high_err_target = cpi->ambient_err;
2733 int low_err_target = cpi->ambient_err >> 1;
2735 // Prevent possible divide by zero error below for perfect KF
2738 // The key frame is not good enough or we can afford
2739 // to make it better without undue risk of popping.
2740 if ((kf_err > high_err_target &&
2741 cpi->rc.projected_frame_size <= frame_over_shoot_limit) ||
2742 (kf_err > low_err_target &&
2743 cpi->rc.projected_frame_size <= frame_under_shoot_limit)) {
2745 q_high = *q > q_low ? *q - 1 : q_low;
2748 *q = ((*q) * high_err_target) / kf_err;
2749 *q = MIN((*q), (q_high + q_low) >> 1);
2750 } else if (kf_err < low_err_target &&
2751 cpi->rc.projected_frame_size >= frame_under_shoot_limit) {
2752 // The key frame is much better than the previous frame
2754 q_low = *q < q_high ? *q + 1 : q_high;
2757 *q = ((*q) * low_err_target) / kf_err;
2758 *q = MIN((*q), (q_high + q_low + 1) >> 1);
2761 // Clamp Q to upper and lower limits:
2762 *q = clamp(*q, q_low, q_high);
2764 loop = *q != last_q;
2765 } else if (recode_loop_test(
2766 cpi, frame_over_shoot_limit, frame_under_shoot_limit,
2767 *q, MAX(q_high, top_index), bottom_index)) {
2768 // Is the projected frame size out of range and are we allowed
2769 // to attempt to recode.
2773 // Frame size out of permitted range:
2774 // Update correction factor & compute new Q to try...
2776 // Frame is too large
2777 if (cpi->rc.projected_frame_size > cpi->rc.this_frame_target) {
2778 // Special case if the projected size is > the max allowed.
2779 if (cpi->rc.projected_frame_size >= cpi->rc.max_frame_bandwidth)
2780 q_high = cpi->rc.worst_quality;
2782 // Raise Qlow as to at least the current value
2783 q_low = *q < q_high ? *q + 1 : q_high;
2785 if (undershoot_seen || loop_count > 1) {
2786 // Update rate_correction_factor unless
2787 vp9_rc_update_rate_correction_factors(cpi, 1);
2789 *q = (q_high + q_low + 1) / 2;
2791 // Update rate_correction_factor unless
2792 vp9_rc_update_rate_correction_factors(cpi, 0);
2794 *q = vp9_rc_regulate_q(cpi, cpi->rc.this_frame_target,
2795 bottom_index, MAX(q_high, top_index));
2797 while (*q < q_low && retries < 10) {
2798 vp9_rc_update_rate_correction_factors(cpi, 0);
2799 *q = vp9_rc_regulate_q(cpi, cpi->rc.this_frame_target,
2800 bottom_index, MAX(q_high, top_index));
2807 // Frame is too small
2808 q_high = *q > q_low ? *q - 1 : q_low;
2810 if (overshoot_seen || loop_count > 1) {
2811 vp9_rc_update_rate_correction_factors(cpi, 1);
2812 *q = (q_high + q_low) / 2;
2814 vp9_rc_update_rate_correction_factors(cpi, 0);
2815 *q = vp9_rc_regulate_q(cpi, cpi->rc.this_frame_target,
2816 bottom_index, top_index);
2817 // Special case reset for qlow for constrained quality.
2818 // This should only trigger where there is very substantial
2819 // undershoot on a frame and the auto cq level is above
2820 // the user passsed in value.
2821 if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY &&
2826 while (*q > q_high && retries < 10) {
2827 vp9_rc_update_rate_correction_factors(cpi, 0);
2828 *q = vp9_rc_regulate_q(cpi, cpi->rc.this_frame_target,
2829 bottom_index, top_index);
2834 undershoot_seen = 1;
2837 // Clamp Q to upper and lower limits:
2838 *q = clamp(*q, q_low, q_high);
2840 loop = *q != last_q;
2846 // Special case for overlay frame.
2847 if (cpi->rc.is_src_frame_alt_ref &&
2848 (cpi->rc.projected_frame_size < cpi->rc.max_frame_bandwidth))
2854 #if CONFIG_INTERNAL_STATS
2855 cpi->tot_recode_hits++;
2861 static void get_ref_frame_flags(VP9_COMP *cpi) {
2862 if (cpi->refresh_last_frame & cpi->refresh_golden_frame)
2863 cpi->gold_is_last = 1;
2864 else if (cpi->refresh_last_frame ^ cpi->refresh_golden_frame)
2865 cpi->gold_is_last = 0;
2867 if (cpi->refresh_last_frame & cpi->refresh_alt_ref_frame)
2868 cpi->alt_is_last = 1;
2869 else if (cpi->refresh_last_frame ^ cpi->refresh_alt_ref_frame)
2870 cpi->alt_is_last = 0;
2872 if (cpi->refresh_alt_ref_frame & cpi->refresh_golden_frame)
2873 cpi->gold_is_alt = 1;
2874 else if (cpi->refresh_alt_ref_frame ^ cpi->refresh_golden_frame)
2875 cpi->gold_is_alt = 0;
2877 cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
2879 if (cpi->gold_is_last)
2880 cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
2882 if (cpi->alt_is_last)
2883 cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
2885 if (cpi->gold_is_alt)
2886 cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
2889 static void set_ext_overrides(VP9_COMP *cpi) {
2890 // Overrides the defaults with the externally supplied values with
2891 // vp9_update_reference() and vp9_update_entropy() calls
2892 // Note: The overrides are valid only for the next frame passed
2893 // to encode_frame_to_data_rate() function
2894 if (cpi->ext_refresh_frame_context_pending) {
2895 cpi->common.refresh_frame_context = cpi->ext_refresh_frame_context;
2896 cpi->ext_refresh_frame_context_pending = 0;
2898 if (cpi->ext_refresh_frame_flags_pending) {
2899 cpi->refresh_last_frame = cpi->ext_refresh_last_frame;
2900 cpi->refresh_golden_frame = cpi->ext_refresh_golden_frame;
2901 cpi->refresh_alt_ref_frame = cpi->ext_refresh_alt_ref_frame;
2902 cpi->ext_refresh_frame_flags_pending = 0;
2906 static void encode_frame_to_data_rate(VP9_COMP *cpi,
2909 unsigned int *frame_flags) {
2910 VP9_COMMON *const cm = &cpi->common;
2913 int frame_over_shoot_limit;
2914 int frame_under_shoot_limit;
2918 SPEED_FEATURES *const sf = &cpi->sf;
2919 unsigned int max_mv_def = MIN(cpi->common.width, cpi->common.height);
2920 struct segmentation *const seg = &cm->seg;
2922 set_ext_overrides(cpi);
2924 /* Scale the source buffer, if required. */
2925 if (cm->mi_cols * 8 != cpi->un_scaled_source->y_width ||
2926 cm->mi_rows * 8 != cpi->un_scaled_source->y_height) {
2927 scale_and_extend_frame(cpi->un_scaled_source, &cpi->scaled_source);
2928 cpi->Source = &cpi->scaled_source;
2930 cpi->Source = cpi->un_scaled_source;
2932 scale_references(cpi);
2934 // Clear down mmx registers to allow floating point in what follows.
2935 vp9_clear_system_state();
2937 // For an alt ref frame in 2 pass we skip the call to the second
2938 // pass function that sets the target bandwidth so we must set it here.
2939 if (cpi->refresh_alt_ref_frame) {
2940 // Set a per frame bit target for the alt ref frame.
2941 cpi->rc.per_frame_bandwidth = cpi->twopass.gf_bits;
2942 // Set a per second target bitrate.
2943 cpi->target_bandwidth = (int)(cpi->twopass.gf_bits * cpi->output_framerate);
2946 // Clear zbin over-quant value and mode boost values.
2947 cpi->zbin_mode_boost = 0;
2949 // Enable or disable mode based tweaking of the zbin.
2950 // For 2 pass only used where GF/ARF prediction quality
2951 // is above a threshold.
2952 cpi->zbin_mode_boost = 0;
2953 cpi->zbin_mode_boost_enabled = 0;
2955 // Current default encoder behavior for the altref sign bias.
2956 cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = cpi->rc.source_alt_ref_active;
2958 // Set default state for segment based loop filter update flags.
2959 cm->lf.mode_ref_delta_update = 0;
2961 // Initialize cpi->mv_step_param to default based on max resolution.
2962 cpi->mv_step_param = vp9_init_search_range(cpi, max_mv_def);
2963 // Initialize cpi->max_mv_magnitude and cpi->mv_step_param if appropriate.
2964 if (sf->auto_mv_step_size) {
2965 if (frame_is_intra_only(&cpi->common)) {
2966 // Initialize max_mv_magnitude for use in the first INTER frame
2967 // after a key/intra-only frame.
2968 cpi->max_mv_magnitude = max_mv_def;
2971 // Allow mv_steps to correspond to twice the max mv magnitude found
2972 // in the previous frame, capped by the default max_mv_magnitude based
2974 cpi->mv_step_param = vp9_init_search_range(
2975 cpi, MIN(max_mv_def, 2 * cpi->max_mv_magnitude));
2976 cpi->max_mv_magnitude = 0;
2980 // Set various flags etc to special state if it is a key frame.
2981 if (frame_is_intra_only(cm)) {
2982 vp9_setup_key_frame(cpi);
2983 // Reset the loop filter deltas and segmentation map.
2984 vp9_reset_segment_features(&cm->seg);
2986 // If segmentation is enabled force a map update for key frames.
2988 seg->update_map = 1;
2989 seg->update_data = 1;
2992 // The alternate reference frame cannot be active for a key frame.
2993 cpi->rc.source_alt_ref_active = 0;
2995 cm->error_resilient_mode = (cpi->oxcf.error_resilient_mode != 0);
2996 cm->frame_parallel_decoding_mode =
2997 (cpi->oxcf.frame_parallel_decoding_mode != 0);
2998 if (cm->error_resilient_mode) {
2999 cm->frame_parallel_decoding_mode = 1;
3000 cm->reset_frame_context = 0;
3001 cm->refresh_frame_context = 0;
3002 } else if (cm->intra_only) {
3003 // Only reset the current context.
3004 cm->reset_frame_context = 2;
3008 // Configure experimental use of segmentation for enhanced coding of
3009 // static regions if indicated.
3010 // Only allowed in second pass of two pass (as requires lagged coding)
3011 // and if the relevant speed feature flag is set.
3012 if ((cpi->pass == 2) && (cpi->sf.static_segmentation)) {
3013 configure_static_seg_features(cpi);
3016 // For 1 pass CBR, check if we are dropping this frame.
3017 // Never drop on key frame.
3018 if (cpi->pass == 0 &&
3019 cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER &&
3020 cm->frame_type != KEY_FRAME) {
3021 if (vp9_drop_frame(cpi)) {
3022 // Update buffer level with zero size, update frame counters, and return.
3023 vp9_update_buffer_level(cpi, 0);
3024 cm->last_frame_type = cm->frame_type;
3025 vp9_rc_postencode_update_drop_frame(cpi);
3026 cm->current_video_frame++;
3031 vp9_clear_system_state();
3033 vp9_zero(cpi->rd_tx_select_threshes);
3035 #if CONFIG_VP9_POSTPROC
3036 if (cpi->oxcf.noise_sensitivity > 0) {
3038 switch (cpi->oxcf.noise_sensitivity) {
3056 vp9_denoise(cpi->Source, cpi->Source, l);
3060 #ifdef OUTPUT_YUV_SRC
3061 vp9_write_yuv_frame(cpi->Source);
3064 // Decide how big to make the frame.
3065 vp9_rc_pick_frame_size_target(cpi);
3067 // Decide frame size bounds
3068 vp9_rc_compute_frame_size_bounds(cpi, cpi->rc.this_frame_target,
3069 &frame_under_shoot_limit,
3070 &frame_over_shoot_limit);
3072 // Decide q and q bounds
3073 q = vp9_rc_pick_q_and_adjust_q_bounds(cpi,
3077 if (!frame_is_intra_only(cm)) {
3078 cm->mcomp_filter_type = DEFAULT_INTERP_FILTER;
3079 /* TODO: Decide this more intelligently */
3080 set_high_precision_mv(cpi, (q < HIGH_PRECISION_MV_QTHRESH));
3083 encode_with_recode_loop(cpi,
3089 frame_over_shoot_limit,
3090 frame_under_shoot_limit);
3092 // Special case code to reduce pulsing when key frames are forced at a
3093 // fixed interval. Note the reconstruction error if it is the frame before
3094 // the force key frame
3095 if (cpi->rc.next_key_frame_forced && cpi->rc.frames_to_key == 1) {
3096 cpi->ambient_err = vp9_calc_ss_err(cpi->Source, get_frame_new_buffer(cm));
3099 // If the encoder forced a KEY_FRAME decision
3100 if (cm->frame_type == KEY_FRAME)
3101 cpi->refresh_last_frame = 1;
3103 cm->frame_to_show = get_frame_new_buffer(cm);
3105 #if WRITE_RECON_BUFFER
3107 write_cx_frame_to_file(cm->frame_to_show,
3108 cm->current_video_frame);
3110 write_cx_frame_to_file(cm->frame_to_show,
3111 cm->current_video_frame + 1000);
3114 // Pick the loop filter level for the frame.
3115 loopfilter_frame(cpi, cm);
3117 #if WRITE_RECON_BUFFER
3119 write_cx_frame_to_file(cm->frame_to_show,
3120 cm->current_video_frame + 2000);
3122 write_cx_frame_to_file(cm->frame_to_show,
3123 cm->current_video_frame + 3000);
3126 // build the bitstream
3127 cpi->dummy_packing = 0;
3128 vp9_pack_bitstream(cpi, dest, size);
3130 if (cm->seg.update_map)
3131 update_reference_segmentation_map(cpi);
3133 release_scaled_references(cpi);
3134 update_reference_frames(cpi);
3136 for (t = TX_4X4; t <= TX_32X32; t++)
3137 full_to_model_counts(cpi->common.counts.coef[t],
3138 cpi->coef_counts[t]);
3139 if (!cpi->common.error_resilient_mode &&
3140 !cpi->common.frame_parallel_decoding_mode) {
3141 vp9_adapt_coef_probs(&cpi->common);
3144 if (!frame_is_intra_only(&cpi->common)) {
3145 if (!cpi->common.error_resilient_mode &&
3146 !cpi->common.frame_parallel_decoding_mode) {
3147 vp9_adapt_mode_probs(&cpi->common);
3148 vp9_adapt_mv_probs(&cpi->common, cpi->common.allow_high_precision_mv);
3152 #ifdef ENTROPY_STATS
3153 vp9_update_mode_context_stats(cpi);
3156 /* Move storing frame_type out of the above loop since it is also
3157 * needed in motion search besides loopfilter */
3158 cm->last_frame_type = cm->frame_type;
3161 output_frame_level_debug_stats(cpi);
3163 if (cpi->refresh_golden_frame == 1)
3164 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
3166 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_GOLDEN;
3168 if (cpi->refresh_alt_ref_frame == 1)
3169 cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
3171 cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_ALTREF;
3173 get_ref_frame_flags(cpi);
3175 vp9_rc_postencode_update(cpi, *size);
3177 if (cm->frame_type == KEY_FRAME) {
3178 // Tell the caller that the frame was coded as a key frame
3179 *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
3181 #if CONFIG_MULTIPLE_ARF
3182 // Reset the sequence number.
3183 if (cpi->multi_arf_enabled) {
3184 cpi->sequence_number = 0;
3185 cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
3186 cpi->new_frame_coding_order_period = -1;
3190 *frame_flags = cm->frame_flags&~FRAMEFLAGS_KEY;
3192 #if CONFIG_MULTIPLE_ARF
3193 /* Increment position in the coded frame sequence. */
3194 if (cpi->multi_arf_enabled) {
3195 ++cpi->sequence_number;
3196 if (cpi->sequence_number >= cpi->frame_coding_order_period) {
3197 cpi->sequence_number = 0;
3198 cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
3199 cpi->new_frame_coding_order_period = -1;
3201 cpi->this_frame_weight = cpi->arf_weight[cpi->sequence_number];
3202 assert(cpi->this_frame_weight >= 0);
3207 // Clear the one shot update flags for segmentation map and mode/ref loop
3209 cm->seg.update_map = 0;
3210 cm->seg.update_data = 0;
3211 cm->lf.mode_ref_delta_update = 0;
3213 // keep track of the last coded dimensions
3214 cm->last_width = cm->width;
3215 cm->last_height = cm->height;
3217 // reset to normal state now that we are done.
3218 cm->last_show_frame = cm->show_frame;
3219 if (cm->show_frame) {
3220 // current mip will be the prev_mip for the next frame
3221 MODE_INFO *temp = cm->prev_mip;
3222 MODE_INFO **temp2 = cm->prev_mi_grid_base;
3223 cm->prev_mip = cm->mip;
3225 cm->prev_mi_grid_base = cm->mi_grid_base;
3226 cm->mi_grid_base = temp2;
3228 // update the upper left visible macroblock ptrs
3229 cm->mi = cm->mip + cm->mode_info_stride + 1;
3230 cm->mi_grid_visible = cm->mi_grid_base + cm->mode_info_stride + 1;
3232 cpi->mb.e_mbd.mi_8x8 = cm->mi_grid_visible;
3233 cpi->mb.e_mbd.mi_8x8[0] = cm->mi;
3235 // Don't increment frame counters if this was an altref buffer
3236 // update not a real frame
3237 ++cm->current_video_frame;
3240 cm->prev_mi = cm->prev_mip + cm->mode_info_stride + 1;
3241 cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mode_info_stride + 1;
3244 static void SvcEncode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
3245 unsigned int *frame_flags) {
3246 vp9_get_svc_params(cpi);
3247 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3250 static void Pass0Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
3251 unsigned int *frame_flags) {
3252 if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
3253 vp9_get_one_pass_cbr_params(cpi);
3255 vp9_get_one_pass_params(cpi);
3257 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3260 static void Pass1Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
3261 unsigned int *frame_flags) {
3266 vp9_get_first_pass_params(cpi);
3267 vp9_set_quantizer(cpi, find_fp_qindex());
3268 vp9_first_pass(cpi);
3271 static void Pass2Encode(VP9_COMP *cpi, size_t *size,
3272 uint8_t *dest, unsigned int *frame_flags) {
3273 cpi->enable_encode_breakout = 1;
3275 vp9_get_second_pass_params(cpi);
3276 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3277 // vp9_print_modes_and_motion_vectors(&cpi->common, "encode.stt");
3279 vp9_twopass_postencode_update(cpi, *size);
3282 static void check_initial_width(VP9_COMP *cpi, YV12_BUFFER_CONFIG *sd) {
3283 VP9_COMMON *const cm = &cpi->common;
3284 if (!cpi->initial_width) {
3285 // TODO(agrange) Subsampling defaults to assuming sampled chroma.
3286 cm->subsampling_x = sd != NULL ? (sd->uv_width < sd->y_width) : 1;
3287 cm->subsampling_y = sd != NULL ? (sd->uv_height < sd->y_height) : 1;
3288 alloc_raw_frame_buffers(cpi);
3289 cpi->initial_width = cm->width;
3290 cpi->initial_height = cm->height;
3295 int vp9_receive_raw_frame(VP9_PTR ptr, unsigned int frame_flags,
3296 YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
3298 VP9_COMP *cpi = (VP9_COMP *) ptr;
3299 struct vpx_usec_timer timer;
3302 check_initial_width(cpi, sd);
3303 vpx_usec_timer_start(&timer);
3304 if (vp9_lookahead_push(cpi->lookahead, sd, time_stamp, end_time, frame_flags,
3305 cpi->active_map_enabled ? cpi->active_map : NULL))
3307 vpx_usec_timer_mark(&timer);
3308 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
3314 static int frame_is_reference(const VP9_COMP *cpi) {
3315 const VP9_COMMON *cm = &cpi->common;
3317 return cm->frame_type == KEY_FRAME ||
3318 cpi->refresh_last_frame ||
3319 cpi->refresh_golden_frame ||
3320 cpi->refresh_alt_ref_frame ||
3321 cm->refresh_frame_context ||
3322 cm->lf.mode_ref_delta_update ||
3323 cm->seg.update_map ||
3324 cm->seg.update_data;
3327 #if CONFIG_MULTIPLE_ARF
3328 int is_next_frame_arf(VP9_COMP *cpi) {
3329 // Negative entry in frame_coding_order indicates an ARF at this position.
3330 return cpi->frame_coding_order[cpi->sequence_number + 1] < 0 ? 1 : 0;
3334 void adjust_frame_rate(VP9_COMP *cpi) {
3335 int64_t this_duration;
3338 if (cpi->source->ts_start == cpi->first_time_stamp_ever) {
3339 this_duration = cpi->source->ts_end - cpi->source->ts_start;
3342 int64_t last_duration = cpi->last_end_time_stamp_seen
3343 - cpi->last_time_stamp_seen;
3345 this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
3347 // do a step update if the duration changes by 10%
3349 step = (int)((this_duration - last_duration) * 10 / last_duration);
3352 if (this_duration) {
3354 vp9_new_framerate(cpi, 10000000.0 / this_duration);
3356 // Average this frame's rate into the last second's average
3357 // frame rate. If we haven't seen 1 second yet, then average
3358 // over the whole interval seen.
3359 const double interval = MIN((double)(cpi->source->ts_end
3360 - cpi->first_time_stamp_ever), 10000000.0);
3361 double avg_duration = 10000000.0 / cpi->oxcf.framerate;
3362 avg_duration *= (interval - avg_duration + this_duration);
3363 avg_duration /= interval;
3365 vp9_new_framerate(cpi, 10000000.0 / avg_duration);
3368 cpi->last_time_stamp_seen = cpi->source->ts_start;
3369 cpi->last_end_time_stamp_seen = cpi->source->ts_end;
3372 int vp9_get_compressed_data(VP9_PTR ptr, unsigned int *frame_flags,
3373 size_t *size, uint8_t *dest,
3374 int64_t *time_stamp, int64_t *time_end, int flush) {
3375 VP9_COMP *cpi = (VP9_COMP *) ptr;
3376 VP9_COMMON *cm = &cpi->common;
3377 struct vpx_usec_timer cmptimer;
3378 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
3379 MV_REFERENCE_FRAME ref_frame;
3380 // FILE *fp_out = fopen("enc_frame_type.txt", "a");
3385 vpx_usec_timer_start(&cmptimer);
3389 set_high_precision_mv(cpi, ALTREF_HIGH_PRECISION_MV);
3392 cm->reset_frame_context = 0;
3393 cm->refresh_frame_context = 1;
3394 cpi->refresh_last_frame = 1;
3395 cpi->refresh_golden_frame = 0;
3396 cpi->refresh_alt_ref_frame = 0;
3398 // Should we code an alternate reference frame.
3399 if (cpi->oxcf.play_alternate && cpi->rc.source_alt_ref_pending) {
3402 #if CONFIG_MULTIPLE_ARF
3403 assert(!cpi->multi_arf_enabled ||
3404 cpi->frame_coding_order[cpi->sequence_number] < 0);
3406 if (cpi->multi_arf_enabled && (cpi->pass == 2))
3407 frames_to_arf = (-cpi->frame_coding_order[cpi->sequence_number])
3408 - cpi->next_frame_in_order;
3411 frames_to_arf = cpi->rc.frames_till_gf_update_due;
3413 assert(frames_to_arf <= cpi->rc.frames_to_key);
3415 if ((cpi->source = vp9_lookahead_peek(cpi->lookahead, frames_to_arf))) {
3416 #if CONFIG_MULTIPLE_ARF
3417 cpi->alt_ref_source[cpi->arf_buffered] = cpi->source;
3419 cpi->alt_ref_source = cpi->source;
3422 if (cpi->oxcf.arnr_max_frames > 0) {
3423 // Produce the filtered ARF frame.
3424 // TODO(agrange) merge these two functions.
3425 configure_arnr_filter(cpi, cm->current_video_frame + frames_to_arf,
3427 vp9_temporal_filter_prepare(cpi, frames_to_arf);
3428 vp9_extend_frame_borders(&cpi->alt_ref_buffer,
3429 cm->subsampling_x, cm->subsampling_y);
3430 force_src_buffer = &cpi->alt_ref_buffer;
3434 cpi->refresh_alt_ref_frame = 1;
3435 cpi->refresh_golden_frame = 0;
3436 cpi->refresh_last_frame = 0;
3437 cpi->rc.is_src_frame_alt_ref = 0;
3439 #if CONFIG_MULTIPLE_ARF
3440 if (!cpi->multi_arf_enabled)
3442 cpi->rc.source_alt_ref_pending = 0; // Clear Pending altf Ref flag.
3447 #if CONFIG_MULTIPLE_ARF
3450 if ((cpi->source = vp9_lookahead_pop(cpi->lookahead, flush))) {
3454 #if CONFIG_MULTIPLE_ARF
3455 // Is this frame the ARF overlay.
3456 cpi->rc.is_src_frame_alt_ref = 0;
3457 for (i = 0; i < cpi->arf_buffered; ++i) {
3458 if (cpi->source == cpi->alt_ref_source[i]) {
3459 cpi->rc.is_src_frame_alt_ref = 1;
3460 cpi->refresh_golden_frame = 1;
3465 cpi->rc.is_src_frame_alt_ref = cpi->alt_ref_source
3466 && (cpi->source == cpi->alt_ref_source);
3468 if (cpi->rc.is_src_frame_alt_ref) {
3469 // Current frame is an ARF overlay frame.
3470 #if CONFIG_MULTIPLE_ARF
3471 cpi->alt_ref_source[i] = NULL;
3473 cpi->alt_ref_source = NULL;
3475 // Don't refresh the last buffer for an ARF overlay frame. It will
3476 // become the GF so preserve last as an alternative prediction option.
3477 cpi->refresh_last_frame = 0;
3479 #if CONFIG_MULTIPLE_ARF
3480 ++cpi->next_frame_in_order;
3486 cpi->un_scaled_source = cpi->Source = force_src_buffer ? force_src_buffer
3487 : &cpi->source->img;
3488 *time_stamp = cpi->source->ts_start;
3489 *time_end = cpi->source->ts_end;
3490 *frame_flags = cpi->source->flags;
3492 #if CONFIG_MULTIPLE_ARF
3493 if ((cm->frame_type != KEY_FRAME) && (cpi->pass == 2))
3494 cpi->rc.source_alt_ref_pending = is_next_frame_arf(cpi);
3498 if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done) {
3499 vp9_end_first_pass(cpi); /* get last stats packet */
3500 cpi->twopass.first_pass_done = 1;
3507 if (cpi->source->ts_start < cpi->first_time_stamp_ever) {
3508 cpi->first_time_stamp_ever = cpi->source->ts_start;
3509 cpi->last_end_time_stamp_seen = cpi->source->ts_start;
3512 // adjust frame rates based on timestamps given
3513 if (cm->show_frame) {
3514 adjust_frame_rate(cpi);
3517 // start with a 0 size frame
3520 // Clear down mmx registers
3521 vp9_clear_system_state(); // __asm emms;
3523 /* find a free buffer for the new frame, releasing the reference previously
3526 cm->fb_idx_ref_cnt[cm->new_fb_idx]--;
3527 cm->new_fb_idx = get_free_fb(cm);
3529 #if CONFIG_MULTIPLE_ARF
3530 /* Set up the correct ARF frame. */
3531 if (cpi->refresh_alt_ref_frame) {
3532 ++cpi->arf_buffered;
3534 if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
3536 cpi->alt_fb_idx = cpi->arf_buffer_idx[cpi->sequence_number];
3540 cm->frame_flags = *frame_flags;
3542 // Reset the frame pointers to the current frame size
3543 vp9_realloc_frame_buffer(get_frame_new_buffer(cm),
3544 cm->width, cm->height,
3545 cm->subsampling_x, cm->subsampling_y,
3546 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL);
3549 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
3550 const int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, ref_frame)];
3551 YV12_BUFFER_CONFIG *const buf = &cm->yv12_fb[idx];
3553 RefBuffer *const ref_buf = &cm->frame_refs[ref_frame - 1];
3556 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
3557 buf->y_crop_width, buf->y_crop_height,
3558 cm->width, cm->height);
3560 if (vp9_is_scaled(&ref_buf->sf))
3561 vp9_extend_frame_borders(buf, cm->subsampling_x, cm->subsampling_y);
3564 vp9_setup_interp_filters(&cpi->mb.e_mbd, DEFAULT_INTERP_FILTER, cm);
3566 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3571 SvcEncode(cpi, size, dest, frame_flags);
3572 } else if (cpi->pass == 1) {
3573 Pass1Encode(cpi, size, dest, frame_flags);
3574 } else if (cpi->pass == 2) {
3575 Pass2Encode(cpi, size, dest, frame_flags);
3578 Pass0Encode(cpi, size, dest, frame_flags);
3581 if (cm->refresh_frame_context)
3582 cm->frame_contexts[cm->frame_context_idx] = cm->fc;
3584 // Frame was dropped, release scaled references.
3586 release_scaled_references(cpi);
3590 cpi->droppable = !frame_is_reference(cpi);
3593 vpx_usec_timer_mark(&cmptimer);
3594 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
3596 if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
3597 generate_psnr_packet(cpi);
3599 #if CONFIG_INTERNAL_STATS
3601 if (cpi->pass != 1) {
3602 cpi->bytes += *size;
3604 if (cm->show_frame) {
3607 if (cpi->b_calculate_psnr) {
3608 YV12_BUFFER_CONFIG *orig = cpi->Source;
3609 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
3610 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
3612 calc_psnr(orig, recon, &psnr);
3614 cpi->total += psnr.psnr[0];
3615 cpi->total_y += psnr.psnr[1];
3616 cpi->total_u += psnr.psnr[2];
3617 cpi->total_v += psnr.psnr[3];
3618 cpi->total_sq_error += psnr.sse[0];
3619 cpi->total_samples += psnr.samples[0];
3623 double frame_ssim2 = 0, weight = 0;
3624 #if CONFIG_VP9_POSTPROC
3625 vp9_deblock(cm->frame_to_show, &cm->post_proc_buffer,
3626 cm->lf.filter_level * 10 / 6);
3628 vp9_clear_system_state();
3630 calc_psnr(orig, pp, &psnr2);
3632 cpi->totalp += psnr2.psnr[0];
3633 cpi->totalp_y += psnr2.psnr[1];
3634 cpi->totalp_u += psnr2.psnr[2];
3635 cpi->totalp_v += psnr2.psnr[3];
3636 cpi->totalp_sq_error += psnr2.sse[0];
3637 cpi->totalp_samples += psnr2.samples[0];
3639 frame_ssim2 = vp9_calc_ssim(orig, recon, 1, &weight);
3641 cpi->summed_quality += frame_ssim2 * weight;
3642 cpi->summed_weights += weight;
3644 frame_ssim2 = vp9_calc_ssim(orig, &cm->post_proc_buffer, 1, &weight);
3646 cpi->summedp_quality += frame_ssim2 * weight;
3647 cpi->summedp_weights += weight;
3650 FILE *f = fopen("q_used.stt", "a");
3651 fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
3652 cpi->common.current_video_frame, y2, u2, v2,
3653 frame_psnr2, frame_ssim2);
3660 if (cpi->b_calculate_ssimg) {
3661 double y, u, v, frame_all;
3662 frame_all = vp9_calc_ssimg(cpi->Source, cm->frame_to_show, &y, &u, &v);
3663 cpi->total_ssimg_y += y;
3664 cpi->total_ssimg_u += u;
3665 cpi->total_ssimg_v += v;
3666 cpi->total_ssimg_all += frame_all;
3676 int vp9_get_preview_raw_frame(VP9_PTR comp, YV12_BUFFER_CONFIG *dest,
3677 vp9_ppflags_t *flags) {
3678 VP9_COMP *cpi = (VP9_COMP *) comp;
3680 if (!cpi->common.show_frame) {
3684 #if CONFIG_VP9_POSTPROC
3685 ret = vp9_post_proc_frame(&cpi->common, dest, flags);
3688 if (cpi->common.frame_to_show) {
3689 *dest = *cpi->common.frame_to_show;
3690 dest->y_width = cpi->common.width;
3691 dest->y_height = cpi->common.height;
3692 dest->uv_width = cpi->common.width >> cpi->common.subsampling_x;
3693 dest->uv_height = cpi->common.height >> cpi->common.subsampling_y;
3699 #endif // !CONFIG_VP9_POSTPROC
3700 vp9_clear_system_state();
3705 int vp9_set_roimap(VP9_PTR comp, unsigned char *map, unsigned int rows,
3706 unsigned int cols, int delta_q[MAX_SEGMENTS],
3707 int delta_lf[MAX_SEGMENTS],
3708 unsigned int threshold[MAX_SEGMENTS]) {
3709 VP9_COMP *cpi = (VP9_COMP *) comp;
3710 signed char feature_data[SEG_LVL_MAX][MAX_SEGMENTS];
3711 struct segmentation *seg = &cpi->common.seg;
3714 if (cpi->common.mb_rows != rows || cpi->common.mb_cols != cols)
3718 vp9_disable_segmentation((VP9_PTR)cpi);
3722 // Set the segmentation Map
3723 vp9_set_segmentation_map((VP9_PTR)cpi, map);
3725 // Activate segmentation.
3726 vp9_enable_segmentation((VP9_PTR)cpi);
3728 // Set up the quant, LF and breakout threshold segment data
3729 for (i = 0; i < MAX_SEGMENTS; i++) {
3730 feature_data[SEG_LVL_ALT_Q][i] = delta_q[i];
3731 feature_data[SEG_LVL_ALT_LF][i] = delta_lf[i];
3732 cpi->segment_encode_breakout[i] = threshold[i];
3735 // Enable the loop and quant changes in the feature mask
3736 for (i = 0; i < MAX_SEGMENTS; i++) {
3738 vp9_enable_segfeature(seg, i, SEG_LVL_ALT_Q);
3740 vp9_disable_segfeature(seg, i, SEG_LVL_ALT_Q);
3743 vp9_enable_segfeature(seg, i, SEG_LVL_ALT_LF);
3745 vp9_disable_segfeature(seg, i, SEG_LVL_ALT_LF);
3748 // Initialize the feature data structure
3749 // SEGMENT_DELTADATA 0, SEGMENT_ABSDATA 1
3750 vp9_set_segment_data((VP9_PTR)cpi, &feature_data[0][0], SEGMENT_DELTADATA);
3755 int vp9_set_active_map(VP9_PTR comp, unsigned char *map,
3756 unsigned int rows, unsigned int cols) {
3757 VP9_COMP *cpi = (VP9_COMP *) comp;
3759 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
3761 vpx_memcpy(cpi->active_map, map, rows * cols);
3762 cpi->active_map_enabled = 1;
3764 cpi->active_map_enabled = 0;
3769 // cpi->active_map_enabled = 0;
3774 int vp9_set_internal_size(VP9_PTR comp,
3775 VPX_SCALING horiz_mode, VPX_SCALING vert_mode) {
3776 VP9_COMP *cpi = (VP9_COMP *) comp;
3777 VP9_COMMON *cm = &cpi->common;
3778 int hr = 0, hs = 0, vr = 0, vs = 0;
3780 if (horiz_mode > ONETWO || vert_mode > ONETWO)
3783 Scale2Ratio(horiz_mode, &hr, &hs);
3784 Scale2Ratio(vert_mode, &vr, &vs);
3786 // always go to the next whole number
3787 cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
3788 cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
3790 assert(cm->width <= cpi->initial_width);
3791 assert(cm->height <= cpi->initial_height);
3792 update_frame_size(cpi);
3796 int vp9_set_size_literal(VP9_PTR comp, unsigned int width,
3797 unsigned int height) {
3798 VP9_COMP *cpi = (VP9_COMP *)comp;
3799 VP9_COMMON *cm = &cpi->common;
3801 check_initial_width(cpi, NULL);
3805 if (cm->width * 5 < cpi->initial_width) {
3806 cm->width = cpi->initial_width / 5 + 1;
3807 printf("Warning: Desired width too small, changed to %d \n", cm->width);
3809 if (cm->width > cpi->initial_width) {
3810 cm->width = cpi->initial_width;
3811 printf("Warning: Desired width too large, changed to %d \n", cm->width);
3816 cm->height = height;
3817 if (cm->height * 5 < cpi->initial_height) {
3818 cm->height = cpi->initial_height / 5 + 1;
3819 printf("Warning: Desired height too small, changed to %d \n", cm->height);
3821 if (cm->height > cpi->initial_height) {
3822 cm->height = cpi->initial_height;
3823 printf("Warning: Desired height too large, changed to %d \n", cm->height);
3827 assert(cm->width <= cpi->initial_width);
3828 assert(cm->height <= cpi->initial_height);
3829 update_frame_size(cpi);
3833 void vp9_set_svc(VP9_PTR comp, int use_svc) {
3834 VP9_COMP *cpi = (VP9_COMP *)comp;
3835 cpi->use_svc = use_svc;
3839 int vp9_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest) {
3843 uint8_t *src = source->y_buffer;
3844 uint8_t *dst = dest->y_buffer;
3846 // Loop through the Y plane raw and reconstruction data summing
3847 // (square differences)
3848 for (i = 0; i < source->y_height; i += 16) {
3849 for (j = 0; j < source->y_width; j += 16) {
3851 total += vp9_mse16x16(src + j, source->y_stride, dst + j, dest->y_stride,
3855 src += 16 * source->y_stride;
3856 dst += 16 * dest->y_stride;
3863 int vp9_get_quantizer(VP9_PTR c) {
3864 return ((VP9_COMP *)c)->common.base_qindex;