1/*
2 * copyright (c) 2004 Michael Niedermayer <michaelni@gmx.at>
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21/**
22 * @file libavcodec/bitstream.h
23 * bitstream api header.
24 */
25
26#ifndef AVCODEC_BITSTREAM_H
27#define AVCODEC_BITSTREAM_H
28
29#include <stdint.h>
30#include <stdlib.h>
31#include <assert.h>
32#include "libavutil/bswap.h"
33#include "libavutil/common.h"
34#include "libavutil/intreadwrite.h"
35#include "libavutil/log.h"
36
37#if defined(ALT_BITSTREAM_READER_LE) && !defined(ALT_BITSTREAM_READER)
38#   define ALT_BITSTREAM_READER
39#endif
40
41//#define ALT_BITSTREAM_WRITER
42//#define ALIGNED_BITSTREAM_WRITER
43#if !defined(LIBMPEG2_BITSTREAM_READER) && !defined(A32_BITSTREAM_READER) && !defined(ALT_BITSTREAM_READER)
44#   if ARCH_ARM
45#       define A32_BITSTREAM_READER
46#   else
47#       define ALT_BITSTREAM_READER
48//#define LIBMPEG2_BITSTREAM_READER
49//#define A32_BITSTREAM_READER
50#   endif
51#endif
52
53extern const uint8_t ff_reverse[256];
54
55#if ARCH_X86
56// avoid +32 for shift optimization (gcc should do that ...)
57static inline  int32_t NEG_SSR32( int32_t a, int8_t s){
58    __asm__ ("sarl %1, %0\n\t"
59         : "+r" (a)
60         : "ic" ((uint8_t)(-s))
61    );
62    return a;
63}
64static inline uint32_t NEG_USR32(uint32_t a, int8_t s){
65    __asm__ ("shrl %1, %0\n\t"
66         : "+r" (a)
67         : "ic" ((uint8_t)(-s))
68    );
69    return a;
70}
71#else
72#    define NEG_SSR32(a,s) ((( int32_t)(a))>>(32-(s)))
73#    define NEG_USR32(a,s) (((uint32_t)(a))>>(32-(s)))
74#endif
75
76/* bit output */
77
78/* buf and buf_end must be present and used by every alternative writer. */
79typedef struct PutBitContext {
80#ifdef ALT_BITSTREAM_WRITER
81    uint8_t *buf, *buf_end;
82    int index;
83#else
84    uint32_t bit_buf;
85    int bit_left;
86    uint8_t *buf, *buf_ptr, *buf_end;
87#endif
88    int size_in_bits;
89} PutBitContext;
90
91static inline void init_put_bits(PutBitContext *s, uint8_t *buffer, int buffer_size)
92{
93    if(buffer_size < 0) {
94        buffer_size = 0;
95        buffer = NULL;
96    }
97
98    s->size_in_bits= 8*buffer_size;
99    s->buf = buffer;
100    s->buf_end = s->buf + buffer_size;
101#ifdef ALT_BITSTREAM_WRITER
102    s->index=0;
103    ((uint32_t*)(s->buf))[0]=0;
104//    memset(buffer, 0, buffer_size);
105#else
106    s->buf_ptr = s->buf;
107    s->bit_left=32;
108    s->bit_buf=0;
109#endif
110}
111
112/* return the number of bits output */
113static inline int put_bits_count(PutBitContext *s)
114{
115#ifdef ALT_BITSTREAM_WRITER
116    return s->index;
117#else
118    return (s->buf_ptr - s->buf) * 8 + 32 - s->bit_left;
119#endif
120}
121
122/* pad the end of the output stream with zeros */
123static inline void flush_put_bits(PutBitContext *s)
124{
125#ifdef ALT_BITSTREAM_WRITER
126    align_put_bits(s);
127#else
128#ifndef BITSTREAM_WRITER_LE
129    s->bit_buf<<= s->bit_left;
130#endif
131    while (s->bit_left < 32) {
132        /* XXX: should test end of buffer */
133#ifdef BITSTREAM_WRITER_LE
134        *s->buf_ptr++=s->bit_buf;
135        s->bit_buf>>=8;
136#else
137        *s->buf_ptr++=s->bit_buf >> 24;
138        s->bit_buf<<=8;
139#endif
140        s->bit_left+=8;
141    }
142    s->bit_left=32;
143    s->bit_buf=0;
144#endif
145}
146
147void align_put_bits(PutBitContext *s);
148void ff_put_string(PutBitContext * pbc, const char *s, int put_zero);
149void ff_copy_bits(PutBitContext *pb, const uint8_t *src, int length);
150
151/* bit input */
152/* buffer, buffer_end and size_in_bits must be present and used by every reader */
153typedef struct GetBitContext {
154    const uint8_t *buffer, *buffer_end;
155#ifdef ALT_BITSTREAM_READER
156    int index;
157#elif defined LIBMPEG2_BITSTREAM_READER
158    uint8_t *buffer_ptr;
159    uint32_t cache;
160    int bit_count;
161#elif defined A32_BITSTREAM_READER
162    uint32_t *buffer_ptr;
163    uint32_t cache0;
164    uint32_t cache1;
165    int bit_count;
166#endif
167    int size_in_bits;
168} GetBitContext;
169
170#define VLC_TYPE int16_t
171
172typedef struct VLC {
173    int bits;
174    VLC_TYPE (*table)[2]; ///< code, bits
175    int table_size, table_allocated;
176} VLC;
177
178typedef struct RL_VLC_ELEM {
179    int16_t level;
180    int8_t len;
181    uint8_t run;
182} RL_VLC_ELEM;
183
184#ifndef ALT_BITSTREAM_WRITER
185static inline void put_bits(PutBitContext *s, int n, unsigned int value)
186{
187    unsigned int bit_buf;
188    int bit_left;
189
190    //    printf("put_bits=%d %x\n", n, value);
191    assert(n == 32 || value < (1U << n));
192
193    bit_buf = s->bit_buf;
194    bit_left = s->bit_left;
195
196    //    printf("n=%d value=%x cnt=%d buf=%x\n", n, value, bit_cnt, bit_buf);
197    /* XXX: optimize */
198#ifdef BITSTREAM_WRITER_LE
199    bit_buf |= value << (32 - bit_left);
200    if (n >= bit_left) {
201#if !HAVE_FAST_UNALIGNED
202        if (3 & (intptr_t) s->buf_ptr) {
203            AV_WL32(s->buf_ptr, bit_buf);
204        } else
205#endif
206        *(uint32_t *)s->buf_ptr = le2me_32(bit_buf);
207        s->buf_ptr+=4;
208        bit_buf = (bit_left==32)?0:value >> bit_left;
209        bit_left+=32;
210    }
211    bit_left-=n;
212#else
213    if (n < bit_left) {
214        bit_buf = (bit_buf<<n) | value;
215        bit_left-=n;
216    } else {
217        bit_buf<<=bit_left;
218        bit_buf |= value >> (n - bit_left);
219#if !HAVE_FAST_UNALIGNED
220        if (3 & (intptr_t) s->buf_ptr) {
221            AV_WB32(s->buf_ptr, bit_buf);
222        } else
223#endif
224        *(uint32_t *)s->buf_ptr = be2me_32(bit_buf);
225        //printf("bitbuf = %08x\n", bit_buf);
226        s->buf_ptr+=4;
227        bit_left+=32 - n;
228        bit_buf = value;
229    }
230#endif
231
232    s->bit_buf = bit_buf;
233    s->bit_left = bit_left;
234}
235#endif
236
237
238#ifdef ALT_BITSTREAM_WRITER
239static inline void put_bits(PutBitContext *s, int n, unsigned int value)
240{
241#    ifdef ALIGNED_BITSTREAM_WRITER
242#        if ARCH_X86
243    __asm__ volatile(
244        "movl %0, %%ecx                 \n\t"
245        "xorl %%eax, %%eax              \n\t"
246        "shrdl %%cl, %1, %%eax          \n\t"
247        "shrl %%cl, %1                  \n\t"
248        "movl %0, %%ecx                 \n\t"
249        "shrl $3, %%ecx                 \n\t"
250        "andl $0xFFFFFFFC, %%ecx        \n\t"
251        "bswapl %1                      \n\t"
252        "orl %1, (%2, %%ecx)            \n\t"
253        "bswapl %%eax                   \n\t"
254        "addl %3, %0                    \n\t"
255        "movl %%eax, 4(%2, %%ecx)       \n\t"
256        : "=&r" (s->index), "=&r" (value)
257        : "r" (s->buf), "r" (n), "0" (s->index), "1" (value<<(-n))
258        : "%eax", "%ecx"
259    );
260#        else
261    int index= s->index;
262    uint32_t *ptr= ((uint32_t *)s->buf)+(index>>5);
263
264    value<<= 32-n;
265
266    ptr[0] |= be2me_32(value>>(index&31));
267    ptr[1]  = be2me_32(value<<(32-(index&31)));
268//if(n>24) printf("%d %d\n", n, value);
269    index+= n;
270    s->index= index;
271#        endif
272#    else //ALIGNED_BITSTREAM_WRITER
273#        if ARCH_X86
274    __asm__ volatile(
275        "movl $7, %%ecx                 \n\t"
276        "andl %0, %%ecx                 \n\t"
277        "addl %3, %%ecx                 \n\t"
278        "negl %%ecx                     \n\t"
279        "shll %%cl, %1                  \n\t"
280        "bswapl %1                      \n\t"
281        "movl %0, %%ecx                 \n\t"
282        "shrl $3, %%ecx                 \n\t"
283        "orl %1, (%%ecx, %2)            \n\t"
284        "addl %3, %0                    \n\t"
285        "movl $0, 4(%%ecx, %2)          \n\t"
286        : "=&r" (s->index), "=&r" (value)
287        : "r" (s->buf), "r" (n), "0" (s->index), "1" (value)
288        : "%ecx"
289    );
290#        else
291    int index= s->index;
292    uint32_t *ptr= (uint32_t*)(((uint8_t *)s->buf)+(index>>3));
293
294    ptr[0] |= be2me_32(value<<(32-n-(index&7) ));
295    ptr[1] = 0;
296//if(n>24) printf("%d %d\n", n, value);
297    index+= n;
298    s->index= index;
299#        endif
300#    endif //!ALIGNED_BITSTREAM_WRITER
301}
302#endif
303
304static inline void put_sbits(PutBitContext *pb, int bits, int32_t val)
305{
306    assert(bits >= 0 && bits <= 31);
307
308    put_bits(pb, bits, val & ((1<<bits)-1));
309}
310
311
312static inline uint8_t* pbBufPtr(PutBitContext *s)
313{
314#ifdef ALT_BITSTREAM_WRITER
315        return s->buf + (s->index>>3);
316#else
317        return s->buf_ptr;
318#endif
319}
320
321/**
322 *
323 * PutBitContext must be flushed & aligned to a byte boundary before calling this.
324 */
325static inline void skip_put_bytes(PutBitContext *s, int n){
326        assert((put_bits_count(s)&7)==0);
327#ifdef ALT_BITSTREAM_WRITER
328        FIXME may need some cleaning of the buffer
329        s->index += n<<3;
330#else
331        assert(s->bit_left==32);
332        s->buf_ptr += n;
333#endif
334}
335
336/**
337 * Skips the given number of bits.
338 * Must only be used if the actual values in the bitstream do not matter.
339 */
340static inline void skip_put_bits(PutBitContext *s, int n){
341#ifdef ALT_BITSTREAM_WRITER
342    s->index += n;
343#else
344    s->bit_left -= n;
345    s->buf_ptr-= s->bit_left>>5;
346    s->bit_left &= 31;
347#endif
348}
349
350/**
351 * Changes the end of the buffer.
352 */
353static inline void set_put_bits_buffer_size(PutBitContext *s, int size){
354    s->buf_end= s->buf + size;
355}
356
357/* Bitstream reader API docs:
358name
359    arbitrary name which is used as prefix for the internal variables
360
361gb
362    getbitcontext
363
364OPEN_READER(name, gb)
365    loads gb into local variables
366
367CLOSE_READER(name, gb)
368    stores local vars in gb
369
370UPDATE_CACHE(name, gb)
371    refills the internal cache from the bitstream
372    after this call at least MIN_CACHE_BITS will be available,
373
374GET_CACHE(name, gb)
375    will output the contents of the internal cache, next bit is MSB of 32 or 64 bit (FIXME 64bit)
376
377SHOW_UBITS(name, gb, num)
378    will return the next num bits
379
380SHOW_SBITS(name, gb, num)
381    will return the next num bits and do sign extension
382
383SKIP_BITS(name, gb, num)
384    will skip over the next num bits
385    note, this is equivalent to SKIP_CACHE; SKIP_COUNTER
386
387SKIP_CACHE(name, gb, num)
388    will remove the next num bits from the cache (note SKIP_COUNTER MUST be called before UPDATE_CACHE / CLOSE_READER)
389
390SKIP_COUNTER(name, gb, num)
391    will increment the internal bit counter (see SKIP_CACHE & SKIP_BITS)
392
393LAST_SKIP_CACHE(name, gb, num)
394    will remove the next num bits from the cache if it is needed for UPDATE_CACHE otherwise it will do nothing
395
396LAST_SKIP_BITS(name, gb, num)
397    is equivalent to SKIP_LAST_CACHE; SKIP_COUNTER
398
399for examples see get_bits, show_bits, skip_bits, get_vlc
400*/
401
402#ifdef ALT_BITSTREAM_READER
403#   define MIN_CACHE_BITS 25
404
405#   define OPEN_READER(name, gb)\
406        int name##_index= (gb)->index;\
407        int name##_cache= 0;\
408
409#   define CLOSE_READER(name, gb)\
410        (gb)->index= name##_index;\
411
412# ifdef ALT_BITSTREAM_READER_LE
413#   define UPDATE_CACHE(name, gb)\
414        name##_cache= AV_RL32( ((const uint8_t *)(gb)->buffer)+(name##_index>>3) ) >> (name##_index&0x07);\
415
416#   define SKIP_CACHE(name, gb, num)\
417        name##_cache >>= (num);
418# else
419#   define UPDATE_CACHE(name, gb)\
420        name##_cache= AV_RB32( ((const uint8_t *)(gb)->buffer)+(name##_index>>3) ) << (name##_index&0x07);\
421
422#   define SKIP_CACHE(name, gb, num)\
423        name##_cache <<= (num);
424# endif
425
426// FIXME name?
427#   define SKIP_COUNTER(name, gb, num)\
428        name##_index += (num);\
429
430#   define SKIP_BITS(name, gb, num)\
431        {\
432            SKIP_CACHE(name, gb, num)\
433            SKIP_COUNTER(name, gb, num)\
434        }\
435
436#   define LAST_SKIP_BITS(name, gb, num) SKIP_COUNTER(name, gb, num)
437#   define LAST_SKIP_CACHE(name, gb, num) ;
438
439# ifdef ALT_BITSTREAM_READER_LE
440#   define SHOW_UBITS(name, gb, num)\
441        ((name##_cache) & (NEG_USR32(0xffffffff,num)))
442
443#   define SHOW_SBITS(name, gb, num)\
444        NEG_SSR32((name##_cache)<<(32-(num)), num)
445# else
446#   define SHOW_UBITS(name, gb, num)\
447        NEG_USR32(name##_cache, num)
448
449#   define SHOW_SBITS(name, gb, num)\
450        NEG_SSR32(name##_cache, num)
451# endif
452
453#   define GET_CACHE(name, gb)\
454        ((uint32_t)name##_cache)
455
456static inline int get_bits_count(GetBitContext *s){
457    return s->index;
458}
459
460static inline void skip_bits_long(GetBitContext *s, int n){
461    s->index += n;
462}
463
464#elif defined LIBMPEG2_BITSTREAM_READER
465//libmpeg2 like reader
466
467#   define MIN_CACHE_BITS 17
468
469#   define OPEN_READER(name, gb)\
470        int name##_bit_count=(gb)->bit_count;\
471        int name##_cache= (gb)->cache;\
472        uint8_t * name##_buffer_ptr=(gb)->buffer_ptr;\
473
474#   define CLOSE_READER(name, gb)\
475        (gb)->bit_count= name##_bit_count;\
476        (gb)->cache= name##_cache;\
477        (gb)->buffer_ptr= name##_buffer_ptr;\
478
479#   define UPDATE_CACHE(name, gb)\
480    if(name##_bit_count >= 0){\
481        name##_cache+= AV_RB16(name##_buffer_ptr) << name##_bit_count; \
482        name##_buffer_ptr+=2;\
483        name##_bit_count-= 16;\
484    }\
485
486#   define SKIP_CACHE(name, gb, num)\
487        name##_cache <<= (num);\
488
489#   define SKIP_COUNTER(name, gb, num)\
490        name##_bit_count += (num);\
491
492#   define SKIP_BITS(name, gb, num)\
493        {\
494            SKIP_CACHE(name, gb, num)\
495            SKIP_COUNTER(name, gb, num)\
496        }\
497
498#   define LAST_SKIP_BITS(name, gb, num) SKIP_BITS(name, gb, num)
499#   define LAST_SKIP_CACHE(name, gb, num) SKIP_CACHE(name, gb, num)
500
501#   define SHOW_UBITS(name, gb, num)\
502        NEG_USR32(name##_cache, num)
503
504#   define SHOW_SBITS(name, gb, num)\
505        NEG_SSR32(name##_cache, num)
506
507#   define GET_CACHE(name, gb)\
508        ((uint32_t)name##_cache)
509
510static inline int get_bits_count(GetBitContext *s){
511    return (s->buffer_ptr - s->buffer)*8 - 16 + s->bit_count;
512}
513
514static inline void skip_bits_long(GetBitContext *s, int n){
515    OPEN_READER(re, s)
516    re_bit_count += n;
517    re_buffer_ptr += 2*(re_bit_count>>4);
518    re_bit_count &= 15;
519    re_cache = ((re_buffer_ptr[-2]<<8) + re_buffer_ptr[-1]) << (16+re_bit_count);
520    UPDATE_CACHE(re, s)
521    CLOSE_READER(re, s)
522}
523
524#elif defined A32_BITSTREAM_READER
525
526#   define MIN_CACHE_BITS 32
527
528#   define OPEN_READER(name, gb)\
529        int name##_bit_count=(gb)->bit_count;\
530        uint32_t name##_cache0= (gb)->cache0;\
531        uint32_t name##_cache1= (gb)->cache1;\
532        uint32_t * name##_buffer_ptr=(gb)->buffer_ptr;\
533
534#   define CLOSE_READER(name, gb)\
535        (gb)->bit_count= name##_bit_count;\
536        (gb)->cache0= name##_cache0;\
537        (gb)->cache1= name##_cache1;\
538        (gb)->buffer_ptr= name##_buffer_ptr;\
539
540#   define UPDATE_CACHE(name, gb)\
541    if(name##_bit_count > 0){\
542        const uint32_t next= be2me_32( *name##_buffer_ptr );\
543        name##_cache0 |= NEG_USR32(next,name##_bit_count);\
544        name##_cache1 |= next<<name##_bit_count;\
545        name##_buffer_ptr++;\
546        name##_bit_count-= 32;\
547    }\
548
549#if ARCH_X86
550#   define SKIP_CACHE(name, gb, num)\
551        __asm__(\
552            "shldl %2, %1, %0          \n\t"\
553            "shll %2, %1               \n\t"\
554            : "+r" (name##_cache0), "+r" (name##_cache1)\
555            : "Ic" ((uint8_t)(num))\
556           );
557#else
558#   define SKIP_CACHE(name, gb, num)\
559        name##_cache0 <<= (num);\
560        name##_cache0 |= NEG_USR32(name##_cache1,num);\
561        name##_cache1 <<= (num);
562#endif
563
564#   define SKIP_COUNTER(name, gb, num)\
565        name##_bit_count += (num);\
566
567#   define SKIP_BITS(name, gb, num)\
568        {\
569            SKIP_CACHE(name, gb, num)\
570            SKIP_COUNTER(name, gb, num)\
571        }\
572
573#   define LAST_SKIP_BITS(name, gb, num) SKIP_BITS(name, gb, num)
574#   define LAST_SKIP_CACHE(name, gb, num) SKIP_CACHE(name, gb, num)
575
576#   define SHOW_UBITS(name, gb, num)\
577        NEG_USR32(name##_cache0, num)
578
579#   define SHOW_SBITS(name, gb, num)\
580        NEG_SSR32(name##_cache0, num)
581
582#   define GET_CACHE(name, gb)\
583        (name##_cache0)
584
585static inline int get_bits_count(GetBitContext *s){
586    return ((uint8_t*)s->buffer_ptr - s->buffer)*8 - 32 + s->bit_count;
587}
588
589static inline void skip_bits_long(GetBitContext *s, int n){
590    OPEN_READER(re, s)
591    re_bit_count += n;
592    re_buffer_ptr += re_bit_count>>5;
593    re_bit_count &= 31;
594    re_cache0 = be2me_32( re_buffer_ptr[-1] ) << re_bit_count;
595    re_cache1 = 0;
596    UPDATE_CACHE(re, s)
597    CLOSE_READER(re, s)
598}
599
600#endif
601
602/**
603 * read mpeg1 dc style vlc (sign bit + mantisse with no MSB).
604 * if MSB not set it is negative
605 * @param n length in bits
606 * @author BERO
607 */
608static inline int get_xbits(GetBitContext *s, int n){
609    register int sign;
610    register int32_t cache;
611    OPEN_READER(re, s)
612    UPDATE_CACHE(re, s)
613    cache = GET_CACHE(re,s);
614    sign=(~cache)>>31;
615    LAST_SKIP_BITS(re, s, n)
616    CLOSE_READER(re, s)
617    return (NEG_USR32(sign ^ cache, n) ^ sign) - sign;
618}
619
620static inline int get_sbits(GetBitContext *s, int n){
621    register int tmp;
622    OPEN_READER(re, s)
623    UPDATE_CACHE(re, s)
624    tmp= SHOW_SBITS(re, s, n);
625    LAST_SKIP_BITS(re, s, n)
626    CLOSE_READER(re, s)
627    return tmp;
628}
629
630/**
631 * reads 1-17 bits.
632 * Note, the alt bitstream reader can read up to 25 bits, but the libmpeg2 reader can't
633 */
634static inline unsigned int get_bits(GetBitContext *s, int n){
635    register int tmp;
636    OPEN_READER(re, s)
637    UPDATE_CACHE(re, s)
638    tmp= SHOW_UBITS(re, s, n);
639    LAST_SKIP_BITS(re, s, n)
640    CLOSE_READER(re, s)
641    return tmp;
642}
643
644/**
645 * shows 1-17 bits.
646 * Note, the alt bitstream reader can read up to 25 bits, but the libmpeg2 reader can't
647 */
648static inline unsigned int show_bits(GetBitContext *s, int n){
649    register int tmp;
650    OPEN_READER(re, s)
651    UPDATE_CACHE(re, s)
652    tmp= SHOW_UBITS(re, s, n);
653//    CLOSE_READER(re, s)
654    return tmp;
655}
656
657static inline void skip_bits(GetBitContext *s, int n){
658 //Note gcc seems to optimize this to s->index+=n for the ALT_READER :))
659    OPEN_READER(re, s)
660    UPDATE_CACHE(re, s)
661    LAST_SKIP_BITS(re, s, n)
662    CLOSE_READER(re, s)
663}
664
665static inline unsigned int get_bits1(GetBitContext *s){
666#ifdef ALT_BITSTREAM_READER
667    int index= s->index;
668    uint8_t result= s->buffer[ index>>3 ];
669#ifdef ALT_BITSTREAM_READER_LE
670    result>>= (index&0x07);
671    result&= 1;
672#else
673    result<<= (index&0x07);
674    result>>= 8 - 1;
675#endif
676    index++;
677    s->index= index;
678
679    return result;
680#else
681    return get_bits(s, 1);
682#endif
683}
684
685static inline unsigned int show_bits1(GetBitContext *s){
686    return show_bits(s, 1);
687}
688
689static inline void skip_bits1(GetBitContext *s){
690    skip_bits(s, 1);
691}
692
693/**
694 * reads 0-32 bits.
695 */
696static inline unsigned int get_bits_long(GetBitContext *s, int n){
697    if(n<=17) return get_bits(s, n);
698    else{
699#ifdef ALT_BITSTREAM_READER_LE
700        int ret= get_bits(s, 16);
701        return ret | (get_bits(s, n-16) << 16);
702#else
703        int ret= get_bits(s, 16) << (n-16);
704        return ret | get_bits(s, n-16);
705#endif
706    }
707}
708
709/**
710 * shows 0-32 bits.
711 */
712static inline unsigned int show_bits_long(GetBitContext *s, int n){
713    if(n<=17) return show_bits(s, n);
714    else{
715        GetBitContext gb= *s;
716        int ret= get_bits_long(s, n);
717        *s= gb;
718        return ret;
719    }
720}
721
722static inline int check_marker(GetBitContext *s, const char *msg)
723{
724    int bit= get_bits1(s);
725    if(!bit)
726        av_log(NULL, AV_LOG_INFO, "Marker bit missing %s\n", msg);
727
728    return bit;
729}
730
731/**
732 * init GetBitContext.
733 * @param buffer bitstream buffer, must be FF_INPUT_BUFFER_PADDING_SIZE bytes larger then the actual read bits
734 * because some optimized bitstream readers read 32 or 64 bit at once and could read over the end
735 * @param bit_size the size of the buffer in bits
736 */
737static inline void init_get_bits(GetBitContext *s,
738                   const uint8_t *buffer, int bit_size)
739{
740    int buffer_size= (bit_size+7)>>3;
741    if(buffer_size < 0 || bit_size < 0) {
742        buffer_size = bit_size = 0;
743        buffer = NULL;
744    }
745
746    s->buffer= buffer;
747    s->size_in_bits= bit_size;
748    s->buffer_end= buffer + buffer_size;
749#ifdef ALT_BITSTREAM_READER
750    s->index=0;
751#elif defined LIBMPEG2_BITSTREAM_READER
752    s->buffer_ptr = (uint8_t*)((intptr_t)buffer&(~1));
753    s->bit_count = 16 + 8*((intptr_t)buffer&1);
754    skip_bits_long(s, 0);
755#elif defined A32_BITSTREAM_READER
756    s->buffer_ptr = (uint32_t*)((intptr_t)buffer&(~3));
757    s->bit_count = 32 + 8*((intptr_t)buffer&3);
758    skip_bits_long(s, 0);
759#endif
760}
761
762static inline void align_get_bits(GetBitContext *s)
763{
764    int n= (-get_bits_count(s)) & 7;
765    if(n) skip_bits(s, n);
766}
767
768#define init_vlc(vlc, nb_bits, nb_codes,\
769                 bits, bits_wrap, bits_size,\
770                 codes, codes_wrap, codes_size,\
771                 flags)\
772        init_vlc_sparse(vlc, nb_bits, nb_codes,\
773                 bits, bits_wrap, bits_size,\
774                 codes, codes_wrap, codes_size,\
775                 NULL, 0, 0, flags)
776
777int init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes,
778             const void *bits, int bits_wrap, int bits_size,
779             const void *codes, int codes_wrap, int codes_size,
780             const void *symbols, int symbols_wrap, int symbols_size,
781             int flags);
782#define INIT_VLC_USE_STATIC 1 ///< VERY strongly deprecated and forbidden
783#define INIT_VLC_LE         2
784#define INIT_VLC_USE_NEW_STATIC 4
785void free_vlc(VLC *vlc);
786
787#define INIT_VLC_STATIC(vlc, bits, a,b,c,d,e,f,g, static_size)\
788{\
789    static VLC_TYPE table[static_size][2];\
790    (vlc)->table= table;\
791    (vlc)->table_allocated= static_size;\
792    init_vlc(vlc, bits, a,b,c,d,e,f,g, INIT_VLC_USE_NEW_STATIC);\
793}
794
795
796/**
797 *
798 * if the vlc code is invalid and max_depth=1 than no bits will be removed
799 * if the vlc code is invalid and max_depth>1 than the number of bits removed
800 * is undefined
801 */
802#define GET_VLC(code, name, gb, table, bits, max_depth)\
803{\
804    int n, index, nb_bits;\
805\
806    index= SHOW_UBITS(name, gb, bits);\
807    code = table[index][0];\
808    n    = table[index][1];\
809\
810    if(max_depth > 1 && n < 0){\
811        LAST_SKIP_BITS(name, gb, bits)\
812        UPDATE_CACHE(name, gb)\
813\
814        nb_bits = -n;\
815\
816        index= SHOW_UBITS(name, gb, nb_bits) + code;\
817        code = table[index][0];\
818        n    = table[index][1];\
819        if(max_depth > 2 && n < 0){\
820            LAST_SKIP_BITS(name, gb, nb_bits)\
821            UPDATE_CACHE(name, gb)\
822\
823            nb_bits = -n;\
824\
825            index= SHOW_UBITS(name, gb, nb_bits) + code;\
826            code = table[index][0];\
827            n    = table[index][1];\
828        }\
829    }\
830    SKIP_BITS(name, gb, n)\
831}
832
833#define GET_RL_VLC(level, run, name, gb, table, bits, max_depth, need_update)\
834{\
835    int n, index, nb_bits;\
836\
837    index= SHOW_UBITS(name, gb, bits);\
838    level = table[index].level;\
839    n     = table[index].len;\
840\
841    if(max_depth > 1 && n < 0){\
842        SKIP_BITS(name, gb, bits)\
843        if(need_update){\
844            UPDATE_CACHE(name, gb)\
845        }\
846\
847        nb_bits = -n;\
848\
849        index= SHOW_UBITS(name, gb, nb_bits) + level;\
850        level = table[index].level;\
851        n     = table[index].len;\
852    }\
853    run= table[index].run;\
854    SKIP_BITS(name, gb, n)\
855}
856
857
858/**
859 * parses a vlc code, faster then get_vlc()
860 * @param bits is the number of bits which will be read at once, must be
861 *             identical to nb_bits in init_vlc()
862 * @param max_depth is the number of times bits bits must be read to completely
863 *                  read the longest vlc code
864 *                  = (max_vlc_length + bits - 1) / bits
865 */
866static av_always_inline int get_vlc2(GetBitContext *s, VLC_TYPE (*table)[2],
867                                  int bits, int max_depth)
868{
869    int code;
870
871    OPEN_READER(re, s)
872    UPDATE_CACHE(re, s)
873
874    GET_VLC(code, re, s, table, bits, max_depth)
875
876    CLOSE_READER(re, s)
877    return code;
878}
879
880//#define TRACE
881
882#ifdef TRACE
883static inline void print_bin(int bits, int n){
884    int i;
885
886    for(i=n-1; i>=0; i--){
887        av_log(NULL, AV_LOG_DEBUG, "%d", (bits>>i)&1);
888    }
889    for(i=n; i<24; i++)
890        av_log(NULL, AV_LOG_DEBUG, " ");
891}
892
893static inline int get_bits_trace(GetBitContext *s, int n, char *file, const char *func, int line){
894    int r= get_bits(s, n);
895
896    print_bin(r, n);
897    av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d bit @%5d in %s %s:%d\n", r, n, r, get_bits_count(s)-n, file, func, line);
898    return r;
899}
900static inline int get_vlc_trace(GetBitContext *s, VLC_TYPE (*table)[2], int bits, int max_depth, char *file, const char *func, int line){
901    int show= show_bits(s, 24);
902    int pos= get_bits_count(s);
903    int r= get_vlc2(s, table, bits, max_depth);
904    int len= get_bits_count(s) - pos;
905    int bits2= show>>(24-len);
906
907    print_bin(bits2, len);
908
909    av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d vlc @%5d in %s %s:%d\n", bits2, len, r, pos, file, func, line);
910    return r;
911}
912static inline int get_xbits_trace(GetBitContext *s, int n, char *file, const char *func, int line){
913    int show= show_bits(s, n);
914    int r= get_xbits(s, n);
915
916    print_bin(show, n);
917    av_log(NULL, AV_LOG_DEBUG, "%5d %2d %3d xbt @%5d in %s %s:%d\n", show, n, r, get_bits_count(s)-n, file, func, line);
918    return r;
919}
920
921#define get_bits(s, n)  get_bits_trace(s, n, __FILE__, __PRETTY_FUNCTION__, __LINE__)
922#define get_bits1(s)    get_bits_trace(s, 1, __FILE__, __PRETTY_FUNCTION__, __LINE__)
923#define get_xbits(s, n) get_xbits_trace(s, n, __FILE__, __PRETTY_FUNCTION__, __LINE__)
924#define get_vlc(s, vlc)            get_vlc_trace(s, (vlc)->table, (vlc)->bits, 3, __FILE__, __PRETTY_FUNCTION__, __LINE__)
925#define get_vlc2(s, tab, bits, max) get_vlc_trace(s, tab, bits, max, __FILE__, __PRETTY_FUNCTION__, __LINE__)
926
927#define tprintf(p, ...) av_log(p, AV_LOG_DEBUG, __VA_ARGS__)
928
929#else //TRACE
930#define tprintf(p, ...) {}
931#endif
932
933static inline int decode012(GetBitContext *gb){
934    int n;
935    n = get_bits1(gb);
936    if (n == 0)
937        return 0;
938    else
939        return get_bits1(gb) + 1;
940}
941
942static inline int decode210(GetBitContext *gb){
943    if (get_bits1(gb))
944        return 0;
945    else
946        return 2 - get_bits1(gb);
947}
948
949#endif /* AVCODEC_BITSTREAM_H */
950