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