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