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