Statistics
| Branch: | Revision:

ffmpeg / libavcodec / vorbis_dec.c @ 80ba1ddb

History | View | Annotate | Download (60.5 KB)

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
#undef V_DEBUG
24
//#define V_DEBUG
25
//#define AV_DEBUG(...) av_log(NULL, AV_LOG_INFO, __VA_ARGS__)
26

    
27
#include <math.h>
28

    
29
#define ALT_BITSTREAM_READER_LE
30
#include "avcodec.h"
31
#include "get_bits.h"
32
#include "dsputil.h"
33
#include "fft.h"
34

    
35
#include "vorbis.h"
36
#include "xiph.h"
37

    
38
#define V_NB_BITS 8
39
#define V_NB_BITS2 11
40
#define V_MAX_VLCS (1 << 16)
41
#define V_MAX_PARTITIONS (1 << 20)
42

    
43
#ifndef V_DEBUG
44
#define AV_DEBUG(...)
45
#endif
46

    
47
#undef NDEBUG
48
#include <assert.h>
49

    
50
typedef struct {
51
    uint_fast8_t dimensions;
52
    uint_fast8_t lookup_type;
53
    uint_fast8_t maxdepth;
54
    VLC vlc;
55
    float *codevectors;
56
    unsigned int nb_bits;
57
} vorbis_codebook;
58

    
59
typedef union  vorbis_floor_u  vorbis_floor_data;
60
typedef struct vorbis_floor0_s vorbis_floor0;
61
typedef struct vorbis_floor1_s vorbis_floor1;
62
struct vorbis_context_s;
63
typedef
64
int (* vorbis_floor_decode_func)
65
    (struct vorbis_context_s *, vorbis_floor_data *, float *);
66
typedef struct {
67
    uint_fast8_t floor_type;
68
    vorbis_floor_decode_func decode;
69
    union vorbis_floor_u {
70
        struct vorbis_floor0_s {
71
            uint_fast8_t  order;
72
            uint_fast16_t rate;
73
            uint_fast16_t bark_map_size;
74
            int_fast32_t *map[2];
75
            uint_fast32_t map_size[2];
76
            uint_fast8_t  amplitude_bits;
77
            uint_fast8_t  amplitude_offset;
78
            uint_fast8_t  num_books;
79
            uint_fast8_t *book_list;
80
            float        *lsp;
81
        } t0;
82
        struct vorbis_floor1_s {
83
            uint_fast8_t partitions;
84
            uint8_t      partition_class[32];
85
            uint_fast8_t class_dimensions[16];
86
            uint_fast8_t class_subclasses[16];
87
            uint_fast8_t class_masterbook[16];
88
            int_fast16_t subclass_books[16][8];
89
            uint_fast8_t multiplier;
90
            uint_fast16_t x_list_dim;
91
            vorbis_floor1_entry *list;
92
        } t1;
93
    } data;
94
} vorbis_floor;
95

    
96
typedef struct {
97
    uint_fast16_t type;
98
    uint_fast32_t begin;
99
    uint_fast32_t end;
100
    unsigned      partition_size;
101
    uint_fast8_t  classifications;
102
    uint_fast8_t  classbook;
103
    int_fast16_t  books[64][8];
104
    uint_fast8_t  maxpass;
105
    uint_fast16_t ptns_to_read;
106
    uint8_t *classifs;
107
} vorbis_residue;
108

    
109
typedef struct {
110
    uint_fast8_t  submaps;
111
    uint_fast16_t coupling_steps;
112
    uint_fast8_t *magnitude;
113
    uint_fast8_t *angle;
114
    uint_fast8_t *mux;
115
    uint_fast8_t  submap_floor[16];
116
    uint_fast8_t  submap_residue[16];
117
} vorbis_mapping;
118

    
119
typedef struct {
120
    uint_fast8_t  blockflag;
121
    uint_fast16_t windowtype;
122
    uint_fast16_t transformtype;
123
    uint_fast8_t  mapping;
124
} vorbis_mode;
125

    
126
typedef struct vorbis_context_s {
127
    AVCodecContext *avccontext;
128
    GetBitContext gb;
129
    DSPContext dsp;
130

    
131
    FFTContext mdct[2];
132
    uint_fast8_t  first_frame;
133
    uint_fast32_t version;
134
    uint_fast8_t  audio_channels;
135
    uint_fast32_t audio_samplerate;
136
    uint_fast32_t bitrate_maximum;
137
    uint_fast32_t bitrate_nominal;
138
    uint_fast32_t bitrate_minimum;
139
    uint_fast32_t blocksize[2];
140
    const float  *win[2];
141
    uint_fast16_t codebook_count;
142
    vorbis_codebook *codebooks;
143
    uint_fast8_t  floor_count;
144
    vorbis_floor *floors;
145
    uint_fast8_t  residue_count;
146
    vorbis_residue *residues;
147
    uint_fast8_t  mapping_count;
148
    vorbis_mapping *mappings;
149
    uint_fast8_t  mode_count;
150
    vorbis_mode  *modes;
151
    uint_fast8_t  mode_number; // mode number for the current packet
152
    uint_fast8_t  previous_window;
153
    float        *channel_residues;
154
    float        *channel_floors;
155
    float        *saved;
156
    float         scale_bias; // for float->int conversion
157
} vorbis_context;
158

    
159
/* Helper functions */
160

    
161
#define BARK(x) \
162
    (13.1f * atan(0.00074f * (x)) + 2.24f * atan(1.85e-8f * (x) * (x)) + 1e-4f * (x))
