]> git.sesse.net Git - ffmpeg/blob - libavcodec/vorbisdec.c
configure: fix libavutil.pc generation
[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 "avcodec.h"
35 #include "get_bits.h"
36 #include "dsputil.h"
37 #include "fft.h"
38 #include "fmtconvert.h"
39
40 #include "vorbis.h"
41 #include "xiph.h"
42
43 #define V_NB_BITS 8
44 #define V_NB_BITS2 11
45 #define V_MAX_VLCS (1 << 16)
46 #define V_MAX_PARTITIONS (1 << 20)
47
48 #undef NDEBUG
49 #include <assert.h>
50
51 typedef struct {
52     uint8_t      dimensions;
53     uint8_t      lookup_type;
54     uint8_t      maxdepth;
55     VLC          vlc;
56     float       *codevectors;
57     unsigned int nb_bits;
58 } vorbis_codebook;
59
60 typedef union  vorbis_floor_u  vorbis_floor_data;
61 typedef struct vorbis_floor0_s vorbis_floor0;
62 typedef struct vorbis_floor1_s vorbis_floor1;
63 struct vorbis_context_s;
64 typedef
65 int (* vorbis_floor_decode_func)
66     (struct vorbis_context_s *, vorbis_floor_data *, float *);
67 typedef struct {
68     uint8_t floor_type;
69     vorbis_floor_decode_func decode;
70     union vorbis_floor_u {
71         struct vorbis_floor0_s {
72             uint8_t       order;
73             uint16_t      rate;
74             uint16_t      bark_map_size;
75             int32_t      *map[2];
76             uint32_t      map_size[2];
77             uint8_t       amplitude_bits;
78             uint8_t       amplitude_offset;
79             uint8_t       num_books;
80             uint8_t      *book_list;
81             float        *lsp;
82         } t0;
83         struct vorbis_floor1_s {
84             uint8_t       partitions;
85             uint8_t       partition_class[32];
86             uint8_t       class_dimensions[16];
87             uint8_t       class_subclasses[16];
88             uint8_t       class_masterbook[16];
89             int16_t       subclass_books[16][8];
90             uint8_t       multiplier;
91             uint16_t      x_list_dim;
92             vorbis_floor1_entry *list;
93         } t1;
94     } data;
95 } vorbis_floor;
96
97 typedef struct {
98     uint16_t      type;
99     uint32_t      begin;
100     uint32_t      end;
101     unsigned      partition_size;
102     uint8_t       classifications;
103     uint8_t       classbook;
104     int16_t       books[64][8];
105     uint8_t       maxpass;
106     uint16_t      ptns_to_read;
107     uint8_t      *classifs;
108 } vorbis_residue;
109
110 typedef struct {
111     uint8_t       submaps;
112     uint16_t      coupling_steps;
113     uint8_t      *magnitude;
114     uint8_t      *angle;
115     uint8_t      *mux;
116     uint8_t       submap_floor[16];
117     uint8_t       submap_residue[16];
118 } vorbis_mapping;
119
120 typedef struct {
121     uint8_t       blockflag;
122     uint16_t      windowtype;
123     uint16_t      transformtype;
124     uint8_t       mapping;
125 } vorbis_mode;
126
127 typedef struct vorbis_context_s {
128     AVCodecContext *avccontext;
129     AVFrame frame;
130     GetBitContext gb;
131     DSPContext dsp;
132     AVFloatDSPContext fdsp;
133     FmtConvertContext fmt_conv;
134
135     FFTContext mdct[2];
136     uint8_t       first_frame;
137     uint32_t      version;
138     uint8_t       audio_channels;
139     uint32_t      audio_samplerate;
140     uint32_t      bitrate_maximum;
141     uint32_t      bitrate_nominal;
142     uint32_t      bitrate_minimum;
143     uint32_t      blocksize[2];
144     const float  *win[2];
145     uint16_t      codebook_count;
146     vorbis_codebook *codebooks;
147     uint8_t       floor_count;
148     vorbis_floor *floors;
149     uint8_t       residue_count;
150     vorbis_residue *residues;
151     uint8_t       mapping_count;
152     vorbis_mapping *mappings;
153     uint8_t       mode_count;
154     vorbis_mode  *modes;
155     uint8_t       mode_number; // mode number for the current packet
156     uint8_t       previous_window;
157     float        *channel_residues;
158     float        *channel_floors;
159     float        *saved;
160     float         scale_bias; // for float->int conversion
161 } vorbis_context;
162
163 /* Helper functions */
164
165 #define BARK(x) \
166     (13.1f * atan(0.00074f * (x)) + 2.24f * atan(1.85e-8f * (x) * (x)) + 1e-4f * (x))
167
168 static const char idx_err_str[] = "Index value %d out of range (0 - %d) for %s at %s:%i\n";
169 #define VALIDATE_INDEX(idx, limit) \
170     if (idx >= limit) {\
171         av_log(vc->avccontext, AV_LOG_ERROR,\
172                idx_err_str,\
173                (int)(idx), (int)(limit - 1), #idx, __FILE__, __LINE__);\
174         return AVERROR_INVALIDDATA;\
175     }
176 #define GET_VALIDATED_INDEX(idx, bits, limit) \
177     {\
178         idx = get_bits(gb, bits);\
179         VALIDATE_INDEX(idx, limit)\
180     }
181
182 static float vorbisfloat2float(unsigned val)
183 {
184     double mant = val & 0x1fffff;
185     long exp    = (val & 0x7fe00000L) >> 21;
186     if (val & 0x80000000)
187         mant = -mant;
188     return ldexp(mant, exp - 20 - 768);
189 }
190
191
192 // Free all allocated memory -----------------------------------------
193
194 static void vorbis_free(vorbis_context *vc)
195 {
196     int i;
197
198     av_freep(&vc->channel_residues);
199     av_freep(&vc->channel_floors);
200     av_freep(&vc->saved);
201
202     for (i = 0; i < vc->residue_count; i++)
203         av_free(vc->residues[i].classifs);
204     av_freep(&vc->residues);
205     av_freep(&vc->modes);
206
207     ff_mdct_end(&vc->mdct[0]);
208     ff_mdct_end(&vc->mdct[1]);
209
210     for (i = 0; i < vc->codebook_count; ++i) {
211         av_free(vc->codebooks[i].codevectors);
212         ff_free_vlc(&vc->codebooks[i].vlc);
213     }
214     av_freep(&vc->codebooks);
215
216     for (i = 0; i < vc->floor_count; ++i) {
217         if (vc->floors[i].floor_type == 0) {
218             av_free(vc->floors[i].data.t0.map[0]);
219             av_free(vc->floors[i].data.t0.map[1]);
220             av_free(vc->floors[i].data.t0.book_list);
221             av_free(vc->floors[i].data.t0.lsp);
222         } else {
223             av_free(vc->floors[i].data.t1.list);
224         }
225     }
226     av_freep(&vc->floors);
227
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             floor_setup->data.t0.amplitude_offset = get_bits(gb, 8);
605             floor_setup->data.t0.num_books        = get_bits(gb, 4) + 1;
606
607             /* allocate mem for booklist */
608             floor_setup->data.t0.book_list =
609                 av_malloc(floor_setup->data.t0.num_books);
610             if (!floor_setup->data.t0.book_list)
611                 return AVERROR(ENOMEM);
612             /* read book indexes */
613             {
614                 int idx;
615                 unsigned book_idx;
616                 for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {
617                     GET_VALIDATED_INDEX(book_idx, 8, vc->codebook_count)
618                     floor_setup->data.t0.book_list[idx] = book_idx;
619                     if (vc->codebooks[book_idx].dimensions > max_codebook_dim)
620                         max_codebook_dim = vc->codebooks[book_idx].dimensions;
621                 }
622             }
623
624             create_map(vc, i);
625
626             /* codebook dim is for padding if codebook dim doesn't *
627              * divide order+1 then we need to read more data       */
628             floor_setup->data.t0.lsp =
629                 av_malloc((floor_setup->data.t0.order + 1 + max_codebook_dim)
630                           * sizeof(*floor_setup->data.t0.lsp));
631             if (!floor_setup->data.t0.lsp)
632                 return AVERROR(ENOMEM);
633
634             /* debug output parsed headers */
635             av_dlog(NULL, "floor0 order: %u\n", floor_setup->data.t0.order);
636             av_dlog(NULL, "floor0 rate: %u\n", floor_setup->data.t0.rate);
637             av_dlog(NULL, "floor0 bark map size: %u\n",
638                     floor_setup->data.t0.bark_map_size);
639             av_dlog(NULL, "floor0 amplitude bits: %u\n",
640                     floor_setup->data.t0.amplitude_bits);
641             av_dlog(NULL, "floor0 amplitude offset: %u\n",
642                     floor_setup->data.t0.amplitude_offset);
643             av_dlog(NULL, "floor0 number of books: %u\n",
644                     floor_setup->data.t0.num_books);
645             av_dlog(NULL, "floor0 book list pointer: %p\n",
646                     floor_setup->data.t0.book_list);
647             {
648                 int idx;
649                 for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {
650                     av_dlog(NULL, "  Book %d: %u\n", idx + 1,
651                             floor_setup->data.t0.book_list[idx]);
652                 }
653             }
654         } else {
655             av_log(vc->avccontext, AV_LOG_ERROR, "Invalid floor type!\n");
656             return AVERROR_INVALIDDATA;
657         }
658     }
659     return 0;
660 }
661
662 // Process residues part
663
664 static int vorbis_parse_setup_hdr_residues(vorbis_context *vc)
665 {
666     GetBitContext *gb = &vc->gb;
667     unsigned i, j, k;
668
669     vc->residue_count = get_bits(gb, 6)+1;
670     vc->residues      = av_mallocz(vc->residue_count * sizeof(*vc->residues));
671
672     av_dlog(NULL, " There are %d residues. \n", vc->residue_count);
673
674     for (i = 0; i < vc->residue_count; ++i) {
675         vorbis_residue *res_setup = &vc->residues[i];
676         uint8_t cascade[64];
677         unsigned high_bits, low_bits;
678
679         res_setup->type = get_bits(gb, 16);
680
681         av_dlog(NULL, " %u. residue type %d\n", i, res_setup->type);
682
683         res_setup->begin          = get_bits(gb, 24);
684         res_setup->end            = get_bits(gb, 24);
685         res_setup->partition_size = get_bits(gb, 24) + 1;
686         /* Validations to prevent a buffer overflow later. */
687         if (res_setup->begin>res_setup->end ||
688             res_setup->end > (res_setup->type == 2 ? vc->audio_channels : 1) * vc->blocksize[1] / 2 ||
689             (res_setup->end-res_setup->begin) / res_setup->partition_size > V_MAX_PARTITIONS) {
690             av_log(vc->avccontext, AV_LOG_ERROR,
691                    "partition out of bounds: type, begin, end, size, blocksize: %"PRIu16", %"PRIu32", %"PRIu32", %u, %"PRIu32"\n",
692                    res_setup->type, res_setup->begin, res_setup->end,
693                    res_setup->partition_size, vc->blocksize[1] / 2);
694             return AVERROR_INVALIDDATA;
695         }
696
697         res_setup->classifications = get_bits(gb, 6) + 1;
698         GET_VALIDATED_INDEX(res_setup->classbook, 8, vc->codebook_count)
699
700         res_setup->ptns_to_read =
701             (res_setup->end - res_setup->begin) / res_setup->partition_size;
702         res_setup->classifs = av_malloc(res_setup->ptns_to_read *
703                                         vc->audio_channels *
704                                         sizeof(*res_setup->classifs));
705         if (!res_setup->classifs)
706             return AVERROR(ENOMEM);
707
708         av_dlog(NULL, "    begin %d end %d part.size %d classif.s %d classbook %d \n",
709                 res_setup->begin, res_setup->end, res_setup->partition_size,
710                 res_setup->classifications, res_setup->classbook);
711
712         for (j = 0; j < res_setup->classifications; ++j) {
713             high_bits = 0;
714             low_bits  = get_bits(gb, 3);
715             if (get_bits1(gb))
716                 high_bits = get_bits(gb, 5);
717             cascade[j] = (high_bits << 3) + low_bits;
718
719             av_dlog(NULL, "     %u class cascade depth: %d\n", j, ilog(cascade[j]));
720         }
721
722         res_setup->maxpass = 0;
723         for (j = 0; j < res_setup->classifications; ++j) {
724             for (k = 0; k < 8; ++k) {
725                 if (cascade[j]&(1 << k)) {
726                     GET_VALIDATED_INDEX(res_setup->books[j][k], 8, vc->codebook_count)
727
728                     av_dlog(NULL, "     %u class cascade depth %u book: %d\n",
729                             j, k, res_setup->books[j][k]);
730
731                     if (k>res_setup->maxpass)
732                         res_setup->maxpass = k;
733                 } else {
734                     res_setup->books[j][k] = -1;
735                 }
736             }
737         }
738     }
739     return 0;
740 }
741
742 // Process mappings part
743
744 static int vorbis_parse_setup_hdr_mappings(vorbis_context *vc)
745 {
746     GetBitContext *gb = &vc->gb;
747     unsigned i, j;
748
749     vc->mapping_count = get_bits(gb, 6)+1;
750     vc->mappings      = av_mallocz(vc->mapping_count * sizeof(*vc->mappings));
751
752     av_dlog(NULL, " There are %d mappings. \n", vc->mapping_count);
753
754     for (i = 0; i < vc->mapping_count; ++i) {
755         vorbis_mapping *mapping_setup = &vc->mappings[i];
756
757         if (get_bits(gb, 16)) {
758             av_log(vc->avccontext, AV_LOG_ERROR, "Other mappings than type 0 are not compliant with the Vorbis I specification. \n");
759             return AVERROR_INVALIDDATA;
760         }
761         if (get_bits1(gb)) {
762             mapping_setup->submaps = get_bits(gb, 4) + 1;
763         } else {
764             mapping_setup->submaps = 1;
765         }
766
767         if (get_bits1(gb)) {
768             mapping_setup->coupling_steps = get_bits(gb, 8) + 1;
769             mapping_setup->magnitude      = av_mallocz(mapping_setup->coupling_steps *
770                                                        sizeof(*mapping_setup->magnitude));
771             mapping_setup->angle          = av_mallocz(mapping_setup->coupling_steps *
772                                                        sizeof(*mapping_setup->angle));
773             for (j = 0; j < mapping_setup->coupling_steps; ++j) {
774                 GET_VALIDATED_INDEX(mapping_setup->magnitude[j], ilog(vc->audio_channels - 1), vc->audio_channels)
775                 GET_VALIDATED_INDEX(mapping_setup->angle[j],     ilog(vc->audio_channels - 1), vc->audio_channels)
776             }
777         } else {
778             mapping_setup->coupling_steps = 0;
779         }
780
781         av_dlog(NULL, "   %u mapping coupling steps: %d\n",
782                 i, mapping_setup->coupling_steps);
783
784         if (get_bits(gb, 2)) {
785             av_log(vc->avccontext, AV_LOG_ERROR, "%u. mapping setup data invalid.\n", i);
786             return AVERROR_INVALIDDATA; // following spec.
787         }
788
789         if (mapping_setup->submaps>1) {
790             mapping_setup->mux = av_mallocz(vc->audio_channels *
791                                             sizeof(*mapping_setup->mux));
792             for (j = 0; j < vc->audio_channels; ++j)
793                 mapping_setup->mux[j] = get_bits(gb, 4);
794         }
795
796         for (j = 0; j < mapping_setup->submaps; ++j) {
797             skip_bits(gb, 8); // FIXME check?
798             GET_VALIDATED_INDEX(mapping_setup->submap_floor[j],   8, vc->floor_count)
799             GET_VALIDATED_INDEX(mapping_setup->submap_residue[j], 8, vc->residue_count)
800
801             av_dlog(NULL, "   %u mapping %u submap : floor %d, residue %d\n", i, j,
802                     mapping_setup->submap_floor[j],
803                     mapping_setup->submap_residue[j]);
804         }
805     }
806     return 0;
807 }
808
809 // Process modes part
810
811 static void create_map(vorbis_context *vc, unsigned floor_number)
812 {
813     vorbis_floor *floors = vc->floors;
814     vorbis_floor0 *vf;
815     int idx;
816     int blockflag, n;
817     int32_t *map;
818
819     for (blockflag = 0; blockflag < 2; ++blockflag) {
820         n = vc->blocksize[blockflag] / 2;
821         floors[floor_number].data.t0.map[blockflag] =
822             av_malloc((n + 1) * sizeof(int32_t)); // n + sentinel
823
824         map =  floors[floor_number].data.t0.map[blockflag];
825         vf  = &floors[floor_number].data.t0;
826
827         for (idx = 0; idx < n; ++idx) {
828             map[idx] = floor(BARK((vf->rate * idx) / (2.0f * n)) *
829                              (vf->bark_map_size / BARK(vf->rate / 2.0f)));
830             if (vf->bark_map_size-1 < map[idx])
831                 map[idx] = vf->bark_map_size - 1;
832         }
833         map[n] = -1;
834         vf->map_size[blockflag] = n;
835     }
836
837     for (idx = 0; idx <= n; ++idx) {
838         av_dlog(NULL, "floor0 map: map at pos %d is %d\n", idx, map[idx]);
839     }
840 }
841
842 static int vorbis_parse_setup_hdr_modes(vorbis_context *vc)
843 {
844     GetBitContext *gb = &vc->gb;
845     unsigned i;
846
847     vc->mode_count = get_bits(gb, 6) + 1;
848     vc->modes      = av_mallocz(vc->mode_count * sizeof(*vc->modes));
849
850     av_dlog(NULL, " There are %d modes.\n", vc->mode_count);
851
852     for (i = 0; i < vc->mode_count; ++i) {
853         vorbis_mode *mode_setup = &vc->modes[i];
854
855         mode_setup->blockflag     = get_bits1(gb);
856         mode_setup->windowtype    = get_bits(gb, 16); //FIXME check
857         mode_setup->transformtype = get_bits(gb, 16); //FIXME check
858         GET_VALIDATED_INDEX(mode_setup->mapping, 8, vc->mapping_count);
859
860         av_dlog(NULL, " %u mode: blockflag %d, windowtype %d, transformtype %d, mapping %d\n",
861                 i, mode_setup->blockflag, mode_setup->windowtype,
862                 mode_setup->transformtype, mode_setup->mapping);
863     }
864     return 0;
865 }
866
867 // Process the whole setup header using the functions above
868
869 static int vorbis_parse_setup_hdr(vorbis_context *vc)
870 {
871     GetBitContext *gb = &vc->gb;
872     int ret;
873
874     if ((get_bits(gb, 8) != 'v') || (get_bits(gb, 8) != 'o') ||
875         (get_bits(gb, 8) != 'r') || (get_bits(gb, 8) != 'b') ||
876         (get_bits(gb, 8) != 'i') || (get_bits(gb, 8) != 's')) {
877         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (no vorbis signature). \n");
878         return AVERROR_INVALIDDATA;
879     }
880
881     if ((ret = vorbis_parse_setup_hdr_codebooks(vc))) {
882         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (codebooks). \n");
883         return ret;
884     }
885     if ((ret = vorbis_parse_setup_hdr_tdtransforms(vc))) {
886         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (time domain transforms). \n");
887         return ret;
888     }
889     if ((ret = vorbis_parse_setup_hdr_floors(vc))) {
890         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (floors). \n");
891         return ret;
892     }
893     if ((ret = vorbis_parse_setup_hdr_residues(vc))) {
894         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (residues). \n");
895         return ret;
896     }
897     if ((ret = vorbis_parse_setup_hdr_mappings(vc))) {
898         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (mappings). \n");
899         return ret;
900     }
901     if ((ret = vorbis_parse_setup_hdr_modes(vc))) {
902         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (modes). \n");
903         return ret;
904     }
905     if (!get_bits1(gb)) {
906         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (framing flag). \n");
907         return AVERROR_INVALIDDATA; // framing flag bit unset error
908     }
909
910     return 0;
911 }
912
913 // Process the identification header
914
915 static int vorbis_parse_id_hdr(vorbis_context *vc)
916 {
917     GetBitContext *gb = &vc->gb;
918     unsigned bl0, bl1;
919
920     if ((get_bits(gb, 8) != 'v') || (get_bits(gb, 8) != 'o') ||
921         (get_bits(gb, 8) != 'r') || (get_bits(gb, 8) != 'b') ||
922         (get_bits(gb, 8) != 'i') || (get_bits(gb, 8) != 's')) {
923         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (no vorbis signature). \n");
924         return AVERROR_INVALIDDATA;
925     }
926
927     vc->version        = get_bits_long(gb, 32);    //FIXME check 0
928     vc->audio_channels = get_bits(gb, 8);
929     if (vc->audio_channels <= 0) {
930         av_log(vc->avccontext, AV_LOG_ERROR, "Invalid number of channels\n");
931         return AVERROR_INVALIDDATA;
932     }
933     vc->audio_samplerate = get_bits_long(gb, 32);
934     if (vc->audio_samplerate <= 0) {
935         av_log(vc->avccontext, AV_LOG_ERROR, "Invalid samplerate\n");
936         return AVERROR_INVALIDDATA;
937     }
938     vc->bitrate_maximum = get_bits_long(gb, 32);
939     vc->bitrate_nominal = get_bits_long(gb, 32);
940     vc->bitrate_minimum = get_bits_long(gb, 32);
941     bl0 = get_bits(gb, 4);
942     bl1 = get_bits(gb, 4);
943     if (bl0 > 13 || bl0 < 6 || bl1 > 13 || bl1 < 6 || bl1 < bl0) {
944         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (illegal blocksize). \n");
945         return AVERROR_INVALIDDATA;
946     }
947     vc->blocksize[0] = (1 << bl0);
948     vc->blocksize[1] = (1 << bl1);
949     vc->win[0] = ff_vorbis_vwin[bl0 - 6];
950     vc->win[1] = ff_vorbis_vwin[bl1 - 6];
951
952     if ((get_bits1(gb)) == 0) {
953         av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (framing flag not set). \n");
954         return AVERROR_INVALIDDATA;
955     }
956
957     vc->channel_residues =  av_malloc((vc->blocksize[1]  / 2) * vc->audio_channels * sizeof(*vc->channel_residues));
958     vc->channel_floors   =  av_malloc((vc->blocksize[1]  / 2) * vc->audio_channels * sizeof(*vc->channel_floors));
959     vc->saved            =  av_mallocz((vc->blocksize[1] / 4) * vc->audio_channels * sizeof(*vc->saved));
960     vc->previous_window  = 0;
961
962     ff_mdct_init(&vc->mdct[0], bl0, 1, -vc->scale_bias);
963     ff_mdct_init(&vc->mdct[1], bl1, 1, -vc->scale_bias);
964
965     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 ",
966             vc->version, vc->audio_channels, vc->audio_samplerate, vc->bitrate_maximum, vc->bitrate_nominal, vc->bitrate_minimum, vc->blocksize[0], vc->blocksize[1]);
967
968 /*
969     BLK = vc->blocksize[0];
970     for (i = 0; i < BLK / 2; ++i) {
971         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)));
972     }
973 */
974
975     return 0;
976 }
977
978 // Process the extradata using the functions above (identification header, setup header)
979
980 static av_cold int vorbis_decode_init(AVCodecContext *avccontext)
981 {
982     vorbis_context *vc = avccontext->priv_data;
983     uint8_t *headers   = avccontext->extradata;
984     int headers_len    = avccontext->extradata_size;
985     uint8_t *header_start[3];
986     int header_len[3];
987     GetBitContext *gb = &vc->gb;
988     int hdr_type, ret;
989
990     vc->avccontext = avccontext;
991     ff_dsputil_init(&vc->dsp, avccontext);
992     avpriv_float_dsp_init(&vc->fdsp, avccontext->flags & CODEC_FLAG_BITEXACT);
993     ff_fmt_convert_init(&vc->fmt_conv, avccontext);
994
995     if (avccontext->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
996         avccontext->sample_fmt = AV_SAMPLE_FMT_FLT;
997         vc->scale_bias = 1.0f;
998     } else {
999         avccontext->sample_fmt = AV_SAMPLE_FMT_S16;
1000         vc->scale_bias = 32768.0f;
1001     }
1002
1003     if (!headers_len) {
1004         av_log(avccontext, AV_LOG_ERROR, "Extradata missing.\n");
1005         return AVERROR_INVALIDDATA;
1006     }
1007
1008     if ((ret = avpriv_split_xiph_headers(headers, headers_len, 30, header_start, header_len)) < 0) {
1009         av_log(avccontext, AV_LOG_ERROR, "Extradata corrupt.\n");
1010         return ret;
1011     }
1012
1013     init_get_bits(gb, header_start[0], header_len[0]*8);
1014     hdr_type = get_bits(gb, 8);
1015     if (hdr_type != 1) {
1016         av_log(avccontext, AV_LOG_ERROR, "First header is not the id header.\n");
1017         return AVERROR_INVALIDDATA;
1018     }
1019     if ((ret = vorbis_parse_id_hdr(vc))) {
1020         av_log(avccontext, AV_LOG_ERROR, "Id header corrupt.\n");
1021         vorbis_free(vc);
1022         return ret;
1023     }
1024
1025     init_get_bits(gb, header_start[2], header_len[2]*8);
1026     hdr_type = get_bits(gb, 8);
1027     if (hdr_type != 5) {
1028         av_log(avccontext, AV_LOG_ERROR, "Third header is not the setup header.\n");
1029         vorbis_free(vc);
1030         return AVERROR_INVALIDDATA;
1031     }
1032     if ((ret = vorbis_parse_setup_hdr(vc))) {
1033         av_log(avccontext, AV_LOG_ERROR, "Setup header corrupt.\n");
1034         vorbis_free(vc);
1035         return ret;
1036     }
1037
1038     if (vc->audio_channels > 8)
1039         avccontext->channel_layout = 0;
1040     else
1041         avccontext->channel_layout = ff_vorbis_channel_layouts[vc->audio_channels - 1];
1042
1043     avccontext->channels    = vc->audio_channels;
1044     avccontext->sample_rate = vc->audio_samplerate;
1045
1046     avcodec_get_frame_defaults(&vc->frame);
1047     avccontext->coded_frame = &vc->frame;
1048
1049     return 0;
1050 }
1051
1052 // Decode audiopackets -------------------------------------------------
1053
1054 // Read and decode floor
1055
1056 static int vorbis_floor0_decode(vorbis_context *vc,
1057                                 vorbis_floor_data *vfu, float *vec)
1058 {
1059     vorbis_floor0 *vf = &vfu->t0;
1060     float *lsp = vf->lsp;
1061     unsigned amplitude, book_idx;
1062     unsigned blockflag = vc->modes[vc->mode_number].blockflag;
1063
1064     amplitude = get_bits(&vc->gb, vf->amplitude_bits);
1065     if (amplitude > 0) {
1066         float last = 0;
1067         unsigned idx, lsp_len = 0;
1068         vorbis_codebook codebook;
1069
1070         book_idx = get_bits(&vc->gb, ilog(vf->num_books));
1071         if (book_idx >= vf->num_books) {
1072             av_log(vc->avccontext, AV_LOG_ERROR,
1073                     "floor0 dec: booknumber too high!\n");
1074             book_idx =  0;
1075         }
1076         av_dlog(NULL, "floor0 dec: booknumber: %u\n", book_idx);
1077         codebook = vc->codebooks[vf->book_list[book_idx]];
1078         /* Invalid codebook! */
1079         if (!codebook.codevectors)
1080             return AVERROR_INVALIDDATA;
1081
1082         while (lsp_len<vf->order) {
1083             int vec_off;
1084
1085             av_dlog(NULL, "floor0 dec: book dimension: %d\n", codebook.dimensions);
1086             av_dlog(NULL, "floor0 dec: maximum depth: %d\n", codebook.maxdepth);
1087             /* read temp vector */
1088             vec_off = get_vlc2(&vc->gb, codebook.vlc.table,
1089                                codebook.nb_bits, codebook.maxdepth)
1090                       * codebook.dimensions;
1091             av_dlog(NULL, "floor0 dec: vector offset: %d\n", vec_off);
1092             /* copy each vector component and add last to it */
1093             for (idx = 0; idx < codebook.dimensions; ++idx)
1094                 lsp[lsp_len+idx] = codebook.codevectors[vec_off+idx] + last;
1095             last = lsp[lsp_len+idx-1]; /* set last to last vector component */
1096
1097             lsp_len += codebook.dimensions;
1098         }
1099         /* DEBUG: output lsp coeffs */
1100         {
1101             int idx;
1102             for (idx = 0; idx < lsp_len; ++idx)
1103                 av_dlog(NULL, "floor0 dec: coeff at %d is %f\n", idx, lsp[idx]);
1104         }
1105
1106         /* synthesize floor output vector */
1107         {
1108             int i;
1109             int order = vf->order;
1110             float wstep = M_PI / vf->bark_map_size;
1111
1112             for (i = 0; i < order; i++)
1113                 lsp[i] = 2.0f * cos(lsp[i]);
1114
1115             av_dlog(NULL, "floor0 synth: map_size = %"PRIu32"; m = %d; wstep = %f\n",
1116                     vf->map_size[blockflag], order, wstep);
1117
1118             i = 0;
1119             while (i < vf->map_size[blockflag]) {
1120                 int j, iter_cond = vf->map[blockflag][i];
1121                 float p = 0.5f;
1122                 float q = 0.5f;
1123                 float two_cos_w = 2.0f * cos(wstep * iter_cond); // needed all times
1124
1125                 /* similar part for the q and p products */
1126                 for (j = 0; j + 1 < order; j += 2) {
1127                     q *= lsp[j]     - two_cos_w;
1128                     p *= lsp[j + 1] - two_cos_w;
1129                 }
1130                 if (j == order) { // even order
1131                     p *= p * (2.0f - two_cos_w);
1132                     q *= q * (2.0f + two_cos_w);
1133                 } else { // odd order
1134                     q *= two_cos_w-lsp[j]; // one more time for q
1135
1136                     /* final step and square */
1137                     p *= p * (4.f - two_cos_w * two_cos_w);
1138                     q *= q;
1139                 }
1140
1141                 /* calculate linear floor value */
1142                 q = exp((((amplitude*vf->amplitude_offset) /
1143                           (((1 << vf->amplitude_bits) - 1) * sqrt(p + q)))
1144                          - vf->amplitude_offset) * .11512925f);
1145
1146                 /* fill vector */
1147                 do {
1148                     vec[i] = q; ++i;
1149                 } while (vf->map[blockflag][i] == iter_cond);
1150             }
1151         }
1152     } else {
1153         /* this channel is unused */
1154         return 1;
1155     }
1156
1157     av_dlog(NULL, " Floor0 decoded\n");
1158
1159     return 0;
1160 }
1161
1162 static int vorbis_floor1_decode(vorbis_context *vc,
1163                                 vorbis_floor_data *vfu, float *vec)
1164 {
1165     vorbis_floor1 *vf = &vfu->t1;
1166     GetBitContext *gb = &vc->gb;
1167     uint16_t range_v[4] = { 256, 128, 86, 64 };
1168     unsigned range = range_v[vf->multiplier - 1];
1169     uint16_t floor1_Y[258];
1170     uint16_t floor1_Y_final[258];
1171     int floor1_flag[258];
1172     unsigned partition_class, cdim, cbits, csub, cval, offset, i, j;
1173     int book, adx, ady, dy, off, predicted, err;
1174
1175
1176     if (!get_bits1(gb)) // silence
1177         return 1;
1178
1179 // Read values (or differences) for the floor's points
1180
1181     floor1_Y[0] = get_bits(gb, ilog(range - 1));
1182     floor1_Y[1] = get_bits(gb, ilog(range - 1));
1183
1184     av_dlog(NULL, "floor 0 Y %d floor 1 Y %d \n", floor1_Y[0], floor1_Y[1]);
1185
1186     offset = 2;
1187     for (i = 0; i < vf->partitions; ++i) {
1188         partition_class = vf->partition_class[i];
1189         cdim   = vf->class_dimensions[partition_class];
1190         cbits  = vf->class_subclasses[partition_class];
1191         csub = (1 << cbits) - 1;
1192         cval = 0;
1193
1194         av_dlog(NULL, "Cbits %u\n", cbits);
1195
1196         if (cbits) // this reads all subclasses for this partition's class
1197             cval = get_vlc2(gb, vc->codebooks[vf->class_masterbook[partition_class]].vlc.table,
1198                             vc->codebooks[vf->class_masterbook[partition_class]].nb_bits, 3);
1199
1200         for (j = 0; j < cdim; ++j) {
1201             book = vf->subclass_books[partition_class][cval & csub];
1202
1203             av_dlog(NULL, "book %d Cbits %u cval %u  bits:%d\n",
1204                     book, cbits, cval, get_bits_count(gb));
1205
1206             cval = cval >> cbits;
1207             if (book > -1) {
1208                 floor1_Y[offset+j] = get_vlc2(gb, vc->codebooks[book].vlc.table,
1209                 vc->codebooks[book].nb_bits, 3);
1210             } else {
1211                 floor1_Y[offset+j] = 0;
1212             }
1213
1214             av_dlog(NULL, " floor(%d) = %d \n",
1215                     vf->list[offset+j].x, floor1_Y[offset+j]);
1216         }
1217         offset+=cdim;
1218     }
1219
1220 // Amplitude calculation from the differences
1221
1222     floor1_flag[0] = 1;
1223     floor1_flag[1] = 1;
1224     floor1_Y_final[0] = floor1_Y[0];
1225     floor1_Y_final[1] = floor1_Y[1];
1226
1227     for (i = 2; i < vf->x_list_dim; ++i) {
1228         unsigned val, highroom, lowroom, room, high_neigh_offs, low_neigh_offs;
1229
1230         low_neigh_offs  = vf->list[i].low;
1231         high_neigh_offs = vf->list[i].high;
1232         dy  = floor1_Y_final[high_neigh_offs] - floor1_Y_final[low_neigh_offs];  // render_point begin
1233         adx = vf->list[high_neigh_offs].x - vf->list[low_neigh_offs].x;
1234         ady = FFABS(dy);
1235         err = ady * (vf->list[i].x - vf->list[low_neigh_offs].x);
1236         off = err / adx;
1237         if (dy < 0) {
1238             predicted = floor1_Y_final[low_neigh_offs] - off;
1239         } else {
1240             predicted = floor1_Y_final[low_neigh_offs] + off;
1241         } // render_point end
1242
1243         val = floor1_Y[i];
1244         highroom = range-predicted;
1245         lowroom  = predicted;
1246         if (highroom < lowroom) {
1247             room = highroom * 2;
1248         } else {
1249             room = lowroom * 2;   // SPEC mispelling
1250         }
1251         if (val) {
1252             floor1_flag[low_neigh_offs]  = 1;
1253             floor1_flag[high_neigh_offs] = 1;
1254             floor1_flag[i]               = 1;
1255             if (val >= room) {
1256                 if (highroom > lowroom) {
1257                     floor1_Y_final[i] = av_clip_uint16(val - lowroom + predicted);
1258                 } else {
1259                     floor1_Y_final[i] = av_clip_uint16(predicted - val + highroom - 1);
1260                 }
1261             } else {
1262                 if (val & 1) {
1263                     floor1_Y_final[i] = av_clip_uint16(predicted - (val + 1) / 2);
1264                 } else {
1265                     floor1_Y_final[i] = av_clip_uint16(predicted + val / 2);
1266                 }
1267             }
1268         } else {
1269             floor1_flag[i]    = 0;
1270             floor1_Y_final[i] = av_clip_uint16(predicted);
1271         }
1272
1273         av_dlog(NULL, " Decoded floor(%d) = %u / val %u\n",
1274                 vf->list[i].x, floor1_Y_final[i], val);
1275     }
1276
1277 // Curve synth - connect the calculated dots and convert from dB scale FIXME optimize ?
1278
1279     ff_vorbis_floor1_render_list(vf->list, vf->x_list_dim, floor1_Y_final, floor1_flag, vf->multiplier, vec, vf->list[1].x);
1280
1281     av_dlog(NULL, " Floor decoded\n");
1282
1283     return 0;
1284 }
1285
1286 // Read and decode residue
1287
1288 static av_always_inline int vorbis_residue_decode_internal(vorbis_context *vc,
1289                                                            vorbis_residue *vr,
1290                                                            unsigned ch,
1291                                                            uint8_t *do_not_decode,
1292                                                            float *vec,
1293                                                            unsigned vlen,
1294                                                            unsigned ch_left,
1295                                                            int vr_type)
1296 {
1297     GetBitContext *gb = &vc->gb;
1298     unsigned c_p_c        = vc->codebooks[vr->classbook].dimensions;
1299     unsigned ptns_to_read = vr->ptns_to_read;
1300     uint8_t *classifs = vr->classifs;
1301     unsigned pass, ch_used, i, j, k, l;
1302     unsigned max_output = (ch - 1) * vlen;
1303
1304     if (vr_type == 2) {
1305         for (j = 1; j < ch; ++j)
1306             do_not_decode[0] &= do_not_decode[j];  // FIXME - clobbering input
1307         if (do_not_decode[0])
1308             return 0;
1309         ch_used = 1;
1310         max_output += vr->end / ch;
1311     } else {
1312         ch_used = ch;
1313         max_output += vr->end;
1314     }
1315
1316     if (max_output > ch_left * vlen) {
1317         av_log(vc->avccontext, AV_LOG_ERROR, "Insufficient output buffer\n");
1318         return -1;
1319     }
1320
1321     av_dlog(NULL, " residue type 0/1/2 decode begin, ch: %d  cpc %d  \n", ch, c_p_c);
1322
1323     for (pass = 0; pass <= vr->maxpass; ++pass) { // FIXME OPTIMIZE?
1324         uint16_t voffset, partition_count, j_times_ptns_to_read;
1325
1326         voffset = vr->begin;
1327         for (partition_count = 0; partition_count < ptns_to_read;) {  // SPEC        error
1328             if (!pass) {
1329                 unsigned inverse_class = ff_inverse[vr->classifications];
1330                 for (j_times_ptns_to_read = 0, j = 0; j < ch_used; ++j) {
1331                     if (!do_not_decode[j]) {
1332                         unsigned temp = get_vlc2(gb, vc->codebooks[vr->classbook].vlc.table,
1333                                                  vc->codebooks[vr->classbook].nb_bits, 3);
1334
1335                         av_dlog(NULL, "Classword: %u\n", temp);
1336
1337                         assert(vr->classifications > 1 && temp <= 65536); //needed for inverse[]
1338                         for (i = 0; i < c_p_c; ++i) {
1339                             unsigned temp2;
1340
1341                             temp2 = (((uint64_t)temp) * inverse_class) >> 32;
1342                             if (partition_count + c_p_c - 1 - i < ptns_to_read)
1343                                 classifs[j_times_ptns_to_read + partition_count + c_p_c - 1 - i] = temp - temp2 * vr->classifications;
1344                             temp = temp2;
1345                         }
1346                     }
1347                     j_times_ptns_to_read += ptns_to_read;
1348                 }
1349             }
1350             for (i = 0; (i < c_p_c) && (partition_count < ptns_to_read); ++i) {
1351                 for (j_times_ptns_to_read = 0, j = 0; j < ch_used; ++j) {
1352                     unsigned voffs;
1353
1354                     if (!do_not_decode[j]) {
1355                         unsigned vqclass = classifs[j_times_ptns_to_read + partition_count];
1356                         int vqbook  = vr->books[vqclass][pass];
1357
1358                         if (vqbook >= 0 && vc->codebooks[vqbook].codevectors) {
1359                             unsigned coffs;
1360                             unsigned dim  = vc->codebooks[vqbook].dimensions;
1361                             unsigned step = dim == 1 ? vr->partition_size
1362                                                      : FASTDIV(vr->partition_size, dim);
1363                             vorbis_codebook codebook = vc->codebooks[vqbook];
1364
1365                             if (vr_type == 0) {
1366
1367                                 voffs = voffset+j*vlen;
1368                                 for (k = 0; k < step; ++k) {
1369                                     coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1370                                     for (l = 0; l < dim; ++l)
1371                                         vec[voffs + k + l * step] += codebook.codevectors[coffs + l];  // FPMATH
1372                                 }
1373                             } else if (vr_type == 1) {
1374                                 voffs = voffset + j * vlen;
1375                                 for (k = 0; k < step; ++k) {
1376                                     coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1377                                     for (l = 0; l < dim; ++l, ++voffs) {
1378                                         vec[voffs]+=codebook.codevectors[coffs+l];  // FPMATH
1379
1380                                         av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d  \n",
1381                                                 pass, voffs, vec[voffs], codebook.codevectors[coffs+l], coffs);
1382                                     }
1383                                 }
1384                             } else if (vr_type == 2 && ch == 2 && (voffset & 1) == 0 && (dim & 1) == 0) { // most frequent case optimized
1385                                 voffs = voffset >> 1;
1386
1387                                 if (dim == 2) {
1388                                     for (k = 0; k < step; ++k) {
1389                                         coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 2;
1390                                         vec[voffs + k       ] += codebook.codevectors[coffs    ];  // FPMATH
1391                                         vec[voffs + k + vlen] += codebook.codevectors[coffs + 1];  // FPMATH
1392                                     }
1393                                 } else if (dim == 4) {
1394                                     for (k = 0; k < step; ++k, voffs += 2) {
1395                                         coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 4;
1396                                         vec[voffs           ] += codebook.codevectors[coffs    ];  // FPMATH
1397                                         vec[voffs + 1       ] += codebook.codevectors[coffs + 2];  // FPMATH
1398                                         vec[voffs + vlen    ] += codebook.codevectors[coffs + 1];  // FPMATH
1399                                         vec[voffs + vlen + 1] += codebook.codevectors[coffs + 3];  // FPMATH
1400                                     }
1401                                 } else
1402                                 for (k = 0; k < step; ++k) {
1403                                     coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1404                                     for (l = 0; l < dim; l += 2, voffs++) {
1405                                         vec[voffs       ] += codebook.codevectors[coffs + l    ];  // FPMATH
1406                                         vec[voffs + vlen] += codebook.codevectors[coffs + l + 1];  // FPMATH
1407
1408                                         av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d+%d  \n",
1409                                                 pass, voffset / ch + (voffs % ch) * vlen,
1410                                                 vec[voffset / ch + (voffs % ch) * vlen],
1411                                                 codebook.codevectors[coffs + l], coffs, l);
1412                                     }
1413                                 }
1414
1415                             } else if (vr_type == 2) {
1416                                 unsigned voffs_div = FASTDIV(voffset, ch);
1417                                 unsigned voffs_mod = voffset - voffs_div * ch;
1418
1419                                 for (k = 0; k < step; ++k) {
1420                                     coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1421                                     for (l = 0; l < dim; ++l) {
1422                                         vec[voffs_div + voffs_mod * vlen] +=
1423                                             codebook.codevectors[coffs + l];
1424
1425                                         av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d+%d  \n",
1426                                                 pass, voffs_div + voffs_mod * vlen,
1427                                                 vec[voffs_div + voffs_mod * vlen],
1428                                                 codebook.codevectors[coffs + l], coffs, l);
1429
1430                                         if (++voffs_mod == ch) {
1431                                             voffs_div++;
1432                                             voffs_mod = 0;
1433                                         }
1434                                     }
1435                                 }
1436                             }
1437                         }
1438                     }
1439                     j_times_ptns_to_read += ptns_to_read;
1440                 }
1441                 ++partition_count;
1442                 voffset += vr->partition_size;
1443             }
1444         }
1445     }
1446     return 0;
1447 }
1448
1449 static inline int vorbis_residue_decode(vorbis_context *vc, vorbis_residue *vr,
1450                                         unsigned ch,
1451                                         uint8_t *do_not_decode,
1452                                         float *vec, unsigned vlen,
1453                                         unsigned ch_left)
1454 {
1455     if (vr->type == 2)
1456         return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, ch_left, 2);
1457     else if (vr->type == 1)
1458         return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, ch_left, 1);
1459     else if (vr->type == 0)
1460         return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, ch_left, 0);
1461     else {
1462         av_log(vc->avccontext, AV_LOG_ERROR, " Invalid residue type while residue decode?! \n");
1463         return AVERROR_INVALIDDATA;
1464     }
1465 }
1466
1467 void ff_vorbis_inverse_coupling(float *mag, float *ang, int blocksize)
1468 {
1469     int i;
1470     for (i = 0;  i < blocksize;  i++) {
1471         if (mag[i] > 0.0) {
1472             if (ang[i] > 0.0) {
1473                 ang[i] = mag[i] - ang[i];
1474             } else {
1475                 float temp = ang[i];
1476                 ang[i]     = mag[i];
1477                 mag[i]    += temp;
1478             }
1479         } else {
1480             if (ang[i] > 0.0) {
1481                 ang[i] += mag[i];
1482             } else {
1483                 float temp = ang[i];
1484                 ang[i]     = mag[i];
1485                 mag[i]    -= temp;
1486             }
1487         }
1488     }
1489 }
1490
1491 // Decode the audio packet using the functions above
1492
1493 static int vorbis_parse_audio_packet(vorbis_context *vc)
1494 {
1495     GetBitContext *gb = &vc->gb;
1496     FFTContext *mdct;
1497     unsigned previous_window = vc->previous_window;
1498     unsigned mode_number, blockflag, blocksize;
1499     int i, j;
1500     uint8_t no_residue[255];
1501     uint8_t do_not_decode[255];
1502     vorbis_mapping *mapping;
1503     float *ch_res_ptr   = vc->channel_residues;
1504     float *ch_floor_ptr = vc->channel_floors;
1505     uint8_t res_chan[255];
1506     unsigned res_num = 0;
1507     int retlen  = 0;
1508     unsigned ch_left = vc->audio_channels;
1509     unsigned vlen;
1510
1511     if (get_bits1(gb)) {
1512         av_log(vc->avccontext, AV_LOG_ERROR, "Not a Vorbis I audio packet.\n");
1513         return AVERROR_INVALIDDATA; // packet type not audio
1514     }
1515
1516     if (vc->mode_count == 1) {
1517         mode_number = 0;
1518     } else {
1519         GET_VALIDATED_INDEX(mode_number, ilog(vc->mode_count-1), vc->mode_count)
1520     }
1521     vc->mode_number = mode_number;
1522     mapping = &vc->mappings[vc->modes[mode_number].mapping];
1523
1524     av_dlog(NULL, " Mode number: %u , mapping: %d , blocktype %d\n", mode_number,
1525             vc->modes[mode_number].mapping, vc->modes[mode_number].blockflag);
1526
1527     blockflag = vc->modes[mode_number].blockflag;
1528     blocksize = vc->blocksize[blockflag];
1529     vlen = blocksize / 2;
1530     if (blockflag) {
1531         previous_window = get_bits(gb, 1);
1532         skip_bits1(gb); // next_window
1533     }
1534
1535     memset(ch_res_ptr,   0, sizeof(float) * vc->audio_channels * vlen); //FIXME can this be removed ?
1536     memset(ch_floor_ptr, 0, sizeof(float) * vc->audio_channels * vlen); //FIXME can this be removed ?
1537
1538 // Decode floor
1539
1540     for (i = 0; i < vc->audio_channels; ++i) {
1541         vorbis_floor *floor;
1542         int ret;
1543         if (mapping->submaps > 1) {
1544             floor = &vc->floors[mapping->submap_floor[mapping->mux[i]]];
1545         } else {
1546             floor = &vc->floors[mapping->submap_floor[0]];
1547         }
1548
1549         ret = floor->decode(vc, &floor->data, ch_floor_ptr);
1550
1551         if (ret < 0) {
1552             av_log(vc->avccontext, AV_LOG_ERROR, "Invalid codebook in vorbis_floor_decode.\n");
1553             return AVERROR_INVALIDDATA;
1554         }
1555         no_residue[i] = ret;
1556         ch_floor_ptr += vlen;
1557     }
1558
1559 // Nonzero vector propagate
1560
1561     for (i = mapping->coupling_steps - 1; i >= 0; --i) {
1562         if (!(no_residue[mapping->magnitude[i]] & no_residue[mapping->angle[i]])) {
1563             no_residue[mapping->magnitude[i]] = 0;
1564             no_residue[mapping->angle[i]]     = 0;
1565         }
1566     }
1567
1568 // Decode residue
1569
1570     for (i = 0; i < mapping->submaps; ++i) {
1571         vorbis_residue *residue;
1572         unsigned ch = 0;
1573         int ret;
1574
1575         for (j = 0; j < vc->audio_channels; ++j) {
1576             if ((mapping->submaps == 1) || (i == mapping->mux[j])) {
1577                 res_chan[j] = res_num;
1578                 if (no_residue[j]) {
1579                     do_not_decode[ch] = 1;
1580                 } else {
1581                     do_not_decode[ch] = 0;
1582                 }
1583                 ++ch;
1584                 ++res_num;
1585             }
1586         }
1587         residue = &vc->residues[mapping->submap_residue[i]];
1588         if (ch_left < ch) {
1589             av_log(vc->avccontext, AV_LOG_ERROR, "Too many channels in vorbis_floor_decode.\n");
1590             return -1;
1591         }
1592         if (ch) {
1593             ret = vorbis_residue_decode(vc, residue, ch, do_not_decode, ch_res_ptr, vlen, ch_left);
1594             if (ret < 0)
1595                 return ret;
1596         }
1597
1598         ch_res_ptr += ch * vlen;
1599         ch_left -= ch;
1600     }
1601
1602     if (ch_left > 0)
1603         return AVERROR_INVALIDDATA;
1604
1605 // Inverse coupling
1606
1607     for (i = mapping->coupling_steps - 1; i >= 0; --i) { //warning: i has to be signed
1608         float *mag, *ang;
1609
1610         mag = vc->channel_residues+res_chan[mapping->magnitude[i]] * blocksize / 2;
1611         ang = vc->channel_residues+res_chan[mapping->angle[i]]     * blocksize / 2;
1612         vc->dsp.vorbis_inverse_coupling(mag, ang, blocksize / 2);
1613     }
1614
1615 // Dotproduct, MDCT
1616
1617     mdct = &vc->mdct[blockflag];
1618
1619     for (j = vc->audio_channels-1;j >= 0; j--) {
1620         ch_floor_ptr = vc->channel_floors   + j           * blocksize / 2;
1621         ch_res_ptr   = vc->channel_residues + res_chan[j] * blocksize / 2;
1622         vc->fdsp.vector_fmul(ch_floor_ptr, ch_floor_ptr, ch_res_ptr, blocksize / 2);
1623         mdct->imdct_half(mdct, ch_res_ptr, ch_floor_ptr);
1624     }
1625
1626 // Overlap/add, save data for next overlapping  FPMATH
1627
1628     retlen = (blocksize + vc->blocksize[previous_window]) / 4;
1629     for (j = 0; j < vc->audio_channels; j++) {
1630         unsigned bs0 = vc->blocksize[0];
1631         unsigned bs1 = vc->blocksize[1];
1632         float *residue    = vc->channel_residues + res_chan[j] * blocksize / 2;
1633         float *saved      = vc->saved + j * bs1 / 4;
1634         float *ret        = vc->channel_floors + j * retlen;
1635         float *buf        = residue;
1636         const float *win  = vc->win[blockflag & previous_window];
1637
1638         if (blockflag == previous_window) {
1639             vc->dsp.vector_fmul_window(ret, saved, buf, win, blocksize / 4);
1640         } else if (blockflag > previous_window) {
1641             vc->dsp.vector_fmul_window(ret, saved, buf, win, bs0 / 4);
1642             memcpy(ret+bs0/2, buf+bs0/4, ((bs1-bs0)/4) * sizeof(float));
1643         } else {
1644             memcpy(ret, saved, ((bs1 - bs0) / 4) * sizeof(float));
1645             vc->dsp.vector_fmul_window(ret + (bs1 - bs0) / 4, saved + (bs1 - bs0) / 4, buf, win, bs0 / 4);
1646         }
1647         memcpy(saved, buf + blocksize / 4, blocksize / 4 * sizeof(float));
1648     }
1649
1650     vc->previous_window = blockflag;
1651     return retlen;
1652 }
1653
1654 // Return the decoded audio packet through the standard api
1655
1656 static int vorbis_decode_frame(AVCodecContext *avccontext, void *data,
1657                                int *got_frame_ptr, AVPacket *avpkt)
1658 {
1659     const uint8_t *buf = avpkt->data;
1660     int buf_size       = avpkt->size;
1661     vorbis_context *vc = avccontext->priv_data;
1662     GetBitContext *gb = &vc->gb;
1663     const float *channel_ptrs[255];
1664     int i, len, ret;
1665
1666     av_dlog(NULL, "packet length %d \n", buf_size);
1667
1668     init_get_bits(gb, buf, buf_size*8);
1669
1670     if ((len = vorbis_parse_audio_packet(vc)) <= 0)
1671         return len;
1672
1673     if (!vc->first_frame) {
1674         vc->first_frame = 1;
1675         *got_frame_ptr = 0;
1676         return buf_size;
1677     }
1678
1679     av_dlog(NULL, "parsed %d bytes %d bits, returned %d samples (*ch*bits) \n",
1680             get_bits_count(gb) / 8, get_bits_count(gb) % 8, len);
1681
1682     /* get output buffer */
1683     vc->frame.nb_samples = len;
1684     if ((ret = avccontext->get_buffer(avccontext, &vc->frame)) < 0) {
1685         av_log(avccontext, AV_LOG_ERROR, "get_buffer() failed\n");
1686         return ret;
1687     }
1688
1689     if (vc->audio_channels > 8) {
1690         for (i = 0; i < vc->audio_channels; i++)
1691             channel_ptrs[i] = vc->channel_floors + i * len;
1692     } else {
1693         for (i = 0; i < vc->audio_channels; i++)
1694             channel_ptrs[i] = vc->channel_floors +
1695                               len * ff_vorbis_channel_layout_offsets[vc->audio_channels - 1][i];
1696     }
1697
1698     if (avccontext->sample_fmt == AV_SAMPLE_FMT_FLT)
1699         vc->fmt_conv.float_interleave((float *)vc->frame.data[0], channel_ptrs,
1700                                       len, vc->audio_channels);
1701     else
1702         vc->fmt_conv.float_to_int16_interleave((int16_t *)vc->frame.data[0],
1703                                                channel_ptrs, len,
1704                                                vc->audio_channels);
1705
1706     *got_frame_ptr   = 1;
1707     *(AVFrame *)data = vc->frame;
1708
1709     return buf_size;
1710 }
1711
1712 // Close decoder
1713
1714 static av_cold int vorbis_decode_close(AVCodecContext *avccontext)
1715 {
1716     vorbis_context *vc = avccontext->priv_data;
1717
1718     vorbis_free(vc);
1719
1720     return 0;
1721 }
1722
1723 static av_cold void vorbis_decode_flush(AVCodecContext *avccontext)
1724 {
1725     vorbis_context *vc = avccontext->priv_data;
1726
1727     if (vc->saved) {
1728         memset(vc->saved, 0, (vc->blocksize[1] / 4) * vc->audio_channels *
1729                              sizeof(*vc->saved));
1730     }
1731     vc->previous_window = 0;
1732 }
1733
1734 AVCodec ff_vorbis_decoder = {
1735     .name            = "vorbis",
1736     .type            = AVMEDIA_TYPE_AUDIO,
1737     .id              = CODEC_ID_VORBIS,
1738     .priv_data_size  = sizeof(vorbis_context),
1739     .init            = vorbis_decode_init,
1740     .close           = vorbis_decode_close,
1741     .decode          = vorbis_decode_frame,
1742     .flush           = vorbis_decode_flush,
1743     .capabilities    = CODEC_CAP_DR1,
1744     .long_name       = NULL_IF_CONFIG_SMALL("Vorbis"),
1745     .channel_layouts = ff_vorbis_channel_layouts,
1746     .sample_fmts     = (const enum AVSampleFormat[]) {
1747         AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
1748     },
1749 };