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.
11 #include "vp8/common/header.h"
13 #include "vp8/common/entropymode.h"
14 #include "vp8/common/findnearmv.h"
16 #include "vp8/common/systemdependent.h"
20 #include "vpx/vpx_encoder.h"
21 #include "vpx_mem/vpx_mem.h"
22 #include "vpx_ports/system_state.h"
23 #include "bitstream.h"
25 #include "defaultcoefcounts.h"
26 #include "vp8/common/common.h"
28 const int vp8cx_base_skip_false_prob[128] = {
29 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
30 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
31 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
32 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 251, 248, 244, 240,
33 236, 232, 229, 225, 221, 217, 213, 208, 204, 199, 194, 190, 187, 183, 179,
34 175, 172, 168, 164, 160, 157, 153, 149, 145, 142, 138, 134, 130, 127, 124,
35 120, 117, 114, 110, 107, 104, 101, 98, 95, 92, 89, 86, 83, 80, 77,
36 74, 71, 68, 65, 62, 59, 56, 53, 50, 47, 44, 41, 38, 35, 32,
37 30, 28, 26, 24, 22, 20, 18, 16,
40 #if defined(SECTIONBITS_OUTPUT)
41 unsigned __int64 Sectionbits[500];
45 int count_mb_seg[4] = { 0, 0, 0, 0 };
48 static void update_mode(vp8_writer *const w, int n, vp8_token tok[/* n */],
49 vp8_tree tree, vp8_prob Pnew[/* n-1 */],
50 vp8_prob Pcur[/* n-1 */],
51 unsigned int bct[/* n-1 */][2],
52 const unsigned int num_events[/* n */]) {
53 unsigned int new_b = 0, old_b = 0;
56 vp8_tree_probs_from_distribution(n--, tok, tree, Pnew, bct, num_events, 256,
60 new_b += vp8_cost_branch(bct[i], Pnew[i]);
61 old_b += vp8_cost_branch(bct[i], Pcur[i]);
64 if (new_b + (n << 8) < old_b) {
70 const vp8_prob p = Pnew[j];
72 vp8_write_literal(w, Pcur[j] = p ? p : 1, 8);
78 static void update_mbintra_mode_probs(VP8_COMP *cpi) {
79 VP8_COMMON *const x = &cpi->common;
81 vp8_writer *const w = cpi->bc;
84 vp8_prob Pnew[VP8_YMODES - 1];
85 unsigned int bct[VP8_YMODES - 1][2];
87 update_mode(w, VP8_YMODES, vp8_ymode_encodings, vp8_ymode_tree, Pnew,
88 x->fc.ymode_prob, bct, (unsigned int *)cpi->mb.ymode_count);
91 vp8_prob Pnew[VP8_UV_MODES - 1];
92 unsigned int bct[VP8_UV_MODES - 1][2];
94 update_mode(w, VP8_UV_MODES, vp8_uv_mode_encodings, vp8_uv_mode_tree, Pnew,
95 x->fc.uv_mode_prob, bct, (unsigned int *)cpi->mb.uv_mode_count);
99 static void write_ymode(vp8_writer *bc, int m, const vp8_prob *p) {
100 vp8_write_token(bc, vp8_ymode_tree, p, vp8_ymode_encodings + m);
103 static void kfwrite_ymode(vp8_writer *bc, int m, const vp8_prob *p) {
104 vp8_write_token(bc, vp8_kf_ymode_tree, p, vp8_kf_ymode_encodings + m);
107 static void write_uv_mode(vp8_writer *bc, int m, const vp8_prob *p) {
108 vp8_write_token(bc, vp8_uv_mode_tree, p, vp8_uv_mode_encodings + m);
111 static void write_bmode(vp8_writer *bc, int m, const vp8_prob *p) {
112 vp8_write_token(bc, vp8_bmode_tree, p, vp8_bmode_encodings + m);
115 static void write_split(vp8_writer *bc, int x) {
116 vp8_write_token(bc, vp8_mbsplit_tree, vp8_mbsplit_probs,
117 vp8_mbsplit_encodings + x);
120 void vp8_pack_tokens(vp8_writer *w, const TOKENEXTRA *p, int xcount) {
121 const TOKENEXTRA *stop = p + xcount;
124 int count = w->count;
125 unsigned int range = w->range;
126 unsigned int lowvalue = w->lowvalue;
129 const int t = p->Token;
130 vp8_token *a = vp8_coef_encodings + t;
131 const vp8_extra_bit_struct *b = vp8_extra_bits + t;
133 const unsigned char *pp = p->context_tree;
137 if (p->skip_eob_node) {
143 const int bb = (v >> --n) & 1;
144 split = 1 + (((range - 1) * pp[i >> 1]) >> 8);
145 i = vp8_coef_tree[i + bb];
149 range = range - split;
154 shift = vp8_norm[range];
159 int offset = shift - count;
161 if ((lowvalue << (offset - 1)) & 0x80000000) {
164 while (x >= 0 && w->buffer[x] == 0xff) {
165 w->buffer[x] = (unsigned char)0;
172 validate_buffer(w->buffer + w->pos, 1, w->buffer_end, w->error);
174 w->buffer[w->pos++] = (lowvalue >> (24 - offset));
177 lowvalue &= 0xffffff;
185 const int e = p->Extra, L = b->Len;
188 const unsigned char *proba = b->prob;
189 const int v2 = e >> 1;
190 int n2 = L; /* number of bits in v2, assumed nonzero */
194 const int bb = (v2 >> --n2) & 1;
195 split = 1 + (((range - 1) * proba[i >> 1]) >> 8);
200 range = range - split;
205 shift = vp8_norm[range];
210 int offset = shift - count;
212 if ((lowvalue << (offset - 1)) & 0x80000000) {
215 while (x >= 0 && w->buffer[x] == 0xff) {
216 w->buffer[x] = (unsigned char)0;
223 validate_buffer(w->buffer + w->pos, 1, w->buffer_end, w->error);
225 w->buffer[w->pos++] = (lowvalue >> (24 - offset));
228 lowvalue &= 0xffffff;
237 split = (range + 1) >> 1;
241 range = range - split;
248 if ((lowvalue & 0x80000000)) {
251 while (x >= 0 && w->buffer[x] == 0xff) {
252 w->buffer[x] = (unsigned char)0;
264 validate_buffer(w->buffer + w->pos, 1, w->buffer_end, w->error);
266 w->buffer[w->pos++] = (lowvalue >> 24);
267 lowvalue &= 0xffffff;
276 w->lowvalue = lowvalue;
280 static void write_partition_size(unsigned char *cx_data, int size) {
285 csize = (size >> 8) & 0xff;
286 *(cx_data + 1) = csize;
287 csize = (size >> 16) & 0xff;
288 *(cx_data + 2) = csize;
291 static void pack_tokens_into_partitions(VP8_COMP *cpi, unsigned char *cx_data,
292 unsigned char *cx_data_end,
295 unsigned char *ptr = cx_data;
296 unsigned char *ptr_end = cx_data_end;
299 for (i = 0; i < num_part; ++i) {
304 vp8_start_encode(w, ptr, ptr_end);
306 for (mb_row = i; mb_row < cpi->common.mb_rows; mb_row += num_part) {
307 const TOKENEXTRA *p = cpi->tplist[mb_row].start;
308 const TOKENEXTRA *stop = cpi->tplist[mb_row].stop;
309 int tokens = (int)(stop - p);
311 vp8_pack_tokens(w, p, tokens);
319 #if CONFIG_MULTITHREAD
320 static void pack_mb_row_tokens(VP8_COMP *cpi, vp8_writer *w) {
323 for (mb_row = 0; mb_row < cpi->common.mb_rows; ++mb_row) {
324 const TOKENEXTRA *p = cpi->tplist[mb_row].start;
325 const TOKENEXTRA *stop = cpi->tplist[mb_row].stop;
326 int tokens = (int)(stop - p);
328 vp8_pack_tokens(w, p, tokens);
331 #endif // CONFIG_MULTITHREAD
333 static void write_mv_ref(vp8_writer *w, MB_PREDICTION_MODE m,
335 assert(NEARESTMV <= m && m <= SPLITMV);
336 vp8_write_token(w, vp8_mv_ref_tree, p,
337 vp8_mv_ref_encoding_array + (m - NEARESTMV));
340 static void write_sub_mv_ref(vp8_writer *w, B_PREDICTION_MODE m,
342 assert(LEFT4X4 <= m && m <= NEW4X4);
343 vp8_write_token(w, vp8_sub_mv_ref_tree, p,
344 vp8_sub_mv_ref_encoding_array + (m - LEFT4X4));
347 static void write_mv(vp8_writer *w, const MV *mv, const int_mv *ref,
348 const MV_CONTEXT *mvc) {
350 e.row = mv->row - ref->as_mv.row;
351 e.col = mv->col - ref->as_mv.col;
353 vp8_encode_motion_vector(w, &e, mvc);
356 static void write_mb_features(vp8_writer *w, const MB_MODE_INFO *mi,
357 const MACROBLOCKD *x) {
358 /* Encode the MB segment id. */
359 if (x->segmentation_enabled && x->update_mb_segmentation_map) {
360 switch (mi->segment_id) {
362 vp8_write(w, 0, x->mb_segment_tree_probs[0]);
363 vp8_write(w, 0, x->mb_segment_tree_probs[1]);
366 vp8_write(w, 0, x->mb_segment_tree_probs[0]);
367 vp8_write(w, 1, x->mb_segment_tree_probs[1]);
370 vp8_write(w, 1, x->mb_segment_tree_probs[0]);
371 vp8_write(w, 0, x->mb_segment_tree_probs[2]);
374 vp8_write(w, 1, x->mb_segment_tree_probs[0]);
375 vp8_write(w, 1, x->mb_segment_tree_probs[2]);
378 /* TRAP.. This should not happen */
380 vp8_write(w, 0, x->mb_segment_tree_probs[0]);
381 vp8_write(w, 0, x->mb_segment_tree_probs[1]);
386 void vp8_convert_rfct_to_prob(VP8_COMP *const cpi) {
387 const int *const rfct = cpi->mb.count_mb_ref_frame_usage;
388 const int rf_intra = rfct[INTRA_FRAME];
390 rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
392 /* Calculate the probabilities used to code the ref frame based on usage */
393 if (!(cpi->prob_intra_coded = rf_intra * 255 / (rf_intra + rf_inter))) {
394 cpi->prob_intra_coded = 1;
397 cpi->prob_last_coded = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
399 if (!cpi->prob_last_coded) cpi->prob_last_coded = 1;
401 cpi->prob_gf_coded = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
402 ? (rfct[GOLDEN_FRAME] * 255) /
403 (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
406 if (!cpi->prob_gf_coded) cpi->prob_gf_coded = 1;
409 static void pack_inter_mode_mvs(VP8_COMP *const cpi) {
410 VP8_COMMON *const pc = &cpi->common;
411 vp8_writer *const w = cpi->bc;
412 const MV_CONTEXT *mvc = pc->fc.mvc;
414 MODE_INFO *m = pc->mi;
415 const int mis = pc->mode_info_stride;
418 int prob_skip_false = 0;
420 cpi->mb.partition_info = cpi->mb.pi;
422 vp8_convert_rfct_to_prob(cpi);
424 if (pc->mb_no_coeff_skip) {
425 int total_mbs = pc->mb_rows * pc->mb_cols;
427 prob_skip_false = (total_mbs - cpi->mb.skip_true_count) * 256 / total_mbs;
429 if (prob_skip_false <= 1) prob_skip_false = 1;
431 if (prob_skip_false > 255) prob_skip_false = 255;
433 cpi->prob_skip_false = prob_skip_false;
434 vp8_write_literal(w, prob_skip_false, 8);
437 vp8_write_literal(w, cpi->prob_intra_coded, 8);
438 vp8_write_literal(w, cpi->prob_last_coded, 8);
439 vp8_write_literal(w, cpi->prob_gf_coded, 8);
441 update_mbintra_mode_probs(cpi);
443 vp8_write_mvprobs(cpi);
445 while (++mb_row < pc->mb_rows) {
448 while (++mb_col < pc->mb_cols) {
449 const MB_MODE_INFO *const mi = &m->mbmi;
450 const MV_REFERENCE_FRAME rf = mi->ref_frame;
451 const MB_PREDICTION_MODE mode = mi->mode;
453 MACROBLOCKD *xd = &cpi->mb.e_mbd;
455 /* Distance of Mb to the various image edges.
456 * These specified to 8th pel as they are always compared to MV
457 * values that are in 1/8th pel units
459 xd->mb_to_left_edge = -((mb_col * 16) << 3);
460 xd->mb_to_right_edge = ((pc->mb_cols - 1 - mb_col) * 16) << 3;
461 xd->mb_to_top_edge = -((mb_row * 16) << 3);
462 xd->mb_to_bottom_edge = ((pc->mb_rows - 1 - mb_row) * 16) << 3;
464 if (cpi->mb.e_mbd.update_mb_segmentation_map) {
465 write_mb_features(w, mi, &cpi->mb.e_mbd);
468 if (pc->mb_no_coeff_skip) {
469 vp8_encode_bool(w, m->mbmi.mb_skip_coeff, prob_skip_false);
472 if (rf == INTRA_FRAME) {
473 vp8_write(w, 0, cpi->prob_intra_coded);
474 write_ymode(w, mode, pc->fc.ymode_prob);
476 if (mode == B_PRED) {
480 write_bmode(w, m->bmi[j].as_mode, pc->fc.bmode_prob);
484 write_uv_mode(w, mi->uv_mode, pc->fc.uv_mode_prob);
485 } else { /* inter coded */
487 vp8_prob mv_ref_p[VP8_MVREFS - 1];
489 vp8_write(w, 1, cpi->prob_intra_coded);
491 if (rf == LAST_FRAME)
492 vp8_write(w, 0, cpi->prob_last_coded);
494 vp8_write(w, 1, cpi->prob_last_coded);
495 vp8_write(w, (rf == GOLDEN_FRAME) ? 0 : 1, cpi->prob_gf_coded);
502 vp8_find_near_mvs(xd, m, &n1, &n2, &best_mv, ct, rf,
503 cpi->common.ref_frame_sign_bias);
504 vp8_clamp_mv2(&best_mv, xd);
506 vp8_mv_ref_probs(mv_ref_p, ct);
509 write_mv_ref(w, mode, mv_ref_p);
511 switch (mode) /* new, split require MVs */
513 case NEWMV: write_mv(w, &mi->mv.as_mv, &best_mv, mvc); break;
519 ++count_mb_seg[mi->partitioning];
522 write_split(w, mi->partitioning);
525 B_PREDICTION_MODE blockmode;
527 const int *const L = vp8_mbsplits[mi->partitioning];
528 int k = -1; /* first block in subset j */
530 int_mv leftmv, abovemv;
532 blockmode = cpi->mb.partition_info->bmi[j].mode;
533 blockmv = cpi->mb.partition_info->bmi[j].mv;
534 while (j != L[++k]) {
537 leftmv.as_int = left_block_mv(m, k);
538 abovemv.as_int = above_block_mv(m, k, mis);
539 mv_contz = vp8_mv_cont(&leftmv, &abovemv);
541 write_sub_mv_ref(w, blockmode, vp8_sub_mv_ref_prob2[mv_contz]);
543 if (blockmode == NEW4X4) {
544 write_mv(w, &blockmv.as_mv, &best_mv, (const MV_CONTEXT *)mvc);
546 } while (++j < cpi->mb.partition_info->count);
554 cpi->mb.partition_info++;
557 ++m; /* skip L prediction border */
558 cpi->mb.partition_info++;
562 static void write_kfmodes(VP8_COMP *cpi) {
563 vp8_writer *const bc = cpi->bc;
564 const VP8_COMMON *const c = &cpi->common;
566 MODE_INFO *m = c->mi;
569 int prob_skip_false = 0;
571 if (c->mb_no_coeff_skip) {
572 int total_mbs = c->mb_rows * c->mb_cols;
574 prob_skip_false = (total_mbs - cpi->mb.skip_true_count) * 256 / total_mbs;
576 if (prob_skip_false <= 1) prob_skip_false = 1;
578 if (prob_skip_false >= 255) prob_skip_false = 255;
580 cpi->prob_skip_false = prob_skip_false;
581 vp8_write_literal(bc, prob_skip_false, 8);
584 while (++mb_row < c->mb_rows) {
587 while (++mb_col < c->mb_cols) {
588 const int ym = m->mbmi.mode;
590 if (cpi->mb.e_mbd.update_mb_segmentation_map) {
591 write_mb_features(bc, &m->mbmi, &cpi->mb.e_mbd);
594 if (c->mb_no_coeff_skip) {
595 vp8_encode_bool(bc, m->mbmi.mb_skip_coeff, prob_skip_false);
598 kfwrite_ymode(bc, ym, vp8_kf_ymode_prob);
601 const int mis = c->mode_info_stride;
605 const B_PREDICTION_MODE A = above_block_mode(m, i, mis);
606 const B_PREDICTION_MODE L = left_block_mode(m, i);
607 const int bm = m->bmi[i].as_mode;
609 write_bmode(bc, bm, vp8_kf_bmode_prob[A][L]);
613 write_uv_mode(bc, (m++)->mbmi.uv_mode, vp8_kf_uv_mode_prob);
616 m++; /* skip L prediction border */
621 /* This function is used for debugging probability trees. */
622 static void print_prob_tree(vp8_prob
623 coef_probs[BLOCK_TYPES][COEF_BANDS][PREV_COEF_CONTEXTS][ENTROPY_NODES])
625 /* print coef probability tree */
627 FILE* f = fopen("enc_tree_probs.txt", "a");
629 for (i = 0; i < BLOCK_TYPES; ++i)
632 for (j = 0; j < COEF_BANDS; ++j)
635 for (k = 0; k < PREV_COEF_CONTEXTS; ++k)
638 for (l = 0; l < ENTROPY_NODES; ++l)
641 (unsigned int)(coef_probs [i][j][k][l]));
654 static void sum_probs_over_prev_coef_context(
655 const unsigned int probs[PREV_COEF_CONTEXTS][MAX_ENTROPY_TOKENS],
658 for (i = 0; i < MAX_ENTROPY_TOKENS; ++i) {
659 for (j = 0; j < PREV_COEF_CONTEXTS; ++j) {
660 const unsigned int tmp = out[i];
661 out[i] += probs[j][i];
663 if (out[i] < tmp) out[i] = UINT_MAX;
668 static int prob_update_savings(const unsigned int *ct, const vp8_prob oldp,
669 const vp8_prob newp, const vp8_prob upd) {
670 const int old_b = vp8_cost_branch(ct, oldp);
671 const int new_b = vp8_cost_branch(ct, newp);
672 const int update_b = 8 + ((vp8_cost_one(upd) - vp8_cost_zero(upd)) >> 8);
674 return old_b - new_b - update_b;
677 static int independent_coef_context_savings(VP8_COMP *cpi) {
678 MACROBLOCK *const x = &cpi->mb;
685 unsigned int prev_coef_count_sum[MAX_ENTROPY_TOKENS] = { 0 };
686 int prev_coef_savings[MAX_ENTROPY_TOKENS] = { 0 };
687 const unsigned int(*probs)[MAX_ENTROPY_TOKENS];
688 /* Calculate new probabilities given the constraint that
689 * they must be equal over the prev coef contexts
692 probs = (const unsigned int(*)[MAX_ENTROPY_TOKENS])x->coef_counts[i][j];
694 /* Reset to default probabilities at key frames */
695 if (cpi->common.frame_type == KEY_FRAME) {
696 probs = default_coef_counts[i][j];
699 sum_probs_over_prev_coef_context(probs, prev_coef_count_sum);
702 /* at every context */
704 /* calc probs and branch cts for this frame only */
705 int t = 0; /* token/prob index */
707 vp8_tree_probs_from_distribution(
708 MAX_ENTROPY_TOKENS, vp8_coef_encodings, vp8_coef_tree,
709 cpi->frame_coef_probs[i][j][k], cpi->frame_branch_ct[i][j][k],
710 prev_coef_count_sum, 256, 1);
713 const unsigned int *ct = cpi->frame_branch_ct[i][j][k][t];
714 const vp8_prob newp = cpi->frame_coef_probs[i][j][k][t];
715 const vp8_prob oldp = cpi->common.fc.coef_probs[i][j][k][t];
716 const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
717 const int s = prob_update_savings(ct, oldp, newp, upd);
719 if (cpi->common.frame_type != KEY_FRAME ||
720 (cpi->common.frame_type == KEY_FRAME && newp != oldp)) {
721 prev_coef_savings[t] += s;
723 } while (++t < ENTROPY_NODES);
724 } while (++k < PREV_COEF_CONTEXTS);
727 /* We only update probabilities if we can save bits, except
728 * for key frames where we have to update all probabilities
729 * to get the equal probabilities across the prev coef
732 if (prev_coef_savings[k] > 0 || cpi->common.frame_type == KEY_FRAME) {
733 savings += prev_coef_savings[k];
735 } while (++k < ENTROPY_NODES);
736 } while (++j < COEF_BANDS);
737 } while (++i < BLOCK_TYPES);
741 static int default_coef_context_savings(VP8_COMP *cpi) {
742 MACROBLOCK *const x = &cpi->mb;
750 /* at every context */
752 /* calc probs and branch cts for this frame only */
753 int t = 0; /* token/prob index */
755 vp8_tree_probs_from_distribution(
756 MAX_ENTROPY_TOKENS, vp8_coef_encodings, vp8_coef_tree,
757 cpi->frame_coef_probs[i][j][k], cpi->frame_branch_ct[i][j][k],
758 x->coef_counts[i][j][k], 256, 1);
761 const unsigned int *ct = cpi->frame_branch_ct[i][j][k][t];
762 const vp8_prob newp = cpi->frame_coef_probs[i][j][k][t];
763 const vp8_prob oldp = cpi->common.fc.coef_probs[i][j][k][t];
764 const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
765 const int s = prob_update_savings(ct, oldp, newp, upd);
770 } while (++t < ENTROPY_NODES);
771 } while (++k < PREV_COEF_CONTEXTS);
772 } while (++j < COEF_BANDS);
773 } while (++i < BLOCK_TYPES);
777 void vp8_calc_ref_frame_costs(int *ref_frame_cost, int prob_intra,
778 int prob_last, int prob_garf) {
779 assert(prob_intra >= 0);
780 assert(prob_intra <= 255);
781 assert(prob_last >= 0);
782 assert(prob_last <= 255);
783 assert(prob_garf >= 0);
784 assert(prob_garf <= 255);
785 ref_frame_cost[INTRA_FRAME] = vp8_cost_zero(prob_intra);
786 ref_frame_cost[LAST_FRAME] =
787 vp8_cost_one(prob_intra) + vp8_cost_zero(prob_last);
788 ref_frame_cost[GOLDEN_FRAME] = vp8_cost_one(prob_intra) +
789 vp8_cost_one(prob_last) +
790 vp8_cost_zero(prob_garf);
791 ref_frame_cost[ALTREF_FRAME] = vp8_cost_one(prob_intra) +
792 vp8_cost_one(prob_last) +
793 vp8_cost_one(prob_garf);
796 int vp8_estimate_entropy_savings(VP8_COMP *cpi) {
799 const int *const rfct = cpi->mb.count_mb_ref_frame_usage;
800 const int rf_intra = rfct[INTRA_FRAME];
802 rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
803 int new_intra, new_last, new_garf, oldtotal, newtotal;
804 int ref_frame_cost[MAX_REF_FRAMES];
806 vpx_clear_system_state();
808 if (cpi->common.frame_type != KEY_FRAME) {
809 if (!(new_intra = rf_intra * 255 / (rf_intra + rf_inter))) new_intra = 1;
811 new_last = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
813 new_garf = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
814 ? (rfct[GOLDEN_FRAME] * 255) /
815 (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
818 vp8_calc_ref_frame_costs(ref_frame_cost, new_intra, new_last, new_garf);
820 newtotal = rfct[INTRA_FRAME] * ref_frame_cost[INTRA_FRAME] +
821 rfct[LAST_FRAME] * ref_frame_cost[LAST_FRAME] +
822 rfct[GOLDEN_FRAME] * ref_frame_cost[GOLDEN_FRAME] +
823 rfct[ALTREF_FRAME] * ref_frame_cost[ALTREF_FRAME];
826 vp8_calc_ref_frame_costs(ref_frame_cost, cpi->prob_intra_coded,
827 cpi->prob_last_coded, cpi->prob_gf_coded);
829 oldtotal = rfct[INTRA_FRAME] * ref_frame_cost[INTRA_FRAME] +
830 rfct[LAST_FRAME] * ref_frame_cost[LAST_FRAME] +
831 rfct[GOLDEN_FRAME] * ref_frame_cost[GOLDEN_FRAME] +
832 rfct[ALTREF_FRAME] * ref_frame_cost[ALTREF_FRAME];
834 savings += (oldtotal - newtotal) / 256;
837 if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS) {
838 savings += independent_coef_context_savings(cpi);
840 savings += default_coef_context_savings(cpi);
846 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
847 int vp8_update_coef_context(VP8_COMP *cpi) {
850 if (cpi->common.frame_type == KEY_FRAME) {
851 /* Reset to default counts/probabilities at key frames */
852 vp8_copy(cpi->mb.coef_counts, default_coef_counts);
855 if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS)
856 savings += independent_coef_context_savings(cpi);
858 savings += default_coef_context_savings(cpi);
864 void vp8_update_coef_probs(VP8_COMP *cpi) {
866 #if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
867 vp8_writer *const w = cpi->bc;
871 vpx_clear_system_state();
878 int prev_coef_savings[ENTROPY_NODES] = { 0 };
879 if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS) {
880 for (k = 0; k < PREV_COEF_CONTEXTS; ++k) {
881 int t; /* token/prob index */
882 for (t = 0; t < ENTROPY_NODES; ++t) {
883 const unsigned int *ct = cpi->frame_branch_ct[i][j][k][t];
884 const vp8_prob newp = cpi->frame_coef_probs[i][j][k][t];
885 const vp8_prob oldp = cpi->common.fc.coef_probs[i][j][k][t];
886 const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
888 prev_coef_savings[t] += prob_update_savings(ct, oldp, newp, upd);
894 /* note: use result from vp8_estimate_entropy_savings, so no
895 * need to call vp8_tree_probs_from_distribution here.
898 /* at every context */
900 /* calc probs and branch cts for this frame only */
901 int t = 0; /* token/prob index */
904 const vp8_prob newp = cpi->frame_coef_probs[i][j][k][t];
906 vp8_prob *Pold = cpi->common.fc.coef_probs[i][j][k] + t;
907 const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
909 int s = prev_coef_savings[t];
912 if (!(cpi->oxcf.error_resilient_mode &
913 VPX_ERROR_RESILIENT_PARTITIONS)) {
914 s = prob_update_savings(cpi->frame_branch_ct[i][j][k][t], *Pold,
920 /* Force updates on key frames if the new is different,
921 * so that we can be sure we end up with equal probabilities
922 * over the prev coef contexts.
924 if ((cpi->oxcf.error_resilient_mode &
925 VPX_ERROR_RESILIENT_PARTITIONS) &&
926 cpi->common.frame_type == KEY_FRAME && newp != *Pold) {
930 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
931 cpi->update_probs[i][j][k][t] = u;
933 vp8_write(w, u, upd);
937 /* send/use new probability */
940 #if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
941 vp8_write_literal(w, newp, 8);
947 } while (++t < ENTROPY_NODES);
949 } while (++k < PREV_COEF_CONTEXTS);
950 } while (++j < COEF_BANDS);
951 } while (++i < BLOCK_TYPES);
954 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
955 static void pack_coef_probs(VP8_COMP *cpi) {
957 vp8_writer *const w = cpi->bc;
966 int t = 0; /* token/prob index */
969 const vp8_prob newp = cpi->common.fc.coef_probs[i][j][k][t];
970 const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
972 const char u = cpi->update_probs[i][j][k][t];
974 vp8_write(w, u, upd);
977 /* send/use new probability */
978 vp8_write_literal(w, newp, 8);
980 } while (++t < ENTROPY_NODES);
981 } while (++k < PREV_COEF_CONTEXTS);
982 } while (++j < COEF_BANDS);
983 } while (++i < BLOCK_TYPES);
987 #ifdef PACKET_TESTING
991 static void put_delta_q(vp8_writer *bc, int delta_q) {
993 vp8_write_bit(bc, 1);
994 vp8_write_literal(bc, abs(delta_q), 4);
997 vp8_write_bit(bc, 1);
999 vp8_write_bit(bc, 0);
1001 vp8_write_bit(bc, 0);
1004 void vp8_pack_bitstream(VP8_COMP *cpi, unsigned char *dest,
1005 unsigned char *dest_end, size_t *size) {
1008 VP8_COMMON *const pc = &cpi->common;
1009 vp8_writer *const bc = cpi->bc;
1010 MACROBLOCKD *const xd = &cpi->mb.e_mbd;
1011 int extra_bytes_packed = 0;
1013 unsigned char *cx_data = dest;
1014 unsigned char *cx_data_end = dest_end;
1015 const int *mb_feature_data_bits;
1017 oh.show_frame = (int)pc->show_frame;
1018 oh.type = (int)pc->frame_type;
1019 oh.version = pc->version;
1020 oh.first_partition_length_in_bytes = 0;
1022 mb_feature_data_bits = vp8_mb_feature_data_bits;
1024 bc[0].error = &pc->error;
1026 validate_buffer(cx_data, 3, cx_data_end, &cpi->common.error);
1029 #if defined(SECTIONBITS_OUTPUT)
1030 Sectionbits[active_section = 1] += sizeof(VP8_HEADER) * 8 * 256;
1033 /* every keyframe send startcode, width, height, scale factor, clamp
1036 if (oh.type == KEY_FRAME) {
1039 validate_buffer(cx_data, 7, cx_data_end, &cpi->common.error);
1041 /* Start / synch code */
1046 /* Pack scale and frame size into 16 bits. Store it 8 bits at a time.
1047 * https://tools.ietf.org/html/rfc6386
1048 * 9.1. Uncompressed Data Chunk
1049 * 16 bits : (2 bits Horizontal Scale << 14) | Width (14 bits)
1050 * 16 bits : (2 bits Vertical Scale << 14) | Height (14 bits)
1052 v = (pc->horiz_scale << 14) | pc->Width;
1053 cx_data[3] = v & 0xff;
1054 cx_data[4] = v >> 8;
1056 v = (pc->vert_scale << 14) | pc->Height;
1057 cx_data[5] = v & 0xff;
1058 cx_data[6] = v >> 8;
1060 extra_bytes_packed = 7;
1061 cx_data += extra_bytes_packed;
1063 vp8_start_encode(bc, cx_data, cx_data_end);
1065 /* signal clr type */
1066 vp8_write_bit(bc, 0);
1067 vp8_write_bit(bc, pc->clamp_type);
1070 vp8_start_encode(bc, cx_data, cx_data_end);
1073 /* Signal whether or not Segmentation is enabled */
1074 vp8_write_bit(bc, xd->segmentation_enabled);
1076 /* Indicate which features are enabled */
1077 if (xd->segmentation_enabled) {
1078 /* Signal whether or not the segmentation map is being updated. */
1079 vp8_write_bit(bc, xd->update_mb_segmentation_map);
1080 vp8_write_bit(bc, xd->update_mb_segmentation_data);
1082 if (xd->update_mb_segmentation_data) {
1085 vp8_write_bit(bc, xd->mb_segement_abs_delta);
1087 /* For each segmentation feature (Quant and loop filter level) */
1088 for (i = 0; i < MB_LVL_MAX; ++i) {
1089 /* For each of the segments */
1090 for (j = 0; j < MAX_MB_SEGMENTS; ++j) {
1091 Data = xd->segment_feature_data[i][j];
1093 /* Frame level data */
1095 vp8_write_bit(bc, 1);
1099 vp8_write_literal(bc, Data, mb_feature_data_bits[i]);
1100 vp8_write_bit(bc, 1);
1102 vp8_write_literal(bc, Data, mb_feature_data_bits[i]);
1103 vp8_write_bit(bc, 0);
1106 vp8_write_bit(bc, 0);
1111 if (xd->update_mb_segmentation_map) {
1112 /* Write the probs used to decode the segment id for each mb */
1113 for (i = 0; i < MB_FEATURE_TREE_PROBS; ++i) {
1114 int Data = xd->mb_segment_tree_probs[i];
1117 vp8_write_bit(bc, 1);
1118 vp8_write_literal(bc, Data, 8);
1120 vp8_write_bit(bc, 0);
1125 vp8_write_bit(bc, pc->filter_type);
1126 vp8_write_literal(bc, pc->filter_level, 6);
1127 vp8_write_literal(bc, pc->sharpness_level, 3);
1129 /* Write out loop filter deltas applied at the MB level based on mode
1130 * or ref frame (if they are enabled).
1132 vp8_write_bit(bc, xd->mode_ref_lf_delta_enabled);
1134 if (xd->mode_ref_lf_delta_enabled) {
1135 /* Do the deltas need to be updated */
1137 xd->mode_ref_lf_delta_update || cpi->oxcf.error_resilient_mode;
1139 vp8_write_bit(bc, send_update);
1144 for (i = 0; i < MAX_REF_LF_DELTAS; ++i) {
1145 Data = xd->ref_lf_deltas[i];
1147 /* Frame level data */
1148 if (xd->ref_lf_deltas[i] != xd->last_ref_lf_deltas[i] ||
1149 cpi->oxcf.error_resilient_mode) {
1150 xd->last_ref_lf_deltas[i] = xd->ref_lf_deltas[i];
1151 vp8_write_bit(bc, 1);
1154 vp8_write_literal(bc, (Data & 0x3F), 6);
1155 vp8_write_bit(bc, 0); /* sign */
1158 vp8_write_literal(bc, (Data & 0x3F), 6);
1159 vp8_write_bit(bc, 1); /* sign */
1162 vp8_write_bit(bc, 0);
1166 for (i = 0; i < MAX_MODE_LF_DELTAS; ++i) {
1167 Data = xd->mode_lf_deltas[i];
1169 if (xd->mode_lf_deltas[i] != xd->last_mode_lf_deltas[i] ||
1170 cpi->oxcf.error_resilient_mode) {
1171 xd->last_mode_lf_deltas[i] = xd->mode_lf_deltas[i];
1172 vp8_write_bit(bc, 1);
1175 vp8_write_literal(bc, (Data & 0x3F), 6);
1176 vp8_write_bit(bc, 0); /* sign */
1179 vp8_write_literal(bc, (Data & 0x3F), 6);
1180 vp8_write_bit(bc, 1); /* sign */
1183 vp8_write_bit(bc, 0);
1188 /* signal here is multi token partition is enabled */
1189 vp8_write_literal(bc, pc->multi_token_partition, 2);
1191 /* Frame Qbaseline quantizer index */
1192 vp8_write_literal(bc, pc->base_qindex, 7);
1194 /* Transmit Dc, Second order and Uv quantizer delta information */
1195 put_delta_q(bc, pc->y1dc_delta_q);
1196 put_delta_q(bc, pc->y2dc_delta_q);
1197 put_delta_q(bc, pc->y2ac_delta_q);
1198 put_delta_q(bc, pc->uvdc_delta_q);
1199 put_delta_q(bc, pc->uvac_delta_q);
1201 /* When there is a key frame all reference buffers are updated using
1204 if (pc->frame_type != KEY_FRAME) {
1205 /* Should the GF or ARF be updated using the transmitted frame
1208 vp8_write_bit(bc, pc->refresh_golden_frame);
1209 vp8_write_bit(bc, pc->refresh_alt_ref_frame);
1211 /* If not being updated from current frame should either GF or ARF
1212 * be updated from another buffer
1214 if (!pc->refresh_golden_frame)
1215 vp8_write_literal(bc, pc->copy_buffer_to_gf, 2);
1217 if (!pc->refresh_alt_ref_frame)
1218 vp8_write_literal(bc, pc->copy_buffer_to_arf, 2);
1220 /* Indicate reference frame sign bias for Golden and ARF frames
1221 * (always 0 for last frame buffer)
1223 vp8_write_bit(bc, pc->ref_frame_sign_bias[GOLDEN_FRAME]);
1224 vp8_write_bit(bc, pc->ref_frame_sign_bias[ALTREF_FRAME]);
1227 #if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
1228 if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS) {
1229 if (pc->frame_type == KEY_FRAME) {
1230 pc->refresh_entropy_probs = 1;
1232 pc->refresh_entropy_probs = 0;
1237 vp8_write_bit(bc, pc->refresh_entropy_probs);
1239 if (pc->frame_type != KEY_FRAME) vp8_write_bit(bc, pc->refresh_last_frame);
1241 vpx_clear_system_state();
1243 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1244 pack_coef_probs(cpi);
1246 if (pc->refresh_entropy_probs == 0) {
1247 /* save a copy for later refresh */
1248 memcpy(&cpi->common.lfc, &cpi->common.fc, sizeof(cpi->common.fc));
1251 vp8_update_coef_probs(cpi);
1254 /* Write out the mb_no_coeff_skip flag */
1255 vp8_write_bit(bc, pc->mb_no_coeff_skip);
1257 if (pc->frame_type == KEY_FRAME) {
1260 pack_inter_mode_mvs(cpi);
1263 vp8_stop_encode(bc);
1267 oh.first_partition_length_in_bytes = cpi->bc->pos;
1269 /* update frame tag */
1271 /* Pack partition size, show frame, version and frame type into to 24 bits.
1272 * Store it 8 bits at a time.
1273 * https://tools.ietf.org/html/rfc6386
1274 * 9.1. Uncompressed Data Chunk
1275 * The uncompressed data chunk comprises a common (for key frames and
1276 * interframes) 3-byte frame tag that contains four fields, as follows:
1278 * 1. A 1-bit frame type (0 for key frames, 1 for interframes).
1280 * 2. A 3-bit version number (0 - 3 are defined as four different
1281 * profiles with different decoding complexity; other values may be
1282 * defined for future variants of the VP8 data format).
1284 * 3. A 1-bit show_frame flag (0 when current frame is not for display,
1285 * 1 when current frame is for display).
1287 * 4. A 19-bit field containing the size of the first data partition in
1290 int v = (oh.first_partition_length_in_bytes << 5) | (oh.show_frame << 4) |
1291 (oh.version << 1) | oh.type;
1294 dest[1] = (v >> 8) & 0xff;
1298 *size = VP8_HEADER_SIZE + extra_bytes_packed + cpi->bc->pos;
1300 cpi->partition_sz[0] = (unsigned int)*size;
1302 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1304 const int num_part = (1 << pc->multi_token_partition);
1305 unsigned char *dp = cpi->partition_d[0] + cpi->partition_sz[0];
1308 /* write token part sizes (all but last) if more than 1 */
1309 validate_buffer(dp, 3 * (num_part - 1), cpi->partition_d_end[0],
1312 cpi->partition_sz[0] += 3 * (num_part - 1);
1314 for (i = 1; i < num_part; ++i) {
1315 write_partition_size(dp, cpi->partition_sz[i]);
1320 if (!cpi->output_partition) {
1321 /* concatenate partition buffers */
1322 for (i = 0; i < num_part; ++i) {
1323 memmove(dp, cpi->partition_d[i + 1], cpi->partition_sz[i + 1]);
1324 cpi->partition_d[i + 1] = dp;
1325 dp += cpi->partition_sz[i + 1];
1329 /* update total size */
1331 for (i = 0; i < num_part + 1; ++i) {
1332 *size += cpi->partition_sz[i];
1336 if (pc->multi_token_partition != ONE_PARTITION) {
1337 int num_part = 1 << pc->multi_token_partition;
1339 /* partition size table at the end of first partition */
1340 cpi->partition_sz[0] += 3 * (num_part - 1);
1341 *size += 3 * (num_part - 1);
1343 validate_buffer(cx_data, 3 * (num_part - 1), cx_data_end, &pc->error);
1345 for (i = 1; i < num_part + 1; ++i) {
1346 cpi->bc[i].error = &pc->error;
1349 pack_tokens_into_partitions(cpi, cx_data + 3 * (num_part - 1), cx_data_end,
1352 for (i = 1; i < num_part; ++i) {
1353 cpi->partition_sz[i] = cpi->bc[i].pos;
1354 write_partition_size(cx_data, cpi->partition_sz[i]);
1356 *size += cpi->partition_sz[i]; /* add to total */
1359 /* add last partition to total size */
1360 cpi->partition_sz[i] = cpi->bc[i].pos;
1361 *size += cpi->partition_sz[i];
1363 bc[1].error = &pc->error;
1365 vp8_start_encode(&cpi->bc[1], cx_data, cx_data_end);
1367 #if CONFIG_MULTITHREAD
1368 if (vpx_atomic_load_acquire(&cpi->b_multi_threaded)) {
1369 pack_mb_row_tokens(cpi, &cpi->bc[1]);
1371 vp8_pack_tokens(&cpi->bc[1], cpi->tok, cpi->tok_count);
1374 vp8_pack_tokens(&cpi->bc[1], cpi->tok, cpi->tok_count);
1375 #endif // CONFIG_MULTITHREAD
1377 vp8_stop_encode(&cpi->bc[1]);
1379 *size += cpi->bc[1].pos;
1380 cpi->partition_sz[1] = cpi->bc[1].pos;