163

    
164
static const char idx_err_str[] = "Index value %d out of range (0 - %d) for %s at %s:%i\n";
165
#define VALIDATE_INDEX(idx, limit) \
166
    if (idx >= limit) {\
167
        av_log(vc->avccontext, AV_LOG_ERROR,\
168
               idx_err_str,\
169
               (int)(idx), (int)(limit - 1), #idx, __FILE__, __LINE__);\
170
        return -1;\
171
    }
172
#define GET_VALIDATED_INDEX(idx, bits, limit) \
173
    {\
174
        idx = get_bits(gb, bits);\
175
        VALIDATE_INDEX(idx, limit)\
176
    }
177

    
178
static float vorbisfloat2float(uint_fast32_t val)
179
{
180
    double mant = val & 0x1fffff;
181
    long exp    = (val & 0x7fe00000L) >> 21;
182
    if (val & 0x80000000)
183
        mant = -mant;
184
    return ldexp(mant, exp - 20 - 768);
185
}
186

    
187

    
188
// Free all allocated memory -----------------------------------------
189

    
190
static void vorbis_free(vorbis_context *vc)
191
{
192
    int_fast16_t i;
193

    
194
    av_freep(&vc->channel_residues);
195
    av_freep(&vc->channel_floors);
196
    av_freep(&vc->saved);
197

    
198
    for (i = 0; i < vc->residue_count; i++)
199
        av_free(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
    for (i = 0; i < vc->codebook_count; ++i) {
207
        av_free(vc->codebooks[i].codevectors);
208
        free_vlc(&vc->codebooks[i].vlc);
209
    }
210
    av_freep(&vc->codebooks);
211

    
212
    for (i = 0; i < vc->floor_count; ++i) {
213
        if (vc->floors[i].floor_type == 0) {
214
            av_free(vc->floors[i].data.t0.map[0]);
215
            av_free(vc->floors[i].data.t0.map[1]);
216
            av_free(vc->floors[i].data.t0.book_list);
217
            av_free(vc->floors[i].data.t0.lsp);
218
        } else {
219
            av_free(vc->floors[i].data.t1.list);
220
        }
221
    }
222
    av_freep(&vc->floors);
223

    
224
    for (i = 0; i < vc->mapping_count; ++i) {
225
        av_free(vc->mappings[i].magnitude);
226
        av_free(vc->mappings[i].angle);
227
        av_free(vc->mappings[i].mux);
228
    }
229
    av_freep(&vc->mappings);
230
}
231

    
232
// Parse setup header -------------------------------------------------
233

    
234
// Process codebooks part
235

    
236
static int vorbis_parse_setup_hdr_codebooks(vorbis_context *vc)
237
{
238
    uint_fast16_t cb;
239
    uint8_t  *tmp_vlc_bits;
240
    uint32_t *tmp_vlc_codes;
241
    GetBitContext *gb = &vc->gb;
242
    uint_fast16_t *codebook_multiplicands;
243

    
244
    vc->codebook_count = get_bits(gb, 8) + 1;
245

    
246
    AV_DEBUG(" Codebooks: %d \n", vc->codebook_count);
247

    
248
    vc->codebooks = av_mallocz(vc->codebook_count * sizeof(vorbis_codebook));
249
    tmp_vlc_bits  = av_mallocz(V_MAX_VLCS * sizeof(uint8_t));
250
    tmp_vlc_codes = av_mallocz(V_MAX_VLCS * sizeof(uint32_t));
251
    codebook_multiplicands = av_malloc(V_MAX_VLCS * sizeof(*codebook_multiplicands));
252

    
253
    for (cb = 0; cb < vc->codebook_count; ++cb) {
254
        vorbis_codebook *codebook_setup = &vc->codebooks[cb];
255
        uint_fast8_t ordered;
256
        uint_fast32_t t, used_entries = 0;
257
        uint_fast32_t entries;
258

    
259
        AV_DEBUG(" %d. Codebook \n", cb);
260

    
261
        if (get_bits(gb, 24) != 0x564342) {
262
            av_log(vc->avccontext, AV_LOG_ERROR, " %"PRIdFAST16". Codebook setup data corrupt. \n", cb);
263
            goto error;
264
        }
265

    
266
        codebook_setup->dimensions=get_bits(gb, 16);
267
        if (codebook_setup->dimensions > 16 || codebook_setup->dimensions == 0) {
268
            av_log(vc->avccontext, AV_LOG_ERROR, " %"PRIdFAST16". Codebook's dimension is invalid (%d). \n", cb, codebook_setup->dimensions);
269
            goto error;
270
        }
271
        entries = get_bits(gb, 24);
272
        if (entries > V_MAX_VLCS) {
273
            av_log(vc->avccontext, AV_LOG_ERROR, " %"PRIdFAST16". Codebook has too many entries (%"PRIdFAST32"). \n", cb, entries);
274
            goto error;
275
        }
276

    
277
        ordered = get_bits1(gb);
278

    
279
        AV_DEBUG(" codebook_dimensions %d, codebook_entries %d \n", codebook_setup->dimensions, entries);
280

    
281
        if (!ordered) {
282
            uint_fast16_t ce;
283
            uint_fast8_t  flag;
284
            uint_fast8_t  sparse = get_bits1(gb);
285

    
286
            AV_DEBUG(" not ordered \n");
287

    
288
            if (sparse) {
289
                AV_DEBUG(" sparse \n");
290

    
291
                used_entries = 0;
292
                for (ce = 0; ce < entries; ++ce) {
293
                    flag = get_bits1(gb);
294
                    if (flag) {
295
                        tmp_vlc_bits[ce] = get_bits(gb, 5) + 1;
296
                        ++used_entries;
297
                    } else
298
                        tmp_vlc_bits[ce] = 0;
299
                }
300
            } else {
301
                AV_DEBUG(" not sparse \n");
302

    
303
                used_entries = entries;
304
                for (ce = 0; ce < entries; ++ce)
305
                    tmp_vlc_bits[ce] = get_bits(gb, 5) + 1;
306
            }
307
        } else {
308
            uint_fast16_t current_entry = 0;
309
            uint_fast8_t current_length = get_bits(gb, 5)+1;
310

    
311
            AV_DEBUG(" ordered, current length: %d \n", current_length);  //FIXME
312

    
313
            used_entries = entries;
314
            for (; current_entry < used_entries && current_length <= 32; ++current_length) {
315
                uint_fast16_t i, number;
316

    
317
                AV_DEBUG(" number bits: %d ", ilog(entries - current_entry));
318

    
319
                number = get_bits(gb, ilog(entries - current_entry));
320

    
321
                AV_DEBUG(" number: %d \n", number);
322

    
323
                for (i = current_entry; i < number+current_entry; ++i)
324
                    if (i < used_entries)
325
                        tmp_vlc_bits[i] = current_length;
326

    
327
                current_entry+=number;
328
            }
329
            if (current_entry>used_entries) {
330
                av_log(vc->avccontext, AV_LOG_ERROR, " More codelengths than codes in codebook. \n");
331
                goto error;
332
            }
333
        }
334

    
335
        codebook_setup->lookup_type = get_bits(gb, 4);
336

    
337
        AV_DEBUG(" lookup type: %d : %s \n", codebook_setup->lookup_type, codebook_setup->lookup_type ? "vq" : "no lookup");
338

    
339
// If the codebook is used for (inverse) VQ, calculate codevectors.
340

    
341
        if (codebook_setup->lookup_type == 1) {
342
            uint_fast16_t i, j, k;
343
            uint_fast16_t codebook_lookup_values = ff_vorbis_nth_root(entries, codebook_setup->dimensions);
344

    
345
            float codebook_minimum_value = vorbisfloat2float(get_bits_long(gb, 32));
346
            float codebook_delta_value   = vorbisfloat2float(get_bits_long(gb, 32));
347
            uint_fast8_t codebook_value_bits = get_bits(gb, 4)+1;
348
            uint_fast8_t codebook_sequence_p = get_bits1(gb);
349

    
350
            AV_DEBUG(" We expect %d numbers for building the codevectors. \n", codebook_lookup_values);
351
            AV_DEBUG("  delta %f minmum %f \n", codebook_delta_value, codebook_minimum_value);
352

    
353
            for (i = 0; i < codebook_lookup_values; ++i) {
354
                codebook_multiplicands[i] = get_bits(gb, codebook_value_bits);
355

    
356
                AV_DEBUG(" multiplicands*delta+minmum : %e \n", (float)codebook_multiplicands[i]*codebook_delta_value+codebook_minimum_value);
357
                AV_DEBUG(" multiplicand %d \n", codebook_multiplicands[i]);
358
            }
359

    
360
// Weed out unused vlcs and build codevector vector
361
            codebook_setup->codevectors = used_entries ? av_mallocz(used_entries*codebook_setup->dimensions * sizeof(float)) : NULL;
362
            for (j = 0, i = 0; i < entries; ++i) {
363
                uint_fast8_t dim = codebook_setup->dimensions;
364

    
365
                if (tmp_vlc_bits[i]) {
366
                    float last = 0.0;
367
                    uint_fast32_t lookup_offset = i;
368

    
369
#ifdef V_DEBUG
370
                    av_log(vc->avccontext, AV_LOG_INFO, "Lookup offset %d ,", i);
371
#endif
372

    
373
                    for (k = 0; k < dim; ++k) {
374
                        uint_fast32_t multiplicand_offset = lookup_offset % codebook_lookup_values;
375
                        codebook_setup->codevectors[j * dim + k] = codebook_multiplicands[multiplicand_offset] * codebook_delta_value + codebook_minimum_value + last;
376
                        if (codebook_sequence_p)
377
                            last = codebook_setup->codevectors[j * dim + k];
378
                        lookup_offset/=codebook_lookup_values;
379
                    }
380
                    tmp_vlc_bits[j] = tmp_vlc_bits[i];
381

    
382
#ifdef V_DEBUG
383
                    av_log(vc->avccontext, AV_LOG_INFO, "real lookup offset %d, vector: ", j);
384
                    for (k = 0; k < dim; ++k)
385
                        av_log(vc->avccontext, AV_LOG_INFO, " %f ", codebook_setup->codevectors[j * dim + k]);
386
                    av_log(vc->avccontext, AV_LOG_INFO, "\n");
387
#endif
388

    
389
                    ++j;
390
                }
391
            }
392
            if (j != used_entries) {
393
                av_log(vc->avccontext, AV_LOG_ERROR, "Bug in codevector vector building code. \n");
394
                goto error;
395
            }
396
            entries = used_entries;
397
        } else if (codebook_setup->lookup_type >= 2) {
398
            av_log(vc->avccontext, AV_LOG_ERROR, "Codebook lookup type not supported. \n");
399
            goto error;
400
        }
401

    
402
// Initialize VLC table
403
        if (ff_vorbis_len2vlc(tmp_vlc_bits, tmp_vlc_codes, entries)) {
404
            av_log(vc->avccontext, AV_LOG_ERROR, " Invalid code lengths while generating vlcs. \n");
405
            goto error;
406
        }
407
        codebook_setup->maxdepth = 0;
408
        for (t = 0; t < entries; ++t)
409
            if (tmp_vlc_bits[t] >= codebook_setup->maxdepth)
410
                codebook_setup->maxdepth = tmp_vlc_bits[t];
411

    
412
        if (codebook_setup->maxdepth > 3 * V_NB_BITS)
413
            codebook_setup->nb_bits = V_NB_BITS2;
414
        else
415
            codebook_setup->nb_bits = V_NB_BITS;
416

    
417
        codebook_setup->maxdepth = (codebook_setup->maxdepth+codebook_setup->nb_bits - 1) / codebook_setup->nb_bits;
418

    
419
        if (init_vlc(&codebook_setup->vlc, codebook_setup->nb_bits, entries, tmp_vlc_bits, sizeof(*tmp_vlc_bits), sizeof(*tmp_vlc_bits), tmp_vlc_codes, sizeof(*tmp_vlc_codes), sizeof(*tmp_vlc_codes), INIT_VLC_LE)) {
420
            av_log(vc->avccontext, AV_LOG_ERROR, " Error generating vlc tables. \n");
421
            goto error;
422
        }
423
    }
424

    
425
    av_free(tmp_vlc_bits);
426
    av_free(tmp_vlc_codes);
427
    av_free(codebook_multiplicands);
428
    return 0;
429

    
430
// Error:
431
error:
432
    av_free(tmp_vlc_bits);
433
    av_free(tmp_vlc_codes);
434
    av_free(codebook_multiplicands);
435
    return -1;
436
}
437

    
438
// Process time domain transforms part (unused in Vorbis I)
439

    
440
static int vorbis_parse_setup_hdr_tdtransforms(vorbis_context *vc)
441
{
442
    GetBitContext *gb = &vc->gb;
443
    uint_fast8_t i;
444
    uint_fast8_t vorbis_time_count = get_bits(gb, 6) + 1;
445

    
446
    for (i = 0; i < vorbis_time_count; ++i) {
447
        uint_fast16_t vorbis_tdtransform = get_bits(gb, 16);
448

    
449
        AV_DEBUG(" Vorbis time domain transform %d: %d \n", vorbis_time_count, vorbis_tdtransform);
450

    
451
        if (vorbis_tdtransform) {
452
            av_log(vc->avccontext, AV_LOG_ERROR, "Vorbis time domain transform data nonzero. \n");
453
            return -1;
454
        }
455
    }
456
    return 0;
457
}
458

    
459
// Process floors part
460

    
461
static int vorbis_floor0_decode(vorbis_context *vc,
462
                                vorbis_floor_data *vfu, float *vec);
463
static void create_map(vorbis_context *vc, uint_fast8_t floor_number);
464
static int vorbis_floor1_decode(vorbis_context *vc,
465
                                vorbis_floor_data *vfu, float *vec);
466
static int vorbis_parse_setup_hdr_floors(vorbis_context *vc)
467
{
468
    GetBitContext *gb = &vc->gb;
469
    int i,j,k;
470

    
471
    vc->floor_count = get_bits(gb, 6) + 1;
472

    
473
    vc->floors = av_mallocz(vc->floor_count * sizeof(vorbis_floor));
474

    
475
    for (i = 0; i < vc->floor_count; ++i) {
476
        vorbis_floor *floor_setup = &vc->floors[i];
477

    
478
        floor_setup->floor_type = get_bits(gb, 16);
479

    
480
        AV_DEBUG(" %d. floor type %d \n", i, floor_setup->floor_type);
481

    
482
        if (floor_setup->floor_type == 1) {
483
            int maximum_class = -1;
484
            uint_fast8_t  rangebits;
485
            uint_fast32_t rangemax;
486
            uint_fast16_t floor1_values = 2;
487

    
488
            floor_setup->decode = vorbis_floor1_decode;
489

    
490
            floor_setup->data.t1.partitions = get_bits(gb, 5);
491

    
492
            AV_DEBUG(" %d.floor: %d partitions \n", i, floor_setup->data.t1.partitions);
493

    
494
            for (j = 0; j < floor_setup->data.t1.partitions; ++j) {
495
                floor_setup->data.t1.partition_class[j] = get_bits(gb, 4);
496
                if (floor_setup->data.t1.partition_class[j] > maximum_class)
497
                    maximum_class = floor_setup->data.t1.partition_class[j];
498

    
499
                AV_DEBUG(" %d. floor %d partition class %d \n", i, j, floor_setup->data.t1.partition_class[j]);
500

    
501
            }
502

    
503
            AV_DEBUG(" maximum class %d \n", maximum_class);
504

    
505
            for (j = 0; j <= maximum_class; ++j) {
506
                floor_setup->data.t1.class_dimensions[j] = get_bits(gb, 3) + 1;
507
                floor_setup->data.t1.class_subclasses[j] = get_bits(gb, 2);
508

    
509
                AV_DEBUG(" %d floor %d class dim: %d subclasses %d \n", i, j, floor_setup->data.t1.class_dimensions[j], floor_setup->data.t1.class_subclasses[j]);
510

    
511
                if (floor_setup->data.t1.class_subclasses[j]) {
512
                    GET_VALIDATED_INDEX(floor_setup->data.t1.class_masterbook[j], 8, vc->codebook_count)
513

    
514
                    AV_DEBUG("   masterbook: %d \n", floor_setup->data.t1.class_masterbook[j]);
515
                }
516

    
517
                for (k = 0; k < (1 << floor_setup->data.t1.class_subclasses[j]); ++k) {
518
                    int16_t bits = get_bits(gb, 8) - 1;
519
                    if (bits != -1)
520
                        VALIDATE_INDEX(bits, vc->codebook_count)
521
                    floor_setup->data.t1.subclass_books[j][k] = bits;
522

    
523
                    AV_DEBUG("    book %d. : %d \n", k, floor_setup->data.t1.subclass_books[j][k]);
524
                }
525
            }
526

    
527
            floor_setup->data.t1.multiplier = get_bits(gb, 2) + 1;
528
            floor_setup->data.t1.x_list_dim = 2;
529

    
530
            for (j = 0; j < floor_setup->data.t1.partitions; ++j)
531
                floor_setup->data.t1.x_list_dim+=floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]];
532

    
533
            floor_setup->data.t1.list = av_mallocz(floor_setup->data.t1.x_list_dim * sizeof(vorbis_floor1_entry));
534

    
535

    
536
            rangebits = get_bits(gb, 4);
537
            rangemax = (1 << rangebits);
538
            if (rangemax > vc->blocksize[1] / 2) {
539
                av_log(vc->avccontext, AV_LOG_ERROR,
540
                       "Floor value is too large for blocksize: %d (%d)\n",
541
                       rangemax, vc->blocksize[1] / 2);
542
                return -1;
543
            }
544
            floor_setup->data.t1.list[0].x = 0;
545
            floor_setup->data.t1.list[1].x = rangemax;
546

    
547
            for (j = 0; j < floor_setup->data.t1.partitions; ++j) {
548
                for (k = 0; k < floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]]; ++k, ++floor1_values) {
549
                    floor_setup->data.t1.list[floor1_values].x = get_bits(gb, rangebits);
550

    
551
                    AV_DEBUG(" %d. floor1 Y coord. %d \n", floor1_values, floor_setup->data.t1.list[floor1_values].x);
552
                }
553
            }
554

    
555
// Precalculate order of x coordinates - needed for decode
556
            ff_vorbis_ready_floor1_list(floor_setup->data.t1.list, floor_setup->data.t1.x_list_dim);
557
        } else if (floor_setup->floor_type == 0) {
558
            uint_fast8_t max_codebook_dim = 0;
559

    
560
            floor_setup->decode = vorbis_floor0_decode;
561

    
562
            floor_setup->data.t0.order          = get_bits(gb,  8);
563
            floor_setup->data.t0.rate           = get_bits(gb, 16);
564
            floor_setup->data.t0.bark_map_size  = get_bits(gb, 16);
565
            floor_setup->data.t0.amplitude_bits = get_bits(gb,  6);
566
            /* zero would result in a div by zero later *
567
             * 2^0 - 1 == 0                             */
568
            if (floor_setup->data.t0.amplitude_bits == 0) {
569
              av_log(vc->avccontext, AV_LOG_ERROR,
570
                     "Floor 0 amplitude bits is 0.\n");
571
              return -1;
572
            }
573
            floor_setup->data.t0.amplitude_offset = get_bits(gb, 8);
574
            floor_setup->data.t0.num_books        = get_bits(gb, 4) + 1;
575

    
576
            /* allocate mem for booklist */
577
            floor_setup->data.t0.book_list =
578
                av_malloc(floor_setup->data.t0.num_books);
579
            if (!floor_setup->data.t0.book_list)
580
                return -1;
581
            /* read book indexes */
582
            {
583
                int idx;
584
                uint_fast8_t book_idx;
585
                for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {
586
                    GET_VALIDATED_INDEX(book_idx, 8, vc->codebook_count)
587
                    floor_setup->data.t0.book_list[idx] = book_idx;
588
                    if (vc->codebooks[book_idx].dimensions > max_codebook_dim)
589
                        max_codebook_dim = vc->codebooks[book_idx].dimensions;
590
                }
591
            }
592

    
593
            create_map(vc, i);
594

    
595
            /* allocate mem for lsp coefficients */
596
            {
597
                /* codebook dim is for padding if codebook dim doesn't *
598
                 * divide order+1 then we need to read more data       */
599
                floor_setup->data.t0.lsp =
600
                    av_malloc((floor_setup->data.t0.order+1 + max_codebook_dim)
601
                              * sizeof(float));
602
                if (!floor_setup->data.t0.lsp)
603
                    return -1;
604
            }
605

    
606
#ifdef V_DEBUG /* debug output parsed headers */
607
            AV_DEBUG("floor0 order: %u\n", floor_setup->data.t0.order);
608
            AV_DEBUG("floor0 rate: %u\n", floor_setup->data.t0.rate);
609
            AV_DEBUG("floor0 bark map size: %u\n",
610
              floor_setup->data.t0.bark_map_size);
611
            AV_DEBUG("floor0 amplitude bits: %u\n",
612
              floor_setup->data.t0.amplitude_bits);
613
            AV_DEBUG("floor0 amplitude offset: %u\n",
614
              floor_setup->data.t0.amplitude_offset);
615
            AV_DEBUG("floor0 number of books: %u\n",
616
              floor_setup->data.t0.num_books);
617
            AV_DEBUG("floor0 book list pointer: %p\n",
618
              floor_setup->data.t0.book_list);
619
            {
620
              int idx;
621
              for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {
622
                  AV_DEBUG("  Book %d: %u\n",
623
                           idx+1,
624
                           floor_setup->data.t0.book_list[idx]);
625
              }
626
            }
627
#endif
628
        } else {
629
            av_log(vc->avccontext, AV_LOG_ERROR, "Invalid floor type!\n");
630
            return -1;
631
        }
