]> git.sesse.net Git - ffmpeg/blob - libavcodec/vorbisdec.c
eamad: release the reference frame on video size changes
[ffmpeg] / libavcodec / vorbisdec.c
1 /**
2  * @file
3  * Vorbis I decoder
4  * @author Denes Balatoni  ( dbalatoni programozo hu )
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * Vorbis I decoder
26  * @author Denes Balatoni  ( dbalatoni programozo hu )
27  */
28
29 #include <inttypes.h>
30 #include <math.h>
31
32 #define ALT_BITSTREAM_READER_LE
33 #include "avcodec.h"
34 #include "get_bits.h"
35 #include "dsputil.h"
36 #include "fft.h"
37 #include "fmtconvert.h"
38
39 #include "vorbis.h"
40 #include "xiph.h"
41
42 #define V_NB_BITS 8
43 #define V_NB_BITS2 11
44 #define V_MAX_VLCS (1 << 16)
45 #define V_MAX_PARTITIONS (1 << 20)
46
47 #undef NDEBUG
48 #include <assert.h>
49
50 typedef struct {
51     uint8_t      dimensions;
52     uint8_t      lookup_type;
53     uint8_t      maxdepth;
54     VLC          vlc;
55     float       *codevectors;
56     unsigned int nb_bits;
57 } vorbis_codebook;
58
59 typedef union  vorbis_floor_u  vorbis_floor_data;
60 typedef struct vorbis_floor0_s vorbis_floor0;
61 typedef struct vorbis_floor1_s vorbis_floor1;
62 struct vorbis_context_s;
63 typedef
64 int (* vorbis_floor_decode_func)
65     (struct vorbis_context_s *, vorbis_floor_data *, float *);
66 typedef struct {
67     uint8_t floor_type;
68     vorbis_floor_decode_func decode;
69     union vorbis_floor_u {
70         struct vorbis_floor0_s {
71             uint8_t       order;
72             uint16_t      rate;
73             uint16_t      bark_map_size;
74             int32_t      *map[2];
75             uint32_t      map_size[2];
76             uint8_t       amplitude_bits;
77             uint8_t       amplitude_offset;
78             uint8_t       num_books;
79             uint8_t      *book_list;
80             float        *lsp;
81         } t0;
82         struct vorbis_floor1_s {
83             uint8_t       partitions;
84             uint8_t       partition_class[32];
85             uint8_t       class_dimensions[16];
86             uint8_t       class_subclasses[16];
87             uint8_t       class_masterbook[16];
88             int16_t       subclass_books[16][8];
89             uint8_t       multiplier;
90             uint16_t      x_list_dim;
91             vorbis_floor1_entry *list;
92         } t1;
93     } data;
94 } vorbis_floor;
95
96 typedef struct {
97     uint16_t      type;
98     uint32_t      begin;
99     uint32_t      end;
100     unsigned      partition_size;
101     uint8_t       classifications;
102     uint8_t       classbook;
103     int16_t       books[64][8];
104     uint8_t       maxpass;
105     uint16_t      ptns_to_read;
106     uint8_t      *classifs;
107 } vorbis_residue;
108
109 typedef struct {
110     uint8_t       submaps;
111     uint16_t      coupling_steps;
112     uint8_t      *magnitude;
113     uint8_t      *angle;
114     uint8_t      *mux;
115     uint8_t       submap_floor[16];
116     uint8_t       submap_residue[16];
117 } vorbis_mapping;
118
119 typedef struct {
120     uint8_t       blockflag;
121     uint16_t      windowtype;
122     uint16_t      transformtype;
123     uint8_t       mapping;
124 } vorbis_mode;
125
126 typedef struct vorbis_context_s {
127     AVCodecContext *avccontext;
128     GetBitContext gb;
129     DSPContext dsp;
130     FmtConvertContext fmt_conv;
131
132     FFTContext mdct[2];
133     uint8_t       first_frame;
134     uint32_t      version;
135     uint8_t       audio_channels;
136     uint32_t      audio_samplerate;
137     uint32_t      bitrate_maximum;
138     uint32_t      bitrate_nominal;
139     uint32_t      bitrate_minimum;
140     uint32_t      blocksize[2];
141     const float  *win[2];
142     uint16_t      codebook_count;
143     vorbis_codebook *codebooks;
144     uint8_t       floor_count;
145     vorbis_floor *floors;
146     uint8_t       residue_count;
147     vorbis_residue *residues;
148     uint8_t       mapping_count;
149     vorbis_mapping *mappings;
150     uint8_t       mode_count;
151     vorbis_mode  *modes;
152     uint8_t       mode_number; // mode number for the current packet
153     uint8_t       previous_window;
154     float        *channel_residues;
155     float        *channel_floors;
156     float        *saved;
157     float         scale_bias; // for float->int conversion
158 } vorbis_context;
159
160 /* Helper functions */
161
162 #define BARK(x) \
163     (13.1f * atan(0.00074f * (x)) + 2.24f * atan(1.85e-8f * (x) * (x)) + 1e-4f * (x))
164
165 static const char idx_err_str[] = "Index value %d out of range (0 - %d) for %s at %s:%i\n";
166 #define VALIDATE_INDEX(idx, limit) \
167     if (idx >= limit) {\
168         av_log(vc->avccontext, AV_LOG_ERROR,\
169                idx_err_str,\
170                (int)(idx), (int)(limit - 1), #idx, __FILE__, __LINE__);\
171         return -1;\
172     }
173 #define GET_VALIDATED_INDEX(idx, bits, limit) \
174     {\
175         idx = get_bits(gb, bits);\
176         VALIDATE_INDEX(idx, limit)\
177     }
178
179 static float vorbisfloat2float(unsigned val)
180 {
181     double mant = val & 0x1fffff;
182     long exp    = (val & 0x7fe00000L) >> 21;
183     if (val & 0x80000000)
184         mant = -mant;
185     return ldexp(mant, exp - 20 - 768);
186 }
187
188
189 // Free all allocated memory -----------------------------------------
190
191 static void vorbis_free(vorbis_context *vc)
192 {
193     int i;
194
195     av_freep(&vc->channel_residues);
196     av_freep(&vc->channel_floors);
197     av_freep(&vc->saved);
198
199     for (i = 0; i < vc->residue_count; i++)
200         av_free(vc->residues[i].classifs);
201     av_freep(&vc->residues);
202     av_freep(&vc->modes);
203
204     ff_mdct_end(&vc->mdct[0]);
205     ff_mdct_end(&vc->mdct[1]);
206
207     for (i = 0; i < vc->codebook_count; ++i) {
208         av_free(vc->codebooks[i].codevectors);
209         free_vlc(&vc->codebooks[i].vlc);
210     }
211     av_freep(&vc->codebooks);
212
213     for (i = 0; i < vc->floor_count; ++i) {
214         if (vc->floors[i].floor_type == 0) {
215             av_free(vc->floors[i].data.t0.map[0]);
216             av_free(vc->floors[i].data.t0.map[1]);
217             av_free(vc->floors[i].data.t0.book_list);
218             av_free(vc->floors[i].data.t0.lsp);
219         } else {
220             av_free(vc->floors[i].data.t1.list);
221         }
222     }
223     av_freep(&vc->floors);
224
225     for (i = 0; i < vc->mapping_count; ++i) {
226         av_free(vc->mappings[i].magnitude);
227         av_free(vc->mappings[i].angle);
228         av_free(vc->mappings[i].mux);
229     }
230     av_freep(&vc->mappings);
231 }
232
233 // Parse setup header -------------------------------------------------
234
235 // Process codebooks part
236
237 static int vorbis_parse_setup_hdr_codebooks(vorbis_context *vc)
238 {
239     unsigned cb;
240     uint8_t  *tmp_vlc_bits;
241     uint32_t *tmp_vlc_codes;
242     GetBitContext *gb = &vc->gb;
243     uint16_t *codebook_multiplicands;
244
245     vc->codebook_count = get_bits(gb, 8) + 1;
246
247     av_dlog(NULL, " Codebooks: %d \n", vc->codebook_count);
248
249     vc->codebooks = av_mallocz(vc->codebook_count * sizeof(*vc->codebooks));
250     tmp_vlc_bits  = av_mallocz(V_MAX_VLCS * sizeof(*tmp_vlc_bits));
251     tmp_vlc_codes = av_mallocz(V_MAX_VLCS * sizeof(*tmp_vlc_codes));
252     codebook_multiplicands = av_malloc(V_MAX_VLCS * sizeof(*codebook_multiplicands));
253
254     for (cb = 0; cb < vc->codebook_count; ++cb) {
255         vorbis_codebook *codebook_setup = &vc->codebooks[cb];
256         unsigned ordered, t, entries, used_entries = 0;
257
258         av_dlog(NULL, " %u. Codebook\n", cb);
259
260         if (get_bits(gb, 24) != 0x564342) {
261             av_log(vc->avccontext, AV_LOG_ERROR,
262                    " %u. Codebook setup data corrupt.\n", cb);
263             goto error;
264         }
265
266         codebook_setup->dimensions=get_bits(gb, 16);
267         if (codebook_setup->dimensions > 16 || codebook_setup->dimensions == 0) {
268             av_log(vc->avccontext, AV_LOG_ERROR,
269                    " %u. Codebook's dimension is invalid (%d).\n",
270                    cb, codebook_setup->dimensions);
271             goto error;
272         }
273         entries = get_bits(gb, 24);
274         if (entries > V_MAX_VLCS) {
275             av_log(vc->avccontext, AV_LOG_ERROR,
276                    " %u. Codebook has too many entries (%u).\n",
277                    cb, entries);
278             goto error;
279         }
280
281         ordered = get_bits1(gb);
282
283         av_dlog(NULL, " codebook_dimensions %d, codebook_entries %u\n",
284                 codebook_setup->dimensions, entries);
285
286         if (!ordered) {
287             unsigned ce, flag;
288             unsigned sparse = get_bits1(gb);
289
290             av_dlog(NULL, " not ordered \n");
291
292             if (sparse) {
293                 av_dlog(NULL, " sparse \n");
294
295                 used_entries = 0;
296                 for (ce = 0; ce < entries; ++ce) {
297                     flag = get_bits1(gb);
298                     if (flag) {
299                         tmp_vlc_bits[ce] = get_bits(gb, 5) + 1;
300                         ++used_entries;
301                     } else
302                         tmp_vlc_bits[ce] = 0;
303                 }
304             } else {
305                 av_dlog(NULL, " not sparse \n");
306
307                 used_entries = entries;
308                 for (ce = 0; ce < entries; ++ce)
309                     tmp_vlc_bits[ce] = get_bits(gb, 5) + 1;
310             }
311         } else {
312             unsigned current_entry  = 0;
313             unsigned current_length = get_bits(gb, 5) + 1;
314
315             av_dlog(NULL, " ordered, current length: %u\n", current_length);  //FIXME
316
317             used_entries = entries;
318             for (; current_entry < used_entries && current_length <= 32; ++current_length) {
319                 unsigned i, number;
320
321                 av_dlog(NULL, " number bits: %u ", ilog(entries - current_entry));
322
323                 number = get_bits(gb, ilog(entries - current_entry));
324
325                 av_dlog(NULL, " number: %u\n", number);
326
327                 for (i = current_entry; i < number+current_entry; ++i)
328                     if (i < used_entries)
329                         tmp_vlc_bits[i] = current_length;
330
331                 current_entry+=number;
332             }
333             if (current_entry>used_entries) {
334                 av_log(vc->avccontext, AV_LOG_ERROR, " More codelengths than codes in codebook. \n");
335                 goto error;
336             }
337         }
338
339         codebook_setup->lookup_type = get_bits(gb, 4);
340
341         av_dlog(NULL, " lookup type: %d : %s \n", codebook_setup->lookup_type,
342                 codebook_setup->lookup_type ? "vq" : "no lookup");
343
344 // If the codebook is used for (inverse) VQ, calculate codevectors.
345
346         if (codebook_setup->lookup_type == 1) {
347             unsigned i, j, k;
348             unsigned codebook_lookup_values = ff_vorbis_nth_root(entries, codebook_setup->dimensions);
349
350             float codebook_minimum_value = vorbisfloat2float(get_bits_long(gb, 32));
351             float codebook_delta_value   = vorbisfloat2float(get_bits_long(gb, 32));
352             unsigned codebook_value_bits = get_bits(gb, 4) + 1;
353             unsigned codebook_sequence_p = get_bits1(gb);
354
355             av_dlog(NULL, " We expect %d numbers for building the codevectors. \n",
356                     codebook_lookup_values);
357             av_dlog(NULL, "  delta %f minmum %f \n",
358                     codebook_delta_value, codebook_minimum_value);
359
360             for (i = 0; i < codebook_lookup_values; ++i) {
361                 codebook_multiplicands[i] = get_bits(gb, codebook_value_bits);
362
363                 av_dlog(NULL, " multiplicands*delta+minmum : %e \n",
364                         (float)codebook_multiplicands[i] * codebook_delta_value + codebook_minimum_value);
365                 av_dlog(NULL, " multiplicand %u\n", codebook_multiplicands[i]);
366             }
367
368 // Weed out unused vlcs and build codevector vector
369             codebook_setup->codevectors = used_entries ? av_mallocz(used_entries *
370                                                                     codebook_setup->dimensions *
371                                                                     sizeof(*codebook_setup->codevectors))
372                                                        : NULL;
373             for (j = 0, i = 0; i < entries; ++i) {
374                 unsigned dim = codebook_setup->dimensions;
375
376                 if (tmp_vlc_bits[i]) {
377                     float last = 0.0;
378                     unsigned lookup_offset = i;
379
380                     av_dlog(vc->avccontext, "Lookup offset %u ,", i);
381
382                     for (k = 0; k < dim; ++k) {
383                         unsigned multiplicand_offset = lookup_offset % codebook_lookup_values;
384                         codebook_setup->codevectors[j * dim + k] = codebook_multiplicands[multiplicand_offset] * codebook_delta_value + codebook_minimum_value + last;
385                         if (codebook_sequence_p)
386                             last = codebook_setup->codevectors[j * dim + k];
387                         lookup_offset/=codebook_lookup_values;
388                     }
389                     tmp_vlc_bits[j] = tmp_vlc_bits[i];
390
391                     av_dlog(vc->avccontext, "real lookup offset %u, vector: ", j);
392                     for (k = 0; k < dim; ++k)
393                         av_dlog(vc->avccontext, " %f ",
394                                 codebook_setup->codevectors[j * dim + k]);
395                     av_dlog(vc->avccontext, "\n");
396
397                     ++j;
398                 }
399             }
400             if (j != used_entries) {
401                 av_log(vc->avccontext, AV_LOG_ERROR, "Bug in codevector vector building code. \n");
402                 goto error;
403             }
404             entries = used_entries;
405         } else if (codebook_setup->lookup_type >= 2) {
406             av_log(vc->avccontext, AV_LOG_ERROR, "Codebook lookup type not supported. \n");
407             goto error;
408         }
409
410 // Initialize VLC table
411         if (ff_vorbis_len2vlc(tmp_vlc_bits, tmp_vlc_codes, entries)) {
412             av_log(vc->avccontext, AV_LOG_ERROR, " Invalid code lengths while generating vlcs. \n");
413             goto error;
414         }
415         codebook_setup->maxdepth = 0;
416         for (t = 0; t < entries; ++t)
417             if (tmp_vlc_bits[t] >= codebook_setup->maxdepth)
418                 codebook_setup->maxdepth = tmp_vlc_bits[t];
419
420         if (codebook_setup->maxdepth > 3 * V_NB_BITS)
421             codebook_setup->nb_bits = V_NB_BITS2;
422         else
423             codebook_setup->nb_bits = V_NB_BITS;
424
425         codebook_setup->maxdepth = (codebook_setup->maxdepth+codebook_setup->nb_bits - 1) / codebook_setup->nb_bits;
426
427         if (init_vlc(&codebook_setup->vlc, codebook_setup->nb_bits, entries, tmp_vlc_bits, sizeof(*tmp_vlc_bits), sizeof(*tmp_vlc_bits), tmp_vlc_codes, sizeof(*tmp_vlc_codes), sizeof(*tmp_vlc_codes), INIT_VLC_LE)) {
428             av_log(vc->avccontext, AV_LOG_ERROR, " Error generating vlc tables. \n");
429             goto error;
430         }
431     }
432
433     av_free(tmp_vlc_bits);
434     av_free(tmp_vlc_codes);
435     av_free(codebook_multiplicands);
436     return 0;
437
438 // Error:
439 error:
440     av_free(tmp_vlc_bits);
441     av_free(tmp_vlc_codes);
442     av_free(codebook_multiplicands);
443     return -1;
444 }
445
446 // Process time domain transforms part (unused in Vorbis I)
447
448 static int vorbis_parse_setup_hdr_tdtransforms(vorbis_context *vc)
449 {
450     GetBitContext *gb = &vc->gb;
451     unsigned i, vorbis_time_count = get_bits(gb, 6) + 1;
452
453     for (i = 0; i < vorbis_time_count; ++i) {
454         unsigned vorbis_tdtransform = get_bits(gb, 16);
455
456         av_dlog(NULL, " Vorbis time domain transform %u: %u\n",
457                 vorbis_time_count, vorbis_tdtransform);
458
459         if (vorbis_tdtransform) {
460             av_log(vc->avccontext, AV_LOG_ERROR, "Vorbis time domain transform data nonzero. \n");
461             return -1;
462         }
463     }
464     return 0;
465 }
466
467 // Process floors part
468
469 static int vorbis_floor0_decode(vorbis_context *vc,
470                                 vorbis_floor_data *vfu, float *vec);
471 static void create_map(vorbis_context *vc, unsigned floor_number);
472 static int vorbis_floor1_decode(vorbis_context *vc,
473                                 vorbis_floor_data *vfu, float *vec);
474 static int vorbis_parse_setup_hdr_floors(vorbis_context *vc)
475 {
476     GetBitContext *gb = &vc->gb;
477     int i,j,k;
478
479     vc->floor_count = get_bits(gb, 6) + 1;
480
481     vc->floors = av_mallocz(vc->floor_count * sizeof(*vc->floors));
482
483     for (i = 0; i < vc->floor_count; ++i) {
484         vorbis_floor *floor_setup = &vc->floors[i];
485
486         floor_setup->floor_type = get_bits(gb, 16);
487
488         av_dlog(NULL, " %d. floor type %d \n", i, floor_setup->floor_type);
489
490         if (floor_setup->floor_type == 1) {
491             int maximum_class = -1;
492             unsigned rangebits, rangemax, floor1_values = 2;
493
494             floor_setup->decode = vorbis_floor1_decode;
495
496             floor_setup->data.t1.partitions = get_bits(gb, 5);
497
498             av_dlog(NULL, " %d.floor: %d partitions \n",
499                     i, floor_setup->data.t1.partitions);
500
501             for (j = 0; j < floor_setup->data.t1.partitions; ++j) {
502                 floor_setup->data.t1.partition_class[j] = get_bits(gb, 4);
503                 if (floor_setup->data.t1.partition_class[j] > maximum_class)
504                     maximum_class = floor_setup->data.t1.partition_class[j];
505
506                 av_dlog(NULL, " %d. floor %d partition class %d \n",
507                         i, j, floor_setup->data.t1.partition_class[j]);
508
509             }
510
511             av_dlog(NULL, " maximum class %d \n", maximum_class);
512
513             for (j = 0; j <= maximum_class; ++j) {
514                 floor_setup->data.t1.class_dimensions[j] = get_bits(gb, 3) + 1;
515                 floor_setup->data.t1.class_subclasses[j] = get_bits(gb, 2);
516
517                 av_dlog(NULL, " %d floor %d class dim: %d subclasses %d \n", i, j,
518                         floor_setup->data.t1.class_dimensions[j],
519                         floor_setup->data.t1.class_subclasses[j]);
520
521                 if (floor_setup->data.t1.class_subclasses[j]) {
522                     GET_VALIDATED_INDEX(floor_setup->data.t1.class_masterbook[j], 8, vc->codebook_count)
523
524                     av_dlog(NULL, "   masterbook: %d \n", floor_setup->data.t1.class_masterbook[j]);
525                 }
526
527                 for (k = 0; k < (1 << floor_setup->data.t1.class_subclasses[j]); ++k) {
528                     int16_t bits = get_bits(gb, 8) - 1;
529                     if (bits != -1)
530                         VALIDATE_INDEX(bits, vc->codebook_count)
531                     floor_setup->data.t1.subclass_books[j][k] = bits;
532
533                     av_dlog(NULL, "    book %d. : %d \n", k, floor_setup->data.t1.subclass_books[j][k]);
534                 }
535             }
536
537             floor_setup->data.t1.multiplier = get_bits(gb, 2) + 1;
538             floor_setup->data.t1.x_list_dim = 2;
539
540             for (j = 0; j < floor_setup->data.t1.partitions; ++j)
541                 floor_setup->data.t1.x_list_dim+=floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]];
542
543             floor_setup->data.t1.list = av_mallocz(floor_setup->data.t1.x_list_dim *
544                                                    sizeof(*floor_setup->data.t1.list));
545
546
547             rangebits = get_bits(gb, 4);
548             rangemax = (1 << rangebits);
549             if (rangemax > vc->blocksize[1] / 2) {
550                 av_log(vc->avccontext, AV_LOG_ERROR,
551                        "Floor value is too large for blocksize: %u (%"PRIu32")\n",
552                        rangemax, vc->blocksize[1] / 2);
553                 return -1;
554             }
555             floor_setup->data.t1.list[0].x = 0;
556             floor_setup->data.t1.list[1].x = rangemax;
557
558             for (j = 0; j < floor_setup->data.t1.partitions; ++j) {
559                 for (k = 0; k < floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]]; ++k, ++floor1_values) {
560                     floor_setup->data.t1.list[floor1_values].x = get_bits(gb, rangebits);
561
562                     av_dlog(NULL, " %u. floor1 Y coord. %d\n", floor1_values,
563                             floor_setup->data.t1.list[floor1_values].x);
564                 }
565             }
566
567 // Precalculate order of x coordinates - needed for decode
568             ff_vorbis_ready_floor1_list(floor_setup->data.t1.list, floor_setup->data.t1.x_list_dim);
569         } else if (floor_setup->floor_type == 0) {
570             unsigned max_codebook_dim = 0;
571
572             floor_setup->decode = vorbis_floor0_decode;
573
574             floor_setup->data.t0.order          = get_bits(gb,  8);
575             floor_setup->data.t0.rate           = get_bits(gb, 16);
576             floor_setup->data.t0.bark_map_size  = get_bits(gb, 16);
577             floor_setup->data.t0.amplitude_bits = get_bits(gb,  6);
578             /* zero would result in a div by zero later *
579              * 2^0 - 1 == 0                             */
580             if (floor_setup->data.t0.amplitude_bits == 0) {
581                 av_log(vc->avccontext, AV_LOG_ERROR,
582                        "Floor 0 amplitude bits is 0.\n");
583                 return -1;
584             }
585             floor_setup->data.t0.amplitude_offset = get_bits(gb, 8);
586             floor_setup->data.t0.num_books        = get_bits(gb, 4) + 1;
587
588             /* allocate mem for booklist */
589             floor_setup->data.t0.book_list =
590                 av_malloc(floor_setup->data.t0.num_books);
591             if (!floor_setup->data.t0.book_list)
592                 return -1;
593             /* read book indexes */
594             {
595                 int idx;
596                 unsigned book_idx;
597                 for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {
598                     GET_VALIDATED_INDEX(book_idx, 8, vc->codebook_count)
599                     floor_setup->data.t0.book_list[idx] = book_idx;
600                     if (vc->codebooks[book_idx].dimensions > max_codebook_dim)
601                         max_codebook_dim = vc->codebooks[book_idx].dimensions;
602                 }
603             }
604
605             create_map(vc, i);
606
607             /* codebook dim is for padding if codebook dim doesn't *
608              * divide order+1 then we need to read more data       */
609             floor_setup->data.t0.lsp =
610                 av_malloc((floor_setup->data.t0.order + 1 + max_codebook_dim)
611                           * sizeof(*floor_setup->data.t0.lsp));
612             if (!floor_setup->data.t0.lsp)
613                 return -1;
614
615             /* debug output parsed headers */
616             av_dlog(NULL, "floor0 order: %u\n", floor_setup->data.t0.order);
617             av_dlog(NULL, "floor0 rate: %u\n", floor_setup->data.t0.rate);
618             av_dlog(NULL, "floor0 bark map size: %u\n",
619                     floor_setup->data.t0.bark_map_size);
620             av_dlog(NULL, "floor0 amplitude bits: %u\n",
621                     floor_setup->data.t0.amplitude_bits);
622             av_dlog(NULL, "floor0 amplitude offset: %u\n",
623                     floor_setup->data.t0.amplitude_offset);
624             av_dlog(NULL, "floor0 number of books: %u\n",
625                     floor_setup->data.t0.num_books);
626             av_dlog(NULL, "floor0 book list pointer: %p\n",
627                     floor_setup->data.t0.book_list);
628             {
629                 int idx;
630                 for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {
631                     av_dlog(NULL, "  Book %d: %u\n", idx + 1,
632                             floor_setup->data.t0.book_list[idx]);
633                 }
634             }
635         } else {
636             av_log(vc->avccontext, AV_LOG_ERROR, "Invalid floor type!\n");
637             return -1;
638         }
639     }
640     return 0;
641 }
642
643 // Process residues part
644
645 static int vorbis_parse_setup_hdr_residues(vorbis_context *vc)
646 {
647     GetBitContext *gb = &vc->gb;
648     unsigned i, j, k;
649
650     vc->residue_count = get_bits(gb, 6)+1;
651     vc->residues      = av_mallocz(vc->residue_count * sizeof(*vc->residues));
652
653     av_dlog(NULL, " There are %d residues. \n", vc->residue_count);
654
655     for (i = 0; i < vc->residue_count; ++i) {
656         vorbis_residue *res_setup = &vc->residues[i];
657         uint8_t cascade[64];
658         unsigned high_bits, low_bits;
659
660         res_setup->type = get_bits(gb, 16);
661
662         av_dlog(NULL, " %u. residue type %d\n", i, res_setup->type);
663
664         res_setup->begin          = get_bits(gb, 24);
665         res_setup->end            = get_bits(gb, 24);
666         res_setup->partition_size = get_bits(gb, 24) + 1;
667         /* Validations to prevent a buffer overflow later. */
668         if (res_setup->begin>res_setup->end ||
669             res_setup->end > vc->avccontext->channels * vc->blocksize[1] / 2 ||
670             (res_setup->end-res_setup->begin) / res_setup->partition_size > V_MAX_PARTITIONS) {
671             av_log(vc->avccontext, AV_LOG_ERROR,
672                    "partition out of bounds: type, begin, end, size, blocksize: %"PRIu16", %"PRIu32", %"PRIu32", %u, %"PRIu32"\n",
673                    res_setup->type, res_setup->begin, res_setup->end,
674                    res_setup->partition_size, vc->blocksize[1] / 2);
675             return -1;
676         }
677
678         res_setup->classifications = get_bits(gb, 6) + 1;
679         GET_VALIDATED_INDEX(res_setup->classbook, 8, vc->codebook_count)
680
681         res_setup->ptns_to_read =
682             (res_setup->end - res_setup->begin) / res_setup->partition_size;
683         res_setup->classifs = av_malloc(res_setup->ptns_to_read *
684                                         vc->audio_channels *
685                                         sizeof(*res_setup->classifs));
686         if (!res_setup->classifs)
687             return AVERROR(ENOMEM);
688
689         av_dlog(NULL, "    begin %d end %d part.size %d classif.s %d classbook %d \n",
690                 res_setup->begin, res_setup->end, res_setup->partition_size,
691                 res_setup->classifications, res_setup->classbook);
692
693         for (j = 0; j < res_setup->classifications; ++j) {
694             high_bits = 0;
695             low_bits  = get_bits(gb, 3);
696             if (get_bits1(gb))
697                 high_bits = get_bits(gb, 5);
698             cascade[j] = (high_bits << 3) + low_bits;
699
700             av_dlog(NULL, "     %u class cascade depth: %d\n", j, ilog(cascade[j]));
701         }
702
703         res_setup->maxpass = 0;
704         for (j = 0; j < res_setup->classifications; ++j) {
705             for (k = 0; k < 8; ++k) {
706                 if (cascade[j]&(1 << k)) {
707                     GET_VALIDATED_INDEX(res_setup->books[j][k], 8, vc->codebook_count)
708
709                     av_dlog(NULL, "     %u class cascade depth %u book: %d\n",
710                             j, k, res_setup->books[j][k]);
711
712                     if (k>res_setup->maxpass)
713                         res_setup->maxpass = k;
714                 } else {
715                     res_setup->books[j][k] = -1;
716                 }
717             }
718         }
719     }
720     return 0;
721 }
722
723 // Process mappings part
724
725 static int vorbis_parse_setup_hdr_mappings(vorbis_context *vc)
726 {
727     GetBitContext *gb = &vc->gb;
728     unsigned i, j;
729
730     vc->mapping_count = get_bits(gb, 6)+1;
731     vc->mappings      = av_mallocz(vc->mapping_count * sizeof(*vc->mappings));
732
733     av_dlog(NULL, " There are %d mappings. \n", vc->mapping_count);
734
735     for (i = 0; i < vc->mapping_count; ++i) {
736         vorbis_mapping *mapping_setup = &vc->mappings[i];
737
738         if (get_bits(gb, 16)) {
739             av_log(vc->avccontext, AV_LOG_ERROR, "Other mappings than type 0 are not compliant with the Vorbis I specification. \n");
740             return -1;
741         }
742         if (get_bits1(gb)) {
743             mapping_setup->submaps = get_bits(gb, 4) + 1;
744         } else {
745             mapping_setup->submaps = 1;
746         }
747
748         if (get_bits1(gb)) {
749             mapping_setup->coupling_steps = get_bits(gb, 8) + 1;
750             mapping_setup->magnitude      = av_mallocz(mapping_setup->coupling_steps *
751                                                        sizeof(*mapping_setup->magnitude));
752             mapping_setup->angle          = av_mallocz(mapping_setup->coupling_steps *
753                                                        sizeof(*mapping_setup->angle));
754             for (j = 0; j < mapping_setup->coupling_steps; ++j) {
755                 GET_VALIDATED_INDEX(mapping_setup->magnitude[j], ilog(vc->audio_channels - 1), vc->audio_channels)
756                 GET_VALIDATED_INDEX(mapping_setup->angle[j],     ilog(vc->audio_channels - 1), vc->audio_channels)
757             }
758         } else {
759             mapping_setup->coupling_steps = 0;
760         }
761
762         av_dlog(NULL, "   %u mapping coupling steps: %d\n",
763                 i, mapping_setup->coupling_steps);
764
765         if (get_bits(gb, 2)) {
766             av_log(vc->avccontext, AV_LOG_ERROR, "%u. mapping setup data invalid.\n", i);
767             return -1; // following spec.
768         }
769
770         if (mapping_setup->submaps>1) {
771             mapping_setup->mux = av_mallocz(vc->audio_channels *
772                                             sizeof(*mapping_setup->mux));
773             for (j = 0; j < vc->audio_channels; ++j)
774                 mapping_setup->mux[j] = get_bits(gb, 4);
775         }
776
777         for (j = 0; j < mapping_setup->submaps; ++j) {
778             skip_bits(gb, 8); // FIXME check?
779             GET_VALIDATED_INDEX(mapping_setup->submap_floor[j],   8, vc->floor_count)
780             GET_VALIDATED_INDEX(mapping_setup->submap_residue[j], 8, vc->residue_count)
781
782             av_dlog(NULL, "   %u mapping %u submap : floor %d, residue %d\n", i, j,
783                     mapping_setup->submap_floor[j],
784                     mapping_setup->submap_residue[j]);
785         }
786     }
787     return 0;
788 }
789
790 // Process modes part
791
792 static void create_map(vorbis_context *vc, unsigned floor_number)
793 {
794     vorbis_floor *floors = vc->floors;
795     vorbis_floor0 *vf;
796     int idx;
797     int blockflag, n;
798     int32_t *map;
799
800     for (blockflag = 0; blockflag < 2; ++blockflag) {
801         n = vc->blocksize[blockflag] / 2;
802         floors[floor_number].data.t0.map[blockflag] =
803             av_malloc((n + 1) * sizeof(int32_t)); // n + sentinel
804
805         map =  floors[floor_number].data.t0.map[blockflag];
806         vf  = &floors[floor_number].data.t0;
807
808         for (idx = 0; idx < n; ++idx) {
809             map[idx] = floor(BARK((vf->rate * idx) / (2.0f * n)) *
810                              ((vf->bark_map_size) /
811                               BARK(vf->rate / 2.0f)));
812             if (vf->bark_map_size-1 < map[idx])
813                 map[idx] = vf->bark_map_size - 1;
814         }
815         map[n] = -1;
816         vf->map_size[blockflag] = n;
817     }
818
819     for (idx = 0; idx <= n; ++idx) {
820         av_dlog(NULL, "floor0 map: map at pos %d is %d\n", idx, map[idx]);
821     }
822 }
823
824 static int vorbis_parse_setup_hdr_modes(vorbis_context *vc)
825 {
826     GetBitContext *gb = &vc->gb;
827     unsigned i;
828
829     vc->mode_count = get_bits(gb, 6) + 1;
830     vc->modes      = av_mallocz(vc->mode_count * sizeof(*vc->modes));
831
832     av_dlog(NULL, " There are %d modes.\n", vc->mode_count);
833
834     for (i = 0; i < vc->mode_count; ++i) {
835         vorbis_mode *mode_setup = &vc->modes[i];
836
837         mode_setup->blockflag     = get_bits1(gb);
838         mode_setup->windowtype    = get_bits(gb, 16); //FIXME check
839         mode_setup->transformtype = get_bits(gb, 16); //FIXME check
840         GET_VALIDATED_INDEX(mode_setup->mapping, 8, vc->mapping_count);
841
842         av_dlog(NULL, " %u mode: blockflag %d, windowtype %d, transformtype %d, mapping %d\n",
843                 i, mode_setup->blockflag, mode_setup->windowtype,
844                 mode_setup->transformtype, mode_setup->mapping);
845     }
846     return 0;
847 }
848
849 // Process the whole setup header using the functions above
850
851 static int vorbis_parse_setup_hdr(vorbis_context *vc)
852 {
853     GetBitContext *gb = &vc->gb;
854
855     if ((get_bits(gb, 8) != 'v') || (get_bits(gb, 8) != 'o') ||
856         (get_bits(gb, 8) != 'r') || (get_bits(gb, 8) != 'b') ||
857         (get_bits(gb, 8) != 'i') || (get_bits(gb, 8) != 's')) {
858         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (no vorbis signature). \n");
859         return -1;
860     }
861
862     if (vorbis_parse_setup_hdr_codebooks(vc)) {
863         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (codebooks). \n");
864         return -2;
865     }
866     if (vorbis_parse_setup_hdr_tdtransforms(vc)) {
867         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (time domain transforms). \n");
868         return -3;
869     }
870     if (vorbis_parse_setup_hdr_floors(vc)) {
871         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (floors). \n");
872         return -4;
873     }
874     if (vorbis_parse_setup_hdr_residues(vc)) {
875         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (residues). \n");
876         return -5;
877     }
878     if (vorbis_parse_setup_hdr_mappings(vc)) {
879         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (mappings). \n");
880         return -6;
881     }
882     if (vorbis_parse_setup_hdr_modes(vc)) {
883         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (modes). \n");
884         return -7;
885     }
886     if (!get_bits1(gb)) {
887         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (framing flag). \n");
888         return -8; // framing flag bit unset error
889     }
890
891     return 0;
892 }
893
894 // Process the identification header
895
896 static int vorbis_parse_id_hdr(vorbis_context *vc)
897 {
898     GetBitContext *gb = &vc->gb;
899     unsigned bl0, bl1;
900
901     if ((get_bits(gb, 8) != 'v') || (get_bits(gb, 8) != 'o') ||
902         (get_bits(gb, 8) != 'r') || (get_bits(gb, 8) != 'b') ||
903         (get_bits(gb, 8) != 'i') || (get_bits(gb, 8) != 's')) {
904         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (no vorbis signature). \n");
905         return -1;
906     }
907
908     vc->version        = get_bits_long(gb, 32);    //FIXME check 0
909     vc->audio_channels = get_bits(gb, 8);
910     if (vc->audio_channels <= 0) {
911         av_log(vc->avccontext, AV_LOG_ERROR, "Invalid number of channels\n");
912         return -1;
913     }
914     vc->audio_samplerate = get_bits_long(gb, 32);
915     if (vc->audio_samplerate <= 0) {
916         av_log(vc->avccontext, AV_LOG_ERROR, "Invalid samplerate\n");
917         return -1;
918     }
919     vc->bitrate_maximum = get_bits_long(gb, 32);
920     vc->bitrate_nominal = get_bits_long(gb, 32);
921     vc->bitrate_minimum = get_bits_long(gb, 32);
922     bl0 = get_bits(gb, 4);
923     bl1 = get_bits(gb, 4);
924     vc->blocksize[0] = (1 << bl0);
925     vc->blocksize[1] = (1 << bl1);
926     if (bl0 > 13 || bl0 < 6 || bl1 > 13 || bl1 < 6 || bl1 < bl0) {
927         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (illegal blocksize). \n");
928         return -3;
929     }
930     // output format int16
931     if (vc->blocksize[1] / 2 * vc->audio_channels * 2 > AVCODEC_MAX_AUDIO_FRAME_SIZE) {
932         av_log(vc->avccontext, AV_LOG_ERROR, "Vorbis channel count makes "
933                "output packets too large.\n");
934         return -4;
935     }
936     vc->win[0] = ff_vorbis_vwin[bl0 - 6];
937     vc->win[1] = ff_vorbis_vwin[bl1 - 6];
938
939     if ((get_bits1(gb)) == 0) {
940         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (framing flag not set). \n");
941         return -2;
942     }
943
944     vc->channel_residues =  av_malloc((vc->blocksize[1]  / 2) * vc->audio_channels * sizeof(*vc->channel_residues));
945     vc->channel_floors   =  av_malloc((vc->blocksize[1]  / 2) * vc->audio_channels * sizeof(*vc->channel_floors));
946     vc->saved            =  av_mallocz((vc->blocksize[1] / 4) * vc->audio_channels * sizeof(*vc->saved));
947     vc->previous_window  = 0;
948
949     ff_mdct_init(&vc->mdct[0], bl0, 1, -vc->scale_bias);
950     ff_mdct_init(&vc->mdct[1], bl1, 1, -vc->scale_bias);
951
952     av_dlog(NULL, " vorbis version %d \n audio_channels %d \n audio_samplerate %d \n bitrate_max %d \n bitrate_nom %d \n bitrate_min %d \n blk_0 %d blk_1 %d \n ",
953             vc->version, vc->audio_channels, vc->audio_samplerate, vc->bitrate_maximum, vc->bitrate_nominal, vc->bitrate_minimum, vc->blocksize[0], vc->blocksize[1]);
954
955 /*
956     BLK = vc->blocksize[0];
957     for (i = 0; i < BLK / 2; ++i) {
958         vc->win[0][i] = sin(0.5*3.14159265358*(sin(((float)i + 0.5) / (float)BLK*3.14159265358))*(sin(((float)i + 0.5) / (float)BLK*3.14159265358)));
959     }
960 */
961
962     return 0;
963 }
964
965 // Process the extradata using the functions above (identification header, setup header)
966
967 static av_cold int vorbis_decode_init(AVCodecContext *avccontext)
968 {
969     vorbis_context *vc = avccontext->priv_data ;
970     uint8_t *headers   = avccontext->extradata;
971     int headers_len    = avccontext->extradata_size;
972     uint8_t *header_start[3];
973     int header_len[3];
974     GetBitContext *gb = &(vc->gb);
975     int hdr_type;
976
977     vc->avccontext = avccontext;
978     dsputil_init(&vc->dsp, avccontext);
979     ff_fmt_convert_init(&vc->fmt_conv, avccontext);
980
981     if (avccontext->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
982         avccontext->sample_fmt = AV_SAMPLE_FMT_FLT;
983         vc->scale_bias = 1.0f;
984     } else {
985         avccontext->sample_fmt = AV_SAMPLE_FMT_S16;
986         vc->scale_bias = 32768.0f;
987     }
988
989     if (!headers_len) {
990         av_log(avccontext, AV_LOG_ERROR, "Extradata missing.\n");
991         return -1;
992     }
993
994     if (ff_split_xiph_headers(headers, headers_len, 30, header_start, header_len) < 0) {
995         av_log(avccontext, AV_LOG_ERROR, "Extradata corrupt.\n");
996         return -1;
997     }
998
999     init_get_bits(gb, header_start[0], header_len[0]*8);
1000     hdr_type = get_bits(gb, 8);
1001     if (hdr_type != 1) {
1002         av_log(avccontext, AV_LOG_ERROR, "First header is not the id header.\n");
1003         return -1;
1004     }
1005     if (vorbis_parse_id_hdr(vc)) {
1006         av_log(avccontext, AV_LOG_ERROR, "Id header corrupt.\n");
1007         vorbis_free(vc);
1008         return -1;
1009     }
1010
1011     init_get_bits(gb, header_start[2], header_len[2]*8);
1012     hdr_type = get_bits(gb, 8);
1013     if (hdr_type != 5) {
1014         av_log(avccontext, AV_LOG_ERROR, "Third header is not the setup header.\n");
1015         vorbis_free(vc);
1016         return -1;
1017     }
1018     if (vorbis_parse_setup_hdr(vc)) {
1019         av_log(avccontext, AV_LOG_ERROR, "Setup header corrupt.\n");
1020         vorbis_free(vc);
1021         return -1;
1022     }
1023
1024     if (vc->audio_channels > 8)
1025         avccontext->channel_layout = 0;
1026     else
1027         avccontext->channel_layout = ff_vorbis_channel_layouts[vc->audio_channels - 1];
1028
1029     avccontext->channels    = vc->audio_channels;
1030     avccontext->sample_rate = vc->audio_samplerate;
1031     avccontext->frame_size  = FFMIN(vc->blocksize[0], vc->blocksize[1]) >> 2;
1032
1033     return 0 ;
1034 }
1035
1036 // Decode audiopackets -------------------------------------------------
1037
1038 // Read and decode floor
1039
1040 static int vorbis_floor0_decode(vorbis_context *vc,
1041                                 vorbis_floor_data *vfu, float *vec)
1042 {
1043     vorbis_floor0 *vf = &vfu->t0;
1044     float *lsp = vf->lsp;
1045     unsigned amplitude, book_idx;
1046     unsigned blockflag = vc->modes[vc->mode_number].blockflag;
1047
1048     amplitude = get_bits(&vc->gb, vf->amplitude_bits);
1049     if (amplitude > 0) {
1050         float last = 0;
1051         unsigned idx, lsp_len = 0;
1052         vorbis_codebook codebook;
1053
1054         book_idx = get_bits(&vc->gb, ilog(vf->num_books));
1055         if (book_idx >= vf->num_books) {
1056             av_log(vc->avccontext, AV_LOG_ERROR,
1057                     "floor0 dec: booknumber too high!\n");
1058             book_idx =  0;
1059         }
1060         av_dlog(NULL, "floor0 dec: booknumber: %u\n", book_idx);
1061         codebook = vc->codebooks[vf->book_list[book_idx]];
1062         /* Invalid codebook! */
1063         if (!codebook.codevectors)
1064             return -1;
1065
1066         while (lsp_len<vf->order) {
1067             int vec_off;
1068
1069             av_dlog(NULL, "floor0 dec: book dimension: %d\n", codebook.dimensions);
1070             av_dlog(NULL, "floor0 dec: maximum depth: %d\n", codebook.maxdepth);
1071             /* read temp vector */
1072             vec_off = get_vlc2(&vc->gb, codebook.vlc.table,
1073                                codebook.nb_bits, codebook.maxdepth)
1074                       * codebook.dimensions;
1075             av_dlog(NULL, "floor0 dec: vector offset: %d\n", vec_off);
1076             /* copy each vector component and add last to it */
1077             for (idx = 0; idx < codebook.dimensions; ++idx)
1078                 lsp[lsp_len+idx] = codebook.codevectors[vec_off+idx] + last;
1079             last = lsp[lsp_len+idx-1]; /* set last to last vector component */
1080
1081             lsp_len += codebook.dimensions;
1082         }
1083         /* DEBUG: output lsp coeffs */
1084         {
1085             int idx;
1086             for (idx = 0; idx < lsp_len; ++idx)
1087                 av_dlog(NULL, "floor0 dec: coeff at %d is %f\n", idx, lsp[idx]);
1088         }
1089
1090         /* synthesize floor output vector */
1091         {
1092             int i;
1093             int order = vf->order;
1094             float wstep = M_PI / vf->bark_map_size;
1095
1096             for (i = 0; i < order; i++)
1097                 lsp[i] = 2.0f * cos(lsp[i]);
1098
1099             av_dlog(NULL, "floor0 synth: map_size = %"PRIu32"; m = %d; wstep = %f\n",
1100                     vf->map_size[blockflag], order, wstep);
1101
1102             i = 0;
1103             while (i < vf->map_size[blockflag]) {
1104                 int j, iter_cond = vf->map[blockflag][i];
1105                 float p = 0.5f;
1106                 float q = 0.5f;
1107                 float two_cos_w = 2.0f * cos(wstep * iter_cond); // needed all times
1108
1109                 /* similar part for the q and p products */
1110                 for (j = 0; j + 1 < order; j += 2) {
1111                     q *= lsp[j]     - two_cos_w;
1112                     p *= lsp[j + 1] - two_cos_w;
1113                 }
1114                 if (j == order) { // even order
1115                     p *= p * (2.0f - two_cos_w);
1116                     q *= q * (2.0f + two_cos_w);
1117                 } else { // odd order
1118                     q *= two_cos_w-lsp[j]; // one more time for q
1119
1120                     /* final step and square */
1121                     p *= p * (4.f - two_cos_w * two_cos_w);
1122                     q *= q;
1123                 }
1124
1125                 /* calculate linear floor value */
1126                 q = exp((((amplitude*vf->amplitude_offset) /
1127                           (((1 << vf->amplitude_bits) - 1) * sqrt(p + q)))
1128                          - vf->amplitude_offset) * .11512925f);
1129
1130                 /* fill vector */
1131                 do {
1132                     vec[i] = q; ++i;
1133                 } while (vf->map[blockflag][i] == iter_cond);
1134             }
1135         }
1136     } else {
1137         /* this channel is unused */
1138         return 1;
1139     }
1140
1141     av_dlog(NULL, " Floor0 decoded\n");
1142
1143     return 0;
1144 }
1145
1146 static int vorbis_floor1_decode(vorbis_context *vc,
1147                                 vorbis_floor_data *vfu, float *vec)
1148 {
1149     vorbis_floor1 *vf = &vfu->t1;
1150     GetBitContext *gb = &vc->gb;
1151     uint16_t range_v[4] = { 256, 128, 86, 64 };
1152     unsigned range = range_v[vf->multiplier - 1];
1153     uint16_t floor1_Y[258];
1154     uint16_t floor1_Y_final[258];
1155     int floor1_flag[258];
1156     unsigned partition_class, cdim, cbits, csub, cval, offset, i, j;
1157     int book, adx, ady, dy, off, predicted, err;
1158
1159
1160     if (!get_bits1(gb)) // silence
1161         return 1;
1162
1163 // Read values (or differences) for the floor's points
1164
1165     floor1_Y[0] = get_bits(gb, ilog(range - 1));
1166     floor1_Y[1] = get_bits(gb, ilog(range - 1));
1167
1168     av_dlog(NULL, "floor 0 Y %d floor 1 Y %d \n", floor1_Y[0], floor1_Y[1]);
1169
1170     offset = 2;
1171     for (i = 0; i < vf->partitions; ++i) {
1172         partition_class = vf->partition_class[i];
1173         cdim   = vf->class_dimensions[partition_class];
1174         cbits  = vf->class_subclasses[partition_class];
1175         csub = (1 << cbits) - 1;
1176         cval = 0;
1177
1178         av_dlog(NULL, "Cbits %u\n", cbits);
1179
1180         if (cbits) // this reads all subclasses for this partition's class
1181             cval = get_vlc2(gb, vc->codebooks[vf->class_masterbook[partition_class]].vlc.table,
1182                             vc->codebooks[vf->class_masterbook[partition_class]].nb_bits, 3);
1183
1184         for (j = 0; j < cdim; ++j) {
1185             book = vf->subclass_books[partition_class][cval & csub];
1186
1187             av_dlog(NULL, "book %d Cbits %u cval %u  bits:%d\n",
1188                     book, cbits, cval, get_bits_count(gb));
1189
1190             cval = cval >> cbits;
1191             if (book > -1) {
1192                 floor1_Y[offset+j] = get_vlc2(gb, vc->codebooks[book].vlc.table,
1193                 vc->codebooks[book].nb_bits, 3);
1194             } else {
1195                 floor1_Y[offset+j] = 0;
1196             }
1197
1198             av_dlog(NULL, " floor(%d) = %d \n",
1199                     vf->list[offset+j].x, floor1_Y[offset+j]);
1200         }
1201         offset+=cdim;
1202     }
1203
1204 // Amplitude calculation from the differences
1205
1206     floor1_flag[0] = 1;
1207     floor1_flag[1] = 1;
1208     floor1_Y_final[0] = floor1_Y[0];
1209     floor1_Y_final[1] = floor1_Y[1];
1210
1211     for (i = 2; i < vf->x_list_dim; ++i) {
1212         unsigned val, highroom, lowroom, room, high_neigh_offs, low_neigh_offs;
1213
1214         low_neigh_offs  = vf->list[i].low;
1215         high_neigh_offs = vf->list[i].high;
1216         dy  = floor1_Y_final[high_neigh_offs] - floor1_Y_final[low_neigh_offs];  // render_point begin
1217         adx = vf->list[high_neigh_offs].x - vf->list[low_neigh_offs].x;
1218         ady = FFABS(dy);
1219         err = ady * (vf->list[i].x - vf->list[low_neigh_offs].x);
1220         off = err / adx;
1221         if (dy < 0) {
1222             predicted = floor1_Y_final[low_neigh_offs] - off;
1223         } else {
1224             predicted = floor1_Y_final[low_neigh_offs] + off;
1225         } // render_point end
1226
1227         val = floor1_Y[i];
1228         highroom = range-predicted;
1229         lowroom  = predicted;
1230         if (highroom < lowroom) {
1231             room = highroom * 2;
1232         } else {
1233             room = lowroom * 2;   // SPEC mispelling
1234         }
1235         if (val) {
1236             floor1_flag[low_neigh_offs]  = 1;
1237             floor1_flag[high_neigh_offs] = 1;
1238             floor1_flag[i]               = 1;
1239             if (val >= room) {
1240                 if (highroom > lowroom) {
1241                     floor1_Y_final[i] = val - lowroom + predicted;
1242                 } else {
1243                     floor1_Y_final[i] = predicted - val + highroom - 1;
1244                 }
1245             } else {
1246                 if (val & 1) {
1247                     floor1_Y_final[i] = predicted - (val + 1) / 2;
1248                 } else {
1249                     floor1_Y_final[i] = predicted + val / 2;
1250                 }
1251             }
1252         } else {
1253             floor1_flag[i]    = 0;
1254             floor1_Y_final[i] = predicted;
1255         }
1256
1257         av_dlog(NULL, " Decoded floor(%d) = %u / val %u\n",
1258                 vf->list[i].x, floor1_Y_final[i], val);
1259     }
1260
1261 // Curve synth - connect the calculated dots and convert from dB scale FIXME optimize ?
1262
1263     ff_vorbis_floor1_render_list(vf->list, vf->x_list_dim, floor1_Y_final, floor1_flag, vf->multiplier, vec, vf->list[1].x);
1264
1265     av_dlog(NULL, " Floor decoded\n");
1266
1267     return 0;
1268 }
1269
1270 // Read and decode residue
1271
1272 static av_always_inline int vorbis_residue_decode_internal(vorbis_context *vc,
1273                                                            vorbis_residue *vr,
1274                                                            unsigned ch,
1275                                                            uint8_t *do_not_decode,
1276                                                            float *vec,
1277                                                            unsigned vlen,
1278                                                            int vr_type)
1279 {
1280     GetBitContext *gb = &vc->gb;
1281     unsigned c_p_c        = vc->codebooks[vr->classbook].dimensions;
1282     unsigned ptns_to_read = vr->ptns_to_read;
1283     uint8_t *classifs = vr->classifs;
1284     unsigned pass, ch_used, i, j, k, l;
1285
1286     if (vr_type == 2) {
1287         for (j = 1; j < ch; ++j)
1288             do_not_decode[0] &= do_not_decode[j];  // FIXME - clobbering input
1289         if (do_not_decode[0])
1290             return 0;
1291         ch_used = 1;
1292     } else {
1293         ch_used = ch;
1294     }
1295
1296     av_dlog(NULL, " residue type 0/1/2 decode begin, ch: %d  cpc %d  \n", ch, c_p_c);
1297
1298     for (pass = 0; pass <= vr->maxpass; ++pass) { // FIXME OPTIMIZE?
1299         uint16_t voffset, partition_count, j_times_ptns_to_read;
1300
1301         voffset = vr->begin;
1302         for (partition_count = 0; partition_count < ptns_to_read;) {  // SPEC        error
1303             if (!pass) {
1304                 unsigned inverse_class = ff_inverse[vr->classifications];
1305                 for (j_times_ptns_to_read = 0, j = 0; j < ch_used; ++j) {
1306                     if (!do_not_decode[j]) {
1307                         unsigned temp = get_vlc2(gb, vc->codebooks[vr->classbook].vlc.table,
1308                                                  vc->codebooks[vr->classbook].nb_bits, 3);
1309
1310                         av_dlog(NULL, "Classword: %u\n", temp);
1311
1312                         assert(vr->classifications > 1 && temp <= 65536); //needed for inverse[]
1313                         for (i = 0; i < c_p_c; ++i) {
1314                             unsigned temp2;
1315
1316                             temp2 = (((uint64_t)temp) * inverse_class) >> 32;
1317                             if (partition_count + c_p_c - 1 - i < ptns_to_read)
1318                                 classifs[j_times_ptns_to_read + partition_count + c_p_c - 1 - i] = temp - temp2 * vr->classifications;
1319                             temp = temp2;
1320                         }
1321                     }
1322                     j_times_ptns_to_read += ptns_to_read;
1323                 }
1324             }
1325             for (i = 0; (i < c_p_c) && (partition_count < ptns_to_read); ++i) {
1326                 for (j_times_ptns_to_read = 0, j = 0; j < ch_used; ++j) {
1327                     unsigned voffs;
1328
1329                     if (!do_not_decode[j]) {
1330                         unsigned vqclass = classifs[j_times_ptns_to_read + partition_count];
1331                         int vqbook  = vr->books[vqclass][pass];
1332
1333                         if (vqbook >= 0 && vc->codebooks[vqbook].codevectors) {
1334                             unsigned coffs;
1335                             unsigned dim  = vc->codebooks[vqbook].dimensions;
1336                             unsigned step = dim == 1 ? vr->partition_size
1337                                                      : FASTDIV(vr->partition_size, dim);
1338                             vorbis_codebook codebook = vc->codebooks[vqbook];
1339
1340                             if (vr_type == 0) {
1341
1342                                 voffs = voffset+j*vlen;
1343                                 for (k = 0; k < step; ++k) {
1344                                     coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1345                                     for (l = 0; l < dim; ++l)
1346                                         vec[voffs + k + l * step] += codebook.codevectors[coffs + l];  // FPMATH
1347                                 }
1348                             } else if (vr_type == 1) {
1349                                 voffs = voffset + j * vlen;
1350                                 for (k = 0; k < step; ++k) {
1351                                     coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1352                                     for (l = 0; l < dim; ++l, ++voffs) {
1353                                         vec[voffs]+=codebook.codevectors[coffs+l];  // FPMATH
1354
1355                                         av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d  \n",
1356                                                 pass, voffs, vec[voffs], codebook.codevectors[coffs+l], coffs);
1357                                     }
1358                                 }
1359                             } else if (vr_type == 2 && ch == 2 && (voffset & 1) == 0 && (dim & 1) == 0) { // most frequent case optimized
1360                                 voffs = voffset >> 1;
1361
1362                                 if (dim == 2) {
1363                                     for (k = 0; k < step; ++k) {
1364                                         coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 2;
1365                                         vec[voffs + k       ] += codebook.codevectors[coffs    ];  // FPMATH
1366                                         vec[voffs + k + vlen] += codebook.codevectors[coffs + 1];  // FPMATH
1367                                     }
1368                                 } else if (dim == 4) {
1369                                     for (k = 0; k < step; ++k, voffs += 2) {
1370                                         coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 4;
1371                                         vec[voffs           ] += codebook.codevectors[coffs    ];  // FPMATH
1372                                         vec[voffs + 1       ] += codebook.codevectors[coffs + 2];  // FPMATH
1373                                         vec[voffs + vlen    ] += codebook.codevectors[coffs + 1];  // FPMATH
1374                                         vec[voffs + vlen + 1] += codebook.codevectors[coffs + 3];  // FPMATH
1375                                     }
1376                                 } else
1377                                 for (k = 0; k < step; ++k) {
1378                                     coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1379                                     for (l = 0; l < dim; l += 2, voffs++) {
1380                                         vec[voffs       ] += codebook.codevectors[coffs + l    ];  // FPMATH
1381                                         vec[voffs + vlen] += codebook.codevectors[coffs + l + 1];  // FPMATH
1382
1383                                         av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d+%d  \n",
1384                                                 pass, voffset / ch + (voffs % ch) * vlen,
1385                                                 vec[voffset / ch + (voffs % ch) * vlen],
1386                                                 codebook.codevectors[coffs + l], coffs, l);
1387                                     }
1388                                 }
1389
1390                             } else if (vr_type == 2) {
1391                                 voffs = voffset;
1392
1393                                 for (k = 0; k < step; ++k) {
1394                                     coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1395                                     for (l = 0; l < dim; ++l, ++voffs) {
1396                                         vec[voffs / ch + (voffs % ch) * vlen] += codebook.codevectors[coffs + l];  // FPMATH FIXME use if and counter instead of / and %
1397
1398                                         av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d+%d  \n",
1399                                                 pass, voffset / ch + (voffs % ch) * vlen,
1400                                                 vec[voffset / ch + (voffs % ch) * vlen],
1401                                                 codebook.codevectors[coffs + l], coffs, l);
1402                                     }
1403                                 }
1404                             }
1405                         }
1406                     }
1407                     j_times_ptns_to_read += ptns_to_read;
1408                 }
1409                 ++partition_count;
1410                 voffset += vr->partition_size;
1411             }
1412         }
1413     }
1414     return 0;
1415 }
1416
1417 static inline int vorbis_residue_decode(vorbis_context *vc, vorbis_residue *vr,
1418                                         unsigned ch,
1419                                         uint8_t *do_not_decode,
1420                                         float *vec, unsigned vlen)
1421 {
1422     if (vr->type == 2)
1423         return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 2);
1424     else if (vr->type == 1)
1425         return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 1);
1426     else if (vr->type == 0)
1427         return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 0);
1428     else {
1429         av_log(vc->avccontext, AV_LOG_ERROR, " Invalid residue type while residue decode?! \n");
1430         return -1;
1431     }
1432 }
1433
1434 void vorbis_inverse_coupling(float *mag, float *ang, int blocksize)
1435 {
1436     int i;
1437     for (i = 0;  i < blocksize;  i++) {
1438         if (mag[i] > 0.0) {
1439             if (ang[i] > 0.0) {
1440                 ang[i] = mag[i] - ang[i];
1441             } else {
1442                 float temp = ang[i];
1443                 ang[i]     = mag[i];
1444                 mag[i]    += temp;
1445             }
1446         } else {
1447             if (ang[i] > 0.0) {
1448                 ang[i] += mag[i];
1449             } else {
1450                 float temp = ang[i];
1451                 ang[i]     = mag[i];
1452                 mag[i]    -= temp;
1453             }
1454         }
1455     }
1456 }
1457
1458 // Decode the audio packet using the functions above
1459
1460 static int vorbis_parse_audio_packet(vorbis_context *vc)
1461 {
1462     GetBitContext *gb = &vc->gb;
1463     FFTContext *mdct;
1464     unsigned previous_window = vc->previous_window;
1465     unsigned mode_number, blockflag, blocksize;
1466     int i, j;
1467     uint8_t no_residue[255];
1468     uint8_t do_not_decode[255];
1469     vorbis_mapping *mapping;
1470     float *ch_res_ptr   = vc->channel_residues;
1471     float *ch_floor_ptr = vc->channel_floors;
1472     uint8_t res_chan[255];
1473     unsigned res_num = 0;
1474     int retlen  = 0;
1475
1476     if (get_bits1(gb)) {
1477         av_log(vc->avccontext, AV_LOG_ERROR, "Not a Vorbis I audio packet.\n");
1478         return -1; // packet type not audio
1479     }
1480
1481     if (vc->mode_count == 1) {
1482         mode_number = 0;
1483     } else {
1484         GET_VALIDATED_INDEX(mode_number, ilog(vc->mode_count-1), vc->mode_count)
1485     }
1486     vc->mode_number = mode_number;
1487     mapping = &vc->mappings[vc->modes[mode_number].mapping];
1488
1489     av_dlog(NULL, " Mode number: %u , mapping: %d , blocktype %d\n", mode_number,
1490             vc->modes[mode_number].mapping, vc->modes[mode_number].blockflag);
1491
1492     blockflag = vc->modes[mode_number].blockflag;
1493     blocksize = vc->blocksize[blockflag];
1494     if (blockflag)
1495         skip_bits(gb, 2); // previous_window, next_window
1496
1497     memset(ch_res_ptr,   0, sizeof(float) * vc->audio_channels * blocksize / 2); //FIXME can this be removed ?
1498     memset(ch_floor_ptr, 0, sizeof(float) * vc->audio_channels * blocksize / 2); //FIXME can this be removed ?
1499
1500 // Decode floor
1501
1502     for (i = 0; i < vc->audio_channels; ++i) {
1503         vorbis_floor *floor;
1504         int ret;
1505         if (mapping->submaps > 1) {
1506             floor = &vc->floors[mapping->submap_floor[mapping->mux[i]]];
1507         } else {
1508             floor = &vc->floors[mapping->submap_floor[0]];
1509         }
1510
1511         ret = floor->decode(vc, &floor->data, ch_floor_ptr);
1512
1513         if (ret < 0) {
1514             av_log(vc->avccontext, AV_LOG_ERROR, "Invalid codebook in vorbis_floor_decode.\n");
1515             return -1;
1516         }
1517         no_residue[i] = ret;
1518         ch_floor_ptr += blocksize / 2;
1519     }
1520
1521 // Nonzero vector propagate
1522
1523     for (i = mapping->coupling_steps - 1; i >= 0; --i) {
1524         if (!(no_residue[mapping->magnitude[i]] & no_residue[mapping->angle[i]])) {
1525             no_residue[mapping->magnitude[i]] = 0;
1526             no_residue[mapping->angle[i]]     = 0;
1527         }
1528     }
1529
1530 // Decode residue
1531
1532     for (i = 0; i < mapping->submaps; ++i) {
1533         vorbis_residue *residue;
1534         unsigned ch = 0;
1535
1536         for (j = 0; j < vc->audio_channels; ++j) {
1537             if ((mapping->submaps == 1) || (i == mapping->mux[j])) {
1538                 res_chan[j] = res_num;
1539                 if (no_residue[j]) {
1540                     do_not_decode[ch] = 1;
1541                 } else {
1542                     do_not_decode[ch] = 0;
1543                 }
1544                 ++ch;
1545                 ++res_num;
1546             }
1547         }
1548         residue = &vc->residues[mapping->submap_residue[i]];
1549         vorbis_residue_decode(vc, residue, ch, do_not_decode, ch_res_ptr, blocksize/2);
1550
1551         ch_res_ptr += ch * blocksize / 2;
1552     }
1553
1554 // Inverse coupling
1555
1556     for (i = mapping->coupling_steps - 1; i >= 0; --i) { //warning: i has to be signed
1557         float *mag, *ang;
1558
1559         mag = vc->channel_residues+res_chan[mapping->magnitude[i]] * blocksize / 2;
1560         ang = vc->channel_residues+res_chan[mapping->angle[i]]     * blocksize / 2;
1561         vc->dsp.vorbis_inverse_coupling(mag, ang, blocksize / 2);
1562     }
1563
1564 // Dotproduct, MDCT
1565
1566     mdct = &vc->mdct[blockflag];
1567
1568     for (j = vc->audio_channels-1;j >= 0; j--) {
1569         ch_floor_ptr = vc->channel_floors   + j           * blocksize / 2;
1570         ch_res_ptr   = vc->channel_residues + res_chan[j] * blocksize / 2;
1571         vc->dsp.vector_fmul(ch_floor_ptr, ch_floor_ptr, ch_res_ptr, blocksize / 2);
1572         mdct->imdct_half(mdct, ch_res_ptr, ch_floor_ptr);
1573     }
1574
1575 // Overlap/add, save data for next overlapping  FPMATH
1576
1577     retlen = (blocksize + vc->blocksize[previous_window]) / 4;
1578     for (j = 0; j < vc->audio_channels; j++) {
1579         unsigned bs0 = vc->blocksize[0];
1580         unsigned bs1 = vc->blocksize[1];
1581         float *residue    = vc->channel_residues + res_chan[j] * blocksize / 2;
1582         float *saved      = vc->saved + j * bs1 / 4;
1583         float *ret        = vc->channel_floors + j * retlen;
1584         float *buf        = residue;
1585         const float *win  = vc->win[blockflag & previous_window];
1586
1587         if (blockflag == previous_window) {
1588             vc->dsp.vector_fmul_window(ret, saved, buf, win, blocksize / 4);
1589         } else if (blockflag > previous_window) {
1590             vc->dsp.vector_fmul_window(ret, saved, buf, win, bs0 / 4);
1591             memcpy(ret+bs0/2, buf+bs0/4, ((bs1-bs0)/4) * sizeof(float));
1592         } else {
1593             memcpy(ret, saved, ((bs1 - bs0) / 4) * sizeof(float));
1594             vc->dsp.vector_fmul_window(ret + (bs1 - bs0) / 4, saved + (bs1 - bs0) / 4, buf, win, bs0 / 4);
1595         }
1596         memcpy(saved, buf + blocksize / 4, blocksize / 4 * sizeof(float));
1597     }
1598
1599     vc->previous_window = blockflag;
1600     return retlen;
1601 }
1602
1603 // Return the decoded audio packet through the standard api
1604
1605 static int vorbis_decode_frame(AVCodecContext *avccontext,
1606                                void *data, int *data_size,
1607                                AVPacket *avpkt)
1608 {
1609     const uint8_t *buf = avpkt->data;
1610     int buf_size       = avpkt->size;
1611     vorbis_context *vc = avccontext->priv_data ;
1612     GetBitContext *gb = &(vc->gb);
1613     const float *channel_ptrs[255];
1614     int i, len;
1615
1616     if (!buf_size)
1617         return 0;
1618
1619     av_dlog(NULL, "packet length %d \n", buf_size);
1620
1621     init_get_bits(gb, buf, buf_size*8);
1622
1623     len = vorbis_parse_audio_packet(vc);
1624
1625     if (len <= 0) {
1626         *data_size = 0;
1627         return buf_size;
1628     }
1629
1630     if (!vc->first_frame) {
1631         vc->first_frame = 1;
1632         *data_size = 0;
1633         return buf_size ;
1634     }
1635
1636     av_dlog(NULL, "parsed %d bytes %d bits, returned %d samples (*ch*bits) \n",
1637             get_bits_count(gb) / 8, get_bits_count(gb) % 8, len);
1638
1639     if (vc->audio_channels > 8) {
1640         for (i = 0; i < vc->audio_channels; i++)
1641             channel_ptrs[i] = vc->channel_floors + i * len;
1642     } else {
1643         for (i = 0; i < vc->audio_channels; i++)
1644             channel_ptrs[i] = vc->channel_floors +
1645                               len * ff_vorbis_channel_layout_offsets[vc->audio_channels - 1][i];
1646     }
1647
1648     if (avccontext->sample_fmt == AV_SAMPLE_FMT_FLT)
1649         vc->fmt_conv.float_interleave(data, channel_ptrs, len, vc->audio_channels);
1650     else
1651         vc->fmt_conv.float_to_int16_interleave(data, channel_ptrs, len,
1652                                                vc->audio_channels);
1653
1654     *data_size = len * vc->audio_channels *
1655                  av_get_bytes_per_sample(avccontext->sample_fmt);
1656
1657     return buf_size ;
1658 }
1659
1660 // Close decoder
1661
1662 static av_cold int vorbis_decode_close(AVCodecContext *avccontext)
1663 {
1664     vorbis_context *vc = avccontext->priv_data;
1665
1666     vorbis_free(vc);
1667
1668     return 0 ;
1669 }
1670
1671 AVCodec ff_vorbis_decoder = {
1672     .name           = "vorbis",
1673     .type           = AVMEDIA_TYPE_AUDIO,
1674     .id             = CODEC_ID_VORBIS,
1675     .priv_data_size = sizeof(vorbis_context),
1676     .init           = vorbis_decode_init,
1677     .close          = vorbis_decode_close,
1678     .decode         = vorbis_decode_frame,
1679     .long_name = NULL_IF_CONFIG_SMALL("Vorbis"),
1680     .channel_layouts = ff_vorbis_channel_layouts,
1681     .sample_fmts = (const enum AVSampleFormat[]) {
1682         AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
1683     },
1684 };
1685