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 #include "vpx/internal/vpx_psnr.h"
18 #include "vpx_ports/vpx_timer.h"
19
20 #include "vp9/common/vp9_alloccommon.h"
21 #include "vp9/common/vp9_filter.h"
22 #include "vp9/common/vp9_idct.h"
23 #if CONFIG_VP9_POSTPROC
24 #include "vp9/common/vp9_postproc.h"
25 #endif
26 #include "vp9/common/vp9_reconinter.h"
27 #include "vp9/common/vp9_systemdependent.h"
28 #include "vp9/common/vp9_tile_common.h"
29
30 #include "vp9/encoder/vp9_aq_complexity.h"
31 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
32 #include "vp9/encoder/vp9_aq_variance.h"
33 #include "vp9/encoder/vp9_bitstream.h"
34 #include "vp9/encoder/vp9_context_tree.h"
35 #include "vp9/encoder/vp9_encodeframe.h"
36 #include "vp9/encoder/vp9_encodemv.h"
37 #include "vp9/encoder/vp9_firstpass.h"
38 #include "vp9/encoder/vp9_mbgraph.h"
39 #include "vp9/encoder/vp9_encoder.h"
40 #include "vp9/encoder/vp9_picklpf.h"
41 #include "vp9/encoder/vp9_ratectrl.h"
42 #include "vp9/encoder/vp9_rd.h"
43 #include "vp9/encoder/vp9_segmentation.h"
44 #include "vp9/encoder/vp9_speed_features.h"
45 #if CONFIG_INTERNAL_STATS
46 #include "vp9/encoder/vp9_ssim.h"
47 #endif
48 #include "vp9/encoder/vp9_temporal_filter.h"
49 #include "vp9/encoder/vp9_resize.h"
50 #include "vp9/encoder/vp9_svc_layercontext.h"
51
52 void vp9_coef_tree_initialize();
53
54 #define SHARP_FILTER_QTHRESH 0 /* Q threshold for 8-tap sharp filter */
55
56 #define ALTREF_HIGH_PRECISION_MV 1 // Whether to use high precision mv
57 // for altref computation.
58 #define HIGH_PRECISION_MV_QTHRESH 200 // Q threshold for high precision
59 // mv. Choose a very high value for
60 // now so that HIGH_PRECISION is always
61 // chosen.
62
63 // #define OUTPUT_YUV_REC
64
65 #ifdef OUTPUT_YUV_DENOISED
66 FILE *yuv_denoised_file = NULL;
67 #endif
68 #ifdef OUTPUT_YUV_REC
69 FILE *yuv_rec_file;
70 #endif
71
72 #if 0
73 FILE *framepsnr;
74 FILE *kf_list;
75 FILE *keyfile;
76 #endif
77
Scale2Ratio(VPX_SCALING mode,int * hr,int * hs)78 static INLINE void Scale2Ratio(VPX_SCALING mode, int *hr, int *hs) {
79 switch (mode) {
80 case NORMAL:
81 *hr = 1;
82 *hs = 1;
83 break;
84 case FOURFIVE:
85 *hr = 4;
86 *hs = 5;
87 break;
88 case THREEFIVE:
89 *hr = 3;
90 *hs = 5;
91 break;
92 case ONETWO:
93 *hr = 1;
94 *hs = 2;
95 break;
96 default:
97 *hr = 1;
98 *hs = 1;
99 assert(0);
100 break;
101 }
102 }
103
vp9_set_high_precision_mv(VP9_COMP * cpi,int allow_high_precision_mv)104 void vp9_set_high_precision_mv(VP9_COMP *cpi, int allow_high_precision_mv) {
105 MACROBLOCK *const mb = &cpi->mb;
106 cpi->common.allow_high_precision_mv = allow_high_precision_mv;
107 if (cpi->common.allow_high_precision_mv) {
108 mb->mvcost = mb->nmvcost_hp;
109 mb->mvsadcost = mb->nmvsadcost_hp;
110 } else {
111 mb->mvcost = mb->nmvcost;
112 mb->mvsadcost = mb->nmvsadcost;
113 }
114 }
115
setup_frame(VP9_COMP * cpi)116 static void setup_frame(VP9_COMP *cpi) {
117 VP9_COMMON *const cm = &cpi->common;
118 // Set up entropy context depending on frame type. The decoder mandates
119 // the use of the default context, index 0, for keyframes and inter
120 // frames where the error_resilient_mode or intra_only flag is set. For
121 // other inter-frames the encoder currently uses only two contexts;
122 // context 1 for ALTREF frames and context 0 for the others.
123 if (frame_is_intra_only(cm) || cm->error_resilient_mode) {
124 vp9_setup_past_independence(cm);
125 } else {
126 if (!cpi->use_svc)
127 cm->frame_context_idx = cpi->refresh_alt_ref_frame;
128 }
129
130 if (cm->frame_type == KEY_FRAME) {
131 if (!is_spatial_svc(cpi))
132 cpi->refresh_golden_frame = 1;
133 cpi->refresh_alt_ref_frame = 1;
134 } else {
135 cm->fc = cm->frame_contexts[cm->frame_context_idx];
136 }
137 }
138
vp9_initialize_enc()139 void vp9_initialize_enc() {
140 static int init_done = 0;
141
142 if (!init_done) {
143 vp9_init_neighbors();
144 vp9_coef_tree_initialize();
145 vp9_tokenize_initialize();
146 vp9_init_me_luts();
147 vp9_rc_init_minq_luts();
148 vp9_entropy_mv_init();
149 vp9_entropy_mode_init();
150 vp9_temporal_filter_init();
151 init_done = 1;
152 }
153 }
154
dealloc_compressor_data(VP9_COMP * cpi)155 static void dealloc_compressor_data(VP9_COMP *cpi) {
156 VP9_COMMON *const cm = &cpi->common;
157 int i;
158
159 // Delete sementation map
160 vpx_free(cpi->segmentation_map);
161 cpi->segmentation_map = NULL;
162 vpx_free(cm->last_frame_seg_map);
163 cm->last_frame_seg_map = NULL;
164 vpx_free(cpi->coding_context.last_frame_seg_map_copy);
165 cpi->coding_context.last_frame_seg_map_copy = NULL;
166
167 vpx_free(cpi->complexity_map);
168 cpi->complexity_map = NULL;
169
170 vp9_cyclic_refresh_free(cpi->cyclic_refresh);
171 cpi->cyclic_refresh = NULL;
172
173 vp9_free_ref_frame_buffers(cm);
174 vp9_free_context_buffers(cm);
175
176 vp9_free_frame_buffer(&cpi->last_frame_uf);
177 vp9_free_frame_buffer(&cpi->scaled_source);
178 vp9_free_frame_buffer(&cpi->scaled_last_source);
179 vp9_free_frame_buffer(&cpi->alt_ref_buffer);
180 vp9_lookahead_destroy(cpi->lookahead);
181
182 vpx_free(cpi->tok);
183 cpi->tok = 0;
184
185 vp9_free_pc_tree(cpi);
186
187 for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
188 LAYER_CONTEXT *const lc = &cpi->svc.layer_context[i];
189 vpx_free(lc->rc_twopass_stats_in.buf);
190 lc->rc_twopass_stats_in.buf = NULL;
191 lc->rc_twopass_stats_in.sz = 0;
192 }
193
194 if (cpi->source_diff_var != NULL) {
195 vpx_free(cpi->source_diff_var);
196 cpi->source_diff_var = NULL;
197 }
198
199 for (i = 0; i < MAX_LAG_BUFFERS; ++i) {
200 vp9_free_frame_buffer(&cpi->svc.scaled_frames[i]);
201 }
202 vpx_memset(&cpi->svc.scaled_frames[0], 0,
203 MAX_LAG_BUFFERS * sizeof(cpi->svc.scaled_frames[0]));
204 }
205
save_coding_context(VP9_COMP * cpi)206 static void save_coding_context(VP9_COMP *cpi) {
207 CODING_CONTEXT *const cc = &cpi->coding_context;
208 VP9_COMMON *cm = &cpi->common;
209
210 // Stores a snapshot of key state variables which can subsequently be
211 // restored with a call to vp9_restore_coding_context. These functions are
212 // intended for use in a re-code loop in vp9_compress_frame where the
213 // quantizer value is adjusted between loop iterations.
214 vp9_copy(cc->nmvjointcost, cpi->mb.nmvjointcost);
215 vp9_copy(cc->nmvcosts, cpi->mb.nmvcosts);
216 vp9_copy(cc->nmvcosts_hp, cpi->mb.nmvcosts_hp);
217
218 vp9_copy(cc->segment_pred_probs, cm->seg.pred_probs);
219
220 vpx_memcpy(cpi->coding_context.last_frame_seg_map_copy,
221 cm->last_frame_seg_map, (cm->mi_rows * cm->mi_cols));
222
223 vp9_copy(cc->last_ref_lf_deltas, cm->lf.last_ref_deltas);
224 vp9_copy(cc->last_mode_lf_deltas, cm->lf.last_mode_deltas);
225
226 cc->fc = cm->fc;
227 }
228
restore_coding_context(VP9_COMP * cpi)229 static void restore_coding_context(VP9_COMP *cpi) {
230 CODING_CONTEXT *const cc = &cpi->coding_context;
231 VP9_COMMON *cm = &cpi->common;
232
233 // Restore key state variables to the snapshot state stored in the
234 // previous call to vp9_save_coding_context.
235 vp9_copy(cpi->mb.nmvjointcost, cc->nmvjointcost);
236 vp9_copy(cpi->mb.nmvcosts, cc->nmvcosts);
237 vp9_copy(cpi->mb.nmvcosts_hp, cc->nmvcosts_hp);
238
239 vp9_copy(cm->seg.pred_probs, cc->segment_pred_probs);
240
241 vpx_memcpy(cm->last_frame_seg_map,
242 cpi->coding_context.last_frame_seg_map_copy,
243 (cm->mi_rows * cm->mi_cols));
244
245 vp9_copy(cm->lf.last_ref_deltas, cc->last_ref_lf_deltas);
246 vp9_copy(cm->lf.last_mode_deltas, cc->last_mode_lf_deltas);
247
248 cm->fc = cc->fc;
249 }
250
configure_static_seg_features(VP9_COMP * cpi)251 static void configure_static_seg_features(VP9_COMP *cpi) {
252 VP9_COMMON *const cm = &cpi->common;
253 const RATE_CONTROL *const rc = &cpi->rc;
254 struct segmentation *const seg = &cm->seg;
255
256 int high_q = (int)(rc->avg_q > 48.0);
257 int qi_delta;
258
259 // Disable and clear down for KF
260 if (cm->frame_type == KEY_FRAME) {
261 // Clear down the global segmentation map
262 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
263 seg->update_map = 0;
264 seg->update_data = 0;
265 cpi->static_mb_pct = 0;
266
267 // Disable segmentation
268 vp9_disable_segmentation(seg);
269
270 // Clear down the segment features.
271 vp9_clearall_segfeatures(seg);
272 } else if (cpi->refresh_alt_ref_frame) {
273 // If this is an alt ref frame
274 // Clear down the global segmentation map
275 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
276 seg->update_map = 0;
277 seg->update_data = 0;
278 cpi->static_mb_pct = 0;
279
280 // Disable segmentation and individual segment features by default
281 vp9_disable_segmentation(seg);
282 vp9_clearall_segfeatures(seg);
283
284 // Scan frames from current to arf frame.
285 // This function re-enables segmentation if appropriate.
286 vp9_update_mbgraph_stats(cpi);
287
288 // If segmentation was enabled set those features needed for the
289 // arf itself.
290 if (seg->enabled) {
291 seg->update_map = 1;
292 seg->update_data = 1;
293
294 qi_delta = vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 0.875);
295 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta - 2);
296 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
297
298 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
299 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
300
301 // Where relevant assume segment data is delta data
302 seg->abs_delta = SEGMENT_DELTADATA;
303 }
304 } else if (seg->enabled) {
305 // All other frames if segmentation has been enabled
306
307 // First normal frame in a valid gf or alt ref group
308 if (rc->frames_since_golden == 0) {
309 // Set up segment features for normal frames in an arf group
310 if (rc->source_alt_ref_active) {
311 seg->update_map = 0;
312 seg->update_data = 1;
313 seg->abs_delta = SEGMENT_DELTADATA;
314
315 qi_delta = vp9_compute_qdelta(rc, rc->avg_q, rc->avg_q * 1.125);
316 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qi_delta + 2);
317 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
318
319 vp9_set_segdata(seg, 1, SEG_LVL_ALT_LF, -2);
320 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_LF);
321
322 // Segment coding disabled for compred testing
323 if (high_q || (cpi->static_mb_pct == 100)) {
324 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
325 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
326 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
327 }
328 } else {
329 // Disable segmentation and clear down features if alt ref
330 // is not active for this group
331
332 vp9_disable_segmentation(seg);
333
334 vpx_memset(cpi->segmentation_map, 0, cm->mi_rows * cm->mi_cols);
335
336 seg->update_map = 0;
337 seg->update_data = 0;
338
339 vp9_clearall_segfeatures(seg);
340 }
341 } else if (rc->is_src_frame_alt_ref) {
342 // Special case where we are coding over the top of a previous
343 // alt ref frame.
344 // Segment coding disabled for compred testing
345
346 // Enable ref frame features for segment 0 as well
347 vp9_enable_segfeature(seg, 0, SEG_LVL_REF_FRAME);
348 vp9_enable_segfeature(seg, 1, SEG_LVL_REF_FRAME);
349
350 // All mbs should use ALTREF_FRAME
351 vp9_clear_segdata(seg, 0, SEG_LVL_REF_FRAME);
352 vp9_set_segdata(seg, 0, SEG_LVL_REF_FRAME, ALTREF_FRAME);
353 vp9_clear_segdata(seg, 1, SEG_LVL_REF_FRAME);
354 vp9_set_segdata(seg, 1, SEG_LVL_REF_FRAME, ALTREF_FRAME);
355
356 // Skip all MBs if high Q (0,0 mv and skip coeffs)
357 if (high_q) {
358 vp9_enable_segfeature(seg, 0, SEG_LVL_SKIP);
359 vp9_enable_segfeature(seg, 1, SEG_LVL_SKIP);
360 }
361 // Enable data update
362 seg->update_data = 1;
363 } else {
364 // All other frames.
365
366 // No updates.. leave things as they are.
367 seg->update_map = 0;
368 seg->update_data = 0;
369 }
370 }
371 }
372
update_reference_segmentation_map(VP9_COMP * cpi)373 static void update_reference_segmentation_map(VP9_COMP *cpi) {
374 VP9_COMMON *const cm = &cpi->common;
375 MODE_INFO **mi_8x8_ptr = cm->mi_grid_visible;
376 uint8_t *cache_ptr = cm->last_frame_seg_map;
377 int row, col;
378
379 for (row = 0; row < cm->mi_rows; row++) {
380 MODE_INFO **mi_8x8 = mi_8x8_ptr;
381 uint8_t *cache = cache_ptr;
382 for (col = 0; col < cm->mi_cols; col++, mi_8x8++, cache++)
383 cache[0] = mi_8x8[0]->mbmi.segment_id;
384 mi_8x8_ptr += cm->mi_stride;
385 cache_ptr += cm->mi_cols;
386 }
387 }
388
389
set_speed_features(VP9_COMP * cpi)390 static void set_speed_features(VP9_COMP *cpi) {
391 #if CONFIG_INTERNAL_STATS
392 int i;
393 for (i = 0; i < MAX_MODES; ++i)
394 cpi->mode_chosen_counts[i] = 0;
395 #endif
396
397 vp9_set_speed_features(cpi);
398
399 // Set rd thresholds based on mode and speed setting
400 vp9_set_rd_speed_thresholds(cpi);
401 vp9_set_rd_speed_thresholds_sub8x8(cpi);
402 }
403
alloc_raw_frame_buffers(VP9_COMP * cpi)404 static void alloc_raw_frame_buffers(VP9_COMP *cpi) {
405 VP9_COMMON *cm = &cpi->common;
406 const VP9EncoderConfig *oxcf = &cpi->oxcf;
407
408 cpi->lookahead = vp9_lookahead_init(oxcf->width, oxcf->height,
409 cm->subsampling_x, cm->subsampling_y,
410 oxcf->lag_in_frames);
411 if (!cpi->lookahead)
412 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
413 "Failed to allocate lag buffers");
414
415 if (vp9_realloc_frame_buffer(&cpi->alt_ref_buffer,
416 oxcf->width, oxcf->height,
417 cm->subsampling_x, cm->subsampling_y,
418 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
419 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
420 "Failed to allocate altref buffer");
421 }
422
alloc_ref_frame_buffers(VP9_COMP * cpi)423 static void alloc_ref_frame_buffers(VP9_COMP *cpi) {
424 VP9_COMMON *const cm = &cpi->common;
425 if (vp9_alloc_ref_frame_buffers(cm, cm->width, cm->height))
426 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
427 "Failed to allocate frame buffers");
428 }
429
alloc_util_frame_buffers(VP9_COMP * cpi)430 static void alloc_util_frame_buffers(VP9_COMP *cpi) {
431 VP9_COMMON *const cm = &cpi->common;
432 if (vp9_realloc_frame_buffer(&cpi->last_frame_uf,
433 cm->width, cm->height,
434 cm->subsampling_x, cm->subsampling_y,
435 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
436 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
437 "Failed to allocate last frame buffer");
438
439 if (vp9_realloc_frame_buffer(&cpi->scaled_source,
440 cm->width, cm->height,
441 cm->subsampling_x, cm->subsampling_y,
442 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
443 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
444 "Failed to allocate scaled source buffer");
445
446 if (vp9_realloc_frame_buffer(&cpi->scaled_last_source,
447 cm->width, cm->height,
448 cm->subsampling_x, cm->subsampling_y,
449 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
450 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
451 "Failed to allocate scaled last source buffer");
452 }
453
vp9_alloc_compressor_data(VP9_COMP * cpi)454 void vp9_alloc_compressor_data(VP9_COMP *cpi) {
455 VP9_COMMON *cm = &cpi->common;
456
457 vp9_alloc_context_buffers(cm, cm->width, cm->height);
458
459 vpx_free(cpi->tok);
460
461 {
462 unsigned int tokens = get_token_alloc(cm->mb_rows, cm->mb_cols);
463 CHECK_MEM_ERROR(cm, cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
464 }
465
466 vp9_setup_pc_tree(&cpi->common, cpi);
467 }
468
update_frame_size(VP9_COMP * cpi)469 static void update_frame_size(VP9_COMP *cpi) {
470 VP9_COMMON *const cm = &cpi->common;
471 MACROBLOCKD *const xd = &cpi->mb.e_mbd;
472
473 vp9_set_mb_mi(cm, cm->width, cm->height);
474 vp9_init_context_buffers(cm);
475 init_macroblockd(cm, xd);
476
477 if (is_spatial_svc(cpi)) {
478 if (vp9_realloc_frame_buffer(&cpi->alt_ref_buffer,
479 cm->width, cm->height,
480 cm->subsampling_x, cm->subsampling_y,
481 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL))
482 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
483 "Failed to reallocate alt_ref_buffer");
484 }
485 }
486
vp9_new_framerate(VP9_COMP * cpi,double framerate)487 void vp9_new_framerate(VP9_COMP *cpi, double framerate) {
488 cpi->oxcf.framerate = framerate < 0.1 ? 30 : framerate;
489 vp9_rc_update_framerate(cpi);
490 }
491
vp9_rescale(int64_t val,int64_t num,int denom)492 int64_t vp9_rescale(int64_t val, int64_t num, int denom) {
493 int64_t llnum = num;
494 int64_t llden = denom;
495 int64_t llval = val;
496
497 return (llval * llnum / llden);
498 }
499
set_tile_limits(VP9_COMP * cpi)500 static void set_tile_limits(VP9_COMP *cpi) {
501 VP9_COMMON *const cm = &cpi->common;
502
503 int min_log2_tile_cols, max_log2_tile_cols;
504 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
505
506 cm->log2_tile_cols = clamp(cpi->oxcf.tile_columns,
507 min_log2_tile_cols, max_log2_tile_cols);
508 cm->log2_tile_rows = cpi->oxcf.tile_rows;
509 }
510
init_buffer_indices(VP9_COMP * cpi)511 static void init_buffer_indices(VP9_COMP *cpi) {
512 cpi->lst_fb_idx = 0;
513 cpi->gld_fb_idx = 1;
514 cpi->alt_fb_idx = 2;
515 }
516
init_config(struct VP9_COMP * cpi,VP9EncoderConfig * oxcf)517 static void init_config(struct VP9_COMP *cpi, VP9EncoderConfig *oxcf) {
518 VP9_COMMON *const cm = &cpi->common;
519
520 cpi->oxcf = *oxcf;
521
522 cm->profile = oxcf->profile;
523 cm->bit_depth = oxcf->bit_depth;
524 cm->color_space = UNKNOWN;
525
526 cm->width = oxcf->width;
527 cm->height = oxcf->height;
528 vp9_alloc_compressor_data(cpi);
529
530 // Spatial scalability.
531 cpi->svc.number_spatial_layers = oxcf->ss_number_layers;
532 // Temporal scalability.
533 cpi->svc.number_temporal_layers = oxcf->ts_number_layers;
534
535 if ((cpi->svc.number_temporal_layers > 1 &&
536 cpi->oxcf.rc_mode == VPX_CBR) ||
537 (cpi->svc.number_spatial_layers > 1 &&
538 cpi->oxcf.mode == TWO_PASS_SECOND_BEST)) {
539 vp9_init_layer_context(cpi);
540 }
541
542 // change includes all joint functionality
543 vp9_change_config(cpi, oxcf);
544
545 cpi->static_mb_pct = 0;
546 cpi->ref_frame_flags = 0;
547
548 init_buffer_indices(cpi);
549
550 set_tile_limits(cpi);
551 }
552
vp9_change_config(struct VP9_COMP * cpi,const VP9EncoderConfig * oxcf)553 void vp9_change_config(struct VP9_COMP *cpi, const VP9EncoderConfig *oxcf) {
554 VP9_COMMON *const cm = &cpi->common;
555 RATE_CONTROL *const rc = &cpi->rc;
556
557 if (cm->profile != oxcf->profile)
558 cm->profile = oxcf->profile;
559 cm->bit_depth = oxcf->bit_depth;
560
561 if (cm->profile <= PROFILE_1)
562 assert(cm->bit_depth == BITS_8);
563 else
564 assert(cm->bit_depth > BITS_8);
565
566 cpi->oxcf = *oxcf;
567
568 rc->baseline_gf_interval = DEFAULT_GF_INTERVAL;
569
570 cpi->refresh_golden_frame = 0;
571 cpi->refresh_last_frame = 1;
572 cm->refresh_frame_context = 1;
573 cm->reset_frame_context = 0;
574
575 vp9_reset_segment_features(&cm->seg);
576 vp9_set_high_precision_mv(cpi, 0);
577
578 {
579 int i;
580
581 for (i = 0; i < MAX_SEGMENTS; i++)
582 cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
583 }
584 cpi->encode_breakout = cpi->oxcf.encode_breakout;
585
586 // local file playback mode == really big buffer
587 if (cpi->oxcf.rc_mode == VPX_VBR) {
588 cpi->oxcf.starting_buffer_level_ms = 60000;
589 cpi->oxcf.optimal_buffer_level_ms = 60000;
590 cpi->oxcf.maximum_buffer_size_ms = 240000;
591 }
592
593 rc->starting_buffer_level = vp9_rescale(cpi->oxcf.starting_buffer_level_ms,
594 cpi->oxcf.target_bandwidth, 1000);
595
596 // Set or reset optimal and maximum buffer levels.
597 if (cpi->oxcf.optimal_buffer_level_ms == 0)
598 rc->optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
599 else
600 rc->optimal_buffer_level = vp9_rescale(cpi->oxcf.optimal_buffer_level_ms,
601 cpi->oxcf.target_bandwidth, 1000);
602
603 if (cpi->oxcf.maximum_buffer_size_ms == 0)
604 rc->maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
605 else
606 rc->maximum_buffer_size = vp9_rescale(cpi->oxcf.maximum_buffer_size_ms,
607 cpi->oxcf.target_bandwidth, 1000);
608 // Under a configuration change, where maximum_buffer_size may change,
609 // keep buffer level clipped to the maximum allowed buffer size.
610 rc->bits_off_target = MIN(rc->bits_off_target, rc->maximum_buffer_size);
611 rc->buffer_level = MIN(rc->buffer_level, rc->maximum_buffer_size);
612
613 // Set up frame rate and related parameters rate control values.
614 vp9_new_framerate(cpi, cpi->oxcf.framerate);
615
616 // Set absolute upper and lower quality limits
617 rc->worst_quality = cpi->oxcf.worst_allowed_q;
618 rc->best_quality = cpi->oxcf.best_allowed_q;
619
620 cm->interp_filter = cpi->sf.default_interp_filter;
621
622 cm->display_width = cpi->oxcf.width;
623 cm->display_height = cpi->oxcf.height;
624
625 if (cpi->initial_width) {
626 // Increasing the size of the frame beyond the first seen frame, or some
627 // otherwise signaled maximum size, is not supported.
628 // TODO(jkoleszar): exit gracefully.
629 assert(cm->width <= cpi->initial_width);
630 assert(cm->height <= cpi->initial_height);
631 }
632 update_frame_size(cpi);
633
634 if ((cpi->svc.number_temporal_layers > 1 &&
635 cpi->oxcf.rc_mode == VPX_CBR) ||
636 (cpi->svc.number_spatial_layers > 1 && cpi->oxcf.pass == 2)) {
637 vp9_update_layer_context_change_config(cpi,
638 (int)cpi->oxcf.target_bandwidth);
639 }
640
641 cpi->alt_ref_source = NULL;
642 rc->is_src_frame_alt_ref = 0;
643
644 #if 0
645 // Experimental RD Code
646 cpi->frame_distortion = 0;
647 cpi->last_frame_distortion = 0;
648 #endif
649
650 set_tile_limits(cpi);
651
652 cpi->ext_refresh_frame_flags_pending = 0;
653 cpi->ext_refresh_frame_context_pending = 0;
654
655 #if CONFIG_VP9_TEMPORAL_DENOISING
656 if (cpi->oxcf.noise_sensitivity > 0) {
657 vp9_denoiser_alloc(&(cpi->denoiser), cm->width, cm->height,
658 cm->subsampling_x, cm->subsampling_y,
659 VP9_ENC_BORDER_IN_PIXELS);
660 }
661 #endif
662 }
663
664 #ifndef M_LOG2_E
665 #define M_LOG2_E 0.693147180559945309417
666 #endif
667 #define log2f(x) (log (x) / (float) M_LOG2_E)
668
cal_nmvjointsadcost(int * mvjointsadcost)669 static void cal_nmvjointsadcost(int *mvjointsadcost) {
670 mvjointsadcost[0] = 600;
671 mvjointsadcost[1] = 300;
672 mvjointsadcost[2] = 300;
673 mvjointsadcost[3] = 300;
674 }
675
cal_nmvsadcosts(int * mvsadcost[2])676 static void cal_nmvsadcosts(int *mvsadcost[2]) {
677 int i = 1;
678
679 mvsadcost[0][0] = 0;
680 mvsadcost[1][0] = 0;
681
682 do {
683 double z = 256 * (2 * (log2f(8 * i) + .6));
684 mvsadcost[0][i] = (int)z;
685 mvsadcost[1][i] = (int)z;
686 mvsadcost[0][-i] = (int)z;
687 mvsadcost[1][-i] = (int)z;
688 } while (++i <= MV_MAX);
689 }
690
cal_nmvsadcosts_hp(int * mvsadcost[2])691 static void cal_nmvsadcosts_hp(int *mvsadcost[2]) {
692 int i = 1;
693
694 mvsadcost[0][0] = 0;
695 mvsadcost[1][0] = 0;
696
697 do {
698 double z = 256 * (2 * (log2f(8 * i) + .6));
699 mvsadcost[0][i] = (int)z;
700 mvsadcost[1][i] = (int)z;
701 mvsadcost[0][-i] = (int)z;
702 mvsadcost[1][-i] = (int)z;
703 } while (++i <= MV_MAX);
704 }
705
706
vp9_create_compressor(VP9EncoderConfig * oxcf)707 VP9_COMP *vp9_create_compressor(VP9EncoderConfig *oxcf) {
708 unsigned int i, j;
709 VP9_COMP *const cpi = vpx_memalign(32, sizeof(VP9_COMP));
710 VP9_COMMON *const cm = cpi != NULL ? &cpi->common : NULL;
711
712 if (!cm)
713 return NULL;
714
715 vp9_zero(*cpi);
716
717 if (setjmp(cm->error.jmp)) {
718 cm->error.setjmp = 0;
719 vp9_remove_compressor(cpi);
720 return 0;
721 }
722
723 cm->error.setjmp = 1;
724
725 vp9_rtcd();
726
727 cpi->use_svc = 0;
728
729 init_config(cpi, oxcf);
730 vp9_rc_init(&cpi->oxcf, oxcf->pass, &cpi->rc);
731
732 cm->current_video_frame = 0;
733
734 cpi->gold_is_last = 0;
735 cpi->alt_is_last = 0;
736 cpi->gold_is_alt = 0;
737
738 cpi->skippable_frame = 0;
739
740 // Create the encoder segmentation map and set all entries to 0
741 CHECK_MEM_ERROR(cm, cpi->segmentation_map,
742 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
743
744 // Create a complexity map used for rd adjustment
745 CHECK_MEM_ERROR(cm, cpi->complexity_map,
746 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
747
748 // Create a map used for cyclic background refresh.
749 CHECK_MEM_ERROR(cm, cpi->cyclic_refresh,
750 vp9_cyclic_refresh_alloc(cm->mi_rows, cm->mi_cols));
751
752 // And a place holder structure is the coding context
753 // for use if we want to save and restore it
754 CHECK_MEM_ERROR(cm, cpi->coding_context.last_frame_seg_map_copy,
755 vpx_calloc(cm->mi_rows * cm->mi_cols, 1));
756
757 for (i = 0; i < (sizeof(cpi->mbgraph_stats) /
758 sizeof(cpi->mbgraph_stats[0])); i++) {
759 CHECK_MEM_ERROR(cm, cpi->mbgraph_stats[i].mb_stats,
760 vpx_calloc(cm->MBs *
761 sizeof(*cpi->mbgraph_stats[i].mb_stats), 1));
762 }
763
764 #if CONFIG_FP_MB_STATS
765 cpi->use_fp_mb_stats = 0;
766 if (cpi->use_fp_mb_stats) {
767 // a place holder used to store the first pass mb stats in the first pass
768 CHECK_MEM_ERROR(cm, cpi->twopass.frame_mb_stats_buf,
769 vpx_calloc(cm->MBs * sizeof(uint8_t), 1));
770 } else {
771 cpi->twopass.frame_mb_stats_buf = NULL;
772 }
773 #endif
774
775 cpi->refresh_alt_ref_frame = 0;
776
777 // Note that at the moment multi_arf will not work with svc.
778 // For the current check in all the execution paths are defaulted to 0
779 // pending further tuning and testing. The code is left in place here
780 // as a place holder in regard to the required paths.
781 cpi->multi_arf_last_grp_enabled = 0;
782 if (oxcf->pass == 2) {
783 if (cpi->use_svc) {
784 cpi->multi_arf_allowed = 0;
785 cpi->multi_arf_enabled = 0;
786 } else {
787 // Disable by default for now.
788 cpi->multi_arf_allowed = 0;
789 cpi->multi_arf_enabled = 0;
790 }
791 } else {
792 cpi->multi_arf_allowed = 0;
793 cpi->multi_arf_enabled = 0;
794 }
795
796 cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
797 #if CONFIG_INTERNAL_STATS
798 cpi->b_calculate_ssimg = 0;
799
800 cpi->count = 0;
801 cpi->bytes = 0;
802
803 if (cpi->b_calculate_psnr) {
804 cpi->total_y = 0.0;
805 cpi->total_u = 0.0;
806 cpi->total_v = 0.0;
807 cpi->total = 0.0;
808 cpi->total_sq_error = 0;
809 cpi->total_samples = 0;
810
811 cpi->totalp_y = 0.0;
812 cpi->totalp_u = 0.0;
813 cpi->totalp_v = 0.0;
814 cpi->totalp = 0.0;
815 cpi->totalp_sq_error = 0;
816 cpi->totalp_samples = 0;
817
818 cpi->tot_recode_hits = 0;
819 cpi->summed_quality = 0;
820 cpi->summed_weights = 0;
821 cpi->summedp_quality = 0;
822 cpi->summedp_weights = 0;
823 }
824
825 if (cpi->b_calculate_ssimg) {
826 cpi->total_ssimg_y = 0;
827 cpi->total_ssimg_u = 0;
828 cpi->total_ssimg_v = 0;
829 cpi->total_ssimg_all = 0;
830 }
831
832 #endif
833
834 cpi->first_time_stamp_ever = INT64_MAX;
835
836 cal_nmvjointsadcost(cpi->mb.nmvjointsadcost);
837 cpi->mb.nmvcost[0] = &cpi->mb.nmvcosts[0][MV_MAX];
838 cpi->mb.nmvcost[1] = &cpi->mb.nmvcosts[1][MV_MAX];
839 cpi->mb.nmvsadcost[0] = &cpi->mb.nmvsadcosts[0][MV_MAX];
840 cpi->mb.nmvsadcost[1] = &cpi->mb.nmvsadcosts[1][MV_MAX];
841 cal_nmvsadcosts(cpi->mb.nmvsadcost);
842
843 cpi->mb.nmvcost_hp[0] = &cpi->mb.nmvcosts_hp[0][MV_MAX];
844 cpi->mb.nmvcost_hp[1] = &cpi->mb.nmvcosts_hp[1][MV_MAX];
845 cpi->mb.nmvsadcost_hp[0] = &cpi->mb.nmvsadcosts_hp[0][MV_MAX];
846 cpi->mb.nmvsadcost_hp[1] = &cpi->mb.nmvsadcosts_hp[1][MV_MAX];
847 cal_nmvsadcosts_hp(cpi->mb.nmvsadcost_hp);
848
849 #if CONFIG_VP9_TEMPORAL_DENOISING
850 #ifdef OUTPUT_YUV_DENOISED
851 yuv_denoised_file = fopen("denoised.yuv", "ab");
852 #endif
853 #endif
854 #ifdef OUTPUT_YUV_REC
855 yuv_rec_file = fopen("rec.yuv", "wb");
856 #endif
857
858 #if 0
859 framepsnr = fopen("framepsnr.stt", "a");
860 kf_list = fopen("kf_list.stt", "w");
861 #endif
862
863 cpi->output_pkt_list = oxcf->output_pkt_list;
864
865 cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
866
867 if (oxcf->pass == 1) {
868 vp9_init_first_pass(cpi);
869 } else if (oxcf->pass == 2) {
870 const size_t packet_sz = sizeof(FIRSTPASS_STATS);
871 const int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
872
873 if (cpi->svc.number_spatial_layers > 1
874 && cpi->svc.number_temporal_layers == 1) {
875 FIRSTPASS_STATS *const stats = oxcf->two_pass_stats_in.buf;
876 FIRSTPASS_STATS *stats_copy[VPX_SS_MAX_LAYERS] = {0};
877 int i;
878
879 for (i = 0; i < oxcf->ss_number_layers; ++i) {
880 FIRSTPASS_STATS *const last_packet_for_layer =
881 &stats[packets - oxcf->ss_number_layers + i];
882 const int layer_id = (int)last_packet_for_layer->spatial_layer_id;
883 const int packets_in_layer = (int)last_packet_for_layer->count + 1;
884 if (layer_id >= 0 && layer_id < oxcf->ss_number_layers) {
885 LAYER_CONTEXT *const lc = &cpi->svc.layer_context[layer_id];
886
887 vpx_free(lc->rc_twopass_stats_in.buf);
888
889 lc->rc_twopass_stats_in.sz = packets_in_layer * packet_sz;
890 CHECK_MEM_ERROR(cm, lc->rc_twopass_stats_in.buf,
891 vpx_malloc(lc->rc_twopass_stats_in.sz));
892 lc->twopass.stats_in_start = lc->rc_twopass_stats_in.buf;
893 lc->twopass.stats_in = lc->twopass.stats_in_start;
894 lc->twopass.stats_in_end = lc->twopass.stats_in_start
895 + packets_in_layer - 1;
896 stats_copy[layer_id] = lc->rc_twopass_stats_in.buf;
897 }
898 }
899
900 for (i = 0; i < packets; ++i) {
901 const int layer_id = (int)stats[i].spatial_layer_id;
902 if (layer_id >= 0 && layer_id < oxcf->ss_number_layers
903 && stats_copy[layer_id] != NULL) {
904 *stats_copy[layer_id] = stats[i];
905 ++stats_copy[layer_id];
906 }
907 }
908
909 vp9_init_second_pass_spatial_svc(cpi);
910 } else {
911 #if CONFIG_FP_MB_STATS
912 if (cpi->use_fp_mb_stats) {
913 const size_t psz = cpi->common.MBs * sizeof(uint8_t);
914 const int ps = (int)(oxcf->firstpass_mb_stats_in.sz / psz);
915
916 cpi->twopass.firstpass_mb_stats.mb_stats_start =
917 oxcf->firstpass_mb_stats_in.buf;
918 cpi->twopass.firstpass_mb_stats.mb_stats_end =
919 cpi->twopass.firstpass_mb_stats.mb_stats_start +
920 (ps - 1) * cpi->common.MBs * sizeof(uint8_t);
921 }
922 #endif
923
924 cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
925 cpi->twopass.stats_in = cpi->twopass.stats_in_start;
926 cpi->twopass.stats_in_end = &cpi->twopass.stats_in[packets - 1];
927
928 vp9_init_second_pass(cpi);
929 }
930 }
931
932 set_speed_features(cpi);
933
934 // Allocate memory to store variances for a frame.
935 CHECK_MEM_ERROR(cm, cpi->source_diff_var,
936 vpx_calloc(cm->MBs, sizeof(diff)));
937 cpi->source_var_thresh = 0;
938 cpi->frames_till_next_var_check = 0;
939
940 // Default rd threshold factors for mode selection
941 for (i = 0; i < BLOCK_SIZES; ++i) {
942 for (j = 0; j < MAX_MODES; ++j)
943 cpi->rd.thresh_freq_fact[i][j] = 32;
944 }
945
946 #define BFP(BT, SDF, SDAF, VF, SVF, SVAF, SDX3F, SDX8F, SDX4DF)\
947 cpi->fn_ptr[BT].sdf = SDF; \
948 cpi->fn_ptr[BT].sdaf = SDAF; \
949 cpi->fn_ptr[BT].vf = VF; \
950 cpi->fn_ptr[BT].svf = SVF; \
951 cpi->fn_ptr[BT].svaf = SVAF; \
952 cpi->fn_ptr[BT].sdx3f = SDX3F; \
953 cpi->fn_ptr[BT].sdx8f = SDX8F; \
954 cpi->fn_ptr[BT].sdx4df = SDX4DF;
955
956 BFP(BLOCK_32X16, vp9_sad32x16, vp9_sad32x16_avg,
957 vp9_variance32x16, vp9_sub_pixel_variance32x16,
958 vp9_sub_pixel_avg_variance32x16, NULL, NULL, vp9_sad32x16x4d)
959
960 BFP(BLOCK_16X32, vp9_sad16x32, vp9_sad16x32_avg,
961 vp9_variance16x32, vp9_sub_pixel_variance16x32,
962 vp9_sub_pixel_avg_variance16x32, NULL, NULL, vp9_sad16x32x4d)
963
964 BFP(BLOCK_64X32, vp9_sad64x32, vp9_sad64x32_avg,
965 vp9_variance64x32, vp9_sub_pixel_variance64x32,
966 vp9_sub_pixel_avg_variance64x32, NULL, NULL, vp9_sad64x32x4d)
967
968 BFP(BLOCK_32X64, vp9_sad32x64, vp9_sad32x64_avg,
969 vp9_variance32x64, vp9_sub_pixel_variance32x64,
970 vp9_sub_pixel_avg_variance32x64, NULL, NULL, vp9_sad32x64x4d)
971
972 BFP(BLOCK_32X32, vp9_sad32x32, vp9_sad32x32_avg,
973 vp9_variance32x32, vp9_sub_pixel_variance32x32,
974 vp9_sub_pixel_avg_variance32x32, vp9_sad32x32x3, vp9_sad32x32x8,
975 vp9_sad32x32x4d)
976
977 BFP(BLOCK_64X64, vp9_sad64x64, vp9_sad64x64_avg,
978 vp9_variance64x64, vp9_sub_pixel_variance64x64,
979 vp9_sub_pixel_avg_variance64x64, vp9_sad64x64x3, vp9_sad64x64x8,
980 vp9_sad64x64x4d)
981
982 BFP(BLOCK_16X16, vp9_sad16x16, vp9_sad16x16_avg,
983 vp9_variance16x16, vp9_sub_pixel_variance16x16,
984 vp9_sub_pixel_avg_variance16x16, vp9_sad16x16x3, vp9_sad16x16x8,
985 vp9_sad16x16x4d)
986
987 BFP(BLOCK_16X8, vp9_sad16x8, vp9_sad16x8_avg,
988 vp9_variance16x8, vp9_sub_pixel_variance16x8,
989 vp9_sub_pixel_avg_variance16x8,
990 vp9_sad16x8x3, vp9_sad16x8x8, vp9_sad16x8x4d)
991
992 BFP(BLOCK_8X16, vp9_sad8x16, vp9_sad8x16_avg,
993 vp9_variance8x16, vp9_sub_pixel_variance8x16,
994 vp9_sub_pixel_avg_variance8x16,
995 vp9_sad8x16x3, vp9_sad8x16x8, vp9_sad8x16x4d)
996
997 BFP(BLOCK_8X8, vp9_sad8x8, vp9_sad8x8_avg,
998 vp9_variance8x8, vp9_sub_pixel_variance8x8,
999 vp9_sub_pixel_avg_variance8x8,
1000 vp9_sad8x8x3, vp9_sad8x8x8, vp9_sad8x8x4d)
1001
1002 BFP(BLOCK_8X4, vp9_sad8x4, vp9_sad8x4_avg,
1003 vp9_variance8x4, vp9_sub_pixel_variance8x4,
1004 vp9_sub_pixel_avg_variance8x4, NULL, vp9_sad8x4x8, vp9_sad8x4x4d)
1005
1006 BFP(BLOCK_4X8, vp9_sad4x8, vp9_sad4x8_avg,
1007 vp9_variance4x8, vp9_sub_pixel_variance4x8,
1008 vp9_sub_pixel_avg_variance4x8, NULL, vp9_sad4x8x8, vp9_sad4x8x4d)
1009
1010 BFP(BLOCK_4X4, vp9_sad4x4, vp9_sad4x4_avg,
1011 vp9_variance4x4, vp9_sub_pixel_variance4x4,
1012 vp9_sub_pixel_avg_variance4x4,
1013 vp9_sad4x4x3, vp9_sad4x4x8, vp9_sad4x4x4d)
1014
1015 cpi->full_search_sad = vp9_full_search_sad;
1016 cpi->diamond_search_sad = vp9_diamond_search_sad;
1017 cpi->refining_search_sad = vp9_refining_search_sad;
1018
1019 /* vp9_init_quantizer() is first called here. Add check in
1020 * vp9_frame_init_quantizer() so that vp9_init_quantizer is only
1021 * called later when needed. This will avoid unnecessary calls of
1022 * vp9_init_quantizer() for every frame.
1023 */
1024 vp9_init_quantizer(cpi);
1025
1026 vp9_loop_filter_init(cm);
1027
1028 cm->error.setjmp = 0;
1029
1030 return cpi;
1031 }
1032
vp9_remove_compressor(VP9_COMP * cpi)1033 void vp9_remove_compressor(VP9_COMP *cpi) {
1034 unsigned int i;
1035
1036 if (!cpi)
1037 return;
1038
1039 if (cpi && (cpi->common.current_video_frame > 0)) {
1040 #if CONFIG_INTERNAL_STATS
1041
1042 vp9_clear_system_state();
1043
1044 // printf("\n8x8-4x4:%d-%d\n", cpi->t8x8_count, cpi->t4x4_count);
1045 if (cpi->oxcf.pass != 1) {
1046 FILE *f = fopen("opsnr.stt", "a");
1047 double time_encoded = (cpi->last_end_time_stamp_seen
1048 - cpi->first_time_stamp_ever) / 10000000.000;
1049 double total_encode_time = (cpi->time_receive_data +
1050 cpi->time_compress_data) / 1000.000;
1051 double dr = (double)cpi->bytes * (double) 8 / (double)1000
1052 / time_encoded;
1053
1054 if (cpi->b_calculate_psnr) {
1055 const double total_psnr =
1056 vpx_sse_to_psnr((double)cpi->total_samples, 255.0,
1057 (double)cpi->total_sq_error);
1058 const double totalp_psnr =
1059 vpx_sse_to_psnr((double)cpi->totalp_samples, 255.0,
1060 (double)cpi->totalp_sq_error);
1061 const double total_ssim = 100 * pow(cpi->summed_quality /
1062 cpi->summed_weights, 8.0);
1063 const double totalp_ssim = 100 * pow(cpi->summedp_quality /
1064 cpi->summedp_weights, 8.0);
1065
1066 fprintf(f, "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\tGLPsnrP\t"
1067 "VPXSSIM\tVPSSIMP\t Time(ms)\n");
1068 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",
1069 dr, cpi->total / cpi->count, total_psnr,
1070 cpi->totalp / cpi->count, totalp_psnr, total_ssim, totalp_ssim,
1071 total_encode_time);
1072 }
1073
1074 if (cpi->b_calculate_ssimg) {
1075 fprintf(f, "BitRate\tSSIM_Y\tSSIM_U\tSSIM_V\tSSIM_A\t Time(ms)\n");
1076 fprintf(f, "%7.2f\t%6.4f\t%6.4f\t%6.4f\t%6.4f\t%8.0f\n", dr,
1077 cpi->total_ssimg_y / cpi->count,
1078 cpi->total_ssimg_u / cpi->count,
1079 cpi->total_ssimg_v / cpi->count,
1080 cpi->total_ssimg_all / cpi->count, total_encode_time);
1081 }
1082
1083 fclose(f);
1084 }
1085
1086 #endif
1087
1088 #if 0
1089 {
1090 printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
1091 printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
1092 printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame,
1093 cpi->time_receive_data / 1000, cpi->time_encode_sb_row / 1000,
1094 cpi->time_compress_data / 1000,
1095 (cpi->time_receive_data + cpi->time_compress_data) / 1000);
1096 }
1097 #endif
1098 }
1099
1100 #if CONFIG_VP9_TEMPORAL_DENOISING
1101 if (cpi->oxcf.noise_sensitivity > 0) {
1102 vp9_denoiser_free(&(cpi->denoiser));
1103 }
1104 #endif
1105
1106 dealloc_compressor_data(cpi);
1107 vpx_free(cpi->tok);
1108
1109 for (i = 0; i < sizeof(cpi->mbgraph_stats) /
1110 sizeof(cpi->mbgraph_stats[0]); ++i) {
1111 vpx_free(cpi->mbgraph_stats[i].mb_stats);
1112 }
1113
1114 #if CONFIG_FP_MB_STATS
1115 if (cpi->use_fp_mb_stats) {
1116 vpx_free(cpi->twopass.frame_mb_stats_buf);
1117 cpi->twopass.frame_mb_stats_buf = NULL;
1118 }
1119 #endif
1120
1121 vp9_remove_common(&cpi->common);
1122 vpx_free(cpi);
1123
1124 #if CONFIG_VP9_TEMPORAL_DENOISING
1125 #ifdef OUTPUT_YUV_DENOISED
1126 fclose(yuv_denoised_file);
1127 #endif
1128 #endif
1129 #ifdef OUTPUT_YUV_REC
1130 fclose(yuv_rec_file);
1131 #endif
1132
1133 #if 0
1134
1135 if (keyfile)
1136 fclose(keyfile);
1137
1138 if (framepsnr)
1139 fclose(framepsnr);
1140
1141 if (kf_list)
1142 fclose(kf_list);
1143
1144 #endif
1145 }
get_sse(const uint8_t * a,int a_stride,const uint8_t * b,int b_stride,int width,int height)1146 static int64_t get_sse(const uint8_t *a, int a_stride,
1147 const uint8_t *b, int b_stride,
1148 int width, int height) {
1149 const int dw = width % 16;
1150 const int dh = height % 16;
1151 int64_t total_sse = 0;
1152 unsigned int sse = 0;
1153 int sum = 0;
1154 int x, y;
1155
1156 if (dw > 0) {
1157 variance(&a[width - dw], a_stride, &b[width - dw], b_stride,
1158 dw, height, &sse, &sum);
1159 total_sse += sse;
1160 }
1161
1162 if (dh > 0) {
1163 variance(&a[(height - dh) * a_stride], a_stride,
1164 &b[(height - dh) * b_stride], b_stride,
1165 width - dw, dh, &sse, &sum);
1166 total_sse += sse;
1167 }
1168
1169 for (y = 0; y < height / 16; ++y) {
1170 const uint8_t *pa = a;
1171 const uint8_t *pb = b;
1172 for (x = 0; x < width / 16; ++x) {
1173 vp9_mse16x16(pa, a_stride, pb, b_stride, &sse);
1174 total_sse += sse;
1175
1176 pa += 16;
1177 pb += 16;
1178 }
1179
1180 a += 16 * a_stride;
1181 b += 16 * b_stride;
1182 }
1183
1184 return total_sse;
1185 }
1186
1187 typedef struct {
1188 double psnr[4]; // total/y/u/v
1189 uint64_t sse[4]; // total/y/u/v
1190 uint32_t samples[4]; // total/y/u/v
1191 } PSNR_STATS;
1192
calc_psnr(const YV12_BUFFER_CONFIG * a,const YV12_BUFFER_CONFIG * b,PSNR_STATS * psnr)1193 static void calc_psnr(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b,
1194 PSNR_STATS *psnr) {
1195 const int widths[3] = {a->y_width, a->uv_width, a->uv_width };
1196 const int heights[3] = {a->y_height, a->uv_height, a->uv_height};
1197 const uint8_t *a_planes[3] = {a->y_buffer, a->u_buffer, a->v_buffer };
1198 const int a_strides[3] = {a->y_stride, a->uv_stride, a->uv_stride};
1199 const uint8_t *b_planes[3] = {b->y_buffer, b->u_buffer, b->v_buffer };
1200 const int b_strides[3] = {b->y_stride, b->uv_stride, b->uv_stride};
1201 int i;
1202 uint64_t total_sse = 0;
1203 uint32_t total_samples = 0;
1204
1205 for (i = 0; i < 3; ++i) {
1206 const int w = widths[i];
1207 const int h = heights[i];
1208 const uint32_t samples = w * h;
1209 const uint64_t sse = get_sse(a_planes[i], a_strides[i],
1210 b_planes[i], b_strides[i],
1211 w, h);
1212 psnr->sse[1 + i] = sse;
1213 psnr->samples[1 + i] = samples;
1214 psnr->psnr[1 + i] = vpx_sse_to_psnr(samples, 255.0, (double)sse);
1215
1216 total_sse += sse;
1217 total_samples += samples;
1218 }
1219
1220 psnr->sse[0] = total_sse;
1221 psnr->samples[0] = total_samples;
1222 psnr->psnr[0] = vpx_sse_to_psnr((double)total_samples, 255.0,
1223 (double)total_sse);
1224 }
1225
generate_psnr_packet(VP9_COMP * cpi)1226 static void generate_psnr_packet(VP9_COMP *cpi) {
1227 struct vpx_codec_cx_pkt pkt;
1228 int i;
1229 PSNR_STATS psnr;
1230 calc_psnr(cpi->Source, cpi->common.frame_to_show, &psnr);
1231 for (i = 0; i < 4; ++i) {
1232 pkt.data.psnr.samples[i] = psnr.samples[i];
1233 pkt.data.psnr.sse[i] = psnr.sse[i];
1234 pkt.data.psnr.psnr[i] = psnr.psnr[i];
1235 }
1236 pkt.kind = VPX_CODEC_PSNR_PKT;
1237 vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
1238 }
1239
vp9_use_as_reference(VP9_COMP * cpi,int ref_frame_flags)1240 int vp9_use_as_reference(VP9_COMP *cpi, int ref_frame_flags) {
1241 if (ref_frame_flags > 7)
1242 return -1;
1243
1244 cpi->ref_frame_flags = ref_frame_flags;
1245 return 0;
1246 }
1247
vp9_update_reference(VP9_COMP * cpi,int ref_frame_flags)1248 void vp9_update_reference(VP9_COMP *cpi, int ref_frame_flags) {
1249 cpi->ext_refresh_golden_frame = (ref_frame_flags & VP9_GOLD_FLAG) != 0;
1250 cpi->ext_refresh_alt_ref_frame = (ref_frame_flags & VP9_ALT_FLAG) != 0;
1251 cpi->ext_refresh_last_frame = (ref_frame_flags & VP9_LAST_FLAG) != 0;
1252 cpi->ext_refresh_frame_flags_pending = 1;
1253 }
1254
get_vp9_ref_frame_buffer(VP9_COMP * cpi,VP9_REFFRAME ref_frame_flag)1255 static YV12_BUFFER_CONFIG *get_vp9_ref_frame_buffer(VP9_COMP *cpi,
1256 VP9_REFFRAME ref_frame_flag) {
1257 MV_REFERENCE_FRAME ref_frame = NONE;
1258 if (ref_frame_flag == VP9_LAST_FLAG)
1259 ref_frame = LAST_FRAME;
1260 else if (ref_frame_flag == VP9_GOLD_FLAG)
1261 ref_frame = GOLDEN_FRAME;
1262 else if (ref_frame_flag == VP9_ALT_FLAG)
1263 ref_frame = ALTREF_FRAME;
1264
1265 return ref_frame == NONE ? NULL : get_ref_frame_buffer(cpi, ref_frame);
1266 }
1267
vp9_copy_reference_enc(VP9_COMP * cpi,VP9_REFFRAME ref_frame_flag,YV12_BUFFER_CONFIG * sd)1268 int vp9_copy_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
1269 YV12_BUFFER_CONFIG *sd) {
1270 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
1271 if (cfg) {
1272 vp8_yv12_copy_frame(cfg, sd);
1273 return 0;
1274 } else {
1275 return -1;
1276 }
1277 }
1278
vp9_set_reference_enc(VP9_COMP * cpi,VP9_REFFRAME ref_frame_flag,YV12_BUFFER_CONFIG * sd)1279 int vp9_set_reference_enc(VP9_COMP *cpi, VP9_REFFRAME ref_frame_flag,
1280 YV12_BUFFER_CONFIG *sd) {
1281 YV12_BUFFER_CONFIG *cfg = get_vp9_ref_frame_buffer(cpi, ref_frame_flag);
1282 if (cfg) {
1283 vp8_yv12_copy_frame(sd, cfg);
1284 return 0;
1285 } else {
1286 return -1;
1287 }
1288 }
1289
vp9_update_entropy(VP9_COMP * cpi,int update)1290 int vp9_update_entropy(VP9_COMP * cpi, int update) {
1291 cpi->ext_refresh_frame_context = update;
1292 cpi->ext_refresh_frame_context_pending = 1;
1293 return 0;
1294 }
1295
1296 #if CONFIG_VP9_TEMPORAL_DENOISING
1297 #if defined(OUTPUT_YUV_DENOISED)
1298 // The denoiser buffer is allocated as a YUV 440 buffer. This function writes it
1299 // as YUV 420. We simply use the top-left pixels of the UV buffers, since we do
1300 // not denoise the UV channels at this time. If ever we implement UV channel
1301 // denoising we will have to modify this.
vp9_write_yuv_frame_420(YV12_BUFFER_CONFIG * s,FILE * f)1302 void vp9_write_yuv_frame_420(YV12_BUFFER_CONFIG *s, FILE *f) {
1303 uint8_t *src = s->y_buffer;
1304 int h = s->y_height;
1305
1306 do {
1307 fwrite(src, s->y_width, 1, f);
1308 src += s->y_stride;
1309 } while (--h);
1310
1311 src = s->u_buffer;
1312 h = s->uv_height / 2;
1313
1314 do {
1315 fwrite(src, s->uv_width / 2, 1, f);
1316 src += s->uv_stride + s->uv_width / 2;
1317 } while (--h);
1318
1319 src = s->v_buffer;
1320 h = s->uv_height / 2;
1321
1322 do {
1323 fwrite(src, s->uv_width / 2, 1, f);
1324 src += s->uv_stride + s->uv_width / 2;
1325 } while (--h);
1326 }
1327 #endif
1328 #endif
1329
1330 #ifdef OUTPUT_YUV_REC
vp9_write_yuv_rec_frame(VP9_COMMON * cm)1331 void vp9_write_yuv_rec_frame(VP9_COMMON *cm) {
1332 YV12_BUFFER_CONFIG *s = cm->frame_to_show;
1333 uint8_t *src = s->y_buffer;
1334 int h = cm->height;
1335
1336 do {
1337 fwrite(src, s->y_width, 1, yuv_rec_file);
1338 src += s->y_stride;
1339 } while (--h);
1340
1341 src = s->u_buffer;
1342 h = s->uv_height;
1343
1344 do {
1345 fwrite(src, s->uv_width, 1, yuv_rec_file);
1346 src += s->uv_stride;
1347 } while (--h);
1348
1349 src = s->v_buffer;
1350 h = s->uv_height;
1351
1352 do {
1353 fwrite(src, s->uv_width, 1, yuv_rec_file);
1354 src += s->uv_stride;
1355 } while (--h);
1356
1357 fflush(yuv_rec_file);
1358 }
1359 #endif
1360
scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG * src,YV12_BUFFER_CONFIG * dst)1361 static void scale_and_extend_frame_nonnormative(const YV12_BUFFER_CONFIG *src,
1362 YV12_BUFFER_CONFIG *dst) {
1363 // TODO(dkovalev): replace YV12_BUFFER_CONFIG with vpx_image_t
1364 int i;
1365 const uint8_t *const srcs[3] = {src->y_buffer, src->u_buffer, src->v_buffer};
1366 const int src_strides[3] = {src->y_stride, src->uv_stride, src->uv_stride};
1367 const int src_widths[3] = {src->y_crop_width, src->uv_crop_width,
1368 src->uv_crop_width };
1369 const int src_heights[3] = {src->y_crop_height, src->uv_crop_height,
1370 src->uv_crop_height};
1371 uint8_t *const dsts[3] = {dst->y_buffer, dst->u_buffer, dst->v_buffer};
1372 const int dst_strides[3] = {dst->y_stride, dst->uv_stride, dst->uv_stride};
1373 const int dst_widths[3] = {dst->y_crop_width, dst->uv_crop_width,
1374 dst->uv_crop_width};
1375 const int dst_heights[3] = {dst->y_crop_height, dst->uv_crop_height,
1376 dst->uv_crop_height};
1377
1378 for (i = 0; i < MAX_MB_PLANE; ++i)
1379 vp9_resize_plane(srcs[i], src_heights[i], src_widths[i], src_strides[i],
1380 dsts[i], dst_heights[i], dst_widths[i], dst_strides[i]);
1381
1382 vp9_extend_frame_borders(dst);
1383 }
1384
scale_and_extend_frame(const YV12_BUFFER_CONFIG * src,YV12_BUFFER_CONFIG * dst)1385 static void scale_and_extend_frame(const YV12_BUFFER_CONFIG *src,
1386 YV12_BUFFER_CONFIG *dst) {
1387 const int src_w = src->y_crop_width;
1388 const int src_h = src->y_crop_height;
1389 const int dst_w = dst->y_crop_width;
1390 const int dst_h = dst->y_crop_height;
1391 const uint8_t *const srcs[3] = {src->y_buffer, src->u_buffer, src->v_buffer};
1392 const int src_strides[3] = {src->y_stride, src->uv_stride, src->uv_stride};
1393 uint8_t *const dsts[3] = {dst->y_buffer, dst->u_buffer, dst->v_buffer};
1394 const int dst_strides[3] = {dst->y_stride, dst->uv_stride, dst->uv_stride};
1395 const InterpKernel *const kernel = vp9_get_interp_kernel(EIGHTTAP);
1396 int x, y, i;
1397
1398 for (y = 0; y < dst_h; y += 16) {
1399 for (x = 0; x < dst_w; x += 16) {
1400 for (i = 0; i < MAX_MB_PLANE; ++i) {
1401 const int factor = (i == 0 || i == 3 ? 1 : 2);
1402 const int x_q4 = x * (16 / factor) * src_w / dst_w;
1403 const int y_q4 = y * (16 / factor) * src_h / dst_h;
1404 const int src_stride = src_strides[i];
1405 const int dst_stride = dst_strides[i];
1406 const uint8_t *src_ptr = srcs[i] + (y / factor) * src_h / dst_h *
1407 src_stride + (x / factor) * src_w / dst_w;
1408 uint8_t *dst_ptr = dsts[i] + (y / factor) * dst_stride + (x / factor);
1409
1410 vp9_convolve8(src_ptr, src_stride, dst_ptr, dst_stride,
1411 kernel[x_q4 & 0xf], 16 * src_w / dst_w,
1412 kernel[y_q4 & 0xf], 16 * src_h / dst_h,
1413 16 / factor, 16 / factor);
1414 }
1415 }
1416 }
1417
1418 vp9_extend_frame_borders(dst);
1419 }
1420
1421 #define WRITE_RECON_BUFFER 0
1422 #if WRITE_RECON_BUFFER
write_cx_frame_to_file(YV12_BUFFER_CONFIG * frame,int this_frame)1423 void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame) {
1424 FILE *yframe;
1425 int i;
1426 char filename[255];
1427
1428 snprintf(filename, sizeof(filename), "cx\\y%04d.raw", this_frame);
1429 yframe = fopen(filename, "wb");
1430
1431 for (i = 0; i < frame->y_height; i++)
1432 fwrite(frame->y_buffer + i * frame->y_stride,
1433 frame->y_width, 1, yframe);
1434
1435 fclose(yframe);
1436 snprintf(filename, sizeof(filename), "cx\\u%04d.raw", this_frame);
1437 yframe = fopen(filename, "wb");
1438
1439 for (i = 0; i < frame->uv_height; i++)
1440 fwrite(frame->u_buffer + i * frame->uv_stride,
1441 frame->uv_width, 1, yframe);
1442
1443 fclose(yframe);
1444 snprintf(filename, sizeof(filename), "cx\\v%04d.raw", this_frame);
1445 yframe = fopen(filename, "wb");
1446
1447 for (i = 0; i < frame->uv_height; i++)
1448 fwrite(frame->v_buffer + i * frame->uv_stride,
1449 frame->uv_width, 1, yframe);
1450
1451 fclose(yframe);
1452 }
1453 #endif
1454
1455 // Function to test for conditions that indicate we should loop
1456 // back and recode a frame.
recode_loop_test(const VP9_COMP * cpi,int high_limit,int low_limit,int q,int maxq,int minq)1457 static int recode_loop_test(const VP9_COMP *cpi,
1458 int high_limit, int low_limit,
1459 int q, int maxq, int minq) {
1460 const VP9_COMMON *const cm = &cpi->common;
1461 const RATE_CONTROL *const rc = &cpi->rc;
1462 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1463 int force_recode = 0;
1464
1465 // Special case trap if maximum allowed frame size exceeded.
1466 if (rc->projected_frame_size > rc->max_frame_bandwidth) {
1467 force_recode = 1;
1468
1469 // Is frame recode allowed.
1470 // Yes if either recode mode 1 is selected or mode 2 is selected
1471 // and the frame is a key frame, golden frame or alt_ref_frame
1472 } else if ((cpi->sf.recode_loop == ALLOW_RECODE) ||
1473 ((cpi->sf.recode_loop == ALLOW_RECODE_KFARFGF) &&
1474 (cm->frame_type == KEY_FRAME ||
1475 cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
1476 // General over and under shoot tests
1477 if ((rc->projected_frame_size > high_limit && q < maxq) ||
1478 (rc->projected_frame_size < low_limit && q > minq)) {
1479 force_recode = 1;
1480 } else if (cpi->oxcf.rc_mode == VPX_CQ) {
1481 // Deal with frame undershoot and whether or not we are
1482 // below the automatically set cq level.
1483 if (q > oxcf->cq_level &&
1484 rc->projected_frame_size < ((rc->this_frame_target * 7) >> 3)) {
1485 force_recode = 1;
1486 }
1487 }
1488 }
1489 return force_recode;
1490 }
1491
vp9_update_reference_frames(VP9_COMP * cpi)1492 void vp9_update_reference_frames(VP9_COMP *cpi) {
1493 VP9_COMMON * const cm = &cpi->common;
1494
1495 // At this point the new frame has been encoded.
1496 // If any buffer copy / swapping is signaled it should be done here.
1497 if (cm->frame_type == KEY_FRAME) {
1498 ref_cnt_fb(cm->frame_bufs,
1499 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
1500 ref_cnt_fb(cm->frame_bufs,
1501 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
1502 } else if (vp9_preserve_existing_gf(cpi)) {
1503 // We have decided to preserve the previously existing golden frame as our
1504 // new ARF frame. However, in the short term in function
1505 // vp9_bitstream.c::get_refresh_mask() we left it in the GF slot and, if
1506 // we're updating the GF with the current decoded frame, we save it to the
1507 // ARF slot instead.
1508 // We now have to update the ARF with the current frame and swap gld_fb_idx
1509 // and alt_fb_idx so that, overall, we've stored the old GF in the new ARF
1510 // slot and, if we're updating the GF, the current frame becomes the new GF.
1511 int tmp;
1512
1513 ref_cnt_fb(cm->frame_bufs,
1514 &cm->ref_frame_map[cpi->alt_fb_idx], cm->new_fb_idx);
1515
1516 tmp = cpi->alt_fb_idx;
1517 cpi->alt_fb_idx = cpi->gld_fb_idx;
1518 cpi->gld_fb_idx = tmp;
1519
1520 if (is_spatial_svc(cpi)) {
1521 cpi->svc.layer_context[0].gold_ref_idx = cpi->gld_fb_idx;
1522 cpi->svc.layer_context[0].alt_ref_idx = cpi->alt_fb_idx;
1523 }
1524 } else { /* For non key/golden frames */
1525 if (cpi->refresh_alt_ref_frame) {
1526 int arf_idx = cpi->alt_fb_idx;
1527 if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
1528 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
1529 arf_idx = gf_group->arf_update_idx[gf_group->index];
1530 }
1531
1532 ref_cnt_fb(cm->frame_bufs,
1533 &cm->ref_frame_map[arf_idx], cm->new_fb_idx);
1534 }
1535
1536 if (cpi->refresh_golden_frame) {
1537 ref_cnt_fb(cm->frame_bufs,
1538 &cm->ref_frame_map[cpi->gld_fb_idx], cm->new_fb_idx);
1539 }
1540 }
1541
1542 if (cpi->refresh_last_frame) {
1543 ref_cnt_fb(cm->frame_bufs,
1544 &cm->ref_frame_map[cpi->lst_fb_idx], cm->new_fb_idx);
1545 }
1546 #if CONFIG_VP9_TEMPORAL_DENOISING
1547 if (cpi->oxcf.noise_sensitivity > 0) {
1548 vp9_denoiser_update_frame_info(&cpi->denoiser,
1549 *cpi->Source,
1550 cpi->common.frame_type,
1551 cpi->refresh_alt_ref_frame,
1552 cpi->refresh_golden_frame,
1553 cpi->refresh_last_frame);
1554 }
1555 #endif
1556 }
1557
loopfilter_frame(VP9_COMP * cpi,VP9_COMMON * cm)1558 static void loopfilter_frame(VP9_COMP *cpi, VP9_COMMON *cm) {
1559 MACROBLOCKD *xd = &cpi->mb.e_mbd;
1560 struct loopfilter *lf = &cm->lf;
1561 if (xd->lossless) {
1562 lf->filter_level = 0;
1563 } else {
1564 struct vpx_usec_timer timer;
1565
1566 vp9_clear_system_state();
1567
1568 vpx_usec_timer_start(&timer);
1569
1570 vp9_pick_filter_level(cpi->Source, cpi, cpi->sf.lpf_pick);
1571
1572 vpx_usec_timer_mark(&timer);
1573 cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
1574 }
1575
1576 if (lf->filter_level > 0) {
1577 vp9_loop_filter_frame(cm->frame_to_show, cm, xd, lf->filter_level, 0, 0);
1578 }
1579
1580 vp9_extend_frame_inner_borders(cm->frame_to_show);
1581 }
1582
vp9_scale_references(VP9_COMP * cpi)1583 void vp9_scale_references(VP9_COMP *cpi) {
1584 VP9_COMMON *cm = &cpi->common;
1585 MV_REFERENCE_FRAME ref_frame;
1586 const VP9_REFFRAME ref_mask[3] = {VP9_LAST_FLAG, VP9_GOLD_FLAG, VP9_ALT_FLAG};
1587
1588 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
1589 const int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, ref_frame)];
1590 const YV12_BUFFER_CONFIG *const ref = &cm->frame_bufs[idx].buf;
1591
1592 // Need to convert from VP9_REFFRAME to index into ref_mask (subtract 1).
1593 if ((cpi->ref_frame_flags & ref_mask[ref_frame - 1]) &&
1594 (ref->y_crop_width != cm->width || ref->y_crop_height != cm->height)) {
1595 const int new_fb = get_free_fb(cm);
1596 vp9_realloc_frame_buffer(&cm->frame_bufs[new_fb].buf,
1597 cm->width, cm->height,
1598 cm->subsampling_x, cm->subsampling_y,
1599 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL);
1600 scale_and_extend_frame(ref, &cm->frame_bufs[new_fb].buf);
1601 cpi->scaled_ref_idx[ref_frame - 1] = new_fb;
1602 } else {
1603 cpi->scaled_ref_idx[ref_frame - 1] = idx;
1604 cm->frame_bufs[idx].ref_count++;
1605 }
1606 }
1607 }
1608
release_scaled_references(VP9_COMP * cpi)1609 static void release_scaled_references(VP9_COMP *cpi) {
1610 VP9_COMMON *cm = &cpi->common;
1611 int i;
1612
1613 for (i = 0; i < 3; i++)
1614 cm->frame_bufs[cpi->scaled_ref_idx[i]].ref_count--;
1615 }
1616
full_to_model_count(unsigned int * model_count,unsigned int * full_count)1617 static void full_to_model_count(unsigned int *model_count,
1618 unsigned int *full_count) {
1619 int n;
1620 model_count[ZERO_TOKEN] = full_count[ZERO_TOKEN];
1621 model_count[ONE_TOKEN] = full_count[ONE_TOKEN];
1622 model_count[TWO_TOKEN] = full_count[TWO_TOKEN];
1623 for (n = THREE_TOKEN; n < EOB_TOKEN; ++n)
1624 model_count[TWO_TOKEN] += full_count[n];
1625 model_count[EOB_MODEL_TOKEN] = full_count[EOB_TOKEN];
1626 }
1627
full_to_model_counts(vp9_coeff_count_model * model_count,vp9_coeff_count * full_count)1628 static void full_to_model_counts(vp9_coeff_count_model *model_count,
1629 vp9_coeff_count *full_count) {
1630 int i, j, k, l;
1631
1632 for (i = 0; i < PLANE_TYPES; ++i)
1633 for (j = 0; j < REF_TYPES; ++j)
1634 for (k = 0; k < COEF_BANDS; ++k)
1635 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
1636 full_to_model_count(model_count[i][j][k][l], full_count[i][j][k][l]);
1637 }
1638
1639 #if 0 && CONFIG_INTERNAL_STATS
1640 static void output_frame_level_debug_stats(VP9_COMP *cpi) {
1641 VP9_COMMON *const cm = &cpi->common;
1642 FILE *const f = fopen("tmp.stt", cm->current_video_frame ? "a" : "w");
1643 int recon_err;
1644
1645 vp9_clear_system_state();
1646
1647 recon_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
1648
1649 if (cpi->twopass.total_left_stats.coded_error != 0.0)
1650 fprintf(f, "%10u %10d %10d %10d %10d"
1651 "%10"PRId64" %10"PRId64" %10"PRId64" %10"PRId64" %10d "
1652 "%7.2lf %7.2lf %7.2lf %7.2lf %7.2lf"
1653 "%6d %6d %5d %5d %5d "
1654 "%10"PRId64" %10.3lf"
1655 "%10lf %8u %10d %10d %10d\n",
1656 cpi->common.current_video_frame, cpi->rc.this_frame_target,
1657 cpi->rc.projected_frame_size,
1658 cpi->rc.projected_frame_size / cpi->common.MBs,
1659 (cpi->rc.projected_frame_size - cpi->rc.this_frame_target),
1660 cpi->rc.vbr_bits_off_target,
1661 cpi->rc.total_target_vs_actual,
1662 (cpi->rc.starting_buffer_level - cpi->rc.bits_off_target),
1663 cpi->rc.total_actual_bits, cm->base_qindex,
1664 vp9_convert_qindex_to_q(cm->base_qindex),
1665 (double)vp9_dc_quant(cm->base_qindex, 0) / 4.0,
1666 vp9_convert_qindex_to_q(cpi->twopass.active_worst_quality),
1667 cpi->rc.avg_q,
1668 vp9_convert_qindex_to_q(cpi->oxcf.cq_level),
1669 cpi->refresh_last_frame, cpi->refresh_golden_frame,
1670 cpi->refresh_alt_ref_frame, cm->frame_type, cpi->rc.gfu_boost,
1671 cpi->twopass.bits_left,
1672 cpi->twopass.total_left_stats.coded_error,
1673 cpi->twopass.bits_left /
1674 (1 + cpi->twopass.total_left_stats.coded_error),
1675 cpi->tot_recode_hits, recon_err, cpi->rc.kf_boost,
1676 cpi->twopass.kf_zeromotion_pct);
1677
1678 fclose(f);
1679
1680 if (0) {
1681 FILE *const fmodes = fopen("Modes.stt", "a");
1682 int i;
1683
1684 fprintf(fmodes, "%6d:%1d:%1d:%1d ", cpi->common.current_video_frame,
1685 cm->frame_type, cpi->refresh_golden_frame,
1686 cpi->refresh_alt_ref_frame);
1687
1688 for (i = 0; i < MAX_MODES; ++i)
1689 fprintf(fmodes, "%5d ", cpi->mode_chosen_counts[i]);
1690
1691 fprintf(fmodes, "\n");
1692
1693 fclose(fmodes);
1694 }
1695 }
1696 #endif
1697
encode_without_recode_loop(VP9_COMP * cpi,int q)1698 static void encode_without_recode_loop(VP9_COMP *cpi,
1699 int q) {
1700 VP9_COMMON *const cm = &cpi->common;
1701 vp9_clear_system_state();
1702 vp9_set_quantizer(cm, q);
1703 setup_frame(cpi);
1704 // Variance adaptive and in frame q adjustment experiments are mutually
1705 // exclusive.
1706 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
1707 vp9_vaq_frame_setup(cpi);
1708 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1709 vp9_setup_in_frame_q_adj(cpi);
1710 } else if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ) {
1711 vp9_cyclic_refresh_setup(cpi);
1712 }
1713 // transform / motion compensation build reconstruction frame
1714 vp9_encode_frame(cpi);
1715
1716 // Update the skip mb flag probabilities based on the distribution
1717 // seen in the last encoder iteration.
1718 // update_base_skip_probs(cpi);
1719 vp9_clear_system_state();
1720 }
1721
encode_with_recode_loop(VP9_COMP * cpi,size_t * size,uint8_t * dest,int q,int bottom_index,int top_index)1722 static void encode_with_recode_loop(VP9_COMP *cpi,
1723 size_t *size,
1724 uint8_t *dest,
1725 int q,
1726 int bottom_index,
1727 int top_index) {
1728 VP9_COMMON *const cm = &cpi->common;
1729 RATE_CONTROL *const rc = &cpi->rc;
1730 int loop_count = 0;
1731 int loop = 0;
1732 int overshoot_seen = 0;
1733 int undershoot_seen = 0;
1734 int q_low = bottom_index, q_high = top_index;
1735 int frame_over_shoot_limit;
1736 int frame_under_shoot_limit;
1737
1738 // Decide frame size bounds
1739 vp9_rc_compute_frame_size_bounds(cpi, rc->this_frame_target,
1740 &frame_under_shoot_limit,
1741 &frame_over_shoot_limit);
1742
1743 do {
1744 vp9_clear_system_state();
1745
1746 vp9_set_quantizer(cm, q);
1747
1748 if (loop_count == 0)
1749 setup_frame(cpi);
1750
1751 // Variance adaptive and in frame q adjustment experiments are mutually
1752 // exclusive.
1753 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
1754 vp9_vaq_frame_setup(cpi);
1755 } else if (cpi->oxcf.aq_mode == COMPLEXITY_AQ) {
1756 vp9_setup_in_frame_q_adj(cpi);
1757 }
1758
1759 // transform / motion compensation build reconstruction frame
1760 vp9_encode_frame(cpi);
1761
1762 // Update the skip mb flag probabilities based on the distribution
1763 // seen in the last encoder iteration.
1764 // update_base_skip_probs(cpi);
1765
1766 vp9_clear_system_state();
1767
1768 // Dummy pack of the bitstream using up to date stats to get an
1769 // accurate estimate of output frame size to determine if we need
1770 // to recode.
1771 if (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF) {
1772 save_coding_context(cpi);
1773 cpi->dummy_packing = 1;
1774 if (!cpi->sf.use_nonrd_pick_mode)
1775 vp9_pack_bitstream(cpi, dest, size);
1776
1777 rc->projected_frame_size = (int)(*size) << 3;
1778 restore_coding_context(cpi);
1779
1780 if (frame_over_shoot_limit == 0)
1781 frame_over_shoot_limit = 1;
1782 }
1783
1784 if (cpi->oxcf.rc_mode == VPX_Q) {
1785 loop = 0;
1786 } else {
1787 if ((cm->frame_type == KEY_FRAME) &&
1788 rc->this_key_frame_forced &&
1789 (rc->projected_frame_size < rc->max_frame_bandwidth)) {
1790 int last_q = q;
1791 int kf_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
1792
1793 int high_err_target = cpi->ambient_err;
1794 int low_err_target = cpi->ambient_err >> 1;
1795
1796 // Prevent possible divide by zero error below for perfect KF
1797 kf_err += !kf_err;
1798
1799 // The key frame is not good enough or we can afford
1800 // to make it better without undue risk of popping.
1801 if ((kf_err > high_err_target &&
1802 rc->projected_frame_size <= frame_over_shoot_limit) ||
1803 (kf_err > low_err_target &&
1804 rc->projected_frame_size <= frame_under_shoot_limit)) {
1805 // Lower q_high
1806 q_high = q > q_low ? q - 1 : q_low;
1807
1808 // Adjust Q
1809 q = (q * high_err_target) / kf_err;
1810 q = MIN(q, (q_high + q_low) >> 1);
1811 } else if (kf_err < low_err_target &&
1812 rc->projected_frame_size >= frame_under_shoot_limit) {
1813 // The key frame is much better than the previous frame
1814 // Raise q_low
1815 q_low = q < q_high ? q + 1 : q_high;
1816
1817 // Adjust Q
1818 q = (q * low_err_target) / kf_err;
1819 q = MIN(q, (q_high + q_low + 1) >> 1);
1820 }
1821
1822 // Clamp Q to upper and lower limits:
1823 q = clamp(q, q_low, q_high);
1824
1825 loop = q != last_q;
1826 } else if (recode_loop_test(
1827 cpi, frame_over_shoot_limit, frame_under_shoot_limit,
1828 q, MAX(q_high, top_index), bottom_index)) {
1829 // Is the projected frame size out of range and are we allowed
1830 // to attempt to recode.
1831 int last_q = q;
1832 int retries = 0;
1833
1834 // Frame size out of permitted range:
1835 // Update correction factor & compute new Q to try...
1836
1837 // Frame is too large
1838 if (rc->projected_frame_size > rc->this_frame_target) {
1839 // Special case if the projected size is > the max allowed.
1840 if (rc->projected_frame_size >= rc->max_frame_bandwidth)
1841 q_high = rc->worst_quality;
1842
1843 // Raise Qlow as to at least the current value
1844 q_low = q < q_high ? q + 1 : q_high;
1845
1846 if (undershoot_seen || loop_count > 1) {
1847 // Update rate_correction_factor unless
1848 vp9_rc_update_rate_correction_factors(cpi, 1);
1849
1850 q = (q_high + q_low + 1) / 2;
1851 } else {
1852 // Update rate_correction_factor unless
1853 vp9_rc_update_rate_correction_factors(cpi, 0);
1854
1855 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1856 bottom_index, MAX(q_high, top_index));
1857
1858 while (q < q_low && retries < 10) {
1859 vp9_rc_update_rate_correction_factors(cpi, 0);
1860 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1861 bottom_index, MAX(q_high, top_index));
1862 retries++;
1863 }
1864 }
1865
1866 overshoot_seen = 1;
1867 } else {
1868 // Frame is too small
1869 q_high = q > q_low ? q - 1 : q_low;
1870
1871 if (overshoot_seen || loop_count > 1) {
1872 vp9_rc_update_rate_correction_factors(cpi, 1);
1873 q = (q_high + q_low) / 2;
1874 } else {
1875 vp9_rc_update_rate_correction_factors(cpi, 0);
1876 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1877 bottom_index, top_index);
1878 // Special case reset for qlow for constrained quality.
1879 // This should only trigger where there is very substantial
1880 // undershoot on a frame and the auto cq level is above
1881 // the user passsed in value.
1882 if (cpi->oxcf.rc_mode == VPX_CQ &&
1883 q < q_low) {
1884 q_low = q;
1885 }
1886
1887 while (q > q_high && retries < 10) {
1888 vp9_rc_update_rate_correction_factors(cpi, 0);
1889 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1890 bottom_index, top_index);
1891 retries++;
1892 }
1893 }
1894
1895 undershoot_seen = 1;
1896 }
1897
1898 // Clamp Q to upper and lower limits:
1899 q = clamp(q, q_low, q_high);
1900
1901 loop = q != last_q;
1902 } else {
1903 loop = 0;
1904 }
1905 }
1906
1907 // Special case for overlay frame.
1908 if (rc->is_src_frame_alt_ref &&
1909 rc->projected_frame_size < rc->max_frame_bandwidth)
1910 loop = 0;
1911
1912 if (loop) {
1913 loop_count++;
1914
1915 #if CONFIG_INTERNAL_STATS
1916 cpi->tot_recode_hits++;
1917 #endif
1918 }
1919 } while (loop);
1920 }
1921
get_ref_frame_flags(VP9_COMP * cpi)1922 static void get_ref_frame_flags(VP9_COMP *cpi) {
1923 if (cpi->refresh_last_frame & cpi->refresh_golden_frame)
1924 cpi->gold_is_last = 1;
1925 else if (cpi->refresh_last_frame ^ cpi->refresh_golden_frame)
1926 cpi->gold_is_last = 0;
1927
1928 if (cpi->refresh_last_frame & cpi->refresh_alt_ref_frame)
1929 cpi->alt_is_last = 1;
1930 else if (cpi->refresh_last_frame ^ cpi->refresh_alt_ref_frame)
1931 cpi->alt_is_last = 0;
1932
1933 if (cpi->refresh_alt_ref_frame & cpi->refresh_golden_frame)
1934 cpi->gold_is_alt = 1;
1935 else if (cpi->refresh_alt_ref_frame ^ cpi->refresh_golden_frame)
1936 cpi->gold_is_alt = 0;
1937
1938 cpi->ref_frame_flags = VP9_ALT_FLAG | VP9_GOLD_FLAG | VP9_LAST_FLAG;
1939
1940 if (cpi->gold_is_last)
1941 cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
1942
1943 if (cpi->rc.frames_till_gf_update_due == INT_MAX &&
1944 !is_spatial_svc(cpi))
1945 cpi->ref_frame_flags &= ~VP9_GOLD_FLAG;
1946
1947 if (cpi->alt_is_last)
1948 cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
1949
1950 if (cpi->gold_is_alt)
1951 cpi->ref_frame_flags &= ~VP9_ALT_FLAG;
1952 }
1953
set_ext_overrides(VP9_COMP * cpi)1954 static void set_ext_overrides(VP9_COMP *cpi) {
1955 // Overrides the defaults with the externally supplied values with
1956 // vp9_update_reference() and vp9_update_entropy() calls
1957 // Note: The overrides are valid only for the next frame passed
1958 // to encode_frame_to_data_rate() function
1959 if (cpi->ext_refresh_frame_context_pending) {
1960 cpi->common.refresh_frame_context = cpi->ext_refresh_frame_context;
1961 cpi->ext_refresh_frame_context_pending = 0;
1962 }
1963 if (cpi->ext_refresh_frame_flags_pending) {
1964 cpi->refresh_last_frame = cpi->ext_refresh_last_frame;
1965 cpi->refresh_golden_frame = cpi->ext_refresh_golden_frame;
1966 cpi->refresh_alt_ref_frame = cpi->ext_refresh_alt_ref_frame;
1967 cpi->ext_refresh_frame_flags_pending = 0;
1968 }
1969 }
1970
vp9_scale_if_required(VP9_COMMON * cm,YV12_BUFFER_CONFIG * unscaled,YV12_BUFFER_CONFIG * scaled)1971 YV12_BUFFER_CONFIG *vp9_scale_if_required(VP9_COMMON *cm,
1972 YV12_BUFFER_CONFIG *unscaled,
1973 YV12_BUFFER_CONFIG *scaled) {
1974 if (cm->mi_cols * MI_SIZE != unscaled->y_width ||
1975 cm->mi_rows * MI_SIZE != unscaled->y_height) {
1976 scale_and_extend_frame_nonnormative(unscaled, scaled);
1977 return scaled;
1978 } else {
1979 return unscaled;
1980 }
1981 }
1982
configure_skippable_frame(VP9_COMP * cpi)1983 static void configure_skippable_frame(VP9_COMP *cpi) {
1984 // If the current frame does not have non-zero motion vector detected in the
1985 // first pass, and so do its previous and forward frames, then this frame
1986 // can be skipped for partition check, and the partition size is assigned
1987 // according to the variance
1988
1989 SVC *const svc = &cpi->svc;
1990 TWO_PASS *const twopass = is_spatial_svc(cpi) ?
1991 &svc->layer_context[svc->spatial_layer_id].twopass
1992 : &cpi->twopass;
1993
1994 cpi->skippable_frame = (!frame_is_intra_only(&cpi->common) &&
1995 twopass->stats_in - 2 > twopass->stats_in_start &&
1996 twopass->stats_in < twopass->stats_in_end &&
1997 (twopass->stats_in - 1)->pcnt_inter - (twopass->stats_in - 1)->pcnt_motion
1998 == 1 &&
1999 (twopass->stats_in - 2)->pcnt_inter - (twopass->stats_in - 2)->pcnt_motion
2000 == 1 &&
2001 twopass->stats_in->pcnt_inter - twopass->stats_in->pcnt_motion == 1);
2002 }
2003
set_arf_sign_bias(VP9_COMP * cpi)2004 static void set_arf_sign_bias(VP9_COMP *cpi) {
2005 VP9_COMMON *const cm = &cpi->common;
2006 int arf_sign_bias;
2007
2008 if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
2009 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2010 arf_sign_bias = cpi->rc.source_alt_ref_active &&
2011 (!cpi->refresh_alt_ref_frame ||
2012 (gf_group->rf_level[gf_group->index] == GF_ARF_LOW));
2013 } else {
2014 arf_sign_bias =
2015 (cpi->rc.source_alt_ref_active && !cpi->refresh_alt_ref_frame);
2016 }
2017 cm->ref_frame_sign_bias[ALTREF_FRAME] = arf_sign_bias;
2018 }
2019
encode_frame_to_data_rate(VP9_COMP * cpi,size_t * size,uint8_t * dest,unsigned int * frame_flags)2020 static void encode_frame_to_data_rate(VP9_COMP *cpi,
2021 size_t *size,
2022 uint8_t *dest,
2023 unsigned int *frame_flags) {
2024 VP9_COMMON *const cm = &cpi->common;
2025 TX_SIZE t;
2026 int q;
2027 int top_index;
2028 int bottom_index;
2029
2030 const SPEED_FEATURES *const sf = &cpi->sf;
2031 const unsigned int max_mv_def = MIN(cm->width, cm->height);
2032 struct segmentation *const seg = &cm->seg;
2033 set_ext_overrides(cpi);
2034
2035 cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
2036 &cpi->scaled_source);
2037
2038 if (cpi->unscaled_last_source != NULL)
2039 cpi->Last_Source = vp9_scale_if_required(cm, cpi->unscaled_last_source,
2040 &cpi->scaled_last_source);
2041
2042 vp9_scale_references(cpi);
2043
2044 vp9_clear_system_state();
2045
2046 // Enable or disable mode based tweaking of the zbin.
2047 // For 2 pass only used where GF/ARF prediction quality
2048 // is above a threshold.
2049 cpi->zbin_mode_boost = 0;
2050 cpi->zbin_mode_boost_enabled = 0;
2051
2052 // Set the arf sign bias for this frame.
2053 set_arf_sign_bias(cpi);
2054
2055 // Set default state for segment based loop filter update flags.
2056 cm->lf.mode_ref_delta_update = 0;
2057
2058 // Initialize cpi->mv_step_param to default based on max resolution.
2059 cpi->mv_step_param = vp9_init_search_range(max_mv_def);
2060 // Initialize cpi->max_mv_magnitude and cpi->mv_step_param if appropriate.
2061 if (sf->mv.auto_mv_step_size) {
2062 if (frame_is_intra_only(cm)) {
2063 // Initialize max_mv_magnitude for use in the first INTER frame
2064 // after a key/intra-only frame.
2065 cpi->max_mv_magnitude = max_mv_def;
2066 } else {
2067 if (cm->show_frame)
2068 // Allow mv_steps to correspond to twice the max mv magnitude found
2069 // in the previous frame, capped by the default max_mv_magnitude based
2070 // on resolution.
2071 cpi->mv_step_param = vp9_init_search_range(MIN(max_mv_def, 2 *
2072 cpi->max_mv_magnitude));
2073 cpi->max_mv_magnitude = 0;
2074 }
2075 }
2076
2077 // Set various flags etc to special state if it is a key frame.
2078 if (frame_is_intra_only(cm)) {
2079 // Reset the loop filter deltas and segmentation map.
2080 vp9_reset_segment_features(&cm->seg);
2081
2082 // If segmentation is enabled force a map update for key frames.
2083 if (seg->enabled) {
2084 seg->update_map = 1;
2085 seg->update_data = 1;
2086 }
2087
2088 // The alternate reference frame cannot be active for a key frame.
2089 cpi->rc.source_alt_ref_active = 0;
2090
2091 cm->error_resilient_mode = (cpi->oxcf.error_resilient_mode != 0);
2092 cm->frame_parallel_decoding_mode =
2093 (cpi->oxcf.frame_parallel_decoding_mode != 0);
2094
2095 // By default, encoder assumes decoder can use prev_mi.
2096 if (cm->error_resilient_mode) {
2097 cm->frame_parallel_decoding_mode = 1;
2098 cm->reset_frame_context = 0;
2099 cm->refresh_frame_context = 0;
2100 } else if (cm->intra_only) {
2101 // Only reset the current context.
2102 cm->reset_frame_context = 2;
2103 }
2104 }
2105
2106 // Configure experimental use of segmentation for enhanced coding of
2107 // static regions if indicated.
2108 // Only allowed in second pass of two pass (as requires lagged coding)
2109 // and if the relevant speed feature flag is set.
2110 if (cpi->oxcf.pass == 2 && cpi->sf.static_segmentation)
2111 configure_static_seg_features(cpi);
2112
2113 // Check if the current frame is skippable for the partition search in the
2114 // second pass according to the first pass stats
2115 if (cpi->oxcf.pass == 2 &&
2116 (!cpi->use_svc || is_spatial_svc(cpi))) {
2117 configure_skippable_frame(cpi);
2118 }
2119
2120 // For 1 pass CBR, check if we are dropping this frame.
2121 // Never drop on key frame.
2122 if (cpi->oxcf.pass == 0 &&
2123 cpi->oxcf.rc_mode == VPX_CBR &&
2124 cm->frame_type != KEY_FRAME) {
2125 if (vp9_rc_drop_frame(cpi)) {
2126 vp9_rc_postencode_update_drop_frame(cpi);
2127 ++cm->current_video_frame;
2128 return;
2129 }
2130 }
2131
2132 vp9_clear_system_state();
2133
2134 #if CONFIG_VP9_POSTPROC
2135 if (cpi->oxcf.noise_sensitivity > 0) {
2136 int l = 0;
2137 switch (cpi->oxcf.noise_sensitivity) {
2138 case 1:
2139 l = 20;
2140 break;
2141 case 2:
2142 l = 40;
2143 break;
2144 case 3:
2145 l = 60;
2146 break;
2147 case 4:
2148 case 5:
2149 l = 100;
2150 break;
2151 case 6:
2152 l = 150;
2153 break;
2154 }
2155 vp9_denoise(cpi->Source, cpi->Source, l);
2156 }
2157 #endif
2158
2159 set_speed_features(cpi);
2160
2161 // Decide q and q bounds.
2162 q = vp9_rc_pick_q_and_bounds(cpi, &bottom_index, &top_index);
2163
2164 if (!frame_is_intra_only(cm)) {
2165 cm->interp_filter = cpi->sf.default_interp_filter;
2166 /* TODO: Decide this more intelligently */
2167 vp9_set_high_precision_mv(cpi, q < HIGH_PRECISION_MV_QTHRESH);
2168 }
2169
2170 if (cpi->sf.recode_loop == DISALLOW_RECODE) {
2171 encode_without_recode_loop(cpi, q);
2172 } else {
2173 encode_with_recode_loop(cpi, size, dest, q, bottom_index, top_index);
2174 }
2175
2176 #if CONFIG_VP9_TEMPORAL_DENOISING
2177 #ifdef OUTPUT_YUV_DENOISED
2178 if (cpi->oxcf.noise_sensitivity > 0) {
2179 vp9_write_yuv_frame_420(&cpi->denoiser.running_avg_y[INTRA_FRAME],
2180 yuv_denoised_file);
2181 }
2182 #endif
2183 #endif
2184
2185
2186 // Special case code to reduce pulsing when key frames are forced at a
2187 // fixed interval. Note the reconstruction error if it is the frame before
2188 // the force key frame
2189 if (cpi->rc.next_key_frame_forced && cpi->rc.frames_to_key == 1) {
2190 cpi->ambient_err = vp9_get_y_sse(cpi->Source, get_frame_new_buffer(cm));
2191 }
2192
2193 // If the encoder forced a KEY_FRAME decision
2194 if (cm->frame_type == KEY_FRAME)
2195 cpi->refresh_last_frame = 1;
2196
2197 cm->frame_to_show = get_frame_new_buffer(cm);
2198
2199 #if WRITE_RECON_BUFFER
2200 if (cm->show_frame)
2201 write_cx_frame_to_file(cm->frame_to_show,
2202 cm->current_video_frame);
2203 else
2204 write_cx_frame_to_file(cm->frame_to_show,
2205 cm->current_video_frame + 1000);
2206 #endif
2207
2208 // Pick the loop filter level for the frame.
2209 loopfilter_frame(cpi, cm);
2210
2211 #if WRITE_RECON_BUFFER
2212 if (cm->show_frame)
2213 write_cx_frame_to_file(cm->frame_to_show,
2214 cm->current_video_frame + 2000);
2215 else
2216 write_cx_frame_to_file(cm->frame_to_show,
2217 cm->current_video_frame + 3000);
2218 #endif
2219
2220 // build the bitstream
2221 cpi->dummy_packing = 0;
2222 vp9_pack_bitstream(cpi, dest, size);
2223
2224 if (cm->seg.update_map)
2225 update_reference_segmentation_map(cpi);
2226
2227 release_scaled_references(cpi);
2228 vp9_update_reference_frames(cpi);
2229
2230 for (t = TX_4X4; t <= TX_32X32; t++)
2231 full_to_model_counts(cm->counts.coef[t], cpi->coef_counts[t]);
2232
2233 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode)
2234 vp9_adapt_coef_probs(cm);
2235
2236 if (!frame_is_intra_only(cm)) {
2237 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
2238 vp9_adapt_mode_probs(cm);
2239 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
2240 }
2241 }
2242
2243 if (cpi->refresh_golden_frame == 1)
2244 cpi->frame_flags |= FRAMEFLAGS_GOLDEN;
2245 else
2246 cpi->frame_flags &= ~FRAMEFLAGS_GOLDEN;
2247
2248 if (cpi->refresh_alt_ref_frame == 1)
2249 cpi->frame_flags |= FRAMEFLAGS_ALTREF;
2250 else
2251 cpi->frame_flags &= ~FRAMEFLAGS_ALTREF;
2252
2253 get_ref_frame_flags(cpi);
2254
2255 cm->last_frame_type = cm->frame_type;
2256 vp9_rc_postencode_update(cpi, *size);
2257
2258 #if 0
2259 output_frame_level_debug_stats(cpi);
2260 #endif
2261
2262 if (cm->frame_type == KEY_FRAME) {
2263 // Tell the caller that the frame was coded as a key frame
2264 *frame_flags = cpi->frame_flags | FRAMEFLAGS_KEY;
2265 } else {
2266 *frame_flags = cpi->frame_flags & ~FRAMEFLAGS_KEY;
2267 }
2268
2269 // Clear the one shot update flags for segmentation map and mode/ref loop
2270 // filter deltas.
2271 cm->seg.update_map = 0;
2272 cm->seg.update_data = 0;
2273 cm->lf.mode_ref_delta_update = 0;
2274
2275 // keep track of the last coded dimensions
2276 cm->last_width = cm->width;
2277 cm->last_height = cm->height;
2278
2279 // reset to normal state now that we are done.
2280 if (!cm->show_existing_frame)
2281 cm->last_show_frame = cm->show_frame;
2282
2283 if (cm->show_frame) {
2284 vp9_swap_mi_and_prev_mi(cm);
2285
2286 // Don't increment frame counters if this was an altref buffer
2287 // update not a real frame
2288 ++cm->current_video_frame;
2289 if (cpi->use_svc)
2290 vp9_inc_frame_in_layer(&cpi->svc);
2291 }
2292 }
2293
SvcEncode(VP9_COMP * cpi,size_t * size,uint8_t * dest,unsigned int * frame_flags)2294 static void SvcEncode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
2295 unsigned int *frame_flags) {
2296 vp9_rc_get_svc_params(cpi);
2297 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2298 }
2299
Pass0Encode(VP9_COMP * cpi,size_t * size,uint8_t * dest,unsigned int * frame_flags)2300 static void Pass0Encode(VP9_COMP *cpi, size_t *size, uint8_t *dest,
2301 unsigned int *frame_flags) {
2302 if (cpi->oxcf.rc_mode == VPX_CBR) {
2303 vp9_rc_get_one_pass_cbr_params(cpi);
2304 } else {
2305 vp9_rc_get_one_pass_vbr_params(cpi);
2306 }
2307 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2308 }
2309
Pass2Encode(VP9_COMP * cpi,size_t * size,uint8_t * dest,unsigned int * frame_flags)2310 static void Pass2Encode(VP9_COMP *cpi, size_t *size,
2311 uint8_t *dest, unsigned int *frame_flags) {
2312 cpi->allow_encode_breakout = ENCODE_BREAKOUT_ENABLED;
2313
2314 vp9_rc_get_second_pass_params(cpi);
2315 encode_frame_to_data_rate(cpi, size, dest, frame_flags);
2316
2317 vp9_twopass_postencode_update(cpi);
2318 }
2319
init_motion_estimation(VP9_COMP * cpi)2320 static void init_motion_estimation(VP9_COMP *cpi) {
2321 int y_stride = cpi->scaled_source.y_stride;
2322
2323 if (cpi->sf.mv.search_method == NSTEP) {
2324 vp9_init3smotion_compensation(&cpi->ss_cfg, y_stride);
2325 } else if (cpi->sf.mv.search_method == DIAMOND) {
2326 vp9_init_dsmotion_compensation(&cpi->ss_cfg, y_stride);
2327 }
2328 }
2329
check_initial_width(VP9_COMP * cpi,int subsampling_x,int subsampling_y)2330 static void check_initial_width(VP9_COMP *cpi, int subsampling_x,
2331 int subsampling_y) {
2332 VP9_COMMON *const cm = &cpi->common;
2333
2334 if (!cpi->initial_width) {
2335 cm->subsampling_x = subsampling_x;
2336 cm->subsampling_y = subsampling_y;
2337
2338 alloc_raw_frame_buffers(cpi);
2339 alloc_ref_frame_buffers(cpi);
2340 alloc_util_frame_buffers(cpi);
2341
2342 init_motion_estimation(cpi);
2343
2344 cpi->initial_width = cm->width;
2345 cpi->initial_height = cm->height;
2346 }
2347 }
2348
2349
vp9_receive_raw_frame(VP9_COMP * cpi,unsigned int frame_flags,YV12_BUFFER_CONFIG * sd,int64_t time_stamp,int64_t end_time)2350 int vp9_receive_raw_frame(VP9_COMP *cpi, unsigned int frame_flags,
2351 YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
2352 int64_t end_time) {
2353 VP9_COMMON *cm = &cpi->common;
2354 struct vpx_usec_timer timer;
2355 int res = 0;
2356 const int subsampling_x = sd->uv_width < sd->y_width;
2357 const int subsampling_y = sd->uv_height < sd->y_height;
2358
2359 check_initial_width(cpi, subsampling_x, subsampling_y);
2360
2361 vpx_usec_timer_start(&timer);
2362
2363 #if CONFIG_SPATIAL_SVC
2364 if (is_spatial_svc(cpi))
2365 res = vp9_svc_lookahead_push(cpi, cpi->lookahead, sd, time_stamp, end_time,
2366 frame_flags);
2367 else
2368 #endif
2369 res = vp9_lookahead_push(cpi->lookahead,
2370 sd, time_stamp, end_time, frame_flags);
2371 if (res)
2372 res = -1;
2373 vpx_usec_timer_mark(&timer);
2374 cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
2375
2376 if ((cm->profile == PROFILE_0 || cm->profile == PROFILE_2) &&
2377 (subsampling_x != 1 || subsampling_y != 1)) {
2378 vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
2379 "Non-4:2:0 color space requires profile 1 or 3");
2380 res = -1;
2381 }
2382 if ((cm->profile == PROFILE_1 || cm->profile == PROFILE_3) &&
2383 (subsampling_x == 1 && subsampling_y == 1)) {
2384 vpx_internal_error(&cm->error, VPX_CODEC_INVALID_PARAM,
2385 "4:2:0 color space requires profile 0 or 2");
2386 res = -1;
2387 }
2388
2389 return res;
2390 }
2391
2392
frame_is_reference(const VP9_COMP * cpi)2393 static int frame_is_reference(const VP9_COMP *cpi) {
2394 const VP9_COMMON *cm = &cpi->common;
2395
2396 return cm->frame_type == KEY_FRAME ||
2397 cpi->refresh_last_frame ||
2398 cpi->refresh_golden_frame ||
2399 cpi->refresh_alt_ref_frame ||
2400 cm->refresh_frame_context ||
2401 cm->lf.mode_ref_delta_update ||
2402 cm->seg.update_map ||
2403 cm->seg.update_data;
2404 }
2405
adjust_frame_rate(VP9_COMP * cpi)2406 void adjust_frame_rate(VP9_COMP *cpi) {
2407 int64_t this_duration;
2408 int step = 0;
2409
2410 if (cpi->source->ts_start == cpi->first_time_stamp_ever) {
2411 this_duration = cpi->source->ts_end - cpi->source->ts_start;
2412 step = 1;
2413 } else {
2414 int64_t last_duration = cpi->last_end_time_stamp_seen
2415 - cpi->last_time_stamp_seen;
2416
2417 this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
2418
2419 // do a step update if the duration changes by 10%
2420 if (last_duration)
2421 step = (int)((this_duration - last_duration) * 10 / last_duration);
2422 }
2423
2424 if (this_duration) {
2425 if (step) {
2426 vp9_new_framerate(cpi, 10000000.0 / this_duration);
2427 } else {
2428 // Average this frame's rate into the last second's average
2429 // frame rate. If we haven't seen 1 second yet, then average
2430 // over the whole interval seen.
2431 const double interval = MIN((double)(cpi->source->ts_end
2432 - cpi->first_time_stamp_ever), 10000000.0);
2433 double avg_duration = 10000000.0 / cpi->oxcf.framerate;
2434 avg_duration *= (interval - avg_duration + this_duration);
2435 avg_duration /= interval;
2436
2437 vp9_new_framerate(cpi, 10000000.0 / avg_duration);
2438 }
2439 }
2440 cpi->last_time_stamp_seen = cpi->source->ts_start;
2441 cpi->last_end_time_stamp_seen = cpi->source->ts_end;
2442 }
2443
2444 // Returns 0 if this is not an alt ref else the offset of the source frame
2445 // used as the arf midpoint.
get_arf_src_index(VP9_COMP * cpi)2446 static int get_arf_src_index(VP9_COMP *cpi) {
2447 RATE_CONTROL *const rc = &cpi->rc;
2448 int arf_src_index = 0;
2449 if (is_altref_enabled(cpi)) {
2450 if (cpi->oxcf.pass == 2) {
2451 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2452 if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
2453 arf_src_index = gf_group->arf_src_offset[gf_group->index];
2454 }
2455 } else if (rc->source_alt_ref_pending) {
2456 arf_src_index = rc->frames_till_gf_update_due;
2457 }
2458 }
2459 return arf_src_index;
2460 }
2461
check_src_altref(VP9_COMP * cpi)2462 static void check_src_altref(VP9_COMP *cpi) {
2463 RATE_CONTROL *const rc = &cpi->rc;
2464
2465 if (cpi->oxcf.pass == 2) {
2466 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2467 rc->is_src_frame_alt_ref =
2468 (gf_group->update_type[gf_group->index] == OVERLAY_UPDATE);
2469 } else {
2470 rc->is_src_frame_alt_ref = cpi->alt_ref_source &&
2471 (cpi->source == cpi->alt_ref_source);
2472 }
2473
2474 if (rc->is_src_frame_alt_ref) {
2475 // Current frame is an ARF overlay frame.
2476 cpi->alt_ref_source = NULL;
2477
2478 // Don't refresh the last buffer for an ARF overlay frame. It will
2479 // become the GF so preserve last as an alternative prediction option.
2480 cpi->refresh_last_frame = 0;
2481 }
2482 }
2483
vp9_get_compressed_data(VP9_COMP * cpi,unsigned int * frame_flags,size_t * size,uint8_t * dest,int64_t * time_stamp,int64_t * time_end,int flush)2484 int vp9_get_compressed_data(VP9_COMP *cpi, unsigned int *frame_flags,
2485 size_t *size, uint8_t *dest,
2486 int64_t *time_stamp, int64_t *time_end, int flush) {
2487 VP9_COMMON *const cm = &cpi->common;
2488 MACROBLOCKD *const xd = &cpi->mb.e_mbd;
2489 RATE_CONTROL *const rc = &cpi->rc;
2490 struct vpx_usec_timer cmptimer;
2491 YV12_BUFFER_CONFIG *force_src_buffer = NULL;
2492 MV_REFERENCE_FRAME ref_frame;
2493 int arf_src_index;
2494
2495 if (!cpi)
2496 return -1;
2497
2498 if (is_spatial_svc(cpi) && cpi->oxcf.pass == 2) {
2499 #if CONFIG_SPATIAL_SVC
2500 vp9_svc_lookahead_peek(cpi, cpi->lookahead, 0, 1);
2501 #endif
2502 vp9_restore_layer_context(cpi);
2503 }
2504
2505 vpx_usec_timer_start(&cmptimer);
2506
2507 cpi->source = NULL;
2508 cpi->last_source = NULL;
2509
2510 vp9_set_high_precision_mv(cpi, ALTREF_HIGH_PRECISION_MV);
2511
2512 // Normal defaults
2513 cm->reset_frame_context = 0;
2514 cm->refresh_frame_context = 1;
2515 cpi->refresh_last_frame = 1;
2516 cpi->refresh_golden_frame = 0;
2517 cpi->refresh_alt_ref_frame = 0;
2518
2519 // Should we encode an arf frame.
2520 arf_src_index = get_arf_src_index(cpi);
2521 if (arf_src_index) {
2522 assert(arf_src_index <= rc->frames_to_key);
2523
2524 #if CONFIG_SPATIAL_SVC
2525 if (is_spatial_svc(cpi))
2526 cpi->source = vp9_svc_lookahead_peek(cpi, cpi->lookahead,
2527 arf_src_index, 0);
2528 else
2529 #endif
2530 cpi->source = vp9_lookahead_peek(cpi->lookahead, arf_src_index);
2531 if (cpi->source != NULL) {
2532 cpi->alt_ref_source = cpi->source;
2533
2534 #if CONFIG_SPATIAL_SVC
2535 if (is_spatial_svc(cpi) && cpi->svc.spatial_layer_id > 0) {
2536 int i;
2537 // Reference a hidden frame from a lower layer
2538 for (i = cpi->svc.spatial_layer_id - 1; i >= 0; --i) {
2539 if (cpi->oxcf.ss_play_alternate[i]) {
2540 cpi->gld_fb_idx = cpi->svc.layer_context[i].alt_ref_idx;
2541 break;
2542 }
2543 }
2544 }
2545 cpi->svc.layer_context[cpi->svc.spatial_layer_id].has_alt_frame = 1;
2546 #endif
2547
2548 if (cpi->oxcf.arnr_max_frames > 0) {
2549 // Produce the filtered ARF frame.
2550 vp9_temporal_filter(cpi, arf_src_index);
2551 vp9_extend_frame_borders(&cpi->alt_ref_buffer);
2552 force_src_buffer = &cpi->alt_ref_buffer;
2553 }
2554
2555 cm->show_frame = 0;
2556 cpi->refresh_alt_ref_frame = 1;
2557 cpi->refresh_golden_frame = 0;
2558 cpi->refresh_last_frame = 0;
2559 rc->is_src_frame_alt_ref = 0;
2560 rc->source_alt_ref_pending = 0;
2561 } else {
2562 rc->source_alt_ref_pending = 0;
2563 }
2564 }
2565
2566 if (!cpi->source) {
2567 // Get last frame source.
2568 if (cm->current_video_frame > 0) {
2569 #if CONFIG_SPATIAL_SVC
2570 if (is_spatial_svc(cpi))
2571 cpi->last_source = vp9_svc_lookahead_peek(cpi, cpi->lookahead, -1, 0);
2572 else
2573 #endif
2574 cpi->last_source = vp9_lookahead_peek(cpi->lookahead, -1);
2575 if (cpi->last_source == NULL)
2576 return -1;
2577 }
2578
2579 // Read in the source frame.
2580 #if CONFIG_SPATIAL_SVC
2581 if (is_spatial_svc(cpi))
2582 cpi->source = vp9_svc_lookahead_pop(cpi, cpi->lookahead, flush);
2583 else
2584 #endif
2585 cpi->source = vp9_lookahead_pop(cpi->lookahead, flush);
2586 if (cpi->source != NULL) {
2587 cm->show_frame = 1;
2588 cm->intra_only = 0;
2589
2590 // Check to see if the frame should be encoded as an arf overlay.
2591 check_src_altref(cpi);
2592 }
2593 }
2594
2595 if (cpi->source) {
2596 cpi->un_scaled_source = cpi->Source = force_src_buffer ? force_src_buffer
2597 : &cpi->source->img;
2598
2599 if (cpi->last_source != NULL) {
2600 cpi->unscaled_last_source = &cpi->last_source->img;
2601 } else {
2602 cpi->unscaled_last_source = NULL;
2603 }
2604
2605 *time_stamp = cpi->source->ts_start;
2606 *time_end = cpi->source->ts_end;
2607 *frame_flags =
2608 (cpi->source->flags & VPX_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
2609
2610 } else {
2611 *size = 0;
2612 if (flush && cpi->oxcf.pass == 1 && !cpi->twopass.first_pass_done) {
2613 vp9_end_first_pass(cpi); /* get last stats packet */
2614 cpi->twopass.first_pass_done = 1;
2615 }
2616 return -1;
2617 }
2618
2619 if (cpi->source->ts_start < cpi->first_time_stamp_ever) {
2620 cpi->first_time_stamp_ever = cpi->source->ts_start;
2621 cpi->last_end_time_stamp_seen = cpi->source->ts_start;
2622 }
2623
2624 // Clear down mmx registers
2625 vp9_clear_system_state();
2626
2627 // adjust frame rates based on timestamps given
2628 if (cm->show_frame) {
2629 adjust_frame_rate(cpi);
2630 }
2631
2632 if (cpi->svc.number_temporal_layers > 1 &&
2633 cpi->oxcf.rc_mode == VPX_CBR) {
2634 vp9_update_temporal_layer_framerate(cpi);
2635 vp9_restore_layer_context(cpi);
2636 }
2637
2638 // start with a 0 size frame
2639 *size = 0;
2640
2641 /* find a free buffer for the new frame, releasing the reference previously
2642 * held.
2643 */
2644 cm->frame_bufs[cm->new_fb_idx].ref_count--;
2645 cm->new_fb_idx = get_free_fb(cm);
2646
2647 if (!cpi->use_svc && cpi->multi_arf_allowed) {
2648 if (cm->frame_type == KEY_FRAME) {
2649 init_buffer_indices(cpi);
2650 } else if (cpi->oxcf.pass == 2) {
2651 const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
2652 cpi->alt_fb_idx = gf_group->arf_ref_idx[gf_group->index];
2653 }
2654 }
2655
2656 cpi->frame_flags = *frame_flags;
2657
2658 if (cpi->oxcf.pass == 2 &&
2659 cm->current_video_frame == 0 &&
2660 cpi->oxcf.allow_spatial_resampling &&
2661 cpi->oxcf.rc_mode == VPX_VBR) {
2662 // Internal scaling is triggered on the first frame.
2663 vp9_set_size_literal(cpi, cpi->oxcf.scaled_frame_width,
2664 cpi->oxcf.scaled_frame_height);
2665 }
2666
2667 // Reset the frame pointers to the current frame size
2668 vp9_realloc_frame_buffer(get_frame_new_buffer(cm),
2669 cm->width, cm->height,
2670 cm->subsampling_x, cm->subsampling_y,
2671 VP9_ENC_BORDER_IN_PIXELS, NULL, NULL, NULL);
2672
2673 alloc_util_frame_buffers(cpi);
2674 init_motion_estimation(cpi);
2675
2676 for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
2677 const int idx = cm->ref_frame_map[get_ref_frame_idx(cpi, ref_frame)];
2678 YV12_BUFFER_CONFIG *const buf = &cm->frame_bufs[idx].buf;
2679 RefBuffer *const ref_buf = &cm->frame_refs[ref_frame - 1];
2680 ref_buf->buf = buf;
2681 ref_buf->idx = idx;
2682 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
2683 buf->y_crop_width, buf->y_crop_height,
2684 cm->width, cm->height);
2685
2686 if (vp9_is_scaled(&ref_buf->sf))
2687 vp9_extend_frame_borders(buf);
2688 }
2689
2690 set_ref_ptrs(cm, xd, LAST_FRAME, LAST_FRAME);
2691
2692 if (cpi->oxcf.aq_mode == VARIANCE_AQ) {
2693 vp9_vaq_init();
2694 }
2695
2696 if (cpi->oxcf.pass == 1 &&
2697 (!cpi->use_svc || is_spatial_svc(cpi))) {
2698 const int lossless = is_lossless_requested(&cpi->oxcf);
2699 cpi->mb.fwd_txm4x4 = lossless ? vp9_fwht4x4 : vp9_fdct4x4;
2700 cpi->mb.itxm_add = lossless ? vp9_iwht4x4_add : vp9_idct4x4_add;
2701 vp9_first_pass(cpi);
2702 } else if (cpi->oxcf.pass == 2 &&
2703 (!cpi->use_svc || is_spatial_svc(cpi))) {
2704 Pass2Encode(cpi, size, dest, frame_flags);
2705 } else if (cpi->use_svc) {
2706 SvcEncode(cpi, size, dest, frame_flags);
2707 } else {
2708 // One pass encode
2709 Pass0Encode(cpi, size, dest, frame_flags);
2710 }
2711
2712 if (cm->refresh_frame_context)
2713 cm->frame_contexts[cm->frame_context_idx] = cm->fc;
2714
2715 // Frame was dropped, release scaled references.
2716 if (*size == 0) {
2717 release_scaled_references(cpi);
2718 }
2719
2720 if (*size > 0) {
2721 cpi->droppable = !frame_is_reference(cpi);
2722 }
2723
2724 // Save layer specific state.
2725 if ((cpi->svc.number_temporal_layers > 1 &&
2726 cpi->oxcf.rc_mode == VPX_CBR) ||
2727 (cpi->svc.number_spatial_layers > 1 && cpi->oxcf.pass == 2)) {
2728 vp9_save_layer_context(cpi);
2729 }
2730
2731 vpx_usec_timer_mark(&cmptimer);
2732 cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
2733
2734 if (cpi->b_calculate_psnr && cpi->oxcf.pass != 1 && cm->show_frame)
2735 generate_psnr_packet(cpi);
2736
2737 #if CONFIG_INTERNAL_STATS
2738
2739 if (cpi->oxcf.pass != 1) {
2740 cpi->bytes += (int)(*size);
2741
2742 if (cm->show_frame) {
2743 cpi->count++;
2744
2745 if (cpi->b_calculate_psnr) {
2746 YV12_BUFFER_CONFIG *orig = cpi->Source;
2747 YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
2748 YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
2749 PSNR_STATS psnr;
2750 calc_psnr(orig, recon, &psnr);
2751
2752 cpi->total += psnr.psnr[0];
2753 cpi->total_y += psnr.psnr[1];
2754 cpi->total_u += psnr.psnr[2];
2755 cpi->total_v += psnr.psnr[3];
2756 cpi->total_sq_error += psnr.sse[0];
2757 cpi->total_samples += psnr.samples[0];
2758
2759 {
2760 PSNR_STATS psnr2;
2761 double frame_ssim2 = 0, weight = 0;
2762 #if CONFIG_VP9_POSTPROC
2763 // TODO(agrange) Add resizing of post-proc buffer in here when the
2764 // encoder is changed to use on-demand buffer allocation.
2765 vp9_deblock(cm->frame_to_show, &cm->post_proc_buffer,
2766 cm->lf.filter_level * 10 / 6);
2767 #endif
2768 vp9_clear_system_state();
2769
2770 calc_psnr(orig, pp, &psnr2);
2771
2772 cpi->totalp += psnr2.psnr[0];
2773 cpi->totalp_y += psnr2.psnr[1];
2774 cpi->totalp_u += psnr2.psnr[2];
2775 cpi->totalp_v += psnr2.psnr[3];
2776 cpi->totalp_sq_error += psnr2.sse[0];
2777 cpi->totalp_samples += psnr2.samples[0];
2778
2779 frame_ssim2 = vp9_calc_ssim(orig, recon, 1, &weight);
2780
2781 cpi->summed_quality += frame_ssim2 * weight;
2782 cpi->summed_weights += weight;
2783
2784 frame_ssim2 = vp9_calc_ssim(orig, &cm->post_proc_buffer, 1, &weight);
2785
2786 cpi->summedp_quality += frame_ssim2 * weight;
2787 cpi->summedp_weights += weight;
2788 #if 0
2789 {
2790 FILE *f = fopen("q_used.stt", "a");
2791 fprintf(f, "%5d : Y%f7.3:U%f7.3:V%f7.3:F%f7.3:S%7.3f\n",
2792 cpi->common.current_video_frame, y2, u2, v2,
2793 frame_psnr2, frame_ssim2);
2794 fclose(f);
2795 }
2796 #endif
2797 }
2798 }
2799
2800 if (cpi->b_calculate_ssimg) {
2801 double y, u, v, frame_all;
2802 frame_all = vp9_calc_ssimg(cpi->Source, cm->frame_to_show, &y, &u, &v);
2803 cpi->total_ssimg_y += y;
2804 cpi->total_ssimg_u += u;
2805 cpi->total_ssimg_v += v;
2806 cpi->total_ssimg_all += frame_all;
2807 }
2808 }
2809 }
2810
2811 #endif
2812 return 0;
2813 }
2814
vp9_get_preview_raw_frame(VP9_COMP * cpi,YV12_BUFFER_CONFIG * dest,vp9_ppflags_t * flags)2815 int vp9_get_preview_raw_frame(VP9_COMP *cpi, YV12_BUFFER_CONFIG *dest,
2816 vp9_ppflags_t *flags) {
2817 VP9_COMMON *cm = &cpi->common;
2818 #if !CONFIG_VP9_POSTPROC
2819 (void)flags;
2820 #endif
2821
2822 if (!cm->show_frame) {
2823 return -1;
2824 } else {
2825 int ret;
2826 #if CONFIG_VP9_POSTPROC
2827 ret = vp9_post_proc_frame(cm, dest, flags);
2828 #else
2829 if (cm->frame_to_show) {
2830 *dest = *cm->frame_to_show;
2831 dest->y_width = cm->width;
2832 dest->y_height = cm->height;
2833 dest->uv_width = cm->width >> cm->subsampling_x;
2834 dest->uv_height = cm->height >> cm->subsampling_y;
2835 ret = 0;
2836 } else {
2837 ret = -1;
2838 }
2839 #endif // !CONFIG_VP9_POSTPROC
2840 vp9_clear_system_state();
2841 return ret;
2842 }
2843 }
2844
vp9_set_active_map(VP9_COMP * cpi,unsigned char * map,int rows,int cols)2845 int vp9_set_active_map(VP9_COMP *cpi, unsigned char *map, int rows, int cols) {
2846 if (rows == cpi->common.mb_rows && cols == cpi->common.mb_cols) {
2847 const int mi_rows = cpi->common.mi_rows;
2848 const int mi_cols = cpi->common.mi_cols;
2849 if (map) {
2850 int r, c;
2851 for (r = 0; r < mi_rows; r++) {
2852 for (c = 0; c < mi_cols; c++) {
2853 cpi->segmentation_map[r * mi_cols + c] =
2854 !map[(r >> 1) * cols + (c >> 1)];
2855 }
2856 }
2857 vp9_enable_segfeature(&cpi->common.seg, 1, SEG_LVL_SKIP);
2858 vp9_enable_segmentation(&cpi->common.seg);
2859 } else {
2860 vp9_disable_segmentation(&cpi->common.seg);
2861 }
2862 return 0;
2863 } else {
2864 return -1;
2865 }
2866 }
2867
vp9_set_internal_size(VP9_COMP * cpi,VPX_SCALING horiz_mode,VPX_SCALING vert_mode)2868 int vp9_set_internal_size(VP9_COMP *cpi,
2869 VPX_SCALING horiz_mode, VPX_SCALING vert_mode) {
2870 VP9_COMMON *cm = &cpi->common;
2871 int hr = 0, hs = 0, vr = 0, vs = 0;
2872
2873 if (horiz_mode > ONETWO || vert_mode > ONETWO)
2874 return -1;
2875
2876 Scale2Ratio(horiz_mode, &hr, &hs);
2877 Scale2Ratio(vert_mode, &vr, &vs);
2878
2879 // always go to the next whole number
2880 cm->width = (hs - 1 + cpi->oxcf.width * hr) / hs;
2881 cm->height = (vs - 1 + cpi->oxcf.height * vr) / vs;
2882 assert(cm->width <= cpi->initial_width);
2883 assert(cm->height <= cpi->initial_height);
2884
2885 update_frame_size(cpi);
2886
2887 return 0;
2888 }
2889
vp9_set_size_literal(VP9_COMP * cpi,unsigned int width,unsigned int height)2890 int vp9_set_size_literal(VP9_COMP *cpi, unsigned int width,
2891 unsigned int height) {
2892 VP9_COMMON *cm = &cpi->common;
2893
2894 check_initial_width(cpi, 1, 1);
2895
2896 if (width) {
2897 cm->width = width;
2898 if (cm->width * 5 < cpi->initial_width) {
2899 cm->width = cpi->initial_width / 5 + 1;
2900 printf("Warning: Desired width too small, changed to %d\n", cm->width);
2901 }
2902 if (cm->width > cpi->initial_width) {
2903 cm->width = cpi->initial_width;
2904 printf("Warning: Desired width too large, changed to %d\n", cm->width);
2905 }
2906 }
2907
2908 if (height) {
2909 cm->height = height;
2910 if (cm->height * 5 < cpi->initial_height) {
2911 cm->height = cpi->initial_height / 5 + 1;
2912 printf("Warning: Desired height too small, changed to %d\n", cm->height);
2913 }
2914 if (cm->height > cpi->initial_height) {
2915 cm->height = cpi->initial_height;
2916 printf("Warning: Desired height too large, changed to %d\n", cm->height);
2917 }
2918 }
2919 assert(cm->width <= cpi->initial_width);
2920 assert(cm->height <= cpi->initial_height);
2921
2922 update_frame_size(cpi);
2923
2924 return 0;
2925 }
2926
vp9_set_svc(VP9_COMP * cpi,int use_svc)2927 void vp9_set_svc(VP9_COMP *cpi, int use_svc) {
2928 cpi->use_svc = use_svc;
2929 return;
2930 }
2931
vp9_get_y_sse(const YV12_BUFFER_CONFIG * a,const YV12_BUFFER_CONFIG * b)2932 int vp9_get_y_sse(const YV12_BUFFER_CONFIG *a, const YV12_BUFFER_CONFIG *b) {
2933 assert(a->y_crop_width == b->y_crop_width);
2934 assert(a->y_crop_height == b->y_crop_height);
2935
2936 return (int)get_sse(a->y_buffer, a->y_stride, b->y_buffer, b->y_stride,
2937 a->y_crop_width, a->y_crop_height);
2938 }
2939
2940
vp9_get_quantizer(VP9_COMP * cpi)2941 int vp9_get_quantizer(VP9_COMP *cpi) {
2942 return cpi->common.base_qindex;
2943 }
2944
vp9_apply_encoding_flags(VP9_COMP * cpi,vpx_enc_frame_flags_t flags)2945 void vp9_apply_encoding_flags(VP9_COMP *cpi, vpx_enc_frame_flags_t flags) {
2946 if (flags & (VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_GF |
2947 VP8_EFLAG_NO_REF_ARF)) {
2948 int ref = 7;
2949
2950 if (flags & VP8_EFLAG_NO_REF_LAST)
2951 ref ^= VP9_LAST_FLAG;
2952
2953 if (flags & VP8_EFLAG_NO_REF_GF)
2954 ref ^= VP9_GOLD_FLAG;
2955
2956 if (flags & VP8_EFLAG_NO_REF_ARF)
2957 ref ^= VP9_ALT_FLAG;
2958
2959 vp9_use_as_reference(cpi, ref);
2960 }
2961
2962 if (flags & (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF |
2963 VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_FORCE_GF |
2964 VP8_EFLAG_FORCE_ARF)) {
2965 int upd = 7;
2966
2967 if (flags & VP8_EFLAG_NO_UPD_LAST)
2968 upd ^= VP9_LAST_FLAG;
2969
2970 if (flags & VP8_EFLAG_NO_UPD_GF)
2971 upd ^= VP9_GOLD_FLAG;
2972
2973 if (flags & VP8_EFLAG_NO_UPD_ARF)
2974 upd ^= VP9_ALT_FLAG;
2975
2976 vp9_update_reference(cpi, upd);
2977 }
2978
2979 if (flags & VP8_EFLAG_NO_UPD_ENTROPY) {
2980 vp9_update_entropy(cpi, 0);
2981 }
2982 }
2983