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