]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_onyx_if.c
Merge "Some cleanups on rate control"
[libvpx] / vp9 / encoder / vp9_onyx_if.c
1 /*
2  * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
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.
9  */
10
11 #include <math.h>
12 #include <stdio.h>
13 #include <limits.h>
14
15 #include "./vpx_config.h"
16 #include "./vpx_scale_rtcd.h"
17
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"
23 #endif
24 #include "vp9/common/vp9_reconinter.h"
25 #include "vp9/common/vp9_systemdependent.h"
26 #include "vp9/common/vp9_tile_common.h"
27
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"
39
40 #include "vpx_ports/vpx_timer.h"
41
42 static void set_default_lf_deltas(struct loopfilter *lf);
43
44 #define DEFAULT_INTERP_FILTER SWITCHABLE
45
46 #define SHARP_FILTER_QTHRESH 0          /* Q threshold for 8-tap sharp filter */
47
48 #define ALTREF_HIGH_PRECISION_MV 1      // Whether to use high precision mv
49                                          //  for altref computation.
50 #define HIGH_PRECISION_MV_QTHRESH 200   // Q threshold for high precision
51                                          // mv. Choose a very high value for
52                                          // now so that HIGH_PRECISION is always
53                                          // chosen.
54
55 // Masks for partially or completely disabling split mode
56 #define DISABLE_ALL_SPLIT         0x3F
57 #define DISABLE_ALL_INTER_SPLIT   0x1F
58 #define DISABLE_COMPOUND_SPLIT    0x18
59 #define LAST_AND_INTRA_SPLIT_ONLY 0x1E
60
61 #if CONFIG_INTERNAL_STATS
62 extern double vp9_calc_ssim(YV12_BUFFER_CONFIG *source,
63                             YV12_BUFFER_CONFIG *dest, int lumamask,
64                             double *weight);
65
66
67 extern double vp9_calc_ssimg(YV12_BUFFER_CONFIG *source,
68                              YV12_BUFFER_CONFIG *dest, double *ssim_y,
69                              double *ssim_u, double *ssim_v);
70
71
72 #endif
73
74 // #define OUTPUT_YUV_REC
75
76 #ifdef OUTPUT_YUV_SRC
77 FILE *yuv_file;
78 #endif
79 #ifdef OUTPUT_YUV_REC
80 FILE *yuv_rec_file;
81 #endif
82
83 #if 0
84 FILE *framepsnr;
85 FILE *kf_list;
86 FILE *keyfile;
87 #endif
88
89
90 #ifdef ENTROPY_STATS
91 extern int intra_mode_stats[INTRA_MODES]
92                            [INTRA_MODES]
93                            [INTRA_MODES];
94 #endif
95
96 #ifdef MODE_STATS
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();
101 #endif
102
103 #ifdef SPEEDSTATS
104 unsigned int frames_at_speed[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
105                                     0, 0, 0};
106 #endif
107
108 #if defined(SECTIONBITS_OUTPUT)
109 extern unsigned __int64 Sectionbits[500];
110 #endif
111
112 extern void vp9_init_quantizer(VP9_COMP *cpi);
113
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};
116
117 static INLINE void Scale2Ratio(int mode, int *hr, int *hs) {
118   switch (mode) {
119     case NORMAL:
120       *hr = 1;
121       *hs = 1;
122       break;
123     case FOURFIVE:
124       *hr = 4;
125       *hs = 5;
126       break;
127     case THREEFIVE:
128       *hr = 3;
129       *hs = 5;
130     break;
131     case ONETWO:
132       *hr = 1;
133       *hs = 2;
134     break;
135     default:
136       *hr = 1;
137       *hs = 1;
138        assert(0);
139       break;
140   }
141 }
142
143 static void set_mvcost(VP9_COMP *cpi) {
144   MACROBLOCK *const mb = &cpi->mb;
145   if (cpi->common.allow_high_precision_mv) {
146     mb->mvcost = mb->nmvcost_hp;
147     mb->mvsadcost = mb->nmvsadcost_hp;
148   } else {
149     mb->mvcost = mb->nmvcost;
150     mb->mvsadcost = mb->nmvsadcost;
151   }
152 }
153
154 void vp9_initialize_enc() {
155   static int init_done = 0;
156
157   if (!init_done) {
158     vp9_initialize_common();
159     vp9_tokenize_initialize();
160     vp9_init_quant_tables();
161     vp9_init_me_luts();
162     vp9_init_minq_luts();
163     // init_base_skip_probs();
164     vp9_entropy_mv_init();
165     init_done = 1;
166   }
167 }
168
169 static void setup_features(VP9_COMMON *cm) {
170   struct loopfilter *const lf = &cm->lf;
171   struct segmentation *const seg = &cm->seg;
172
173   // Set up default state for MB feature flags
174   seg->enabled = 0;
175
176   seg->update_map = 0;
177   seg->update_data = 0;
178   vpx_memset(seg->tree_probs, 255, sizeof(seg->tree_probs));
179
180   vp9_clearall_segfeatures(seg);
181
182   lf->mode_ref_delta_enabled = 0;
183   lf->mode_ref_delta_update = 0;
184   vp9_zero(lf->ref_deltas);
185   vp9_zero(lf->mode_deltas);
186   vp9_zero(lf->last_ref_deltas);
187   vp9_zero(lf->last_mode_deltas);
188
189   set_default_lf_deltas(lf);
190 }
191
192 static void dealloc_compressor_data(VP9_COMP *cpi) {
193   // Delete sementation map
194   vpx_free(cpi->segmentation_map);
195   cpi->segmentation_map = 0;
196   vpx_free(cpi->common.last_frame_seg_map);
197   cpi->common.last_frame_seg_map = 0;
198   vpx_free(cpi->coding_context.last_frame_seg_map_copy);
199   cpi->coding_context.last_frame_seg_map_copy = 0;
200
201   vpx_free(cpi->complexity_map);
202   cpi->complexity_map = 0;
203   vpx_free(cpi->active_map);
204   cpi->active_map = 0;
205
206   vp9_free_frame_buffers(&cpi->common);
207
208   vp9_free_frame_buffer(&cpi->last_frame_uf);
209   vp9_free_frame_buffer(&cpi->scaled_source);
210   vp9_free_frame_buffer(&cpi->alt_ref_buffer);
211   vp9_lookahead_destroy(cpi->lookahead);
212
213   vpx_free(cpi->tok);
214   cpi->tok = 0;
215
216   // Activity mask based per mb zbin adjustments
217   vpx_free(cpi->mb_activity_map);
218   cpi->mb_activity_map = 0;
219   vpx_free(cpi->mb_norm_activity_map);
220   cpi->mb_norm_activity_map = 0;
221
222   vpx_free(cpi->above_context[0]);
223   cpi->above_context[0] = NULL;
224
225   vpx_free(cpi->above_seg_context);
226   cpi->above_seg_context = NULL;
227 }
228
229 // Computes a q delta (in "q index" terms) to get from a starting q value
230 // to a target value
231 // target q value
232 int vp9_compute_qdelta(VP9_COMP *cpi, double qstart, double qtarget) {
233   int i;
234   int start_index = cpi->rc.worst_quality;
235   int target_index = cpi->rc.worst_quality;
236
237   // Convert the average q value to an index.
238   for (i = cpi->rc.best_quality; i < cpi->rc.worst_quality; i++) {
239     start_index = i;
240     if (vp9_convert_qindex_to_q(i) >= qstart)
241       break;
242   }
243
244   // Convert the q target to an index
245   for (i = cpi->rc.best_quality; i < cpi->rc.worst_quality; i++) {
246     target_index = i;
247     if (vp9_convert_qindex_to_q(i) >= qtarget)
248       break;
249   }
250
251   return target_index - start_index;
252 }
253
254 // Computes a q delta (in "q index" terms) to get from a starting q value
255 // to a value that should equate to thegiven rate ratio.
256
257 int vp9_compute_qdelta_by_rate(VP9_COMP *cpi,
258                                double base_q_index, double rate_target_ratio) {
259   int i;
260   int base_bits_per_mb;
261   int target_bits_per_mb;
262   int target_index = cpi->rc.worst_quality;
263
264   // Make SURE use of floating point in this function is safe.
265   vp9_clear_system_state();
266
267   // Look up the current projected bits per block for the base index
268   base_bits_per_mb = vp9_bits_per_mb(cpi->common.frame_type,
269                                      base_q_index, 1.0);
270
271   // Find the target bits per mb based on the base value and given ratio.
272   target_bits_per_mb = rate_target_ratio * base_bits_per_mb;
273
274   // Convert the q target to an index
275   for (i = cpi->rc.best_quality; i < cpi->rc.worst_quality; i++) {
276     target_index = i;
277     if (vp9_bits_per_mb(cpi->common.frame_type,
278                         i, 1.0) <= target_bits_per_mb )
279       break;
280   }
281
282   return target_index - base_q_index;
283 }
284
285 // This function sets up a set of segments with delta Q values around
286 // the baseline frame quantizer.
287 static void setup_in_frame_q_adj(VP9_COMP *cpi) {
288   VP9_COMMON *cm = &cpi->common;
289   struct segmentation *seg = &cm->seg;
290   // double q_ratio;
291   int segment;
292   int qindex_delta;
293
294   // Make SURE use of floating point in this function is safe.
295   vp9_clear_system_state();
296
297   if (cm->frame_type == KEY_FRAME ||
298       cpi->refresh_alt_ref_frame ||
299       (cpi->refresh_golden_frame && !cpi->is_src_frame_alt_ref)) {
300     // Clear down the segment map
301     vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
302
303     // Clear down the complexity map used for rd
304     vpx_memset(cpi->complexity_map, 0, cm->mi_rows * cm->mi_cols);
305
306     // Enable segmentation
307     vp9_enable_segmentation((VP9_PTR)cpi);
308     vp9_clearall_segfeatures(seg);
309
310     // Select delta coding method
311     seg->abs_delta = SEGMENT_DELTADATA;
312
313     // Segment 0 "Q" feature is disabled so it defaults to the baseline Q
314     vp9_disable_segfeature(seg, 0, SEG_LVL_ALT_Q);
315
316     // Use some of the segments for in frame Q adjustment
317     for (segment = 1; segment < 3; segment++) {
318       qindex_delta =
319         vp9_compute_qdelta_by_rate(cpi, cm->base_qindex,
320                                    in_frame_q_adj_ratio[segment]);
321       vp9_enable_segfeature(seg, segment, SEG_LVL_ALT_Q);
322       vp9_set_segdata(seg, segment, SEG_LVL_ALT_Q, qindex_delta);
323     }
324   }
325 }
326
327 static void configure_static_seg_features(VP9_COMP *cpi) {
328   VP9_COMMON *cm = &cpi->common;
329   struct segmentation *seg = &cm->seg;
330
331   int high_q = (int)(cpi->rc.avg_q > 48.0);
332   int qi_delta;
333
334   // Disable and clear down for KF
335   if (cm->frame_type == KEY_FRAME) {
336     // Clear down the global segmentation map
337     vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
338     seg->update_map = 0;
339     seg->update_data = 0;
340     cpi->static_mb_pct = 0;
341
342     // Disable segmentation
343     vp9_disable_segmentation((VP9_PTR)cpi);
344
345     // Clear down the segment features.
346     vp9_clearall_segfeatures(seg);
347   } else if (cpi->refresh_alt_ref_frame) {
348     // If this is an alt ref frame
349     // Clear down the global segmentation map
350     vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
351     seg->update_map = 0;
352     seg->update_data = 0;
353     cpi->static_mb_pct = 0;
354
355     // Disable segmentation and individual segment features by default
356     vp9_disable_segmentation((VP9_PTR)cpi);
357     vp9_clearall_segfeatures(seg);
358
359     // Scan frames from current to arf frame.
360     // This function re-enables segmentation if appropriate.
361     vp9_update_mbgraph_stats(cpi);
362
363     // If segmentation was enabled set those features needed for the
364     // arf itself.
365     if (seg->enabled) {
366       seg->update_map = 1;
367       seg->update_data = 1;
368
369       qi_delta = vp9_compute_qdelta(
370           cpi, cpi->rc.avg_q, (cpi->rc.avg_q * 0.875));
371       vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, (qi_delta - 2));
372       vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
373
374       vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
375       vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
376
377       // Where relevant assume segment data is delta data
378       seg->abs_delta = SEGMENT_DELTADATA;
379     }
380   } else if (seg->enabled) {
381     // All other frames if segmentation has been enabled
382
383     // First normal frame in a valid gf or alt ref group
384     if (cpi->rc.frames_since_golden == 0) {
385       // Set up segment features for normal frames in an arf group
386       if (cpi->source_alt_ref_active) {
387         seg->update_map = 0;
388         seg->update_data = 1;
389         seg->abs_delta = SEGMENT_DELTADATA;
390
391         qi_delta = vp9_compute_qdelta(cpi, cpi->rc.avg_q,
392                                       (cpi->rc.avg_q * 1.125));
393         vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, (qi_delta + 2));
394         vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
395
396         vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
397         vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
398
399         // Segment coding disabled for compred testing
400         if (high_q || (cpi->static_mb_pct == 100)) {
401           vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
402           vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
403           vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
404         }
405       } else {
406         // Disable segmentation and clear down features if alt ref
407         // is not active for this group
408
409         vp9_disable_segmentation((VP9_PTR)cpi);
410
411         vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
412
413         seg->update_map = 0;
414         seg->update_data = 0;
415
416         vp9_clearall_segfeatures(seg);
417       }
418     } else if (cpi->is_src_frame_alt_ref) {
419       // Special case where we are coding over the top of a previous
420       // alt ref frame.
421       // Segment coding disabled for compred testing
422
423       // Enable ref frame features for segment 0 as well
424       vp9_enable_segfeature(seg, 0, SEG_LVL_REF_FRAME);
425       vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
426
427       // All mbs should use ALTREF_FRAME
428       vp9_clear_segdata(seg, 0, SEG_LVL_REF_FRAME);
429       vp9_set_segdata(seg, 0, SEG_LVL_REF_FRAME, ALTREF_FRAME);
430       vp9_clear_segdata(seg, 1, SEG_LVL_REF_FRAME);
431       vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
432
433       // Skip all MBs if high Q (0,0 mv and skip coeffs)
434       if (high_q) {
435         vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
436         vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
437       }
438       // Enable data update
439       seg->update_data = 1;
440     } else {
441       // All other frames.
442
443       // No updates.. leave things as they are.
444       seg->update_map = 0;
445       seg->update_data = 0;
446     }
447   }
448 }
449
450 // DEBUG: Print out the segment id of each MB in the current frame.
451 static void print_seg_map(VP9_COMP *cpi) {
452   VP9_COMMON *cm = &cpi->common;
453   int row, col;
454   int map_index = 0;
455   FILE *statsfile = fopen("segmap.stt", "a");
456
457   fprintf(statsfile, "%10d\n", cm->current_video_frame);
458
459   for (row = 0; row < cpi->common.mi_rows; row++) {
460     for (col = 0; col < cpi->common.mi_cols; col++) {
461       fprintf(statsfile, "%10d", cpi->segmentation_map[map_index]);
462       map_index++;
463     }
464     fprintf(statsfile, "\n");
465   }
466   fprintf(statsfile, "\n");
467
468   fclose(statsfile);
469 }
470
471 static void update_reference_segmentation_map(VP9_COMP *cpi) {
472   VP9_COMMON *const cm = &cpi->common;
473   int row, col;
474   MODE_INFO **mi_8x8, **mi_8x8_ptr = cm->mi_grid_visible;
475   uint8_t *cache_ptr = cm->last_frame_seg_map, *cache;
476
477   for (row = 0; row < cm->mi_rows; row++) {
478     mi_8x8 = mi_8x8_ptr;
479     cache = cache_ptr;
480     for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
481       cache[0] = mi_8x8[0]->mbmi.segment_id;
482     mi_8x8_ptr += cm->mode_info_stride;
483     cache_ptr += cm->mi_cols;
484   }
485 }
486
487 static void set_default_lf_deltas(struct loopfilter *lf) {
488   lf->mode_ref_delta_enabled = 1;
489   lf->mode_ref_delta_update = 1;
490
491   vp9_zero(lf->ref_deltas);
492   vp9_zero(lf->mode_deltas);
493
494   // Test of ref frame deltas
495   lf->ref_deltas[INTRA_FRAME] = 2;
496   lf->ref_deltas[LAST_FRAME] = 0;
497   lf->ref_deltas[GOLDEN_FRAME] = -2;
498   lf->ref_deltas[ALTREF_FRAME] = -2;
499
500   lf->mode_deltas[0] = 0;   // Zero
501   lf->mode_deltas[1] = 0;   // New mv
502 }
503
504 static void set_rd_speed_thresholds(VP9_COMP *cpi, int mode) {
505   SPEED_FEATURES *sf = &cpi->sf;
506   int i;
507
508   // Set baseline threshold values
509   for (i = 0; i < MAX_MODES; ++i)
510     sf->thresh_mult[i] = mode == 0 ? -500 : 0;
511
512   sf->thresh_mult[THR_NEARESTMV] = 0;
513   sf->thresh_mult[THR_NEARESTG] = 0;
514   sf->thresh_mult[THR_NEARESTA] = 0;
515
516   sf->thresh_mult[THR_DC] += 1000;
517
518   sf->thresh_mult[THR_NEWMV] += 1000;
519   sf->thresh_mult[THR_NEWA] += 1000;
520   sf->thresh_mult[THR_NEWG] += 1000;
521
522   sf->thresh_mult[THR_NEARMV] += 1000;
523   sf->thresh_mult[THR_NEARA] += 1000;
524   sf->thresh_mult[THR_COMP_NEARESTLA] += 1000;
525   sf->thresh_mult[THR_COMP_NEARESTGA] += 1000;
526
527   sf->thresh_mult[THR_TM] += 1000;
528
529   sf->thresh_mult[THR_COMP_NEARLA] += 1500;
530   sf->thresh_mult[THR_COMP_NEWLA] += 2000;
531   sf->thresh_mult[THR_NEARG] += 1000;
532   sf->thresh_mult[THR_COMP_NEARGA] += 1500;
533   sf->thresh_mult[THR_COMP_NEWGA] += 2000;
534
535   sf->thresh_mult[THR_ZEROMV] += 2000;
536   sf->thresh_mult[THR_ZEROG] += 2000;
537   sf->thresh_mult[THR_ZEROA] += 2000;
538   sf->thresh_mult[THR_COMP_ZEROLA] += 2500;
539   sf->thresh_mult[THR_COMP_ZEROGA] += 2500;
540
541   sf->thresh_mult[THR_H_PRED] += 2000;
542   sf->thresh_mult[THR_V_PRED] += 2000;
543   sf->thresh_mult[THR_D45_PRED ] += 2500;
544   sf->thresh_mult[THR_D135_PRED] += 2500;
545   sf->thresh_mult[THR_D117_PRED] += 2500;
546   sf->thresh_mult[THR_D153_PRED] += 2500;
547   sf->thresh_mult[THR_D207_PRED] += 2500;
548   sf->thresh_mult[THR_D63_PRED] += 2500;
549
550   /* disable frame modes if flags not set */
551   if (!(cpi->ref_frame_flags & VP9_LAST_FLAG)) {
552     sf->thresh_mult[THR_NEWMV    ] = INT_MAX;
553     sf->thresh_mult[THR_NEARESTMV] = INT_MAX;
554     sf->thresh_mult[THR_ZEROMV   ] = INT_MAX;
555     sf->thresh_mult[THR_NEARMV   ] = INT_MAX;
556   }
557   if (!(cpi->ref_frame_flags & VP9_GOLD_FLAG)) {
558     sf->thresh_mult[THR_NEARESTG ] = INT_MAX;
559     sf->thresh_mult[THR_ZEROG    ] = INT_MAX;
560     sf->thresh_mult[THR_NEARG    ] = INT_MAX;
561     sf->thresh_mult[THR_NEWG     ] = INT_MAX;
562   }
563   if (!(cpi->ref_frame_flags & VP9_ALT_FLAG)) {
564     sf->thresh_mult[THR_NEARESTA ] = INT_MAX;
565     sf->thresh_mult[THR_ZEROA    ] = INT_MAX;
566     sf->thresh_mult[THR_NEARA    ] = INT_MAX;
567     sf->thresh_mult[THR_NEWA     ] = INT_MAX;
568   }
569
570   if ((cpi->ref_frame_flags & (VP9_LAST_FLAG | VP9_ALT_FLAG)) !=
571       (VP9_LAST_FLAG | VP9_ALT_FLAG)) {
572     sf->thresh_mult[THR_COMP_ZEROLA   ] = INT_MAX;
573     sf->thresh_mult[THR_COMP_NEARESTLA] = INT_MAX;
574     sf->thresh_mult[THR_COMP_NEARLA   ] = INT_MAX;
575     sf->thresh_mult[THR_COMP_NEWLA    ] = INT_MAX;
576   }
577   if ((cpi->ref_frame_flags & (VP9_GOLD_FLAG | VP9_ALT_FLAG)) !=
578       (VP9_GOLD_FLAG | VP9_ALT_FLAG)) {
579     sf->thresh_mult[THR_COMP_ZEROGA   ] = INT_MAX;
580     sf->thresh_mult[THR_COMP_NEARESTGA] = INT_MAX;
581     sf->thresh_mult[THR_COMP_NEARGA   ] = INT_MAX;
582     sf->thresh_mult[THR_COMP_NEWGA    ] = INT_MAX;
583   }
584 }
585
586 static void set_rd_speed_thresholds_sub8x8(VP9_COMP *cpi, int mode) {
587   SPEED_FEATURES *sf = &cpi->sf;
588   int i;
589
590   for (i = 0; i < MAX_REFS; ++i)
591     sf->thresh_mult_sub8x8[i] = mode == 0 ? -500 : 0;
592
593   sf->thresh_mult_sub8x8[THR_LAST] += 2500;
594   sf->thresh_mult_sub8x8[THR_GOLD] += 2500;
595   sf->thresh_mult_sub8x8[THR_ALTR] += 2500;
596   sf->thresh_mult_sub8x8[THR_INTRA] += 2500;
597   sf->thresh_mult_sub8x8[THR_COMP_LA] += 4500;
598   sf->thresh_mult_sub8x8[THR_COMP_GA] += 4500;
599
600   // Check for masked out split cases.
601   for (i = 0; i < MAX_REFS; i++) {
602     if (sf->disable_split_mask & (1 << i))
603       sf->thresh_mult_sub8x8[i] = INT_MAX;
604   }
605
606   // disable mode test if frame flag is not set
607   if (!(cpi->ref_frame_flags & VP9_LAST_FLAG))
608     sf->thresh_mult_sub8x8[THR_LAST] = INT_MAX;
609   if (!(cpi->ref_frame_flags & VP9_GOLD_FLAG))
610     sf->thresh_mult_sub8x8[THR_GOLD] = INT_MAX;
611   if (!(cpi->ref_frame_flags & VP9_ALT_FLAG))
612     sf->thresh_mult_sub8x8[THR_ALTR] = INT_MAX;
613   if ((cpi->ref_frame_flags & (VP9_LAST_FLAG | VP9_ALT_FLAG)) !=
614       (VP9_LAST_FLAG | VP9_ALT_FLAG))
615     sf->thresh_mult_sub8x8[THR_COMP_LA] = INT_MAX;
616   if ((cpi->ref_frame_flags & (VP9_GOLD_FLAG | VP9_ALT_FLAG)) !=
617       (VP9_GOLD_FLAG | VP9_ALT_FLAG))
618     sf->thresh_mult_sub8x8[THR_COMP_GA] = INT_MAX;
619 }
620
621 void vp9_set_speed_features(VP9_COMP *cpi) {
622   SPEED_FEATURES *sf = &cpi->sf;
623   int mode = cpi->compressor_speed;
624   int speed = cpi->speed;
625   int i;
626
627   // Only modes 0 and 1 supported for now in experimental code basae
628   if (mode > 1)
629     mode = 1;
630
631   for (i = 0; i < MAX_MODES; ++i)
632     cpi->mode_chosen_counts[i] = 0;
633
634   // best quality defaults
635   sf->RD = 1;
636   sf->search_method = NSTEP;
637   sf->auto_filter = 1;
638   sf->recode_loop = 1;
639   sf->subpel_search_method = SUBPEL_TREE;
640   sf->subpel_iters_per_step = 2;
641   sf->optimize_coefficients = !cpi->oxcf.lossless;
642   sf->reduce_first_step_size = 0;
643   sf->auto_mv_step_size = 0;
644   sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
645   sf->comp_inter_joint_search_thresh = BLOCK_4X4;
646   sf->adaptive_rd_thresh = 0;
647   sf->use_lastframe_partitioning = LAST_FRAME_PARTITION_OFF;
648   sf->tx_size_search_method = USE_FULL_RD;
649   sf->use_lp32x32fdct = 0;
650   sf->adaptive_motion_search = 0;
651   sf->use_avoid_tested_higherror = 0;
652   sf->reference_masking = 0;
653   sf->use_one_partition_size_always = 0;
654   sf->less_rectangular_check = 0;
655   sf->use_square_partition_only = 0;
656   sf->auto_min_max_partition_size = 0;
657   sf->max_partition_size = BLOCK_64X64;
658   sf->min_partition_size = BLOCK_4X4;
659   sf->adjust_partitioning_from_last_frame = 0;
660   sf->last_partitioning_redo_frequency = 4;
661   sf->disable_split_mask = 0;
662   sf->mode_search_skip_flags = 0;
663   sf->disable_split_var_thresh = 0;
664   sf->disable_filter_search_var_thresh = 0;
665   for (i = 0; i < TX_SIZES; i++) {
666     sf->intra_y_mode_mask[i] = ALL_INTRA_MODES;
667     sf->intra_uv_mode_mask[i] = ALL_INTRA_MODES;
668   }
669   sf->use_rd_breakout = 0;
670   sf->skip_encode_sb = 0;
671   sf->use_uv_intra_rd_estimate = 0;
672   sf->use_fast_lpf_pick = 0;
673   sf->use_fast_coef_updates = 0;
674   sf->using_small_partition_info = 0;
675   sf->mode_skip_start = MAX_MODES;  // Mode index at which mode skip mask set
676
677 #if CONFIG_MULTIPLE_ARF
678   // Switch segmentation off.
679   sf->static_segmentation = 0;
680 #else
681   sf->static_segmentation = 0;
682 #endif
683
684   switch (mode) {
685     case 0:  // This is the best quality mode.
686       break;
687
688     case 1:
689 #if CONFIG_MULTIPLE_ARF
690       // Switch segmentation off.
691       sf->static_segmentation = 0;
692 #else
693       sf->static_segmentation = 0;
694 #endif
695       sf->use_avoid_tested_higherror = 1;
696       sf->adaptive_rd_thresh = 1;
697       sf->recode_loop = (speed < 1);
698
699       if (speed == 1) {
700         sf->use_square_partition_only = !frame_is_intra_only(&cpi->common);
701         sf->less_rectangular_check  = 1;
702         sf->tx_size_search_method = frame_is_intra_only(&cpi->common)
703                                      ? USE_FULL_RD : USE_LARGESTALL;
704
705         if (MIN(cpi->common.width, cpi->common.height) >= 720)
706           sf->disable_split_mask = cpi->common.show_frame ?
707               DISABLE_ALL_SPLIT : DISABLE_ALL_INTER_SPLIT;
708         else
709           sf->disable_split_mask = DISABLE_COMPOUND_SPLIT;
710
711         sf->use_rd_breakout = 1;
712         sf->adaptive_motion_search = 1;
713         sf->auto_mv_step_size = 1;
714         sf->adaptive_rd_thresh = 2;
715         sf->recode_loop = 2;
716         sf->intra_y_mode_mask[TX_32X32] = INTRA_DC_H_V;
717         sf->intra_uv_mode_mask[TX_32X32] = INTRA_DC_H_V;
718         sf->intra_uv_mode_mask[TX_16X16] = INTRA_DC_H_V;
719       }
720       if (speed == 2) {
721         sf->use_square_partition_only = !frame_is_intra_only(&cpi->common);
722         sf->less_rectangular_check  = 1;
723         sf->tx_size_search_method = frame_is_intra_only(&cpi->common)
724                                      ? USE_FULL_RD : USE_LARGESTALL;
725
726         if (MIN(cpi->common.width, cpi->common.height) >= 720)
727           sf->disable_split_mask = cpi->common.show_frame ?
728               DISABLE_ALL_SPLIT : DISABLE_ALL_INTER_SPLIT;
729         else
730           sf->disable_split_mask = LAST_AND_INTRA_SPLIT_ONLY;
731
732
733         sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
734                                      FLAG_SKIP_INTRA_BESTINTER |
735                                      FLAG_SKIP_COMP_BESTINTRA |
736                                      FLAG_SKIP_INTRA_LOWVAR;
737
738         sf->use_rd_breakout = 1;
739         sf->adaptive_motion_search = 1;
740         sf->auto_mv_step_size = 1;
741
742         sf->disable_filter_search_var_thresh = 16;
743         sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
744
745         sf->auto_min_max_partition_size = 1;
746         sf->use_lastframe_partitioning = LAST_FRAME_PARTITION_LOW_MOTION;
747         sf->adjust_partitioning_from_last_frame = 1;
748         sf->last_partitioning_redo_frequency = 3;
749
750         sf->adaptive_rd_thresh = 2;
751         sf->recode_loop = 2;
752         sf->use_lp32x32fdct = 1;
753         sf->mode_skip_start = 11;
754         sf->intra_y_mode_mask[TX_32X32] = INTRA_DC_H_V;
755         sf->intra_y_mode_mask[TX_16X16] = INTRA_DC_H_V;
756         sf->intra_uv_mode_mask[TX_32X32] = INTRA_DC_H_V;
757         sf->intra_uv_mode_mask[TX_16X16] = INTRA_DC_H_V;
758       }
759       if (speed == 3) {
760         sf->use_square_partition_only = 1;
761         sf->tx_size_search_method = USE_LARGESTALL;
762
763         if (MIN(cpi->common.width, cpi->common.height) >= 720)
764           sf->disable_split_mask = DISABLE_ALL_SPLIT;
765         else
766           sf->disable_split_mask = DISABLE_ALL_INTER_SPLIT;
767
768         sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
769                                      FLAG_SKIP_INTRA_BESTINTER |
770                                      FLAG_SKIP_COMP_BESTINTRA |
771                                      FLAG_SKIP_INTRA_LOWVAR;
772
773         sf->use_rd_breakout = 1;
774         sf->adaptive_motion_search = 1;
775         sf->auto_mv_step_size = 1;
776
777         sf->disable_filter_search_var_thresh = 16;
778         sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
779
780         sf->auto_min_max_partition_size = 1;
781         sf->use_lastframe_partitioning = LAST_FRAME_PARTITION_ALL;
782         sf->adjust_partitioning_from_last_frame = 1;
783         sf->last_partitioning_redo_frequency = 3;
784
785         sf->use_uv_intra_rd_estimate = 1;
786         sf->skip_encode_sb = 1;
787         sf->use_lp32x32fdct = 1;
788         sf->subpel_iters_per_step = 1;
789         sf->use_fast_coef_updates = 2;
790
791         sf->adaptive_rd_thresh = 4;
792         sf->mode_skip_start = 6;
793       }
794       if (speed == 4) {
795         sf->use_square_partition_only = 1;
796         sf->tx_size_search_method = USE_LARGESTALL;
797         sf->disable_split_mask = DISABLE_ALL_SPLIT;
798
799         sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
800                                      FLAG_SKIP_INTRA_BESTINTER |
801                                      FLAG_SKIP_COMP_BESTINTRA |
802                                      FLAG_SKIP_COMP_REFMISMATCH |
803                                      FLAG_SKIP_INTRA_LOWVAR |
804                                      FLAG_EARLY_TERMINATE;
805
806         sf->use_rd_breakout = 1;
807         sf->adaptive_motion_search = 1;
808         sf->auto_mv_step_size = 1;
809
810         sf->disable_filter_search_var_thresh = 16;
811         sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
812
813         sf->auto_min_max_partition_size = 1;
814         sf->use_lastframe_partitioning = LAST_FRAME_PARTITION_ALL;
815         sf->adjust_partitioning_from_last_frame = 1;
816         sf->last_partitioning_redo_frequency = 3;
817
818         sf->use_uv_intra_rd_estimate = 1;
819         sf->skip_encode_sb = 1;
820         sf->use_lp32x32fdct = 1;
821         sf->subpel_iters_per_step = 1;
822         sf->use_fast_coef_updates = 2;
823
824         sf->adaptive_rd_thresh = 4;
825         sf->mode_skip_start = 6;
826
827         /* sf->intra_y_mode_mask = INTRA_DC_ONLY;
828         sf->intra_uv_mode_mask = INTRA_DC_ONLY;
829         sf->search_method = BIGDIA;
830         sf->disable_split_var_thresh = 64;
831         sf->disable_filter_search_var_thresh = 64; */
832       }
833       if (speed == 5) {
834         sf->comp_inter_joint_search_thresh = BLOCK_SIZES;
835         sf->use_one_partition_size_always = 1;
836         sf->always_this_block_size = BLOCK_16X16;
837         sf->tx_size_search_method = frame_is_intra_only(&cpi->common) ?
838                                      USE_FULL_RD : USE_LARGESTALL;
839         sf->mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH |
840                                      FLAG_SKIP_INTRA_BESTINTER |
841                                      FLAG_SKIP_COMP_BESTINTRA |
842                                      FLAG_SKIP_COMP_REFMISMATCH |
843                                      FLAG_SKIP_INTRA_LOWVAR |
844                                      FLAG_EARLY_TERMINATE;
845         sf->use_rd_breakout = 1;
846         sf->use_lp32x32fdct = 1;
847         sf->optimize_coefficients = 0;
848         sf->auto_mv_step_size = 1;
849         // sf->reduce_first_step_size = 1;
850         // sf->reference_masking = 1;
851
852         sf->disable_split_mask = DISABLE_ALL_SPLIT;
853         sf->search_method = HEX;
854         sf->subpel_iters_per_step = 1;
855         sf->disable_split_var_thresh = 64;
856         sf->disable_filter_search_var_thresh = 96;
857         for (i = 0; i < TX_SIZES; i++) {
858           sf->intra_y_mode_mask[i] = INTRA_DC_ONLY;
859           sf->intra_uv_mode_mask[i] = INTRA_DC_ONLY;
860         }
861         sf->use_fast_coef_updates = 2;
862         sf->adaptive_rd_thresh = 4;
863         sf->mode_skip_start = 6;
864       }
865       break;
866   }; /* switch */
867
868   // Set rd thresholds based on mode and speed setting
869   set_rd_speed_thresholds(cpi, mode);
870   set_rd_speed_thresholds_sub8x8(cpi, mode);
871
872   // Slow quant, dct and trellis not worthwhile for first pass
873   // so make sure they are always turned off.
874   if (cpi->pass == 1) {
875     sf->optimize_coefficients = 0;
876   }
877
878   // No recode for 1 pass.
879   if (cpi->pass == 0) {
880     sf->recode_loop = 0;
881     sf->optimize_coefficients = 0;
882   }
883
884   cpi->mb.fwd_txm4x4 = vp9_fdct4x4;
885   if (cpi->oxcf.lossless || cpi->mb.e_mbd.lossless) {
886     cpi->mb.fwd_txm4x4 = vp9_fwht4x4;
887   }
888
889   if (cpi->sf.subpel_search_method == SUBPEL_ITERATIVE) {
890     cpi->find_fractional_mv_step = vp9_find_best_sub_pixel_iterative;
891     cpi->find_fractional_mv_step_comp = vp9_find_best_sub_pixel_comp_iterative;
892   } else if (cpi->sf.subpel_search_method == SUBPEL_TREE) {
893     cpi->find_fractional_mv_step = vp9_find_best_sub_pixel_tree;
894     cpi->find_fractional_mv_step_comp = vp9_find_best_sub_pixel_comp_tree;
895   }
896
897   cpi->mb.optimize = cpi->sf.optimize_coefficients == 1 && cpi->pass != 1;
898
899 #ifdef SPEEDSTATS
900   frames_at_speed[cpi->speed]++;
901 #endif
902 }
903
904 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
905   VP9_COMMON *cm = &cpi->common;
906
907   cpi->lookahead = vp9_lookahead_init(cpi->oxcf.width, cpi->oxcf.height,
908                                       cm->subsampling_x, cm->subsampling_y,
909                                       cpi->oxcf.lag_in_frames);
910   if (!cpi->lookahead)
911     vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
912                        "Failed to allocate lag buffers");
913
914   if (vp9_realloc_frame_buffer(&cpi->alt_ref_buffer,
915                                cpi->oxcf.width, cpi->oxcf.height,
916                                cm->subsampling_x, cm->subsampling_y,
917                                VP9BORDERINPIXELS))
918     vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
919                        "Failed to allocate altref buffer");
920 }
921
922 void vp9_alloc_compressor_data(VP9_COMP *cpi) {
923   VP9_COMMON *cm = &cpi->common;
924
925   if (vp9_alloc_frame_buffers(cm, cm->width, cm->height))
926     vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
927                        "Failed to allocate frame buffers");
928
929   if (vp9_alloc_frame_buffer(&cpi->last_frame_uf,
930                              cm->width, cm->height,
931                              cm->subsampling_x, cm->subsampling_y,
932                              VP9BORDERINPIXELS))
933     vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
934                        "Failed to allocate last frame buffer");
935
936   if (vp9_alloc_frame_buffer(&cpi->scaled_source,
937                              cm->width, cm->height,
938                              cm->subsampling_x, cm->subsampling_y,
939                              VP9BORDERINPIXELS))
940     vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
941                        "Failed to allocate scaled source buffer");
942
943   vpx_free(cpi->tok);
944
945   {
946     unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
947
948     CHECK_MEM_ERROR(cm, cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
949   }
950
951   vpx_free(cpi->mb_activity_map);
952   CHECK_MEM_ERROR(cm, cpi->mb_activity_map,
953                   vpx_calloc(sizeof(unsigned int),
954                              cm->mb_rows * cm->mb_cols));
955
956   vpx_free(cpi->mb_norm_activity_map);
957   CHECK_MEM_ERROR(cm, cpi->mb_norm_activity_map,
958                   vpx_calloc(sizeof(unsigned int),
959                              cm->mb_rows * cm->mb_cols));
960
961   // 2 contexts per 'mi unit', so that we have one context per 4x4 txfm
962   // block where mi unit size is 8x8.
963   vpx_free(cpi->above_context[0]);
964   CHECK_MEM_ERROR(cm, cpi->above_context[0],
965                   vpx_calloc(2 * mi_cols_aligned_to_sb(cm->mi_cols) *
966                              MAX_MB_PLANE,
967                              sizeof(*cpi->above_context[0])));
968
969   vpx_free(cpi->above_seg_context);
970   CHECK_MEM_ERROR(cm, cpi->above_seg_context,
971                   vpx_calloc(mi_cols_aligned_to_sb(cm->mi_cols),
972                              sizeof(*cpi->above_seg_context)));
973 }
974
975
976 static void update_frame_size(VP9_COMP *cpi) {
977   VP9_COMMON *cm = &cpi->common;
978
979   vp9_update_frame_size(cm);
980
981   // Update size of buffers local to this frame
982   if (vp9_realloc_frame_buffer(&cpi->last_frame_uf,
983                                cm->width, cm->height,
984                                cm->subsampling_x, cm->subsampling_y,
985                                VP9BORDERINPIXELS))
986     vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
987                        "Failed to reallocate last frame buffer");
988
989   if (vp9_realloc_frame_buffer(&cpi->scaled_source,
990                                cm->width, cm->height,
991                                cm->subsampling_x, cm->subsampling_y,
992                                VP9BORDERINPIXELS))
993     vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
994                        "Failed to reallocate scaled source buffer");
995
996   {
997     int y_stride = cpi->scaled_source.y_stride;
998
999     if (cpi->sf.search_method == NSTEP) {
1000       vp9_init3smotion_compensation(&cpi->mb, y_stride);
1001     } else if (cpi->sf.search_method == DIAMOND) {
1002       vp9_init_dsmotion_compensation(&cpi->mb, y_stride);
1003     }
1004   }
1005
1006   {
1007     int i;
1008     for (i = 1; i < MAX_MB_PLANE; ++i) {
1009       cpi->above_context[i] = cpi->above_context[0] +
1010                               i * sizeof(*cpi->above_context[0]) * 2 *
1011                               mi_cols_aligned_to_sb(cm->mi_cols);
1012     }
1013   }
1014 }
1015
1016
1017 // Table that converts 0-63 Q range values passed in outside to the Qindex
1018 // range used internally.
1019 static const int q_trans[] = {
1020   0,    4,   8,  12,  16,  20,  24,  28,
1021   32,   36,  40,  44,  48,  52,  56,  60,
1022   64,   68,  72,  76,  80,  84,  88,  92,
1023   96,  100, 104, 108, 112, 116, 120, 124,
1024   128, 132, 136, 140, 144, 148, 152, 156,
1025   160, 164, 168, 172, 176, 180, 184, 188,
1026   192, 196, 200, 204, 208, 212, 216, 220,
1027   224, 228, 232, 236, 240, 244, 249, 255,
1028 };
1029
1030 int vp9_reverse_trans(int x) {
1031   int i;
1032
1033   for (i = 0; i < 64; i++)
1034     if (q_trans[i] >= x)
1035       return i;
1036
1037   return 63;
1038 };
1039 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
1040   if (framerate < 0.1)
1041     framerate = 30;
1042
1043   cpi->oxcf.framerate = framerate;
1044   cpi->output_framerate = cpi->oxcf.framerate;
1045   cpi->rc.per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth
1046                                       / cpi->output_framerate);
1047   cpi->rc.av_per_frame_bandwidth = (int)(cpi->oxcf.target_bandwidth
1048                                          / cpi->output_framerate);
1049   cpi->rc.min_frame_bandwidth = (int)(cpi->rc.av_per_frame_bandwidth *
1050                                       cpi->oxcf.two_pass_vbrmin_section / 100);
1051
1052
1053   cpi->rc.min_frame_bandwidth = MAX(cpi->rc.min_frame_bandwidth,
1054                                     FRAME_OVERHEAD_BITS);
1055
1056   // Set Maximum gf/arf interval
1057   cpi->rc.max_gf_interval = 16;
1058
1059   // Extended interval for genuinely static scenes
1060   cpi->twopass.static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
1061
1062   // Special conditions when alt ref frame enabled in lagged compress mode
1063   if (cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames) {
1064     if (cpi->rc.max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1065       cpi->rc.max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1066
1067     if (cpi->twopass.static_scene_max_gf_interval > cpi->oxcf.lag_in_frames - 1)
1068       cpi->twopass.static_scene_max_gf_interval = cpi->oxcf.lag_in_frames - 1;
1069   }
1070
1071   if (cpi->rc.max_gf_interval > cpi->twopass.static_scene_max_gf_interval)
1072     cpi->rc.max_gf_interval = cpi->twopass.static_scene_max_gf_interval;
1073 }
1074
1075 static int64_t rescale(int val, int64_t num, int denom) {
1076   int64_t llnum = num;
1077   int64_t llden = denom;
1078   int64_t llval = val;
1079
1080   return (llval * llnum / llden);
1081 }
1082
1083 static void set_tile_limits(VP9_COMP *cpi) {
1084   VP9_COMMON *const cm = &cpi->common;
1085
1086   int min_log2_tile_cols, max_log2_tile_cols;
1087   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1088
1089   cm->log2_tile_cols = clamp(cpi->oxcf.tile_columns,
1090                              min_log2_tile_cols, max_log2_tile_cols);
1091   cm->log2_tile_rows = cpi->oxcf.tile_rows;
1092 }
1093
1094 static void init_config(VP9_PTR ptr, VP9_CONFIG *oxcf) {
1095   VP9_COMP *cpi = (VP9_COMP *)(ptr);
1096   VP9_COMMON *const cm = &cpi->common;
1097   int i;
1098
1099   cpi->oxcf = *oxcf;
1100
1101   cm->version = oxcf->version;
1102
1103   cm->width = oxcf->width;
1104   cm->height = oxcf->height;
1105   cm->subsampling_x = 0;
1106   cm->subsampling_y = 0;
1107   vp9_alloc_compressor_data(cpi);
1108
1109   // change includes all joint functionality
1110   vp9_change_config(ptr, oxcf);
1111
1112   // Initialize active best and worst q and average q values.
1113   cpi->rc.active_worst_quality         = cpi->oxcf.worst_allowed_q;
1114   cpi->rc.active_best_quality          = cpi->oxcf.best_allowed_q;
1115   cpi->rc.avg_frame_qindex          = cpi->oxcf.worst_allowed_q;
1116
1117   // Initialise the starting buffer levels
1118   cpi->rc.buffer_level              = cpi->oxcf.starting_buffer_level;
1119   cpi->rc.bits_off_target           = cpi->oxcf.starting_buffer_level;
1120
1121   cpi->rc.rolling_target_bits       = cpi->rc.av_per_frame_bandwidth;
1122   cpi->rc.rolling_actual_bits       = cpi->rc.av_per_frame_bandwidth;
1123   cpi->rc.long_rolling_target_bits  = cpi->rc.av_per_frame_bandwidth;
1124   cpi->rc.long_rolling_actual_bits  = cpi->rc.av_per_frame_bandwidth;
1125
1126   cpi->rc.total_actual_bits         = 0;
1127   cpi->rc.total_target_vs_actual    = 0;
1128
1129   cpi->static_mb_pct = 0;
1130
1131   cpi->lst_fb_idx = 0;
1132   cpi->gld_fb_idx = 1;
1133   cpi->alt_fb_idx = 2;
1134
1135   cpi->current_layer = 0;
1136   cpi->use_svc = 0;
1137
1138   set_tile_limits(cpi);
1139
1140   cpi->fixed_divide[0] = 0;
1141   for (i = 1; i < 512; i++)
1142     cpi->fixed_divide[i] = 0x80000 / i;
1143 }
1144
1145
1146 void vp9_change_config(VP9_PTR ptr, VP9_CONFIG *oxcf) {
1147   VP9_COMP *cpi = (VP9_COMP *)(ptr);
1148   VP9_COMMON *const cm = &cpi->common;
1149
1150   if (!cpi || !oxcf)
1151     return;
1152
1153   if (cm->version != oxcf->version) {
1154     cm->version = oxcf->version;
1155   }
1156
1157   cpi->oxcf = *oxcf;
1158
1159   switch (cpi->oxcf.Mode) {
1160       // Real time and one pass deprecated in test code base
1161     case MODE_GOODQUALITY:
1162       cpi->pass = 0;
1163       cpi->compressor_speed = 2;
1164       cpi->oxcf.cpu_used = clamp(cpi->oxcf.cpu_used, -5, 5);
1165       break;
1166
1167     case MODE_FIRSTPASS:
1168       cpi->pass = 1;
1169       cpi->compressor_speed = 1;
1170       break;
1171
1172     case MODE_SECONDPASS:
1173       cpi->pass = 2;
1174       cpi->compressor_speed = 1;
1175       cpi->oxcf.cpu_used = clamp(cpi->oxcf.cpu_used, -5, 5);
1176       break;
1177
1178     case MODE_SECONDPASS_BEST:
1179       cpi->pass = 2;
1180       cpi->compressor_speed = 0;
1181       break;
1182   }
1183
1184   cpi->oxcf.worst_allowed_q = q_trans[oxcf->worst_allowed_q];
1185   cpi->oxcf.best_allowed_q = q_trans[oxcf->best_allowed_q];
1186   cpi->oxcf.cq_level = q_trans[cpi->oxcf.cq_level];
1187
1188   cpi->oxcf.lossless = oxcf->lossless;
1189   cpi->mb.e_mbd.itxm_add = cpi->oxcf.lossless ? vp9_iwht4x4_add
1190                                               : vp9_idct4x4_add;
1191   cpi->rc.baseline_gf_interval = DEFAULT_GF_INTERVAL;
1192
1193   cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
1194
1195   // cpi->use_golden_frame_only = 0;
1196   // cpi->use_last_frame_only = 0;
1197   cpi->refresh_golden_frame = 0;
1198   cpi->refresh_last_frame = 1;
1199   cm->refresh_frame_context = 1;
1200   cm->reset_frame_context = 0;
1201
1202   setup_features(cm);
1203   cpi->common.allow_high_precision_mv = 0;  // Default mv precision
1204   set_mvcost(cpi);
1205
1206   {
1207     int i;
1208
1209     for (i = 0; i < MAX_SEGMENTS; i++)
1210       cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
1211   }
1212
1213   // At the moment the first order values may not be > MAXQ
1214   cpi->oxcf.fixed_q = MIN(cpi->oxcf.fixed_q, MAXQ);
1215
1216   // local file playback mode == really big buffer
1217   if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK) {
1218     cpi->oxcf.starting_buffer_level   = 60000;
1219     cpi->oxcf.optimal_buffer_level    = 60000;
1220     cpi->oxcf.maximum_buffer_size     = 240000;
1221   }
1222
1223   // Convert target bandwidth from Kbit/s to Bit/s
1224   cpi->oxcf.target_bandwidth       *= 1000;
1225
1226   cpi->oxcf.starting_buffer_level = rescale(cpi->oxcf.starting_buffer_level,
1227                                             cpi->oxcf.target_bandwidth, 1000);
1228
1229   // Set or reset optimal and maximum buffer levels.
1230   if (cpi->oxcf.optimal_buffer_level == 0)
1231     cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
1232   else
1233     cpi->oxcf.optimal_buffer_level = rescale(cpi->oxcf.optimal_buffer_level,
1234                                              cpi->oxcf.target_bandwidth, 1000);
1235
1236   if (cpi->oxcf.maximum_buffer_size == 0)
1237     cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
1238   else
1239     cpi->oxcf.maximum_buffer_size = rescale(cpi->oxcf.maximum_buffer_size,
1240                                             cpi->oxcf.target_bandwidth, 1000);
1241
1242   // Set up frame rate and related parameters rate control values.
1243   vp9_new_framerate(cpi, cpi->oxcf.framerate);
1244
1245   // Set absolute upper and lower quality limits
1246   cpi->rc.worst_quality = cpi->oxcf.worst_allowed_q;
1247   cpi->rc.best_quality = cpi->oxcf.best_allowed_q;
1248
1249   // active values should only be modified if out of new range
1250   cpi->rc.active_worst_quality = clamp(cpi->rc.active_worst_quality,
1251                                     cpi->oxcf.best_allowed_q,
1252                                     cpi->oxcf.worst_allowed_q);
1253
1254   cpi->rc.active_best_quality = clamp(cpi->rc.active_best_quality,
1255                                    cpi->oxcf.best_allowed_q,
1256                                    cpi->oxcf.worst_allowed_q);
1257
1258   cpi->cq_target_quality = cpi->oxcf.cq_level;
1259
1260   cm->mcomp_filter_type = DEFAULT_INTERP_FILTER;
1261
1262   cpi->target_bandwidth = cpi->oxcf.target_bandwidth;
1263
1264   cm->display_width = cpi->oxcf.width;
1265   cm->display_height = cpi->oxcf.height;
1266
1267   // VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs)
1268   cpi->oxcf.Sharpness = MIN(7, cpi->oxcf.Sharpness);
1269
1270   cpi->common.lf.sharpness_level = cpi->oxcf.Sharpness;
1271
1272   if (cpi->initial_width) {
1273     // Increasing the size of the frame beyond the first seen frame, or some
1274     // otherwise signalled maximum size, is not supported.
1275     // TODO(jkoleszar): exit gracefully.
1276     assert(cm->width <= cpi->initial_width);
1277     assert(cm->height <= cpi->initial_height);
1278   }
1279   update_frame_size(cpi);
1280
1281   if (cpi->oxcf.fixed_q >= 0) {
1282     cpi->rc.last_q[0] = cpi->oxcf.fixed_q;
1283     cpi->rc.last_q[1] = cpi->oxcf.fixed_q;
1284     cpi->rc.last_boosted_qindex = cpi->oxcf.fixed_q;
1285   }
1286
1287   cpi->speed = cpi->oxcf.cpu_used;
1288
1289   if (cpi->oxcf.lag_in_frames == 0) {
1290     // force to allowlag to 0 if lag_in_frames is 0;
1291     cpi->oxcf.allow_lag = 0;
1292   } else if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS) {
1293      // Limit on lag buffers as these are not currently dynamically allocated
1294     cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
1295   }
1296
1297   // YX Temp
1298 #if CONFIG_MULTIPLE_ARF
1299   vp9_zero(cpi->alt_ref_source);
1300 #else
1301   cpi->alt_ref_source = NULL;
1302 #endif
1303   cpi->is_src_frame_alt_ref = 0;
1304
1305 #if 0
1306   // Experimental RD Code
1307   cpi->frame_distortion = 0;
1308   cpi->last_frame_distortion = 0;
1309 #endif
1310
1311   set_tile_limits(cpi);
1312 }
1313
1314 #define M_LOG2_E 0.693147180559945309417
1315 #define log2f(x) (log (x) / (float) M_LOG2_E)
1316
1317 static void cal_nmvjointsadcost(int *mvjointsadcost) {
1318   mvjointsadcost[0] = 600;
1319   mvjointsadcost[1] = 300;
1320   mvjointsadcost[2] = 300;
1321   mvjointsadcost[0] = 300;
1322 }
1323
1324 static void cal_nmvsadcosts(int *mvsadcost[2]) {
1325   int i = 1;
1326
1327   mvsadcost[0][0] = 0;
1328   mvsadcost[1][0] = 0;
1329
1330   do {
1331     double z = 256 * (2 * (log2f(8 * i) + .6));
1332     mvsadcost[0][i] = (int)z;
1333     mvsadcost[1][i] = (int)z;
1334     mvsadcost[0][-i] = (int)z;
1335     mvsadcost[1][-i] = (int)z;
1336   } while (++i <= MV_MAX);
1337 }
1338
1339 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
1340   int i = 1;
1341
1342   mvsadcost[0][0] = 0;
1343   mvsadcost[1][0] = 0;
1344
1345   do {
1346     double z = 256 * (2 * (log2f(8 * i) + .6));
1347     mvsadcost[0][i] = (int)z;
1348     mvsadcost[1][i] = (int)z;
1349     mvsadcost[0][-i] = (int)z;
1350     mvsadcost[1][-i] = (int)z;
1351   } while (++i <= MV_MAX);
1352 }
1353
1354 static void alloc_mode_context(VP9_COMMON *cm, int num_4x4_blk,
1355                                PICK_MODE_CONTEXT *ctx) {
1356   int num_pix = num_4x4_blk << 4;
1357   int i, k;
1358   ctx->num_4x4_blk = num_4x4_blk;
1359   CHECK_MEM_ERROR(cm, ctx->zcoeff_blk,
1360                   vpx_calloc(num_4x4_blk, sizeof(uint8_t)));
1361   for (i = 0; i < MAX_MB_PLANE; ++i) {
1362     for (k = 0; k < 3; ++k) {
1363       CHECK_MEM_ERROR(cm, ctx->coeff[i][k],
1364                       vpx_memalign(16, num_pix * sizeof(int16_t)));
1365       CHECK_MEM_ERROR(cm, ctx->qcoeff[i][k],
1366                       vpx_memalign(16, num_pix * sizeof(int16_t)));
1367       CHECK_MEM_ERROR(cm, ctx->dqcoeff[i][k],
1368                       vpx_memalign(16, num_pix * sizeof(int16_t)));
1369       CHECK_MEM_ERROR(cm, ctx->eobs[i][k],
1370                       vpx_memalign(16, num_pix * sizeof(uint16_t)));
1371       ctx->coeff_pbuf[i][k]   = ctx->coeff[i][k];
1372       ctx->qcoeff_pbuf[i][k]  = ctx->qcoeff[i][k];
1373       ctx->dqcoeff_pbuf[i][k] = ctx->dqcoeff[i][k];
1374       ctx->eobs_pbuf[i][k]    = ctx->eobs[i][k];
1375     }
1376   }
1377 }
1378
1379 static void free_mode_context(PICK_MODE_CONTEXT *ctx) {
1380   int i, k;
1381   vpx_free(ctx->zcoeff_blk);
1382   ctx->zcoeff_blk = 0;
1383   for (i = 0; i < MAX_MB_PLANE; ++i) {
1384     for (k = 0; k < 3; ++k) {
1385       vpx_free(ctx->coeff[i][k]);
1386       ctx->coeff[i][k] = 0;
1387       vpx_free(ctx->qcoeff[i][k]);
1388       ctx->qcoeff[i][k] = 0;
1389       vpx_free(ctx->dqcoeff[i][k]);
1390       ctx->dqcoeff[i][k] = 0;
1391       vpx_free(ctx->eobs[i][k]);
1392       ctx->eobs[i][k] = 0;
1393     }
1394   }
1395 }
1396
1397 static void init_pick_mode_context(VP9_COMP *cpi) {
1398   int i;
1399   VP9_COMMON *const cm = &cpi->common;
1400   MACROBLOCK *const x  = &cpi->mb;
1401
1402
1403   for (i = 0; i < BLOCK_SIZES; ++i) {
1404     const int num_4x4_w = num_4x4_blocks_wide_lookup[i];
1405     const int num_4x4_h = num_4x4_blocks_high_lookup[i];
1406     const int num_4x4_blk = MAX(4, num_4x4_w * num_4x4_h);
1407     if (i < BLOCK_16X16) {
1408       for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1409         for (x->mb_index = 0; x->mb_index < 4; ++x->mb_index) {
1410           for (x->b_index = 0; x->b_index < 16 / num_4x4_blk; ++x->b_index) {
1411             PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1412             alloc_mode_context(cm, num_4x4_blk, ctx);
1413           }
1414         }
1415       }
1416     } else if (i < BLOCK_32X32) {
1417       for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1418         for (x->mb_index = 0; x->mb_index < 64 / num_4x4_blk; ++x->mb_index) {
1419           PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1420           ctx->num_4x4_blk = num_4x4_blk;
1421           alloc_mode_context(cm, num_4x4_blk, ctx);
1422         }
1423       }
1424     } else if (i < BLOCK_64X64) {
1425       for (x->sb_index = 0; x->sb_index < 256 / num_4x4_blk; ++x->sb_index) {
1426         PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1427         ctx->num_4x4_blk = num_4x4_blk;
1428         alloc_mode_context(cm, num_4x4_blk, ctx);
1429       }
1430     } else {
1431       PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1432       ctx->num_4x4_blk = num_4x4_blk;
1433       alloc_mode_context(cm, num_4x4_blk, ctx);
1434     }
1435   }
1436 }
1437
1438 static void free_pick_mode_context(MACROBLOCK *x) {
1439   int i;
1440
1441   for (i = 0; i < BLOCK_SIZES; ++i) {
1442     const int num_4x4_w = num_4x4_blocks_wide_lookup[i];
1443     const int num_4x4_h = num_4x4_blocks_high_lookup[i];
1444     const int num_4x4_blk = MAX(4, num_4x4_w * num_4x4_h);
1445     if (i < BLOCK_16X16) {
1446       for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1447         for (x->mb_index = 0; x->mb_index < 4; ++x->mb_index) {
1448           for (x->b_index = 0; x->b_index < 16 / num_4x4_blk; ++x->b_index) {
1449             PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1450             free_mode_context(ctx);
1451           }
1452         }
1453       }
1454     } else if (i < BLOCK_32X32) {
1455       for (x->sb_index = 0; x->sb_index < 4; ++x->sb_index) {
1456         for (x->mb_index = 0; x->mb_index < 64 / num_4x4_blk; ++x->mb_index) {
1457           PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1458           free_mode_context(ctx);
1459         }
1460       }
1461     } else if (i < BLOCK_64X64) {
1462       for (x->sb_index = 0; x->sb_index < 256 / num_4x4_blk; ++x->sb_index) {
1463         PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1464         free_mode_context(ctx);
1465       }
1466     } else {
1467       PICK_MODE_CONTEXT *ctx = get_block_context(x, i);
1468       free_mode_context(ctx);
1469     }
1470   }
1471 }
1472
1473 VP9_PTR vp9_create_compressor(VP9_CONFIG *oxcf) {
1474   int i, j;
1475   volatile union {
1476     VP9_COMP *cpi;
1477     VP9_PTR   ptr;
1478   } ctx;
1479
1480   VP9_COMP *cpi;
1481   VP9_COMMON *cm;
1482
1483   cpi = ctx.cpi = vpx_memalign(32, sizeof(VP9_COMP));
1484   // Check that the CPI instance is valid
1485   if (!cpi)
1486     return 0;
1487
1488   cm = &cpi->common;
1489
1490   vp9_zero(*cpi);
1491
1492   if (setjmp(cm->error.jmp)) {
1493     VP9_PTR ptr = ctx.ptr;
1494
1495     ctx.cpi->common.error.setjmp = 0;
1496     vp9_remove_compressor(&ptr);
1497     return 0;
1498   }
1499
1500   cm->error.setjmp = 1;
1501
1502   CHECK_MEM_ERROR(cm, cpi->mb.ss, vpx_calloc(sizeof(search_site),
1503                                              (MAX_MVSEARCH_STEPS * 8) + 1));
1504
1505   vp9_create_common(cm);
1506
1507   init_config((VP9_PTR)cpi, oxcf);
1508
1509   init_pick_mode_context(cpi);
1510
1511   cm->current_video_frame   = 0;
1512   cpi->rc.frames_till_gf_update_due = 0;
1513
1514   // Set reference frame sign bias for ALTREF frame to 1 (for now)
1515   cm->ref_frame_sign_bias[ALTREF_FRAME] = 1;
1516
1517   cpi->rc.baseline_gf_interval = DEFAULT_GF_INTERVAL;
1518
1519   cpi->gold_is_last = 0;
1520   cpi->alt_is_last  = 0;
1521   cpi->gold_is_alt  = 0;
1522
1523   // Spatial scalability
1524   cpi->number_spatial_layers = oxcf->ss_number_layers;
1525
1526   // Create the encoder segmentation map and set all entries to 0
1527   CHECK_MEM_ERROR(cm, cpi->segmentation_map,
1528                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1529
1530   // Create a complexity map used for rd adjustment
1531   CHECK_MEM_ERROR(cm, cpi->complexity_map,
1532                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1533
1534
1535   // And a place holder structure is the coding context
1536   // for use if we want to save and restore it
1537   CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
1538                   vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
1539
1540   CHECK_MEM_ERROR(cm, cpi->active_map, vpx_calloc(cm->MBs, 1));
1541   vpx_memset(cpi->active_map, 1, cm->MBs);
1542   cpi->active_map_enabled = 0;
1543
1544   for (i = 0; i < (sizeof(cpi->mbgraph_stats) /
1545                    sizeof(cpi->mbgraph_stats[0])); i++) {
1546     CHECK_MEM_ERROR(cm, cpi->mbgraph_stats[i].mb_stats,
1547                     vpx_calloc(cm->MBs *
1548                                sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
1549   }
1550
1551 #ifdef ENTROPY_STATS
1552   if (cpi->pass != 1)
1553     init_context_counters();
1554 #endif
1555
1556 #ifdef MODE_STATS
1557   init_tx_count_stats();
1558   init_switchable_interp_stats();
1559 #endif
1560
1561   /*Initialize the feed-forward activity masking.*/
1562   cpi->activity_avg = 90 << 12;
1563
1564   cpi->frames_since_key = 8;  // Sensible default for first frame.
1565   cpi->key_frame_frequency = cpi->oxcf.key_freq;
1566   cpi->this_key_frame_forced = 0;
1567   cpi->next_key_frame_forced = 0;
1568
1569   cpi->source_alt_ref_pending = 0;
1570   cpi->source_alt_ref_active = 0;
1571   cpi->refresh_alt_ref_frame = 0;
1572
1573 #if CONFIG_MULTIPLE_ARF
1574   // Turn multiple ARF usage on/off. This is a quick hack for the initial test
1575   // version. It should eventually be set via the codec API.
1576   cpi->multi_arf_enabled = 1;
1577
1578   if (cpi->multi_arf_enabled) {
1579     cpi->sequence_number = 0;
1580     cpi->frame_coding_order_period = 0;
1581     vp9_zero(cpi->frame_coding_order);
1582     vp9_zero(cpi->arf_buffer_idx);
1583   }
1584 #endif
1585
1586   cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
1587 #if CONFIG_INTERNAL_STATS
1588   cpi->b_calculate_ssimg = 0;
1589
1590   cpi->count = 0;
1591   cpi->bytes = 0;
1592
1593   if (cpi->b_calculate_psnr) {
1594     cpi->total_sq_error = 0.0;
1595     cpi->total_sq_error2 = 0.0;
1596     cpi->total_y = 0.0;
1597     cpi->total_u = 0.0;
1598     cpi->total_v = 0.0;
1599     cpi->total = 0.0;
1600     cpi->totalp_y = 0.0;
1601     cpi->totalp_u = 0.0;
1602     cpi->totalp_v = 0.0;
1603     cpi->totalp = 0.0;
1604     cpi->tot_recode_hits = 0;
1605     cpi->summed_quality = 0;
1606     cpi->summed_weights = 0;
1607     cpi->summedp_quality = 0;
1608     cpi->summedp_weights = 0;
1609   }
1610
1611   if (cpi->b_calculate_ssimg) {
1612     cpi->total_ssimg_y = 0;
1613     cpi->total_ssimg_u = 0;
1614     cpi->total_ssimg_v = 0;
1615     cpi->total_ssimg_all = 0;
1616   }
1617
1618 #endif
1619
1620   cpi->first_time_stamp_ever = INT64_MAX;
1621
1622   cpi->rc.frames_till_gf_update_due      = 0;
1623   cpi->rc.key_frame_count              = 1;
1624
1625   cpi->rc.ni_av_qi                     = cpi->oxcf.worst_allowed_q;
1626   cpi->rc.ni_tot_qi                    = 0;
1627   cpi->rc.ni_frames                   = 0;
1628   cpi->rc.tot_q = 0.0;
1629   cpi->rc.avg_q = vp9_convert_qindex_to_q(cpi->oxcf.worst_allowed_q);
1630
1631   cpi->rc.rate_correction_factor         = 1.0;
1632   cpi->rc.key_frame_rate_correction_factor = 1.0;
1633   cpi->rc.gf_rate_correction_factor  = 1.0;
1634   cpi->twopass.est_max_qcorrection_factor  = 1.0;
1635
1636   cal_nmvjointsadcost(cpi->mb.nmvjointsadcost);
1637   cpi->mb.nmvcost[0] = &cpi->mb.nmvcosts[0][MV_MAX];
1638   cpi->mb.nmvcost[1] = &cpi->mb.nmvcosts[1][MV_MAX];
1639   cpi->mb.nmvsadcost[0] = &cpi->mb.nmvsadcosts[0][MV_MAX];
1640   cpi->mb.nmvsadcost[1] = &cpi->mb.nmvsadcosts[1][MV_MAX];
1641   cal_nmvsadcosts(cpi->mb.nmvsadcost);
1642
1643   cpi->mb.nmvcost_hp[0] = &cpi->mb.nmvcosts_hp[0][MV_MAX];
1644   cpi->mb.nmvcost_hp[1] = &cpi->mb.nmvcosts_hp[1][MV_MAX];
1645   cpi->mb.nmvsadcost_hp[0] = &cpi->mb.nmvsadcosts_hp[0][MV_MAX];
1646   cpi->mb.nmvsadcost_hp[1] = &cpi->mb.nmvsadcosts_hp[1][MV_MAX];
1647   cal_nmvsadcosts_hp(cpi->mb.nmvsadcost_hp);
1648
1649   for (i = 0; i < KEY_FRAME_CONTEXT; i++)
1650     cpi->rc.prior_key_frame_distance[i] = (int)cpi->output_framerate;
1651
1652 #ifdef OUTPUT_YUV_SRC
1653   yuv_file = fopen("bd.yuv", "ab");
1654 #endif
1655 #ifdef OUTPUT_YUV_REC
1656   yuv_rec_file = fopen("rec.yuv", "wb");
1657 #endif
1658
1659 #if 0
1660   framepsnr = fopen("framepsnr.stt", "a");
1661   kf_list = fopen("kf_list.stt", "w");
1662 #endif
1663
1664   cpi->output_pkt_list = oxcf->output_pkt_list;
1665
1666   cpi->enable_encode_breakout = 1;
1667
1668   if (cpi->pass == 1) {
1669     vp9_init_first_pass(cpi);
1670   } else if (cpi->pass == 2) {
1671     size_t packet_sz = sizeof(FIRSTPASS_STATS);
1672     int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
1673
1674     cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
1675     cpi->twopass.stats_in = cpi->twopass.stats_in_start;
1676     cpi->twopass.stats_in_end = (void *)((char *)cpi->twopass.stats_in
1677                                          + (packets - 1) * packet_sz);
1678     vp9_init_second_pass(cpi);
1679   }
1680
1681   vp9_set_speed_features(cpi);
1682
1683   // Default rd threshold factors for mode selection
1684   for (i = 0; i < BLOCK_SIZES; ++i) {
1685     for (j = 0; j < MAX_MODES; ++j)
1686       cpi->rd_thresh_freq_fact[i][j] = 32;
1687     for (j = 0; j < MAX_REFS; ++j)
1688       cpi->rd_thresh_freq_sub8x8[i][j] = 32;
1689   }
1690
1691 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SVFHH, SVFHV, SVFHHV, \
1692             SDX3F, SDX8F, SDX4DF)\
1693     cpi->fn_ptr[BT].sdf            = SDF; \
1694     cpi->fn_ptr[BT].sdaf           = SDAF; \
1695     cpi->fn_ptr[BT].vf             = VF; \
1696     cpi->fn_ptr[BT].svf            = SVF; \
1697     cpi->fn_ptr[BT].svaf           = SVAF; \
1698     cpi->fn_ptr[BT].svf_halfpix_h  = SVFHH; \
1699     cpi->fn_ptr[BT].svf_halfpix_v  = SVFHV; \
1700     cpi->fn_ptr[BT].svf_halfpix_hv = SVFHHV; \
1701     cpi->fn_ptr[BT].sdx3f          = SDX3F; \
1702     cpi->fn_ptr[BT].sdx8f          = SDX8F; \
1703     cpi->fn_ptr[BT].sdx4df         = SDX4DF;
1704
1705   BFP(BLOCK_32X16, vp9_sad32x16, vp9_sad32x16_avg,
1706       vp9_variance32x16, vp9_sub_pixel_variance32x16,
1707       vp9_sub_pixel_avg_variance32x16, NULL, NULL,
1708       NULL, NULL, NULL,
1709       vp9_sad32x16x4d)
1710
1711   BFP(BLOCK_16X32, vp9_sad16x32, vp9_sad16x32_avg,
1712       vp9_variance16x32, vp9_sub_pixel_variance16x32,
1713       vp9_sub_pixel_avg_variance16x32, NULL, NULL,
1714       NULL, NULL, NULL,
1715       vp9_sad16x32x4d)
1716
1717   BFP(BLOCK_64X32, vp9_sad64x32, vp9_sad64x32_avg,
1718       vp9_variance64x32, vp9_sub_pixel_variance64x32,
1719       vp9_sub_pixel_avg_variance64x32, NULL, NULL,
1720       NULL, NULL, NULL,
1721       vp9_sad64x32x4d)
1722
1723   BFP(BLOCK_32X64, vp9_sad32x64, vp9_sad32x64_avg,
1724       vp9_variance32x64, vp9_sub_pixel_variance32x64,
1725       vp9_sub_pixel_avg_variance32x64, NULL, NULL,
1726       NULL, NULL, NULL,
1727       vp9_sad32x64x4d)
1728
1729   BFP(BLOCK_32X32, vp9_sad32x32, vp9_sad32x32_avg,
1730       vp9_variance32x32, vp9_sub_pixel_variance32x32,
1731       vp9_sub_pixel_avg_variance32x32, vp9_variance_halfpixvar32x32_h,
1732       vp9_variance_halfpixvar32x32_v,
1733       vp9_variance_halfpixvar32x32_hv, vp9_sad32x32x3, vp9_sad32x32x8,
1734       vp9_sad32x32x4d)
1735
1736   BFP(BLOCK_64X64, vp9_sad64x64, vp9_sad64x64_avg,
1737       vp9_variance64x64, vp9_sub_pixel_variance64x64,
1738       vp9_sub_pixel_avg_variance64x64, vp9_variance_halfpixvar64x64_h,
1739       vp9_variance_halfpixvar64x64_v,
1740       vp9_variance_halfpixvar64x64_hv, vp9_sad64x64x3, vp9_sad64x64x8,
1741       vp9_sad64x64x4d)
1742
1743   BFP(BLOCK_16X16, vp9_sad16x16, vp9_sad16x16_avg,
1744       vp9_variance16x16, vp9_sub_pixel_variance16x16,
1745       vp9_sub_pixel_avg_variance16x16, vp9_variance_halfpixvar16x16_h,
1746       vp9_variance_halfpixvar16x16_v,
1747       vp9_variance_halfpixvar16x16_hv, vp9_sad16x16x3, vp9_sad16x16x8,
1748       vp9_sad16x16x4d)
1749
1750   BFP(BLOCK_16X8, vp9_sad16x8, vp9_sad16x8_avg,
1751       vp9_variance16x8, vp9_sub_pixel_variance16x8,
1752       vp9_sub_pixel_avg_variance16x8, NULL, NULL, NULL,
1753       vp9_sad16x8x3, vp9_sad16x8x8, vp9_sad16x8x4d)
1754
1755   BFP(BLOCK_8X16, vp9_sad8x16, vp9_sad8x16_avg,
1756       vp9_variance8x16, vp9_sub_pixel_variance8x16,
1757       vp9_sub_pixel_avg_variance8x16, NULL, NULL, NULL,
1758       vp9_sad8x16x3, vp9_sad8x16x8, vp9_sad8x16x4d)
1759
1760   BFP(BLOCK_8X8, vp9_sad8x8, vp9_sad8x8_avg,
1761       vp9_variance8x8, vp9_sub_pixel_variance8x8,
1762       vp9_sub_pixel_avg_variance8x8, NULL, NULL, NULL,
1763       vp9_sad8x8x3, vp9_sad8x8x8, vp9_sad8x8x4d)
1764
1765   BFP(BLOCK_8X4, vp9_sad8x4, vp9_sad8x4_avg,
1766       vp9_variance8x4, vp9_sub_pixel_variance8x4,
1767       vp9_sub_pixel_avg_variance8x4, NULL, NULL,
1768       NULL, NULL, vp9_sad8x4x8,
1769       vp9_sad8x4x4d)
1770
1771   BFP(BLOCK_4X8, vp9_sad4x8, vp9_sad4x8_avg,
1772       vp9_variance4x8, vp9_sub_pixel_variance4x8,
1773       vp9_sub_pixel_avg_variance4x8, NULL, NULL,
1774       NULL, NULL, vp9_sad4x8x8,
1775       vp9_sad4x8x4d)
1776
1777   BFP(BLOCK_4X4, vp9_sad4x4, vp9_sad4x4_avg,
1778       vp9_variance4x4, vp9_sub_pixel_variance4x4,
1779       vp9_sub_pixel_avg_variance4x4, NULL, NULL, NULL,
1780       vp9_sad4x4x3, vp9_sad4x4x8, vp9_sad4x4x4d)
1781
1782   cpi->full_search_sad = vp9_full_search_sad;
1783   cpi->diamond_search_sad = vp9_diamond_search_sad;
1784   cpi->refining_search_sad = vp9_refining_search_sad;
1785
1786   // make sure frame 1 is okay
1787   cpi->error_bins[0] = cpi->common.MBs;
1788
1789   /* vp9_init_quantizer() is first called here. Add check in
1790    * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
1791    * called later when needed. This will avoid unnecessary calls of
1792    * vp9_init_quantizer() for every frame.
1793    */
1794   vp9_init_quantizer(cpi);
1795
1796   vp9_loop_filter_init(cm);
1797
1798   cpi->common.error.setjmp = 0;
1799
1800   vp9_zero(cpi->y_uv_mode_count);
1801
1802 #ifdef MODE_TEST_HIT_STATS
1803   vp9_zero(cpi->mode_test_hits);
1804 #endif
1805
1806   return (VP9_PTR) cpi;
1807 }
1808
1809 void vp9_remove_compressor(VP9_PTR *ptr) {
1810   VP9_COMP *cpi = (VP9_COMP *)(*ptr);
1811   int i;
1812
1813   if (!cpi)
1814     return;
1815
1816   if (cpi && (cpi->common.current_video_frame > 0)) {
1817     if (cpi->pass == 2) {
1818       vp9_end_second_pass(cpi);
1819     }
1820
1821 #ifdef MODE_STATS
1822     if (cpi->pass != 1) {
1823       write_tx_count_stats();
1824       write_switchable_interp_stats();
1825     }
1826 #endif
1827
1828 #if CONFIG_INTERNAL_STATS
1829
1830     vp9_clear_system_state();
1831
1832     // printf("\n8x8-4x4:%d-%d\n", cpi->t8x8_count, cpi->t4x4_count);
1833     if (cpi->pass != 1) {
1834       FILE *f = fopen("opsnr.stt", "a");
1835       double time_encoded = (cpi->last_end_time_stamp_seen
1836                              - cpi->first_time_stamp_ever) / 10000000.000;
1837       double total_encode_time = (cpi->time_receive_data +
1838                                   cpi->time_compress_data)   / 1000.000;
1839       double dr = (double)cpi->bytes * (double) 8 / (double)1000
1840                   / time_encoded;
1841
1842       if (cpi->b_calculate_psnr) {
1843         YV12_BUFFER_CONFIG *lst_yv12 =
1844             &cpi->common.yv12_fb[cpi->common.ref_frame_map[cpi->lst_fb_idx]];
1845         double samples = 3.0 / 2 * cpi->count *
1846                          lst_yv12->y_width * lst_yv12->y_height;
1847         double total_psnr = vp9_mse2psnr(samples, 255.0, cpi->total_sq_error);
1848         double total_psnr2 = vp9_mse2psnr(samples, 255.0, cpi->total_sq_error2);
1849         double total_ssim = 100 * pow(cpi->summed_quality /
1850                                       cpi->summed_weights, 8.0);
1851         double total_ssimp = 100 * pow(cpi->summedp_quality /
1852                                        cpi->summedp_weights, 8.0);
1853
1854         fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
1855                 "VPXSSIM\tVPSSIMP\t  Time(ms)\n");
1856         fprintf(f, "%7.2f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t%8.0f\n",
1857                 dr, cpi->total / cpi->count, total_psnr,
1858                 cpi->totalp / cpi->count, total_psnr2, total_ssim, total_ssimp,
1859                 total_encode_time);
1860       }
1861
1862       if (cpi->b_calculate_ssimg) {
1863         fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t  Time(ms)\n");
1864         fprintf(f, "%7.2f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
1865                 cpi->total_ssimg_y / cpi->count,
1866                 cpi->total_ssimg_u / cpi->count,
1867                 cpi->total_ssimg_v / cpi->count,
1868                 cpi->total_ssimg_all / cpi->count, total_encode_time);
1869       }
1870
1871       fclose(f);
1872     }
1873
1874 #endif
1875
1876 #ifdef MODE_TEST_HIT_STATS
1877     if (cpi->pass != 1) {
1878       double norm_per_pixel_mode_tests = 0;
1879       double norm_counts[BLOCK_SIZES];
1880       int i;
1881       int sb64_per_frame;
1882       int norm_factors[BLOCK_SIZES] =
1883         {256, 128, 128, 64, 32, 32, 16, 8, 8, 4, 2, 2, 1};
1884       FILE *f = fopen("mode_hit_stats.stt", "a");
1885
1886       // On average, how many mode tests do we do
1887       for (i = 0; i < BLOCK_SIZES; ++i) {
1888         norm_counts[i] = (double)cpi->mode_test_hits[i] /
1889                          (double)norm_factors[i];
1890         norm_per_pixel_mode_tests += norm_counts[i];
1891       }
1892       // Convert to a number per 64x64 and per frame
1893       sb64_per_frame = ((cpi->common.height + 63) / 64) *
1894                        ((cpi->common.width + 63) / 64);
1895       norm_per_pixel_mode_tests =
1896         norm_per_pixel_mode_tests /
1897         (double)(cpi->common.current_video_frame * sb64_per_frame);
1898
1899       fprintf(f, "%6.4f\n", norm_per_pixel_mode_tests);
1900       fclose(f);
1901     }
1902 #endif
1903
1904 #ifdef ENTROPY_STATS
1905     {
1906       int i, j, k;
1907       FILE *fmode = fopen("vp9_modecontext.c", "w");
1908
1909       fprintf(fmode, "\n#include \"vp9_entropymode.h\"\n\n");
1910       fprintf(fmode, "const unsigned int vp9_kf_default_bmode_counts ");
1911       fprintf(fmode, "[INTRA_MODES][INTRA_MODES]"
1912                      "[INTRA_MODES] =\n{\n");
1913
1914       for (i = 0; i < INTRA_MODES; i++) {
1915         fprintf(fmode, "    { // Above Mode :  %d\n", i);
1916
1917         for (j = 0; j < INTRA_MODES; j++) {
1918           fprintf(fmode, "        {");
1919
1920           for (k = 0; k < INTRA_MODES; k++) {
1921             if (!intra_mode_stats[i][j][k])
1922               fprintf(fmode, " %5d, ", 1);
1923             else
1924               fprintf(fmode, " %5d, ", intra_mode_stats[i][j][k]);
1925           }
1926
1927           fprintf(fmode, "}, // left_mode %d\n", j);
1928         }
1929
1930         fprintf(fmode, "    },\n");
1931       }
1932
1933       fprintf(fmode, "};\n");
1934       fclose(fmode);
1935     }
1936 #endif
1937
1938
1939 #if defined(SECTIONBITS_OUTPUT)
1940
1941     if (0) {
1942       int i;
1943       FILE *f = fopen("tokenbits.stt", "a");
1944
1945       for (i = 0; i < 28; i++)
1946         fprintf(f, "%8d", (int)(Sectionbits[i] / 256));
1947
1948       fprintf(f, "\n");
1949       fclose(f);
1950     }
1951
1952 #endif
1953
1954 #if 0
1955     {
1956       printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
1957       printf("\n_frames recive_data encod_mb_row compress_frame  Total\n");
1958       printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
1959              cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
1960              cpi->time_compress_data / 1000,
1961              (cpi->time_receive_data + cpi->time_compress_data) / 1000);
1962     }
1963 #endif
1964   }
1965
1966   free_pick_mode_context(&cpi->mb);
1967   dealloc_compressor_data(cpi);
1968   vpx_free(cpi->mb.ss);
1969   vpx_free(cpi->tok);
1970
1971   for (i = 0; i < sizeof(cpi->mbgraph_stats) /
1972                   sizeof(cpi->mbgraph_stats[0]); ++i) {
1973     vpx_free(cpi->mbgraph_stats[i].mb_stats);
1974   }
1975
1976   vp9_remove_common(&cpi->common);
1977   vpx_free(cpi);
1978   *ptr = 0;
1979
1980 #ifdef OUTPUT_YUV_SRC
1981   fclose(yuv_file);
1982 #endif
1983 #ifdef OUTPUT_YUV_REC
1984   fclose(yuv_rec_file);
1985 #endif
1986
1987 #if 0
1988
1989   if (keyfile)
1990     fclose(keyfile);
1991
1992   if (framepsnr)
1993     fclose(framepsnr);
1994
1995   if (kf_list)
1996     fclose(kf_list);
1997
1998 #endif
1999 }
2000
2001
2002 static uint64_t calc_plane_error(uint8_t *orig, int orig_stride,
2003                                  uint8_t *recon, int recon_stride,
2004                                  unsigned int cols, unsigned int rows) {
2005   unsigned int row, col;
2006   uint64_t total_sse = 0;
2007   int diff;
2008
2009   for (row = 0; row + 16 <= rows; row += 16) {
2010     for (col = 0; col + 16 <= cols; col += 16) {
2011       unsigned int sse;
2012
2013       vp9_mse16x16(orig + col, orig_stride, recon + col, recon_stride, &sse);
2014       total_sse += sse;
2015     }
2016
2017     /* Handle odd-sized width */
2018     if (col < cols) {
2019       unsigned int border_row, border_col;
2020       uint8_t *border_orig = orig;
2021       uint8_t *border_recon = recon;
2022
2023       for (border_row = 0; border_row < 16; border_row++) {
2024         for (border_col = col; border_col < cols; border_col++) {
2025           diff = border_orig[border_col] - border_recon[border_col];
2026           total_sse += diff * diff;
2027         }
2028
2029         border_orig += orig_stride;
2030         border_recon += recon_stride;
2031       }
2032     }
2033
2034     orig += orig_stride * 16;
2035     recon += recon_stride * 16;
2036   }
2037
2038   /* Handle odd-sized height */
2039   for (; row < rows; row++) {
2040     for (col = 0; col < cols; col++) {
2041       diff = orig[col] - recon[col];
2042       total_sse += diff * diff;
2043     }
2044
2045     orig += orig_stride;
2046     recon += recon_stride;
2047   }
2048
2049   return total_sse;
2050 }
2051
2052
2053 static void generate_psnr_packet(VP9_COMP *cpi) {
2054   YV12_BUFFER_CONFIG      *orig = cpi->Source;
2055   YV12_BUFFER_CONFIG      *recon = cpi->common.frame_to_show;
2056   struct vpx_codec_cx_pkt  pkt;
2057   uint64_t                 sse;
2058   int                      i;
2059   unsigned int             width = orig->y_crop_width;
2060   unsigned int             height = orig->y_crop_height;
2061
2062   pkt.kind = VPX_CODEC_PSNR_PKT;
2063   sse = calc_plane_error(orig->y_buffer, orig->y_stride,
2064                          recon->y_buffer, recon->y_stride,
2065                          width, height);
2066   pkt.data.psnr.sse[0] = sse;
2067   pkt.data.psnr.sse[1] = sse;
2068   pkt.data.psnr.samples[0] = width * height;
2069   pkt.data.psnr.samples[1] = width * height;
2070
2071   width = orig->uv_crop_width;
2072   height = orig->uv_crop_height;
2073
2074   sse = calc_plane_error(orig->u_buffer, orig->uv_stride,
2075                          recon->u_buffer, recon->uv_stride,
2076                          width, height);
2077   pkt.data.psnr.sse[0] += sse;
2078   pkt.data.psnr.sse[2] = sse;
2079   pkt.data.psnr.samples[0] += width * height;
2080   pkt.data.psnr.samples[2] = width * height;
2081
2082   sse = calc_plane_error(orig->v_buffer, orig->uv_stride,
2083                          recon->v_buffer, recon->uv_stride,
2084                          width, height);
2085   pkt.data.psnr.sse[0] += sse;
2086   pkt.data.psnr.sse[3] = sse;
2087   pkt.data.psnr.samples[0] += width * height;
2088   pkt.data.psnr.samples[3] = width * height;
2089
2090   for (i = 0; i < 4; i++)
2091     pkt.data.psnr.psnr[i] = vp9_mse2psnr(pkt.data.psnr.samples[i], 255.0,
2092                                          (double)pkt.data.psnr.sse[i]);
2093
2094   vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
2095 }
2096
2097
2098 int vp9_use_as_reference(VP9_PTR ptr, int ref_frame_flags) {
2099   VP9_COMP *cpi = (VP9_COMP *)(ptr);
2100
2101   if (ref_frame_flags > 7)
2102     return -1;
2103
2104   cpi->ref_frame_flags = ref_frame_flags;
2105   return 0;
2106 }
2107 int vp9_update_reference(VP9_PTR ptr, int ref_frame_flags) {
2108   VP9_COMP *cpi = (VP9_COMP *)(ptr);
2109
2110   if (ref_frame_flags > 7)
2111     return -1;
2112
2113   cpi->refresh_golden_frame = 0;
2114   cpi->refresh_alt_ref_frame = 0;
2115   cpi->refresh_last_frame   = 0;
2116
2117   if (ref_frame_flags & VP9_LAST_FLAG)
2118     cpi->refresh_last_frame = 1;
2119
2120   if (ref_frame_flags & VP9_GOLD_FLAG)
2121     cpi->refresh_golden_frame = 1;
2122
2123   if (ref_frame_flags & VP9_ALT_FLAG)
2124     cpi->refresh_alt_ref_frame = 1;
2125
2126   return 0;
2127 }
2128
2129 int vp9_copy_reference_enc(VP9_PTR ptr, VP9_REFFRAME ref_frame_flag,
2130                            YV12_BUFFER_CONFIG *sd) {
2131   VP9_COMP *cpi = (VP9_COMP *)(ptr);
2132   VP9_COMMON *cm = &cpi->common;
2133   int ref_fb_idx;
2134
2135   if (ref_frame_flag == VP9_LAST_FLAG)
2136     ref_fb_idx = cm->ref_frame_map[cpi->lst_fb_idx];
2137   else if (ref_frame_flag == VP9_GOLD_FLAG)
2138     ref_fb_idx = cm->ref_frame_map[cpi->gld_fb_idx];
2139   else if (ref_frame_flag == VP9_ALT_FLAG)
2140     ref_fb_idx = cm->ref_frame_map[cpi->alt_fb_idx];
2141   else
2142     return -1;
2143
2144   vp8_yv12_copy_frame(&cm->yv12_fb[ref_fb_idx], sd);
2145
2146   return 0;
2147 }
2148
2149 int vp9_get_reference_enc(VP9_PTR ptr, int index, YV12_BUFFER_CONFIG **fb) {
2150   VP9_COMP *cpi = (VP9_COMP *)(ptr);
2151   VP9_COMMON *cm = &cpi->common;
2152
2153   if (index < 0 || index >= NUM_REF_FRAMES)
2154     return -1;
2155
2156   *fb = &cm->yv12_fb[cm->ref_frame_map[index]];
2157   return 0;
2158 }
2159
2160 int vp9_set_reference_enc(VP9_PTR ptr, VP9_REFFRAME ref_frame_flag,
2161                           YV12_BUFFER_CONFIG *sd) {
2162   VP9_COMP *cpi = (VP9_COMP *)(ptr);
2163   VP9_COMMON *cm = &cpi->common;
2164
2165   int ref_fb_idx;
2166
2167   if (ref_frame_flag == VP9_LAST_FLAG)
2168     ref_fb_idx = cm->ref_frame_map[cpi->lst_fb_idx];
2169   else if (ref_frame_flag == VP9_GOLD_FLAG)
2170     ref_fb_idx = cm->ref_frame_map[cpi->gld_fb_idx];
2171   else if (ref_frame_flag == VP9_ALT_FLAG)
2172     ref_fb_idx = cm->ref_frame_map[cpi->alt_fb_idx];
2173   else
2174     return -1;
2175
2176   vp8_yv12_copy_frame(sd, &cm->yv12_fb[ref_fb_idx]);
2177
2178   return 0;
2179 }
2180 int vp9_update_entropy(VP9_PTR comp, int update) {
2181   ((VP9_COMP *)comp)->common.refresh_frame_context = update;
2182   return 0;
2183 }
2184
2185
2186 #ifdef OUTPUT_YUV_SRC
2187 void vp9_write_yuv_frame(YV12_BUFFER_CONFIG *s) {
2188   uint8_t *src = s->y_buffer;
2189   int h = s->y_height;
2190
2191   do {
2192     fwrite(src, s->y_width, 1,  yuv_file);
2193     src += s->y_stride;
2194   } while (--h);
2195
2196   src = s->u_buffer;
2197   h = s->uv_height;
2198
2199   do {
2200     fwrite(src, s->uv_width, 1,  yuv_file);
2201     src += s->uv_stride;
2202   } while (--h);
2203
2204   src = s->v_buffer;
2205   h = s->uv_height;
2206
2207   do {
2208     fwrite(src, s->uv_width, 1, yuv_file);
2209     src += s->uv_stride;
2210   } while (--h);
2211 }
2212 #endif
2213
2214 #ifdef OUTPUT_YUV_REC
2215 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
2216   YV12_BUFFER_CONFIG *s = cm->frame_to_show;
2217   uint8_t *src = s->y_buffer;
2218   int h = cm->height;
2219
2220   do {
2221     fwrite(src, s->y_width, 1,  yuv_rec_file);
2222     src += s->y_stride;
2223   } while (--h);
2224
2225   src = s->u_buffer;
2226   h = s->uv_height;
2227
2228   do {
2229     fwrite(src, s->uv_width, 1,  yuv_rec_file);
2230     src += s->uv_stride;
2231   } while (--h);
2232
2233   src = s->v_buffer;
2234   h = s->uv_height;
2235
2236   do {
2237     fwrite(src, s->uv_width, 1, yuv_rec_file);
2238     src += s->uv_stride;
2239   } while (--h);
2240
2241 #if CONFIG_ALPHA
2242   if (s->alpha_buffer) {
2243     src = s->alpha_buffer;
2244     h = s->alpha_height;
2245     do {
2246       fwrite(src, s->alpha_width, 1,  yuv_rec_file);
2247       src += s->alpha_stride;
2248     } while (--h);
2249   }
2250 #endif
2251
2252   fflush(yuv_rec_file);
2253 }
2254 #endif
2255
2256 static void scale_and_extend_frame(YV12_BUFFER_CONFIG *src_fb,
2257                                    YV12_BUFFER_CONFIG *dst_fb) {
2258   const int in_w = src_fb->y_crop_width;
2259   const int in_h = src_fb->y_crop_height;
2260   const int out_w = dst_fb->y_crop_width;
2261   const int out_h = dst_fb->y_crop_height;
2262   int x, y, i;
2263
2264   uint8_t *srcs[4] = {src_fb->y_buffer, src_fb->u_buffer, src_fb->v_buffer,
2265                       src_fb->alpha_buffer};
2266   int src_strides[4] = {src_fb->y_stride, src_fb->uv_stride, src_fb->uv_stride,
2267                         src_fb->alpha_stride};
2268
2269   uint8_t *dsts[4] = {dst_fb->y_buffer, dst_fb->u_buffer, dst_fb->v_buffer,
2270                       dst_fb->alpha_buffer};
2271   int dst_strides[4] = {dst_fb->y_stride, dst_fb->uv_stride, dst_fb->uv_stride,
2272                         dst_fb->alpha_stride};
2273
2274   for (y = 0; y < out_h; y += 16) {
2275     for (x = 0; x < out_w; x += 16) {
2276       for (i = 0; i < MAX_MB_PLANE; ++i) {
2277         const int factor = i == 0 ? 1 : 2;
2278         const int x_q4 = x * (16 / factor) * in_w / out_w;
2279         const int y_q4 = y * (16 / factor) * in_h / out_h;
2280         const int src_stride = src_strides[i];
2281         const int dst_stride = dst_strides[i];
2282         uint8_t *src = srcs[i] + y / factor * in_h / out_h * src_stride +
2283                                  x / factor * in_w / out_w;
2284         uint8_t *dst = dsts[i] + y / factor * dst_stride + x / factor;
2285
2286         vp9_convolve8(src, src_stride, dst, dst_stride,
2287                       vp9_sub_pel_filters_8[x_q4 & 0xf], 16 * in_w / out_w,
2288                       vp9_sub_pel_filters_8[y_q4 & 0xf], 16 * in_h / out_h,
2289                       16 / factor, 16 / factor);
2290       }
2291     }
2292   }
2293
2294   vp8_yv12_extend_frame_borders(dst_fb);
2295 }
2296
2297
2298 static void update_alt_ref_frame_stats(VP9_COMP *cpi) {
2299   // this frame refreshes means next frames don't unless specified by user
2300   cpi->rc.frames_since_golden = 0;
2301
2302 #if CONFIG_MULTIPLE_ARF
2303   if (!cpi->multi_arf_enabled)
2304 #endif
2305     // Clear the alternate reference update pending flag.
2306     cpi->source_alt_ref_pending = 0;
2307
2308   // Set the alternate reference frame active flag
2309   cpi->source_alt_ref_active = 1;
2310 }
2311 static void update_golden_frame_stats(VP9_COMP *cpi) {
2312   // Update the Golden frame usage counts.
2313   if (cpi->refresh_golden_frame) {
2314     // this frame refreshes means next frames don't unless specified by user
2315     cpi->refresh_golden_frame = 0;
2316     cpi->rc.frames_since_golden = 0;
2317
2318     // ******** Fixed Q test code only ************
2319     // If we are going to use the ALT reference for the next group of frames
2320     // set a flag to say so.
2321     if (cpi->oxcf.fixed_q >= 0 &&
2322         cpi->oxcf.play_alternate && !cpi->refresh_alt_ref_frame) {
2323       cpi->source_alt_ref_pending = 1;
2324       cpi->rc.frames_till_gf_update_due = cpi->rc.baseline_gf_interval;
2325
2326       // TODO(ivan): For SVC encoder, GF automatic update is disabled by using
2327       // a large GF_interval.
2328       if (cpi->use_svc) {
2329         cpi->rc.frames_till_gf_update_due = INT_MAX;
2330       }
2331     }
2332
2333     if (!cpi->source_alt_ref_pending)
2334       cpi->source_alt_ref_active = 0;
2335
2336     // Decrement count down till next gf
2337     if (cpi->rc.frames_till_gf_update_due > 0)
2338       cpi->rc.frames_till_gf_update_due--;
2339
2340   } else if (!cpi->refresh_alt_ref_frame) {
2341     // Decrement count down till next gf
2342     if (cpi->rc.frames_till_gf_update_due > 0)
2343       cpi->rc.frames_till_gf_update_due--;
2344
2345     if (cpi->frames_till_alt_ref_frame)
2346       cpi->frames_till_alt_ref_frame--;
2347
2348     cpi->rc.frames_since_golden++;
2349   }
2350 }
2351
2352 static int find_fp_qindex() {
2353   int i;
2354
2355   for (i = 0; i < QINDEX_RANGE; i++) {
2356     if (vp9_convert_qindex_to_q(i) >= 30.0) {
2357       break;
2358     }
2359   }
2360
2361   if (i == QINDEX_RANGE)
2362     i--;
2363
2364   return i;
2365 }
2366
2367 static void Pass1Encode(VP9_COMP *cpi, unsigned long *size, unsigned char *dest,
2368                         unsigned int *frame_flags) {
2369   (void) size;
2370   (void) dest;
2371   (void) frame_flags;
2372
2373   vp9_set_quantizer(cpi, find_fp_qindex());
2374   vp9_first_pass(cpi);
2375 }
2376
2377 #define WRITE_RECON_BUFFER 0
2378 #if WRITE_RECON_BUFFER
2379 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame) {
2380   FILE *yframe;
2381   int i;
2382   char filename[255];
2383
2384   snprintf(filename, sizeof(filename), "cx\\y%04d.raw", this_frame);
2385   yframe = fopen(filename, "wb");
2386
2387   for (i = 0; i < frame->y_height; i++)
2388     fwrite(frame->y_buffer + i * frame->y_stride,
2389            frame->y_width, 1, yframe);
2390
2391   fclose(yframe);
2392   snprintf(filename, sizeof(filename), "cx\\u%04d.raw", this_frame);
2393   yframe = fopen(filename, "wb");
2394
2395   for (i = 0; i < frame->uv_height; i++)
2396     fwrite(frame->u_buffer + i * frame->uv_stride,
2397            frame->uv_width, 1, yframe);
2398
2399   fclose(yframe);
2400   snprintf(filename, sizeof(filename), "cx\\v%04d.raw", this_frame);
2401   yframe = fopen(filename, "wb");
2402
2403   for (i = 0; i < frame->uv_height; i++)
2404     fwrite(frame->v_buffer + i * frame->uv_stride,
2405            frame->uv_width, 1, yframe);
2406
2407   fclose(yframe);
2408 }
2409 #endif
2410
2411 static double compute_edge_pixel_proportion(YV12_BUFFER_CONFIG *frame) {
2412 #define EDGE_THRESH 128
2413   int i, j;
2414   int num_edge_pels = 0;
2415   int num_pels = (frame->y_height - 2) * (frame->y_width - 2);
2416   uint8_t *prev = frame->y_buffer + 1;
2417   uint8_t *curr = frame->y_buffer + 1 + frame->y_stride;
2418   uint8_t *next = frame->y_buffer + 1 + 2 * frame->y_stride;
2419   for (i = 1; i < frame->y_height - 1; i++) {
2420     for (j = 1; j < frame->y_width - 1; j++) {
2421       /* Sobel hor and ver gradients */
2422       int v = 2 * (curr[1] - curr[-1]) + (prev[1] - prev[-1]) +
2423               (next[1] - next[-1]);
2424       int h = 2 * (prev[0] - next[0]) + (prev[1] - next[1]) +
2425               (prev[-1] - next[-1]);
2426       h = (h < 0 ? -h : h);
2427       v = (v < 0 ? -v : v);
2428       if (h > EDGE_THRESH || v > EDGE_THRESH)
2429         num_edge_pels++;
2430       curr++;
2431       prev++;
2432       next++;
2433     }
2434     curr += frame->y_stride - frame->y_width + 2;
2435     prev += frame->y_stride - frame->y_width + 2;
2436     next += frame->y_stride - frame->y_width + 2;
2437   }
2438   return (double)num_edge_pels / num_pels;
2439 }
2440
2441 // Function to test for conditions that indicate we should loop
2442 // back and recode a frame.
2443 static int recode_loop_test(VP9_COMP *cpi,
2444                             int high_limit, int low_limit,
2445                             int q, int maxq, int minq) {
2446   int force_recode = 0;
2447   VP9_COMMON *cm = &cpi->common;
2448
2449   // Is frame recode allowed at all
2450   // Yes if either recode mode 1 is selected or mode two is selected
2451   // and the frame is a key frame. golden frame or alt_ref_frame
2452   if ((cpi->sf.recode_loop == 1) ||
2453       ((cpi->sf.recode_loop == 2) &&
2454        ((cm->frame_type == KEY_FRAME) ||
2455         cpi->refresh_golden_frame ||
2456         cpi->refresh_alt_ref_frame))) {
2457     // General over and under shoot tests
2458     if (((cpi->rc.projected_frame_size > high_limit) && (q < maxq)) ||
2459         ((cpi->rc.projected_frame_size < low_limit) && (q > minq))) {
2460       force_recode = 1;
2461     } else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
2462       // Deal with frame undershoot and whether or not we are
2463       // below the automatically set cq level.
2464       if (q > cpi->cq_target_quality &&
2465           cpi->rc.projected_frame_size <
2466           ((cpi->rc.this_frame_target * 7) >> 3)) {
2467         force_recode = 1;
2468       } else if (q > cpi->oxcf.cq_level &&
2469                  cpi->rc.projected_frame_size < cpi->rc.min_frame_bandwidth &&
2470                  cpi->rc.active_best_quality > cpi->oxcf.cq_level) {
2471         // Severe undershoot and between auto and user cq level
2472         force_recode = 1;
2473         cpi->rc.active_best_quality = cpi->oxcf.cq_level;
2474       }
2475     }
2476   }
2477
2478   return force_recode;
2479 }
2480
2481 static void update_reference_frames(VP9_COMP * const cpi) {
2482   VP9_COMMON * const cm = &cpi->common;
2483
2484   // At this point the new frame has been encoded.
2485   // If any buffer copy / swapping is signaled it should be done here.
2486   if (cm->frame_type == KEY_FRAME) {
2487     ref_cnt_fb(cm->fb_idx_ref_cnt,
2488                &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2489     ref_cnt_fb(cm->fb_idx_ref_cnt,
2490                &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2491   }
2492 #if CONFIG_MULTIPLE_ARF
2493   else if (!cpi->multi_arf_enabled && cpi->refresh_golden_frame &&
2494       !cpi->refresh_alt_ref_frame) {
2495 #else
2496   else if (cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame &&
2497            !cpi->use_svc) {
2498 #endif
2499     /* Preserve the previously existing golden frame and update the frame in
2500      * the alt ref slot instead. This is highly specific to the current use of
2501      * alt-ref as a forward reference, and this needs to be generalized as
2502      * other uses are implemented (like RTC/temporal scaling)
2503      *
2504      * The update to the buffer in the alt ref slot was signaled in
2505      * vp9_pack_bitstream(), now swap the buffer pointers so that it's treated
2506      * as the golden frame next time.
2507      */
2508     int tmp;
2509
2510     ref_cnt_fb(cm->fb_idx_ref_cnt,
2511                &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
2512
2513     tmp = cpi->alt_fb_idx;
2514     cpi->alt_fb_idx = cpi->gld_fb_idx;
2515     cpi->gld_fb_idx = tmp;
2516   }  else { /* For non key/golden frames */
2517     if (cpi->refresh_alt_ref_frame) {
2518       int arf_idx = cpi->alt_fb_idx;
2519 #if CONFIG_MULTIPLE_ARF
2520       if (cpi->multi_arf_enabled) {
2521         arf_idx = cpi->arf_buffer_idx[cpi->sequence_number + 1];
2522       }
2523 #endif
2524       ref_cnt_fb(cm->fb_idx_ref_cnt,
2525                  &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
2526     }
2527
2528     if (cpi->refresh_golden_frame) {
2529       ref_cnt_fb(cm->fb_idx_ref_cnt,
2530                  &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
2531     }
2532   }
2533
2534   if (cpi->refresh_last_frame) {
2535     ref_cnt_fb(cm->fb_idx_ref_cnt,
2536                &cm->ref_frame_map[cpi->lst_fb_idx], cm->new_fb_idx);
2537   }
2538 }
2539
2540 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
2541   MACROBLOCKD *xd = &cpi->mb.e_mbd;
2542   struct loopfilter *lf = &cm->lf;
2543   if (xd->lossless) {
2544       lf->filter_level = 0;
2545   } else {
2546     struct vpx_usec_timer timer;
2547
2548     vp9_clear_system_state();
2549
2550     vpx_usec_timer_start(&timer);
2551
2552     vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.use_fast_lpf_pick);
2553
2554     vpx_usec_timer_mark(&timer);
2555     cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
2556   }
2557
2558   if (lf->filter_level > 0) {
2559     vp9_set_alt_lf_level(cpi, lf->filter_level);
2560     vp9_loop_filter_frame(cm, xd, lf->filter_level, 0, 0);
2561   }
2562
2563   vp9_extend_frame_inner_borders(cm->frame_to_show,
2564                                  cm->subsampling_x, cm->subsampling_y);
2565 }
2566
2567 static void scale_references(VP9_COMP *cpi) {
2568   VP9_COMMON *cm = &cpi->common;
2569   int i;
2570   int refs[ALLOWED_REFS_PER_FRAME] = {cpi->lst_fb_idx, cpi->gld_fb_idx,
2571                                       cpi->alt_fb_idx};
2572
2573   for (i = 0; i < 3; i++) {
2574     YV12_BUFFER_CONFIG *ref = &cm->yv12_fb[cm->ref_frame_map[refs[i]]];
2575
2576     if (ref->y_crop_width != cm->width ||
2577         ref->y_crop_height != cm->height) {
2578       int new_fb = get_free_fb(cm);
2579
2580       vp9_realloc_frame_buffer(&cm->yv12_fb[new_fb],
2581                                cm->width, cm->height,
2582                                cm->subsampling_x, cm->subsampling_y,
2583                                VP9BORDERINPIXELS);
2584       scale_and_extend_frame(ref, &cm->yv12_fb[new_fb]);
2585       cpi->scaled_ref_idx[i] = new_fb;
2586     } else {
2587       cpi->scaled_ref_idx[i] = cm->ref_frame_map[refs[i]];
2588       cm->fb_idx_ref_cnt[cm->ref_frame_map[refs[i]]]++;
2589     }
2590   }
2591 }
2592
2593 static void release_scaled_references(VP9_COMP *cpi) {
2594   VP9_COMMON *cm = &cpi->common;
2595   int i;
2596
2597   for (i = 0; i < 3; i++)
2598     cm->fb_idx_ref_cnt[cpi->scaled_ref_idx[i]]--;
2599 }
2600
2601 static void full_to_model_count(unsigned int *model_count,
2602                                 unsigned int *full_count) {
2603   int n;
2604   model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
2605   model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
2606   model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
2607   for (n = THREE_TOKEN; n < DCT_EOB_TOKEN; ++n)
2608     model_count[TWO_TOKEN] += full_count[n];
2609   model_count[DCT_EOB_MODEL_TOKEN] = full_count[DCT_EOB_TOKEN];
2610 }
2611
2612 static void full_to_model_counts(
2613     vp9_coeff_count_model *model_count, vp9_coeff_count *full_count) {
2614   int i, j, k, l;
2615   for (i = 0; i < BLOCK_TYPES; ++i)
2616     for (j = 0; j < REF_TYPES; ++j)
2617       for (k = 0; k < COEF_BANDS; ++k)
2618         for (l = 0; l < PREV_COEF_CONTEXTS; ++l) {
2619           if (l >= 3 && k == 0)
2620             continue;
2621           full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
2622         }
2623 }
2624
2625 #if 0 && CONFIG_INTERNAL_STATS
2626 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
2627   VP9_COMMON *const cm = &cpi->common;
2628   FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
2629   int recon_err;
2630
2631   vp9_clear_system_state();  // __asm emms;
2632
2633   recon_err = vp9_calc_ss_err(cpi->Source, get_frame_new_buffer(cm));
2634
2635   if (cpi->twopass.total_left_stats.coded_error != 0.0)
2636     fprintf(f, "%10d %10d %10d %10d %10d %10d %10d %10d %10d"
2637         "%7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f"
2638         "%6d %6d %5d %5d %5d %8.2f %10d %10.3f"
2639         "%10.3f %8d %10d %10d %10d\n",
2640         cpi->common.current_video_frame, cpi->rc.this_frame_target,
2641         cpi->rc.projected_frame_size, 0,
2642         (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
2643         (int)cpi->rc.total_target_vs_actual,
2644         (int)(cpi->oxcf.starting_buffer_level - cpi->rc.bits_off_target),
2645         (int)cpi->rc.total_actual_bits, cm->base_qindex,
2646         vp9_convert_qindex_to_q(cm->base_qindex),
2647         (double)vp9_dc_quant(cm->base_qindex, 0) / 4.0,
2648         vp9_convert_qindex_to_q(cpi->rc.active_best_quality),
2649         vp9_convert_qindex_to_q(cpi->rc.active_worst_quality), cpi->rc.avg_q,
2650         vp9_convert_qindex_to_q(cpi->rc.ni_av_qi),
2651         vp9_convert_qindex_to_q(cpi->cq_target_quality),
2652         cpi->refresh_last_frame, cpi->refresh_golden_frame,
2653         cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
2654         cpi->twopass.est_max_qcorrection_factor, (int)cpi->twopass.bits_left,
2655         cpi->twopass.total_left_stats.coded_error,
2656         (double)cpi->twopass.bits_left /
2657             (1 + cpi->twopass.total_left_stats.coded_error),
2658         cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
2659         cpi->kf_zeromotion_pct);
2660
2661   fclose(f);
2662
2663   if (0) {
2664     FILE *const fmodes = fopen("Modes.stt", "a");
2665     int i;
2666
2667     fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
2668             cm->frame_type, cpi->refresh_golden_frame,
2669             cpi->refresh_alt_ref_frame);
2670
2671     for (i = 0; i < MAX_MODES; ++i)
2672       fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
2673     for (i = 0; i < MAX_REFS; ++i)
2674       fprintf(fmodes, "%5d ", cpi->sub8x8_mode_chosen_counts[i]);
2675
2676     fprintf(fmodes, "\n");
2677
2678     fclose(fmodes);
2679   }
2680 }
2681 #endif
2682
2683 static void encode_with_recode_loop(VP9_COMP *cpi,
2684                                     unsigned long *size,
2685                                     uint8_t *dest,
2686                                     int q,
2687                                     int bottom_index,
2688                                     int top_index,
2689                                     int frame_over_shoot_limit,
2690                                     int frame_under_shoot_limit) {
2691   VP9_COMMON *const cm = &cpi->common;
2692   int loop_count = 0;
2693   int loop = 0;
2694   int overshoot_seen = 0;
2695   int undershoot_seen = 0;
2696   int q_low = bottom_index, q_high = top_index;
2697   do {
2698     vp9_clear_system_state();  // __asm emms;
2699
2700     vp9_set_quantizer(cpi, q);
2701
2702     if (loop_count == 0) {
2703       // Set up entropy context depending on frame type. The decoder mandates
2704       // the use of the default context, index 0, for keyframes and inter
2705       // frames where the error_resilient_mode or intra_only flag is set. For
2706       // other inter-frames the encoder currently uses only two contexts;
2707       // context 1 for ALTREF frames and context 0 for the others.
2708       if (cm->frame_type == KEY_FRAME) {
2709         vp9_setup_key_frame(cpi);
2710       } else {
2711         if (!cm->intra_only && !cm->error_resilient_mode) {
2712           cpi->common.frame_context_idx = cpi->refresh_alt_ref_frame;
2713         }
2714         vp9_setup_inter_frame(cpi);
2715       }
2716     }
2717
2718     // Variance adaptive and in frame q adjustment experiments are mutually
2719     // exclusive.
2720     if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
2721       vp9_vaq_frame_setup(cpi);
2722     } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
2723       setup_in_frame_q_adj(cpi);
2724     }
2725
2726     // transform / motion compensation build reconstruction frame
2727
2728     vp9_encode_frame(cpi);
2729
2730     // Update the skip mb flag probabilities based on the distribution
2731     // seen in the last encoder iteration.
2732     // update_base_skip_probs(cpi);
2733
2734     vp9_clear_system_state();  // __asm emms;
2735
2736     // Dummy pack of the bitstream using up to date stats to get an
2737     // accurate estimate of output frame size to determine if we need
2738     // to recode.
2739     vp9_save_coding_context(cpi);
2740     cpi->dummy_packing = 1;
2741     vp9_pack_bitstream(cpi, dest, size);
2742     cpi->rc.projected_frame_size = (*size) << 3;
2743     vp9_restore_coding_context(cpi);
2744
2745     if (frame_over_shoot_limit == 0)
2746       frame_over_shoot_limit = 1;
2747
2748     if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
2749       loop = 0;
2750     } else {
2751       // Special case handling for forced key frames
2752       if ((cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced) {
2753         int last_q = q;
2754         int kf_err = vp9_calc_ss_err(cpi->Source, get_frame_new_buffer(cm));
2755
2756         int high_err_target = cpi->ambient_err;
2757         int low_err_target = cpi->ambient_err >> 1;
2758
2759         // Prevent possible divide by zero error below for perfect KF
2760         kf_err += !kf_err;
2761
2762         // The key frame is not good enough or we can afford
2763         // to make it better without undue risk of popping.
2764         if ((kf_err > high_err_target &&
2765              cpi->rc.projected_frame_size <= frame_over_shoot_limit) ||
2766             (kf_err > low_err_target &&
2767              cpi->rc.projected_frame_size <= frame_under_shoot_limit)) {
2768           // Lower q_high
2769           q_high = q > q_low ? q - 1 : q_low;
2770
2771           // Adjust Q
2772           q = (q * high_err_target) / kf_err;
2773           q = MIN(q, (q_high + q_low) >> 1);
2774         } else if (kf_err < low_err_target &&
2775                    cpi->rc.projected_frame_size >= frame_under_shoot_limit) {
2776           // The key frame is much better than the previous frame
2777           // Raise q_low
2778           q_low = q < q_high ? q + 1 : q_high;
2779
2780           // Adjust Q
2781           q = (q * low_err_target) / kf_err;
2782           q = MIN(q, (q_high + q_low + 1) >> 1);
2783         }
2784
2785         // Clamp Q to upper and lower limits:
2786         q = clamp(q, q_low, q_high);
2787
2788         loop = q != last_q;
2789       } else if (recode_loop_test(
2790           cpi, frame_over_shoot_limit, frame_under_shoot_limit,
2791           q, top_index, bottom_index)) {
2792         // Is the projected frame size out of range and are we allowed
2793         // to attempt to recode.
2794         int last_q = q;
2795         int retries = 0;
2796
2797         // Frame size out of permitted range:
2798         // Update correction factor & compute new Q to try...
2799
2800         // Frame is too large
2801         if (cpi->rc.projected_frame_size > cpi->rc.this_frame_target) {
2802           // Raise Qlow as to at least the current value
2803           q_low = q < q_high ? q + 1 : q_high;
2804
2805           if (undershoot_seen || loop_count > 1) {
2806             // Update rate_correction_factor unless
2807             vp9_update_rate_correction_factors(cpi, 1);
2808
2809             q = (q_high + q_low + 1) / 2;
2810           } else {
2811             // Update rate_correction_factor unless
2812             vp9_update_rate_correction_factors(cpi, 0);
2813
2814             q = vp9_regulate_q(cpi, cpi->rc.this_frame_target);
2815
2816             while (q < q_low && retries < 10) {
2817               vp9_update_rate_correction_factors(cpi, 0);
2818               q = vp9_regulate_q(cpi, cpi->rc.this_frame_target);
2819               retries++;
2820             }
2821           }
2822
2823           overshoot_seen = 1;
2824         } else {
2825           // Frame is too small
2826           q_high = q > q_low ? q - 1 : q_low;
2827
2828           if (overshoot_seen || loop_count > 1) {
2829             // Update rate_correction_factor unless
2830             // cpi->rc.active_worst_quality has changed.
2831             vp9_update_rate_correction_factors(cpi, 1);
2832
2833             q = (q_high + q_low) / 2;
2834           } else {
2835             // Update rate_correction_factor unless
2836             // cpi->rc.active_worst_quality has changed.
2837             vp9_update_rate_correction_factors(cpi, 0);
2838
2839             q = vp9_regulate_q(cpi, cpi->rc.this_frame_target);
2840
2841             // Special case reset for qlow for constrained quality.
2842             // This should only trigger where there is very substantial
2843             // undershoot on a frame and the auto cq level is above
2844             // the user passsed in value.
2845             if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY && q < q_low) {
2846               q_low = q;
2847             }
2848
2849             while (q > q_high && retries < 10) {
2850               vp9_update_rate_correction_factors(cpi, 0);
2851               q = vp9_regulate_q(cpi, cpi->rc.this_frame_target);
2852               retries++;
2853             }
2854           }
2855
2856           undershoot_seen = 1;
2857         }
2858
2859         // Clamp Q to upper and lower limits:
2860         q = clamp(q, q_low, q_high);
2861
2862         loop = q != last_q;
2863       } else {
2864         loop = 0;
2865       }
2866     }
2867
2868     if (cpi->is_src_frame_alt_ref)
2869       loop = 0;
2870
2871     if (loop) {
2872       loop_count++;
2873
2874 #if CONFIG_INTERNAL_STATS
2875       cpi->tot_recode_hits++;
2876 #endif
2877     }
2878   } while (loop);
2879 }
2880
2881 static void encode_frame_to_data_rate(VP9_COMP *cpi,
2882                                       unsigned long *size,
2883                                       uint8_t *dest,
2884                                       unsigned int *frame_flags) {
2885   VP9_COMMON *const cm = &cpi->common;
2886   TX_SIZE t;
2887   int q;
2888   int frame_over_shoot_limit;
2889   int frame_under_shoot_limit;
2890
2891   int top_index;
2892   int bottom_index;
2893
2894   SPEED_FEATURES *const sf = &cpi->sf;
2895   unsigned int max_mv_def = MIN(cpi->common.width, cpi->common.height);
2896   struct segmentation *const seg = &cm->seg;
2897
2898   /* Scale the source buffer, if required. */
2899   if (cm->mi_cols * 8 != cpi->un_scaled_source->y_width ||
2900       cm->mi_rows * 8 != cpi->un_scaled_source->y_height) {
2901     scale_and_extend_frame(cpi->un_scaled_source, &cpi->scaled_source);
2902     cpi->Source = &cpi->scaled_source;
2903   } else {
2904     cpi->Source = cpi->un_scaled_source;
2905   }
2906   scale_references(cpi);
2907
2908   // Clear down mmx registers to allow floating point in what follows.
2909   vp9_clear_system_state();
2910
2911   // For an alt ref frame in 2 pass we skip the call to the second
2912   // pass function that sets the target bandwidth so we must set it here.
2913   if (cpi->refresh_alt_ref_frame) {
2914     // Set a per frame bit target for the alt ref frame.
2915     cpi->rc.per_frame_bandwidth = cpi->twopass.gf_bits;
2916     // Set a per second target bitrate.
2917     cpi->target_bandwidth = (int)(cpi->twopass.gf_bits * cpi->output_framerate);
2918   }
2919
2920   // Clear zbin over-quant value and mode boost values.
2921   cpi->zbin_mode_boost = 0;
2922
2923   // Enable or disable mode based tweaking of the zbin.
2924   // For 2 pass only used where GF/ARF prediction quality
2925   // is above a threshold.
2926   cpi->zbin_mode_boost = 0;
2927   cpi->zbin_mode_boost_enabled = 0;
2928
2929   // Current default encoder behavior for the altref sign bias.
2930   cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = cpi->source_alt_ref_active;
2931
2932   // Check to see if a key frame is signaled.
2933   // For two pass with auto key frame enabled cm->frame_type may already be
2934   // set, but not for one pass.
2935   if ((cm->current_video_frame == 0) ||
2936       (cm->frame_flags & FRAMEFLAGS_KEY) ||
2937       (cpi->oxcf.auto_key && (cpi->frames_since_key %
2938                               cpi->key_frame_frequency == 0))) {
2939     // Set frame type to key frame for the force key frame, if we exceed the
2940     // maximum distance in an automatic keyframe selection or for the first
2941     // frame.
2942     cm->frame_type = KEY_FRAME;
2943   }
2944
2945   // Set default state for segment based loop filter update flags.
2946   cm->lf.mode_ref_delta_update = 0;
2947
2948   // Initialize cpi->mv_step_param to default based on max resolution.
2949   cpi->mv_step_param = vp9_init_search_range(cpi, max_mv_def);
2950   // Initialize cpi->max_mv_magnitude and cpi->mv_step_param if appropriate.
2951   if (sf->auto_mv_step_size) {
2952     if (frame_is_intra_only(&cpi->common)) {
2953       // Initialize max_mv_magnitude for use in the first INTER frame
2954       // after a key/intra-only frame.
2955       cpi->max_mv_magnitude = max_mv_def;
2956     } else {
2957       if (cm->show_frame)
2958         // Allow mv_steps to correspond to twice the max mv magnitude found
2959         // in the previous frame, capped by the default max_mv_magnitude based
2960         // on resolution.
2961         cpi->mv_step_param = vp9_init_search_range(
2962             cpi, MIN(max_mv_def, 2 * cpi->max_mv_magnitude));
2963       cpi->max_mv_magnitude = 0;
2964     }
2965   }
2966
2967   // Set various flags etc to special state if it is a key frame.
2968   if (frame_is_intra_only(cm)) {
2969     vp9_setup_key_frame(cpi);
2970     // Reset the loop filter deltas and segmentation map.
2971     setup_features(cm);
2972
2973     // If segmentation is enabled force a map update for key frames.
2974     if (seg->enabled) {
2975       seg->update_map = 1;
2976       seg->update_data = 1;
2977     }
2978
2979     // The alternate reference frame cannot be active for a key frame.
2980     cpi->source_alt_ref_active = 0;
2981
2982     cm->error_resilient_mode = (cpi->oxcf.error_resilient_mode != 0);
2983     cm->frame_parallel_decoding_mode =
2984       (cpi->oxcf.frame_parallel_decoding_mode != 0);
2985     if (cm->error_resilient_mode) {
2986       cm->frame_parallel_decoding_mode = 1;
2987       cm->reset_frame_context = 0;
2988       cm->refresh_frame_context = 0;
2989     } else if (cm->intra_only) {
2990       // Only reset the current context.
2991       cm->reset_frame_context = 2;
2992     }
2993   }
2994
2995   // Configure experimental use of segmentation for enhanced coding of
2996   // static regions if indicated.
2997   // Only allowed in second pass of two pass (as requires lagged coding)
2998   // and if the relevant speed feature flag is set.
2999   if ((cpi->pass == 2) && (cpi->sf.static_segmentation)) {
3000     configure_static_seg_features(cpi);
3001   }
3002
3003   // Decide how big to make the frame.
3004   vp9_pick_frame_size(cpi);
3005
3006   vp9_clear_system_state();
3007
3008   q = vp9_pick_q_and_adjust_q_bounds(cpi, &bottom_index, &top_index);
3009
3010   vp9_compute_frame_size_bounds(cpi, &frame_under_shoot_limit,
3011                                 &frame_over_shoot_limit);
3012
3013 #if CONFIG_MULTIPLE_ARF
3014   // Force the quantizer determined by the coding order pattern.
3015   if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
3016       cpi->oxcf.end_usage != USAGE_CONSTANT_QUALITY) {
3017     double new_q;
3018     double current_q = vp9_convert_qindex_to_q(cpi->rc.active_worst_quality);
3019     int level = cpi->this_frame_weight;
3020     assert(level >= 0);
3021
3022     // Set quantizer steps at 10% increments.
3023     new_q = current_q * (1.0 - (0.2 * (cpi->max_arf_level - level)));
3024     q = cpi->rc.active_worst_quality +
3025         vp9_compute_qdelta(cpi, current_q, new_q);
3026
3027     bottom_index = q;
3028     top_index    = q;
3029
3030     printf("frame:%d q:%d\n", cm->current_video_frame, q);
3031   }
3032 #endif
3033
3034   vp9_zero(cpi->rd_tx_select_threshes);
3035
3036   if (!frame_is_intra_only(cm)) {
3037     cm->mcomp_filter_type = DEFAULT_INTERP_FILTER;
3038     /* TODO: Decide this more intelligently */
3039     cm->allow_high_precision_mv = q < HIGH_PRECISION_MV_QTHRESH;
3040     set_mvcost(cpi);
3041   }
3042
3043 #if CONFIG_VP9_POSTPROC
3044   if (cpi->oxcf.noise_sensitivity > 0) {
3045     int l = 0;
3046     switch (cpi->oxcf.noise_sensitivity) {
3047       case 1:
3048         l = 20;
3049         break;
3050       case 2:
3051         l = 40;
3052         break;
3053       case 3:
3054         l = 60;
3055         break;
3056       case 4:
3057       case 5:
3058         l = 100;
3059         break;
3060       case 6:
3061         l = 150;
3062         break;
3063     }
3064     vp9_denoise(cpi->Source, cpi->Source, l);
3065   }
3066 #endif
3067
3068 #ifdef OUTPUT_YUV_SRC
3069   vp9_write_yuv_frame(cpi->Source);
3070 #endif
3071
3072   encode_with_recode_loop(cpi,
3073                           size,
3074                           dest,
3075                           q,
3076                           bottom_index,
3077                           top_index,
3078                           frame_over_shoot_limit,
3079                           frame_under_shoot_limit);
3080
3081   // Special case code to reduce pulsing when key frames are forced at a
3082   // fixed interval. Note the reconstruction error if it is the frame before
3083   // the force key frame
3084   if (cpi->next_key_frame_forced && (cpi->twopass.frames_to_key == 0)) {
3085     cpi->ambient_err = vp9_calc_ss_err(cpi->Source, get_frame_new_buffer(cm));
3086   }
3087
3088   if (cm->frame_type == KEY_FRAME)
3089     cpi->refresh_last_frame = 1;
3090
3091   cm->frame_to_show = get_frame_new_buffer(cm);
3092
3093 #if WRITE_RECON_BUFFER
3094   if (cm->show_frame)
3095     write_cx_frame_to_file(cm->frame_to_show,
3096                            cm->current_video_frame);
3097   else
3098     write_cx_frame_to_file(cm->frame_to_show,
3099                            cm->current_video_frame + 1000);
3100 #endif
3101
3102   // Pick the loop filter level for the frame.
3103   loopfilter_frame(cpi, cm);
3104
3105 #if WRITE_RECON_BUFFER
3106   if (cm->show_frame)
3107     write_cx_frame_to_file(cm->frame_to_show,
3108                            cm->current_video_frame + 2000);
3109   else
3110     write_cx_frame_to_file(cm->frame_to_show,
3111                            cm->current_video_frame + 3000);
3112 #endif
3113
3114   // build the bitstream
3115   cpi->dummy_packing = 0;
3116   vp9_pack_bitstream(cpi, dest, size);
3117
3118   if (cm->seg.update_map)
3119     update_reference_segmentation_map(cpi);
3120
3121   release_scaled_references(cpi);
3122   update_reference_frames(cpi);
3123
3124   for (t = TX_4X4; t <= TX_32X32; t++)
3125     full_to_model_counts(cpi->common.counts.coef[t],
3126                          cpi->coef_counts[t]);
3127   if (!cpi->common.error_resilient_mode &&
3128       !cpi->common.frame_parallel_decoding_mode) {
3129     vp9_adapt_coef_probs(&cpi->common);
3130   }
3131
3132   if (!frame_is_intra_only(&cpi->common)) {
3133     FRAME_COUNTS *counts = &cpi->common.counts;
3134
3135     vp9_copy(counts->y_mode, cpi->y_mode_count);
3136     vp9_copy(counts->uv_mode, cpi->y_uv_mode_count);
3137     vp9_copy(counts->intra_inter, cpi->intra_inter_count);
3138     vp9_copy(counts->comp_inter, cpi->comp_inter_count);
3139     vp9_copy(counts->single_ref, cpi->single_ref_count);
3140     vp9_copy(counts->comp_ref, cpi->comp_ref_count);
3141     counts->mv = cpi->NMVcount;
3142     if (!cpi->common.error_resilient_mode &&
3143         !cpi->common.frame_parallel_decoding_mode) {
3144       vp9_adapt_mode_probs(&cpi->common);
3145       vp9_adapt_mv_probs(&cpi->common, cpi->common.allow_high_precision_mv);
3146     }
3147   }
3148
3149 #ifdef ENTROPY_STATS
3150   vp9_update_mode_context_stats(cpi);
3151 #endif
3152
3153   /* Move storing frame_type out of the above loop since it is also
3154    * needed in motion search besides loopfilter */
3155   cm->last_frame_type = cm->frame_type;
3156
3157   // Update rate control heuristics
3158   cpi->rc.projected_frame_size = (*size) << 3;
3159
3160   // Post encode loop adjustment of Q prediction.
3161   vp9_update_rate_correction_factors(
3162       cpi, (cpi->sf.recode_loop ||
3163             cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) ? 2 : 0);
3164
3165
3166   cpi->rc.last_q[cm->frame_type] = cm->base_qindex;
3167
3168   // Keep record of last boosted (KF/KF/ARF) Q value.
3169   // If the current frame is coded at a lower Q then we also update it.
3170   // If all mbs in this group are skipped only update if the Q value is
3171   // better than that already stored.
3172   // This is used to help set quality in forced key frames to reduce popping
3173   if ((cm->base_qindex < cpi->rc.last_boosted_qindex) ||
3174       ((cpi->static_mb_pct < 100) &&
3175        ((cm->frame_type == KEY_FRAME) ||
3176         cpi->refresh_alt_ref_frame ||
3177         (cpi->refresh_golden_frame && !cpi->is_src_frame_alt_ref)))) {
3178     cpi->rc.last_boosted_qindex = cm->base_qindex;
3179   }
3180
3181   if (cm->frame_type == KEY_FRAME) {
3182     vp9_adjust_key_frame_context(cpi);
3183   }
3184
3185   // Keep a record of ambient average Q.
3186   if (cm->frame_type != KEY_FRAME)
3187     cpi->rc.avg_frame_qindex = (2 + 3 * cpi->rc.avg_frame_qindex +
3188                             cm->base_qindex) >> 2;
3189
3190   // Keep a record from which we can calculate the average Q excluding GF
3191   // updates and key frames.
3192   if (cm->frame_type != KEY_FRAME &&
3193       !cpi->refresh_golden_frame &&
3194       !cpi->refresh_alt_ref_frame) {
3195     cpi->rc.ni_frames++;
3196     cpi->rc.tot_q += vp9_convert_qindex_to_q(q);
3197     cpi->rc.avg_q = cpi->rc.tot_q / (double)cpi->rc.ni_frames;
3198
3199     // Calculate the average Q for normal inter frames (not key or GFU frames).
3200     cpi->rc.ni_tot_qi += q;
3201     cpi->rc.ni_av_qi = cpi->rc.ni_tot_qi / cpi->rc.ni_frames;
3202   }
3203
3204   // Update the buffer level variable.
3205   // Non-viewable frames are a special case and are treated as pure overhead.
3206   if (!cm->show_frame)
3207     cpi->rc.bits_off_target -= cpi->rc.projected_frame_size;
3208   else
3209     cpi->rc.bits_off_target += cpi->rc.av_per_frame_bandwidth -
3210                                cpi->rc.projected_frame_size;
3211
3212   // Clip the buffer level at the maximum buffer size
3213   if (cpi->rc.bits_off_target > cpi->oxcf.maximum_buffer_size)
3214     cpi->rc.bits_off_target = cpi->oxcf.maximum_buffer_size;
3215
3216   // Rolling monitors of whether we are over or underspending used to help
3217   // regulate min and Max Q in two pass.
3218   if (cm->frame_type != KEY_FRAME) {
3219     cpi->rc.rolling_target_bits =
3220         ((cpi->rc.rolling_target_bits * 3) +
3221          cpi->rc.this_frame_target + 2) / 4;
3222     cpi->rc.rolling_actual_bits =
3223         ((cpi->rc.rolling_actual_bits * 3) +
3224          cpi->rc.projected_frame_size + 2) / 4;
3225     cpi->rc.long_rolling_target_bits =
3226         ((cpi->rc.long_rolling_target_bits * 31) +
3227          cpi->rc.this_frame_target + 16) / 32;
3228     cpi->rc.long_rolling_actual_bits =
3229         ((cpi->rc.long_rolling_actual_bits * 31) +
3230          cpi->rc.projected_frame_size + 16) / 32;
3231   }
3232
3233   // Actual bits spent
3234   cpi->rc.total_actual_bits += cpi->rc.projected_frame_size;
3235
3236   // Debug stats
3237   cpi->rc.total_target_vs_actual += (cpi->rc.this_frame_target -
3238                                      cpi->rc.projected_frame_size);
3239
3240   cpi->rc.buffer_level = cpi->rc.bits_off_target;
3241
3242 #ifndef DISABLE_RC_LONG_TERM_MEM
3243   // Update bits left to the kf and gf groups to account for overshoot or
3244   // undershoot on these frames
3245   if (cm->frame_type == KEY_FRAME) {
3246     cpi->twopass.kf_group_bits += cpi->rc.this_frame_target -
3247                                   cpi->rc.projected_frame_size;
3248
3249     cpi->twopass.kf_group_bits = MAX(cpi->twopass.kf_group_bits, 0);
3250   } else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) {
3251     cpi->twopass.gf_group_bits += cpi->rc.this_frame_target -
3252                                   cpi->rc.projected_frame_size;
3253
3254     cpi->twopass.gf_group_bits = MAX(cpi->twopass.gf_group_bits, 0);
3255   }
3256 #endif
3257
3258 #if 0
3259   output_frame_level_debug_stats(cpi);
3260 #endif
3261   if (cpi->refresh_golden_frame == 1)
3262     cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
3263   else
3264     cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_GOLDEN;
3265
3266   if (cpi->refresh_alt_ref_frame == 1)
3267     cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
3268   else
3269     cm->frame_flags = cm->frame_flags&~FRAMEFLAGS_ALTREF;
3270
3271
3272   if (cpi->refresh_last_frame & cpi->refresh_golden_frame)
3273     cpi->gold_is_last = 1;
3274   else if (cpi->refresh_last_frame ^ cpi->refresh_golden_frame)
3275     cpi->gold_is_last = 0;
3276
3277   if (cpi->refresh_last_frame & cpi->refresh_alt_ref_frame)
3278     cpi->alt_is_last = 1;
3279   else if (cpi->refresh_last_frame ^ cpi->refresh_alt_ref_frame)
3280     cpi->alt_is_last = 0;
3281
3282   if (cpi->refresh_alt_ref_frame & cpi->refresh_golden_frame)
3283     cpi->gold_is_alt = 1;
3284   else if (cpi->refresh_alt_ref_frame ^ cpi->refresh_golden_frame)
3285     cpi->gold_is_alt = 0;
3286
3287   cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
3288
3289   if (cpi->gold_is_last)
3290     cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
3291
3292   if (cpi->alt_is_last)
3293     cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
3294
3295   if (cpi->gold_is_alt)
3296     cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
3297
3298   if (cpi->oxcf.play_alternate && cpi->refresh_alt_ref_frame
3299       && (cm->frame_type != KEY_FRAME))
3300     // Update the alternate reference frame stats as appropriate.
3301     update_alt_ref_frame_stats(cpi);
3302   else
3303     // Update the Golden frame stats as appropriate.
3304     update_golden_frame_stats(cpi);
3305
3306   if (cm->frame_type == KEY_FRAME) {
3307     // Tell the caller that the frame was coded as a key frame
3308     *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
3309
3310 #if CONFIG_MULTIPLE_ARF
3311     // Reset the sequence number.
3312     if (cpi->multi_arf_enabled) {
3313       cpi->sequence_number = 0;
3314       cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
3315       cpi->new_frame_coding_order_period = -1;
3316     }
3317 #endif
3318
3319     // As this frame is a key frame the next defaults to an inter frame.
3320     cm->frame_type = INTER_FRAME;
3321   } else {
3322     *frame_flags = cm->frame_flags&~FRAMEFLAGS_KEY;
3323
3324 #if CONFIG_MULTIPLE_ARF
3325     /* Increment position in the coded frame sequence. */
3326     if (cpi->multi_arf_enabled) {
3327       ++cpi->sequence_number;
3328       if (cpi->sequence_number >= cpi->frame_coding_order_period) {
3329         cpi->sequence_number = 0;
3330         cpi->frame_coding_order_period = cpi->new_frame_coding_order_period;
3331         cpi->new_frame_coding_order_period = -1;
3332       }
3333       cpi->this_frame_weight = cpi->arf_weight[cpi->sequence_number];
3334       assert(cpi->this_frame_weight >= 0);
3335     }
3336 #endif
3337   }
3338
3339   // Clear the one shot update flags for segmentation map and mode/ref loop
3340   // filter deltas.
3341   cm->seg.update_map = 0;
3342   cm->seg.update_data = 0;
3343   cm->lf.mode_ref_delta_update = 0;
3344
3345   // keep track of the last coded dimensions
3346   cm->last_width = cm->width;
3347   cm->last_height = cm->height;
3348
3349   // reset to normal state now that we are done.
3350   cm->last_show_frame = cm->show_frame;
3351   if (cm->show_frame) {
3352     // current mip will be the prev_mip for the next frame
3353     MODE_INFO *temp = cm->prev_mip;
3354     MODE_INFO **temp2 = cm->prev_mi_grid_base;
3355     cm->prev_mip = cm->mip;
3356     cm->mip = temp;
3357     cm->prev_mi_grid_base = cm->mi_grid_base;
3358     cm->mi_grid_base = temp2;
3359
3360     // update the upper left visible macroblock ptrs
3361     cm->mi = cm->mip + cm->mode_info_stride + 1;
3362     cm->mi_grid_visible = cm->mi_grid_base + cm->mode_info_stride + 1;
3363
3364     cpi->mb.e_mbd.mi_8x8 = cm->mi_grid_visible;
3365     cpi->mb.e_mbd.mi_8x8[0] = cm->mi;
3366
3367     // Don't increment frame counters if this was an altref buffer
3368     // update not a real frame
3369     ++cm->current_video_frame;
3370     ++cpi->frames_since_key;
3371   }
3372   // restore prev_mi
3373   cm->prev_mi = cm->prev_mip + cm->mode_info_stride + 1;
3374   cm->prev_mi_grid_visible = cm->prev_mi_grid_base + cm->mode_info_stride + 1;
3375 }
3376
3377 static void Pass2Encode(VP9_COMP *cpi, unsigned long *size,
3378                         unsigned char *dest, unsigned int *frame_flags) {
3379   cpi->enable_encode_breakout = 1;
3380
3381   if (!cpi->refresh_alt_ref_frame)
3382     vp9_second_pass(cpi);
3383
3384   encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3385   // vp9_print_modes_and_motion_vectors(&cpi->common, "encode.stt");
3386 #ifdef DISABLE_RC_LONG_TERM_MEM
3387   cpi->twopass.bits_left -=  cpi->rc.this_frame_target;
3388 #else
3389   cpi->twopass.bits_left -= 8 * *size;
3390 #endif
3391
3392   if (!cpi->refresh_alt_ref_frame) {
3393     double lower_bounds_min_rate = FRAME_OVERHEAD_BITS * cpi->oxcf.framerate;
3394     double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth
3395                                         * cpi->oxcf.two_pass_vbrmin_section
3396                                         / 100);
3397
3398     if (two_pass_min_rate < lower_bounds_min_rate)
3399       two_pass_min_rate = lower_bounds_min_rate;
3400
3401     cpi->twopass.bits_left += (int64_t)(two_pass_min_rate
3402                               / cpi->oxcf.framerate);
3403   }
3404 }
3405
3406 static void check_initial_width(VP9_COMP *cpi, YV12_BUFFER_CONFIG *sd) {
3407   VP9_COMMON            *cm = &cpi->common;
3408   if (!cpi->initial_width) {
3409     // TODO(jkoleszar): Support 1/4 subsampling?
3410     cm->subsampling_x = (sd != NULL) && sd->uv_width < sd->y_width;
3411     cm->subsampling_y = (sd != NULL) && sd->uv_height < sd->y_height;
3412     alloc_raw_frame_buffers(cpi);
3413
3414     cpi->initial_width = cm->width;
3415     cpi->initial_height = cm->height;
3416   }
3417 }
3418
3419
3420 int vp9_receive_raw_frame(VP9_PTR ptr, unsigned int frame_flags,
3421                           YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
3422                           int64_t end_time) {
3423   VP9_COMP              *cpi = (VP9_COMP *) ptr;
3424   struct vpx_usec_timer  timer;
3425   int                    res = 0;
3426
3427   check_initial_width(cpi, sd);
3428   vpx_usec_timer_start(&timer);
3429   if (vp9_lookahead_push(cpi->lookahead, sd, time_stamp, end_time, frame_flags,
3430                          cpi->active_map_enabled ? cpi->active_map : NULL))
3431     res = -1;
3432   vpx_usec_timer_mark(&timer);
3433   cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
3434
3435   return res;
3436 }
3437
3438
3439 static int frame_is_reference(const VP9_COMP *cpi) {
3440   const VP9_COMMON *cm = &cpi->common;
3441
3442   return cm->frame_type == KEY_FRAME ||
3443          cpi->refresh_last_frame ||
3444          cpi->refresh_golden_frame ||
3445          cpi->refresh_alt_ref_frame ||
3446          cm->refresh_frame_context ||
3447          cm->lf.mode_ref_delta_update ||
3448          cm->seg.update_map ||
3449          cm->seg.update_data;
3450 }
3451
3452 #if CONFIG_MULTIPLE_ARF
3453 int is_next_frame_arf(VP9_COMP *cpi) {
3454   // Negative entry in frame_coding_order indicates an ARF at this position.
3455   return cpi->frame_coding_order[cpi->sequence_number + 1] < 0 ? 1 : 0;
3456 }
3457 #endif
3458
3459 int vp9_get_compressed_data(VP9_PTR ptr, unsigned int *frame_flags,
3460                             unsigned long *size, unsigned char *dest,
3461                             int64_t *time_stamp, int64_t *time_end, int flush) {
3462   VP9_COMP *cpi = (VP9_COMP *) ptr;
3463   VP9_COMMON *cm = &cpi->common;
3464   struct vpx_usec_timer  cmptimer;
3465   YV12_BUFFER_CONFIG    *force_src_buffer = NULL;
3466   int i;
3467   // FILE *fp_out = fopen("enc_frame_type.txt", "a");
3468
3469   if (!cpi)
3470     return -1;
3471
3472   vpx_usec_timer_start(&cmptimer);
3473
3474   cpi->source = NULL;
3475
3476   cpi->common.allow_high_precision_mv = ALTREF_HIGH_PRECISION_MV;
3477   set_mvcost(cpi);
3478
3479   // Should we code an alternate reference frame.
3480   if (cpi->oxcf.play_alternate && cpi->source_alt_ref_pending) {
3481     int frames_to_arf;
3482
3483 #if CONFIG_MULTIPLE_ARF
3484     assert(!cpi->multi_arf_enabled ||
3485            cpi->frame_coding_order[cpi->sequence_number] < 0);
3486
3487     if (cpi->multi_arf_enabled && (cpi->pass == 2))
3488       frames_to_arf = (-cpi->frame_coding_order[cpi->sequence_number])
3489         - cpi->next_frame_in_order;
3490     else
3491 #endif
3492       frames_to_arf = cpi->rc.frames_till_gf_update_due;
3493
3494     assert(frames_to_arf < cpi->twopass.frames_to_key);
3495
3496     if ((cpi->source = vp9_lookahead_peek(cpi->lookahead, frames_to_arf))) {
3497 #if CONFIG_MULTIPLE_ARF
3498       cpi->alt_ref_source[cpi->arf_buffered] = cpi->source;
3499 #else
3500       cpi->alt_ref_source = cpi->source;
3501 #endif
3502
3503       if (cpi->oxcf.arnr_max_frames > 0) {
3504         // Produce the filtered ARF frame.
3505         // TODO(agrange) merge these two functions.
3506         configure_arnr_filter(cpi, cm->current_video_frame + frames_to_arf,
3507                               cpi->rc.gfu_boost);
3508         vp9_temporal_filter_prepare(cpi, frames_to_arf);
3509         vp9_extend_frame_borders(&cpi->alt_ref_buffer,
3510                                  cm->subsampling_x, cm->subsampling_y);
3511         force_src_buffer = &cpi->alt_ref_buffer;
3512       }
3513
3514       cm->show_frame = 0;
3515       cpi->refresh_alt_ref_frame = 1;
3516       cpi->refresh_golden_frame = 0;
3517       cpi->refresh_last_frame = 0;
3518       cpi->is_src_frame_alt_ref = 0;
3519
3520       // TODO(agrange) This needs to vary depending on where the next ARF is.
3521       cpi->frames_till_alt_ref_frame = frames_to_arf;
3522
3523 #if CONFIG_MULTIPLE_ARF
3524       if (!cpi->multi_arf_enabled)
3525 #endif
3526         cpi->source_alt_ref_pending = 0;   // Clear Pending altf Ref flag.
3527     }
3528   }
3529
3530   if (!cpi->source) {
3531 #if CONFIG_MULTIPLE_ARF
3532     int i;
3533 #endif
3534     if ((cpi->source = vp9_lookahead_pop(cpi->lookahead, flush))) {
3535       cm->show_frame = 1;
3536       cm->intra_only = 0;
3537
3538 #if CONFIG_MULTIPLE_ARF
3539       // Is this frame the ARF overlay.
3540       cpi->is_src_frame_alt_ref = 0;
3541       for (i = 0; i < cpi->arf_buffered; ++i) {
3542         if (cpi->source == cpi->alt_ref_source[i]) {
3543           cpi->is_src_frame_alt_ref = 1;
3544           cpi->refresh_golden_frame = 1;
3545           break;
3546         }
3547       }
3548 #else
3549       cpi->is_src_frame_alt_ref = cpi->alt_ref_source
3550                                   && (cpi->source == cpi->alt_ref_source);
3551 #endif
3552       if (cpi->is_src_frame_alt_ref) {
3553         // Current frame is an ARF overlay frame.
3554 #if CONFIG_MULTIPLE_ARF
3555         cpi->alt_ref_source[i] = NULL;
3556 #else
3557         cpi->alt_ref_source = NULL;
3558 #endif
3559         // Don't refresh the last buffer for an ARF overlay frame. It will
3560         // become the GF so preserve last as an alternative prediction option.
3561         cpi->refresh_last_frame = 0;
3562       }
3563 #if CONFIG_MULTIPLE_ARF
3564       ++cpi->next_frame_in_order;
3565 #endif
3566     }
3567   }
3568
3569   if (cpi->source) {
3570     cpi->un_scaled_source = cpi->Source = force_src_buffer ? force_src_buffer
3571                                                            : &cpi->source->img;
3572     *time_stamp = cpi->source->ts_start;
3573     *time_end = cpi->source->ts_end;
3574     *frame_flags = cpi->source->flags;
3575
3576     // fprintf(fp_out, "   Frame:%d", cm->current_video_frame);
3577 #if CONFIG_MULTIPLE_ARF
3578     if (cpi->multi_arf_enabled) {
3579       // fprintf(fp_out, "   seq_no:%d  this_frame_weight:%d",
3580       //         cpi->sequence_number, cpi->this_frame_weight);
3581     } else {
3582       // fprintf(fp_out, "\n");
3583     }
3584 #else
3585     // fprintf(fp_out, "\n");
3586 #endif
3587
3588 #if CONFIG_MULTIPLE_ARF
3589     if ((cm->frame_type != KEY_FRAME) && (cpi->pass == 2))
3590       cpi->source_alt_ref_pending = is_next_frame_arf(cpi);
3591 #endif
3592   } else {
3593     *size = 0;
3594     if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done) {
3595       vp9_end_first_pass(cpi);    /* get last stats packet */
3596       cpi->twopass.first_pass_done = 1;
3597     }
3598
3599     // fclose(fp_out);
3600     return -1;
3601   }
3602
3603   if (cpi->source->ts_start < cpi->first_time_stamp_ever) {
3604     cpi->first_time_stamp_ever = cpi->source->ts_start;
3605     cpi->last_end_time_stamp_seen = cpi->source->ts_start;
3606   }
3607
3608   // adjust frame rates based on timestamps given
3609   if (!cpi->refresh_alt_ref_frame) {
3610     int64_t this_duration;
3611     int step = 0;
3612
3613     if (cpi->source->ts_start == cpi->first_time_stamp_ever) {
3614       this_duration = cpi->source->ts_end - cpi->source->ts_start;
3615       step = 1;
3616     } else {
3617       int64_t last_duration = cpi->last_end_time_stamp_seen
3618                                 - cpi->last_time_stamp_seen;
3619
3620       this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
3621
3622       // do a step update if the duration changes by 10%
3623       if (last_duration)
3624         step = (int)((this_duration - last_duration) * 10 / last_duration);
3625     }
3626
3627     if (this_duration) {
3628       if (step) {
3629         vp9_new_framerate(cpi, 10000000.0 / this_duration);
3630       } else {
3631         // Average this frame's rate into the last second's average
3632         // frame rate. If we haven't seen 1 second yet, then average
3633         // over the whole interval seen.
3634         const double interval = MIN((double)(cpi->source->ts_end
3635                                      - cpi->first_time_stamp_ever), 10000000.0);
3636         double avg_duration = 10000000.0 / cpi->oxcf.framerate;
3637         avg_duration *= (interval - avg_duration + this_duration);
3638         avg_duration /= interval;
3639
3640         vp9_new_framerate(cpi, 10000000.0 / avg_duration);
3641       }
3642     }
3643
3644     cpi->last_time_stamp_seen = cpi->source->ts_start;
3645     cpi->last_end_time_stamp_seen = cpi->source->ts_end;
3646   }
3647
3648   // start with a 0 size frame
3649   *size = 0;
3650
3651   // Clear down mmx registers
3652   vp9_clear_system_state();  // __asm emms;
3653
3654   /* find a free buffer for the new frame, releasing the reference previously
3655    * held.
3656    */
3657   cm->fb_idx_ref_cnt[cm->new_fb_idx]--;
3658   cm->new_fb_idx = get_free_fb(cm);
3659
3660 #if CONFIG_MULTIPLE_ARF
3661   /* Set up the correct ARF frame. */
3662   if (cpi->refresh_alt_ref_frame) {
3663     ++cpi->arf_buffered;
3664   }
3665   if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
3666       (cpi->pass == 2)) {
3667     cpi->alt_fb_idx = cpi->arf_buffer_idx[cpi->sequence_number];
3668   }
3669 #endif
3670
3671   /* Get the mapping of L/G/A to the reference buffer pool */
3672   cm->active_ref_idx[0] = cm->ref_frame_map[cpi->lst_fb_idx];
3673   cm->active_ref_idx[1] = cm->ref_frame_map[cpi->gld_fb_idx];
3674   cm->active_ref_idx[2] = cm->ref_frame_map[cpi->alt_fb_idx];
3675
3676 #if 0  // CONFIG_MULTIPLE_ARF
3677   if (cpi->multi_arf_enabled) {
3678     fprintf(fp_out, "      idx(%d, %d, %d, %d) active(%d, %d, %d)",
3679         cpi->lst_fb_idx, cpi->gld_fb_idx, cpi->alt_fb_idx, cm->new_fb_idx,
3680         cm->active_ref_idx[0], cm->active_ref_idx[1], cm->active_ref_idx[2]);
3681     if (cpi->refresh_alt_ref_frame)
3682       fprintf(fp_out, "  type:ARF");
3683     if (cpi->is_src_frame_alt_ref)
3684       fprintf(fp_out, "  type:OVERLAY[%d]", cpi->alt_fb_idx);
3685     fprintf(fp_out, "\n");
3686   }
3687 #endif
3688
3689   cm->frame_type = INTER_FRAME;
3690   cm->frame_flags = *frame_flags;
3691
3692   // Reset the frame pointers to the current frame size
3693   vp9_realloc_frame_buffer(get_frame_new_buffer(cm),
3694                            cm->width, cm->height,
3695                            cm->subsampling_x, cm->subsampling_y,
3696                            VP9BORDERINPIXELS);
3697
3698   // Calculate scaling factors for each of the 3 available references
3699   for (i = 0; i < ALLOWED_REFS_PER_FRAME; ++i) {
3700     vp9_setup_scale_factors(cm, i);
3701     if (vp9_is_scaled(&cm->active_ref_scale_comm[i]))
3702       vp9_extend_frame_borders(&cm->yv12_fb[cm->active_ref_idx[i]],
3703                                cm->subsampling_x, cm->subsampling_y);
3704   }
3705
3706   vp9_setup_interp_filters(&cpi->mb.e_mbd, DEFAULT_INTERP_FILTER, cm);
3707
3708   if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
3709       vp9_vaq_init();
3710   }
3711
3712   if (cpi->pass == 1) {
3713     Pass1Encode(cpi, size, dest, frame_flags);
3714   } else if (cpi->pass == 2) {
3715     Pass2Encode(cpi, size, dest, frame_flags);
3716   } else {
3717     encode_frame_to_data_rate(cpi, size, dest, frame_flags);
3718   }
3719
3720   if (cm->refresh_frame_context)
3721     cm->frame_contexts[cm->frame_context_idx] = cm->fc;
3722
3723   if (*size > 0) {
3724     // if its a dropped frame honor the requests on subsequent frames
3725     cpi->droppable = !frame_is_reference(cpi);
3726
3727     // return to normal state
3728     cm->reset_frame_context = 0;
3729     cm->refresh_frame_context = 1;
3730     cpi->refresh_alt_ref_frame = 0;
3731     cpi->refresh_golden_frame = 0;
3732     cpi->refresh_last_frame = 1;
3733     cm->frame_type = INTER_FRAME;
3734   }
3735
3736   vpx_usec_timer_mark(&cmptimer);
3737   cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
3738
3739   if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame)
3740     generate_psnr_packet(cpi);
3741
3742 #if CONFIG_INTERNAL_STATS
3743
3744   if (cpi->pass != 1) {
3745     cpi->bytes += *size;
3746
3747     if (cm->show_frame) {
3748       cpi->count++;
3749
3750       if (cpi->b_calculate_psnr) {
3751         double ye, ue, ve;
3752         double frame_psnr;
3753         YV12_BUFFER_CONFIG      *orig = cpi->Source;
3754         YV12_BUFFER_CONFIG      *recon = cpi->common.frame_to_show;
3755         YV12_BUFFER_CONFIG      *pp = &cm->post_proc_buffer;
3756         int y_samples = orig->y_height * orig->y_width;
3757         int uv_samples = orig->uv_height * orig->uv_width;
3758         int t_samples = y_samples + 2 * uv_samples;
3759         double sq_error;
3760
3761         ye = (double)calc_plane_error(orig->y_buffer, orig->y_stride,
3762                               recon->y_buffer, recon->y_stride,
3763                               orig->y_crop_width, orig->y_crop_height);
3764
3765         ue = (double)calc_plane_error(orig->u_buffer, orig->uv_stride,
3766                               recon->u_buffer, recon->uv_stride,
3767                               orig->uv_crop_width, orig->uv_crop_height);
3768
3769         ve = (double)calc_plane_error(orig->v_buffer, orig->uv_stride,
3770                               recon->v_buffer, recon->uv_stride,
3771                               orig->uv_crop_width, orig->uv_crop_height);
3772
3773         sq_error = ye + ue + ve;
3774
3775         frame_psnr = vp9_mse2psnr(t_samples, 255.0, sq_error);
3776
3777         cpi->total_y += vp9_mse2psnr(y_samples, 255.0, ye);
3778         cpi->total_u += vp9_mse2psnr(uv_samples, 255.0, ue);
3779         cpi->total_v += vp9_mse2psnr(uv_samples, 255.0, ve);
3780         cpi->total_sq_error += sq_error;
3781         cpi->total  += frame_psnr;
3782         {
3783           double frame_psnr2, frame_ssim2 = 0;
3784           double weight = 0;
3785 #if CONFIG_VP9_POSTPROC
3786           vp9_deblock(cm->frame_to_show, &cm->post_proc_buffer,
3787                       cm->lf.filter_level * 10 / 6);
3788 #endif
3789           vp9_clear_system_state();
3790
3791           ye = (double)calc_plane_error(orig->y_buffer, orig->y_stride,
3792                                 pp->y_buffer, pp->y_stride,
3793                                 orig->y_crop_width, orig->y_crop_height);
3794
3795           ue = (double)calc_plane_error(orig->u_buffer, orig->uv_stride,
3796                                 pp->u_buffer, pp->uv_stride,
3797                                 orig->uv_crop_width, orig->uv_crop_height);
3798
3799           ve = (double)calc_plane_error(orig->v_buffer, orig->uv_stride,
3800                                 pp->v_buffer, pp->uv_stride,
3801                                 orig->uv_crop_width, orig->uv_crop_height);
3802
3803           sq_error = ye + ue + ve;
3804
3805           frame_psnr2 = vp9_mse2psnr(t_samples, 255.0, sq_error);
3806
3807           cpi->totalp_y += vp9_mse2psnr(y_samples, 255.0, ye);
3808           cpi->totalp_u += vp9_mse2psnr(uv_samples, 255.0, ue);
3809           cpi->totalp_v += vp9_mse2psnr(uv_samples, 255.0, ve);
3810           cpi->total_sq_error2 += sq_error;
3811           cpi->totalp  += frame_psnr2;
3812
3813           frame_ssim2 = vp9_calc_ssim(cpi->Source,
3814                                       recon, 1, &weight);
3815
3816           cpi->summed_quality += frame_ssim2 * weight;
3817           cpi->summed_weights += weight;
3818
3819           frame_ssim2 = vp9_calc_ssim(cpi->Source,
3820                                       &cm->post_proc_buffer, 1, &weight);
3821
3822           cpi->summedp_quality += frame_ssim2 * weight;
3823           cpi->summedp_weights += weight;
3824 #if 0
3825           {
3826             FILE *f = fopen("q_used.stt", "a");
3827             fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
3828                     cpi->common.current_video_frame, y2, u2, v2,
3829                     frame_psnr2, frame_ssim2);
3830             fclose(f);
3831           }
3832 #endif
3833         }
3834       }
3835
3836       if (cpi->b_calculate_ssimg) {
3837         double y, u, v, frame_all;
3838         frame_all =  vp9_calc_ssimg(cpi->Source, cm->frame_to_show,
3839                                     &y, &u, &v);
3840         cpi->total_ssimg_y += y;
3841         cpi->total_ssimg_u += u;
3842         cpi->total_ssimg_v += v;
3843         cpi->total_ssimg_all += frame_all;
3844       }
3845     }
3846   }
3847
3848 #endif
3849   // fclose(fp_out);
3850   return 0;
3851 }
3852
3853 int vp9_get_preview_raw_frame(VP9_PTR comp, YV12_BUFFER_CONFIG *dest,
3854                               vp9_ppflags_t *flags) {
3855   VP9_COMP *cpi = (VP9_COMP *) comp;
3856
3857   if (!cpi->common.show_frame) {
3858     return -1;
3859   } else {
3860     int ret;
3861 #if CONFIG_VP9_POSTPROC
3862     ret = vp9_post_proc_frame(&cpi->common, dest, flags);
3863 #else
3864
3865     if (cpi->common.frame_to_show) {
3866       *dest = *cpi->common.frame_to_show;
3867       dest->y_width = cpi->common.width;
3868       dest->y_height = cpi->common.height;
3869       dest->uv_height = cpi->common.height / 2;
3870       ret = 0;
3871     } else {
3872       ret = -1;
3873     }
3874
3875 #endif  // !CONFIG_VP9_POSTPROC
3876     vp9_clear_system_state();
3877     return ret;
3878   }
3879 }
3880
3881 int vp9_set_roimap(VP9_PTR comp, unsigned char *map, unsigned int rows,
3882                    unsigned int cols, int delta_q[MAX_SEGMENTS],
3883                    int delta_lf[MAX_SEGMENTS],
3884                    unsigned int threshold[MAX_SEGMENTS]) {
3885   VP9_COMP *cpi = (VP9_COMP *) comp;
3886   signed char feature_data[SEG_LVL_MAX][MAX_SEGMENTS];
3887   struct segmentation *seg = &cpi->common.seg;
3888   int i;
3889
3890   if (cpi->common.mb_rows != rows || cpi->common.mb_cols != cols)
3891     return -1;
3892
3893   if (!map) {
3894     vp9_disable_segmentation((VP9_PTR)cpi);
3895     return 0;
3896   }
3897
3898   // Set the segmentation Map
3899   vp9_set_segmentation_map((VP9_PTR)cpi, map);
3900
3901   // Activate segmentation.
3902   vp9_enable_segmentation((VP9_PTR)cpi);
3903
3904   // Set up the quant, LF and breakout threshold segment data
3905   for (i = 0; i < MAX_SEGMENTS; i++) {
3906     feature_data[SEG_LVL_ALT_Q][i] = delta_q[i];
3907     feature_data[SEG_LVL_ALT_LF][i] = delta_lf[i];
3908     cpi->segment_encode_breakout[i] = threshold[i];
3909   }
3910
3911   // Enable the loop and quant changes in the feature mask
3912   for (i = 0; i < MAX_SEGMENTS; i++) {
3913     if (delta_q[i])
3914       vp9_enable_segfeature(seg, i, SEG_LVL_ALT_Q);
3915     else
3916       vp9_disable_segfeature(seg, i, SEG_LVL_ALT_Q);
3917
3918     if (delta_lf[i])
3919       vp9_enable_segfeature(seg, i, SEG_LVL_ALT_LF);
3920     else
3921       vp9_disable_segfeature(seg, i, SEG_LVL_ALT_LF);
3922   }
3923
3924   // Initialize the feature data structure
3925   // SEGMENT_DELTADATA    0, SEGMENT_ABSDATA      1
3926   vp9_set_segment_data((VP9_PTR)cpi, &feature_data[0][0], SEGMENT_DELTADATA);
3927
3928   return 0;
3929 }
3930
3931 int vp9_set_active_map(VP9_PTR comp, unsigned char *map,
3932                        unsigned int rows, unsigned int cols) {
3933   VP9_COMP *cpi = (VP9_COMP *) comp;
3934
3935   if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
3936     if (map) {
3937       vpx_memcpy(cpi->active_map, map, rows * cols);
3938       cpi->active_map_enabled = 1;
3939     } else {
3940       cpi->active_map_enabled = 0;
3941     }
3942
3943     return 0;
3944   } else {
3945     // cpi->active_map_enabled = 0;
3946     return -1;
3947   }
3948 }
3949
3950 int vp9_set_internal_size(VP9_PTR comp,
3951                           VPX_SCALING horiz_mode, VPX_SCALING vert_mode) {
3952   VP9_COMP *cpi = (VP9_COMP *) comp;
3953   VP9_COMMON *cm = &cpi->common;
3954   int hr = 0, hs = 0, vr = 0, vs = 0;
3955
3956   if (horiz_mode > ONETWO || vert_mode > ONETWO)
3957     return -1;
3958
3959   Scale2Ratio(horiz_mode, &hr, &hs);
3960   Scale2Ratio(vert_mode, &vr, &vs);
3961
3962   // always go to the next whole number
3963   cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
3964   cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
3965
3966   assert(cm->width <= cpi->initial_width);
3967   assert(cm->height <= cpi->initial_height);
3968   update_frame_size(cpi);
3969   return 0;
3970 }
3971
3972 int vp9_set_size_literal(VP9_PTR comp, unsigned int width,
3973                          unsigned int height) {
3974   VP9_COMP *cpi = (VP9_COMP *)comp;
3975   VP9_COMMON *cm = &cpi->common;
3976
3977   check_initial_width(cpi, NULL);
3978
3979   if (width) {
3980     cm->width = width;
3981     if (cm->width * 5 < cpi->initial_width) {
3982       cm->width = cpi->initial_width / 5 + 1;
3983       printf("Warning: Desired width too small, changed to %d \n", cm->width);
3984     }
3985     if (cm->width > cpi->initial_width) {
3986       cm->width = cpi->initial_width;
3987       printf("Warning: Desired width too large, changed to %d \n", cm->width);
3988     }
3989   }
3990
3991   if (height) {
3992     cm->height = height;
3993     if (cm->height * 5 < cpi->initial_height) {
3994       cm->height = cpi->initial_height / 5 + 1;
3995       printf("Warning: Desired height too small, changed to %d \n", cm->height);
3996     }
3997     if (cm->height > cpi->initial_height) {
3998       cm->height = cpi->initial_height;
3999       printf("Warning: Desired height too large, changed to %d \n", cm->height);
4000     }
4001   }
4002
4003   assert(cm->width <= cpi->initial_width);
4004   assert(cm->height <= cpi->initial_height);
4005   update_frame_size(cpi);
4006   return 0;
4007 }
4008
4009 void vp9_set_svc(VP9_PTR comp, int use_svc) {
4010   VP9_COMP *cpi = (VP9_COMP *)comp;
4011   cpi->use_svc = use_svc;
4012   return;
4013 }
4014
4015 int vp9_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest) {
4016   int i, j;
4017   int total = 0;
4018
4019   uint8_t *src = source->y_buffer;
4020   uint8_t *dst = dest->y_buffer;
4021
4022   // Loop through the Y plane raw and reconstruction data summing
4023   // (square differences)
4024   for (i = 0; i < source->y_height; i += 16) {
4025     for (j = 0; j < source->y_width; j += 16) {
4026       unsigned int sse;
4027       total += vp9_mse16x16(src + j, source->y_stride, dst + j, dest->y_stride,
4028                             &sse);
4029     }
4030
4031     src += 16 * source->y_stride;
4032     dst += 16 * dest->y_stride;
4033   }
4034
4035   return total;
4036 }
4037
4038
4039 int vp9_get_quantizer(VP9_PTR c) {
4040   return ((VP9_COMP *)c)->common.base_qindex;
4041 }