632
    }
633
    return 0;
634
}
635

    
636
// Process residues part
637

    
638
static int vorbis_parse_setup_hdr_residues(vorbis_context *vc)
639
{
640
    GetBitContext *gb = &vc->gb;
641
    uint_fast8_t i, j, k;
642

    
643
    vc->residue_count = get_bits(gb, 6)+1;
644
    vc->residues      = av_mallocz(vc->residue_count * sizeof(vorbis_residue));
645

    
646
    AV_DEBUG(" There are %d residues. \n", vc->residue_count);
647

    
648
    for (i = 0; i < vc->residue_count; ++i) {
649
        vorbis_residue *res_setup = &vc->residues[i];
650
        uint_fast8_t cascade[64];
651
        uint_fast8_t high_bits;
652
        uint_fast8_t low_bits;
653

    
654
        res_setup->type = get_bits(gb, 16);
655

    
656
        AV_DEBUG(" %d. residue type %d \n", i, res_setup->type);
657

    
658
        res_setup->begin          = get_bits(gb, 24);
659
        res_setup->end            = get_bits(gb, 24);
660
        res_setup->partition_size = get_bits(gb, 24) + 1;
661
        /* Validations to prevent a buffer overflow later. */
662
        if (res_setup->begin>res_setup->end ||
663
            res_setup->end > vc->avccontext->channels * vc->blocksize[1] / 2 ||
664
            (res_setup->end-res_setup->begin) / res_setup->partition_size > V_MAX_PARTITIONS) {
665
            av_log(vc->avccontext, AV_LOG_ERROR, "partition out of bounds: type, begin, end, size, blocksize: %"PRIdFAST16", %"PRIdFAST32", %"PRIdFAST32", %u, %"PRIdFAST32"\n", res_setup->type, res_setup->begin, res_setup->end, res_setup->partition_size, vc->blocksize[1] / 2);
666
            return -1;
667
        }
668

    
669
        res_setup->classifications = get_bits(gb, 6) + 1;
670
        GET_VALIDATED_INDEX(res_setup->classbook, 8, vc->codebook_count)
671

    
672
        res_setup->ptns_to_read =
673
            (res_setup->end - res_setup->begin) / res_setup->partition_size;
674
        res_setup->classifs = av_malloc(res_setup->ptns_to_read *
675
                                        vc->audio_channels *
676
                                        sizeof(*res_setup->classifs));
677
        if (!res_setup->classifs)
678
            return AVERROR(ENOMEM);
679

    
680
        AV_DEBUG("    begin %d end %d part.size %d classif.s %d classbook %d \n", res_setup->begin, res_setup->end, res_setup->partition_size,
681
          res_setup->classifications, res_setup->classbook);
682

    
683
        for (j = 0; j < res_setup->classifications; ++j) {
684
            high_bits = 0;
685
            low_bits  = get_bits(gb, 3);
686
            if (get_bits1(gb))
687
                high_bits = get_bits(gb, 5);
688
            cascade[j] = (high_bits << 3) + low_bits;
689

    
690
            AV_DEBUG("     %d class casscade depth: %d \n", j, ilog(cascade[j]));
691
        }
692

    
693
        res_setup->maxpass = 0;
694
        for (j = 0; j < res_setup->classifications; ++j) {
695
            for (k = 0; k < 8; ++k) {
696
                if (cascade[j]&(1 << k)) {
697
                    GET_VALIDATED_INDEX(res_setup->books[j][k], 8, vc->codebook_count)
698

    
699
                    AV_DEBUG("     %d class casscade depth %d book: %d \n", j, k, res_setup->books[j][k]);
700

    
701
                    if (k>res_setup->maxpass)
702
                        res_setup->maxpass = k;
703
                } else {
704
                    res_setup->books[j][k] = -1;
705
                }
706
            }
707
        }
708
    }
709
    return 0;
710
}
711

    
712
// Process mappings part
713

    
714
static int vorbis_parse_setup_hdr_mappings(vorbis_context *vc)
715
{
716
    GetBitContext *gb = &vc->gb;
717
    uint_fast8_t i, j;
718

    
719
    vc->mapping_count = get_bits(gb, 6)+1;
720
    vc->mappings      = av_mallocz(vc->mapping_count * sizeof(vorbis_mapping));
721

    
722
    AV_DEBUG(" There are %d mappings. \n", vc->mapping_count);
723

    
724
    for (i = 0; i < vc->mapping_count; ++i) {
725
        vorbis_mapping *mapping_setup = &vc->mappings[i];
726

    
727
        if (get_bits(gb, 16)) {
728
            av_log(vc->avccontext, AV_LOG_ERROR, "Other mappings than type 0 are not compliant with the Vorbis I specification. \n");
729
            return -1;
730
        }
731
        if (get_bits1(gb)) {
732
            mapping_setup->submaps = get_bits(gb, 4) + 1;
733
        } else {
734
            mapping_setup->submaps = 1;
735
        }
736

    
737
        if (get_bits1(gb)) {
738
            mapping_setup->coupling_steps = get_bits(gb, 8) + 1;
739
            mapping_setup->magnitude      = av_mallocz(mapping_setup->coupling_steps * sizeof(uint_fast8_t));
740
            mapping_setup->angle          = av_mallocz(mapping_setup->coupling_steps * sizeof(uint_fast8_t));
741
            for (j = 0; j < mapping_setup->coupling_steps; ++j) {
742
                GET_VALIDATED_INDEX(mapping_setup->magnitude[j], ilog(vc->audio_channels - 1), vc->audio_channels)
743
                GET_VALIDATED_INDEX(mapping_setup->angle[j],     ilog(vc->audio_channels - 1), vc->audio_channels)
744
            }
745
        } else {
746
            mapping_setup->coupling_steps = 0;
747
        }
748

    
749
        AV_DEBUG("   %d mapping coupling steps: %d \n", i, mapping_setup->coupling_steps);
750

    
751
        if (get_bits(gb, 2)) {
752
            av_log(vc->avccontext, AV_LOG_ERROR, "%d. mapping setup data invalid. \n", i);
753
            return -1; // following spec.
754
        }
755

    
756
        if (mapping_setup->submaps>1) {
757
            mapping_setup->mux = av_mallocz(vc->audio_channels * sizeof(uint_fast8_t));
758
            for (j = 0; j < vc->audio_channels; ++j)
759
                mapping_setup->mux[j] = get_bits(gb, 4);
760
        }
761

    
762
        for (j = 0; j < mapping_setup->submaps; ++j) {
763
            skip_bits(gb, 8); // FIXME check?
764
            GET_VALIDATED_INDEX(mapping_setup->submap_floor[j],   8, vc->floor_count)
765
            GET_VALIDATED_INDEX(mapping_setup->submap_residue[j], 8, vc->residue_count)
766

    
767
            AV_DEBUG("   %d mapping %d submap : floor %d, residue %d \n", i, j, mapping_setup->submap_floor[j], mapping_setup->submap_residue[j]);
768
        }
769
    }
770
    return 0;
771
}
772

    
773
// Process modes part
774

    
775
static void create_map(vorbis_context *vc, uint_fast8_t floor_number)
776
{
777
    vorbis_floor *floors = vc->floors;
778
    vorbis_floor0 *vf;
779
    int idx;
780
    int_fast8_t blockflag;
781
    int_fast32_t *map;
782
    int_fast32_t n; //TODO: could theoretically be smaller?
783

    
784
    for (blockflag = 0; blockflag < 2; ++blockflag) {
785
        n = vc->blocksize[blockflag] / 2;
786
        floors[floor_number].data.t0.map[blockflag] =
787
            av_malloc((n+1) * sizeof(int_fast32_t)); // n + sentinel
788

    
789
        map =  floors[floor_number].data.t0.map[blockflag];
790
        vf  = &floors[floor_number].data.t0;
791

    
792
        for (idx = 0; idx < n; ++idx) {
793
            map[idx] = floor(BARK((vf->rate * idx) / (2.0f * n)) *
794
                             ((vf->bark_map_size) /
795
                              BARK(vf->rate / 2.0f)));
796
            if (vf->bark_map_size-1 < map[idx])
797
                map[idx] = vf->bark_map_size - 1;
798
        }
799
        map[n] = -1;
800
        vf->map_size[blockflag] = n;
801
    }
802

    
803
#   ifdef V_DEBUG
804
    for (idx = 0; idx <= n; ++idx) {
805
        AV_DEBUG("floor0 map: map at pos %d is %d\n",
806
                 idx, map[idx]);
807
    }
808
#   endif
809
}
810

    
811
static int vorbis_parse_setup_hdr_modes(vorbis_context *vc)
812
{
813
    GetBitContext *gb = &vc->gb;
814
    uint_fast8_t i;
815

    
816
    vc->mode_count = get_bits(gb, 6) + 1;
817
    vc->modes      = av_mallocz(vc->mode_count * sizeof(vorbis_mode));
818

    
819
    AV_DEBUG(" There are %d modes.\n", vc->mode_count);
820

    
821
    for (i = 0; i < vc->mode_count; ++i) {
822
        vorbis_mode *mode_setup = &vc->modes[i];
823

    
824
        mode_setup->blockflag     = get_bits1(gb);
825
        mode_setup->windowtype    = get_bits(gb, 16); //FIXME check
826
        mode_setup->transformtype = get_bits(gb, 16); //FIXME check
827
        GET_VALIDATED_INDEX(mode_setup->mapping, 8, vc->mapping_count);
828

    
829
        AV_DEBUG(" %d mode: blockflag %d, windowtype %d, transformtype %d, mapping %d \n", i, mode_setup->blockflag, mode_setup->windowtype, mode_setup->transformtype, mode_setup->mapping);
830
    }
831
    return 0;
832
}
833

    
834
// Process the whole setup header using the functions above
835

    
836
static int vorbis_parse_setup_hdr(vorbis_context *vc)
837
{
838
    GetBitContext *gb = &vc->gb;
839

    
840
    if ((get_bits(gb, 8) != 'v') || (get_bits(gb, 8) != 'o') ||
841
        (get_bits(gb, 8) != 'r') || (get_bits(gb, 8) != 'b') ||
842
        (get_bits(gb, 8) != 'i') || (get_bits(gb, 8) != 's')) {
843
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (no vorbis signature). \n");
844
        return -1;
845
    }
846

    
847
    if (vorbis_parse_setup_hdr_codebooks(vc)) {
848
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (codebooks). \n");
849
        return -2;
850
    }
851
    if (vorbis_parse_setup_hdr_tdtransforms(vc)) {
852
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (time domain transforms). \n");
853
        return -3;
854
    }
855
    if (vorbis_parse_setup_hdr_floors(vc)) {
856
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (floors). \n");
857
        return -4;
858
    }
859
    if (vorbis_parse_setup_hdr_residues(vc)) {
860
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (residues). \n");
861
        return -5;
862
    }
863
    if (vorbis_parse_setup_hdr_mappings(vc)) {
864
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (mappings). \n");
865
        return -6;
866
    }
867
    if (vorbis_parse_setup_hdr_modes(vc)) {
868
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (modes). \n");
869
        return -7;
870
    }
871
    if (!get_bits1(gb)) {
872
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (framing flag). \n");
873
        return -8; // framing flag bit unset error
874
    }
875

    
876
    return 0;
877
}
878

    
879
// Process the identification header
880

    
881
static int vorbis_parse_id_hdr(vorbis_context *vc)
882
{
883
    GetBitContext *gb = &vc->gb;
884
    uint_fast8_t bl0, bl1;
885

    
886
    if ((get_bits(gb, 8) != 'v') || (get_bits(gb, 8) != 'o') ||
887
        (get_bits(gb, 8) != 'r') || (get_bits(gb, 8) != 'b') ||
888
        (get_bits(gb, 8) != 'i') || (get_bits(gb, 8) != 's')) {
889
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (no vorbis signature). \n");
890
        return -1;
891
    }
892

    
893
    vc->version        = get_bits_long(gb, 32);    //FIXME check 0
894
    vc->audio_channels = get_bits(gb, 8);
895
    if (vc->audio_channels <= 0) {
896
        av_log(vc->avccontext, AV_LOG_ERROR, "Invalid number of channels\n");
897
        return -1;
898
    }
899
    vc->audio_samplerate = get_bits_long(gb, 32);
900
    if (vc->audio_samplerate <= 0) {
901
        av_log(vc->avccontext, AV_LOG_ERROR, "Invalid samplerate\n");
902
        return -1;
903
    }
904
    vc->bitrate_maximum = get_bits_long(gb, 32);
905
    vc->bitrate_nominal = get_bits_long(gb, 32);
906
    vc->bitrate_minimum = get_bits_long(gb, 32);
907
    bl0 = get_bits(gb, 4);
908
    bl1 = get_bits(gb, 4);
909
    vc->blocksize[0] = (1 << bl0);
910
    vc->blocksize[1] = (1 << bl1);
911
    if (bl0 > 13 || bl0 < 6 || bl1 > 13 || bl1 < 6 || bl1 < bl0) {
912
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (illegal blocksize). \n");
913
        return -3;
914
    }
915
    // output format int16
916
    if (vc->blocksize[1] / 2 * vc->audio_channels * 2 > AVCODEC_MAX_AUDIO_FRAME_SIZE) {
917
        av_log(vc->avccontext, AV_LOG_ERROR, "Vorbis channel count makes "
918
               "output packets too large.\n");
919
        return -4;
920
    }
921
    vc->win[0] = ff_vorbis_vwin[bl0 - 6];
922
    vc->win[1] = ff_vorbis_vwin[bl1 - 6];
923

    
924
    if ((get_bits1(gb)) == 0) {
925
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (framing flag not set). \n");
926
        return -2;
927
    }
928

    
929
    vc->channel_residues =  av_malloc((vc->blocksize[1]  / 2) * vc->audio_channels * sizeof(float));
930
    vc->channel_floors   =  av_malloc((vc->blocksize[1]  / 2) * vc->audio_channels * sizeof(float));
931
    vc->saved            =  av_mallocz((vc->blocksize[1] / 4) * vc->audio_channels * sizeof(float));
932
    vc->previous_window  = 0;
933

    
934
    ff_mdct_init(&vc->mdct[0], bl0, 1, -vc->scale_bias);
935
    ff_mdct_init(&vc->mdct[1], bl1, 1, -vc->scale_bias);
936

    
937
    AV_DEBUG(" 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 ",
938
            vc->version, vc->audio_channels, vc->audio_samplerate, vc->bitrate_maximum, vc->bitrate_nominal, vc->bitrate_minimum, vc->blocksize[0], vc->blocksize[1]);
939

    
940
/*
941
    BLK = vc->blocksize[0];
942
    for (i = 0; i < BLK / 2; ++i) {
943
        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)));
944
    }
945
*/
946

    
947
    return 0;
948
}
949

    
950
// Process the extradata using the functions above (identification header, setup header)
951

    
952
static av_cold int vorbis_decode_init(AVCodecContext *avccontext)
953
{
954
    vorbis_context *vc = avccontext->priv_data ;
955
    uint8_t *headers   = avccontext->extradata;
956
    int headers_len    = avccontext->extradata_size;
957
    uint8_t *header_start[3];
958
    int header_len[3];
959
    GetBitContext *gb = &(vc->gb);
960
    int hdr_type;
961

    
962
    vc->avccontext = avccontext;
963
    dsputil_init(&vc->dsp, avccontext);
964

    
965
    vc->scale_bias = 32768.0f;
966

    
967
    if (!headers_len) {
968
        av_log(avccontext, AV_LOG_ERROR, "Extradata missing.\n");
969
        return -1;
970
    }
971

    
972
    if (ff_split_xiph_headers(headers, headers_len, 30, header_start, header_len) < 0) {
973
        av_log(avccontext, AV_LOG_ERROR, "Extradata corrupt.\n");
974
        return -1;
975
    }
976

    
977
    init_get_bits(gb, header_start[0], header_len[0]*8);
978
    hdr_type = get_bits(gb, 8);
979
    if (hdr_type != 1) {
980
        av_log(avccontext, AV_LOG_ERROR, "First header is not the id header.\n");
981
        return -1;
982
    }
983
    if (vorbis_parse_id_hdr(vc)) {
984
        av_log(avccontext, AV_LOG_ERROR, "Id header corrupt.\n");
985
        vorbis_free(vc);
986
        return -1;
987
    }
988

    
989
    init_get_bits(gb, header_start[2], header_len[2]*8);
990
    hdr_type = get_bits(gb, 8);
991
    if (hdr_type != 5) {
992
        av_log(avccontext, AV_LOG_ERROR, "Third header is not the setup header.\n");
993
        vorbis_free(vc);
994
        return -1;
995
    }
996
    if (vorbis_parse_setup_hdr(vc)) {
997
        av_log(avccontext, AV_LOG_ERROR, "Setup header corrupt.\n");
998
        vorbis_free(vc);
999
        return -1;
1000
    }
1001

    
1002
    if (vc->audio_channels > 8)
1003
        avccontext->channel_layout = 0;
1004
    else
1005
        avccontext->channel_layout = ff_vorbis_channel_layouts[vc->audio_channels - 1];
1006

    
1007
    avccontext->channels    = vc->audio_channels;
1008
    avccontext->sample_rate = vc->audio_samplerate;
1009
    avccontext->frame_size  = FFMIN(vc->blocksize[0], vc->blocksize[1]) >> 2;
1010
    avccontext->sample_fmt  = AV_SAMPLE_FMT_S16;
1011

    
1012
    return 0 ;
1013
}
1014

    
1015
// Decode audiopackets -------------------------------------------------
1016

    
1017
// Read and decode floor
1018

    
1019
static int vorbis_floor0_decode(vorbis_context *vc,
1020
                                vorbis_floor_data *vfu, float *vec)
