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