]> git.sesse.net Git - ffmpeg/blob - libavcodec/common.h
* removing casualties of battle of the wits and English language
[ffmpeg] / libavcodec / common.h
1 /**
2  * @file common.h
3  * common internal api header.
4  */
5
6 #ifndef COMMON_H
7 #define COMMON_H
8
9 #if defined(WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
10 #    define CONFIG_WIN32
11 #endif
12
13 //#define ALT_BITSTREAM_WRITER
14 //#define ALIGNED_BITSTREAM_WRITER
15
16 #define ALT_BITSTREAM_READER
17 //#define LIBMPEG2_BITSTREAM_READER
18 //#define A32_BITSTREAM_READER
19 #define LIBMPEG2_BITSTREAM_READER_HACK //add BERO
20
21 #ifndef M_PI
22 #define M_PI    3.14159265358979323846
23 #endif
24
25 #ifdef HAVE_AV_CONFIG_H
26 /* only include the following when compiling package */
27 #    include "config.h"
28
29 #    include <stdlib.h>
30 #    include <stdio.h>
31 #    include <string.h>
32 #    include <ctype.h>
33 #    ifndef __BEOS__
34 #        include <errno.h>
35 #    else
36 #        include "berrno.h"
37 #    endif
38 #    include <math.h>
39
40 #    ifndef ENODATA
41 #        define ENODATA  61
42 #    endif
43
44 #include <stddef.h>
45 #ifndef offsetof
46 # define offsetof(T,F) ((unsigned int)((char *)&((T *)0)->F))
47 #endif
48
49 #define AVOPTION_CODEC_BOOL(name, help, field) \
50     { name, help, offsetof(AVCodecContext, field), FF_OPT_TYPE_BOOL }
51 #define AVOPTION_CODEC_DOUBLE(name, help, field, minv, maxv, defval) \
52     { name, help, offsetof(AVCodecContext, field), FF_OPT_TYPE_DOUBLE, minv, maxv, defval }
53 #define AVOPTION_CODEC_FLAG(name, help, field, flag, defval) \
54     { name, help, offsetof(AVCodecContext, field), FF_OPT_TYPE_FLAG, flag, 0, defval }
55 #define AVOPTION_CODEC_INT(name, help, field, minv, maxv, defval) \
56     { name, help, offsetof(AVCodecContext, field), FF_OPT_TYPE_INT, minv, maxv, defval }
57 #define AVOPTION_CODEC_STRING(name, help, field, str, val) \
58     { name, help, offsetof(AVCodecContext, field), FF_OPT_TYPE_STRING, .defval = val, .defstr = str }
59 #define AVOPTION_CODEC_RCOVERRIDE(name, help, field) \
60     { name, help, offsetof(AVCodecContext, field), FF_OPT_TYPE_RCOVERRIDE, .defval = 0, .defstr = NULL }
61 #define AVOPTION_SUB(ptr) { .name = NULL, .help = (const char*)ptr }
62 #define AVOPTION_END() AVOPTION_SUB(NULL)
63
64 struct AVOption;
65 #ifdef HAVE_MMX
66 extern const struct AVOption avoptions_common[3 + 5];
67 #else
68 extern const struct AVOption avoptions_common[3];
69 #endif
70 extern const struct AVOption avoptions_workaround_bug[11];
71
72 #endif /* HAVE_AV_CONFIG_H */
73
74 /* Suppress restrict if it was not defined in config.h.  */
75 #ifndef restrict
76 #    define restrict
77 #endif
78
79 #if defined(__GNUC__) && (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ > 0)
80 #    define always_inline __attribute__((always_inline)) inline
81 #else
82 #    define always_inline inline
83 #endif
84
85 #if defined(__GNUC__) && (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ > 0)
86 #    define attribute_used __attribute__((used))
87 #else
88 #    define attribute_used
89 #endif
90
91 #ifndef EMULATE_INTTYPES
92 #   include <inttypes.h>
93 #else
94     typedef signed char  int8_t;
95     typedef signed short int16_t;
96     typedef signed int   int32_t;
97     typedef unsigned char  uint8_t;
98     typedef unsigned short uint16_t;
99     typedef unsigned int   uint32_t;
100
101 #   ifdef CONFIG_WIN32
102         typedef signed __int64   int64_t;
103         typedef unsigned __int64 uint64_t;
104 #   else /* other OS */
105         typedef signed long long   int64_t;
106         typedef unsigned long long uint64_t;
107 #   endif /* other OS */
108 #endif /* HAVE_INTTYPES_H */
109
110 #ifndef INT64_MAX
111 #define INT64_MAX int64_t_C(9223372036854775807)
112 #endif
113
114 #ifdef EMULATE_FAST_INT
115 /* note that we don't emulate 64bit ints */
116 typedef signed char int_fast8_t;
117 typedef signed int  int_fast16_t;
118 typedef signed int  int_fast32_t;
119 typedef unsigned char uint_fast8_t;
120 typedef unsigned int  uint_fast16_t;
121 typedef unsigned int  uint_fast32_t;
122 #endif
123
124 #if defined(CONFIG_OS2) || defined(CONFIG_SUNOS)
125 static inline float floorf(float f) { 
126     return floor(f); 
127 }
128 #endif
129
130 #ifdef CONFIG_WIN32
131
132 /* windows */
133
134 #    ifndef __MINGW32__
135 #        define int64_t_C(c)     (c ## i64)
136 #        define uint64_t_C(c)    (c ## i64)
137
138 #    ifdef HAVE_AV_CONFIG_H
139 #            define inline __inline
140 #    endif
141
142 #    else
143 #        define int64_t_C(c)     (c ## LL)
144 #        define uint64_t_C(c)    (c ## ULL)
145 #    endif /* __MINGW32__ */
146
147 #    ifdef HAVE_AV_CONFIG_H
148 #        ifdef _DEBUG
149 #            define DEBUG
150 #        endif
151
152 #        define snprintf _snprintf
153 #        define vsnprintf _vsnprintf
154 #    endif
155
156 /* CONFIG_WIN32 end */
157 #elif defined (CONFIG_OS2)
158 /* OS/2 EMX */
159
160 #ifndef int64_t_C
161 #define int64_t_C(c)     (c ## LL)
162 #define uint64_t_C(c)    (c ## ULL)
163 #endif
164
165 #ifdef HAVE_AV_CONFIG_H
166
167 #ifdef USE_FASTMEMCPY
168 #include "fastmemcpy.h"
169 #endif
170
171 #include <float.h>
172
173 #endif /* HAVE_AV_CONFIG_H */
174
175 /* CONFIG_OS2 end */
176 #else
177
178 /* unix */
179
180 #ifndef int64_t_C
181 #define int64_t_C(c)     (c ## LL)
182 #define uint64_t_C(c)    (c ## ULL)
183 #endif
184
185 #ifdef HAVE_AV_CONFIG_H
186
187 #        ifdef USE_FASTMEMCPY
188 #            include "fastmemcpy.h"
189 #        endif
190 #    endif /* HAVE_AV_CONFIG_H */
191
192 #endif /* !CONFIG_WIN32 && !CONFIG_OS2 */
193
194 #ifdef HAVE_AV_CONFIG_H
195
196 #    include "bswap.h"
197
198 #    if defined(__MINGW32__) || defined(__CYGWIN__) || \
199         defined(__OS2__) || (defined (__OpenBSD__) && !defined(__ELF__))
200 #        define MANGLE(a) "_" #a
201 #    else
202 #        define MANGLE(a) #a
203 #    endif
204
205 /* debug stuff */
206
207 #    ifndef DEBUG
208 #        define NDEBUG
209 #    endif
210 #    include <assert.h>
211
212 /* dprintf macros */
213 #    if defined(CONFIG_WIN32) && !defined(__MINGW32__)
214
215 inline void dprintf(const char* fmt,...) {}
216
217 #    else
218
219 #        ifdef DEBUG
220 #            define dprintf(fmt,...) printf(fmt, __VA_ARGS__)
221 #        else
222 #            define dprintf(fmt,...)
223 #        endif
224
225 #    endif /* !CONFIG_WIN32 */
226
227 #    define av_abort()      do { av_log(NULL, AV_LOG_ERROR, "Abort at %s:%d\n", __FILE__, __LINE__); abort(); } while (0)
228
229 //rounded divison & shift
230 #define RSHIFT(a,b) ((a) > 0 ? ((a) + (1<<((b)-1)))>>(b) : ((a) + (1<<((b)-1))-1)>>(b))
231 /* assume b>0 */
232 #define ROUNDED_DIV(a,b) (((a)>0 ? (a) + ((b)>>1) : (a) - ((b)>>1))/(b))
233 #define ABS(a) ((a) >= 0 ? (a) : (-(a)))
234
235 #define FFMAX(a,b) ((a) > (b) ? (a) : (b))
236 #define FFMIN(a,b) ((a) > (b) ? (b) : (a))
237
238 extern const uint32_t inverse[256];
239
240 #ifdef ARCH_X86
241 #    define FASTDIV(a,b) \
242     ({\
243         int ret,dmy;\
244         asm volatile(\
245             "mull %3"\
246             :"=d"(ret),"=a"(dmy)\
247             :"1"(a),"g"(inverse[b])\
248             );\
249         ret;\
250     })
251 #elif defined(CONFIG_FASTDIV)
252 #    define FASTDIV(a,b)   ((uint32_t)((((uint64_t)a)*inverse[b])>>32))
253 #else
254 #    define FASTDIV(a,b)   ((a)/(b))
255 #endif
256  
257 #ifdef ARCH_X86
258 // avoid +32 for shift optimization (gcc should do that ...)
259 static inline  int32_t NEG_SSR32( int32_t a, int8_t s){
260     asm ("sarl %1, %0\n\t"
261          : "+r" (a)
262          : "ic" ((uint8_t)(-s))
263     );
264     return a;
265 }
266 static inline uint32_t NEG_USR32(uint32_t a, int8_t s){
267     asm ("shrl %1, %0\n\t"
268          : "+r" (a)
269          : "ic" ((uint8_t)(-s))
270     );
271     return a;
272 }
273 #else
274 #    define NEG_SSR32(a,s) ((( int32_t)(a))>>(32-(s)))
275 #    define NEG_USR32(a,s) (((uint32_t)(a))>>(32-(s)))
276 #endif
277
278 /* bit output */
279
280 struct PutBitContext;
281
282 typedef void (*WriteDataFunc)(void *, uint8_t *, int);
283
284 /* buf and buf_end must be present and used by every alternative writer. */
285 typedef struct PutBitContext {
286 #ifdef ALT_BITSTREAM_WRITER
287     uint8_t *buf, *buf_end;
288     int index;
289 #else
290     uint32_t bit_buf;
291     int bit_left;
292     uint8_t *buf, *buf_ptr, *buf_end;
293 #endif
294 } PutBitContext;
295
296 static inline void init_put_bits(PutBitContext *s, uint8_t *buffer, int buffer_size)
297 {
298     s->buf = buffer;
299     s->buf_end = s->buf + buffer_size;
300 #ifdef ALT_BITSTREAM_WRITER
301     s->index=0;
302     ((uint32_t*)(s->buf))[0]=0;
303 //    memset(buffer, 0, buffer_size);
304 #else
305     s->buf_ptr = s->buf;
306     s->bit_left=32;
307     s->bit_buf=0;
308 #endif
309 }
310
311 /* return the number of bits output */
312 static inline int put_bits_count(PutBitContext *s)
313 {
314 #ifdef ALT_BITSTREAM_WRITER
315     return s->index;
316 #else
317     return (s->buf_ptr - s->buf) * 8 + 32 - s->bit_left;
318 #endif
319 }
320
321 /* pad the end of the output stream with zeros */
322 static inline void flush_put_bits(PutBitContext *s)
323 {
324 #ifdef ALT_BITSTREAM_WRITER
325     align_put_bits(s);
326 #else
327     s->bit_buf<<= s->bit_left;
328     while (s->bit_left < 32) {
329         /* XXX: should test end of buffer */
330         *s->buf_ptr++=s->bit_buf >> 24;
331         s->bit_buf<<=8;
332         s->bit_left+=8;
333     }
334     s->bit_left=32;
335     s->bit_buf=0;
336 #endif
337 }
338
339 void align_put_bits(PutBitContext *s);
340 void put_string(PutBitContext * pbc, char *s, int put_zero);
341
342 /* bit input */
343 /* buffer, buffer_end and size_in_bits must be present and used by every reader */
344 typedef struct GetBitContext {
345     const uint8_t *buffer, *buffer_end;
346 #ifdef ALT_BITSTREAM_READER
347     int index;
348 #elif defined LIBMPEG2_BITSTREAM_READER
349     uint8_t *buffer_ptr;
350     uint32_t cache;
351     int bit_count;
352 #elif defined A32_BITSTREAM_READER
353     uint32_t *buffer_ptr;
354     uint32_t cache0;
355     uint32_t cache1;
356     int bit_count;
357 #endif
358     int size_in_bits;
359 } GetBitContext;
360
361 #define VLC_TYPE int16_t
362
363 typedef struct VLC {
364     int bits;
365     VLC_TYPE (*table)[2]; ///< code, bits
366     int table_size, table_allocated;
367 } VLC;
368
369 typedef struct RL_VLC_ELEM {
370     int16_t level;
371     int8_t len;
372     uint8_t run;
373 } RL_VLC_ELEM;
374
375 #ifdef ARCH_SPARC64
376 #define UNALIGNED_STORES_ARE_BAD
377 #endif
378
379 /* used to avoid missaligned exceptions on some archs (alpha, ...) */
380 #ifdef ARCH_X86
381 #    define unaligned32(a) (*(uint32_t*)(a))
382 #else
383 #    ifdef __GNUC__
384 static inline uint32_t unaligned32(const void *v) {
385     struct Unaligned {
386         uint32_t i;
387     } __attribute__((packed));
388
389     return ((const struct Unaligned *) v)->i;
390 }
391 #    elif defined(__DECC)
392 static inline uint32_t unaligned32(const void *v) {
393     return *(const __unaligned uint32_t *) v;
394 }
395 #    else
396 static inline uint32_t unaligned32(const void *v) {
397     return *(const uint32_t *) v;
398 }
399 #    endif
400 #endif //!ARCH_X86
401
402 #ifndef ALT_BITSTREAM_WRITER
403 static inline void put_bits(PutBitContext *s, int n, unsigned int value)
404 {
405     unsigned int bit_buf;
406     int bit_left;
407
408 #ifdef STATS
409     st_out_bit_counts[st_current_index] += n;
410 #endif
411     //    printf("put_bits=%d %x\n", n, value);
412     assert(n == 32 || value < (1U << n));
413     
414     bit_buf = s->bit_buf;
415     bit_left = s->bit_left;
416
417     //    printf("n=%d value=%x cnt=%d buf=%x\n", n, value, bit_cnt, bit_buf);
418     /* XXX: optimize */
419     if (n < bit_left) {
420         bit_buf = (bit_buf<<n) | value;
421         bit_left-=n;
422     } else {
423         bit_buf<<=bit_left;
424         bit_buf |= value >> (n - bit_left);
425 #ifdef UNALIGNED_STORES_ARE_BAD
426         if (3 & (int) s->buf_ptr) {
427             s->buf_ptr[0] = bit_buf >> 24;
428             s->buf_ptr[1] = bit_buf >> 16;
429             s->buf_ptr[2] = bit_buf >>  8;
430             s->buf_ptr[3] = bit_buf      ;
431         } else
432 #endif
433         *(uint32_t *)s->buf_ptr = be2me_32(bit_buf);
434         //printf("bitbuf = %08x\n", bit_buf);
435         s->buf_ptr+=4;
436         bit_left+=32 - n;
437         bit_buf = value;
438     }
439
440     s->bit_buf = bit_buf;
441     s->bit_left = bit_left;
442 }
443 #endif
444
445
446 #ifdef ALT_BITSTREAM_WRITER
447 static inline void put_bits(PutBitContext *s, int n, unsigned int value)
448 {
449 #    ifdef ALIGNED_BITSTREAM_WRITER
450 #        ifdef ARCH_X86
451     asm volatile(
452         "movl %0, %%ecx                 \n\t"
453         "xorl %%eax, %%eax              \n\t"
454         "shrdl %%cl, %1, %%eax          \n\t"
455         "shrl %%cl, %1                  \n\t"
456         "movl %0, %%ecx                 \n\t"
457         "shrl $3, %%ecx                 \n\t"
458         "andl $0xFFFFFFFC, %%ecx        \n\t"
459         "bswapl %1                      \n\t"
460         "orl %1, (%2, %%ecx)            \n\t"
461         "bswapl %%eax                   \n\t"
462         "addl %3, %0                    \n\t"
463         "movl %%eax, 4(%2, %%ecx)       \n\t"
464         : "=&r" (s->index), "=&r" (value)
465         : "r" (s->buf), "r" (n), "0" (s->index), "1" (value<<(-n))
466         : "%eax", "%ecx"
467     );
468 #        else
469     int index= s->index;
470     uint32_t *ptr= ((uint32_t *)s->buf)+(index>>5);
471     
472     value<<= 32-n; 
473     
474     ptr[0] |= be2me_32(value>>(index&31));
475     ptr[1]  = be2me_32(value<<(32-(index&31)));
476 //if(n>24) printf("%d %d\n", n, value);
477     index+= n;
478     s->index= index;
479 #        endif
480 #    else //ALIGNED_BITSTREAM_WRITER
481 #        ifdef ARCH_X86
482     asm volatile(
483         "movl $7, %%ecx                 \n\t"
484         "andl %0, %%ecx                 \n\t"
485         "addl %3, %%ecx                 \n\t"
486         "negl %%ecx                     \n\t"
487         "shll %%cl, %1                  \n\t"
488         "bswapl %1                      \n\t"
489         "movl %0, %%ecx                 \n\t"
490         "shrl $3, %%ecx                 \n\t"
491         "orl %1, (%%ecx, %2)            \n\t"
492         "addl %3, %0                    \n\t"
493         "movl $0, 4(%%ecx, %2)          \n\t"
494         : "=&r" (s->index), "=&r" (value)
495         : "r" (s->buf), "r" (n), "0" (s->index), "1" (value)
496         : "%ecx"
497     );
498 #        else
499     int index= s->index;
500     uint32_t *ptr= (uint32_t*)(((uint8_t *)s->buf)+(index>>3));
501     
502     ptr[0] |= be2me_32(value<<(32-n-(index&7) ));
503     ptr[1] = 0;
504 //if(n>24) printf("%d %d\n", n, value);
505     index+= n;
506     s->index= index;
507 #        endif
508 #    endif //!ALIGNED_BITSTREAM_WRITER
509 }
510 #endif
511
512
513 static inline uint8_t* pbBufPtr(PutBitContext *s)
514 {
515 #ifdef ALT_BITSTREAM_WRITER
516         return s->buf + (s->index>>3);
517 #else
518         return s->buf_ptr;
519 #endif
520 }
521
522 /**
523  *
524  * PutBitContext must be flushed & aligned to a byte boundary before calling this.
525  */
526 static inline void skip_put_bytes(PutBitContext *s, int n){
527         assert((put_bits_count(s)&7)==0);
528 #ifdef ALT_BITSTREAM_WRITER
529         FIXME may need some cleaning of the buffer
530         s->index += n<<3;
531 #else
532         assert(s->bit_left==32);
533         s->buf_ptr += n;
534 #endif    
535 }
536
537 /**
538  * Changes the end of the buffer.
539  */
540 static inline void set_put_bits_buffer_size(PutBitContext *s, int size){
541     s->buf_end= s->buf + size;
542 }
543
544 /* Bitstream reader API docs:
545 name
546     abritary name which is used as prefix for the internal variables
547
548 gb
549     getbitcontext
550
551 OPEN_READER(name, gb)
552     loads gb into local variables
553
554 CLOSE_READER(name, gb)
555     stores local vars in gb
556
557 UPDATE_CACHE(name, gb)
558     refills the internal cache from the bitstream
559     after this call at least MIN_CACHE_BITS will be available,
560
561 GET_CACHE(name, gb)
562     will output the contents of the internal cache, next bit is MSB of 32 or 64 bit (FIXME 64bit)
563
564 SHOW_UBITS(name, gb, num)
565     will return the nest num bits
566
567 SHOW_SBITS(name, gb, num)
568     will return the nest num bits and do sign extension
569
570 SKIP_BITS(name, gb, num)
571     will skip over the next num bits
572     note, this is equinvalent to SKIP_CACHE; SKIP_COUNTER
573
574 SKIP_CACHE(name, gb, num)
575     will remove the next num bits from the cache (note SKIP_COUNTER MUST be called before UPDATE_CACHE / CLOSE_READER)
576
577 SKIP_COUNTER(name, gb, num)
578     will increment the internal bit counter (see SKIP_CACHE & SKIP_BITS)
579
580 LAST_SKIP_CACHE(name, gb, num)
581     will remove the next num bits from the cache if it is needed for UPDATE_CACHE otherwise it will do nothing
582
583 LAST_SKIP_BITS(name, gb, num)
584     is equinvalent to SKIP_LAST_CACHE; SKIP_COUNTER
585
586 for examples see get_bits, show_bits, skip_bits, get_vlc
587 */
588
589 static inline int unaligned32_be(const void *v)
590 {
591 #ifdef CONFIG_ALIGN
592         const uint8_t *p=v;
593         return (((p[0]<<8) | p[1])<<16) | (p[2]<<8) | (p[3]);
594 #else
595         return be2me_32( unaligned32(v)); //original
596 #endif
597 }
598
599 #ifdef ALT_BITSTREAM_READER
600 #   define MIN_CACHE_BITS 25
601
602 #   define OPEN_READER(name, gb)\
603         int name##_index= (gb)->index;\
604         int name##_cache= 0;\
605
606 #   define CLOSE_READER(name, gb)\
607         (gb)->index= name##_index;\
608
609 #   define UPDATE_CACHE(name, gb)\
610         name##_cache= unaligned32_be( ((uint8_t *)(gb)->buffer)+(name##_index>>3) ) << (name##_index&0x07);\
611
612 #   define SKIP_CACHE(name, gb, num)\
613         name##_cache <<= (num);\
614
615 // FIXME name?
616 #   define SKIP_COUNTER(name, gb, num)\
617         name##_index += (num);\
618
619 #   define SKIP_BITS(name, gb, num)\
620         {\
621             SKIP_CACHE(name, gb, num)\
622             SKIP_COUNTER(name, gb, num)\
623         }\
624
625 #   define LAST_SKIP_BITS(name, gb, num) SKIP_COUNTER(name, gb, num)
626 #   define LAST_SKIP_CACHE(name, gb, num) ;
627
628 #   define SHOW_UBITS(name, gb, num)\
629         NEG_USR32(name##_cache, num)
630
631 #   define SHOW_SBITS(name, gb, num)\
632         NEG_SSR32(name##_cache, num)
633
634 #   define GET_CACHE(name, gb)\
635         ((uint32_t)name##_cache)
636
637 static inline int get_bits_count(GetBitContext *s){
638     return s->index;
639 }
640 #elif defined LIBMPEG2_BITSTREAM_READER
641 //libmpeg2 like reader
642
643 #   define MIN_CACHE_BITS 17
644
645 #   define OPEN_READER(name, gb)\
646         int name##_bit_count=(gb)->bit_count;\
647         int name##_cache= (gb)->cache;\
648         uint8_t * name##_buffer_ptr=(gb)->buffer_ptr;\
649
650 #   define CLOSE_READER(name, gb)\
651         (gb)->bit_count= name##_bit_count;\
652         (gb)->cache= name##_cache;\
653         (gb)->buffer_ptr= name##_buffer_ptr;\
654
655 #ifdef LIBMPEG2_BITSTREAM_READER_HACK
656
657 #   define UPDATE_CACHE(name, gb)\
658     if(name##_bit_count >= 0){\
659         name##_cache+= (int)be2me_16(*(uint16_t*)name##_buffer_ptr) << name##_bit_count;\
660         ((uint16_t*)name##_buffer_ptr)++;\
661         name##_bit_count-= 16;\
662     }\
663
664 #else
665
666 #   define UPDATE_CACHE(name, gb)\
667     if(name##_bit_count >= 0){\
668         name##_cache+= ((name##_buffer_ptr[0]<<8) + name##_buffer_ptr[1]) << name##_bit_count;\
669         name##_buffer_ptr+=2;\
670         name##_bit_count-= 16;\
671     }\
672
673 #endif
674
675 #   define SKIP_CACHE(name, gb, num)\
676         name##_cache <<= (num);\
677
678 #   define SKIP_COUNTER(name, gb, num)\
679         name##_bit_count += (num);\
680
681 #   define SKIP_BITS(name, gb, num)\
682         {\
683             SKIP_CACHE(name, gb, num)\
684             SKIP_COUNTER(name, gb, num)\
685         }\
686
687 #   define LAST_SKIP_BITS(name, gb, num) SKIP_BITS(name, gb, num)
688 #   define LAST_SKIP_CACHE(name, gb, num) SKIP_CACHE(name, gb, num)
689
690 #   define SHOW_UBITS(name, gb, num)\
691         NEG_USR32(name##_cache, num)
692
693 #   define SHOW_SBITS(name, gb, num)\
694         NEG_SSR32(name##_cache, num)
695
696 #   define GET_CACHE(name, gb)\
697         ((uint32_t)name##_cache)
698
699 static inline int get_bits_count(GetBitContext *s){
700     return (s->buffer_ptr - s->buffer)*8 - 16 + s->bit_count;
701 }
702
703 #elif defined A32_BITSTREAM_READER
704
705 #   define MIN_CACHE_BITS 32
706
707 #   define OPEN_READER(name, gb)\
708         int name##_bit_count=(gb)->bit_count;\
709         uint32_t name##_cache0= (gb)->cache0;\
710         uint32_t name##_cache1= (gb)->cache1;\
711         uint32_t * name##_buffer_ptr=(gb)->buffer_ptr;\
712
713 #   define CLOSE_READER(name, gb)\
714         (gb)->bit_count= name##_bit_count;\
715         (gb)->cache0= name##_cache0;\
716         (gb)->cache1= name##_cache1;\
717         (gb)->buffer_ptr= name##_buffer_ptr;\
718
719 #   define UPDATE_CACHE(name, gb)\
720     if(name##_bit_count > 0){\
721         const uint32_t next= be2me_32( *name##_buffer_ptr );\
722         name##_cache0 |= NEG_USR32(next,name##_bit_count);\
723         name##_cache1 |= next<<name##_bit_count;\
724         name##_buffer_ptr++;\
725         name##_bit_count-= 32;\
726     }\
727
728 #ifdef ARCH_X86
729 #   define SKIP_CACHE(name, gb, num)\
730         asm(\
731             "shldl %2, %1, %0           \n\t"\
732             "shll %2, %1                \n\t"\
733             : "+r" (name##_cache0), "+r" (name##_cache1)\
734             : "Ic" ((uint8_t)num)\
735            );
736 #else
737 #   define SKIP_CACHE(name, gb, num)\
738         name##_cache0 <<= (num);\
739         name##_cache0 |= NEG_USR32(name##_cache1,num);\
740         name##_cache1 <<= (num);
741 #endif
742
743 #   define SKIP_COUNTER(name, gb, num)\
744         name##_bit_count += (num);\
745
746 #   define SKIP_BITS(name, gb, num)\
747         {\
748             SKIP_CACHE(name, gb, num)\
749             SKIP_COUNTER(name, gb, num)\
750         }\
751
752 #   define LAST_SKIP_BITS(name, gb, num) SKIP_BITS(name, gb, num)
753 #   define LAST_SKIP_CACHE(name, gb, num) SKIP_CACHE(name, gb, num)
754
755 #   define SHOW_UBITS(name, gb, num)\
756         NEG_USR32(name##_cache0, num)
757
758 #   define SHOW_SBITS(name, gb, num)\
759         NEG_SSR32(name##_cache0, num)
760
761 #   define GET_CACHE(name, gb)\
762         (name##_cache0)
763
764 static inline int get_bits_count(GetBitContext *s){
765     return ((uint8_t*)s->buffer_ptr - s->buffer)*8 - 32 + s->bit_count;
766 }
767
768 #endif
769
770 /**
771  * read mpeg1 dc style vlc (sign bit + mantisse with no MSB).
772  * if MSB not set it is negative 
773  * @param n length in bits
774  * @author BERO  
775  */
776 static inline int get_xbits(GetBitContext *s, int n){
777     register int tmp;
778     register int32_t cache;
779     OPEN_READER(re, s)
780     UPDATE_CACHE(re, s)
781     cache = GET_CACHE(re,s);
782     if ((int32_t)cache<0) { //MSB=1
783         tmp = NEG_USR32(cache,n);
784     } else {
785     //   tmp = (-1<<n) | NEG_USR32(cache,n) + 1; mpeg12.c algo
786     //   tmp = - (NEG_USR32(cache,n) ^ ((1 << n) - 1)); h263.c algo
787         tmp = - NEG_USR32(~cache,n);
788     }
789     LAST_SKIP_BITS(re, s, n)
790     CLOSE_READER(re, s)
791     return tmp;
792 }
793
794 static inline int get_sbits(GetBitContext *s, int n){
795     register int tmp;
796     OPEN_READER(re, s)
797     UPDATE_CACHE(re, s)
798     tmp= SHOW_SBITS(re, s, n);
799     LAST_SKIP_BITS(re, s, n)
800     CLOSE_READER(re, s)
801     return tmp;
802 }
803
804 /**
805  * reads 0-17 bits.
806  * Note, the alt bitstream reader can read upto 25 bits, but the libmpeg2 reader cant
807  */
808 static inline unsigned int get_bits(GetBitContext *s, int n){
809     register int tmp;
810     OPEN_READER(re, s)
811     UPDATE_CACHE(re, s)
812     tmp= SHOW_UBITS(re, s, n);
813     LAST_SKIP_BITS(re, s, n)
814     CLOSE_READER(re, s)
815     return tmp;
816 }
817
818 unsigned int get_bits_long(GetBitContext *s, int n);
819
820 /**
821  * shows 0-17 bits.
822  * Note, the alt bitstream reader can read upto 25 bits, but the libmpeg2 reader cant
823  */
824 static inline unsigned int show_bits(GetBitContext *s, int n){
825     register int tmp;
826     OPEN_READER(re, s)
827     UPDATE_CACHE(re, s)
828     tmp= SHOW_UBITS(re, s, n);
829 //    CLOSE_READER(re, s)
830     return tmp;
831 }
832
833 unsigned int show_bits_long(GetBitContext *s, int n);
834
835 static inline void skip_bits(GetBitContext *s, int n){
836  //Note gcc seems to optimize this to s->index+=n for the ALT_READER :))
837     OPEN_READER(re, s)
838     UPDATE_CACHE(re, s)
839     LAST_SKIP_BITS(re, s, n)
840     CLOSE_READER(re, s)
841 }
842
843 static inline unsigned int get_bits1(GetBitContext *s){
844 #ifdef ALT_BITSTREAM_READER
845     int index= s->index;
846     uint8_t result= s->buffer[ index>>3 ];
847     result<<= (index&0x07);
848     result>>= 8 - 1;
849     index++;
850     s->index= index;
851
852     return result;
853 #else
854     return get_bits(s, 1);
855 #endif
856 }
857
858 static inline unsigned int show_bits1(GetBitContext *s){
859     return show_bits(s, 1);
860 }
861
862 static inline void skip_bits1(GetBitContext *s){
863     skip_bits(s, 1);
864 }
865
866 /**
867  * init GetBitContext.
868  * @param buffer bitstream buffer, must be FF_INPUT_BUFFER_PADDING_SIZE bytes larger then the actual read bits
869  * because some optimized bitstream readers read 32 or 64 bit at once and could read over the end
870  * @param bit_size the size of the buffer in bits
871  */
872 static inline void init_get_bits(GetBitContext *s,
873                    const uint8_t *buffer, int bit_size)
874 {
875     const int buffer_size= (bit_size+7)>>3;
876
877     s->buffer= buffer;
878     s->size_in_bits= bit_size;
879     s->buffer_end= buffer + buffer_size;
880 #ifdef ALT_BITSTREAM_READER
881     s->index=0;
882 #elif defined LIBMPEG2_BITSTREAM_READER
883 #ifdef LIBMPEG2_BITSTREAM_READER_HACK
884   if ((int)buffer&1) {
885      /* word alignment */
886     s->cache = (*buffer++)<<24;
887     s->buffer_ptr = buffer;
888     s->bit_count = 16-8;
889   } else
890 #endif
891   {
892     s->buffer_ptr = buffer;
893     s->bit_count = 16;
894     s->cache = 0;
895   }
896 #elif defined A32_BITSTREAM_READER
897     s->buffer_ptr = (uint32_t*)buffer;
898     s->bit_count = 32;
899     s->cache0 = 0;
900     s->cache1 = 0;
901 #endif
902     {
903         OPEN_READER(re, s)
904         UPDATE_CACHE(re, s)
905         UPDATE_CACHE(re, s)
906         CLOSE_READER(re, s)
907     }
908 #ifdef A32_BITSTREAM_READER
909     s->cache1 = 0;
910 #endif
911 }
912
913 int check_marker(GetBitContext *s, const char *msg);
914 void align_get_bits(GetBitContext *s);
915 int init_vlc(VLC *vlc, int nb_bits, int nb_codes,
916              const void *bits, int bits_wrap, int bits_size,
917              const void *codes, int codes_wrap, int codes_size);
918 void free_vlc(VLC *vlc);
919
920 /**
921  *
922  * if the vlc code is invalid and max_depth=1 than no bits will be removed
923  * if the vlc code is invalid and max_depth>1 than the number of bits removed
924  * is undefined
925  */
926 #define GET_VLC(code, name, gb, table, bits, max_depth)\
927 {\
928     int n, index, nb_bits;\
929 \
930     index= SHOW_UBITS(name, gb, bits);\
931     code = table[index][0];\
932     n    = table[index][1];\
933 \
934     if(max_depth > 1 && n < 0){\
935         LAST_SKIP_BITS(name, gb, bits)\
936         UPDATE_CACHE(name, gb)\
937 \
938         nb_bits = -n;\
939 \
940         index= SHOW_UBITS(name, gb, nb_bits) + code;\
941         code = table[index][0];\
942         n    = table[index][1];\
943         if(max_depth > 2 && n < 0){\
944             LAST_SKIP_BITS(name, gb, nb_bits)\
945             UPDATE_CACHE(name, gb)\
946 \
947             nb_bits = -n;\
948 \
949             index= SHOW_UBITS(name, gb, nb_bits) + code;\
950             code = table[index][0];\
951             n    = table[index][1];\
952         }\
953     }\
954     SKIP_BITS(name, gb, n)\
955 }
956
957 #define GET_RL_VLC(level, run, name, gb, table, bits, max_depth)\
958 {\
959     int n, index, nb_bits;\
960 \
961     index= SHOW_UBITS(name, gb, bits);\
962     level = table[index].level;\
963     n     = table[index].len;\
964 \
965     if(max_depth > 1 && n < 0){\
966         LAST_SKIP_BITS(name, gb, bits)\
967         UPDATE_CACHE(name, gb)\
968 \
969         nb_bits = -n;\
970 \
971         index= SHOW_UBITS(name, gb, nb_bits) + level;\
972         level = table[index].level;\
973         n     = table[index].len;\
974     }\
975     run= table[index].run;\
976     SKIP_BITS(name, gb, n)\
977 }
978
979 // deprecated, dont use get_vlc for new code, use get_vlc2 instead or use GET_VLC directly
980 static inline int get_vlc(GetBitContext *s, VLC *vlc)
981 {
982     int code;
983     VLC_TYPE (*table)[2]= vlc->table;
984     
985     OPEN_READER(re, s)
986     UPDATE_CACHE(re, s)
987
988     GET_VLC(code, re, s, table, vlc->bits, 3)    
989
990     CLOSE_READER(re, s)
991     return code;
992 }
993
994 /**
995  * parses a vlc code, faster then get_vlc()
996  * @param bits is the number of bits which will be read at once, must be 
997  *             identical to nb_bits in init_vlc()
998  * @param max_depth is the number of times bits bits must be readed to completly
999  *                  read the longest vlc code 
1000  *                  = (max_vlc_length + bits - 1) / bits
1001  */
1002 static always_inline int get_vlc2(GetBitContext *s, VLC_TYPE (*table)[2],
1003                                   int bits, int max_depth)
1004 {
1005     int code;
1006     
1007     OPEN_READER(re, s)
1008     UPDATE_CACHE(re, s)
1009
1010     GET_VLC(code, re, s, table, bits, max_depth)
1011
1012     CLOSE_READER(re, s)
1013     return code;
1014 }
1015
1016 //#define TRACE
1017
1018 #ifdef TRACE
1019
1020 static inline void print_bin(int bits, int n){
1021     int i;
1022     
1023     for(i=n-1; i>=0; i--){
1024         printf("%d", (bits>>i)&1);
1025     }
1026     for(i=n; i<24; i++)
1027         printf(" ");
1028 }
1029
1030 static inline int get_bits_trace(GetBitContext *s, int n, char *file, char *func, int line){
1031     int r= get_bits(s, n);
1032     
1033     print_bin(r, n);
1034     printf("%5d %2d %3d bit @%5d in %s %s:%d\n", r, n, r, get_bits_count(s)-n, file, func, line);
1035     return r;
1036 }
1037 static inline int get_vlc_trace(GetBitContext *s, VLC_TYPE (*table)[2], int bits, int max_depth, char *file, char *func, int line){
1038     int show= show_bits(s, 24);
1039     int pos= get_bits_count(s);
1040     int r= get_vlc2(s, table, bits, max_depth);
1041     int len= get_bits_count(s) - pos;
1042     int bits2= show>>(24-len);
1043     
1044     print_bin(bits2, len);
1045     
1046     printf("%5d %2d %3d vlc @%5d in %s %s:%d\n", bits2, len, r, pos, file, func, line);
1047     return r;
1048 }
1049 static inline int get_xbits_trace(GetBitContext *s, int n, char *file, char *func, int line){
1050     int show= show_bits(s, n);
1051     int r= get_xbits(s, n);
1052     
1053     print_bin(show, n);
1054     printf("%5d %2d %3d xbt @%5d in %s %s:%d\n", show, n, r, get_bits_count(s)-n, file, func, line);
1055     return r;
1056 }
1057
1058 #define get_bits(s, n)  get_bits_trace(s, n, __FILE__, __PRETTY_FUNCTION__, __LINE__)
1059 #define get_bits1(s)    get_bits_trace(s, 1, __FILE__, __PRETTY_FUNCTION__, __LINE__)
1060 #define get_xbits(s, n) get_xbits_trace(s, n, __FILE__, __PRETTY_FUNCTION__, __LINE__)
1061 #define get_vlc(s, vlc)            get_vlc_trace(s, (vlc)->table, (vlc)->bits, 3, __FILE__, __PRETTY_FUNCTION__, __LINE__)
1062 #define get_vlc2(s, tab, bits, max) get_vlc_trace(s, tab, bits, max, __FILE__, __PRETTY_FUNCTION__, __LINE__)
1063
1064 #define tprintf printf
1065
1066 #else //TRACE
1067 #define tprintf(...) {}
1068 #endif
1069
1070 /* define it to include statistics code (useful only for optimizing
1071    codec efficiency */
1072 //#define STATS
1073
1074 #ifdef STATS
1075
1076 enum {
1077     ST_UNKNOWN,
1078     ST_DC,
1079     ST_INTRA_AC,
1080     ST_INTER_AC,
1081     ST_INTRA_MB,
1082     ST_INTER_MB,
1083     ST_MV,
1084     ST_NB,
1085 };
1086
1087 extern int st_current_index;
1088 extern unsigned int st_bit_counts[ST_NB];
1089 extern unsigned int st_out_bit_counts[ST_NB];
1090
1091 void print_stats(void);
1092 #endif
1093
1094 /* misc math functions */
1095 extern const uint8_t ff_log2_tab[256];
1096
1097 static inline int av_log2(unsigned int v)
1098 {
1099     int n;
1100
1101     n = 0;
1102     if (v & 0xffff0000) {
1103         v >>= 16;
1104         n += 16;
1105     }
1106     if (v & 0xff00) {
1107         v >>= 8;
1108         n += 8;
1109     }
1110     n += ff_log2_tab[v];
1111
1112     return n;
1113 }
1114
1115 static inline int av_log2_16bit(unsigned int v)
1116 {
1117     int n;
1118
1119     n = 0;
1120     if (v & 0xff00) {
1121         v >>= 8;
1122         n += 8;
1123     }
1124     n += ff_log2_tab[v];
1125
1126     return n;
1127 }
1128
1129 /* median of 3 */
1130 static inline int mid_pred(int a, int b, int c)
1131 {
1132 #if 0
1133     int t= (a-b)&((a-b)>>31);
1134     a-=t;
1135     b+=t;
1136     b-= (b-c)&((b-c)>>31);
1137     b+= (a-b)&((a-b)>>31);
1138
1139     return b;
1140 #else
1141     if(a>b){
1142         if(c>b){
1143             if(c>a) b=a;
1144             else    b=c;
1145         }
1146     }else{
1147         if(b>c){
1148             if(c>a) b=c;
1149             else    b=a;
1150         }
1151     }
1152     return b;
1153 #endif
1154 }
1155
1156 static inline int clip(int a, int amin, int amax)
1157 {
1158     if (a < amin)
1159         return amin;
1160     else if (a > amax)
1161         return amax;
1162     else
1163         return a;
1164 }
1165
1166 /* math */
1167 extern const uint8_t ff_sqrt_tab[128];
1168
1169 int64_t ff_gcd(int64_t a, int64_t b);
1170
1171 static inline int ff_sqrt(int a)
1172 {
1173     int ret=0;
1174     int s;
1175     int ret_sq=0;
1176     
1177     if(a<128) return ff_sqrt_tab[a];
1178     
1179     for(s=15; s>=0; s--){
1180         int b= ret_sq + (1<<(s*2)) + (ret<<s)*2;
1181         if(b<=a){
1182             ret_sq=b;
1183             ret+= 1<<s;
1184         }
1185     }
1186     return ret;
1187 }
1188
1189 /**
1190  * converts fourcc string to int
1191  */
1192 static inline int ff_get_fourcc(const char *s){
1193     assert( strlen(s)==4 );
1194
1195     return (s[0]) + (s[1]<<8) + (s[2]<<16) + (s[3]<<24);
1196 }
1197
1198 #define MKTAG(a,b,c,d) (a | (b << 8) | (c << 16) | (d << 24))
1199 #define MKBETAG(a,b,c,d) (d | (c << 8) | (b << 16) | (a << 24))
1200
1201
1202 #ifdef ARCH_X86
1203 #define MASK_ABS(mask, level)\
1204             asm volatile(\
1205                 "cdq                    \n\t"\
1206                 "xorl %1, %0            \n\t"\
1207                 "subl %1, %0            \n\t"\
1208                 : "+a" (level), "=&d" (mask)\
1209             );
1210 #else
1211 #define MASK_ABS(mask, level)\
1212             mask= level>>31;\
1213             level= (level^mask)-mask;
1214 #endif
1215
1216
1217 #if __CPU__ >= 686 && !defined(RUNTIME_CPUDETECT)
1218 #define COPY3_IF_LT(x,y,a,b,c,d)\
1219 asm volatile (\
1220     "cmpl %0, %3        \n\t"\
1221     "cmovl %3, %0       \n\t"\
1222     "cmovl %4, %1       \n\t"\
1223     "cmovl %5, %2       \n\t"\
1224     : "+r" (x), "+r" (a), "+r" (c)\
1225     : "r" (y), "r" (b), "r" (d)\
1226 );
1227 #else
1228 #define COPY3_IF_LT(x,y,a,b,c,d)\
1229 if((y)<(x)){\
1230      (x)=(y);\
1231      (a)=(b);\
1232      (c)=(d);\
1233 }
1234 #endif
1235
1236 #ifdef ARCH_X86
1237 static inline long long rdtsc()
1238 {
1239         long long l;
1240         asm volatile(   "rdtsc\n\t"
1241                 : "=A" (l)
1242         );
1243         return l;
1244 }
1245
1246 #define START_TIMER \
1247 uint64_t tend;\
1248 uint64_t tstart= rdtsc();\
1249
1250 #define STOP_TIMER(id) \
1251 tend= rdtsc();\
1252 {\
1253   static uint64_t tsum=0;\
1254   static int tcount=0;\
1255   static int tskip_count=0;\
1256   if(tcount<2 || tend - tstart < 8*tsum/tcount){\
1257       tsum+= tend - tstart;\
1258       tcount++;\
1259   }else\
1260       tskip_count++;\
1261   if(256*256*256*64%(tcount+tskip_count)==0){\
1262       av_log(NULL, AV_LOG_DEBUG, "%Ld dezicycles in %s, %d runs, %d skips\n", tsum*10/tcount, id, tcount, tskip_count);\
1263   }\
1264 }
1265 #endif
1266
1267 #define CLAMP_TO_8BIT(d) ((d > 0xff) ? 0xff : (d < 0) ? 0 : d)
1268
1269 /* avoid usage of various functions */
1270 #define malloc please_use_av_malloc
1271 #define free please_use_av_free
1272 #define realloc please_use_av_realloc
1273 #if !(defined(LIBAVFORMAT_BUILD) || defined(_FRAMEHOOK_H))
1274 #define printf please_use_av_log
1275 #define fprintf please_use_av_log
1276 #endif
1277
1278 #define CHECKED_ALLOCZ(p, size)\
1279 {\
1280     p= av_mallocz(size);\
1281     if(p==NULL && (size)!=0){\
1282         perror("malloc");\
1283         goto fail;\
1284     }\
1285 }
1286
1287 #endif /* HAVE_AV_CONFIG_H */
1288
1289 #endif /* COMMON_H */