1021
{
1022
    vorbis_floor0 *vf = &vfu->t0;
1023
    float *lsp = vf->lsp;
1024
    uint_fast32_t amplitude;
1025
    uint_fast32_t book_idx;
1026
    uint_fast8_t blockflag = vc->modes[vc->mode_number].blockflag;
1027

    
1028
    amplitude = get_bits(&vc->gb, vf->amplitude_bits);
1029
    if (amplitude > 0) {
1030
        float last = 0;
1031
        uint_fast16_t lsp_len = 0;
1032
        uint_fast16_t idx;
1033
        vorbis_codebook codebook;
1034

    
1035
        book_idx = get_bits(&vc->gb, ilog(vf->num_books));
1036
        if (book_idx >= vf->num_books) {
1037
            av_log(vc->avccontext, AV_LOG_ERROR,
1038
                    "floor0 dec: booknumber too high!\n");
1039
            book_idx =  0;
1040
            //FIXME: look above
1041
        }
1042
        AV_DEBUG("floor0 dec: booknumber: %u\n", book_idx);
1043
        codebook = vc->codebooks[vf->book_list[book_idx]];
1044
        /* Invalid codebook! */
1045
        if (!codebook.codevectors)
1046
            return -1;
1047

    
1048
        while (lsp_len<vf->order) {
1049
            int vec_off;
1050

    
1051
            AV_DEBUG("floor0 dec: book dimension: %d\n", codebook.dimensions);
1052
            AV_DEBUG("floor0 dec: maximum depth: %d\n", codebook.maxdepth);
1053
            /* read temp vector */
1054
            vec_off = get_vlc2(&vc->gb, codebook.vlc.table,
1055
                               codebook.nb_bits, codebook.maxdepth)
1056
                      * codebook.dimensions;
1057
            AV_DEBUG("floor0 dec: vector offset: %d\n", vec_off);
1058
            /* copy each vector component and add last to it */
1059
            for (idx = 0; idx < codebook.dimensions; ++idx)
1060
                lsp[lsp_len+idx] = codebook.codevectors[vec_off+idx] + last;
1061
            last = lsp[lsp_len+idx-1]; /* set last to last vector component */
1062

    
1063
            lsp_len += codebook.dimensions;
1064
        }
1065
#ifdef V_DEBUG
1066
        /* DEBUG: output lsp coeffs */
1067
        {
1068
            int idx;
1069
            for (idx = 0; idx < lsp_len; ++idx)
1070
                AV_DEBUG("floor0 dec: coeff at %d is %f\n", idx, lsp[idx]);
1071
        }
1072
#endif
1073

    
1074
        /* synthesize floor output vector */
1075
        {
1076
            int i;
1077
            int order = vf->order;
1078
            float wstep = M_PI / vf->bark_map_size;
1079

    
1080
            for (i = 0; i < order; i++)
1081
                lsp[i] = 2.0f * cos(lsp[i]);
1082

    
1083
            AV_DEBUG("floor0 synth: map_size = %d; m = %d; wstep = %f\n",
1084
                     vf->map_size, order, wstep);
1085

    
1086
            i = 0;
1087
            while (i < vf->map_size[blockflag]) {
1088
                int j, iter_cond = vf->map[blockflag][i];
1089
                float p = 0.5f;
1090
                float q = 0.5f;
1091
                float two_cos_w = 2.0f * cos(wstep * iter_cond); // needed all times
1092

    
1093
                /* similar part for the q and p products */
1094
                for (j = 0; j + 1 < order; j += 2) {
1095
                    q *= lsp[j]     - two_cos_w;
1096
                    p *= lsp[j + 1] - two_cos_w;
1097
                }
1098
                if (j == order) { // even order
1099
                    p *= p * (2.0f - two_cos_w);
1100
                    q *= q * (2.0f + two_cos_w);
1101
                } else { // odd order
1102
                    q *= two_cos_w-lsp[j]; // one more time for q
1103

    
1104
                    /* final step and square */
1105
                    p *= p * (4.f - two_cos_w * two_cos_w);
1106
                    q *= q;
1107
                }
1108

    
1109
                /* calculate linear floor value */
1110
                {
1111
                    q = exp((((amplitude*vf->amplitude_offset) /
1112
                              (((1 << vf->amplitude_bits) - 1) * sqrt(p + q)))
1113
                             - vf->amplitude_offset) * .11512925f);
1114
                }
1115

    
1116
                /* fill vector */
1117
                do {
1118
                    vec[i] = q; ++i;
1119
                } while (vf->map[blockflag][i] == iter_cond);
1120
            }
1121
        }
1122
    } else {
1123
        /* this channel is unused */
1124
        return 1;
1125
    }
1126

    
1127
    AV_DEBUG(" Floor0 decoded\n");
1128

    
1129
    return 0;
1130
}
1131

    
1132
static int vorbis_floor1_decode(vorbis_context *vc,
1133
                                vorbis_floor_data *vfu, float *vec)
