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