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 "vp8/common/header.h"
14 #include "vp8/common/entropymode.h"
15 #include "vp8/common/findnearmv.h"
17 #include "vp8/common/systemdependent.h"
21 #include "vp8/common/pragmas.h"
22 #include "vpx/vpx_encoder.h"
23 #include "vpx_mem/vpx_mem.h"
24 #include "bitstream.h"
26 #include "defaultcoefcounts.h"
27 #include "vp8/common/common.h"
29 const int vp8cx_base_skip_false_prob[128] =
31 255, 255, 255, 255, 255, 255, 255, 255,
32 255, 255, 255, 255, 255, 255, 255, 255,
33 255, 255, 255, 255, 255, 255, 255, 255,
34 255, 255, 255, 255, 255, 255, 255, 255,
35 255, 255, 255, 255, 255, 255, 255, 255,
36 255, 255, 255, 255, 255, 255, 255, 255,
37 255, 255, 255, 255, 255, 255, 255, 255,
38 251, 248, 244, 240, 236, 232, 229, 225,
39 221, 217, 213, 208, 204, 199, 194, 190,
40 187, 183, 179, 175, 172, 168, 164, 160,
41 157, 153, 149, 145, 142, 138, 134, 130,
42 127, 124, 120, 117, 114, 110, 107, 104,
43 101, 98, 95, 92, 89, 86, 83, 80,
44 77, 74, 71, 68, 65, 62, 59, 56,
45 53, 50, 47, 44, 41, 38, 35, 32,
46 30, 28, 26, 24, 22, 20, 18, 16,
49 #if defined(SECTIONBITS_OUTPUT)
50 unsigned __int64 Sectionbits[500];
53 #ifdef VP8_ENTROPY_STATS
54 int intra_mode_stats[10][10][10];
55 static unsigned int tree_update_hist [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [ENTROPY_NODES] [2];
56 extern unsigned int active_section;
60 int count_mb_seg[4] = { 0, 0, 0, 0 };
64 static void update_mode(
67 vp8_token tok [/* n */],
69 vp8_prob Pnew [/* n-1 */],
70 vp8_prob Pcur [/* n-1 */],
71 unsigned int bct [/* n-1 */] [2],
72 const unsigned int num_events[/* n */]
75 unsigned int new_b = 0, old_b = 0;
78 vp8_tree_probs_from_distribution(
80 Pnew, bct, num_events,
86 new_b += vp8_cost_branch(bct[i], Pnew[i]);
87 old_b += vp8_cost_branch(bct[i], Pcur[i]);
91 if (new_b + (n << 8) < old_b)
99 const vp8_prob p = Pnew[j];
101 vp8_write_literal(w, Pcur[j] = p ? p : 1, 8);
109 static void update_mbintra_mode_probs(VP8_COMP *cpi)
111 VP8_COMMON *const x = & cpi->common;
113 vp8_writer *const w = cpi->bc;
116 vp8_prob Pnew [VP8_YMODES-1];
117 unsigned int bct [VP8_YMODES-1] [2];
120 w, VP8_YMODES, vp8_ymode_encodings, vp8_ymode_tree,
121 Pnew, x->fc.ymode_prob, bct, (unsigned int *)cpi->mb.ymode_count
125 vp8_prob Pnew [VP8_UV_MODES-1];
126 unsigned int bct [VP8_UV_MODES-1] [2];
129 w, VP8_UV_MODES, vp8_uv_mode_encodings, vp8_uv_mode_tree,
130 Pnew, x->fc.uv_mode_prob, bct, (unsigned int *)cpi->mb.uv_mode_count
135 static void write_ymode(vp8_writer *bc, int m, const vp8_prob *p)
137 vp8_write_token(bc, vp8_ymode_tree, p, vp8_ymode_encodings + m);
140 static void kfwrite_ymode(vp8_writer *bc, int m, const vp8_prob *p)
142 vp8_write_token(bc, vp8_kf_ymode_tree, p, vp8_kf_ymode_encodings + m);
145 static void write_uv_mode(vp8_writer *bc, int m, const vp8_prob *p)
147 vp8_write_token(bc, vp8_uv_mode_tree, p, vp8_uv_mode_encodings + m);
151 static void write_bmode(vp8_writer *bc, int m, const vp8_prob *p)
153 vp8_write_token(bc, vp8_bmode_tree, p, vp8_bmode_encodings + m);
156 static void write_split(vp8_writer *bc, int x)
159 bc, vp8_mbsplit_tree, vp8_mbsplit_probs, vp8_mbsplit_encodings + x
163 void vp8_pack_tokens_c(vp8_writer *w, const TOKENEXTRA *p, int xcount)
165 const TOKENEXTRA *stop = p + xcount;
168 int count = w->count;
169 unsigned int range = w->range;
170 unsigned int lowvalue = w->lowvalue;
174 const int t = p->Token;
175 vp8_token *a = vp8_coef_encodings + t;
176 const vp8_extra_bit_struct *b = vp8_extra_bits + t;
178 const unsigned char *pp = p->context_tree;
182 if (p->skip_eob_node)
190 const int bb = (v >> --n) & 1;
191 split = 1 + (((range - 1) * pp[i>>1]) >> 8);
192 i = vp8_coef_tree[i+bb];
197 range = range - split;
204 shift = vp8_norm[range];
210 int offset = shift - count;
212 if ((lowvalue << (offset - 1)) & 0x80000000)
216 while (x >= 0 && w->buffer[x] == 0xff)
218 w->buffer[x] = (unsigned char)0;
225 validate_buffer(w->buffer + w->pos,
230 w->buffer[w->pos++] = (lowvalue >> (24 - offset));
233 lowvalue &= 0xffffff;
244 const int e = p->Extra, L = b->Len;
248 const unsigned char *proba = b->prob;
249 const int v2 = e >> 1;
250 int n2 = L; /* number of bits in v2, assumed nonzero */
255 const int bb = (v2 >> --n2) & 1;
256 split = 1 + (((range - 1) * proba[i>>1]) >> 8);
262 range = range - split;
269 shift = vp8_norm[range];
275 int offset = shift - count;
277 if ((lowvalue << (offset - 1)) & 0x80000000)
281 while (x >= 0 && w->buffer[x] == 0xff)
283 w->buffer[x] = (unsigned char)0;
290 validate_buffer(w->buffer + w->pos,
295 w->buffer[w->pos++] = (lowvalue >> (24 - offset));
298 lowvalue &= 0xffffff;
310 split = (range + 1) >> 1;
315 range = range - split;
324 if ((lowvalue & 0x80000000))
328 while (x >= 0 && w->buffer[x] == 0xff)
330 w->buffer[x] = (unsigned char)0;
344 validate_buffer(w->buffer + w->pos,
349 w->buffer[w->pos++] = (lowvalue >> 24);
350 lowvalue &= 0xffffff;
360 w->lowvalue = lowvalue;
365 static void write_partition_size(unsigned char *cx_data, int size)
371 csize = (size >> 8) & 0xff;
372 *(cx_data + 1) = csize;
373 csize = (size >> 16) & 0xff;
374 *(cx_data + 2) = csize;
378 static void pack_tokens_into_partitions_c(VP8_COMP *cpi, unsigned char *cx_data,
379 unsigned char * cx_data_end,
384 unsigned char *ptr = cx_data;
385 unsigned char *ptr_end = cx_data_end;
388 for (i = 0; i < num_part; i++)
394 vp8_start_encode(w, ptr, ptr_end);
396 for (mb_row = i; mb_row < cpi->common.mb_rows; mb_row += num_part)
398 const TOKENEXTRA *p = cpi->tplist[mb_row].start;
399 const TOKENEXTRA *stop = cpi->tplist[mb_row].stop;
400 int tokens = (int)(stop - p);
402 vp8_pack_tokens_c(w, p, tokens);
411 static void pack_mb_row_tokens_c(VP8_COMP *cpi, vp8_writer *w)
415 for (mb_row = 0; mb_row < cpi->common.mb_rows; mb_row++)
417 const TOKENEXTRA *p = cpi->tplist[mb_row].start;
418 const TOKENEXTRA *stop = cpi->tplist[mb_row].stop;
419 int tokens = (int)(stop - p);
421 vp8_pack_tokens_c(w, p, tokens);
426 static void write_mv_ref
428 vp8_writer *w, MB_PREDICTION_MODE m, const vp8_prob *p
432 assert(NEARESTMV <= m && m <= SPLITMV);
434 vp8_write_token(w, vp8_mv_ref_tree, p,
435 vp8_mv_ref_encoding_array - NEARESTMV + m);
438 static void write_sub_mv_ref
440 vp8_writer *w, B_PREDICTION_MODE m, const vp8_prob *p
444 assert(LEFT4X4 <= m && m <= NEW4X4);
446 vp8_write_token(w, vp8_sub_mv_ref_tree, p,
447 vp8_sub_mv_ref_encoding_array - LEFT4X4 + m);
452 vp8_writer *w, const MV *mv, const int_mv *ref, const MV_CONTEXT *mvc
456 e.row = mv->row - ref->as_mv.row;
457 e.col = mv->col - ref->as_mv.col;
459 vp8_encode_motion_vector(w, &e, mvc);
462 static void write_mb_features(vp8_writer *w, const MB_MODE_INFO *mi, const MACROBLOCKD *x)
464 /* Encode the MB segment id. */
465 if (x->segmentation_enabled && x->update_mb_segmentation_map)
467 switch (mi->segment_id)
470 vp8_write(w, 0, x->mb_segment_tree_probs[0]);
471 vp8_write(w, 0, x->mb_segment_tree_probs[1]);
474 vp8_write(w, 0, x->mb_segment_tree_probs[0]);
475 vp8_write(w, 1, x->mb_segment_tree_probs[1]);
478 vp8_write(w, 1, x->mb_segment_tree_probs[0]);
479 vp8_write(w, 0, x->mb_segment_tree_probs[2]);
482 vp8_write(w, 1, x->mb_segment_tree_probs[0]);
483 vp8_write(w, 1, x->mb_segment_tree_probs[2]);
486 /* TRAP.. This should not happen */
488 vp8_write(w, 0, x->mb_segment_tree_probs[0]);
489 vp8_write(w, 0, x->mb_segment_tree_probs[1]);
494 void vp8_convert_rfct_to_prob(VP8_COMP *const cpi)
496 const int *const rfct = cpi->mb.count_mb_ref_frame_usage;
497 const int rf_intra = rfct[INTRA_FRAME];
498 const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
500 /* Calculate the probabilities used to code the ref frame based on usage */
501 if (!(cpi->prob_intra_coded = rf_intra * 255 / (rf_intra + rf_inter)))
502 cpi->prob_intra_coded = 1;
504 cpi->prob_last_coded = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
506 if (!cpi->prob_last_coded)
507 cpi->prob_last_coded = 1;
509 cpi->prob_gf_coded = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
510 ? (rfct[GOLDEN_FRAME] * 255) / (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME]) : 128;
512 if (!cpi->prob_gf_coded)
513 cpi->prob_gf_coded = 1;
517 static void pack_inter_mode_mvs(VP8_COMP *const cpi)
519 VP8_COMMON *const pc = & cpi->common;
520 vp8_writer *const w = cpi->bc;
521 const MV_CONTEXT *mvc = pc->fc.mvc;
524 MODE_INFO *m = pc->mi;
525 const int mis = pc->mode_info_stride;
528 int prob_skip_false = 0;
530 cpi->mb.partition_info = cpi->mb.pi;
532 vp8_convert_rfct_to_prob(cpi);
534 #ifdef VP8_ENTROPY_STATS
538 if (pc->mb_no_coeff_skip)
540 int total_mbs = pc->mb_rows * pc->mb_cols;
542 prob_skip_false = (total_mbs - cpi->mb.skip_true_count ) * 256 / total_mbs;
544 if (prob_skip_false <= 1)
547 if (prob_skip_false > 255)
548 prob_skip_false = 255;
550 cpi->prob_skip_false = prob_skip_false;
551 vp8_write_literal(w, prob_skip_false, 8);
554 vp8_write_literal(w, cpi->prob_intra_coded, 8);
555 vp8_write_literal(w, cpi->prob_last_coded, 8);
556 vp8_write_literal(w, cpi->prob_gf_coded, 8);
558 update_mbintra_mode_probs(cpi);
560 vp8_write_mvprobs(cpi);
562 while (++mb_row < pc->mb_rows)
566 while (++mb_col < pc->mb_cols)
568 const MB_MODE_INFO *const mi = & m->mbmi;
569 const MV_REFERENCE_FRAME rf = mi->ref_frame;
570 const MB_PREDICTION_MODE mode = mi->mode;
572 MACROBLOCKD *xd = &cpi->mb.e_mbd;
574 /* Distance of Mb to the various image edges.
575 * These specified to 8th pel as they are always compared to MV
576 * values that are in 1/8th pel units
578 xd->mb_to_left_edge = -((mb_col * 16) << 3);
579 xd->mb_to_right_edge = ((pc->mb_cols - 1 - mb_col) * 16) << 3;
580 xd->mb_to_top_edge = -((mb_row * 16)) << 3;
581 xd->mb_to_bottom_edge = ((pc->mb_rows - 1 - mb_row) * 16) << 3;
583 #ifdef VP8_ENTROPY_STATS
587 if (cpi->mb.e_mbd.update_mb_segmentation_map)
588 write_mb_features(w, mi, &cpi->mb.e_mbd);
590 if (pc->mb_no_coeff_skip)
591 vp8_encode_bool(w, m->mbmi.mb_skip_coeff, prob_skip_false);
593 if (rf == INTRA_FRAME)
595 vp8_write(w, 0, cpi->prob_intra_coded);
596 #ifdef VP8_ENTROPY_STATS
599 write_ymode(w, mode, pc->fc.ymode_prob);
606 write_bmode(w, m->bmi[j].as_mode, pc->fc.bmode_prob);
610 write_uv_mode(w, mi->uv_mode, pc->fc.uv_mode_prob);
612 else /* inter coded */
615 vp8_prob mv_ref_p [VP8_MVREFS-1];
617 vp8_write(w, 1, cpi->prob_intra_coded);
619 if (rf == LAST_FRAME)
620 vp8_write(w, 0, cpi->prob_last_coded);
623 vp8_write(w, 1, cpi->prob_last_coded);
624 vp8_write(w, (rf == GOLDEN_FRAME) ? 0 : 1, cpi->prob_gf_coded);
631 vp8_find_near_mvs(xd, m, &n1, &n2, &best_mv, ct, rf, cpi->common.ref_frame_sign_bias);
632 vp8_clamp_mv2(&best_mv, xd);
634 vp8_mv_ref_probs(mv_ref_p, ct);
636 #ifdef VP8_ENTROPY_STATS
637 accum_mv_refs(mode, ct);
642 #ifdef VP8_ENTROPY_STATS
646 write_mv_ref(w, mode, mv_ref_p);
648 switch (mode) /* new, split require MVs */
652 #ifdef VP8_ENTROPY_STATS
656 write_mv(w, &mi->mv.as_mv, &best_mv, mvc);
664 ++count_mb_seg [mi->partitioning];
667 write_split(w, mi->partitioning);
671 B_PREDICTION_MODE blockmode;
673 const int *const L = vp8_mbsplits [mi->partitioning];
674 int k = -1; /* first block in subset j */
676 int_mv leftmv, abovemv;
678 blockmode = cpi->mb.partition_info->bmi[j].mode;
679 blockmv = cpi->mb.partition_info->bmi[j].mv;
687 leftmv.as_int = left_block_mv(m, k);
688 abovemv.as_int = above_block_mv(m, k, mis);
689 mv_contz = vp8_mv_cont(&leftmv, &abovemv);
691 write_sub_mv_ref(w, blockmode, vp8_sub_mv_ref_prob2 [mv_contz]);
693 if (blockmode == NEW4X4)
695 #ifdef VP8_ENTROPY_STATS
698 write_mv(w, &blockmv.as_mv, &best_mv, (const MV_CONTEXT *) mvc);
701 while (++j < cpi->mb.partition_info->count);
710 cpi->mb.partition_info++;
713 ++m; /* skip L prediction border */
714 cpi->mb.partition_info++;
719 static void write_kfmodes(VP8_COMP *cpi)
721 vp8_writer *const bc = cpi->bc;
722 const VP8_COMMON *const c = & cpi->common;
724 MODE_INFO *m = c->mi;
727 int prob_skip_false = 0;
729 if (c->mb_no_coeff_skip)
731 int total_mbs = c->mb_rows * c->mb_cols;
733 prob_skip_false = (total_mbs - cpi->mb.skip_true_count ) * 256 / total_mbs;
735 if (prob_skip_false <= 1)
738 if (prob_skip_false >= 255)
739 prob_skip_false = 255;
741 cpi->prob_skip_false = prob_skip_false;
742 vp8_write_literal(bc, prob_skip_false, 8);
745 while (++mb_row < c->mb_rows)
749 while (++mb_col < c->mb_cols)
751 const int ym = m->mbmi.mode;
753 if (cpi->mb.e_mbd.update_mb_segmentation_map)
754 write_mb_features(bc, &m->mbmi, &cpi->mb.e_mbd);
756 if (c->mb_no_coeff_skip)
757 vp8_encode_bool(bc, m->mbmi.mb_skip_coeff, prob_skip_false);
759 kfwrite_ymode(bc, ym, vp8_kf_ymode_prob);
763 const int mis = c->mode_info_stride;
768 const B_PREDICTION_MODE A = above_block_mode(m, i, mis);
769 const B_PREDICTION_MODE L = left_block_mode(m, i);
770 const int bm = m->bmi[i].as_mode;
772 #ifdef VP8_ENTROPY_STATS
773 ++intra_mode_stats [A] [L] [bm];
776 write_bmode(bc, bm, vp8_kf_bmode_prob [A] [L]);
781 write_uv_mode(bc, (m++)->mbmi.uv_mode, vp8_kf_uv_mode_prob);
784 m++; /* skip L prediction border */
789 /* This function is used for debugging probability trees. */
790 static void print_prob_tree(vp8_prob
791 coef_probs[BLOCK_TYPES][COEF_BANDS][PREV_COEF_CONTEXTS][ENTROPY_NODES])
793 /* print coef probability tree */
795 FILE* f = fopen("enc_tree_probs.txt", "a");
797 for (i = 0; i < BLOCK_TYPES; i++)
800 for (j = 0; j < COEF_BANDS; j++)
803 for (k = 0; k < PREV_COEF_CONTEXTS; k++)
806 for (l = 0; l < ENTROPY_NODES; l++)
809 (unsigned int)(coef_probs [i][j][k][l]));
822 static void sum_probs_over_prev_coef_context(
823 const unsigned int probs[PREV_COEF_CONTEXTS][MAX_ENTROPY_TOKENS],
827 for (i=0; i < MAX_ENTROPY_TOKENS; ++i)
829 for (j=0; j < PREV_COEF_CONTEXTS; ++j)
831 const unsigned int tmp = out[i];
832 out[i] += probs[j][i];
840 static int prob_update_savings(const unsigned int *ct,
841 const vp8_prob oldp, const vp8_prob newp,
844 const int old_b = vp8_cost_branch(ct, oldp);
845 const int new_b = vp8_cost_branch(ct, newp);
846 const int update_b = 8 +
847 ((vp8_cost_one(upd) - vp8_cost_zero(upd)) >> 8);
849 return old_b - new_b - update_b;
852 static int independent_coef_context_savings(VP8_COMP *cpi)
854 MACROBLOCK *const x = & cpi->mb;
863 unsigned int prev_coef_count_sum[MAX_ENTROPY_TOKENS] = {0};
864 int prev_coef_savings[MAX_ENTROPY_TOKENS] = {0};
865 const unsigned int (*probs)[MAX_ENTROPY_TOKENS];
866 /* Calculate new probabilities given the constraint that
867 * they must be equal over the prev coef contexts
870 probs = (const unsigned int (*)[MAX_ENTROPY_TOKENS])
871 x->coef_counts[i][j];
873 /* Reset to default probabilities at key frames */
874 if (cpi->common.frame_type == KEY_FRAME)
875 probs = default_coef_counts[i][j];
877 sum_probs_over_prev_coef_context(probs, prev_coef_count_sum);
881 /* at every context */
883 /* calc probs and branch cts for this frame only */
884 int t = 0; /* token/prob index */
886 vp8_tree_probs_from_distribution(
887 MAX_ENTROPY_TOKENS, vp8_coef_encodings, vp8_coef_tree,
888 cpi->frame_coef_probs[i][j][k],
889 cpi->frame_branch_ct [i][j][k],
895 const unsigned int *ct = cpi->frame_branch_ct [i][j][k][t];
896 const vp8_prob newp = cpi->frame_coef_probs [i][j][k][t];
897 const vp8_prob oldp = cpi->common.fc.coef_probs [i][j][k][t];
898 const vp8_prob upd = vp8_coef_update_probs [i][j][k][t];
899 const int s = prob_update_savings(ct, oldp, newp, upd);
901 if (cpi->common.frame_type != KEY_FRAME ||
902 (cpi->common.frame_type == KEY_FRAME && newp != oldp))
903 prev_coef_savings[t] += s;
905 while (++t < ENTROPY_NODES);
907 while (++k < PREV_COEF_CONTEXTS);
911 /* We only update probabilities if we can save bits, except
912 * for key frames where we have to update all probabilities
913 * to get the equal probabilities across the prev coef
916 if (prev_coef_savings[k] > 0 ||
917 cpi->common.frame_type == KEY_FRAME)
918 savings += prev_coef_savings[k];
920 while (++k < ENTROPY_NODES);
922 while (++j < COEF_BANDS);
924 while (++i < BLOCK_TYPES);
928 static int default_coef_context_savings(VP8_COMP *cpi)
930 MACROBLOCK *const x = & cpi->mb;
941 /* at every context */
943 /* calc probs and branch cts for this frame only */
944 int t = 0; /* token/prob index */
946 vp8_tree_probs_from_distribution(
947 MAX_ENTROPY_TOKENS, vp8_coef_encodings, vp8_coef_tree,
948 cpi->frame_coef_probs [i][j][k],
949 cpi->frame_branch_ct [i][j][k],
950 x->coef_counts [i][j][k],
956 const unsigned int *ct = cpi->frame_branch_ct [i][j][k][t];
957 const vp8_prob newp = cpi->frame_coef_probs [i][j][k][t];
958 const vp8_prob oldp = cpi->common.fc.coef_probs [i][j][k][t];
959 const vp8_prob upd = vp8_coef_update_probs [i][j][k][t];
960 const int s = prob_update_savings(ct, oldp, newp, upd);
967 while (++t < ENTROPY_NODES);
969 while (++k < PREV_COEF_CONTEXTS);
971 while (++j < COEF_BANDS);
973 while (++i < BLOCK_TYPES);
977 void vp8_calc_ref_frame_costs(int *ref_frame_cost,
983 assert(prob_intra >= 0);
984 assert(prob_intra <= 255);
985 assert(prob_last >= 0);
986 assert(prob_last <= 255);
987 assert(prob_garf >= 0);
988 assert(prob_garf <= 255);
989 ref_frame_cost[INTRA_FRAME] = vp8_cost_zero(prob_intra);
990 ref_frame_cost[LAST_FRAME] = vp8_cost_one(prob_intra)
991 + vp8_cost_zero(prob_last);
992 ref_frame_cost[GOLDEN_FRAME] = vp8_cost_one(prob_intra)
993 + vp8_cost_one(prob_last)
994 + vp8_cost_zero(prob_garf);
995 ref_frame_cost[ALTREF_FRAME] = vp8_cost_one(prob_intra)
996 + vp8_cost_one(prob_last)
997 + vp8_cost_one(prob_garf);
1001 int vp8_estimate_entropy_savings(VP8_COMP *cpi)
1005 const int *const rfct = cpi->mb.count_mb_ref_frame_usage;
1006 const int rf_intra = rfct[INTRA_FRAME];
1007 const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
1008 int new_intra, new_last, new_garf, oldtotal, newtotal;
1009 int ref_frame_cost[MAX_REF_FRAMES];
1011 vp8_clear_system_state();
1013 if (cpi->common.frame_type != KEY_FRAME)
1015 if (!(new_intra = rf_intra * 255 / (rf_intra + rf_inter)))
1018 new_last = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
1020 new_garf = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
1021 ? (rfct[GOLDEN_FRAME] * 255) / (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME]) : 128;
1024 vp8_calc_ref_frame_costs(ref_frame_cost,new_intra,new_last,new_garf);
1027 rfct[INTRA_FRAME] * ref_frame_cost[INTRA_FRAME] +
1028 rfct[LAST_FRAME] * ref_frame_cost[LAST_FRAME] +
1029 rfct[GOLDEN_FRAME] * ref_frame_cost[GOLDEN_FRAME] +
1030 rfct[ALTREF_FRAME] * ref_frame_cost[ALTREF_FRAME];
1034 vp8_calc_ref_frame_costs(ref_frame_cost,cpi->prob_intra_coded,
1035 cpi->prob_last_coded,cpi->prob_gf_coded);
1038 rfct[INTRA_FRAME] * ref_frame_cost[INTRA_FRAME] +
1039 rfct[LAST_FRAME] * ref_frame_cost[LAST_FRAME] +
1040 rfct[GOLDEN_FRAME] * ref_frame_cost[GOLDEN_FRAME] +
1041 rfct[ALTREF_FRAME] * ref_frame_cost[ALTREF_FRAME];
1043 savings += (oldtotal - newtotal) / 256;
1047 if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS)
1048 savings += independent_coef_context_savings(cpi);
1050 savings += default_coef_context_savings(cpi);
1056 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1057 int vp8_update_coef_context(VP8_COMP *cpi)
1062 if (cpi->common.frame_type == KEY_FRAME)
1064 /* Reset to default counts/probabilities at key frames */
1065 vp8_copy(cpi->coef_counts, default_coef_counts);
1068 if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS)
1069 savings += independent_coef_context_savings(cpi);
1071 savings += default_coef_context_savings(cpi);
1077 void vp8_update_coef_probs(VP8_COMP *cpi)
1080 #if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
1081 vp8_writer *const w = cpi->bc;
1085 vp8_clear_system_state();
1094 int prev_coef_savings[ENTROPY_NODES] = {0};
1095 if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS)
1097 for (k = 0; k < PREV_COEF_CONTEXTS; ++k)
1099 int t; /* token/prob index */
1100 for (t = 0; t < ENTROPY_NODES; ++t)
1102 const unsigned int *ct = cpi->frame_branch_ct [i][j]
1104 const vp8_prob newp = cpi->frame_coef_probs[i][j][k][t];
1105 const vp8_prob oldp = cpi->common.fc.coef_probs[i][j]
1107 const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
1109 prev_coef_savings[t] +=
1110 prob_update_savings(ct, oldp, newp, upd);
1117 /* note: use result from vp8_estimate_entropy_savings, so no
1118 * need to call vp8_tree_probs_from_distribution here.
1121 /* at every context */
1123 /* calc probs and branch cts for this frame only */
1124 int t = 0; /* token/prob index */
1128 const vp8_prob newp = cpi->frame_coef_probs [i][j][k][t];
1130 vp8_prob *Pold = cpi->common.fc.coef_probs [i][j][k] + t;
1131 const vp8_prob upd = vp8_coef_update_probs [i][j][k][t];
1133 int s = prev_coef_savings[t];
1136 if (!(cpi->oxcf.error_resilient_mode &
1137 VPX_ERROR_RESILIENT_PARTITIONS))
1139 s = prob_update_savings(
1140 cpi->frame_branch_ct [i][j][k][t],
1147 /* Force updates on key frames if the new is different,
1148 * so that we can be sure we end up with equal probabilities
1149 * over the prev coef contexts.
1151 if ((cpi->oxcf.error_resilient_mode &
1152 VPX_ERROR_RESILIENT_PARTITIONS) &&
1153 cpi->common.frame_type == KEY_FRAME && newp != *Pold)
1156 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1157 cpi->update_probs[i][j][k][t] = u;
1159 vp8_write(w, u, upd);
1163 #ifdef VP8_ENTROPY_STATS
1164 ++ tree_update_hist [i][j][k][t] [u];
1169 /* send/use new probability */
1172 #if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
1173 vp8_write_literal(w, newp, 8);
1181 while (++t < ENTROPY_NODES);
1183 /* Accum token counts for generation of default statistics */
1184 #ifdef VP8_ENTROPY_STATS
1189 context_counters [i][j][k][t] += cpi->coef_counts [i][j][k][t];
1191 while (++t < MAX_ENTROPY_TOKENS);
1196 while (++k < PREV_COEF_CONTEXTS);
1198 while (++j < COEF_BANDS);
1200 while (++i < BLOCK_TYPES);
1204 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1205 static void pack_coef_probs(VP8_COMP *cpi)
1208 vp8_writer *const w = cpi->bc;
1220 int t = 0; /* token/prob index */
1224 const vp8_prob newp = cpi->common.fc.coef_probs [i][j][k][t];
1225 const vp8_prob upd = vp8_coef_update_probs [i][j][k][t];
1227 const char u = cpi->update_probs[i][j][k][t] ;
1229 vp8_write(w, u, upd);
1233 /* send/use new probability */
1234 vp8_write_literal(w, newp, 8);
1237 while (++t < ENTROPY_NODES);
1239 while (++k < PREV_COEF_CONTEXTS);
1241 while (++j < COEF_BANDS);
1243 while (++i < BLOCK_TYPES);
1247 #ifdef PACKET_TESTING
1251 static void put_delta_q(vp8_writer *bc, int delta_q)
1255 vp8_write_bit(bc, 1);
1256 vp8_write_literal(bc, abs(delta_q), 4);
1259 vp8_write_bit(bc, 1);
1261 vp8_write_bit(bc, 0);
1264 vp8_write_bit(bc, 0);
1267 void vp8_pack_bitstream(VP8_COMP *cpi, unsigned char *dest, unsigned char * dest_end, unsigned long *size)
1271 VP8_COMMON *const pc = & cpi->common;
1272 vp8_writer *const bc = cpi->bc;
1273 MACROBLOCKD *const xd = & cpi->mb.e_mbd;
1274 int extra_bytes_packed = 0;
1276 unsigned char *cx_data = dest;
1277 unsigned char *cx_data_end = dest_end;
1278 const int *mb_feature_data_bits;
1280 oh.show_frame = (int) pc->show_frame;
1281 oh.type = (int)pc->frame_type;
1282 oh.version = pc->version;
1283 oh.first_partition_length_in_bytes = 0;
1285 mb_feature_data_bits = vp8_mb_feature_data_bits;
1287 bc[0].error = &pc->error;
1289 validate_buffer(cx_data, 3, cx_data_end, &cpi->common.error);
1292 #if defined(SECTIONBITS_OUTPUT)
1293 Sectionbits[active_section = 1] += sizeof(VP8_HEADER) * 8 * 256;
1296 /* every keyframe send startcode, width, height, scale factor, clamp
1299 if (oh.type == KEY_FRAME)
1303 validate_buffer(cx_data, 7, cx_data_end, &cpi->common.error);
1305 /* Start / synch code */
1310 v = (pc->horiz_scale << 14) | pc->Width;
1312 cx_data[4] = v >> 8;
1314 v = (pc->vert_scale << 14) | pc->Height;
1316 cx_data[6] = v >> 8;
1319 extra_bytes_packed = 7;
1320 cx_data += extra_bytes_packed ;
1322 vp8_start_encode(bc, cx_data, cx_data_end);
1324 /* signal clr type */
1325 vp8_write_bit(bc, pc->clr_type);
1326 vp8_write_bit(bc, pc->clamp_type);
1330 vp8_start_encode(bc, cx_data, cx_data_end);
1333 /* Signal whether or not Segmentation is enabled */
1334 vp8_write_bit(bc, xd->segmentation_enabled);
1336 /* Indicate which features are enabled */
1337 if (xd->segmentation_enabled)
1339 /* Signal whether or not the segmentation map is being updated. */
1340 vp8_write_bit(bc, xd->update_mb_segmentation_map);
1341 vp8_write_bit(bc, xd->update_mb_segmentation_data);
1343 if (xd->update_mb_segmentation_data)
1347 vp8_write_bit(bc, xd->mb_segement_abs_delta);
1349 /* For each segmentation feature (Quant and loop filter level) */
1350 for (i = 0; i < MB_LVL_MAX; i++)
1352 /* For each of the segments */
1353 for (j = 0; j < MAX_MB_SEGMENTS; j++)
1355 Data = xd->segment_feature_data[i][j];
1357 /* Frame level data */
1360 vp8_write_bit(bc, 1);
1365 vp8_write_literal(bc, Data, mb_feature_data_bits[i]);
1366 vp8_write_bit(bc, 1);
1370 vp8_write_literal(bc, Data, mb_feature_data_bits[i]);
1371 vp8_write_bit(bc, 0);
1375 vp8_write_bit(bc, 0);
1380 if (xd->update_mb_segmentation_map)
1382 /* Write the probs used to decode the segment id for each mb */
1383 for (i = 0; i < MB_FEATURE_TREE_PROBS; i++)
1385 int Data = xd->mb_segment_tree_probs[i];
1389 vp8_write_bit(bc, 1);
1390 vp8_write_literal(bc, Data, 8);
1393 vp8_write_bit(bc, 0);
1398 vp8_write_bit(bc, pc->filter_type);
1399 vp8_write_literal(bc, pc->filter_level, 6);
1400 vp8_write_literal(bc, pc->sharpness_level, 3);
1402 /* Write out loop filter deltas applied at the MB level based on mode
1403 * or ref frame (if they are enabled).
1405 vp8_write_bit(bc, xd->mode_ref_lf_delta_enabled);
1407 if (xd->mode_ref_lf_delta_enabled)
1409 /* Do the deltas need to be updated */
1410 int send_update = xd->mode_ref_lf_delta_update
1411 || cpi->oxcf.error_resilient_mode;
1413 vp8_write_bit(bc, send_update);
1419 for (i = 0; i < MAX_REF_LF_DELTAS; i++)
1421 Data = xd->ref_lf_deltas[i];
1423 /* Frame level data */
1424 if (xd->ref_lf_deltas[i] != xd->last_ref_lf_deltas[i]
1425 || cpi->oxcf.error_resilient_mode)
1427 xd->last_ref_lf_deltas[i] = xd->ref_lf_deltas[i];
1428 vp8_write_bit(bc, 1);
1432 vp8_write_literal(bc, (Data & 0x3F), 6);
1433 vp8_write_bit(bc, 0); /* sign */
1438 vp8_write_literal(bc, (Data & 0x3F), 6);
1439 vp8_write_bit(bc, 1); /* sign */
1443 vp8_write_bit(bc, 0);
1447 for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
1449 Data = xd->mode_lf_deltas[i];
1451 if (xd->mode_lf_deltas[i] != xd->last_mode_lf_deltas[i]
1452 || cpi->oxcf.error_resilient_mode)
1454 xd->last_mode_lf_deltas[i] = xd->mode_lf_deltas[i];
1455 vp8_write_bit(bc, 1);
1459 vp8_write_literal(bc, (Data & 0x3F), 6);
1460 vp8_write_bit(bc, 0); /* sign */
1465 vp8_write_literal(bc, (Data & 0x3F), 6);
1466 vp8_write_bit(bc, 1); /* sign */
1470 vp8_write_bit(bc, 0);
1475 /* signal here is multi token partition is enabled */
1476 vp8_write_literal(bc, pc->multi_token_partition, 2);
1478 /* Frame Qbaseline quantizer index */
1479 vp8_write_literal(bc, pc->base_qindex, 7);
1481 /* Transmit Dc, Second order and Uv quantizer delta information */
1482 put_delta_q(bc, pc->y1dc_delta_q);
1483 put_delta_q(bc, pc->y2dc_delta_q);
1484 put_delta_q(bc, pc->y2ac_delta_q);
1485 put_delta_q(bc, pc->uvdc_delta_q);
1486 put_delta_q(bc, pc->uvac_delta_q);
1488 /* When there is a key frame all reference buffers are updated using
1491 if (pc->frame_type != KEY_FRAME)
1493 /* Should the GF or ARF be updated using the transmitted frame
1496 vp8_write_bit(bc, pc->refresh_golden_frame);
1497 vp8_write_bit(bc, pc->refresh_alt_ref_frame);
1499 /* If not being updated from current frame should either GF or ARF
1500 * be updated from another buffer
1502 if (!pc->refresh_golden_frame)
1503 vp8_write_literal(bc, pc->copy_buffer_to_gf, 2);
1505 if (!pc->refresh_alt_ref_frame)
1506 vp8_write_literal(bc, pc->copy_buffer_to_arf, 2);
1508 /* Indicate reference frame sign bias for Golden and ARF frames
1509 * (always 0 for last frame buffer)
1511 vp8_write_bit(bc, pc->ref_frame_sign_bias[GOLDEN_FRAME]);
1512 vp8_write_bit(bc, pc->ref_frame_sign_bias[ALTREF_FRAME]);
1515 #if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
1516 if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS)
1518 if (pc->frame_type == KEY_FRAME)
1519 pc->refresh_entropy_probs = 1;
1521 pc->refresh_entropy_probs = 0;
1525 vp8_write_bit(bc, pc->refresh_entropy_probs);
1527 if (pc->frame_type != KEY_FRAME)
1528 vp8_write_bit(bc, pc->refresh_last_frame);
1530 #ifdef VP8_ENTROPY_STATS
1532 if (pc->frame_type == INTER_FRAME)
1539 vp8_clear_system_state();
1541 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1542 pack_coef_probs(cpi);
1544 if (pc->refresh_entropy_probs == 0)
1546 /* save a copy for later refresh */
1547 vpx_memcpy(&cpi->common.lfc, &cpi->common.fc, sizeof(cpi->common.fc));
1550 vp8_update_coef_probs(cpi);
1553 #ifdef VP8_ENTROPY_STATS
1557 /* Write out the mb_no_coeff_skip flag */
1558 vp8_write_bit(bc, pc->mb_no_coeff_skip);
1560 if (pc->frame_type == KEY_FRAME)
1564 #ifdef VP8_ENTROPY_STATS
1570 pack_inter_mode_mvs(cpi);
1572 #ifdef VP8_ENTROPY_STATS
1577 vp8_stop_encode(bc);
1581 oh.first_partition_length_in_bytes = cpi->bc->pos;
1583 /* update frame tag */
1585 int v = (oh.first_partition_length_in_bytes << 5) |
1586 (oh.show_frame << 4) |
1595 *size = VP8_HEADER_SIZE + extra_bytes_packed + cpi->bc->pos;
1597 cpi->partition_sz[0] = *size;
1599 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1601 const int num_part = (1 << pc->multi_token_partition);
1602 unsigned char * dp = cpi->partition_d[0] + cpi->partition_sz[0];
1606 /* write token part sizes (all but last) if more than 1 */
1607 validate_buffer(dp, 3 * (num_part - 1), cpi->partition_d_end[0],
1610 cpi->partition_sz[0] += 3*(num_part-1);
1612 for(i = 1; i < num_part; i++)
1614 write_partition_size(dp, cpi->partition_sz[i]);
1619 if (!cpi->output_partition)
1621 /* concatenate partition buffers */
1622 for(i = 0; i < num_part; i++)
1624 vpx_memmove(dp, cpi->partition_d[i+1], cpi->partition_sz[i+1]);
1625 cpi->partition_d[i+1] = dp;
1626 dp += cpi->partition_sz[i+1];
1630 /* update total size */
1632 for(i = 0; i < num_part+1; i++)
1634 *size += cpi->partition_sz[i];
1638 if (pc->multi_token_partition != ONE_PARTITION)
1640 int num_part = 1 << pc->multi_token_partition;
1642 /* partition size table at the end of first partition */
1643 cpi->partition_sz[0] += 3 * (num_part - 1);
1644 *size += 3 * (num_part - 1);
1646 validate_buffer(cx_data, 3 * (num_part - 1), cx_data_end,
1649 for(i = 1; i < num_part + 1; i++)
1651 cpi->bc[i].error = &pc->error;
1654 pack_tokens_into_partitions(cpi, cx_data + 3 * (num_part - 1),
1655 cx_data_end, num_part);
1657 for(i = 1; i < num_part; i++)
1659 cpi->partition_sz[i] = cpi->bc[i].pos;
1660 write_partition_size(cx_data, cpi->partition_sz[i]);
1662 *size += cpi->partition_sz[i]; /* add to total */
1665 /* add last partition to total size */
1666 cpi->partition_sz[i] = cpi->bc[i].pos;
1667 *size += cpi->partition_sz[i];
1671 bc[1].error = &pc->error;
1673 vp8_start_encode(&cpi->bc[1], cx_data, cx_data_end);
1675 #if CONFIG_MULTITHREAD
1676 if (cpi->b_multi_threaded)
1677 pack_mb_row_tokens(cpi, &cpi->bc[1]);
1680 pack_tokens(&cpi->bc[1], cpi->tok, cpi->tok_count);
1682 vp8_stop_encode(&cpi->bc[1]);
1684 *size += cpi->bc[1].pos;
1685 cpi->partition_sz[1] = cpi->bc[1].pos;
1690 #ifdef VP8_ENTROPY_STATS
1691 void print_tree_update_probs()
1694 FILE *f = fopen("context.c", "a");
1696 fprintf(f, "\n/* Update probabilities for token entropy tree. */\n\n");
1697 fprintf(f, "const vp8_prob tree_update_probs[BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [ENTROPY_NODES] = {\n");
1699 for (i = 0; i < BLOCK_TYPES; i++)
1701 fprintf(f, " { \n");
1703 for (j = 0; j < COEF_BANDS; j++)
1707 for (k = 0; k < PREV_COEF_CONTEXTS; k++)
1711 for (l = 0; l < ENTROPY_NODES; l++)
1713 Sum = tree_update_hist[i][j][k][l][0] + tree_update_hist[i][j][k][l][1];
1717 if (((tree_update_hist[i][j][k][l][0] * 255) / Sum) > 0)
1718 fprintf(f, "%3ld, ", (tree_update_hist[i][j][k][l][0] * 255) / Sum);
1720 fprintf(f, "%3ld, ", 1);
1723 fprintf(f, "%3ld, ", 128);
1729 fprintf(f, " },\n");
1732 fprintf(f, " },\n");