1134
{
1135
    vorbis_floor1 *vf = &vfu->t1;
1136
    GetBitContext *gb = &vc->gb;
1137
    uint_fast16_t range_v[4] = { 256, 128, 86, 64 };
1138
    uint_fast16_t range = range_v[vf->multiplier-1];
1139
    uint_fast16_t floor1_Y[258];
1140
    uint_fast16_t floor1_Y_final[258];
1141
    int floor1_flag[258];
1142
    uint_fast8_t class_;
1143
    uint_fast8_t cdim;
1144
    uint_fast8_t cbits;
1145
    uint_fast8_t csub;
1146
    uint_fast8_t cval;
1147
    int_fast16_t book;
1148
    uint_fast16_t offset;
1149
    uint_fast16_t i,j;
1150
    int_fast16_t adx, ady, dy, off, predicted;
1151
    int_fast32_t err;
1152

    
1153

    
1154
    if (!get_bits1(gb)) // silence
1155
        return 1;
1156

    
1157
// Read values (or differences) for the floor's points
1158

    
1159
    floor1_Y[0] = get_bits(gb, ilog(range - 1));
1160
    floor1_Y[1] = get_bits(gb, ilog(range - 1));
1161

    
1162
    AV_DEBUG("floor 0 Y %d floor 1 Y %d \n", floor1_Y[0], floor1_Y[1]);
1163

    
1164
    offset = 2;
1165
    for (i = 0; i < vf->partitions; ++i) {
1166
        class_ = vf->partition_class[i];
1167
        cdim   = vf->class_dimensions[class_];
1168
        cbits  = vf->class_subclasses[class_];
1169
        csub = (1 << cbits) - 1;
1170
        cval = 0;
1171

    
1172
        AV_DEBUG("Cbits %d \n", cbits);
1173

    
1174
        if (cbits) // this reads all subclasses for this partition's class
1175
            cval = get_vlc2(gb, vc->codebooks[vf->class_masterbook[class_]].vlc.table,
1176
                            vc->codebooks[vf->class_masterbook[class_]].nb_bits, 3);
1177

    
1178
        for (j = 0; j < cdim; ++j) {
1179
            book = vf->subclass_books[class_][cval & csub];
1180

    
1181
            AV_DEBUG("book %d Cbits %d cval %d  bits:%d \n", book, cbits, cval, get_bits_count(gb));
1182

    
1183
            cval = cval >> cbits;
1184
            if (book > -1) {
1185
                floor1_Y[offset+j] = get_vlc2(gb, vc->codebooks[book].vlc.table,
1186
                vc->codebooks[book].nb_bits, 3);
1187
            } else {
1188
                floor1_Y[offset+j] = 0;
1189
            }
1190

    
1191
            AV_DEBUG(" floor(%d) = %d \n", vf->list[offset+j].x, floor1_Y[offset+j]);
1192
        }
1193
        offset+=cdim;
1194
    }
1195

    
1196
// Amplitude calculation from the differences
1197

    
1198
    floor1_flag[0] = 1;
1199
    floor1_flag[1] = 1;
1200
    floor1_Y_final[0] = floor1_Y[0];
1201
    floor1_Y_final[1] = floor1_Y[1];
1202

    
1203
    for (i = 2; i < vf->x_list_dim; ++i) {
1204
        uint_fast16_t val, highroom, lowroom, room;
1205
        uint_fast16_t high_neigh_offs;
1206
        uint_fast16_t low_neigh_offs;
1207

    
1208
        low_neigh_offs  = vf->list[i].low;
1209
        high_neigh_offs = vf->list[i].high;
1210
        dy  = floor1_Y_final[high_neigh_offs] - floor1_Y_final[low_neigh_offs];  // render_point begin
1211
        adx = vf->list[high_neigh_offs].x - vf->list[low_neigh_offs].x;
1212
        ady = FFABS(dy);
1213
        err = ady * (vf->list[i].x - vf->list[low_neigh_offs].x);
1214
        off = err / adx;
1215
        if (dy < 0) {
1216
            predicted = floor1_Y_final[low_neigh_offs] - off;
1217
        } else {
1218
            predicted = floor1_Y_final[low_neigh_offs] + off;
1219
        } // render_point end
1220

    
1221
        val = floor1_Y[i];
1222
        highroom = range-predicted;
1223
        lowroom  = predicted;
1224
        if (highroom < lowroom) {
1225
            room = highroom * 2;
1226
        } else {
1227
            room = lowroom * 2;   // SPEC mispelling
1228
        }
1229
        if (val) {
1230
            floor1_flag[low_neigh_offs]  = 1;
1231
            floor1_flag[high_neigh_offs] = 1;
1232
            floor1_flag[i]               = 1;
1233
            if (val >= room) {
1234
                if (highroom > lowroom) {
1235
                    floor1_Y_final[i] = val - lowroom + predicted;
1236
                } else {
1237
                    floor1_Y_final[i] = predicted - val + highroom - 1;
1238
                }
1239
            } else {
1240
                if (val & 1) {
1241
                    floor1_Y_final[i] = predicted - (val + 1) / 2;
1242
                } else {
1243
                    floor1_Y_final[i] = predicted + val / 2;
1244
                }
1245
            }
1246
        } else {
1247
            floor1_flag[i]    = 0;
1248
            floor1_Y_final[i] = predicted;
1249
        }
1250

    
1251
        AV_DEBUG(" Decoded floor(%d) = %d / val %d \n", vf->list[i].x, floor1_Y_final[i], val);
1252
    }
1253

    
1254
// Curve synth - connect the calculated dots and convert from dB scale FIXME optimize ?
1255

    
1256
    ff_vorbis_floor1_render_list(vf->list, vf->x_list_dim, floor1_Y_final, floor1_flag, vf->multiplier, vec, vf->list[1].x);
1257

    
1258
    AV_DEBUG(" Floor decoded\n");
1259

    
1260
    return 0;
1261
}
1262

    
1263
// Read and decode residue
1264

    
1265
static av_always_inline int vorbis_residue_decode_internal(vorbis_context *vc,
1266
                                                           vorbis_residue *vr,
1267
                                                           uint_fast8_t ch,
1268
                                                           uint_fast8_t *do_not_decode,
1269
                                                           float *vec,
1270
                                                           uint_fast16_t vlen,
1271
                                                           int vr_type)
