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