2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
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.
12 #include "vpx_config.h"
15 #include "vp8/common/common.h"
17 #include "vp8/common/extend.h"
18 #include "vp8/common/entropymode.h"
19 #include "vp8/common/quant_common.h"
20 #include "segmentation.h"
21 #include "vp8/common/setupintrarecon.h"
22 #include "encodeintra.h"
23 #include "vp8/common/reconinter.h"
25 #include "pickinter.h"
26 #include "vp8/common/findnearmv.h"
29 #include "vp8/common/invtrans.h"
30 #include "vpx_ports/vpx_timer.h"
31 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
32 #include "bitstream.h"
35 extern void vp8_stuff_mb(VP8_COMP *cpi, MACROBLOCKD *x, TOKENEXTRA **t) ;
36 extern void vp8_calc_ref_frame_costs(int *ref_frame_cost,
41 extern void vp8_convert_rfct_to_prob(VP8_COMP *const cpi);
42 extern void vp8cx_initialize_me_consts(VP8_COMP *cpi, int QIndex);
43 extern void vp8_auto_select_speed(VP8_COMP *cpi);
44 extern void vp8cx_init_mbrthread_data(VP8_COMP *cpi,
49 void vp8_build_block_offsets(MACROBLOCK *x);
50 void vp8_setup_block_ptrs(MACROBLOCK *x);
51 int vp8cx_encode_inter_macroblock(VP8_COMP *cpi, MACROBLOCK *x, TOKENEXTRA **t,
52 int recon_yoffset, int recon_uvoffset,
53 int mb_row, int mb_col);
54 int vp8cx_encode_intra_macroblock(VP8_COMP *cpi, MACROBLOCK *x,
56 static void adjust_act_zbin( VP8_COMP *cpi, MACROBLOCK *x );
59 unsigned int inter_y_modes[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
60 unsigned int inter_uv_modes[4] = {0, 0, 0, 0};
61 unsigned int inter_b_modes[15] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
62 unsigned int y_modes[5] = {0, 0, 0, 0, 0};
63 unsigned int uv_modes[4] = {0, 0, 0, 0};
64 unsigned int b_modes[14] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
68 /* activity_avg must be positive, or flat regions could get a zero weight
69 * (infinite lambda), which confounds analysis.
70 * This also avoids the need for divide by zero checks in
71 * vp8_activity_masking().
73 #define VP8_ACTIVITY_AVG_MIN (64)
75 /* This is used as a reference when computing the source variance for the
76 * purposes of activity masking.
77 * Eventually this should be replaced by custom no-reference routines,
78 * which will be faster.
80 static const unsigned char VP8_VAR_OFFS[16]=
82 128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128
86 // Original activity measure from Tim T's code.
87 static unsigned int tt_activity_measure( VP8_COMP *cpi, MACROBLOCK *x )
91 /* TODO: This could also be done over smaller areas (8x8), but that would
92 * require extensive changes elsewhere, as lambda is assumed to be fixed
93 * over an entire MB in most of the code.
94 * Another option is to compute four 8x8 variances, and pick a single
95 * lambda using a non-linear combination (e.g., the smallest, or second
98 act = vp8_variance16x16(x->src.y_buffer,
99 x->src.y_stride, VP8_VAR_OFFS, 0, &sse);
102 /* If the region is flat, lower the activity some more. */
104 act = act < 5<<12 ? act : 5<<12;
109 // Stub for alternative experimental activity measures.
110 static unsigned int alt_activity_measure( VP8_COMP *cpi,
111 MACROBLOCK *x, int use_dc_pred )
113 return vp8_encode_intra(cpi,x, use_dc_pred);
117 // Measure the activity of the current macroblock
118 // What we measure here is TBD so abstracted to this function
119 #define ALT_ACT_MEASURE 1
120 static unsigned int mb_activity_measure( VP8_COMP *cpi, MACROBLOCK *x,
121 int mb_row, int mb_col)
123 unsigned int mb_activity;
125 if ( ALT_ACT_MEASURE )
127 int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
129 // Or use and alternative.
130 mb_activity = alt_activity_measure( cpi, x, use_dc_pred );
134 // Original activity measure from Tim T's code.
135 mb_activity = tt_activity_measure( cpi, x );
138 if ( mb_activity < VP8_ACTIVITY_AVG_MIN )
139 mb_activity = VP8_ACTIVITY_AVG_MIN;
144 // Calculate an "average" mb activity value for the frame
146 static void calc_av_activity( VP8_COMP *cpi, int64_t activity_sum )
149 // Find median: Simple n^2 algorithm for experimentation
153 unsigned int * sortlist;
156 // Create a list to sort to
157 CHECK_MEM_ERROR(sortlist,
158 vpx_calloc(sizeof(unsigned int),
161 // Copy map to sort list
162 vpx_memcpy( sortlist, cpi->mb_activity_map,
163 sizeof(unsigned int) * cpi->common.MBs );
166 // Ripple each value down to its correct position
167 for ( i = 1; i < cpi->common.MBs; i ++ )
169 for ( j = i; j > 0; j -- )
171 if ( sortlist[j] < sortlist[j-1] )
175 sortlist[j-1] = sortlist[j];
183 // Even number MBs so estimate median as mean of two either side.
184 median = ( 1 + sortlist[cpi->common.MBs >> 1] +
185 sortlist[(cpi->common.MBs >> 1) + 1] ) >> 1;
187 cpi->activity_avg = median;
192 // Simple mean for now
193 cpi->activity_avg = (unsigned int)(activity_sum/cpi->common.MBs);
196 if (cpi->activity_avg < VP8_ACTIVITY_AVG_MIN)
197 cpi->activity_avg = VP8_ACTIVITY_AVG_MIN;
199 // Experimental code: return fixed value normalized for several clips
200 if ( ALT_ACT_MEASURE )
201 cpi->activity_avg = 100000;
204 #define USE_ACT_INDEX 0
205 #define OUTPUT_NORM_ACT_STATS 0
208 // Calculate and activity index for each mb
209 static void calc_activity_index( VP8_COMP *cpi, MACROBLOCK *x )
211 VP8_COMMON *const cm = & cpi->common;
218 #if OUTPUT_NORM_ACT_STATS
219 FILE *f = fopen("norm_act.stt", "a");
220 fprintf(f, "\n%12d\n", cpi->activity_avg );
223 // Reset pointers to start of activity map
224 x->mb_activity_ptr = cpi->mb_activity_map;
226 // Calculate normalized mb activity number.
227 for (mb_row = 0; mb_row < cm->mb_rows; mb_row++)
229 // for each macroblock col in image
230 for (mb_col = 0; mb_col < cm->mb_cols; mb_col++)
232 // Read activity from the map
233 act = *(x->mb_activity_ptr);
235 // Calculate a normalized activity number
236 a = act + 4*cpi->activity_avg;
237 b = 4*act + cpi->activity_avg;
240 *(x->activity_ptr) = (int)((b + (a>>1))/a) - 1;
242 *(x->activity_ptr) = 1 - (int)((a + (b>>1))/b);
244 #if OUTPUT_NORM_ACT_STATS
245 fprintf(f, " %6d", *(x->mb_activity_ptr));
247 // Increment activity map pointers
248 x->mb_activity_ptr++;
251 #if OUTPUT_NORM_ACT_STATS
257 #if OUTPUT_NORM_ACT_STATS
264 // Loop through all MBs. Note activity of each, average activity and
265 // calculate a normalized activity for each
266 static void build_activity_map( VP8_COMP *cpi )
268 MACROBLOCK *const x = & cpi->mb;
269 MACROBLOCKD *xd = &x->e_mbd;
270 VP8_COMMON *const cm = & cpi->common;
273 YV12_BUFFER_CONFIG *new_yv12 = &cm->yv12_fb[cm->new_fb_idx];
275 int recon_y_stride = new_yv12->y_stride;
279 unsigned int mb_activity;
280 int64_t activity_sum = 0;
282 // for each macroblock row in image
283 for (mb_row = 0; mb_row < cm->mb_rows; mb_row++)
286 // reset above block coeffs
287 xd->up_available = (mb_row != 0);
288 recon_yoffset = (mb_row * recon_y_stride * 16);
290 // for each macroblock col in image
291 for (mb_col = 0; mb_col < cm->mb_cols; mb_col++)
294 xd->dst.y_buffer = new_yv12->y_buffer + recon_yoffset;
295 xd->left_available = (mb_col != 0);
298 //Copy current mb to a buffer
299 vp8_copy_mem16x16(x->src.y_buffer, x->src.y_stride, x->thismb, 16);
302 mb_activity = mb_activity_measure( cpi, x, mb_row, mb_col );
305 activity_sum += mb_activity;
307 // Store MB level activity details.
308 *x->mb_activity_ptr = mb_activity;
310 // Increment activity map pointer
311 x->mb_activity_ptr++;
313 // adjust to the next column of source macroblocks
314 x->src.y_buffer += 16;
318 // adjust to the next row of mbs
319 x->src.y_buffer += 16 * x->src.y_stride - 16 * cm->mb_cols;
322 //extend the recon for intra prediction
323 vp8_extend_mb_row(new_yv12, xd->dst.y_buffer + 16,
324 xd->dst.u_buffer + 8, xd->dst.v_buffer + 8);
329 // Calculate an "average" MB activity
330 calc_av_activity(cpi, activity_sum);
333 // Calculate an activity index number of each mb
334 calc_activity_index( cpi, x );
339 // Macroblock activity masking
340 void vp8_activity_masking(VP8_COMP *cpi, MACROBLOCK *x)
343 x->rdmult += *(x->mb_activity_ptr) * (x->rdmult >> 2);
344 x->errorperbit = x->rdmult * 100 /(110 * x->rddiv);
345 x->errorperbit += (x->errorperbit==0);
349 int64_t act = *(x->mb_activity_ptr);
351 // Apply the masking to the RD multiplier.
352 a = act + (2*cpi->activity_avg);
353 b = (2*act) + cpi->activity_avg;
355 x->rdmult = (unsigned int)(((int64_t)x->rdmult*b + (a>>1))/a);
356 x->errorperbit = x->rdmult * 100 /(110 * x->rddiv);
357 x->errorperbit += (x->errorperbit==0);
360 // Activity based Zbin adjustment
361 adjust_act_zbin(cpi, x);
365 void encode_mb_row(VP8_COMP *cpi,
374 int recon_yoffset, recon_uvoffset;
376 int ref_fb_idx = cm->lst_fb_idx;
377 int dst_fb_idx = cm->new_fb_idx;
378 int recon_y_stride = cm->yv12_fb[ref_fb_idx].y_stride;
379 int recon_uv_stride = cm->yv12_fb[ref_fb_idx].uv_stride;
380 int map_index = (mb_row * cpi->common.mb_cols);
382 #if (CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
383 const int num_part = (1 << cm->multi_token_partition);
384 TOKENEXTRA * tp_start = cpi->tok;
388 #if CONFIG_MULTITHREAD
389 const int nsync = cpi->mt_sync_range;
390 const int rightmost_col = cm->mb_cols + nsync;
391 volatile const int *last_row_current_mb_col;
392 volatile int *current_mb_col = &cpi->mt_current_mb_col[mb_row];
394 if ((cpi->b_multi_threaded != 0) && (mb_row != 0))
395 last_row_current_mb_col = &cpi->mt_current_mb_col[mb_row - 1];
397 last_row_current_mb_col = &rightmost_col;
400 #if (CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
402 w= &cpi->bc[1 + (mb_row % num_part)];
407 // reset above block coeffs
408 xd->above_context = cm->above_context;
410 xd->up_available = (mb_row != 0);
411 recon_yoffset = (mb_row * recon_y_stride * 16);
412 recon_uvoffset = (mb_row * recon_uv_stride * 8);
414 cpi->tplist[mb_row].start = *tp;
415 //printf("Main mb_row = %d\n", mb_row);
417 // Distance of Mb to the top & bottom edges, specified in 1/8th pel
418 // units as they are always compared to values that are in 1/8th pel units
419 xd->mb_to_top_edge = -((mb_row * 16) << 3);
420 xd->mb_to_bottom_edge = ((cm->mb_rows - 1 - mb_row) * 16) << 3;
422 // Set up limit values for vertical motion vector components
423 // to prevent them extending beyond the UMV borders
424 x->mv_row_min = -((mb_row * 16) + (VP8BORDERINPIXELS - 16));
425 x->mv_row_max = ((cm->mb_rows - 1 - mb_row) * 16)
426 + (VP8BORDERINPIXELS - 16);
428 // Set the mb activity pointer to the start of the row.
429 x->mb_activity_ptr = &cpi->mb_activity_map[map_index];
431 // for each macroblock col in image
432 for (mb_col = 0; mb_col < cm->mb_cols; mb_col++)
435 #if (CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
438 // Distance of Mb to the left & right edges, specified in
439 // 1/8th pel units as they are always compared to values
440 // that are in 1/8th pel units
441 xd->mb_to_left_edge = -((mb_col * 16) << 3);
442 xd->mb_to_right_edge = ((cm->mb_cols - 1 - mb_col) * 16) << 3;
444 // Set up limit values for horizontal motion vector components
445 // to prevent them extending beyond the UMV borders
446 x->mv_col_min = -((mb_col * 16) + (VP8BORDERINPIXELS - 16));
447 x->mv_col_max = ((cm->mb_cols - 1 - mb_col) * 16)
448 + (VP8BORDERINPIXELS - 16);
450 xd->dst.y_buffer = cm->yv12_fb[dst_fb_idx].y_buffer + recon_yoffset;
451 xd->dst.u_buffer = cm->yv12_fb[dst_fb_idx].u_buffer + recon_uvoffset;
452 xd->dst.v_buffer = cm->yv12_fb[dst_fb_idx].v_buffer + recon_uvoffset;
453 xd->left_available = (mb_col != 0);
455 x->rddiv = cpi->RDDIV;
456 x->rdmult = cpi->RDMULT;
458 //Copy current mb to a buffer
459 vp8_copy_mem16x16(x->src.y_buffer, x->src.y_stride, x->thismb, 16);
461 #if CONFIG_MULTITHREAD
462 if (cpi->b_multi_threaded != 0)
464 *current_mb_col = mb_col - 1; // set previous MB done
466 if ((mb_col & (nsync - 1)) == 0)
468 while (mb_col > (*last_row_current_mb_col - nsync))
477 if(cpi->oxcf.tuning == VP8_TUNE_SSIM)
478 vp8_activity_masking(cpi, x);
480 // Is segmentation enabled
481 // MB level adjustment to quantizer
482 if (xd->segmentation_enabled)
484 // Code to set segment id in xd->mbmi.segment_id for current MB (with range checking)
485 if (cpi->segmentation_map[map_index+mb_col] <= 3)
486 xd->mode_info_context->mbmi.segment_id = cpi->segmentation_map[map_index+mb_col];
488 xd->mode_info_context->mbmi.segment_id = 0;
490 vp8cx_mb_init_quantizer(cpi, x, 1);
493 xd->mode_info_context->mbmi.segment_id = 0; // Set to Segment 0 by default
495 x->active_ptr = cpi->active_map + map_index + mb_col;
497 if (cm->frame_type == KEY_FRAME)
499 *totalrate += vp8cx_encode_intra_macroblock(cpi, x, tp);
501 y_modes[xd->mbmi.mode] ++;
506 *totalrate += vp8cx_encode_inter_macroblock(cpi, x, tp, recon_yoffset, recon_uvoffset, mb_row, mb_col);
509 inter_y_modes[xd->mbmi.mode] ++;
511 if (xd->mbmi.mode == SPLITMV)
515 for (b = 0; b < xd->mbmi.partition_count; b++)
517 inter_b_modes[x->partition->bmi[b].mode] ++;
523 // Count of last ref frame 0,0 usage
524 if ((xd->mode_info_context->mbmi.mode == ZEROMV) && (xd->mode_info_context->mbmi.ref_frame == LAST_FRAME))
525 cpi->inter_zz_count ++;
527 // Special case code for cyclic refresh
528 // If cyclic update enabled then copy xd->mbmi.segment_id; (which may have been updated based on mode
529 // during vp8cx_encode_inter_macroblock()) back into the global segmentation map
530 if ((cpi->current_layer == 0) &&
531 (cpi->cyclic_refresh_mode_enabled && xd->segmentation_enabled))
533 cpi->segmentation_map[map_index+mb_col] = xd->mode_info_context->mbmi.segment_id;
535 // If the block has been refreshed mark it as clean (the magnitude of the -ve influences how long it will be before we consider another refresh):
536 // Else if it was coded (last frame 0,0) and has not already been refreshed then mark it as a candidate for cleanup next time (marked 0)
537 // else mark it as dirty (1).
538 if (xd->mode_info_context->mbmi.segment_id)
539 cpi->cyclic_refresh_map[map_index+mb_col] = -1;
540 else if ((xd->mode_info_context->mbmi.mode == ZEROMV) && (xd->mode_info_context->mbmi.ref_frame == LAST_FRAME))
542 if (cpi->cyclic_refresh_map[map_index+mb_col] == 1)
543 cpi->cyclic_refresh_map[map_index+mb_col] = 0;
546 cpi->cyclic_refresh_map[map_index+mb_col] = 1;
551 cpi->tplist[mb_row].stop = *tp;
553 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
554 /* pack tokens for this MB */
556 int tok_count = *tp - tp_start;
557 pack_tokens(w, tp_start, tok_count);
560 // Increment pointer into gf usage flags structure.
563 // Increment the activity mask pointers.
564 x->mb_activity_ptr++;
566 // adjust to the next column of macroblocks
567 x->src.y_buffer += 16;
568 x->src.u_buffer += 8;
569 x->src.v_buffer += 8;
574 // Keep track of segment usage
575 segment_counts[xd->mode_info_context->mbmi.segment_id] ++;
578 xd->mode_info_context++;
583 //extend the recon for intra prediction
584 vp8_extend_mb_row( &cm->yv12_fb[dst_fb_idx],
585 xd->dst.y_buffer + 16,
586 xd->dst.u_buffer + 8,
587 xd->dst.v_buffer + 8);
589 #if CONFIG_MULTITHREAD
590 if (cpi->b_multi_threaded != 0)
591 *current_mb_col = rightmost_col;
594 // this is to account for the border
595 xd->mode_info_context++;
599 void init_encode_frame_mb_context(VP8_COMP *cpi)
601 MACROBLOCK *const x = & cpi->mb;
602 VP8_COMMON *const cm = & cpi->common;
603 MACROBLOCKD *const xd = & x->e_mbd;
605 // GF active flags data structure
606 x->gf_active_ptr = (signed char *)cpi->gf_active_flags;
608 // Activity map pointer
609 x->mb_activity_ptr = cpi->mb_activity_map;
613 x->partition_info = x->pi;
615 xd->mode_info_context = cm->mi;
616 xd->mode_info_stride = cm->mode_info_stride;
618 xd->frame_type = cm->frame_type;
620 // reset intra mode contexts
621 if (cm->frame_type == KEY_FRAME)
622 vp8_init_mbmode_probs(cm);
624 // Copy data over into macro block data structures.
625 x->src = * cpi->Source;
626 xd->pre = cm->yv12_fb[cm->lst_fb_idx];
627 xd->dst = cm->yv12_fb[cm->new_fb_idx];
629 // set up frame for intra coded blocks
630 vp8_setup_intra_recon(&cm->yv12_fb[cm->new_fb_idx]);
632 vp8_build_block_offsets(x);
634 vp8_setup_block_dptrs(&x->e_mbd);
636 vp8_setup_block_ptrs(x);
638 xd->mode_info_context->mbmi.mode = DC_PRED;
639 xd->mode_info_context->mbmi.uv_mode = DC_PRED;
641 xd->left_context = &cm->left_context;
643 vp8_zero(cpi->count_mb_ref_frame_usage)
644 vp8_zero(cpi->ymode_count)
645 vp8_zero(cpi->uv_mode_count)
649 vpx_memset(cm->above_context, 0,
650 sizeof(ENTROPY_CONTEXT_PLANES) * cm->mb_cols);
652 // Special case treatment when GF and ARF are not sensible options for reference
653 if (cpi->ref_frame_flags == VP8_LAST_FLAG)
654 vp8_calc_ref_frame_costs(x->ref_frame_cost,
655 cpi->prob_intra_coded,255,128);
656 else if ((cpi->oxcf.number_of_layers > 1) &&
657 (cpi->ref_frame_flags == VP8_GOLD_FLAG))
658 vp8_calc_ref_frame_costs(x->ref_frame_cost,
659 cpi->prob_intra_coded,1,255);
660 else if ((cpi->oxcf.number_of_layers > 1) &&
661 (cpi->ref_frame_flags == VP8_ALT_FLAG))
662 vp8_calc_ref_frame_costs(x->ref_frame_cost,
663 cpi->prob_intra_coded,1,1);
665 vp8_calc_ref_frame_costs(x->ref_frame_cost,
666 cpi->prob_intra_coded,
667 cpi->prob_last_coded,
670 xd->fullpixel_mask = 0xffffffff;
672 xd->fullpixel_mask = 0xfffffff8;
675 void vp8_encode_frame(VP8_COMP *cpi)
678 MACROBLOCK *const x = & cpi->mb;
679 VP8_COMMON *const cm = & cpi->common;
680 MACROBLOCKD *const xd = & x->e_mbd;
681 TOKENEXTRA *tp = cpi->tok;
682 int segment_counts[MAX_MB_SEGMENTS];
684 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
685 BOOL_CODER * bc = &cpi->bc[1]; // bc[0] is for control partition
686 const int num_part = (1 << cm->multi_token_partition);
689 vpx_memset(segment_counts, 0, sizeof(segment_counts));
692 if (cpi->compressor_speed == 2)
694 if (cpi->oxcf.cpu_used < 0)
695 cpi->Speed = -(cpi->oxcf.cpu_used);
697 vp8_auto_select_speed(cpi);
700 // Functions setup for all frame types so we can use MC in AltRef
701 if (cm->mcomp_filter_type == SIXTAP)
703 xd->subpixel_predict = vp8_sixtap_predict4x4;
704 xd->subpixel_predict8x4 = vp8_sixtap_predict8x4;
705 xd->subpixel_predict8x8 = vp8_sixtap_predict8x8;
706 xd->subpixel_predict16x16 = vp8_sixtap_predict16x16;
710 xd->subpixel_predict = vp8_bilinear_predict4x4;
711 xd->subpixel_predict8x4 = vp8_bilinear_predict8x4;
712 xd->subpixel_predict8x8 = vp8_bilinear_predict8x8;
713 xd->subpixel_predict16x16 = vp8_bilinear_predict16x16;
716 // Reset frame count of inter 0,0 motion vector usage.
717 cpi->inter_zz_count = 0;
719 cpi->prediction_error = 0;
720 cpi->intra_error = 0;
721 cpi->skip_true_count = 0;
726 cpi->frame_distortion = 0;
727 cpi->last_mb_distortion = 0;
730 xd->mode_info_context = cm->mi;
732 vp8_zero(cpi->MVcount);
734 vp8_zero(cpi->coef_counts);
736 vp8cx_frame_init_quantizer(cpi);
738 vp8_initialize_rd_consts(cpi,
739 vp8_dc_quant(cm->base_qindex, cm->y1dc_delta_q));
741 vp8cx_initialize_me_consts(cpi, cm->base_qindex);
743 if(cpi->oxcf.tuning == VP8_TUNE_SSIM)
745 // Initialize encode frame context.
746 init_encode_frame_mb_context(cpi);
748 // Build a frame level activity map
749 build_activity_map(cpi);
752 // re-init encode frame context.
753 init_encode_frame_mb_context(cpi);
755 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
758 for(i = 0; i < num_part; i++)
760 vp8_start_encode(&bc[i], cpi->partition_d[i + 1],
761 cpi->partition_d_end[i + 1]);
762 bc[i].error = &cm->error;
769 struct vpx_usec_timer emr_timer;
770 vpx_usec_timer_start(&emr_timer);
772 #if CONFIG_MULTITHREAD
773 if (cpi->b_multi_threaded)
777 vp8cx_init_mbrthread_data(cpi, x, cpi->mb_row_ei, 1, cpi->encoding_thread_count);
779 for (i = 0; i < cm->mb_rows; i++)
780 cpi->mt_current_mb_col[i] = -1;
782 for (i = 0; i < cpi->encoding_thread_count; i++)
784 sem_post(&cpi->h_event_start_encoding[i]);
787 for (mb_row = 0; mb_row < cm->mb_rows; mb_row += (cpi->encoding_thread_count + 1))
789 vp8_zero(cm->left_context)
791 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
794 tp = cpi->tok + mb_row * (cm->mb_cols * 16 * 24);
797 encode_mb_row(cpi, cm, mb_row, x, xd, &tp, segment_counts, &totalrate);
799 // adjust to the next row of mbs
800 x->src.y_buffer += 16 * x->src.y_stride * (cpi->encoding_thread_count + 1) - 16 * cm->mb_cols;
801 x->src.u_buffer += 8 * x->src.uv_stride * (cpi->encoding_thread_count + 1) - 8 * cm->mb_cols;
802 x->src.v_buffer += 8 * x->src.uv_stride * (cpi->encoding_thread_count + 1) - 8 * cm->mb_cols;
804 xd->mode_info_context += xd->mode_info_stride * cpi->encoding_thread_count;
805 x->partition_info += xd->mode_info_stride * cpi->encoding_thread_count;
806 x->gf_active_ptr += cm->mb_cols * cpi->encoding_thread_count;
808 if(mb_row == cm->mb_rows - 1)
810 sem_post(&cpi->h_event_end_encoding); /* signal frame encoding end */
814 sem_wait(&cpi->h_event_end_encoding); /* wait for other threads to finish */
816 for (mb_row = 0; mb_row < cm->mb_rows; mb_row ++)
818 cpi->tok_count += cpi->tplist[mb_row].stop - cpi->tplist[mb_row].start;
821 if (xd->segmentation_enabled)
825 if (xd->segmentation_enabled)
828 for (i = 0; i < cpi->encoding_thread_count; i++)
830 for (j = 0; j < 4; j++)
831 segment_counts[j] += cpi->mb_row_ei[i].segment_counts[j];
836 for (i = 0; i < cpi->encoding_thread_count; i++)
838 totalrate += cpi->mb_row_ei[i].totalrate;
845 // for each macroblock row in image
846 for (mb_row = 0; mb_row < cm->mb_rows; mb_row++)
848 vp8_zero(cm->left_context)
850 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
854 encode_mb_row(cpi, cm, mb_row, x, xd, &tp, segment_counts, &totalrate);
856 // adjust to the next row of mbs
857 x->src.y_buffer += 16 * x->src.y_stride - 16 * cm->mb_cols;
858 x->src.u_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
859 x->src.v_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
862 cpi->tok_count = tp - cpi->tok;
865 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
868 for(i = 0; i < num_part; i++)
870 vp8_stop_encode(&bc[i]);
871 cpi->partition_sz[i+1] = bc[i].pos;
876 vpx_usec_timer_mark(&emr_timer);
877 cpi->time_encode_mb_row += vpx_usec_timer_elapsed(&emr_timer);
881 // Work out the segment probabilities if segmentation is enabled
882 if (xd->segmentation_enabled)
888 vpx_memset(xd->mb_segment_tree_probs, 255 , sizeof(xd->mb_segment_tree_probs));
890 tot_count = segment_counts[0] + segment_counts[1] + segment_counts[2] + segment_counts[3];
894 xd->mb_segment_tree_probs[0] = ((segment_counts[0] + segment_counts[1]) * 255) / tot_count;
896 tot_count = segment_counts[0] + segment_counts[1];
900 xd->mb_segment_tree_probs[1] = (segment_counts[0] * 255) / tot_count;
903 tot_count = segment_counts[2] + segment_counts[3];
906 xd->mb_segment_tree_probs[2] = (segment_counts[2] * 255) / tot_count;
908 // Zero probabilities not allowed
909 for (i = 0; i < MB_FEATURE_TREE_PROBS; i ++)
911 if (xd->mb_segment_tree_probs[i] == 0)
912 xd->mb_segment_tree_probs[i] = 1;
917 // 256 rate units to the bit
918 cpi->projected_frame_size = totalrate >> 8; // projected_frame_size in units of BYTES
920 // Make a note of the percentage MBs coded Intra.
921 if (cm->frame_type == KEY_FRAME)
923 cpi->this_frame_percent_intra = 100;
929 tot_modes = cpi->count_mb_ref_frame_usage[INTRA_FRAME]
930 + cpi->count_mb_ref_frame_usage[LAST_FRAME]
931 + cpi->count_mb_ref_frame_usage[GOLDEN_FRAME]
932 + cpi->count_mb_ref_frame_usage[ALTREF_FRAME];
935 cpi->this_frame_percent_intra = cpi->count_mb_ref_frame_usage[INTRA_FRAME] * 100 / tot_modes;
942 int flag[2] = {0, 0};
944 for (cnt = 0; cnt < MVPcount; cnt++)
946 if (cm->fc.pre_mvc[0][cnt] != cm->fc.mvc[0][cnt])
949 vpx_memcpy(cm->fc.pre_mvc[0], cm->fc.mvc[0], MVPcount);
954 for (cnt = 0; cnt < MVPcount; cnt++)
956 if (cm->fc.pre_mvc[1][cnt] != cm->fc.mvc[1][cnt])
959 vpx_memcpy(cm->fc.pre_mvc[1], cm->fc.mvc[1], MVPcount);
964 if (flag[0] || flag[1])
965 vp8_build_component_cost_table(cpi->mb.mvcost, (const MV_CONTEXT *) cm->fc.mvc, flag);
969 #if ! CONFIG_REALTIME_ONLY
970 // Adjust the projected reference frame usage probability numbers to reflect
971 // what we have just seen. This may be useful when we make multiple iterations
972 // of the recode loop rather than continuing to use values from the previous frame.
973 if ((cm->frame_type != KEY_FRAME) && ((cpi->oxcf.number_of_layers > 1) ||
974 (!cm->refresh_alt_ref_frame && !cm->refresh_golden_frame)))
976 vp8_convert_rfct_to_prob(cpi);
980 void vp8_setup_block_ptrs(MACROBLOCK *x)
985 for (r = 0; r < 4; r++)
987 for (c = 0; c < 4; c++)
989 x->block[r*4+c].src_diff = x->src_diff + r * 4 * 16 + c * 4;
993 for (r = 0; r < 2; r++)
995 for (c = 0; c < 2; c++)
997 x->block[16 + r*2+c].src_diff = x->src_diff + 256 + r * 4 * 8 + c * 4;
1002 for (r = 0; r < 2; r++)
1004 for (c = 0; c < 2; c++)
1006 x->block[20 + r*2+c].src_diff = x->src_diff + 320 + r * 4 * 8 + c * 4;
1010 x->block[24].src_diff = x->src_diff + 384;
1013 for (i = 0; i < 25; i++)
1015 x->block[i].coeff = x->coeff + i * 16;
1019 void vp8_build_block_offsets(MACROBLOCK *x)
1024 vp8_build_block_doffsets(&x->e_mbd);
1027 x->thismb_ptr = &x->thismb[0];
1028 for (br = 0; br < 4; br++)
1030 for (bc = 0; bc < 4; bc++)
1032 BLOCK *this_block = &x->block[block];
1033 //this_block->base_src = &x->src.y_buffer;
1034 //this_block->src_stride = x->src.y_stride;
1035 //this_block->src = 4 * br * this_block->src_stride + 4 * bc;
1036 this_block->base_src = &x->thismb_ptr;
1037 this_block->src_stride = 16;
1038 this_block->src = 4 * br * 16 + 4 * bc;
1044 for (br = 0; br < 2; br++)
1046 for (bc = 0; bc < 2; bc++)
1048 BLOCK *this_block = &x->block[block];
1049 this_block->base_src = &x->src.u_buffer;
1050 this_block->src_stride = x->src.uv_stride;
1051 this_block->src = 4 * br * this_block->src_stride + 4 * bc;
1057 for (br = 0; br < 2; br++)
1059 for (bc = 0; bc < 2; bc++)
1061 BLOCK *this_block = &x->block[block];
1062 this_block->base_src = &x->src.v_buffer;
1063 this_block->src_stride = x->src.uv_stride;
1064 this_block->src = 4 * br * this_block->src_stride + 4 * bc;
1070 static void sum_intra_stats(VP8_COMP *cpi, MACROBLOCK *x)
1072 const MACROBLOCKD *xd = & x->e_mbd;
1073 const MB_PREDICTION_MODE m = xd->mode_info_context->mbmi.mode;
1074 const MB_PREDICTION_MODE uvm = xd->mode_info_context->mbmi.uv_mode;
1077 const int is_key = cpi->common.frame_type == KEY_FRAME;
1079 ++ (is_key ? uv_modes : inter_uv_modes)[uvm];
1083 unsigned int *const bct = is_key ? b_modes : inter_b_modes;
1089 ++ bct[xd->block[b].bmi.mode];
1096 ++cpi->ymode_count[m];
1097 ++cpi->uv_mode_count[uvm];
1101 // Experimental stub function to create a per MB zbin adjustment based on
1102 // some previously calculated measure of MB activity.
1103 static void adjust_act_zbin( VP8_COMP *cpi, MACROBLOCK *x )
1106 x->act_zbin_adj = *(x->mb_activity_ptr);
1110 int64_t act = *(x->mb_activity_ptr);
1112 // Apply the masking to the RD multiplier.
1113 a = act + 4*cpi->activity_avg;
1114 b = 4*act + cpi->activity_avg;
1116 if ( act > cpi->activity_avg )
1117 x->act_zbin_adj = (int)(((int64_t)b + (a>>1))/a) - 1;
1119 x->act_zbin_adj = 1 - (int)(((int64_t)a + (b>>1))/b);
1123 int vp8cx_encode_intra_macroblock(VP8_COMP *cpi, MACROBLOCK *x, TOKENEXTRA **t)
1125 MACROBLOCKD *xd = &x->e_mbd;
1128 if (cpi->sf.RD && cpi->compressor_speed != 2)
1129 vp8_rd_pick_intra_mode(cpi, x, &rate);
1131 vp8_pick_intra_mode(cpi, x, &rate);
1133 if(cpi->oxcf.tuning == VP8_TUNE_SSIM)
1135 adjust_act_zbin( cpi, x );
1136 vp8_update_zbin_extra(cpi, x);
1139 if (x->e_mbd.mode_info_context->mbmi.mode == B_PRED)
1140 vp8_encode_intra4x4mby(x);
1142 vp8_encode_intra16x16mby(x);
1144 vp8_encode_intra16x16mbuv(x);
1146 sum_intra_stats(cpi, x);
1148 vp8_tokenize_mb(cpi, &x->e_mbd, t);
1150 if (xd->mode_info_context->mbmi.mode != B_PRED)
1151 vp8_inverse_transform_mby(xd);
1153 vp8_dequant_idct_add_uv_block
1154 (xd->qcoeff+16*16, xd->dequant_uv,
1155 xd->dst.u_buffer, xd->dst.v_buffer,
1156 xd->dst.uv_stride, xd->eobs+16);
1163 extern void vp8_fix_contexts(MACROBLOCKD *x);
1165 int vp8cx_encode_inter_macroblock
1167 VP8_COMP *cpi, MACROBLOCK *x, TOKENEXTRA **t,
1168 int recon_yoffset, int recon_uvoffset,
1169 int mb_row, int mb_col
1172 MACROBLOCKD *const xd = &x->e_mbd;
1173 int intra_error = 0;
1179 if (xd->segmentation_enabled)
1180 x->encode_breakout = cpi->segment_encode_breakout[xd->mode_info_context->mbmi.segment_id];
1182 x->encode_breakout = cpi->oxcf.encode_breakout;
1184 #if CONFIG_TEMPORAL_DENOISING
1185 // Reset the best sse mode/mv for each macroblock.
1186 x->e_mbd.best_sse_inter_mode = 0;
1187 x->e_mbd.best_sse_mv.as_int = 0;
1188 x->e_mbd.need_to_clamp_best_mvs = 0;
1193 int zbin_mode_boost_enabled = cpi->zbin_mode_boost_enabled;
1195 /* Are we using the fast quantizer for the mode selection? */
1196 if(cpi->sf.use_fastquant_for_pick)
1198 cpi->mb.quantize_b = vp8_fast_quantize_b;
1199 cpi->mb.quantize_b_pair = vp8_fast_quantize_b_pair;
1201 /* the fast quantizer does not use zbin_extra, so
1202 * do not recalculate */
1203 cpi->zbin_mode_boost_enabled = 0;
1205 vp8_rd_pick_inter_mode(cpi, x, recon_yoffset, recon_uvoffset, &rate,
1206 &distortion, &intra_error);
1208 /* switch back to the regular quantizer for the encode */
1209 if (cpi->sf.improved_quant)
1211 cpi->mb.quantize_b = vp8_regular_quantize_b;
1212 cpi->mb.quantize_b_pair = vp8_regular_quantize_b_pair;
1215 /* restore cpi->zbin_mode_boost_enabled */
1216 cpi->zbin_mode_boost_enabled = zbin_mode_boost_enabled;
1221 vp8_pick_inter_mode(cpi, x, recon_yoffset, recon_uvoffset, &rate,
1222 &distortion, &intra_error, mb_row, mb_col);
1225 cpi->prediction_error += distortion;
1226 cpi->intra_error += intra_error;
1228 if(cpi->oxcf.tuning == VP8_TUNE_SSIM)
1230 // Adjust the zbin based on this MB rate.
1231 adjust_act_zbin( cpi, x );
1235 // Experimental RD code
1236 cpi->frame_distortion += distortion;
1237 cpi->last_mb_distortion = distortion;
1240 // MB level adjutment to quantizer setup
1241 if (xd->segmentation_enabled)
1243 // If cyclic update enabled
1244 if (cpi->current_layer == 0 && cpi->cyclic_refresh_mode_enabled)
1246 // Clear segment_id back to 0 if not coded (last frame 0,0)
1247 if ((xd->mode_info_context->mbmi.segment_id == 1) &&
1248 ((xd->mode_info_context->mbmi.ref_frame != LAST_FRAME) || (xd->mode_info_context->mbmi.mode != ZEROMV)))
1250 xd->mode_info_context->mbmi.segment_id = 0;
1252 /* segment_id changed, so update */
1253 vp8cx_mb_init_quantizer(cpi, x, 1);
1259 // Experimental code. Special case for gf and arf zeromv modes.
1260 // Increase zbin size to supress noise
1261 cpi->zbin_mode_boost = 0;
1262 if (cpi->zbin_mode_boost_enabled)
1264 if ( xd->mode_info_context->mbmi.ref_frame != INTRA_FRAME )
1266 if (xd->mode_info_context->mbmi.mode == ZEROMV)
1268 if (xd->mode_info_context->mbmi.ref_frame != LAST_FRAME)
1269 cpi->zbin_mode_boost = GF_ZEROMV_ZBIN_BOOST;
1271 cpi->zbin_mode_boost = LF_ZEROMV_ZBIN_BOOST;
1273 else if (xd->mode_info_context->mbmi.mode == SPLITMV)
1274 cpi->zbin_mode_boost = 0;
1276 cpi->zbin_mode_boost = MV_ZBIN_BOOST;
1280 /* The fast quantizer doesn't use zbin_extra, only do so with
1281 * the regular quantizer. */
1282 if (cpi->sf.improved_quant)
1283 vp8_update_zbin_extra(cpi, x);
1286 cpi->count_mb_ref_frame_usage[xd->mode_info_context->mbmi.ref_frame] ++;
1288 if (xd->mode_info_context->mbmi.ref_frame == INTRA_FRAME)
1290 vp8_encode_intra16x16mbuv(x);
1292 if (xd->mode_info_context->mbmi.mode == B_PRED)
1294 vp8_encode_intra4x4mby(x);
1298 vp8_encode_intra16x16mby(x);
1301 sum_intra_stats(cpi, x);
1307 if (xd->mode_info_context->mbmi.ref_frame == LAST_FRAME)
1308 ref_fb_idx = cpi->common.lst_fb_idx;
1309 else if (xd->mode_info_context->mbmi.ref_frame == GOLDEN_FRAME)
1310 ref_fb_idx = cpi->common.gld_fb_idx;
1312 ref_fb_idx = cpi->common.alt_fb_idx;
1314 xd->pre.y_buffer = cpi->common.yv12_fb[ref_fb_idx].y_buffer + recon_yoffset;
1315 xd->pre.u_buffer = cpi->common.yv12_fb[ref_fb_idx].u_buffer + recon_uvoffset;
1316 xd->pre.v_buffer = cpi->common.yv12_fb[ref_fb_idx].v_buffer + recon_uvoffset;
1320 vp8_encode_inter16x16(x);
1323 vp8_build_inter16x16_predictors_mb(xd, xd->dst.y_buffer,
1324 xd->dst.u_buffer, xd->dst.v_buffer,
1325 xd->dst.y_stride, xd->dst.uv_stride);
1331 vp8_tokenize_mb(cpi, xd, t);
1333 if (xd->mode_info_context->mbmi.mode != B_PRED)
1334 vp8_inverse_transform_mby(xd);
1336 vp8_dequant_idct_add_uv_block
1337 (xd->qcoeff+16*16, xd->dequant_uv,
1338 xd->dst.u_buffer, xd->dst.v_buffer,
1339 xd->dst.uv_stride, xd->eobs+16);
1343 /* always set mb_skip_coeff as it is needed by the loopfilter */
1344 xd->mode_info_context->mbmi.mb_skip_coeff = 1;
1346 if (cpi->common.mb_no_coeff_skip)
1348 cpi->skip_true_count ++;
1349 vp8_fix_contexts(xd);
1353 vp8_stuff_mb(cpi, xd, t);