1272
{
1273
    GetBitContext *gb = &vc->gb;
1274
    uint_fast8_t c_p_c = vc->codebooks[vr->classbook].dimensions;
1275
    uint_fast16_t ptns_to_read = vr->ptns_to_read;
1276
    uint8_t *classifs = vr->classifs;
1277
    uint_fast8_t pass;
1278
    uint_fast8_t ch_used;
1279
    uint_fast8_t i,j,l;
1280
    uint_fast16_t k;
1281

    
1282
    if (vr_type == 2) {
1283
        for (j = 1; j < ch; ++j)
1284
            do_not_decode[0] &= do_not_decode[j];  // FIXME - clobbering input
1285
        if (do_not_decode[0])
1286
            return 0;
1287
        ch_used = 1;
1288
    } else {
1289
        ch_used = ch;
1290
    }
1291

    
1292
    AV_DEBUG(" residue type 0/1/2 decode begin, ch: %d  cpc %d  \n", ch, c_p_c);
1293

    
1294
    for (pass = 0; pass <= vr->maxpass; ++pass) { // FIXME OPTIMIZE?
1295
        uint_fast16_t voffset;
1296
        uint_fast16_t partition_count;
1297
        uint_fast16_t j_times_ptns_to_read;
1298

    
1299
        voffset = vr->begin;
1300
        for (partition_count = 0; partition_count < ptns_to_read;) {  // SPEC        error
1301
            if (!pass) {
1302
                uint_fast32_t inverse_class = ff_inverse[vr->classifications];
1303
                for (j_times_ptns_to_read = 0, j = 0; j < ch_used; ++j) {
1304
                    if (!do_not_decode[j]) {
1305
                        uint_fast32_t temp = get_vlc2(gb, vc->codebooks[vr->classbook].vlc.table,
1306
                        vc->codebooks[vr->classbook].nb_bits, 3);
1307

    
1308
                        AV_DEBUG("Classword: %d \n", temp);
1309

    
1310
                        assert(vr->classifications > 1 && temp <= 65536); //needed for inverse[]
1311
                        for (i = 0; i < c_p_c; ++i) {
1312
                            uint_fast32_t temp2;
1313

    
1314
                            temp2 = (((uint_fast64_t)temp) * inverse_class) >> 32;
1315
                            if (partition_count + c_p_c - 1 - i < ptns_to_read)
1316
                                classifs[j_times_ptns_to_read + partition_count + c_p_c - 1 - i] = temp - temp2 * vr->classifications;
1317
                            temp = temp2;
1318
                        }
1319
                    }
1320
                    j_times_ptns_to_read += ptns_to_read;
1321
                }
1322
            }
1323
            for (i = 0; (i < c_p_c) && (partition_count < ptns_to_read); ++i) {
1324
                for (j_times_ptns_to_read = 0, j = 0; j < ch_used; ++j) {
1325
                    uint_fast16_t voffs;
1326

    
1327
                    if (!do_not_decode[j]) {
1328
                        uint_fast8_t vqclass = classifs[j_times_ptns_to_read+partition_count];
1329
                        int_fast16_t vqbook = vr->books[vqclass][pass];
1330

    
1331
                        if (vqbook >= 0 && vc->codebooks[vqbook].codevectors) {
1332
                            uint_fast16_t coffs;
1333
                            unsigned dim =  vc->codebooks[vqbook].dimensions; // not uint_fast8_t: 64bit is slower here on amd64
1334
                            uint_fast16_t step = dim == 1 ? vr->partition_size
1335
                                                          : FASTDIV(vr->partition_size, dim);
1336
                            vorbis_codebook codebook = vc->codebooks[vqbook];
1337

    
1338
                            if (vr_type == 0) {
1339

    
1340
                                voffs = voffset+j*vlen;
1341
                                for (k = 0; k < step; ++k) {
1342
                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1343
                                    for (l = 0; l < dim; ++l)
1344
                                        vec[voffs + k + l * step] += codebook.codevectors[coffs + l];  // FPMATH
1345
                                }
1346
                            } else if (vr_type == 1) {
1347
                                voffs = voffset + j * vlen;
1348
                                for (k = 0; k < step; ++k) {
1349
                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1350
                                    for (l = 0; l < dim; ++l, ++voffs) {
1351
                                        vec[voffs]+=codebook.codevectors[coffs+l];  // FPMATH
1352

    
1353
                                        AV_DEBUG(" pass %d offs: %d curr: %f change: %f cv offs.: %d  \n", pass, voffs, vec[voffs], codebook.codevectors[coffs+l], coffs);
1354
                                    }
1355
                                }
1356
                            } else if (vr_type == 2 && ch == 2 && (voffset & 1) == 0 && (dim & 1) == 0) { // most frequent case optimized
1357
                                voffs = voffset >> 1;
1358

    
1359
                                if (dim == 2) {
1360
                                    for (k = 0; k < step; ++k) {
1361
                                        coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 2;
1362
                                        vec[voffs + k       ] += codebook.codevectors[coffs    ];  // FPMATH
1363
                                        vec[voffs + k + vlen] += codebook.codevectors[coffs + 1];  // FPMATH
1364
                                    }
1365
                                } else if (dim == 4) {
1366
                                    for (k = 0; k < step; ++k, voffs += 2) {
1367
                                        coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 4;
1368
                                        vec[voffs           ] += codebook.codevectors[coffs    ];  // FPMATH
1369
                                        vec[voffs + 1       ] += codebook.codevectors[coffs + 2];  // FPMATH
1370
                                        vec[voffs + vlen    ] += codebook.codevectors[coffs + 1];  // FPMATH
1371
                                        vec[voffs + vlen + 1] += codebook.codevectors[coffs + 3];  // FPMATH
1372
                                    }
1373
                                } else
1374
                                for (k = 0; k < step; ++k) {
1375
                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1376
                                    for (l = 0; l < dim; l += 2, voffs++) {
1377
                                        vec[voffs       ] += codebook.codevectors[coffs + l    ];  // FPMATH
1378
                                        vec[voffs + vlen] += codebook.codevectors[coffs + l + 1];  // FPMATH
1379

    
1380
                                        AV_DEBUG(" pass %d offs: %d curr: %f change: %f cv offs.: %d+%d  \n", pass, voffset / ch + (voffs % ch) * vlen, vec[voffset / ch + (voffs % ch) * vlen], codebook.codevectors[coffs + l], coffs, l);
1381
                                    }
1382
                                }
1383

    
1384
                            } else if (vr_type == 2) {
1385
                                voffs = voffset;
1386

    
1387
                                for (k = 0; k < step; ++k) {
1388
                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1389
                                    for (l = 0; l < dim; ++l, ++voffs) {
1390
                                        vec[voffs / ch + (voffs % ch) * vlen] += codebook.codevectors[coffs + l];  // FPMATH FIXME use if and counter instead of / and %
1391

    
1392
                                        AV_DEBUG(" pass %d offs: %d curr: %f change: %f cv offs.: %d+%d  \n", pass, voffset / ch + (voffs % ch) * vlen, vec[voffset / ch + (voffs % ch) * vlen], codebook.codevectors[coffs + l], coffs, l);
1393
                                    }
1394
                                }
1395
                            }
1396
                        }
1397
                    }
1398
                    j_times_ptns_to_read += ptns_to_read;
1399
                }
1400
                ++partition_count;
1401
                voffset += vr->partition_size;
1402
            }
1403
        }
1404
    }
1405
    return 0;
1406
}
1407

    
1408
static inline int vorbis_residue_decode(vorbis_context *vc, vorbis_residue *vr,
1409
                                        uint_fast8_t ch,
1410
                                        uint_fast8_t *do_not_decode,
1411
                                        float *vec, uint_fast16_t vlen)
