1 /*
2  * Common bit i/o utils
3  * Copyright (c) 2000, 2001 Fabrice Bellard
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  * Copyright (c) 2010 Loren Merritt
6  *
7  * alternative bitstream reader & writer by Michael Niedermayer <michaelni@gmx.at>
8  *
9  * This file is part of FFmpeg.
10  *
11  * FFmpeg is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * FFmpeg is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with FFmpeg; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24  */
25 
26 /**
27  * @file
28  * bitstream api.
29  */
30 
31 //#include "avcodec.h"
32 #include "ffmpeg_get_bits.h"
33 #include "ffmpeg_intreadwrite.h"
34 
35 #define av_log(...)
36 
37 #ifdef ROCKBOX
38 #undef DEBUGF
39 #define DEBUGF(...)
40 #endif
41 #define trace(...) { fprintf (stderr, __VA_ARGS__); }
42 //#define trace(fmt,...)
43 #define DEBUGF trace
44 
45 const uint8_t ff_log2_run[32]={
46  0, 0, 0, 0, 1, 1, 1, 1,
47  2, 2, 2, 2, 3, 3, 3, 3,
48  4, 4, 5, 5, 6, 6, 7, 7,
49  8, 9,10,11,12,13,14,15
50 };
51 
52 #if 0 // unused in rockbox
53 void align_put_bits(PutBitContext *s)
54 {
55 #ifdef ALT_BITSTREAM_WRITER
56     put_bits(s,(  - s->index) & 7,0);
57 #else
58     put_bits(s,s->bit_left & 7,0);
59 #endif
60 }
61 
62 void ff_put_string(PutBitContext *pb, const char *string, int terminate_string)
63 {
64     while(*string){
65         put_bits(pb, 8, *string);
66         string++;
67     }
68     if(terminate_string)
69         put_bits(pb, 8, 0);
70 }
71 #endif
72 
73 
74 /* VLC decoding */
75 
76 //#define DEBUG_VLC
77 
78 #define GET_DATA(v, table, i, wrap, size) \
79 {\
80     const uint8_t *ptr = (const uint8_t *)table + i * wrap;\
81     switch(size) {\
82     case 1:\
83         v = *(const uint8_t *)ptr;\
84         break;\
85     case 2:\
86         v = *(const uint16_t *)ptr;\
87         break;\
88     default:\
89         v = *(const uint32_t *)ptr;\
90         break;\
91     }\
92 }
93 
94 
alloc_table(VLC * vlc,int size,int use_static)95 static int alloc_table(VLC *vlc, int size, int use_static)
96 {
97     int index;
98     index = vlc->table_size;
99     vlc->table_size += size;
100     if (vlc->table_size > vlc->table_allocated) {
101         if(use_static)
102         {
103             DEBUGF("init_vlc() used with too little memory : table_size > allocated_memory\n");
104             return -1;
105         }
106 //            abort(); //cant do anything, init_vlc() is used with too little memory
107 //        vlc->table_allocated += (1 << vlc->bits);
108 //        vlc->table = av_realloc(vlc->table,
109 //                                sizeof(VLC_TYPE) * 2 * vlc->table_allocated);
110         if (!vlc->table)
111             return -1;
112     }
113     return index;
114 }
115 
116 /*
117 static av_always_inline uint32_t bitswap_32(uint32_t x) {
118     return av_reverse[x&0xFF]<<24
119          | av_reverse[(x>>8)&0xFF]<<16
120          | av_reverse[(x>>16)&0xFF]<<8
121          | av_reverse[x>>24];
122 }
123 */
124 
125 typedef struct {
126     uint8_t bits;
127     uint16_t symbol;
128     /** codeword, with the first bit-to-be-read in the msb
129      * (even if intended for a little-endian bitstream reader) */
130     uint32_t code;
131 } __attribute__((__packed__)) VLCcode; /* packed to save space */
132 
compare_vlcspec(const void * a,const void * b)133 static int compare_vlcspec(const void *a, const void *b)
134 {
135     const VLCcode *sa=a, *sb=b;
136     return (sa->code >> 1) - (sb->code >> 1);
137 }
138 
139 /**
140  * Build VLC decoding tables suitable for use with get_vlc().
141  *
142  * @param vlc            the context to be initted
143  *
144  * @param table_nb_bits  max length of vlc codes to store directly in this table
145  *                       (Longer codes are delegated to subtables.)
146  *
147  * @param nb_codes       number of elements in codes[]
148  *
149  * @param codes          descriptions of the vlc codes
150  *                       These must be ordered such that codes going into the same subtable are contiguous.
151  *                       Sorting by VLCcode.code is sufficient, though not necessary.
152  */
build_table(VLC * vlc,int table_nb_bits,int nb_codes,VLCcode * codes,int flags)153 static int build_table(VLC *vlc, int table_nb_bits, int nb_codes,
154                        VLCcode *codes, int flags)
155 {
156     int table_size, table_index, index, symbol, subtable_bits;
157     int i, j, k, n, nb, inc;
158     uint32_t code, code_prefix;
159     VLC_TYPE (*table)[2];
160 
161     table_size = 1 << table_nb_bits;
162     table_index = alloc_table(vlc, table_size, flags & INIT_VLC_USE_NEW_STATIC);
163 #ifdef DEBUG_VLC
164     av_log(NULL,AV_LOG_DEBUG,"new table index=%d size=%d\n",
165            table_index, table_size);
166 #endif
167     if (table_index < 0)
168         return -1;
169     table = &vlc->table[table_index];
170 
171     for (i = 0; i < table_size; i++) {
172         table[i][1] = 0; //bits
173         table[i][0] = -1; //codes
174     }
175 
176     /* first pass: map codes and compute auxillary table sizes */
177     for (i = 0; i < nb_codes; i++) {
178         n = codes[i].bits;
179         code = codes[i].code;
180         symbol = codes[i].symbol;
181 #if defined(DEBUG_VLC) && 0
182         av_log(NULL,AV_LOG_DEBUG,"i=%d n=%d code=0x%x\n", i, n, code);
183 #endif
184         if (n <= table_nb_bits) {
185             /* no need to add another table */
186             j = code >> (32 - table_nb_bits);
187             nb = 1 << (table_nb_bits - n);
188             inc = 1;
189 /*            if (flags & INIT_VLC_LE) {
190                 j = bitswap_32(code);
191                 inc = 1 << n;
192             } */
193             for (k = 0; k < nb; k++) {
194 #ifdef DEBUG_VLC
195                 av_log(NULL, AV_LOG_DEBUG, "%4x: code=%d n=%d\n",
196                        j, i, n);
197 #endif
198                 if (table[j][1] /*bits*/ != 0) {
199                     av_log(NULL, AV_LOG_ERROR, "incorrect codes\n");
200                     return -1;
201                 }
202                 table[j][1] = n; //bits
203                 table[j][0] = symbol;
204                 j += inc;
205             }
206         } else {
207             /* fill auxiliary table recursively */
208             n -= table_nb_bits;
209             code_prefix = code >> (32 - table_nb_bits);
210             subtable_bits = n;
211             codes[i].bits = n;
212             codes[i].code = code << table_nb_bits;
213             for (k = i+1; k < nb_codes; k++) {
214                 n = codes[k].bits - table_nb_bits;
215                 if (n <= 0)
216                     break;
217                 code = codes[k].code;
218                 if (code >> (32 - table_nb_bits) != code_prefix)
219                     break;
220                 codes[k].bits = n;
221                 codes[k].code = code << table_nb_bits;
222                 subtable_bits = FFMAX(subtable_bits, n);
223             }
224             subtable_bits = FFMIN(subtable_bits, table_nb_bits);
225             j = /*(flags & INIT_VLC_LE) ? bitswap_32(code_prefix) >> (32 - table_nb_bits) :*/ code_prefix;
226             table[j][1] = -subtable_bits;
227 #ifdef DEBUG_VLC
228             av_log(NULL,AV_LOG_DEBUG,"%4x: n=%d (subtable)\n",
229                    j, codes[i].bits + table_nb_bits);
230 #endif
231             index = build_table(vlc, subtable_bits, k-i, codes+i, flags);
232             if (index < 0)
233                 return -1;
234             /* note: realloc has been done, so reload tables */
235             table = &vlc->table[table_index];
236             table[j][0] = index; //code
237             i = k-1;
238         }
239     }
240     return table_index;
241 }
242 
243 
244 /* Build VLC decoding tables suitable for use with get_vlc().
245 
246    'nb_bits' set thee decoding table size (2^nb_bits) entries. The
247    bigger it is, the faster is the decoding. But it should not be too
248    big to save memory and L1 cache. '9' is a good compromise.
249 
250    'nb_codes' : number of vlcs codes
251 
252    'bits' : table which gives the size (in bits) of each vlc code.
253 
254    'codes' : table which gives the bit pattern of of each vlc code.
255 
256    'symbols' : table which gives the values to be returned from get_vlc().
257 
258    'xxx_wrap' : give the number of bytes between each entry of the
259    'bits' or 'codes' tables.
260 
261    'xxx_size' : gives the number of bytes of each entry of the 'bits'
262    or 'codes' tables.
263 
264    'wrap' and 'size' allows to use any memory configuration and types
265    (byte/word/long) to store the 'bits', 'codes', and 'symbols' tables.
266 
267    'use_static' should be set to 1 for tables, which should be freed
268    with av_free_static(), 0 if free_vlc() will be used.
269 */
270 
271 /* Rockbox: support for INIT_VLC_LE is currently disabled since none of our
272    codecs use it, there's a LUT based bit reverse function for this commented
273    out above (bitswap_32) and an inline asm version in libtremor/codebook.c
274    if we ever want this */
275 
276 static VLCcode buf[1336+1]; /* worst case is wma, which has one table with 1336 entries */
277 
init_vlc_sparse(VLC * vlc,int nb_bits,int nb_codes,const void * bits,int bits_wrap,int bits_size,const void * codes,int codes_wrap,int codes_size,const void * symbols,int symbols_wrap,int symbols_size,int flags)278 int init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes,
279              const void *bits, int bits_wrap, int bits_size,
280              const void *codes, int codes_wrap, int codes_size,
281              const void *symbols, int symbols_wrap, int symbols_size,
282              int flags)
283 {
284     if (nb_codes+1 > (int)(sizeof (buf)/ sizeof (VLCcode)))
285     {
286         DEBUGF("Table is larger than temp buffer!\n");
287         return -1;
288     }
289 
290     int i, j, ret;
291 
292     vlc->bits = nb_bits;
293     if(flags & INIT_VLC_USE_NEW_STATIC){
294         if(vlc->table_size && vlc->table_size == vlc->table_allocated){
295             return 0;
296         }else if(vlc->table_size){
297             DEBUGF("fatal error, we are called on a partially initialized table\n");
298             return -1;
299 //            abort(); // fatal error, we are called on a partially initialized table
300         }
301     }else {
302         vlc->table = NULL;
303         vlc->table_allocated = 0;
304         vlc->table_size = 0;
305     }
306 
307 #ifdef DEBUG_VLC
308     av_log(NULL,AV_LOG_DEBUG,"build table nb_codes=%d\n", nb_codes);
309 #endif
310 
311 //    buf = av_malloc((nb_codes+1)*sizeof(VLCcode));
312 
313 //    assert(symbols_size <= 2 || !symbols);
314     j = 0;
315 #define COPY(condition)\
316     for (i = 0; i < nb_codes; i++) {\
317         GET_DATA(buf[j].bits, bits, i, bits_wrap, bits_size);\
318         if (!(condition))\
319             continue;\
320         GET_DATA(buf[j].code, codes, i, codes_wrap, codes_size);\
321 /*        if (flags & INIT_VLC_LE)*/\
322 /*            buf[j].code = bitswap_32(buf[j].code);*/\
323 /*        else*/\
324             buf[j].code <<= 32 - buf[j].bits;\
325         if (symbols)\
326             GET_DATA(buf[j].symbol, symbols, i, symbols_wrap, symbols_size)\
327         else\
328             buf[j].symbol = i;\
329         j++;\
330     }
331     COPY(buf[j].bits > nb_bits);
332     // qsort is the slowest part of init_vlc, and could probably be improved or avoided
333     qsort(buf, j, sizeof(VLCcode), compare_vlcspec);
334     COPY(buf[j].bits && buf[j].bits <= nb_bits);
335     nb_codes = j;
336 
337     ret = build_table(vlc, nb_bits, nb_codes, buf, flags);
338 
339 //    av_free(buf);
340     if (ret < 0) {
341 //        av_freep(&vlc->table);
342         return -1;
343     }
344     if((flags & INIT_VLC_USE_NEW_STATIC) && vlc->table_size != vlc->table_allocated) {
345         av_log(NULL, AV_LOG_ERROR, "needed %d had %d\n", vlc->table_size, vlc->table_allocated);
346     }
347     return 0;
348 }
349 
350 /* not used in rockbox
351 void free_vlc(VLC *vlc)
352 {
353     av_freep(&vlc->table);
354 }
355 */
356 
357