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