Use endian-neutral bitstream packing/unpacking
[profile/ivi/libvpx.git] / vp8 / encoder / bitstream.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11
12 #include "vp8/common/header.h"
13 #include "encodemv.h"
14 #include "vp8/common/entropymode.h"
15 #include "vp8/common/findnearmv.h"
16 #include "mcomp.h"
17 #include "vp8/common/systemdependent.h"
18 #include <assert.h>
19 #include <stdio.h>
20 #include "vp8/common/pragmas.h"
21 #include "vpx_mem/vpx_mem.h"
22 #include "bitstream.h"
23
24 const int vp8cx_base_skip_false_prob[128] =
25 {
26     255, 255, 255, 255, 255, 255, 255, 255,
27     255, 255, 255, 255, 255, 255, 255, 255,
28     255, 255, 255, 255, 255, 255, 255, 255,
29     255, 255, 255, 255, 255, 255, 255, 255,
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     251, 248, 244, 240, 236, 232, 229, 225,
34     221, 217, 213, 208, 204, 199, 194, 190,
35     187, 183, 179, 175, 172, 168, 164, 160,
36     157, 153, 149, 145, 142, 138, 134, 130,
37     127, 124, 120, 117, 114, 110, 107, 104,
38     101, 98,  95,  92,  89,  86,  83, 80,
39     77,  74,  71,  68,  65,  62,  59, 56,
40     53,  50,  47,  44,  41,  38,  35, 32,
41     30,  28,  26,  24,  22,  20,  18, 16,
42 };
43 #ifdef VP8REF
44 #define __int64 long long
45 #endif
46
47 #if defined(SECTIONBITS_OUTPUT)
48 unsigned __int64 Sectionbits[500];
49 #endif
50
51 #ifdef ENTROPY_STATS
52 int intra_mode_stats[10][10][10];
53 static unsigned int tree_update_hist [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [vp8_coef_tokens-1] [2];
54 extern unsigned int active_section;
55 #endif
56
57 #ifdef MODE_STATS
58 int count_mb_seg[4] = { 0, 0, 0, 0 };
59 #endif
60
61
62 static void update_mode(
63     vp8_writer *const w,
64     int n,
65     vp8_token tok               [/* n */],
66     vp8_tree tree,
67     vp8_prob Pnew               [/* n-1 */],
68     vp8_prob Pcur               [/* n-1 */],
69     unsigned int bct            [/* n-1 */] [2],
70     const unsigned int num_events[/* n */]
71 )
72 {
73     unsigned int new_b = 0, old_b = 0;
74     int i = 0;
75
76     vp8_tree_probs_from_distribution(
77         n--, tok, tree,
78         Pnew, bct, num_events,
79         256, 1
80     );
81
82     do
83     {
84         new_b += vp8_cost_branch(bct[i], Pnew[i]);
85         old_b += vp8_cost_branch(bct[i], Pcur[i]);
86     }
87     while (++i < n);
88
89     if (new_b + (n << 8) < old_b)
90     {
91         int i = 0;
92
93         vp8_write_bit(w, 1);
94
95         do
96         {
97             const vp8_prob p = Pnew[i];
98
99             vp8_write_literal(w, Pcur[i] = p ? p : 1, 8);
100         }
101         while (++i < n);
102     }
103     else
104         vp8_write_bit(w, 0);
105 }
106
107 static void update_mbintra_mode_probs(VP8_COMP *cpi)
108 {
109     VP8_COMMON *const x = & cpi->common;
110
111     vp8_writer *const w = & cpi->bc;
112
113     {
114         vp8_prob Pnew   [VP8_YMODES-1];
115         unsigned int bct [VP8_YMODES-1] [2];
116
117         update_mode(
118             w, VP8_YMODES, vp8_ymode_encodings, vp8_ymode_tree,
119             Pnew, x->fc.ymode_prob, bct, (unsigned int *)cpi->ymode_count
120         );
121     }
122     {
123         vp8_prob Pnew   [VP8_UV_MODES-1];
124         unsigned int bct [VP8_UV_MODES-1] [2];
125
126         update_mode(
127             w, VP8_UV_MODES, vp8_uv_mode_encodings, vp8_uv_mode_tree,
128             Pnew, x->fc.uv_mode_prob, bct, (unsigned int *)cpi->uv_mode_count
129         );
130     }
131 }
132
133 static void write_ymode(vp8_writer *bc, int m, const vp8_prob *p)
134 {
135     vp8_write_token(bc, vp8_ymode_tree, p, vp8_ymode_encodings + m);
136 }
137
138 static void kfwrite_ymode(vp8_writer *bc, int m, const vp8_prob *p)
139 {
140     vp8_write_token(bc, vp8_kf_ymode_tree, p, vp8_kf_ymode_encodings + m);
141 }
142
143 static void write_uv_mode(vp8_writer *bc, int m, const vp8_prob *p)
144 {
145     vp8_write_token(bc, vp8_uv_mode_tree, p, vp8_uv_mode_encodings + m);
146 }
147
148
149 static void write_bmode(vp8_writer *bc, int m, const vp8_prob *p)
150 {
151     vp8_write_token(bc, vp8_bmode_tree, p, vp8_bmode_encodings + m);
152 }
153
154 static void write_split(vp8_writer *bc, int x)
155 {
156     vp8_write_token(
157         bc, vp8_mbsplit_tree, vp8_mbsplit_probs, vp8_mbsplit_encodings + x
158     );
159 }
160
161 static const unsigned int norm[256] =
162 {
163     0, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
164     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
165     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
166     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
167     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
168     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
169     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
170     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
171 };
172
173 static void pack_tokens_c(vp8_writer *w, const TOKENEXTRA *p, int xcount)
174 {
175     const TOKENEXTRA *const stop = p + xcount;
176     unsigned int split;
177     unsigned int shift;
178     int count = w->count;
179     unsigned int range = w->range;
180     unsigned int lowvalue = w->lowvalue;
181
182     while (p < stop)
183     {
184         const int t = p->Token;
185         vp8_token *const a = vp8_coef_encodings + t;
186         const vp8_extra_bit_struct *const b = vp8_extra_bits + t;
187         int i = 0;
188         const unsigned char *pp = p->context_tree;
189         int v = a->value;
190         int n = a->Len;
191
192         if (p->skip_eob_node)
193         {
194             n--;
195             i = 2;
196         }
197
198         do
199         {
200             const int bb = (v >> --n) & 1;
201             split = 1 + (((range - 1) * pp[i>>1]) >> 8);
202             i = vp8_coef_tree[i+bb];
203
204             if (bb)
205             {
206                 lowvalue += split;
207                 range = range - split;
208             }
209             else
210             {
211                 range = split;
212             }
213
214             shift = norm[range];
215             range <<= shift;
216             count += shift;
217
218             if (count >= 0)
219             {
220                 int offset = shift - count;
221
222                 if ((lowvalue << (offset - 1)) & 0x80000000)
223                 {
224                     int x = w->pos - 1;
225
226                     while (x >= 0 && w->buffer[x] == 0xff)
227                     {
228                         w->buffer[x] = (unsigned char)0;
229                         x--;
230                     }
231
232                     w->buffer[x] += 1;
233                 }
234
235                 w->buffer[w->pos++] = (lowvalue >> (24 - offset));
236                 lowvalue <<= offset;
237                 shift = count;
238                 lowvalue &= 0xffffff;
239                 count -= 8 ;
240             }
241
242             lowvalue <<= shift;
243         }
244         while (n);
245
246
247         if (b->base_val)
248         {
249             const int e = p->Extra, L = b->Len;
250
251             if (L)
252             {
253                 const unsigned char *pp = b->prob;
254                 int v = e >> 1;
255                 int n = L;              /* number of bits in v, assumed nonzero */
256                 int i = 0;
257
258                 do
259                 {
260                     const int bb = (v >> --n) & 1;
261                     split = 1 + (((range - 1) * pp[i>>1]) >> 8);
262                     i = b->tree[i+bb];
263
264                     if (bb)
265                     {
266                         lowvalue += split;
267                         range = range - split;
268                     }
269                     else
270                     {
271                         range = split;
272                     }
273
274                     shift = norm[range];
275                     range <<= shift;
276                     count += shift;
277
278                     if (count >= 0)
279                     {
280                         int offset = shift - count;
281
282                         if ((lowvalue << (offset - 1)) & 0x80000000)
283                         {
284                             int x = w->pos - 1;
285
286                             while (x >= 0 && w->buffer[x] == 0xff)
287                             {
288                                 w->buffer[x] = (unsigned char)0;
289                                 x--;
290                             }
291
292                             w->buffer[x] += 1;
293                         }
294
295                         w->buffer[w->pos++] = (lowvalue >> (24 - offset));
296                         lowvalue <<= offset;
297                         shift = count;
298                         lowvalue &= 0xffffff;
299                         count -= 8 ;
300                     }
301
302                     lowvalue <<= shift;
303                 }
304                 while (n);
305             }
306
307
308             {
309
310                 split = (range + 1) >> 1;
311
312                 if (e & 1)
313                 {
314                     lowvalue += split;
315                     range = range - split;
316                 }
317                 else
318                 {
319                     range = split;
320                 }
321
322                 range <<= 1;
323
324                 if ((lowvalue & 0x80000000))
325                 {
326                     int x = w->pos - 1;
327
328                     while (x >= 0 && w->buffer[x] == 0xff)
329                     {
330                         w->buffer[x] = (unsigned char)0;
331                         x--;
332                     }
333
334                     w->buffer[x] += 1;
335
336                 }
337
338                 lowvalue  <<= 1;
339
340                 if (!++count)
341                 {
342                     count = -8;
343                     w->buffer[w->pos++] = (lowvalue >> 24);
344                     lowvalue &= 0xffffff;
345                 }
346             }
347
348         }
349
350         ++p;
351     }
352
353     w->count = count;
354     w->lowvalue = lowvalue;
355     w->range = range;
356
357 }
358
359 static void write_partition_size(unsigned char *cx_data, int size)
360 {
361     signed char csize;
362
363     csize = size & 0xff;
364     *cx_data = csize;
365     csize = (size >> 8) & 0xff;
366     *(cx_data + 1) = csize;
367     csize = (size >> 16) & 0xff;
368     *(cx_data + 2) = csize;
369
370 }
371
372 static void pack_tokens_into_partitions_c(VP8_COMP *cpi, unsigned char *cx_data, int num_part, int *size)
373 {
374
375     int i;
376     unsigned char *ptr = cx_data;
377     unsigned int shift;
378     vp8_writer *w = &cpi->bc2;
379     *size = 3 * (num_part - 1);
380     ptr = cx_data + (*size);
381
382     for (i = 0; i < num_part; i++)
383     {
384         vp8_start_encode(w, ptr);
385         {
386             unsigned int split;
387             int count = w->count;
388             unsigned int range = w->range;
389             unsigned int lowvalue = w->lowvalue;
390             int mb_row;
391
392             for (mb_row = i; mb_row < cpi->common.mb_rows; mb_row += num_part)
393             {
394                 TOKENEXTRA *p    = cpi->tplist[mb_row].start;
395                 TOKENEXTRA *stop = cpi->tplist[mb_row].stop;
396
397                 while (p < stop)
398                 {
399                     const int t = p->Token;
400                     vp8_token *const a = vp8_coef_encodings + t;
401                     const vp8_extra_bit_struct *const b = vp8_extra_bits + t;
402                     int i = 0;
403                     const unsigned char *pp = p->context_tree;
404                     int v = a->value;
405                     int n = a->Len;
406
407                     if (p->skip_eob_node)
408                     {
409                         n--;
410                         i = 2;
411                     }
412
413                     do
414                     {
415                         const int bb = (v >> --n) & 1;
416                         split = 1 + (((range - 1) * pp[i>>1]) >> 8);
417                         i = vp8_coef_tree[i+bb];
418
419                         if (bb)
420                         {
421                             lowvalue += split;
422                             range = range - split;
423                         }
424                         else
425                         {
426                             range = split;
427                         }
428
429                         shift = norm[range];
430                         range <<= shift;
431                         count += shift;
432
433                         if (count >= 0)
434                         {
435                             int offset = shift - count;
436
437                             if ((lowvalue << (offset - 1)) & 0x80000000)
438                             {
439                                 int x = w->pos - 1;
440
441                                 while (x >= 0 && w->buffer[x] == 0xff)
442                                 {
443                                     w->buffer[x] = (unsigned char)0;
444                                     x--;
445                                 }
446
447                                 w->buffer[x] += 1;
448                             }
449
450                             w->buffer[w->pos++] = (lowvalue >> (24 - offset));
451                             lowvalue <<= offset;
452                             shift = count;
453                             lowvalue &= 0xffffff;
454                             count -= 8 ;
455                         }
456
457                         lowvalue <<= shift;
458                     }
459                     while (n);
460
461
462                     if (b->base_val)
463                     {
464                         const int e = p->Extra, L = b->Len;
465
466                         if (L)
467                         {
468                             const unsigned char *pp = b->prob;
469                             int v = e >> 1;
470                             int n = L;              /* number of bits in v, assumed nonzero */
471                             int i = 0;
472
473                             do
474                             {
475                                 const int bb = (v >> --n) & 1;
476                                 split = 1 + (((range - 1) * pp[i>>1]) >> 8);
477                                 i = b->tree[i+bb];
478
479                                 if (bb)
480                                 {
481                                     lowvalue += split;
482                                     range = range - split;
483                                 }
484                                 else
485                                 {
486                                     range = split;
487                                 }
488
489                                 shift = norm[range];
490                                 range <<= shift;
491                                 count += shift;
492
493                                 if (count >= 0)
494                                 {
495                                     int offset = shift - count;
496
497                                     if ((lowvalue << (offset - 1)) & 0x80000000)
498                                     {
499                                         int x = w->pos - 1;
500
501                                         while (x >= 0 && w->buffer[x] == 0xff)
502                                         {
503                                             w->buffer[x] = (unsigned char)0;
504                                             x--;
505                                         }
506
507                                         w->buffer[x] += 1;
508                                     }
509
510                                     w->buffer[w->pos++] = (lowvalue >> (24 - offset));
511                                     lowvalue <<= offset;
512                                     shift = count;
513                                     lowvalue &= 0xffffff;
514                                     count -= 8 ;
515                                 }
516
517                                 lowvalue <<= shift;
518                             }
519                             while (n);
520                         }
521
522                         {
523                             split = (range + 1) >> 1;
524
525                             if (e & 1)
526                             {
527                                 lowvalue += split;
528                                 range = range - split;
529                             }
530                             else
531                             {
532                                 range = split;
533                             }
534
535                             range <<= 1;
536
537                             if ((lowvalue & 0x80000000))
538                             {
539                                 int x = w->pos - 1;
540
541                                 while (x >= 0 && w->buffer[x] == 0xff)
542                                 {
543                                     w->buffer[x] = (unsigned char)0;
544                                     x--;
545                                 }
546
547                                 w->buffer[x] += 1;
548
549                             }
550
551                             lowvalue  <<= 1;
552
553                             if (!++count)
554                             {
555                                 count = -8;
556                                 w->buffer[w->pos++] = (lowvalue >> 24);
557                                 lowvalue &= 0xffffff;
558                             }
559                         }
560
561                     }
562
563                     ++p;
564                 }
565             }
566
567             w->count    = count;
568             w->lowvalue = lowvalue;
569             w->range    = range;
570
571         }
572
573         vp8_stop_encode(w);
574         *size +=   w->pos;
575
576         if (i < (num_part - 1))
577         {
578             write_partition_size(cx_data, w->pos);
579             cx_data += 3;
580             ptr += w->pos;
581         }
582     }
583 }
584
585
586 static void pack_mb_row_tokens_c(VP8_COMP *cpi, vp8_writer *w)
587 {
588
589     unsigned int split;
590     int count = w->count;
591     unsigned int range = w->range;
592     unsigned int lowvalue = w->lowvalue;
593     unsigned int shift;
594     int mb_row;
595
596     for (mb_row = 0; mb_row < cpi->common.mb_rows; mb_row++)
597     {
598         TOKENEXTRA *p    = cpi->tplist[mb_row].start;
599         TOKENEXTRA *stop = cpi->tplist[mb_row].stop;
600
601         while (p < stop)
602         {
603             const int t = p->Token;
604             vp8_token *const a = vp8_coef_encodings + t;
605             const vp8_extra_bit_struct *const b = vp8_extra_bits + t;
606             int i = 0;
607             const unsigned char *pp = p->context_tree;
608             int v = a->value;
609             int n = a->Len;
610
611             if (p->skip_eob_node)
612             {
613                 n--;
614                 i = 2;
615             }
616
617             do
618             {
619                 const int bb = (v >> --n) & 1;
620                 split = 1 + (((range - 1) * pp[i>>1]) >> 8);
621                 i = vp8_coef_tree[i+bb];
622
623                 if (bb)
624                 {
625                     lowvalue += split;
626                     range = range - split;
627                 }
628                 else
629                 {
630                     range = split;
631                 }
632
633                 shift = norm[range];
634                 range <<= shift;
635                 count += shift;
636
637                 if (count >= 0)
638                 {
639                     int offset = shift - count;
640
641                     if ((lowvalue << (offset - 1)) & 0x80000000)
642                     {
643                         int x = w->pos - 1;
644
645                         while (x >= 0 && w->buffer[x] == 0xff)
646                         {
647                             w->buffer[x] = (unsigned char)0;
648                             x--;
649                         }
650
651                         w->buffer[x] += 1;
652                     }
653
654                     w->buffer[w->pos++] = (lowvalue >> (24 - offset));
655                     lowvalue <<= offset;
656                     shift = count;
657                     lowvalue &= 0xffffff;
658                     count -= 8 ;
659                 }
660
661                 lowvalue <<= shift;
662             }
663             while (n);
664
665
666             if (b->base_val)
667             {
668                 const int e = p->Extra, L = b->Len;
669
670                 if (L)
671                 {
672                     const unsigned char *pp = b->prob;
673                     int v = e >> 1;
674                     int n = L;              /* number of bits in v, assumed nonzero */
675                     int i = 0;
676
677                     do
678                     {
679                         const int bb = (v >> --n) & 1;
680                         split = 1 + (((range - 1) * pp[i>>1]) >> 8);
681                         i = b->tree[i+bb];
682
683                         if (bb)
684                         {
685                             lowvalue += split;
686                             range = range - split;
687                         }
688                         else
689                         {
690                             range = split;
691                         }
692
693                         shift = norm[range];
694                         range <<= shift;
695                         count += shift;
696
697                         if (count >= 0)
698                         {
699                             int offset = shift - count;
700
701                             if ((lowvalue << (offset - 1)) & 0x80000000)
702                             {
703                                 int x = w->pos - 1;
704
705                                 while (x >= 0 && w->buffer[x] == 0xff)
706                                 {
707                                     w->buffer[x] = (unsigned char)0;
708                                     x--;
709                                 }
710
711                                 w->buffer[x] += 1;
712                             }
713
714                             w->buffer[w->pos++] = (lowvalue >> (24 - offset));
715                             lowvalue <<= offset;
716                             shift = count;
717                             lowvalue &= 0xffffff;
718                             count -= 8 ;
719                         }
720
721                         lowvalue <<= shift;
722                     }
723                     while (n);
724                 }
725
726                 {
727                     split = (range + 1) >> 1;
728
729                     if (e & 1)
730                     {
731                         lowvalue += split;
732                         range = range - split;
733                     }
734                     else
735                     {
736                         range = split;
737                     }
738
739                     range <<= 1;
740
741                     if ((lowvalue & 0x80000000))
742                     {
743                         int x = w->pos - 1;
744
745                         while (x >= 0 && w->buffer[x] == 0xff)
746                         {
747                             w->buffer[x] = (unsigned char)0;
748                             x--;
749                         }
750
751                         w->buffer[x] += 1;
752
753                     }
754
755                     lowvalue  <<= 1;
756
757                     if (!++count)
758                     {
759                         count = -8;
760                         w->buffer[w->pos++] = (lowvalue >> 24);
761                         lowvalue &= 0xffffff;
762                     }
763                 }
764
765             }
766
767             ++p;
768         }
769     }
770
771     w->count = count;
772     w->lowvalue = lowvalue;
773     w->range = range;
774
775 }
776
777 static void write_mv_ref
778 (
779     vp8_writer *w, MB_PREDICTION_MODE m, const vp8_prob *p
780 )
781 {
782
783     assert(NEARESTMV <= m  &&  m <= SPLITMV);
784
785     vp8_write_token(w, vp8_mv_ref_tree, p,
786                     vp8_mv_ref_encoding_array - NEARESTMV + m);
787 }
788
789 static void write_sub_mv_ref
790 (
791     vp8_writer *w, B_PREDICTION_MODE m, const vp8_prob *p
792 )
793 {
794     assert(LEFT4X4 <= m  &&  m <= NEW4X4);
795
796     vp8_write_token(w, vp8_sub_mv_ref_tree, p,
797                     vp8_sub_mv_ref_encoding_array - LEFT4X4 + m);
798 }
799
800 static void write_mv
801 (
802     vp8_writer *w, const MV *mv, const MV *ref, const MV_CONTEXT *mvc
803 )
804 {
805     MV e;
806     e.row = mv->row - ref->row;
807     e.col = mv->col - ref->col;
808
809     vp8_encode_motion_vector(w, &e, mvc);
810 }
811
812 static void write_mb_features(vp8_writer *w, const MB_MODE_INFO *mi, const MACROBLOCKD *x)
813 {
814     // Encode the MB segment id.
815     if (x->segmentation_enabled && x->update_mb_segmentation_map)
816     {
817         switch (mi->segment_id)
818         {
819         case 0:
820             vp8_write(w, 0, x->mb_segment_tree_probs[0]);
821             vp8_write(w, 0, x->mb_segment_tree_probs[1]);
822             break;
823         case 1:
824             vp8_write(w, 0, x->mb_segment_tree_probs[0]);
825             vp8_write(w, 1, x->mb_segment_tree_probs[1]);
826             break;
827         case 2:
828             vp8_write(w, 1, x->mb_segment_tree_probs[0]);
829             vp8_write(w, 0, x->mb_segment_tree_probs[2]);
830             break;
831         case 3:
832             vp8_write(w, 1, x->mb_segment_tree_probs[0]);
833             vp8_write(w, 1, x->mb_segment_tree_probs[2]);
834             break;
835
836             // TRAP.. This should not happen
837         default:
838             vp8_write(w, 0, x->mb_segment_tree_probs[0]);
839             vp8_write(w, 0, x->mb_segment_tree_probs[1]);
840             break;
841         }
842     }
843 }
844
845
846 static void pack_inter_mode_mvs(VP8_COMP *const cpi)
847 {
848     VP8_COMMON *const pc = & cpi->common;
849     vp8_writer *const w = & cpi->bc;
850     const MV_CONTEXT *mvc = pc->fc.mvc;
851
852     const int *const rfct = cpi->count_mb_ref_frame_usage;
853     const int rf_intra = rfct[INTRA_FRAME];
854     const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
855
856     MODE_INFO *m = pc->mi, *ms;
857     const int mis = pc->mode_info_stride;
858     int mb_row = -1;
859
860     int prob_last_coded;
861     int prob_gf_coded;
862     int prob_skip_false = 0;
863     ms = pc->mi - 1;
864
865     cpi->mb.partition_info = cpi->mb.pi;
866
867     // Calculate the probabilities to be used to code the reference frame based on actual useage this frame
868     if (!(cpi->prob_intra_coded = rf_intra * 255 / (rf_intra + rf_inter)))
869         cpi->prob_intra_coded = 1;
870
871     prob_last_coded = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
872
873     if (!prob_last_coded)
874         prob_last_coded = 1;
875
876     prob_gf_coded = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
877                     ? (rfct[GOLDEN_FRAME] * 255) / (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME]) : 128;
878
879     if (!prob_gf_coded)
880         prob_gf_coded = 1;
881
882
883 #ifdef ENTROPY_STATS
884     active_section = 1;
885 #endif
886
887     if (pc->mb_no_coeff_skip)
888     {
889         prob_skip_false = cpi->skip_false_count * 256 / (cpi->skip_false_count + cpi->skip_true_count);
890
891         if (prob_skip_false <= 1)
892             prob_skip_false = 1;
893
894         if (prob_skip_false > 255)
895             prob_skip_false = 255;
896
897         cpi->prob_skip_false = prob_skip_false;
898         vp8_write_literal(w, prob_skip_false, 8);
899     }
900
901     vp8_write_literal(w, cpi->prob_intra_coded, 8);
902     vp8_write_literal(w, prob_last_coded, 8);
903     vp8_write_literal(w, prob_gf_coded, 8);
904
905     update_mbintra_mode_probs(cpi);
906
907     vp8_write_mvprobs(cpi);
908
909     while (++mb_row < pc->mb_rows)
910     {
911         int mb_col = -1;
912
913         while (++mb_col < pc->mb_cols)
914         {
915             const MB_MODE_INFO *const mi = & m->mbmi;
916             const MV_REFERENCE_FRAME rf = mi->ref_frame;
917             const MB_PREDICTION_MODE mode = mi->mode;
918
919             MACROBLOCKD *xd = &cpi->mb.e_mbd;
920
921             // Distance of Mb to the various image edges.
922             // These specified to 8th pel as they are always compared to MV values that are in 1/8th pel units
923             xd->mb_to_left_edge = -((mb_col * 16) << 3);
924             xd->mb_to_right_edge = ((pc->mb_cols - 1 - mb_col) * 16) << 3;
925             xd->mb_to_top_edge = -((mb_row * 16)) << 3;
926             xd->mb_to_bottom_edge = ((pc->mb_rows - 1 - mb_row) * 16) << 3;
927
928 #ifdef ENTROPY_STATS
929             active_section = 9;
930 #endif
931
932             if (cpi->mb.e_mbd.update_mb_segmentation_map)
933                 write_mb_features(w, mi, &cpi->mb.e_mbd);
934
935             if (pc->mb_no_coeff_skip)
936                 vp8_encode_bool(w, m->mbmi.mb_skip_coeff, prob_skip_false);
937
938             if (rf == INTRA_FRAME)
939             {
940                 vp8_write(w, 0, cpi->prob_intra_coded);
941 #ifdef ENTROPY_STATS
942                 active_section = 6;
943 #endif
944                 write_ymode(w, mode, pc->fc.ymode_prob);
945
946                 if (mode == B_PRED)
947                 {
948                     int j = 0;
949
950                     do
951                         write_bmode(w, m->bmi[j].mode, pc->fc.bmode_prob);
952
953                     while (++j < 16);
954                 }
955
956                 write_uv_mode(w, mi->uv_mode, pc->fc.uv_mode_prob);
957             }
958             else    /* inter coded */
959             {
960                 MV best_mv;
961                 vp8_prob mv_ref_p [VP8_MVREFS-1];
962
963                 vp8_write(w, 1, cpi->prob_intra_coded);
964
965                 if (rf == LAST_FRAME)
966                     vp8_write(w, 0, prob_last_coded);
967                 else
968                 {
969                     vp8_write(w, 1, prob_last_coded);
970                     vp8_write(w, (rf == GOLDEN_FRAME) ? 0 : 1, prob_gf_coded);
971                 }
972
973                 {
974                     MV n1, n2;
975                     int ct[4];
976
977                     vp8_find_near_mvs(xd, m, &n1, &n2, &best_mv, ct, rf, cpi->common.ref_frame_sign_bias);
978                     vp8_mv_ref_probs(mv_ref_p, ct);
979
980 #ifdef ENTROPY_STATS
981                     accum_mv_refs(mode, ct);
982 #endif
983
984                 }
985
986 #ifdef ENTROPY_STATS
987                 active_section = 3;
988 #endif
989
990                 write_mv_ref(w, mode, mv_ref_p);
991
992                 switch (mode)   /* new, split require MVs */
993                 {
994                 case NEWMV:
995
996 #ifdef ENTROPY_STATS
997                     active_section = 5;
998 #endif
999
1000                     write_mv(w, &mi->mv.as_mv, &best_mv, mvc);
1001                     break;
1002
1003                 case SPLITMV:
1004                 {
1005                     int j = 0;
1006
1007 #ifdef MODE_STATS
1008                     ++count_mb_seg [mi->partitioning];
1009 #endif
1010
1011                     write_split(w, mi->partitioning);
1012
1013                     do
1014                     {
1015                         const B_MODE_INFO *const b = cpi->mb.partition_info->bmi + j;
1016                         const int *const  L = vp8_mbsplits [mi->partitioning];
1017                         int k = -1;  /* first block in subset j */
1018                         int mv_contz;
1019
1020                         while (j != L[++k])
1021                             if (k >= 16)
1022                                 assert(0);
1023
1024                         mv_contz = vp8_mv_cont
1025                                    (&(vp8_left_bmi(m, k)->mv.as_mv),
1026                                     &(vp8_above_bmi(m, k, mis)->mv.as_mv));
1027                         write_sub_mv_ref(w, b->mode, vp8_sub_mv_ref_prob2 [mv_contz]); //pc->fc.sub_mv_ref_prob);
1028
1029                         if (b->mode == NEW4X4)
1030                         {
1031 #ifdef ENTROPY_STATS
1032                             active_section = 11;
1033 #endif
1034                             write_mv(w, &b->mv.as_mv, &best_mv, (const MV_CONTEXT *) mvc);
1035                         }
1036                     }
1037                     while (++j < cpi->mb.partition_info->count);
1038                 }
1039                 break;
1040                 default:
1041                     break;
1042                 }
1043             }
1044
1045             ++m;
1046             cpi->mb.partition_info++;
1047         }
1048
1049         ++m;  /* skip L prediction border */
1050         cpi->mb.partition_info++;
1051     }
1052 }
1053
1054
1055 static void write_kfmodes(VP8_COMP *cpi)
1056 {
1057     vp8_writer *const bc = & cpi->bc;
1058     const VP8_COMMON *const c = & cpi->common;
1059     /* const */
1060     MODE_INFO *m = c->mi;
1061
1062     int mb_row = -1;
1063     int prob_skip_false = 0;
1064
1065     if (c->mb_no_coeff_skip)
1066     {
1067         prob_skip_false = cpi->skip_false_count * 256 / (cpi->skip_false_count + cpi->skip_true_count);
1068
1069         if (prob_skip_false <= 1)
1070             prob_skip_false = 1;
1071
1072         if (prob_skip_false >= 255)
1073             prob_skip_false = 255;
1074
1075         cpi->prob_skip_false = prob_skip_false;
1076         vp8_write_literal(bc, prob_skip_false, 8);
1077     }
1078
1079     while (++mb_row < c->mb_rows)
1080     {
1081         int mb_col = -1;
1082
1083         while (++mb_col < c->mb_cols)
1084         {
1085             const int ym = m->mbmi.mode;
1086
1087             if (cpi->mb.e_mbd.update_mb_segmentation_map)
1088                 write_mb_features(bc, &m->mbmi, &cpi->mb.e_mbd);
1089
1090             if (c->mb_no_coeff_skip)
1091                 vp8_encode_bool(bc, m->mbmi.mb_skip_coeff, prob_skip_false);
1092
1093             kfwrite_ymode(bc, ym, c->kf_ymode_prob);
1094
1095             if (ym == B_PRED)
1096             {
1097                 const int mis = c->mode_info_stride;
1098                 int i = 0;
1099
1100                 do
1101                 {
1102                     const B_PREDICTION_MODE A = vp8_above_bmi(m, i, mis)->mode;
1103                     const B_PREDICTION_MODE L = vp8_left_bmi(m, i)->mode;
1104                     const int bm = m->bmi[i].mode;
1105
1106 #ifdef ENTROPY_STATS
1107                     ++intra_mode_stats [A] [L] [bm];
1108 #endif
1109
1110                     write_bmode(bc, bm, c->kf_bmode_prob [A] [L]);
1111                 }
1112                 while (++i < 16);
1113             }
1114
1115             write_uv_mode(bc, (m++)->mbmi.uv_mode, c->kf_uv_mode_prob);
1116         }
1117
1118         m++;    // skip L prediction border
1119     }
1120 }
1121 int vp8_estimate_entropy_savings(VP8_COMP *cpi)
1122 {
1123     int i = 0;
1124     int savings = 0;
1125
1126     const int *const rfct = cpi->count_mb_ref_frame_usage;
1127     const int rf_intra = rfct[INTRA_FRAME];
1128     const int rf_inter = rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
1129     int new_intra, new_last, gf_last, oldtotal, newtotal;
1130     int ref_frame_cost[MAX_REF_FRAMES];
1131
1132     vp8_clear_system_state(); //__asm emms;
1133
1134     if (cpi->common.frame_type != KEY_FRAME)
1135     {
1136         if (!(new_intra = rf_intra * 255 / (rf_intra + rf_inter)))
1137             new_intra = 1;
1138
1139         new_last = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
1140
1141         gf_last = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
1142                   ? (rfct[GOLDEN_FRAME] * 255) / (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME]) : 128;
1143
1144         // new costs
1145         ref_frame_cost[INTRA_FRAME]   = vp8_cost_zero(new_intra);
1146         ref_frame_cost[LAST_FRAME]    = vp8_cost_one(new_intra)
1147                                         + vp8_cost_zero(new_last);
1148         ref_frame_cost[GOLDEN_FRAME]  = vp8_cost_one(new_intra)
1149                                         + vp8_cost_one(new_last)
1150                                         + vp8_cost_zero(gf_last);
1151         ref_frame_cost[ALTREF_FRAME]  = vp8_cost_one(new_intra)
1152                                         + vp8_cost_one(new_last)
1153                                         + vp8_cost_one(gf_last);
1154
1155         newtotal =
1156             rfct[INTRA_FRAME] * ref_frame_cost[INTRA_FRAME] +
1157             rfct[LAST_FRAME] * ref_frame_cost[LAST_FRAME] +
1158             rfct[GOLDEN_FRAME] * ref_frame_cost[GOLDEN_FRAME] +
1159             rfct[ALTREF_FRAME] * ref_frame_cost[ALTREF_FRAME];
1160
1161
1162         // old costs
1163         ref_frame_cost[INTRA_FRAME]   = vp8_cost_zero(cpi->prob_intra_coded);
1164         ref_frame_cost[LAST_FRAME]    = vp8_cost_one(cpi->prob_intra_coded)
1165                                         + vp8_cost_zero(cpi->prob_last_coded);
1166         ref_frame_cost[GOLDEN_FRAME]  = vp8_cost_one(cpi->prob_intra_coded)
1167                                         + vp8_cost_one(cpi->prob_last_coded)
1168                                         + vp8_cost_zero(cpi->prob_gf_coded);
1169         ref_frame_cost[ALTREF_FRAME]  = vp8_cost_one(cpi->prob_intra_coded)
1170                                         + vp8_cost_one(cpi->prob_last_coded)
1171                                         + vp8_cost_one(cpi->prob_gf_coded);
1172
1173         oldtotal =
1174             rfct[INTRA_FRAME] * ref_frame_cost[INTRA_FRAME] +
1175             rfct[LAST_FRAME] * ref_frame_cost[LAST_FRAME] +
1176             rfct[GOLDEN_FRAME] * ref_frame_cost[GOLDEN_FRAME] +
1177             rfct[ALTREF_FRAME] * ref_frame_cost[ALTREF_FRAME];
1178
1179         savings += (oldtotal - newtotal) / 256;
1180     }
1181
1182
1183     do
1184     {
1185         int j = 0;
1186
1187         do
1188         {
1189             int k = 0;
1190
1191             do
1192             {
1193                 /* at every context */
1194
1195                 /* calc probs and branch cts for this frame only */
1196                 //vp8_prob new_p           [vp8_coef_tokens-1];
1197                 //unsigned int branch_ct   [vp8_coef_tokens-1] [2];
1198
1199                 int t = 0;      /* token/prob index */
1200
1201                 vp8_tree_probs_from_distribution(
1202                     vp8_coef_tokens, vp8_coef_encodings, vp8_coef_tree,
1203                     cpi->frame_coef_probs [i][j][k], cpi->frame_branch_ct [i][j][k], cpi->coef_counts [i][j][k],
1204                     256, 1
1205                 );
1206
1207                 do
1208                 {
1209                     const unsigned int *ct  = cpi->frame_branch_ct [i][j][k][t];
1210                     const vp8_prob newp = cpi->frame_coef_probs [i][j][k][t];
1211
1212                     const vp8_prob old = cpi->common.fc.coef_probs [i][j][k][t];
1213                     const vp8_prob upd = vp8_coef_update_probs [i][j][k][t];
1214
1215                     const int old_b = vp8_cost_branch(ct, old);
1216                     const int new_b = vp8_cost_branch(ct, newp);
1217
1218                     const int update_b = 8 +
1219                                          ((vp8_cost_one(upd) - vp8_cost_zero(upd)) >> 8);
1220
1221                     const int s = old_b - new_b - update_b;
1222
1223                     if (s > 0)
1224                         savings += s;
1225
1226
1227                 }
1228                 while (++t < vp8_coef_tokens - 1);
1229
1230
1231             }
1232             while (++k < PREV_COEF_CONTEXTS);
1233         }
1234         while (++j < COEF_BANDS);
1235     }
1236     while (++i < BLOCK_TYPES);
1237
1238     return savings;
1239 }
1240
1241 static void update_coef_probs(VP8_COMP *cpi)
1242 {
1243     int i = 0;
1244     vp8_writer *const w = & cpi->bc;
1245     int savings = 0;
1246
1247     vp8_clear_system_state(); //__asm emms;
1248
1249
1250     do
1251     {
1252         int j = 0;
1253
1254         do
1255         {
1256             int k = 0;
1257
1258             do
1259             {
1260                 //note: use result from vp8_estimate_entropy_savings, so no need to call vp8_tree_probs_from_distribution here.
1261                 /* at every context */
1262
1263                 /* calc probs and branch cts for this frame only */
1264                 //vp8_prob new_p           [vp8_coef_tokens-1];
1265                 //unsigned int branch_ct   [vp8_coef_tokens-1] [2];
1266
1267                 int t = 0;      /* token/prob index */
1268
1269                 //vp8_tree_probs_from_distribution(
1270                 //    vp8_coef_tokens, vp8_coef_encodings, vp8_coef_tree,
1271                 //    new_p, branch_ct, (unsigned int *)cpi->coef_counts [i][j][k],
1272                 //    256, 1
1273                 //    );
1274
1275                 do
1276                 {
1277                     const unsigned int *ct  = cpi->frame_branch_ct [i][j][k][t];
1278                     const vp8_prob newp = cpi->frame_coef_probs [i][j][k][t];
1279
1280                     vp8_prob *Pold = cpi->common.fc.coef_probs [i][j][k] + t;
1281                     const vp8_prob old = *Pold;
1282                     const vp8_prob upd = vp8_coef_update_probs [i][j][k][t];
1283
1284                     const int old_b = vp8_cost_branch(ct, old);
1285                     const int new_b = vp8_cost_branch(ct, newp);
1286
1287                     const int update_b = 8 +
1288                                          ((vp8_cost_one(upd) - vp8_cost_zero(upd)) >> 8);
1289
1290                     const int s = old_b - new_b - update_b;
1291                     const int u = s > 0 ? 1 : 0;
1292
1293                     vp8_write(w, u, upd);
1294
1295
1296 #ifdef ENTROPY_STATS
1297                     ++ tree_update_hist [i][j][k][t] [u];
1298 #endif
1299
1300                     if (u)
1301                     {
1302                         /* send/use new probability */
1303
1304                         *Pold = newp;
1305                         vp8_write_literal(w, newp, 8);
1306
1307                         savings += s;
1308
1309                     }
1310
1311                 }
1312                 while (++t < vp8_coef_tokens - 1);
1313
1314                 /* Accum token counts for generation of default statistics */
1315 #ifdef ENTROPY_STATS
1316                 t = 0;
1317
1318                 do
1319                 {
1320                     context_counters [i][j][k][t] += cpi->coef_counts [i][j][k][t];
1321                 }
1322                 while (++t < vp8_coef_tokens);
1323
1324 #endif
1325
1326             }
1327             while (++k < PREV_COEF_CONTEXTS);
1328         }
1329         while (++j < COEF_BANDS);
1330     }
1331     while (++i < BLOCK_TYPES);
1332
1333 }
1334 #ifdef PACKET_TESTING
1335 FILE *vpxlogc = 0;
1336 #endif
1337
1338 static void put_delta_q(vp8_writer *bc, int delta_q)
1339 {
1340     if (delta_q != 0)
1341     {
1342         vp8_write_bit(bc, 1);
1343         vp8_write_literal(bc, abs(delta_q), 4);
1344
1345         if (delta_q < 0)
1346             vp8_write_bit(bc, 1);
1347         else
1348             vp8_write_bit(bc, 0);
1349     }
1350     else
1351         vp8_write_bit(bc, 0);
1352 }
1353
1354 void vp8_pack_bitstream(VP8_COMP *cpi, unsigned char *dest, unsigned long *size)
1355 {
1356     int i, j;
1357     VP8_HEADER oh;
1358     VP8_COMMON *const pc = & cpi->common;
1359     vp8_writer *const bc = & cpi->bc;
1360     MACROBLOCKD *const xd = & cpi->mb.e_mbd;
1361     int extra_bytes_packed = 0;
1362
1363     unsigned char *cx_data = dest;
1364     const int *mb_feature_data_bits;
1365
1366     oh.show_frame = (int) pc->show_frame;
1367     oh.type = (int)pc->frame_type;
1368     oh.version = pc->version;
1369
1370     mb_feature_data_bits = vp8_mb_feature_data_bits;
1371     cx_data += 3;
1372
1373 #if defined(SECTIONBITS_OUTPUT)
1374     Sectionbits[active_section = 1] += sizeof(VP8_HEADER) * 8 * 256;
1375 #endif
1376
1377     //vp8_kf_default_bmode_probs() is called in vp8_setup_key_frame() once for each
1378     //K frame before encode frame. pc->kf_bmode_prob doesn't get changed anywhere
1379     //else. No need to call it again here. --yw
1380     //vp8_kf_default_bmode_probs( pc->kf_bmode_prob);
1381
1382     // every keyframe send startcode, width, height, scale factor, clamp and color type
1383     if (oh.type == KEY_FRAME)
1384     {
1385         int v;
1386
1387         // Start / synch code
1388         cx_data[0] = 0x9D;
1389         cx_data[1] = 0x01;
1390         cx_data[2] = 0x2a;
1391
1392         v = (pc->horiz_scale << 14) | pc->Width;
1393         cx_data[3] = v;
1394         cx_data[4] = v >> 8;
1395
1396         v = (pc->vert_scale << 14) | pc->Height;
1397         cx_data[5] = v;
1398         cx_data[6] = v >> 8;
1399
1400         extra_bytes_packed = 7;
1401         cx_data += extra_bytes_packed ;
1402
1403         vp8_start_encode(bc, cx_data);
1404
1405         // signal clr type
1406         vp8_write_bit(bc, pc->clr_type);
1407         vp8_write_bit(bc, pc->clamp_type);
1408
1409     }
1410     else
1411         vp8_start_encode(bc, cx_data);
1412
1413
1414     // Signal whether or not Segmentation is enabled
1415     vp8_write_bit(bc, (xd->segmentation_enabled) ? 1 : 0);
1416
1417     // Indicate which features are enabled
1418     if (xd->segmentation_enabled)
1419     {
1420         // Signal whether or not the segmentation map is being updated.
1421         vp8_write_bit(bc, (xd->update_mb_segmentation_map) ? 1 : 0);
1422         vp8_write_bit(bc, (xd->update_mb_segmentation_data) ? 1 : 0);
1423
1424         if (xd->update_mb_segmentation_data)
1425         {
1426             signed char Data;
1427
1428             vp8_write_bit(bc, (xd->mb_segement_abs_delta) ? 1 : 0);
1429
1430             // For each segmentation feature (Quant and loop filter level)
1431             for (i = 0; i < MB_LVL_MAX; i++)
1432             {
1433                 // For each of the segments
1434                 for (j = 0; j < MAX_MB_SEGMENTS; j++)
1435                 {
1436                     Data = xd->segment_feature_data[i][j];
1437
1438                     // Frame level data
1439                     if (Data)
1440                     {
1441                         vp8_write_bit(bc, 1);
1442
1443                         if (Data < 0)
1444                         {
1445                             Data = - Data;
1446                             vp8_write_literal(bc, Data, mb_feature_data_bits[i]);
1447                             vp8_write_bit(bc, 1);
1448                         }
1449                         else
1450                         {
1451                             vp8_write_literal(bc, Data, mb_feature_data_bits[i]);
1452                             vp8_write_bit(bc, 0);
1453                         }
1454                     }
1455                     else
1456                         vp8_write_bit(bc, 0);
1457                 }
1458             }
1459         }
1460
1461         if (xd->update_mb_segmentation_map)
1462         {
1463             // Write the probs used to decode the segment id for each macro block.
1464             for (i = 0; i < MB_FEATURE_TREE_PROBS; i++)
1465             {
1466                 int Data = xd->mb_segment_tree_probs[i];
1467
1468                 if (Data != 255)
1469                 {
1470                     vp8_write_bit(bc, 1);
1471                     vp8_write_literal(bc, Data, 8);
1472                 }
1473                 else
1474                     vp8_write_bit(bc, 0);
1475             }
1476         }
1477     }
1478
1479     // Code to determine whether or not to update the scan order.
1480     vp8_write_bit(bc, pc->filter_type);
1481     vp8_write_literal(bc, pc->filter_level, 6);
1482     vp8_write_literal(bc, pc->sharpness_level, 3);
1483
1484     // Write out loop filter deltas applied at the MB level based on mode or ref frame (if they are enabled).
1485     vp8_write_bit(bc, (xd->mode_ref_lf_delta_enabled) ? 1 : 0);
1486
1487     if (xd->mode_ref_lf_delta_enabled)
1488     {
1489         // Do the deltas need to be updated
1490         int send_update = xd->mode_ref_lf_delta_update
1491                           || cpi->oxcf.error_resilient_mode;
1492
1493         vp8_write_bit(bc, send_update);
1494         if (send_update)
1495         {
1496             int Data;
1497
1498             // Send update
1499             for (i = 0; i < MAX_REF_LF_DELTAS; i++)
1500             {
1501                 Data = xd->ref_lf_deltas[i];
1502
1503                 // Frame level data
1504                 if (xd->ref_lf_deltas[i] != xd->last_ref_lf_deltas[i]
1505                     || cpi->oxcf.error_resilient_mode)
1506                 {
1507                     xd->last_ref_lf_deltas[i] = xd->ref_lf_deltas[i];
1508                     vp8_write_bit(bc, 1);
1509
1510                     if (Data > 0)
1511                     {
1512                         vp8_write_literal(bc, (Data & 0x3F), 6);
1513                         vp8_write_bit(bc, 0);    // sign
1514                     }
1515                     else
1516                     {
1517                         Data = -Data;
1518                         vp8_write_literal(bc, (Data & 0x3F), 6);
1519                         vp8_write_bit(bc, 1);    // sign
1520                     }
1521                 }
1522                 else
1523                     vp8_write_bit(bc, 0);
1524             }
1525
1526             // Send update
1527             for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
1528             {
1529                 Data = xd->mode_lf_deltas[i];
1530
1531                 if (xd->mode_lf_deltas[i] != xd->last_mode_lf_deltas[i]
1532                     || cpi->oxcf.error_resilient_mode)
1533                 {
1534                     xd->last_mode_lf_deltas[i] = xd->mode_lf_deltas[i];
1535                     vp8_write_bit(bc, 1);
1536
1537                     if (Data > 0)
1538                     {
1539                         vp8_write_literal(bc, (Data & 0x3F), 6);
1540                         vp8_write_bit(bc, 0);    // sign
1541                     }
1542                     else
1543                     {
1544                         Data = -Data;
1545                         vp8_write_literal(bc, (Data & 0x3F), 6);
1546                         vp8_write_bit(bc, 1);    // sign
1547                     }
1548                 }
1549                 else
1550                     vp8_write_bit(bc, 0);
1551             }
1552         }
1553     }
1554
1555     //signal here is multi token partition is enabled
1556     vp8_write_literal(bc, pc->multi_token_partition, 2);
1557
1558     // Frame Qbaseline quantizer index
1559     vp8_write_literal(bc, pc->base_qindex, 7);
1560
1561     // Transmit Dc, Second order and Uv quantizer delta information
1562     put_delta_q(bc, pc->y1dc_delta_q);
1563     put_delta_q(bc, pc->y2dc_delta_q);
1564     put_delta_q(bc, pc->y2ac_delta_q);
1565     put_delta_q(bc, pc->uvdc_delta_q);
1566     put_delta_q(bc, pc->uvac_delta_q);
1567
1568     // When there is a key frame all reference buffers are updated using the new key frame
1569     if (pc->frame_type != KEY_FRAME)
1570     {
1571         // Should the GF or ARF be updated using the transmitted frame or buffer
1572         vp8_write_bit(bc, pc->refresh_golden_frame);
1573         vp8_write_bit(bc, pc->refresh_alt_ref_frame);
1574
1575         // If not being updated from current frame should either GF or ARF be updated from another buffer
1576         if (!pc->refresh_golden_frame)
1577             vp8_write_literal(bc, pc->copy_buffer_to_gf, 2);
1578
1579         if (!pc->refresh_alt_ref_frame)
1580             vp8_write_literal(bc, pc->copy_buffer_to_arf, 2);
1581
1582         // Indicate reference frame sign bias for Golden and ARF frames (always 0 for last frame buffer)
1583         vp8_write_bit(bc, pc->ref_frame_sign_bias[GOLDEN_FRAME]);
1584         vp8_write_bit(bc, pc->ref_frame_sign_bias[ALTREF_FRAME]);
1585     }
1586
1587     vp8_write_bit(bc, pc->refresh_entropy_probs);
1588
1589     if (pc->frame_type != KEY_FRAME)
1590         vp8_write_bit(bc, pc->refresh_last_frame);
1591
1592 #ifdef ENTROPY_STATS
1593
1594     if (pc->frame_type == INTER_FRAME)
1595         active_section = 0;
1596     else
1597         active_section = 7;
1598
1599 #endif
1600
1601     vp8_clear_system_state();  //__asm emms;
1602
1603     //************************************************
1604     // save a copy for later refresh
1605     {
1606         vpx_memcpy(&cpi->common.lfc, &cpi->common.fc, sizeof(cpi->common.fc));
1607     }
1608
1609     update_coef_probs(cpi);
1610
1611 #ifdef ENTROPY_STATS
1612     active_section = 2;
1613 #endif
1614
1615     // Write out the mb_no_coeff_skip flag
1616     vp8_write_bit(bc, pc->mb_no_coeff_skip);
1617
1618     if (pc->frame_type == KEY_FRAME)
1619     {
1620         write_kfmodes(cpi);
1621
1622 #ifdef ENTROPY_STATS
1623         active_section = 8;
1624 #endif
1625     }
1626     else
1627     {
1628         pack_inter_mode_mvs(cpi);
1629
1630 #ifdef ENTROPY_STATS
1631         active_section = 1;
1632 #endif
1633     }
1634
1635     vp8_stop_encode(bc);
1636
1637
1638     if (pc->multi_token_partition != ONE_PARTITION)
1639     {
1640         int num_part;
1641         int asize;
1642         num_part = 1 << pc->multi_token_partition;
1643
1644         pack_tokens_into_partitions(cpi, cx_data + bc->pos, num_part, &asize);
1645
1646         oh.first_partition_length_in_bytes = cpi->bc.pos;
1647
1648         *size = cpi->bc.pos + VP8_HEADER_SIZE + asize + extra_bytes_packed;
1649     }
1650     else
1651     {
1652         vp8_start_encode(&cpi->bc2, cx_data + bc->pos);
1653
1654 #if CONFIG_MULTITHREAD
1655         if (cpi->b_multi_threaded)
1656             pack_mb_row_tokens(cpi, &cpi->bc2);
1657         else
1658 #endif
1659             pack_tokens(&cpi->bc2, cpi->tok, cpi->tok_count);
1660
1661         vp8_stop_encode(&cpi->bc2);
1662         oh.first_partition_length_in_bytes = cpi->bc.pos ;
1663         *size = cpi->bc2.pos + cpi->bc.pos + VP8_HEADER_SIZE + extra_bytes_packed;
1664     }
1665
1666     {
1667         int v = (oh.first_partition_length_in_bytes << 5) |
1668                 (oh.show_frame << 4) |
1669                 (oh.version << 1) |
1670                 oh.type;
1671
1672         dest[0] = v;
1673         dest[1] = v >> 8;
1674         dest[2] = v >> 16;
1675     }
1676 }
1677
1678 #ifdef ENTROPY_STATS
1679 void print_tree_update_probs()
1680 {
1681     int i, j, k, l;
1682     FILE *f = fopen("context.c", "a");
1683     int Sum;
1684     fprintf(f, "\n/* Update probabilities for token entropy tree. */\n\n");
1685     fprintf(f, "const vp8_prob tree_update_probs[BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [vp8_coef_tokens-1] = {\n");
1686
1687     for (i = 0; i < BLOCK_TYPES; i++)
1688     {
1689         fprintf(f, "  { \n");
1690
1691         for (j = 0; j < COEF_BANDS; j++)
1692         {
1693             fprintf(f, "    {\n");
1694
1695             for (k = 0; k < PREV_COEF_CONTEXTS; k++)
1696             {
1697                 fprintf(f, "      {");
1698
1699                 for (l = 0; l < MAX_ENTROPY_TOKENS - 1; l++)
1700                 {
1701                     Sum = tree_update_hist[i][j][k][l][0] + tree_update_hist[i][j][k][l][1];
1702
1703                     if (Sum > 0)
1704                     {
1705                         if (((tree_update_hist[i][j][k][l][0] * 255) / Sum) > 0)
1706                             fprintf(f, "%3ld, ", (tree_update_hist[i][j][k][l][0] * 255) / Sum);
1707                         else
1708                             fprintf(f, "%3ld, ", 1);
1709                     }
1710                     else
1711                         fprintf(f, "%3ld, ", 128);
1712                 }
1713
1714                 fprintf(f, "},\n");
1715             }
1716
1717             fprintf(f, "    },\n");
1718         }
1719
1720         fprintf(f, "  },\n");
1721     }
1722
1723     fprintf(f, "};\n");
1724     fclose(f);
1725 }
1726 #endif