1412
{
1413
    if (vr->type == 2)
1414
        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 2);
1415
    else if (vr->type == 1)
1416
        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 1);
1417
    else if (vr->type == 0)
1418
        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 0);
1419
    else {
1420
        av_log(vc->avccontext, AV_LOG_ERROR, " Invalid residue type while residue decode?! \n");
1421
        return -1;
1422
    }
1423
}
1424

    
1425
void vorbis_inverse_coupling(float *mag, float *ang, int blocksize)
1426
{
1427
    int i;
1428
    for (i = 0;  i < blocksize;  i++) {
1429
        if (mag[i] > 0.0) {
1430
            if (ang[i] > 0.0) {
1431
                ang[i] = mag[i] - ang[i];
1432
            } else {
1433
                float temp = ang[i];
1434
                ang[i]     = mag[i];
1435
                mag[i]    += temp;
1436
            }
1437
        } else {
1438
            if (ang[i] > 0.0) {
1439
                ang[i] += mag[i];
1440
            } else {
1441
                float temp = ang[i];
1442
                ang[i]     = mag[i];
1443
                mag[i]    -= temp;
1444
            }
1445
        }
1446
    }
1447
}
1448

    
1449
// Decode the audio packet using the functions above
1450

    
1451
static int vorbis_parse_audio_packet(vorbis_context *vc)
1452
{
1453
    GetBitContext *gb = &vc->gb;
1454

    
1455
    uint_fast8_t previous_window = vc->previous_window;
1456
    uint_fast8_t mode_number;
1457
    uint_fast8_t blockflag;
1458
    uint_fast16_t blocksize;
1459
    int_fast32_t i,j;
1460
    uint_fast8_t no_residue[255];
1461
    uint_fast8_t do_not_decode[255];
1462
    vorbis_mapping *mapping;
1463
    float *ch_res_ptr   = vc->channel_residues;
1464
    float *ch_floor_ptr = vc->channel_floors;
1465
    uint_fast8_t res_chan[255];
1466
    uint_fast8_t res_num = 0;
1467
    int_fast16_t retlen  = 0;
1468

    
1469
    if (get_bits1(gb)) {
1470
        av_log(vc->avccontext, AV_LOG_ERROR, "Not a Vorbis I audio packet.\n");
1471
        return -1; // packet type not audio
1472
    }
1473

    
1474
    if (vc->mode_count == 1) {
1475
        mode_number = 0;
1476
    } else {
1477
        GET_VALIDATED_INDEX(mode_number, ilog(vc->mode_count-1), vc->mode_count)
1478
    }
1479
    vc->mode_number = mode_number;
1480
    mapping = &vc->mappings[vc->modes[mode_number].mapping];
1481

    
1482
    AV_DEBUG(" Mode number: %d , mapping: %d , blocktype %d \n", mode_number, vc->modes[mode_number].mapping, vc->modes[mode_number].blockflag);
1483

    
1484
    blockflag = vc->modes[mode_number].blockflag;
1485
    blocksize = vc->blocksize[blockflag];
1486
    if (blockflag)
1487
        skip_bits(gb, 2); // previous_window, next_window
1488

    
1489
    memset(ch_res_ptr,   0, sizeof(float) * vc->audio_channels * blocksize / 2); //FIXME can this be removed ?
1490
    memset(ch_floor_ptr, 0, sizeof(float) * vc->audio_channels * blocksize / 2); //FIXME can this be removed ?
1491

    
1492
// Decode floor
1493

    
1494
    for (i = 0; i < vc->audio_channels; ++i) {
1495
        vorbis_floor *floor;
1496
        int ret;
1497
        if (mapping->submaps > 1) {
1498
            floor = &vc->floors[mapping->submap_floor[mapping->mux[i]]];
1499
        } else {
1500
            floor = &vc->floors[mapping->submap_floor[0]];
1501
        }
1502

    
1503
        ret = floor->decode(vc, &floor->data, ch_floor_ptr);
1504

    
1505
        if (ret < 0) {
1506
            av_log(vc->avccontext, AV_LOG_ERROR, "Invalid codebook in vorbis_floor_decode.\n");
1507
            return -1;
1508
        }
1509
        no_residue[i] = ret;
1510
        ch_floor_ptr += blocksize / 2;
1511
    }
1512

    
1513
// Nonzero vector propagate
1514

    
1515
    for (i = mapping->coupling_steps - 1; i >= 0; --i) {
1516
        if (!(no_residue[mapping->magnitude[i]] & no_residue[mapping->angle[i]])) {
1517
            no_residue[mapping->magnitude[i]] = 0;
1518
            no_residue[mapping->angle[i]]     = 0;
1519
        }
1520
    }
1521

    
1522
// Decode residue
1523

    
1524
    for (i = 0; i < mapping->submaps; ++i) {
1525
        vorbis_residue *residue;
1526
        uint_fast8_t ch = 0;
1527

    
1528
        for (j = 0; j < vc->audio_channels; ++j) {
1529
            if ((mapping->submaps == 1) || (i == mapping->mux[j])) {
1530
                res_chan[j] = res_num;
1531
                if (no_residue[j]) {
1532
                    do_not_decode[ch] = 1;
1533
                } else {
1534
                    do_not_decode[ch] = 0;
1535
                }
1536
                ++ch;
1537
                ++res_num;
1538
            }
1539
        }
1540
        residue = &vc->residues[mapping->submap_residue[i]];
1541
        vorbis_residue_decode(vc, residue, ch, do_not_decode, ch_res_ptr, blocksize/2);
1542

    
1543
        ch_res_ptr += ch * blocksize / 2;
1544
    }
1545

    
1546
// Inverse coupling
1547

    
1548
    for (i = mapping->coupling_steps - 1; i >= 0; --i) { //warning: i has to be signed
1549
        float *mag, *ang;
1550

    
1551
        mag = vc->channel_residues+res_chan[mapping->magnitude[i]] * blocksize / 2;
1552
        ang = vc->channel_residues+res_chan[mapping->angle[i]]     * blocksize / 2;
1553
        vc->dsp.vorbis_inverse_coupling(mag, ang, blocksize / 2);
1554
    }
1555

    
1556
// Dotproduct, MDCT
1557

    
1558
    for (j = vc->audio_channels-1;j >= 0; j--) {
1559
        ch_floor_ptr = vc->channel_floors   + j           * blocksize / 2;
1560
        ch_res_ptr   = vc->channel_residues + res_chan[j] * blocksize / 2;
1561
        vc->dsp.vector_fmul(ch_floor_ptr, ch_floor_ptr, ch_res_ptr, blocksize / 2);
1562
        ff_imdct_half(&vc->mdct[blockflag], ch_res_ptr, ch_floor_ptr);
1563
    }
1564

    
1565
// Overlap/add, save data for next overlapping  FPMATH
1566

    
1567
    retlen = (blocksize + vc->blocksize[previous_window]) / 4;
1568
    for (j = 0; j < vc->audio_channels; j++) {
1569
        uint_fast16_t bs0 = vc->blocksize[0];
1570
        uint_fast16_t bs1 = vc->blocksize[1];
1571
        float *residue    = vc->channel_residues + res_chan[j] * blocksize / 2;
1572
        float *saved      = vc->saved + j * bs1 / 4;
1573
        float *ret        = vc->channel_floors + j * retlen;
1574
        float *buf        = residue;
1575
        const float *win  = vc->win[blockflag & previous_window];
1576

    
1577
        if (blockflag == previous_window) {
1578
            vc->dsp.vector_fmul_window(ret, saved, buf, win, blocksize / 4);
1579
        } else if (blockflag > previous_window) {
1580
            vc->dsp.vector_fmul_window(ret, saved, buf, win, bs0 / 4);
1581
            memcpy(ret+bs0/2, buf+bs0/4, ((bs1-bs0)/4) * sizeof(float));
1582
        } else {
1583
            memcpy(ret, saved, ((bs1 - bs0) / 4) * sizeof(float));
1584
            vc->dsp.vector_fmul_window(ret + (bs1 - bs0) / 4, saved + (bs1 - bs0) / 4, buf, win, bs0 / 4);
1585
        }
1586
        memcpy(saved, buf + blocksize / 4, blocksize / 4 * sizeof(float));
1587
    }
1588

    
1589
    vc->previous_window = blockflag;
1590
    return retlen;
1591
}
1592

    
1593
// Return the decoded audio packet through the standard api
1594

    
1595
static int vorbis_decode_frame(AVCodecContext *avccontext,
1596
                               void *data, int *data_size,
1597
                               AVPacket *avpkt)
