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 "vpx/vpx_encoder.h"
22 #include "vpx_mem/vpx_mem.h"
23 #include "bitstream.h"
25 #include "defaultcoefcounts.h"
26 #include "vp8/common/common.h"
28 const int vp8cx_base_skip_false_prob[128] =
30 255, 255, 255, 255, 255, 255, 255, 255,
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 251, 248, 244, 240, 236, 232, 229, 225,
38 221, 217, 213, 208, 204, 199, 194, 190,
39 187, 183, 179, 175, 172, 168, 164, 160,
40 157, 153, 149, 145, 142, 138, 134, 130,
41 127, 124, 120, 117, 114, 110, 107, 104,
42 101, 98, 95, 92, 89, 86, 83, 80,
43 77, 74, 71, 68, 65, 62, 59, 56,
44 53, 50, 47, 44, 41, 38, 35, 32,
45 30, 28, 26, 24, 22, 20, 18, 16,
48 #if defined(SECTIONBITS_OUTPUT)
49 unsigned __int64 Sectionbits[500];
52 #ifdef VP8_ENTROPY_STATS
53 int intra_mode_stats[10][10][10];
54 static unsigned int tree_update_hist [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [ENTROPY_NODES] [2];
55 extern unsigned int active_section;
59 int count_mb_seg[4] = { 0, 0, 0, 0 };
63 static void update_mode(
66 vp8_token tok [/* n */],
68 vp8_prob Pnew [/* n-1 */],
69 vp8_prob Pcur [/* n-1 */],
70 unsigned int bct [/* n-1 */] [2],
71 const unsigned int num_events[/* n */]
74 unsigned int new_b = 0, old_b = 0;
77 vp8_tree_probs_from_distribution(
79 Pnew, bct, num_events,
85 new_b += vp8_cost_branch(bct[i], Pnew[i]);
86 old_b += vp8_cost_branch(bct[i], Pcur[i]);
90 if (new_b + (n << 8) < old_b)
98 const vp8_prob p = Pnew[j];
100 vp8_write_literal(w, Pcur[j] = p ? p : 1, 8);
108 static void update_mbintra_mode_probs(VP8_COMP *cpi)
110 VP8_COMMON *const x = & cpi->common;
112 vp8_writer *const w = cpi->bc;
115 vp8_prob Pnew [VP8_YMODES-1];
116 unsigned int bct [VP8_YMODES-1] [2];
119 w, VP8_YMODES, vp8_ymode_encodings, vp8_ymode_tree,
120 Pnew, x->fc.ymode_prob, bct, (unsigned int *)cpi->mb.ymode_count
124 vp8_prob Pnew [VP8_UV_MODES-1];
125 unsigned int bct [VP8_UV_MODES-1] [2];
128 w, VP8_UV_MODES, vp8_uv_mode_encodings, vp8_uv_mode_tree,
129 Pnew, x->fc.uv_mode_prob, bct, (unsigned int *)cpi->mb.uv_mode_count
134 static void write_ymode(vp8_writer *bc, int m, const vp8_prob *p)
136 vp8_write_token(bc, vp8_ymode_tree, p, vp8_ymode_encodings + m);
139 static void kfwrite_ymode(vp8_writer *bc, int m, const vp8_prob *p)
141 vp8_write_token(bc, vp8_kf_ymode_tree, p, vp8_kf_ymode_encodings + m);
144 static void write_uv_mode(vp8_writer *bc, int m, const vp8_prob *p)
146 vp8_write_token(bc, vp8_uv_mode_tree, p, vp8_uv_mode_encodings + m);
150 static void write_bmode(vp8_writer *bc, int m, const vp8_prob *p)
152 vp8_write_token(bc, vp8_bmode_tree, p, vp8_bmode_encodings + m);
155 static void write_split(vp8_writer *bc, int x)
158 bc, vp8_mbsplit_tree, vp8_mbsplit_probs, vp8_mbsplit_encodings + x
162 void vp8_pack_tokens(vp8_writer *w, const TOKENEXTRA *p, int xcount)
164 const TOKENEXTRA *stop = p + xcount;
167 int count = w->count;
168 unsigned int range = w->range;
169 unsigned int lowvalue = w->lowvalue;
173 const int t = p->Token;
174 vp8_token *a = vp8_coef_encodings + t;
175 const vp8_extra_bit_struct *b = vp8_extra_bits + t;
177 const unsigned char *pp = p->context_tree;
181 if (p->skip_eob_node)
189 const int bb = (v >> --n) & 1;
190 split = 1 + (((range - 1) * pp[i>>1]) >> 8);
191 i = vp8_coef_tree[i+bb];
196 range = range - split;
203 shift = vp8_norm[range];
209 int offset = shift - count;
211 if ((lowvalue << (offset - 1)) & 0x80000000)
215 while (x >= 0 && w->buffer[x] == 0xff)
217 w->buffer[x] = (unsigned char)0;
224 validate_buffer(w->buffer + w->pos,
229 w->buffer[w->pos++] = (lowvalue >> (24 - offset));
232 lowvalue &= 0xffffff;
243 const int e = p->Extra, L = b->Len;
247 const unsigned char *proba = b->prob;
248 const int v2 = e >> 1;
249 int n2 = L; /* number of bits in v2, assumed nonzero */
254 const int bb = (v2 >> --n2) & 1;
255 split = 1 + (((range - 1) * proba[i>>1]) >> 8);
261 range = range - split;
268 shift = vp8_norm[range];
274 int offset = shift - count;
276 if ((lowvalue << (offset - 1)) & 0x80000000)
280 while (x >= 0 && w->buffer[x] == 0xff)
282 w->buffer[x] = (unsigned char)0;
289 validate_buffer(w->buffer + w->pos,
294 w->buffer[w->pos++] = (lowvalue >> (24 - offset));
297 lowvalue &= 0xffffff;
309 split = (range + 1) >> 1;
314 range = range - split;
323 if ((lowvalue & 0x80000000))
327 while (x >= 0 && w->buffer[x] == 0xff)
329 w->buffer[x] = (unsigned char)0;
343 validate_buffer(w->buffer + w->pos,
348 w->buffer[w->pos++] = (lowvalue >> 24);
349 lowvalue &= 0xffffff;
359 w->lowvalue = lowvalue;
364 static void write_partition_size(unsigned char *cx_data, int size)
370 csize = (size >> 8) & 0xff;
371 *(cx_data + 1) = csize;
372 csize = (size >> 16) & 0xff;
373 *(cx_data + 2) = csize;
377 static void pack_tokens_into_partitions(VP8_COMP *cpi, unsigned char *cx_data,
378 unsigned char * cx_data_end,
383 unsigned char *ptr = cx_data;
384 unsigned char *ptr_end = cx_data_end;
387 for (i = 0; i < num_part; i++)
393 vp8_start_encode(w, ptr, ptr_end);
395 for (mb_row = i; mb_row < cpi->common.mb_rows; mb_row += num_part)
397 const TOKENEXTRA *p = cpi->tplist[mb_row].start;
398 const TOKENEXTRA *stop = cpi->tplist[mb_row].stop;
399 int tokens = (int)(stop - p);
401 vp8_pack_tokens(w, p, tokens);
410 static void pack_mb_row_tokens(VP8_COMP *cpi, vp8_writer *w)
414 for (mb_row = 0; mb_row < cpi->common.mb_rows; mb_row++)
416 const TOKENEXTRA *p = cpi->tplist[mb_row].start;
417 const TOKENEXTRA *stop = cpi->tplist[mb_row].stop;
418 int tokens = (int)(stop - p);
420 vp8_pack_tokens(w, p, tokens);
425 static void write_mv_ref
427 vp8_writer *w, MB_PREDICTION_MODE m, const vp8_prob *p
431 assert(NEARESTMV <= m && m <= SPLITMV);
433 vp8_write_token(w, vp8_mv_ref_tree, p,
434 vp8_mv_ref_encoding_array + (m - NEARESTMV));
437 static void write_sub_mv_ref
439 vp8_writer *w, B_PREDICTION_MODE m, const vp8_prob *p
443 assert(LEFT4X4 <= m && m <= NEW4X4);
445 vp8_write_token(w, vp8_sub_mv_ref_tree, p,
446 vp8_sub_mv_ref_encoding_array + (m - LEFT4X4));
451 vp8_writer *w, const MV *mv, const int_mv *ref, const MV_CONTEXT *mvc
455 e.row = mv->row - ref->as_mv.row;
456 e.col = mv->col - ref->as_mv.col;
458 vp8_encode_motion_vector(w, &e, mvc);
461 static void write_mb_features(vp8_writer *w, const MB_MODE_INFO *mi, const MACROBLOCKD *x)
463 /* Encode the MB segment id. */
464 if (x->segmentation_enabled && x->update_mb_segmentation_map)
466 switch (mi->segment_id)
469 vp8_write(w, 0, x->mb_segment_tree_probs[0]);
470 vp8_write(w, 0, x->mb_segment_tree_probs[1]);
473 vp8_write(w, 0, x->mb_segment_tree_probs[0]);
474 vp8_write(w, 1, x->mb_segment_tree_probs[1]);
477 vp8_write(w, 1, x->mb_segment_tree_probs[0]);
478 vp8_write(w, 0, x->mb_segment_tree_probs[2]);
481 vp8_write(w, 1, x->mb_segment_tree_probs[0]);
482 vp8_write(w, 1, x->mb_segment_tree_probs[2]);
485 /* TRAP.. This should not happen */
487 vp8_write(w, 0, x->mb_segment_tree_probs[0]);
488 vp8_write(w, 0, x->mb_segment_tree_probs[1]);
493 void vp8_convert_rfct_to_prob(VP8_COMP *const cpi)
495 const int *const rfct = cpi->mb.count_mb_ref_frame_usage;
496 const int rf_intra = rfct[INTRA_FRAME];
497 const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
499 /* Calculate the probabilities used to code the ref frame based on usage */
500 if (!(cpi->prob_intra_coded = rf_intra * 255 / (rf_intra + rf_inter)))
501 cpi->prob_intra_coded = 1;
503 cpi->prob_last_coded = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
505 if (!cpi->prob_last_coded)
506 cpi->prob_last_coded = 1;
508 cpi->prob_gf_coded = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
509 ? (rfct[GOLDEN_FRAME] * 255) / (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME]) : 128;
511 if (!cpi->prob_gf_coded)
512 cpi->prob_gf_coded = 1;
516 static void pack_inter_mode_mvs(VP8_COMP *const cpi)
518 VP8_COMMON *const pc = & cpi->common;
519 vp8_writer *const w = cpi->bc;
520 const MV_CONTEXT *mvc = pc->fc.mvc;
523 MODE_INFO *m = pc->mi;
524 const int mis = pc->mode_info_stride;
527 int prob_skip_false = 0;
529 cpi->mb.partition_info = cpi->mb.pi;
531 vp8_convert_rfct_to_prob(cpi);
533 #ifdef VP8_ENTROPY_STATS
537 if (pc->mb_no_coeff_skip)
539 int total_mbs = pc->mb_rows * pc->mb_cols;
541 prob_skip_false = (total_mbs - cpi->mb.skip_true_count ) * 256 / total_mbs;
543 if (prob_skip_false <= 1)
546 if (prob_skip_false > 255)
547 prob_skip_false = 255;
549 cpi->prob_skip_false = prob_skip_false;
550 vp8_write_literal(w, prob_skip_false, 8);
553 vp8_write_literal(w, cpi->prob_intra_coded, 8);
554 vp8_write_literal(w, cpi->prob_last_coded, 8);
555 vp8_write_literal(w, cpi->prob_gf_coded, 8);
557 update_mbintra_mode_probs(cpi);
559 vp8_write_mvprobs(cpi);
561 while (++mb_row < pc->mb_rows)
565 while (++mb_col < pc->mb_cols)
567 const MB_MODE_INFO *const mi = & m->mbmi;
568 const MV_REFERENCE_FRAME rf = mi->ref_frame;
569 const MB_PREDICTION_MODE mode = mi->mode;
571 MACROBLOCKD *xd = &cpi->mb.e_mbd;
573 /* Distance of Mb to the various image edges.
574 * These specified to 8th pel as they are always compared to MV
575 * values that are in 1/8th pel units
577 xd->mb_to_left_edge = -((mb_col * 16) << 3);
578 xd->mb_to_right_edge = ((pc->mb_cols - 1 - mb_col) * 16) << 3;
579 xd->mb_to_top_edge = -((mb_row * 16) << 3);
580 xd->mb_to_bottom_edge = ((pc->mb_rows - 1 - mb_row) * 16) << 3;
582 #ifdef VP8_ENTROPY_STATS
586 if (cpi->mb.e_mbd.update_mb_segmentation_map)
587 write_mb_features(w, mi, &cpi->mb.e_mbd);
589 if (pc->mb_no_coeff_skip)
590 vp8_encode_bool(w, m->mbmi.mb_skip_coeff, prob_skip_false);
592 if (rf == INTRA_FRAME)
594 vp8_write(w, 0, cpi->prob_intra_coded);
595 #ifdef VP8_ENTROPY_STATS
598 write_ymode(w, mode, pc->fc.ymode_prob);
605 write_bmode(w, m->bmi[j].as_mode, pc->fc.bmode_prob);
609 write_uv_mode(w, mi->uv_mode, pc->fc.uv_mode_prob);
611 else /* inter coded */
614 vp8_prob mv_ref_p [VP8_MVREFS-1];
616 vp8_write(w, 1, cpi->prob_intra_coded);
618 if (rf == LAST_FRAME)
619 vp8_write(w, 0, cpi->prob_last_coded);
622 vp8_write(w, 1, cpi->prob_last_coded);
623 vp8_write(w, (rf == GOLDEN_FRAME) ? 0 : 1, cpi->prob_gf_coded);
630 vp8_find_near_mvs(xd, m, &n1, &n2, &best_mv, ct, rf, cpi->common.ref_frame_sign_bias);
631 vp8_clamp_mv2(&best_mv, xd);
633 vp8_mv_ref_probs(mv_ref_p, ct);
635 #ifdef VP8_ENTROPY_STATS
636 accum_mv_refs(mode, ct);
641 #ifdef VP8_ENTROPY_STATS
645 write_mv_ref(w, mode, mv_ref_p);
647 switch (mode) /* new, split require MVs */
651 #ifdef VP8_ENTROPY_STATS
655 write_mv(w, &mi->mv.as_mv, &best_mv, mvc);
663 ++count_mb_seg [mi->partitioning];
666 write_split(w, mi->partitioning);
670 B_PREDICTION_MODE blockmode;
672 const int *const L = vp8_mbsplits [mi->partitioning];
673 int k = -1; /* first block in subset j */
675 int_mv leftmv, abovemv;
677 blockmode = cpi->mb.partition_info->bmi[j].mode;
678 blockmv = cpi->mb.partition_info->bmi[j].mv;
686 leftmv.as_int = left_block_mv(m, k);
687 abovemv.as_int = above_block_mv(m, k, mis);
688 mv_contz = vp8_mv_cont(&leftmv, &abovemv);
690 write_sub_mv_ref(w, blockmode, vp8_sub_mv_ref_prob2 [mv_contz]);
692 if (blockmode == NEW4X4)
694 #ifdef VP8_ENTROPY_STATS
697 write_mv(w, &blockmv.as_mv, &best_mv, (const MV_CONTEXT *) mvc);
700 while (++j < cpi->mb.partition_info->count);
709 cpi->mb.partition_info++;
712 ++m; /* skip L prediction border */
713 cpi->mb.partition_info++;
718 static void write_kfmodes(VP8_COMP *cpi)
720 vp8_writer *const bc = cpi->bc;
721 const VP8_COMMON *const c = & cpi->common;
723 MODE_INFO *m = c->mi;
726 int prob_skip_false = 0;
728 if (c->mb_no_coeff_skip)
730 int total_mbs = c->mb_rows * c->mb_cols;
732 prob_skip_false = (total_mbs - cpi->mb.skip_true_count ) * 256 / total_mbs;
734 if (prob_skip_false <= 1)
737 if (prob_skip_false >= 255)
738 prob_skip_false = 255;
740 cpi->prob_skip_false = prob_skip_false;
741 vp8_write_literal(bc, prob_skip_false, 8);
744 while (++mb_row < c->mb_rows)
748 while (++mb_col < c->mb_cols)
750 const int ym = m->mbmi.mode;
752 if (cpi->mb.e_mbd.update_mb_segmentation_map)
753 write_mb_features(bc, &m->mbmi, &cpi->mb.e_mbd);
755 if (c->mb_no_coeff_skip)
756 vp8_encode_bool(bc, m->mbmi.mb_skip_coeff, prob_skip_false);
758 kfwrite_ymode(bc, ym, vp8_kf_ymode_prob);
762 const int mis = c->mode_info_stride;
767 const B_PREDICTION_MODE A = above_block_mode(m, i, mis);
768 const B_PREDICTION_MODE L = left_block_mode(m, i);
769 const int bm = m->bmi[i].as_mode;
771 #ifdef VP8_ENTROPY_STATS
772 ++intra_mode_stats [A] [L] [bm];
775 write_bmode(bc, bm, vp8_kf_bmode_prob [A] [L]);
780 write_uv_mode(bc, (m++)->mbmi.uv_mode, vp8_kf_uv_mode_prob);
783 m++; /* skip L prediction border */
788 /* This function is used for debugging probability trees. */
789 static void print_prob_tree(vp8_prob
790 coef_probs[BLOCK_TYPES][COEF_BANDS][PREV_COEF_CONTEXTS][ENTROPY_NODES])
792 /* print coef probability tree */
794 FILE* f = fopen("enc_tree_probs.txt", "a");
796 for (i = 0; i < BLOCK_TYPES; i++)
799 for (j = 0; j < COEF_BANDS; j++)
802 for (k = 0; k < PREV_COEF_CONTEXTS; k++)
805 for (l = 0; l < ENTROPY_NODES; l++)
808 (unsigned int)(coef_probs [i][j][k][l]));
821 static void sum_probs_over_prev_coef_context(
822 const unsigned int probs[PREV_COEF_CONTEXTS][MAX_ENTROPY_TOKENS],
826 for (i=0; i < MAX_ENTROPY_TOKENS; ++i)
828 for (j=0; j < PREV_COEF_CONTEXTS; ++j)
830 const unsigned int tmp = out[i];
831 out[i] += probs[j][i];
839 static int prob_update_savings(const unsigned int *ct,
840 const vp8_prob oldp, const vp8_prob newp,
843 const int old_b = vp8_cost_branch(ct, oldp);
844 const int new_b = vp8_cost_branch(ct, newp);
845 const int update_b = 8 +
846 ((vp8_cost_one(upd) - vp8_cost_zero(upd)) >> 8);
848 return old_b - new_b - update_b;
851 static int independent_coef_context_savings(VP8_COMP *cpi)
853 MACROBLOCK *const x = & cpi->mb;
862 unsigned int prev_coef_count_sum[MAX_ENTROPY_TOKENS] = {0};
863 int prev_coef_savings[MAX_ENTROPY_TOKENS] = {0};
864 const unsigned int (*probs)[MAX_ENTROPY_TOKENS];
865 /* Calculate new probabilities given the constraint that
866 * they must be equal over the prev coef contexts
869 probs = (const unsigned int (*)[MAX_ENTROPY_TOKENS])
870 x->coef_counts[i][j];
872 /* Reset to default probabilities at key frames */
873 if (cpi->common.frame_type == KEY_FRAME)
874 probs = default_coef_counts[i][j];
876 sum_probs_over_prev_coef_context(probs, prev_coef_count_sum);
880 /* at every context */
882 /* calc probs and branch cts for this frame only */
883 int t = 0; /* token/prob index */
885 vp8_tree_probs_from_distribution(
886 MAX_ENTROPY_TOKENS, vp8_coef_encodings, vp8_coef_tree,
887 cpi->frame_coef_probs[i][j][k],
888 cpi->frame_branch_ct [i][j][k],
894 const unsigned int *ct = cpi->frame_branch_ct [i][j][k][t];
895 const vp8_prob newp = cpi->frame_coef_probs [i][j][k][t];
896 const vp8_prob oldp = cpi->common.fc.coef_probs [i][j][k][t];
897 const vp8_prob upd = vp8_coef_update_probs [i][j][k][t];
898 const int s = prob_update_savings(ct, oldp, newp, upd);
900 if (cpi->common.frame_type != KEY_FRAME ||
901 (cpi->common.frame_type == KEY_FRAME && newp != oldp))
902 prev_coef_savings[t] += s;
904 while (++t < ENTROPY_NODES);
906 while (++k < PREV_COEF_CONTEXTS);
910 /* We only update probabilities if we can save bits, except
911 * for key frames where we have to update all probabilities
912 * to get the equal probabilities across the prev coef
915 if (prev_coef_savings[k] > 0 ||
916 cpi->common.frame_type == KEY_FRAME)
917 savings += prev_coef_savings[k];
919 while (++k < ENTROPY_NODES);
921 while (++j < COEF_BANDS);
923 while (++i < BLOCK_TYPES);
927 static int default_coef_context_savings(VP8_COMP *cpi)
929 MACROBLOCK *const x = & cpi->mb;
940 /* at every context */
942 /* calc probs and branch cts for this frame only */
943 int t = 0; /* token/prob index */
945 vp8_tree_probs_from_distribution(
946 MAX_ENTROPY_TOKENS, vp8_coef_encodings, vp8_coef_tree,
947 cpi->frame_coef_probs [i][j][k],
948 cpi->frame_branch_ct [i][j][k],
949 x->coef_counts [i][j][k],
955 const unsigned int *ct = cpi->frame_branch_ct [i][j][k][t];
956 const vp8_prob newp = cpi->frame_coef_probs [i][j][k][t];
957 const vp8_prob oldp = cpi->common.fc.coef_probs [i][j][k][t];
958 const vp8_prob upd = vp8_coef_update_probs [i][j][k][t];
959 const int s = prob_update_savings(ct, oldp, newp, upd);
966 while (++t < ENTROPY_NODES);
968 while (++k < PREV_COEF_CONTEXTS);
970 while (++j < COEF_BANDS);
972 while (++i < BLOCK_TYPES);
976 void vp8_calc_ref_frame_costs(int *ref_frame_cost,
982 assert(prob_intra >= 0);
983 assert(prob_intra <= 255);
984 assert(prob_last >= 0);
985 assert(prob_last <= 255);
986 assert(prob_garf >= 0);
987 assert(prob_garf <= 255);
988 ref_frame_cost[INTRA_FRAME] = vp8_cost_zero(prob_intra);
989 ref_frame_cost[LAST_FRAME] = vp8_cost_one(prob_intra)
990 + vp8_cost_zero(prob_last);
991 ref_frame_cost[GOLDEN_FRAME] = vp8_cost_one(prob_intra)
992 + vp8_cost_one(prob_last)
993 + vp8_cost_zero(prob_garf);
994 ref_frame_cost[ALTREF_FRAME] = vp8_cost_one(prob_intra)
995 + vp8_cost_one(prob_last)
996 + vp8_cost_one(prob_garf);
1000 int vp8_estimate_entropy_savings(VP8_COMP *cpi)
1004 const int *const rfct = cpi->mb.count_mb_ref_frame_usage;
1005 const int rf_intra = rfct[INTRA_FRAME];
1006 const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
1007 int new_intra, new_last, new_garf, oldtotal, newtotal;
1008 int ref_frame_cost[MAX_REF_FRAMES];
1010 vp8_clear_system_state();
1012 if (cpi->common.frame_type != KEY_FRAME)
1014 if (!(new_intra = rf_intra * 255 / (rf_intra + rf_inter)))
1017 new_last = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
1019 new_garf = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
1020 ? (rfct[GOLDEN_FRAME] * 255) / (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME]) : 128;
1023 vp8_calc_ref_frame_costs(ref_frame_cost,new_intra,new_last,new_garf);
1026 rfct[INTRA_FRAME] * ref_frame_cost[INTRA_FRAME] +
1027 rfct[LAST_FRAME] * ref_frame_cost[LAST_FRAME] +
1028 rfct[GOLDEN_FRAME] * ref_frame_cost[GOLDEN_FRAME] +
1029 rfct[ALTREF_FRAME] * ref_frame_cost[ALTREF_FRAME];
1033 vp8_calc_ref_frame_costs(ref_frame_cost,cpi->prob_intra_coded,
1034 cpi->prob_last_coded,cpi->prob_gf_coded);
1037 rfct[INTRA_FRAME] * ref_frame_cost[INTRA_FRAME] +
1038 rfct[LAST_FRAME] * ref_frame_cost[LAST_FRAME] +
1039 rfct[GOLDEN_FRAME] * ref_frame_cost[GOLDEN_FRAME] +
1040 rfct[ALTREF_FRAME] * ref_frame_cost[ALTREF_FRAME];
1042 savings += (oldtotal - newtotal) / 256;
1046 if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS)
1047 savings += independent_coef_context_savings(cpi);
1049 savings += default_coef_context_savings(cpi);
1055 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1056 int vp8_update_coef_context(VP8_COMP *cpi)
1061 if (cpi->common.frame_type == KEY_FRAME)
1063 /* Reset to default counts/probabilities at key frames */
1064 vp8_copy(cpi->mb.coef_counts, default_coef_counts);
1067 if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS)
1068 savings += independent_coef_context_savings(cpi);
1070 savings += default_coef_context_savings(cpi);
1076 void vp8_update_coef_probs(VP8_COMP *cpi)
1079 #if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
1080 vp8_writer *const w = cpi->bc;
1084 vp8_clear_system_state();
1093 int prev_coef_savings[ENTROPY_NODES] = {0};
1094 if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS)
1096 for (k = 0; k < PREV_COEF_CONTEXTS; ++k)
1098 int t; /* token/prob index */
1099 for (t = 0; t < ENTROPY_NODES; ++t)
1101 const unsigned int *ct = cpi->frame_branch_ct [i][j]
1103 const vp8_prob newp = cpi->frame_coef_probs[i][j][k][t];
1104 const vp8_prob oldp = cpi->common.fc.coef_probs[i][j]
1106 const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
1108 prev_coef_savings[t] +=
1109 prob_update_savings(ct, oldp, newp, upd);
1116 /* note: use result from vp8_estimate_entropy_savings, so no
1117 * need to call vp8_tree_probs_from_distribution here.
1120 /* at every context */
1122 /* calc probs and branch cts for this frame only */
1123 int t = 0; /* token/prob index */
1127 const vp8_prob newp = cpi->frame_coef_probs [i][j][k][t];
1129 vp8_prob *Pold = cpi->common.fc.coef_probs [i][j][k] + t;
1130 const vp8_prob upd = vp8_coef_update_probs [i][j][k][t];
1132 int s = prev_coef_savings[t];
1135 if (!(cpi->oxcf.error_resilient_mode &
1136 VPX_ERROR_RESILIENT_PARTITIONS))
1138 s = prob_update_savings(
1139 cpi->frame_branch_ct [i][j][k][t],
1146 /* Force updates on key frames if the new is different,
1147 * so that we can be sure we end up with equal probabilities
1148 * over the prev coef contexts.
1150 if ((cpi->oxcf.error_resilient_mode &
1151 VPX_ERROR_RESILIENT_PARTITIONS) &&
1152 cpi->common.frame_type == KEY_FRAME && newp != *Pold)
1155 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1156 cpi->update_probs[i][j][k][t] = u;
1158 vp8_write(w, u, upd);
1162 #ifdef VP8_ENTROPY_STATS
1163 ++ tree_update_hist [i][j][k][t] [u];
1168 /* send/use new probability */
1171 #if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
1172 vp8_write_literal(w, newp, 8);
1180 while (++t < ENTROPY_NODES);
1182 /* Accum token counts for generation of default statistics */
1183 #ifdef VP8_ENTROPY_STATS
1188 context_counters [i][j][k][t] += cpi->coef_counts [i][j][k][t];
1190 while (++t < MAX_ENTROPY_TOKENS);
1195 while (++k < PREV_COEF_CONTEXTS);
1197 while (++j < COEF_BANDS);
1199 while (++i < BLOCK_TYPES);
1203 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1204 static void pack_coef_probs(VP8_COMP *cpi)
1207 vp8_writer *const w = cpi->bc;
1219 int t = 0; /* token/prob index */
1223 const vp8_prob newp = cpi->common.fc.coef_probs [i][j][k][t];
1224 const vp8_prob upd = vp8_coef_update_probs [i][j][k][t];
1226 const char u = cpi->update_probs[i][j][k][t] ;
1228 vp8_write(w, u, upd);
1232 /* send/use new probability */
1233 vp8_write_literal(w, newp, 8);
1236 while (++t < ENTROPY_NODES);
1238 while (++k < PREV_COEF_CONTEXTS);
1240 while (++j < COEF_BANDS);
1242 while (++i < BLOCK_TYPES);
1246 #ifdef PACKET_TESTING
1250 static void put_delta_q(vp8_writer *bc, int delta_q)
1254 vp8_write_bit(bc, 1);
1255 vp8_write_literal(bc, abs(delta_q), 4);
1258 vp8_write_bit(bc, 1);
1260 vp8_write_bit(bc, 0);
1263 vp8_write_bit(bc, 0);
1266 void vp8_pack_bitstream(VP8_COMP *cpi, unsigned char *dest, unsigned char * dest_end, unsigned long *size)
1270 VP8_COMMON *const pc = & cpi->common;
1271 vp8_writer *const bc = cpi->bc;
1272 MACROBLOCKD *const xd = & cpi->mb.e_mbd;
1273 int extra_bytes_packed = 0;
1275 unsigned char *cx_data = dest;
1276 unsigned char *cx_data_end = dest_end;
1277 const int *mb_feature_data_bits;
1279 oh.show_frame = (int) pc->show_frame;
1280 oh.type = (int)pc->frame_type;
1281 oh.version = pc->version;
1282 oh.first_partition_length_in_bytes = 0;
1284 mb_feature_data_bits = vp8_mb_feature_data_bits;
1286 bc[0].error = &pc->error;
1288 validate_buffer(cx_data, 3, cx_data_end, &cpi->common.error);
1291 #if defined(SECTIONBITS_OUTPUT)
1292 Sectionbits[active_section = 1] += sizeof(VP8_HEADER) * 8 * 256;
1295 /* every keyframe send startcode, width, height, scale factor, clamp
1298 if (oh.type == KEY_FRAME)
1302 validate_buffer(cx_data, 7, cx_data_end, &cpi->common.error);
1304 /* Start / synch code */
1309 v = (pc->horiz_scale << 14) | pc->Width;
1311 cx_data[4] = v >> 8;
1313 v = (pc->vert_scale << 14) | pc->Height;
1315 cx_data[6] = v >> 8;
1318 extra_bytes_packed = 7;
1319 cx_data += extra_bytes_packed ;
1321 vp8_start_encode(bc, cx_data, cx_data_end);
1323 /* signal clr type */
1324 vp8_write_bit(bc, 0);
1325 vp8_write_bit(bc, pc->clamp_type);
1329 vp8_start_encode(bc, cx_data, cx_data_end);
1332 /* Signal whether or not Segmentation is enabled */
1333 vp8_write_bit(bc, xd->segmentation_enabled);
1335 /* Indicate which features are enabled */
1336 if (xd->segmentation_enabled)
1338 /* Signal whether or not the segmentation map is being updated. */
1339 vp8_write_bit(bc, xd->update_mb_segmentation_map);
1340 vp8_write_bit(bc, xd->update_mb_segmentation_data);
1342 if (xd->update_mb_segmentation_data)
1346 vp8_write_bit(bc, xd->mb_segement_abs_delta);
1348 /* For each segmentation feature (Quant and loop filter level) */
1349 for (i = 0; i < MB_LVL_MAX; i++)
1351 /* For each of the segments */
1352 for (j = 0; j < MAX_MB_SEGMENTS; j++)
1354 Data = xd->segment_feature_data[i][j];
1356 /* Frame level data */
1359 vp8_write_bit(bc, 1);
1364 vp8_write_literal(bc, Data, mb_feature_data_bits[i]);
1365 vp8_write_bit(bc, 1);
1369 vp8_write_literal(bc, Data, mb_feature_data_bits[i]);
1370 vp8_write_bit(bc, 0);
1374 vp8_write_bit(bc, 0);
1379 if (xd->update_mb_segmentation_map)
1381 /* Write the probs used to decode the segment id for each mb */
1382 for (i = 0; i < MB_FEATURE_TREE_PROBS; i++)
1384 int Data = xd->mb_segment_tree_probs[i];
1388 vp8_write_bit(bc, 1);
1389 vp8_write_literal(bc, Data, 8);
1392 vp8_write_bit(bc, 0);
1397 vp8_write_bit(bc, pc->filter_type);
1398 vp8_write_literal(bc, pc->filter_level, 6);
1399 vp8_write_literal(bc, pc->sharpness_level, 3);
1401 /* Write out loop filter deltas applied at the MB level based on mode
1402 * or ref frame (if they are enabled).
1404 vp8_write_bit(bc, xd->mode_ref_lf_delta_enabled);
1406 if (xd->mode_ref_lf_delta_enabled)
1408 /* Do the deltas need to be updated */
1409 int send_update = xd->mode_ref_lf_delta_update
1410 || cpi->oxcf.error_resilient_mode;
1412 vp8_write_bit(bc, send_update);
1418 for (i = 0; i < MAX_REF_LF_DELTAS; i++)
1420 Data = xd->ref_lf_deltas[i];
1422 /* Frame level data */
1423 if (xd->ref_lf_deltas[i] != xd->last_ref_lf_deltas[i]
1424 || cpi->oxcf.error_resilient_mode)
1426 xd->last_ref_lf_deltas[i] = xd->ref_lf_deltas[i];
1427 vp8_write_bit(bc, 1);
1431 vp8_write_literal(bc, (Data & 0x3F), 6);
1432 vp8_write_bit(bc, 0); /* sign */
1437 vp8_write_literal(bc, (Data & 0x3F), 6);
1438 vp8_write_bit(bc, 1); /* sign */
1442 vp8_write_bit(bc, 0);
1446 for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
1448 Data = xd->mode_lf_deltas[i];
1450 if (xd->mode_lf_deltas[i] != xd->last_mode_lf_deltas[i]
1451 || cpi->oxcf.error_resilient_mode)
1453 xd->last_mode_lf_deltas[i] = xd->mode_lf_deltas[i];
1454 vp8_write_bit(bc, 1);
1458 vp8_write_literal(bc, (Data & 0x3F), 6);
1459 vp8_write_bit(bc, 0); /* sign */
1464 vp8_write_literal(bc, (Data & 0x3F), 6);
1465 vp8_write_bit(bc, 1); /* sign */
1469 vp8_write_bit(bc, 0);
1474 /* signal here is multi token partition is enabled */
1475 vp8_write_literal(bc, pc->multi_token_partition, 2);
1477 /* Frame Qbaseline quantizer index */
1478 vp8_write_literal(bc, pc->base_qindex, 7);
1480 /* Transmit Dc, Second order and Uv quantizer delta information */
1481 put_delta_q(bc, pc->y1dc_delta_q);
1482 put_delta_q(bc, pc->y2dc_delta_q);
1483 put_delta_q(bc, pc->y2ac_delta_q);
1484 put_delta_q(bc, pc->uvdc_delta_q);
1485 put_delta_q(bc, pc->uvac_delta_q);
1487 /* When there is a key frame all reference buffers are updated using
1490 if (pc->frame_type != KEY_FRAME)
1492 /* Should the GF or ARF be updated using the transmitted frame
1495 vp8_write_bit(bc, pc->refresh_golden_frame);
1496 vp8_write_bit(bc, pc->refresh_alt_ref_frame);
1498 /* If not being updated from current frame should either GF or ARF
1499 * be updated from another buffer
1501 if (!pc->refresh_golden_frame)
1502 vp8_write_literal(bc, pc->copy_buffer_to_gf, 2);
1504 if (!pc->refresh_alt_ref_frame)
1505 vp8_write_literal(bc, pc->copy_buffer_to_arf, 2);
1507 /* Indicate reference frame sign bias for Golden and ARF frames
1508 * (always 0 for last frame buffer)
1510 vp8_write_bit(bc, pc->ref_frame_sign_bias[GOLDEN_FRAME]);
1511 vp8_write_bit(bc, pc->ref_frame_sign_bias[ALTREF_FRAME]);
1514 #if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
1515 if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS)
1517 if (pc->frame_type == KEY_FRAME)
1518 pc->refresh_entropy_probs = 1;
1520 pc->refresh_entropy_probs = 0;
1524 vp8_write_bit(bc, pc->refresh_entropy_probs);
1526 if (pc->frame_type != KEY_FRAME)
1527 vp8_write_bit(bc, pc->refresh_last_frame);
1529 #ifdef VP8_ENTROPY_STATS
1531 if (pc->frame_type == INTER_FRAME)
1538 vp8_clear_system_state();
1540 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1541 pack_coef_probs(cpi);
1543 if (pc->refresh_entropy_probs == 0)
1545 /* save a copy for later refresh */
1546 vpx_memcpy(&cpi->common.lfc, &cpi->common.fc, sizeof(cpi->common.fc));
1549 vp8_update_coef_probs(cpi);
1552 #ifdef VP8_ENTROPY_STATS
1556 /* Write out the mb_no_coeff_skip flag */
1557 vp8_write_bit(bc, pc->mb_no_coeff_skip);
1559 if (pc->frame_type == KEY_FRAME)
1563 #ifdef VP8_ENTROPY_STATS
1569 pack_inter_mode_mvs(cpi);
1571 #ifdef VP8_ENTROPY_STATS
1576 vp8_stop_encode(bc);
1580 oh.first_partition_length_in_bytes = cpi->bc->pos;
1582 /* update frame tag */
1584 int v = (oh.first_partition_length_in_bytes << 5) |
1585 (oh.show_frame << 4) |
1594 *size = VP8_HEADER_SIZE + extra_bytes_packed + cpi->bc->pos;
1596 cpi->partition_sz[0] = *size;
1598 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1600 const int num_part = (1 << pc->multi_token_partition);
1601 unsigned char * dp = cpi->partition_d[0] + cpi->partition_sz[0];
1605 /* write token part sizes (all but last) if more than 1 */
1606 validate_buffer(dp, 3 * (num_part - 1), cpi->partition_d_end[0],
1609 cpi->partition_sz[0] += 3*(num_part-1);
1611 for(i = 1; i < num_part; i++)
1613 write_partition_size(dp, cpi->partition_sz[i]);
1618 if (!cpi->output_partition)
1620 /* concatenate partition buffers */
1621 for(i = 0; i < num_part; i++)
1623 vpx_memmove(dp, cpi->partition_d[i+1], cpi->partition_sz[i+1]);
1624 cpi->partition_d[i+1] = dp;
1625 dp += cpi->partition_sz[i+1];
1629 /* update total size */
1631 for(i = 0; i < num_part+1; i++)
1633 *size += cpi->partition_sz[i];
1637 if (pc->multi_token_partition != ONE_PARTITION)
1639 int num_part = 1 << pc->multi_token_partition;
1641 /* partition size table at the end of first partition */
1642 cpi->partition_sz[0] += 3 * (num_part - 1);
1643 *size += 3 * (num_part - 1);
1645 validate_buffer(cx_data, 3 * (num_part - 1), cx_data_end,
1648 for(i = 1; i < num_part + 1; i++)
1650 cpi->bc[i].error = &pc->error;
1653 pack_tokens_into_partitions(cpi, cx_data + 3 * (num_part - 1),
1654 cx_data_end, num_part);
1656 for(i = 1; i < num_part; i++)
1658 cpi->partition_sz[i] = cpi->bc[i].pos;
1659 write_partition_size(cx_data, cpi->partition_sz[i]);
1661 *size += cpi->partition_sz[i]; /* add to total */
1664 /* add last partition to total size */
1665 cpi->partition_sz[i] = cpi->bc[i].pos;
1666 *size += cpi->partition_sz[i];
1670 bc[1].error = &pc->error;
1672 vp8_start_encode(&cpi->bc[1], cx_data, cx_data_end);
1674 #if CONFIG_MULTITHREAD
1675 if (cpi->b_multi_threaded)
1676 pack_mb_row_tokens(cpi, &cpi->bc[1]);
1679 vp8_pack_tokens(&cpi->bc[1], cpi->tok, cpi->tok_count);
1681 vp8_stop_encode(&cpi->bc[1]);
1683 *size += cpi->bc[1].pos;
1684 cpi->partition_sz[1] = cpi->bc[1].pos;
1689 #ifdef VP8_ENTROPY_STATS
1690 void print_tree_update_probs()
1693 FILE *f = fopen("context.c", "a");
1695 fprintf(f, "\n/* Update probabilities for token entropy tree. */\n\n");
1696 fprintf(f, "const vp8_prob tree_update_probs[BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [ENTROPY_NODES] = {\n");
1698 for (i = 0; i < BLOCK_TYPES; i++)
1700 fprintf(f, " { \n");
1702 for (j = 0; j < COEF_BANDS; j++)
1706 for (k = 0; k < PREV_COEF_CONTEXTS; k++)
1710 for (l = 0; l < ENTROPY_NODES; l++)
1712 Sum = tree_update_hist[i][j][k][l][0] + tree_update_hist[i][j][k][l][1];
1716 if (((tree_update_hist[i][j][k][l][0] * 255) / Sum) > 0)
1717 fprintf(f, "%3ld, ", (tree_update_hist[i][j][k][l][0] * 255) / Sum);
1719 fprintf(f, "%3ld, ", 1);
1722 fprintf(f, "%3ld, ", 128);
1728 fprintf(f, " },\n");
1731 fprintf(f, " },\n");