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