1598
{
1599
    const uint8_t *buf = avpkt->data;
1600
    int buf_size       = avpkt->size;
1601
    vorbis_context *vc = avccontext->priv_data ;
1602
    GetBitContext *gb = &(vc->gb);
1603
    const float *channel_ptrs[255];
1604
    int i;
1605

    
1606
    int_fast16_t len;
1607

    
1608
    if (!buf_size)
1609
        return 0;
1610

    
1611
    AV_DEBUG("packet length %d \n", buf_size);
1612

    
1613
    init_get_bits(gb, buf, buf_size*8);
1614

    
1615
    len = vorbis_parse_audio_packet(vc);
1616

    
1617
    if (len <= 0) {
1618
        *data_size = 0;
1619
        return buf_size;
1620
    }
1621

    
1622
    if (!vc->first_frame) {
1623
        vc->first_frame = 1;
1624
        *data_size = 0;
1625
        return buf_size ;
1626
    }
1627

    
1628
    AV_DEBUG("parsed %d bytes %d bits, returned %d samples (*ch*bits) \n", get_bits_count(gb)/8, get_bits_count(gb)%8, len);
1629

    
1630
    if (vc->audio_channels > 8) {
1631
        for (i = 0; i < vc->audio_channels; i++)
1632
            channel_ptrs[i] = vc->channel_floors + i * len;
1633
    } else {
1634
        for (i = 0; i < vc->audio_channels; i++)
1635
            channel_ptrs[i] = vc->channel_floors +
1636
                              len * ff_vorbis_channel_layout_offsets[vc->audio_channels - 1][i];
1637
    }
1638

    
1639
    vc->dsp.float_to_int16_interleave(data, channel_ptrs, len, vc->audio_channels);
1640
    *data_size = len * 2 * vc->audio_channels;
1641

    
1642
    return buf_size ;
1643
}
1644

    
1645
// Close decoder
1646

    
1647
static av_cold int vorbis_decode_close(AVCodecContext *avccontext)
1648
{
1649
    vorbis_context *vc = avccontext->priv_data;
1650

    
1651
    vorbis_free(vc);
1652

    
1653
    return 0 ;
1654
}
1655

    
1656
AVCodec ff_vorbis_decoder = {
1657
    "vorbis",
1658
    AVMEDIA_TYPE_AUDIO,
1659
    CODEC_ID_VORBIS,
1660
    sizeof(vorbis_context),
1661
    vorbis_decode_init,
1662
    NULL,
1663
    vorbis_decode_close,
1664
    vorbis_decode_frame,
1665
    .long_name = NULL_IF_CONFIG_SMALL("Vorbis"),
1666
    .channel_layouts = ff_vorbis_channel_layouts,
1667
};
1668