Statistics
| Branch: | Revision:

ffmpeg / libavcodec / vorbis.c @ 36cd3069

History | View | Annotate | Download (61.8 KB)

1
/**
2
 * @file vorbis.c
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
#undef V_DEBUG
25
//#define V_DEBUG
26
//#define AV_DEBUG(...) av_log(NULL, AV_LOG_INFO, __VA_ARGS__)
27

    
28
#include <math.h>
29

    
30
#define ALT_BITSTREAM_READER_LE
31
#include "avcodec.h"
32
#include "bitstream.h"
33
#include "dsputil.h"
34

    
35
#include "vorbis.h"
36

    
37
#define V_NB_BITS 8
38
#define V_NB_BITS2 11
39
#define V_MAX_VLCS (1<<16)
40

    
41
#ifndef V_DEBUG
42
#define AV_DEBUG(...)
43
#endif
44

    
45
#undef NDEBUG
46
#include <assert.h>
47

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

    
57
typedef union vorbis_floor_u vorbis_floor_data;
58
typedef struct vorbis_floor0_s vorbis_floor0;
59
typedef struct vorbis_floor1_s vorbis_floor1;
60
struct vorbis_context_s;
61
typedef
62
uint_fast8_t (* vorbis_floor_decode_func)
63
             (struct vorbis_context_s *, vorbis_floor_data *, float *);
64
typedef struct {
65
    uint_fast8_t floor_type;
66
    vorbis_floor_decode_func decode;
67
    union vorbis_floor_u
68
    {
69
        struct vorbis_floor0_s
70
        {
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
        {
84
            uint_fast8_t partitions;
85
            uint_fast8_t maximum_class;
86
            uint_fast8_t partition_class[32];
87
            uint_fast8_t class_dimensions[16];
88
            uint_fast8_t class_subclasses[16];
89
            uint_fast8_t class_masterbook[16];
90
            int_fast16_t subclass_books[16][8];
91
            uint_fast8_t multiplier;
92
            uint_fast16_t x_list_dim;
93
            floor1_entry_t * list;
94
        } t1;
95
    } data;
96
} vorbis_floor;
97

    
98
typedef struct {
99
    uint_fast16_t type;
100
    uint_fast32_t begin;
101
    uint_fast32_t end;
102
    uint_fast32_t partition_size;
103
    uint_fast8_t classifications;
104
    uint_fast8_t classbook;
105
    int_fast16_t books[64][8];
106
    uint_fast8_t maxpass;
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
    MDCTContext 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
    float *channel_residues;
153
    float *channel_floors;
154
    float *saved;
155
    uint_fast16_t saved_start;
156
    float *ret;
157
    float *buf;
158
    float *buf_tmp;
159
    uint_fast32_t add_bias; // for float->int conversion
160
    uint_fast32_t exp_bias;
161
} vorbis_context;
162

    
163
/* Helper functions */
164

    
165
#define BARK(x) \
166
    (13.1f*atan(0.00074f*(x))+2.24f*atan(1.85e-8f*(x)*(x))+1e-4f*(x))
167

    
168
unsigned int ff_vorbis_nth_root(unsigned int x, unsigned int n) {   // x^(1/n)
169
    unsigned int ret=0, i, j;
170

    
171
    do {
172
        ++ret;
173
        for(i=0,j=ret;i<n-1;i++) j*=ret;
174
    } while (j<=x);
175

    
176
    return (ret-1);
177
}
178

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

    
186

    
187
// Generate vlc codes from vorbis huffman code lengths
188

    
189
int ff_vorbis_len2vlc(uint8_t *bits, uint32_t *codes, uint_fast32_t num) {
190
    uint_fast32_t exit_at_level[33]={404,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
191
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
192

    
193
    uint_fast8_t i,j;
194
    uint_fast32_t code,p;
195

    
196
#ifdef V_DEBUG
197
    GetBitContext gb;
198
#endif
199

    
200
    for(p=0;(bits[p]==0) && (p<num);++p);
201
    if (p==num) {
202
//        av_log(vc->avccontext, AV_LOG_INFO, "An empty codebook. Heh?! \n");
203
        return 0;
204
    }
205

    
206
    codes[p]=0;
207
    for(i=0;i<bits[p];++i) {
208
        exit_at_level[i+1]=1<<i;
209
    }
210

    
211
#ifdef V_DEBUG
212
    av_log(NULL, AV_LOG_INFO, " %d. of %d code len %d code %d - ", p, num, bits[p], codes[p]);
213
    init_get_bits(&gb, (uint_fast8_t *)&codes[p], bits[p]);
214
    for(i=0;i<bits[p];++i) {
215
        av_log(NULL, AV_LOG_INFO, "%s", get_bits1(&gb) ? "1" : "0");
216
    }
217
    av_log(NULL, AV_LOG_INFO, "\n");
218
#endif
219

    
220
    ++p;
221

    
222
    for(;p<num;++p) {
223
        if (bits[p]==0) continue;
224
        // find corresponding exit(node which the tree can grow further from)
225
        for(i=bits[p];i>0;--i) {
226
            if (exit_at_level[i]) break;
227
        }
228
        if (!i) return 1; // overspecified tree
229
        code=exit_at_level[i];
230
        exit_at_level[i]=0;
231
        // construct code (append 0s to end) and introduce new exits
232
        for(j=i+1;j<=bits[p];++j) {
233
            exit_at_level[j]=code+(1<<(j-1));
234
        }
235
        codes[p]=code;
236

    
237
#ifdef V_DEBUG
238
        av_log(NULL, AV_LOG_INFO, " %d. code len %d code %d - ", p, bits[p], codes[p]);
239
        init_get_bits(&gb, (uint_fast8_t *)&codes[p], bits[p]);
240
        for(i=0;i<bits[p];++i) {
241
            av_log(NULL, AV_LOG_INFO, "%s", get_bits1(&gb) ? "1" : "0");
242
        }
243
        av_log(NULL, AV_LOG_INFO, "\n");
244
#endif
245

    
246
    }
247

    
248
    //no exits should be left (underspecified tree - ie. unused valid vlcs - not allowed by SPEC)
249
    for (p=1; p<33; p++)
250
        if (exit_at_level[p]) return 1;
251

    
252
    return 0;
253
}
254

    
255
void ff_vorbis_ready_floor1_list(floor1_entry_t * list, int values) {
256
    int i;
257
    list[0].sort = 0;
258
    list[1].sort = 1;
259
    for (i = 2; i < values; i++) {
260
        int j;
261
        list[i].low = 0;
262
        list[i].high = 1;
263
        list[i].sort = i;
264
        for (j = 2; j < i; j++) {
265
            int tmp = list[j].x;
266
            if (tmp < list[i].x) {
267
                if (tmp > list[list[i].low].x) list[i].low = j;
268
            } else {
269
                if (tmp < list[list[i].high].x) list[i].high = j;
270
            }
271
        }
272
    }
273
    for (i = 0; i < values - 1; i++) {
274
        int j;
275
        for (j = i + 1; j < values; j++) {
276
            if (list[list[i].sort].x > list[list[j].sort].x) {
277
                int tmp = list[i].sort;
278
                list[i].sort = list[j].sort;
279
                list[j].sort = tmp;
280
            }
281
        }
282
    }
283
}
284

    
285
// Free all allocated memory -----------------------------------------
286

    
287
static void vorbis_free(vorbis_context *vc) {
288
    int_fast16_t i;
289

    
290
    av_freep(&vc->channel_residues);
291
    av_freep(&vc->channel_floors);
292
    av_freep(&vc->saved);
293
    av_freep(&vc->ret);
294
    av_freep(&vc->buf);
295
    av_freep(&vc->buf_tmp);
296

    
297
    av_freep(&vc->residues);
298
    av_freep(&vc->modes);
299

    
300
    ff_mdct_end(&vc->mdct[0]);
301
    ff_mdct_end(&vc->mdct[1]);
302

    
303
    for(i=0;i<vc->codebook_count;++i) {
304
        av_free(vc->codebooks[i].codevectors);
305
        free_vlc(&vc->codebooks[i].vlc);
306
    }
307
    av_freep(&vc->codebooks);
308

    
309
    for(i=0;i<vc->floor_count;++i) {
310
        if(vc->floors[i].floor_type==0) {
311
            av_free(vc->floors[i].data.t0.map[0]);
312
            av_free(vc->floors[i].data.t0.map[1]);
313
            av_free(vc->floors[i].data.t0.book_list);
314
            av_free(vc->floors[i].data.t0.lsp);
315
        }
316
        else {
317
            av_free(vc->floors[i].data.t1.list);
318
        }
319
    }
320
    av_freep(&vc->floors);
321

    
322
    for(i=0;i<vc->mapping_count;++i) {
323
        av_free(vc->mappings[i].magnitude);
324
        av_free(vc->mappings[i].angle);
325
        av_free(vc->mappings[i].mux);
326
    }
327
    av_freep(&vc->mappings);
328

    
329
    if(vc->exp_bias){
330
        av_freep(&vc->win[0]);
331
        av_freep(&vc->win[1]);
332
    }
333
}
334

    
335
// Parse setup header -------------------------------------------------
336

    
337
// Process codebooks part
338

    
339
static int vorbis_parse_setup_hdr_codebooks(vorbis_context *vc) {
340
    uint_fast16_t cb;
341
    uint8_t *tmp_vlc_bits;
342
    uint32_t *tmp_vlc_codes;
343
    GetBitContext *gb=&vc->gb;
344

    
345
    vc->codebook_count=get_bits(gb,8)+1;
346

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

    
349
    vc->codebooks=(vorbis_codebook *)av_mallocz(vc->codebook_count * sizeof(vorbis_codebook));
350
    tmp_vlc_bits=(uint8_t *)av_mallocz(V_MAX_VLCS * sizeof(uint8_t));
351
    tmp_vlc_codes=(uint32_t *)av_mallocz(V_MAX_VLCS * sizeof(uint32_t));
352

    
353
    for(cb=0;cb<vc->codebook_count;++cb) {
354
        vorbis_codebook *codebook_setup=&vc->codebooks[cb];
355
        uint_fast8_t ordered;
356
        uint_fast32_t t, used_entries=0;
357
        uint_fast32_t entries;
358

    
359
        AV_DEBUG(" %d. Codebook \n", cb);
360

    
361
        if (get_bits(gb, 24)!=0x564342) {
362
            av_log(vc->avccontext, AV_LOG_ERROR, " %"PRIdFAST16". Codebook setup data corrupt. \n", cb);
363
            goto error;
364
        }
365

    
366
        codebook_setup->dimensions=get_bits(gb, 16);
367
        if (codebook_setup->dimensions>16) {
368
            av_log(vc->avccontext, AV_LOG_ERROR, " %"PRIdFAST16". Codebook's dimension is too large (%d). \n", cb, codebook_setup->dimensions);
369
            goto error;
370
        }
371
        entries=get_bits(gb, 24);
372
        if (entries>V_MAX_VLCS) {
373
            av_log(vc->avccontext, AV_LOG_ERROR, " %"PRIdFAST16". Codebook has too many entries (%"PRIdFAST32"). \n", cb, entries);
374
            goto error;
375
        }
376

    
377
        ordered=get_bits1(gb);
378

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

    
381
        if (!ordered) {
382
            uint_fast16_t ce;
383
            uint_fast8_t flag;
384
            uint_fast8_t sparse=get_bits1(gb);
385

    
386
            AV_DEBUG(" not ordered \n");
387

    
388
            if (sparse) {
389
                AV_DEBUG(" sparse \n");
390

    
391
                used_entries=0;
392
                for(ce=0;ce<entries;++ce) {
393
                    flag=get_bits1(gb);
394
                    if (flag) {
395
                        tmp_vlc_bits[ce]=get_bits(gb, 5)+1;
396
                        ++used_entries;
397
                    }
398
                    else tmp_vlc_bits[ce]=0;
399
                }
400
            } else {
401
                AV_DEBUG(" not sparse \n");
402

    
403
                used_entries=entries;
404
                for(ce=0;ce<entries;++ce) {
405
                    tmp_vlc_bits[ce]=get_bits(gb, 5)+1;
406
                }
407
            }
408
        } else {
409
            uint_fast16_t current_entry=0;
410
            uint_fast8_t current_length=get_bits(gb, 5)+1;
411

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

    
414
            used_entries=entries;
415
            for(;current_entry<used_entries;++current_length) {
416
                uint_fast16_t i, number;
417

    
418
                AV_DEBUG(" number bits: %d ", ilog(entries - current_entry));
419

    
420
                number=get_bits(gb, ilog(entries - current_entry));
421

    
422
                AV_DEBUG(" number: %d \n", number);
423

    
424
                for(i=current_entry;i<number+current_entry;++i) {
425
                    if (i<used_entries) tmp_vlc_bits[i]=current_length;
426
                }
427

    
428
                current_entry+=number;
429
            }
430
            if (current_entry>used_entries) {
431
                av_log(vc->avccontext, AV_LOG_ERROR, " More codelengths than codes in codebook. \n");
432
                goto error;
433
            }
434
        }
435

    
436
        codebook_setup->lookup_type=get_bits(gb, 4);
437

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

    
440
// If the codebook is used for (inverse) VQ, calculate codevectors.
441

    
442
        if (codebook_setup->lookup_type==1) {
443
            uint_fast16_t i, j, k;
444
            uint_fast16_t codebook_lookup_values=ff_vorbis_nth_root(entries, codebook_setup->dimensions);
445
            uint_fast16_t codebook_multiplicands[codebook_lookup_values];
446

    
447
            float codebook_minimum_value=vorbisfloat2float(get_bits_long(gb, 32));
448
            float codebook_delta_value=vorbisfloat2float(get_bits_long(gb, 32));
449
            uint_fast8_t codebook_value_bits=get_bits(gb, 4)+1;
450
            uint_fast8_t codebook_sequence_p=get_bits1(gb);
451

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

    
455
            for(i=0;i<codebook_lookup_values;++i) {
456
                codebook_multiplicands[i]=get_bits(gb, codebook_value_bits);
457

    
458
                AV_DEBUG(" multiplicands*delta+minmum : %e \n", (float)codebook_multiplicands[i]*codebook_delta_value+codebook_minimum_value);
459
                AV_DEBUG(" multiplicand %d \n", codebook_multiplicands[i]);
460
            }
461

    
462
// Weed out unused vlcs and build codevector vector
463
            codebook_setup->codevectors=(float *)av_mallocz(used_entries*codebook_setup->dimensions * sizeof(float));
464
            for(j=0, i=0;i<entries;++i) {
465
                uint_fast8_t dim=codebook_setup->dimensions;
466

    
467
                if (tmp_vlc_bits[i]) {
468
                    float last=0.0;
469
                    uint_fast32_t lookup_offset=i;
470

    
471
#ifdef V_DEBUG
472
                    av_log(vc->avccontext, AV_LOG_INFO, "Lookup offset %d ,", i);
473
#endif
474

    
475
                    for(k=0;k<dim;++k) {
476
                        uint_fast32_t multiplicand_offset = lookup_offset % codebook_lookup_values;
477
                        codebook_setup->codevectors[j*dim+k]=codebook_multiplicands[multiplicand_offset]*codebook_delta_value+codebook_minimum_value+last;
478
                        if (codebook_sequence_p) {
479
                            last=codebook_setup->codevectors[j*dim+k];
480
                        }
481
                        lookup_offset/=codebook_lookup_values;
482
                    }
483
                    tmp_vlc_bits[j]=tmp_vlc_bits[i];
484

    
485
#ifdef V_DEBUG
486
                    av_log(vc->avccontext, AV_LOG_INFO, "real lookup offset %d, vector: ", j);
487
                    for(k=0;k<dim;++k) {
488
                        av_log(vc->avccontext, AV_LOG_INFO, " %f ", codebook_setup->codevectors[j*dim+k]);
489
                    }
490
                    av_log(vc->avccontext, AV_LOG_INFO, "\n");
491
#endif
492

    
493
                    ++j;
494
                }
495
            }
496
            if (j!=used_entries) {
497
                av_log(vc->avccontext, AV_LOG_ERROR, "Bug in codevector vector building code. \n");
498
                goto error;
499
            }
500
            entries=used_entries;
501
        }
502
        else if (codebook_setup->lookup_type>=2) {
503
            av_log(vc->avccontext, AV_LOG_ERROR, "Codebook lookup type not supported. \n");
504
            goto error;
505
        }
506

    
507
// Initialize VLC table
508
        if (ff_vorbis_len2vlc(tmp_vlc_bits, tmp_vlc_codes, entries)) {
509
            av_log(vc->avccontext, AV_LOG_ERROR, " Invalid code lengths while generating vlcs. \n");
510
            goto error;
511
        }
512
        codebook_setup->maxdepth=0;
513
        for(t=0;t<entries;++t)
514
            if (tmp_vlc_bits[t]>=codebook_setup->maxdepth) codebook_setup->maxdepth=tmp_vlc_bits[t];
515

    
516
        if(codebook_setup->maxdepth > 3*V_NB_BITS) codebook_setup->nb_bits=V_NB_BITS2;
517
        else                                       codebook_setup->nb_bits=V_NB_BITS;
518

    
519
        codebook_setup->maxdepth=(codebook_setup->maxdepth+codebook_setup->nb_bits-1)/codebook_setup->nb_bits;
520

    
521
        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)) {
522
            av_log(vc->avccontext, AV_LOG_ERROR, " Error generating vlc tables. \n");
523
            goto error;
524
        }
525
    }
526

    
527
    av_free(tmp_vlc_bits);
528
    av_free(tmp_vlc_codes);
529
    return 0;
530

    
531
// Error:
532
error:
533
    av_free(tmp_vlc_bits);
534
    av_free(tmp_vlc_codes);
535
    return 1;
536
}
537

    
538
// Process time domain transforms part (unused in Vorbis I)
539

    
540
static int vorbis_parse_setup_hdr_tdtransforms(vorbis_context *vc) {
541
    GetBitContext *gb=&vc->gb;
542
    uint_fast8_t i;
543
    uint_fast8_t vorbis_time_count=get_bits(gb, 6)+1;
544

    
545
    for(i=0;i<vorbis_time_count;++i) {
546
        uint_fast16_t vorbis_tdtransform=get_bits(gb, 16);
547

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

    
550
        if (vorbis_tdtransform) {
551
            av_log(vc->avccontext, AV_LOG_ERROR, "Vorbis time domain transform data nonzero. \n");
552
            return 1;
553
        }
554
    }
555
    return 0;
556
}
557

    
558
// Process floors part
559

    
560
static uint_fast8_t vorbis_floor0_decode(vorbis_context *vc,
561
                                         vorbis_floor_data *vfu, float *vec);
562
static void create_map( vorbis_context * vc, uint_fast8_t floor_number );
563
static uint_fast8_t vorbis_floor1_decode(vorbis_context *vc,
564
                                         vorbis_floor_data *vfu, float *vec);
565
static int vorbis_parse_setup_hdr_floors(vorbis_context *vc) {
566
    GetBitContext *gb=&vc->gb;
567
    uint_fast16_t i,j,k;
568

    
569
    vc->floor_count=get_bits(gb, 6)+1;
570

    
571
    vc->floors=(vorbis_floor *)av_mallocz(vc->floor_count * sizeof(vorbis_floor));
572

    
573
    for (i=0;i<vc->floor_count;++i) {
574
        vorbis_floor *floor_setup=&vc->floors[i];
575

    
576
        floor_setup->floor_type=get_bits(gb, 16);
577

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

    
580
        if (floor_setup->floor_type==1) {
581
            uint_fast8_t maximum_class=0;
582
            uint_fast8_t rangebits;
583
            uint_fast16_t floor1_values=2;
584

    
585
            floor_setup->decode=vorbis_floor1_decode;
586

    
587
            floor_setup->data.t1.partitions=get_bits(gb, 5);
588

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

    
591
            for(j=0;j<floor_setup->data.t1.partitions;++j) {
592
                floor_setup->data.t1.partition_class[j]=get_bits(gb, 4);
593
                if (floor_setup->data.t1.partition_class[j]>maximum_class) maximum_class=floor_setup->data.t1.partition_class[j];
594

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

    
597
            }
598

    
599
            AV_DEBUG(" maximum class %d \n", maximum_class);
600

    
601
            floor_setup->data.t1.maximum_class=maximum_class;
602

    
603
            for(j=0;j<=maximum_class;++j) {
604
                floor_setup->data.t1.class_dimensions[j]=get_bits(gb, 3)+1;
605
                floor_setup->data.t1.class_subclasses[j]=get_bits(gb, 2);
606

    
607
                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]);
608

    
609
                if (floor_setup->data.t1.class_subclasses[j]) {
610
                    floor_setup->data.t1.class_masterbook[j]=get_bits(gb, 8);
611

    
612
                    AV_DEBUG("   masterbook: %d \n", floor_setup->data.t1.class_masterbook[j]);
613
                }
614

    
615
                for(k=0;k<(1<<floor_setup->data.t1.class_subclasses[j]);++k) {
616
                    floor_setup->data.t1.subclass_books[j][k]=(int16_t)get_bits(gb, 8)-1;
617

    
618
                    AV_DEBUG("    book %d. : %d \n", k, floor_setup->data.t1.subclass_books[j][k]);
619
                }
620
            }
621

    
622
            floor_setup->data.t1.multiplier=get_bits(gb, 2)+1;
623
            floor_setup->data.t1.x_list_dim=2;
624

    
625
            for(j=0;j<floor_setup->data.t1.partitions;++j) {
626
                floor_setup->data.t1.x_list_dim+=floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]];
627
            }
628

    
629
            floor_setup->data.t1.list=(floor1_entry_t *)av_mallocz(floor_setup->data.t1.x_list_dim * sizeof(floor1_entry_t));
630

    
631

    
632
            rangebits=get_bits(gb, 4);
633
            floor_setup->data.t1.list[0].x = 0;
634
            floor_setup->data.t1.list[1].x = (1<<rangebits);
635

    
636
            for(j=0;j<floor_setup->data.t1.partitions;++j) {
637
                for(k=0;k<floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]];++k,++floor1_values) {
638
                    floor_setup->data.t1.list[floor1_values].x=get_bits(gb, rangebits);
639

    
640
                    AV_DEBUG(" %d. floor1 Y coord. %d \n", floor1_values, floor_setup->data.t1.list[floor1_values].x);
641
                }
642
            }
643

    
644
// Precalculate order of x coordinates - needed for decode
645
            ff_vorbis_ready_floor1_list(floor_setup->data.t1.list, floor_setup->data.t1.x_list_dim);
646
        }
647
        else if(floor_setup->floor_type==0) {
648
            uint_fast8_t max_codebook_dim=0;
649

    
650
            floor_setup->decode=vorbis_floor0_decode;
651

    
652
            floor_setup->data.t0.order=get_bits(gb, 8);
653
            floor_setup->data.t0.rate=get_bits(gb, 16);
654
            floor_setup->data.t0.bark_map_size=get_bits(gb, 16);
655
            floor_setup->data.t0.amplitude_bits=get_bits(gb, 6);
656
            /* zero would result in a div by zero later *
657
             * 2^0 - 1 == 0                             */
658
            if (floor_setup->data.t0.amplitude_bits == 0) {
659
              av_log(vc->avccontext, AV_LOG_ERROR,
660
                     "Floor 0 amplitude bits is 0.\n");
661
              return 1;
662
            }
663
            floor_setup->data.t0.amplitude_offset=get_bits(gb, 8);
664
            floor_setup->data.t0.num_books=get_bits(gb, 4)+1;
665

    
666
            /* allocate mem for booklist */
667
            floor_setup->data.t0.book_list=
668
                av_malloc(floor_setup->data.t0.num_books);
669
            if(!floor_setup->data.t0.book_list) { return 1; }
670
            /* read book indexes */
671
            {
672
                int idx;
673
                uint_fast8_t book_idx;
674
                for (idx=0;idx<floor_setup->data.t0.num_books;++idx) {
675
                    book_idx=get_bits(gb, 8);
676
                    floor_setup->data.t0.book_list[idx]=book_idx;
677
                    if (vc->codebooks[book_idx].dimensions > max_codebook_dim)
678
                        max_codebook_dim=vc->codebooks[book_idx].dimensions;
679

    
680
                    if (floor_setup->data.t0.book_list[idx]>vc->codebook_count)
681
                        return 1;
682
                }
683
            }
684

    
685
            create_map( vc, i );
686

    
687
            /* allocate mem for lsp coefficients */
688
            {
689
                /* codebook dim is for padding if codebook dim doesn't *
690
                 * divide order+1 then we need to read more data       */
691
                floor_setup->data.t0.lsp=
692
                    av_malloc((floor_setup->data.t0.order+1 + max_codebook_dim)
693
                              * sizeof(float));
694
                if(!floor_setup->data.t0.lsp) { return 1; }
695
            }
696

    
697
#ifdef V_DEBUG /* debug output parsed headers */
698
            AV_DEBUG("floor0 order: %u\n", floor_setup->data.t0.order);
699
            AV_DEBUG("floor0 rate: %u\n", floor_setup->data.t0.rate);
700
            AV_DEBUG("floor0 bark map size: %u\n",
701
              floor_setup->data.t0.bark_map_size);
702
            AV_DEBUG("floor0 amplitude bits: %u\n",
703
              floor_setup->data.t0.amplitude_bits);
704
            AV_DEBUG("floor0 amplitude offset: %u\n",
705
              floor_setup->data.t0.amplitude_offset);
706
            AV_DEBUG("floor0 number of books: %u\n",
707
              floor_setup->data.t0.num_books);
708
            AV_DEBUG("floor0 book list pointer: %p\n",
709
              floor_setup->data.t0.book_list);
710
            {
711
              int idx;
712
              for (idx=0;idx<floor_setup->data.t0.num_books;++idx) {
713
                AV_DEBUG( "  Book %d: %u\n",
714
                  idx+1,
715
                  floor_setup->data.t0.book_list[idx] );
716
              }
717
            }
718
#endif
719
        }
720
        else {
721
            av_log(vc->avccontext, AV_LOG_ERROR, "Invalid floor type!\n");
722
            return 1;
723
        }
724
    }
725
    return 0;
726
}
727

    
728
// Process residues part
729

    
730
static int vorbis_parse_setup_hdr_residues(vorbis_context *vc){
731
    GetBitContext *gb=&vc->gb;
732
    uint_fast8_t i, j, k;
733

    
734
    vc->residue_count=get_bits(gb, 6)+1;
735
    vc->residues=(vorbis_residue *)av_mallocz(vc->residue_count * sizeof(vorbis_residue));
736

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

    
739
    for(i=0;i<vc->residue_count;++i) {
740
        vorbis_residue *res_setup=&vc->residues[i];
741
        uint_fast8_t cascade[64];
742
        uint_fast8_t high_bits;
743
        uint_fast8_t low_bits;
744

    
745
        res_setup->type=get_bits(gb, 16);
746

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

    
749
        res_setup->begin=get_bits(gb, 24);
750
        res_setup->end=get_bits(gb, 24);
751
        res_setup->partition_size=get_bits(gb, 24)+1;
752
        res_setup->classifications=get_bits(gb, 6)+1;
753
        res_setup->classbook=get_bits(gb, 8);
754

    
755
        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,
756
          res_setup->classifications, res_setup->classbook);
757

    
758
        for(j=0;j<res_setup->classifications;++j) {
759
            high_bits=0;
760
            low_bits=get_bits(gb, 3);
761
            if (get_bits1(gb)) {
762
                high_bits=get_bits(gb, 5);
763
            }
764
            cascade[j]=(high_bits<<3)+low_bits;
765

    
766
            AV_DEBUG("     %d class casscade depth: %d \n", j, ilog(cascade[j]));
767
        }
768

    
769
        res_setup->maxpass=0;
770
        for(j=0;j<res_setup->classifications;++j) {
771
            for(k=0;k<8;++k) {
772
                if (cascade[j]&(1<<k)) {
773
                        res_setup->books[j][k]=get_bits(gb, 8);
774

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

    
777
                    if (k>res_setup->maxpass) {
778
                        res_setup->maxpass=k;
779
                    }
780
                } else {
781
                    res_setup->books[j][k]=-1;
782
                }
783
            }
784
        }
785
    }
786
    return 0;
787
}
788

    
789
// Process mappings part
790

    
791
static int vorbis_parse_setup_hdr_mappings(vorbis_context *vc) {
792
    GetBitContext *gb=&vc->gb;
793
    uint_fast8_t i, j;
794

    
795
    vc->mapping_count=get_bits(gb, 6)+1;
796
    vc->mappings=(vorbis_mapping *)av_mallocz(vc->mapping_count * sizeof(vorbis_mapping));
797

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

    
800
    for(i=0;i<vc->mapping_count;++i) {
801
        vorbis_mapping *mapping_setup=&vc->mappings[i];
802

    
803
        if (get_bits(gb, 16)) {
804
            av_log(vc->avccontext, AV_LOG_ERROR, "Other mappings than type 0 are not compliant with the Vorbis I specification. \n");
805
            return 1;
806
        }
807
        if (get_bits1(gb)) {
808
            mapping_setup->submaps=get_bits(gb, 4)+1;
809
        } else {
810
            mapping_setup->submaps=1;
811
        }
812

    
813
        if (get_bits1(gb)) {
814
            mapping_setup->coupling_steps=get_bits(gb, 8)+1;
815
            mapping_setup->magnitude=(uint_fast8_t *)av_mallocz(mapping_setup->coupling_steps * sizeof(uint_fast8_t));
816
            mapping_setup->angle=(uint_fast8_t *)av_mallocz(mapping_setup->coupling_steps * sizeof(uint_fast8_t));
817
            for(j=0;j<mapping_setup->coupling_steps;++j) {
818
                mapping_setup->magnitude[j]=get_bits(gb, ilog(vc->audio_channels-1));
819
                mapping_setup->angle[j]=get_bits(gb, ilog(vc->audio_channels-1));
820
                // FIXME: sanity checks
821
            }
822
        } else {
823
            mapping_setup->coupling_steps=0;
824
        }
825

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

    
828
        if(get_bits(gb, 2)) {
829
            av_log(vc->avccontext, AV_LOG_ERROR, "%d. mapping setup data invalid. \n", i);
830
            return 1; // following spec.
831
        }
832

    
833
        if (mapping_setup->submaps>1) {
834
            mapping_setup->mux=(uint_fast8_t *)av_mallocz(vc->audio_channels * sizeof(uint_fast8_t));
835
            for(j=0;j<vc->audio_channels;++j) {
836
                mapping_setup->mux[j]=get_bits(gb, 4);
837
            }
838
        }
839

    
840
        for(j=0;j<mapping_setup->submaps;++j) {
841
            get_bits(gb, 8); // FIXME check?
842
            mapping_setup->submap_floor[j]=get_bits(gb, 8);
843
            mapping_setup->submap_residue[j]=get_bits(gb, 8);
844

    
845
            AV_DEBUG("   %d mapping %d submap : floor %d, residue %d \n", i, j, mapping_setup->submap_floor[j], mapping_setup->submap_residue[j]);
846
        }
847
    }
848
    return 0;
849
}
850

    
851
// Process modes part
852

    
853
static void create_map( vorbis_context * vc, uint_fast8_t floor_number )
854
{
855
    vorbis_floor * floors=vc->floors;
856
    vorbis_floor0 * vf;
857
    int idx;
858
    int_fast8_t blockflag;
859
    int_fast32_t * map;
860
    int_fast32_t n; //TODO: could theoretically be smaller?
861

    
862
    for (blockflag=0;blockflag<2;++blockflag)
863
    {
864
    n=vc->blocksize[blockflag]/2;
865
    floors[floor_number].data.t0.map[blockflag]=
866
        av_malloc((n+1) * sizeof(int_fast32_t)); // n+sentinel
867

    
868
    map=floors[floor_number].data.t0.map[blockflag];
869
    vf=&floors[floor_number].data.t0;
870

    
871
    for (idx=0; idx<n;++idx) {
872
        map[idx]=floor( BARK((vf->rate*idx)/(2.0f*n)) *
873
                              ((vf->bark_map_size)/
874
                               BARK(vf->rate/2.0f )) );
875
        if (vf->bark_map_size-1 < map[idx]) {
876
            map[idx]=vf->bark_map_size-1;
877
        }
878
    }
879
    map[n]=-1;
880
    vf->map_size[blockflag]=n;
881
    }
882

    
883
#   ifdef V_DEBUG
884
    for(idx=0;idx<=n;++idx) {
885
        AV_DEBUG("floor0 map: map at pos %d is %d\n",
886
                 idx, map[idx]);
887
    }
888
#   endif
889
}
890

    
891
static int vorbis_parse_setup_hdr_modes(vorbis_context *vc) {
892
    GetBitContext *gb=&vc->gb;
893
    uint_fast8_t i;
894

    
895
    vc->mode_count=get_bits(gb, 6)+1;
896
    vc->modes=(vorbis_mode *)av_mallocz(vc->mode_count * sizeof(vorbis_mode));
897

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

    
900
    for(i=0;i<vc->mode_count;++i) {
901
        vorbis_mode *mode_setup=&vc->modes[i];
902

    
903
        mode_setup->blockflag=get_bits(gb, 1);
904
        mode_setup->windowtype=get_bits(gb, 16); //FIXME check
905
        mode_setup->transformtype=get_bits(gb, 16); //FIXME check
906
        mode_setup->mapping=get_bits(gb, 8); //FIXME check
907

    
908
        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);
909
    }
910
    return 0;
911
}
912

    
913
// Process the whole setup header using the functions above
914

    
915
static int vorbis_parse_setup_hdr(vorbis_context *vc) {
916
    GetBitContext *gb=&vc->gb;
917

    
918
    if ((get_bits(gb, 8)!='v') || (get_bits(gb, 8)!='o') ||
919
    (get_bits(gb, 8)!='r') || (get_bits(gb, 8)!='b') ||
920
    (get_bits(gb, 8)!='i') || (get_bits(gb, 8)!='s')) {
921
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (no vorbis signature). \n");
922
        return 1;
923
    }
924

    
925
    if (vorbis_parse_setup_hdr_codebooks(vc)) {
926
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (codebooks). \n");
927
        return 2;
928
    }
929
    if (vorbis_parse_setup_hdr_tdtransforms(vc)) {
930
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (time domain transforms). \n");
931
        return 3;
932
    }
933
    if (vorbis_parse_setup_hdr_floors(vc)) {
934
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (floors). \n");
935
        return 4;
936
    }
937
    if (vorbis_parse_setup_hdr_residues(vc)) {
938
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (residues). \n");
939
        return 5;
940
    }
941
    if (vorbis_parse_setup_hdr_mappings(vc)) {
942
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (mappings). \n");
943
        return 6;
944
    }
945
    if (vorbis_parse_setup_hdr_modes(vc)) {
946
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (modes). \n");
947
        return 7;
948
    }
949
    if (!get_bits1(gb)) {
950
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (framing flag). \n");
951
        return 8; // framing flag bit unset error
952
    }
953

    
954
    return 0;
955
}
956

    
957
// Process the identification header
958

    
959
static int vorbis_parse_id_hdr(vorbis_context *vc){
960
    GetBitContext *gb=&vc->gb;
961
    uint_fast8_t bl0, bl1;
962

    
963
    if ((get_bits(gb, 8)!='v') || (get_bits(gb, 8)!='o') ||
964
    (get_bits(gb, 8)!='r') || (get_bits(gb, 8)!='b') ||
965
    (get_bits(gb, 8)!='i') || (get_bits(gb, 8)!='s')) {
966
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (no vorbis signature). \n");
967
        return 1;
968
    }
969

    
970
    vc->version=get_bits_long(gb, 32);    //FIXME check 0
971
    vc->audio_channels=get_bits(gb, 8);   //FIXME check >0
972
    vc->audio_samplerate=get_bits_long(gb, 32);   //FIXME check >0
973
    vc->bitrate_maximum=get_bits_long(gb, 32);
974
    vc->bitrate_nominal=get_bits_long(gb, 32);
975
    vc->bitrate_minimum=get_bits_long(gb, 32);
976
    bl0=get_bits(gb, 4);
977
    bl1=get_bits(gb, 4);
978
    vc->blocksize[0]=(1<<bl0);
979
    vc->blocksize[1]=(1<<bl1);
980
    if (bl0>13 || bl0<6 || bl1>13 || bl1<6 || bl1<bl0) {
981
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (illegal blocksize). \n");
982
        return 3;
983
    }
984
    // output format int16
985
    if (vc->blocksize[1]/2 * vc->audio_channels * 2 >
986
                                             AVCODEC_MAX_AUDIO_FRAME_SIZE) {
987
        av_log(vc->avccontext, AV_LOG_ERROR, "Vorbis channel count makes "
988
               "output packets too large.\n");
989
        return 4;
990
    }
991
    vc->win[0]=ff_vorbis_vwin[bl0-6];
992
    vc->win[1]=ff_vorbis_vwin[bl1-6];
993

    
994
    if(vc->exp_bias){
995
        int i, j;
996
        for(j=0; j<2; j++){
997
            float *win = av_malloc(vc->blocksize[j]/2 * sizeof(float));
998
            for(i=0; i<vc->blocksize[j]/2; i++)
999
                win[i] = vc->win[j][i] * (1<<15);
1000
            vc->win[j] = win;
1001
        }
1002
    }
1003

    
1004
    if ((get_bits1(gb)) == 0) {
1005
        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (framing flag not set). \n");
1006
        return 2;
1007
    }
1008

    
1009
    vc->channel_residues=(float *)av_malloc((vc->blocksize[1]/2)*vc->audio_channels * sizeof(float));
1010
    vc->channel_floors=(float *)av_malloc((vc->blocksize[1]/2)*vc->audio_channels * sizeof(float));
1011
    vc->saved=(float *)av_malloc((vc->blocksize[1]/2)*vc->audio_channels * sizeof(float));
1012
    vc->ret=(float *)av_malloc((vc->blocksize[1]/2)*vc->audio_channels * sizeof(float));
1013
    vc->buf=(float *)av_malloc(vc->blocksize[1] * sizeof(float));
1014
    vc->buf_tmp=(float *)av_malloc(vc->blocksize[1] * sizeof(float));
1015
    vc->saved_start=0;
1016

    
1017
    ff_mdct_init(&vc->mdct[0], bl0, 1);
1018
    ff_mdct_init(&vc->mdct[1], bl1, 1);
1019

    
1020
    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 ",
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

    
1035
static int vorbis_decode_init(AVCodecContext *avccontext) {
1036
    vorbis_context *vc = avccontext->priv_data ;
1037
    uint8_t *headers = avccontext->extradata;
1038
    int headers_len=avccontext->extradata_size;
1039
    uint8_t *header_start[3];
1040
    int header_len[3];
1041
    GetBitContext *gb = &(vc->gb);
1042
    int i, j, hdr_type;
1043

    
1044
    vc->avccontext = avccontext;
1045
    dsputil_init(&vc->dsp, avccontext);
1046

    
1047
    if(vc->dsp.float_to_int16 == ff_float_to_int16_c) {
1048
        vc->add_bias = 385;
1049
        vc->exp_bias = 0;
1050
    } else {
1051
        vc->add_bias = 0;
1052
        vc->exp_bias = 15<<23;
1053
    }
1054

    
1055
    if (!headers_len) {
1056
        av_log(avccontext, AV_LOG_ERROR, "Extradata corrupt.\n");
1057
        return -1;
1058
    }
1059

    
1060
    if(headers[0] == 0 && headers[1] == 30) {
1061
        for(i = 0; i < 3; i++){
1062
            header_len[i] = *headers++ << 8;
1063
            header_len[i] += *headers++;
1064
            header_start[i] = headers;
1065
            headers += header_len[i];
1066
        }
1067
    } else if(headers[0] == 2) {
1068
        for(j=1,i=0;i<2;++i, ++j) {
1069
            header_len[i]=0;
1070
            while(j<headers_len && headers[j]==0xff) {
1071
                header_len[i]+=0xff;
1072
                ++j;
1073
            }
1074
            if (j>=headers_len) {
1075
                av_log(avccontext, AV_LOG_ERROR, "Extradata corrupt.\n");
1076
                return -1;
1077
            }
1078
            header_len[i]+=headers[j];
1079
        }
1080
        header_len[2]=headers_len-header_len[0]-header_len[1]-j;
1081
        headers+=j;
1082
        header_start[0] = headers;
1083
        header_start[1] = header_start[0] + header_len[0];
1084
        header_start[2] = header_start[1] + header_len[1];
1085
    } else {
1086
        av_log(avccontext, AV_LOG_ERROR, "Extradata corrupt.\n");
1087
        return -1;
1088
    }
1089

    
1090
    init_get_bits(gb, header_start[0], header_len[0]*8);
1091
    hdr_type=get_bits(gb, 8);
1092
    if (hdr_type!=1) {
1093
        av_log(avccontext, AV_LOG_ERROR, "First header is not the id header.\n");
1094
        return -1;
1095
    }
1096
    if (vorbis_parse_id_hdr(vc)) {
1097
        av_log(avccontext, AV_LOG_ERROR, "Id header corrupt.\n");
1098
        vorbis_free(vc);
1099
        return -1;
1100
    }
1101

    
1102
    init_get_bits(gb, header_start[2], header_len[2]*8);
1103
    hdr_type=get_bits(gb, 8);
1104
    if (hdr_type!=5) {
1105
        av_log(avccontext, AV_LOG_ERROR, "Third header is not the setup header.\n");
1106
        return -1;
1107
    }
1108
    if (vorbis_parse_setup_hdr(vc)) {
1109
        av_log(avccontext, AV_LOG_ERROR, "Setup header corrupt.\n");
1110
        vorbis_free(vc);
1111
        return -1;
1112
    }
1113

    
1114
    avccontext->channels = vc->audio_channels;
1115
    avccontext->sample_rate = vc->audio_samplerate;
1116

    
1117
    return 0 ;
1118
}
1119

    
1120
// Decode audiopackets -------------------------------------------------
1121

    
1122
// Read and decode floor
1123

    
1124
static uint_fast8_t vorbis_floor0_decode(vorbis_context *vc,
1125
                                         vorbis_floor_data *vfu, float *vec) {
1126
    vorbis_floor0 * vf=&vfu->t0;
1127
    float * lsp=vf->lsp;
1128
    uint_fast32_t amplitude;
1129
    uint_fast32_t book_idx;
1130
    uint_fast8_t blockflag=vc->modes[vc->mode_number].blockflag;
1131

    
1132
    amplitude=get_bits(&vc->gb, vf->amplitude_bits);
1133
    if (amplitude>0) {
1134
        float last = 0;
1135
        uint_fast16_t lsp_len = 0;
1136
        uint_fast16_t idx;
1137
        vorbis_codebook codebook;
1138

    
1139
        book_idx=get_bits(&vc->gb, ilog(vf->num_books));
1140
        if ( book_idx >= vf->num_books ) {
1141
            av_log( vc->avccontext, AV_LOG_ERROR,
1142
                    "floor0 dec: booknumber too high!\n" );
1143
            //FIXME: look above
1144
        }
1145
        AV_DEBUG( "floor0 dec: booknumber: %u\n", book_idx );
1146
        codebook=vc->codebooks[vf->book_list[book_idx]];
1147

    
1148
        while (lsp_len<vf->order) {
1149
            int vec_off;
1150

    
1151
            AV_DEBUG( "floor0 dec: book dimension: %d\n", codebook.dimensions );
1152
            AV_DEBUG( "floor0 dec: maximum depth: %d\n", codebook.maxdepth );
1153
            /* read temp vector */
1154
            vec_off=get_vlc2(&vc->gb,
1155
                             codebook.vlc.table,
1156
                             codebook.nb_bits,
1157
                             codebook.maxdepth ) *
1158
                             codebook.dimensions;
1159
            AV_DEBUG( "floor0 dec: vector offset: %d\n", vec_off );
1160
            /* copy each vector component and add last to it */
1161
            for (idx=0; idx<codebook.dimensions; ++idx) {
1162
                lsp[lsp_len+idx]=codebook.codevectors[vec_off+idx]+last;
1163
            }
1164
            last=lsp[lsp_len+idx-1]; /* set last to last vector component */
1165

    
1166
            lsp_len += codebook.dimensions;
1167
        }
1168
#ifdef V_DEBUG
1169
        /* DEBUG: output lsp coeffs */
1170
        {
1171
            int idx;
1172
            for ( idx = 0; idx < lsp_len; ++idx )
1173
                AV_DEBUG("floor0 dec: coeff at %d is %f\n", idx, lsp[idx] );
1174
        }
1175
#endif
1176

    
1177
        /* synthesize floor output vector */
1178
        {
1179
            int i;
1180
            int order=vf->order;
1181
            float wstep=M_PI/vf->bark_map_size;
1182

    
1183
            for(i=0;i<order;i++) { lsp[i]=2.0f*cos(lsp[i]); }
1184

    
1185
            AV_DEBUG("floor0 synth: map_size=%d; m=%d; wstep=%f\n",
1186
                     vf->map_size, order, wstep);
1187

    
1188
            i=0;
1189
            while(i<vf->map_size[blockflag]) {
1190
                int j, iter_cond=vf->map[blockflag][i];
1191
                float p=0.5f;
1192
                float q=0.5f;
1193
                float two_cos_w=2.0f*cos(wstep*iter_cond); // needed all times
1194

    
1195
                /* similar part for the q and p products */
1196
                for(j=0;j<order;j+=2) {
1197
                    q *= lsp[j]  -two_cos_w;
1198
                    p *= lsp[j+1]-two_cos_w;
1199
                }
1200
                if(j==order) { // even order
1201
                    p *= p*(2.0f-two_cos_w);
1202
                    q *= q*(2.0f+two_cos_w);
1203
                }
1204
                else { // odd order
1205
                    q *= two_cos_w-lsp[j]; // one more time for q
1206

    
1207
                    /* final step and square */
1208
                    p *= p*(4.f-two_cos_w*two_cos_w);
1209
                    q *= q;
1210
                }
1211

    
1212
                /* calculate linear floor value */
1213
                {
1214
                    q=exp( (
1215
                             ( (amplitude*vf->amplitude_offset)/
1216
                               (((1<<vf->amplitude_bits)-1) * sqrt(p+q)) )
1217
                             - vf->amplitude_offset ) * .11512925f
1218
                         );
1219
                }
1220

    
1221
                /* fill vector */
1222
                do { vec[i]=q; ++i; }while(vf->map[blockflag][i]==iter_cond);
1223
            }
1224
        }
1225
    }
1226
    else {
1227
        /* this channel is unused */
1228
        return 1;
1229
    }
1230

    
1231
    AV_DEBUG(" Floor0 decoded\n");
1232

    
1233
    return 0;
1234
}
1235

    
1236
static void render_line(int x0, int y0, int x1, int y1, float * buf, int n) {
1237
    int dy = y1 - y0;
1238
    int adx = x1 - x0;
1239
    int ady = FFABS(dy);
1240
    int base = dy / adx;
1241
    int x = x0;
1242
    int y = y0;
1243
    int err = 0;
1244
    int sy;
1245
    if (dy < 0) sy = base - 1;
1246
    else        sy = base + 1;
1247
    ady = ady - FFABS(base) * adx;
1248
    if (x >= n) return;
1249
    buf[x] = ff_vorbis_floor1_inverse_db_table[y];
1250
    for (x = x0 + 1; x < x1; x++) {
1251
        if (x >= n) return;
1252
        err += ady;
1253
        if (err >= adx) {
1254
            err -= adx;
1255
            y += sy;
1256
        } else {
1257
            y += base;
1258
        }
1259
        buf[x] = ff_vorbis_floor1_inverse_db_table[y];
1260
    }
1261
}
1262

    
1263
void ff_vorbis_floor1_render_list(floor1_entry_t * list, int values, uint_fast16_t * y_list, int * flag, int multiplier, float * out, int samples) {
1264
    int lx, ly, i;
1265
    lx = 0;
1266
    ly = y_list[0] * multiplier;
1267
    for (i = 1; i < values; i++) {
1268
        int pos = list[i].sort;
1269
        if (flag[pos]) {
1270
            render_line(lx, ly, list[pos].x, y_list[pos] * multiplier, out, samples);
1271
            lx = list[pos].x;
1272
            ly = y_list[pos] * multiplier;
1273
        }
1274
        if (lx >= samples) break;
1275
    }
1276
    if (lx < samples) render_line(lx, ly, samples, ly, out, samples);
1277
}
1278

    
1279
static uint_fast8_t vorbis_floor1_decode(vorbis_context *vc, vorbis_floor_data *vfu, float *vec) {
1280
    vorbis_floor1 * vf=&vfu->t1;
1281
    GetBitContext *gb=&vc->gb;
1282
    uint_fast16_t range_v[4]={ 256, 128, 86, 64 };
1283
    uint_fast16_t range=range_v[vf->multiplier-1];
1284
    uint_fast16_t floor1_Y[vf->x_list_dim];
1285
    uint_fast16_t floor1_Y_final[vf->x_list_dim];
1286
    int floor1_flag[vf->x_list_dim];
1287
    uint_fast8_t class_;
1288
    uint_fast8_t cdim;
1289
    uint_fast8_t cbits;
1290
    uint_fast8_t csub;
1291
    uint_fast8_t cval;
1292
    int_fast16_t book;
1293
    uint_fast16_t offset;
1294
    uint_fast16_t i,j;
1295
    /*u*/int_fast16_t adx, ady, off, predicted; // WTF ? dy/adx= (unsigned)dy/adx ?
1296
    int_fast16_t dy, err;
1297

    
1298

    
1299
    if (!get_bits1(gb)) return 1; // silence
1300

    
1301
// Read values (or differences) for the floor's points
1302

    
1303
    floor1_Y[0]=get_bits(gb, ilog(range-1));
1304
    floor1_Y[1]=get_bits(gb, ilog(range-1));
1305

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

    
1308
    offset=2;
1309
    for(i=0;i<vf->partitions;++i) {
1310
        class_=vf->partition_class[i];
1311
        cdim=vf->class_dimensions[class_];
1312
        cbits=vf->class_subclasses[class_];
1313
        csub=(1<<cbits)-1;
1314
        cval=0;
1315

    
1316
        AV_DEBUG("Cbits %d \n", cbits);
1317

    
1318
        if (cbits) { // this reads all subclasses for this partition's class
1319
            cval=get_vlc2(gb, vc->codebooks[vf->class_masterbook[class_]].vlc.table,
1320
            vc->codebooks[vf->class_masterbook[class_]].nb_bits, 3);
1321
        }
1322

    
1323
        for(j=0;j<cdim;++j) {
1324
            book=vf->subclass_books[class_][cval & csub];
1325

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

    
1328
            cval=cval>>cbits;
1329
            if (book>-1) {
1330
                floor1_Y[offset+j]=get_vlc2(gb, vc->codebooks[book].vlc.table,
1331
                vc->codebooks[book].nb_bits, 3);
1332
            } else {
1333
                floor1_Y[offset+j]=0;
1334
            }
1335

    
1336
            AV_DEBUG(" floor(%d) = %d \n", vf->list[offset+j].x, floor1_Y[offset+j]);
1337
        }
1338
        offset+=cdim;
1339
    }
1340

    
1341
// Amplitude calculation from the differences
1342

    
1343
    floor1_flag[0]=1;
1344
    floor1_flag[1]=1;
1345
    floor1_Y_final[0]=floor1_Y[0];
1346
    floor1_Y_final[1]=floor1_Y[1];
1347

    
1348
    for(i=2;i<vf->x_list_dim;++i) {
1349
        uint_fast16_t val, highroom, lowroom, room;
1350
        uint_fast16_t high_neigh_offs;
1351
        uint_fast16_t low_neigh_offs;
1352

    
1353
        low_neigh_offs=vf->list[i].low;
1354
        high_neigh_offs=vf->list[i].high;
1355
        dy=floor1_Y_final[high_neigh_offs]-floor1_Y_final[low_neigh_offs];  // render_point begin
1356
        adx=vf->list[high_neigh_offs].x-vf->list[low_neigh_offs].x;
1357
        ady= FFABS(dy);
1358
        err=ady*(vf->list[i].x-vf->list[low_neigh_offs].x);
1359
        off=(int16_t)err/(int16_t)adx;
1360
        if (dy<0) {
1361
            predicted=floor1_Y_final[low_neigh_offs]-off;
1362
        } else {
1363
            predicted=floor1_Y_final[low_neigh_offs]+off;
1364
        } // render_point end
1365

    
1366
        val=floor1_Y[i];
1367
        highroom=range-predicted;
1368
        lowroom=predicted;
1369
        if (highroom < lowroom) {
1370
            room=highroom*2;
1371
        } else {
1372
            room=lowroom*2;   // SPEC mispelling
1373
        }
1374
        if (val) {
1375
            floor1_flag[low_neigh_offs]=1;
1376
            floor1_flag[high_neigh_offs]=1;
1377
            floor1_flag[i]=1;
1378
            if (val>=room) {
1379
                if (highroom > lowroom) {
1380
                    floor1_Y_final[i]=val-lowroom+predicted;
1381
                } else {
1382
                    floor1_Y_final[i]=predicted-val+highroom-1;
1383
                }
1384
            } else {
1385
                if (val & 1) {
1386
                    floor1_Y_final[i]=predicted-(val+1)/2;
1387
                } else {
1388
                    floor1_Y_final[i]=predicted+val/2;
1389
                }
1390
            }
1391
        } else {
1392
            floor1_flag[i]=0;
1393
            floor1_Y_final[i]=predicted;
1394
        }
1395

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

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

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

    
1403
    AV_DEBUG(" Floor decoded\n");
1404

    
1405
    return 0;
1406
}
1407

    
1408
// Read and decode residue
1409

    
1410
static int vorbis_residue_decode(vorbis_context *vc, vorbis_residue *vr, uint_fast8_t ch, uint_fast8_t *do_not_decode, float *vec, uint_fast16_t vlen) {
1411
    GetBitContext *gb=&vc->gb;
1412
    uint_fast8_t c_p_c=vc->codebooks[vr->classbook].dimensions;
1413
    uint_fast16_t n_to_read=vr->end-vr->begin;
1414
    uint_fast16_t ptns_to_read=n_to_read/vr->partition_size;
1415
    uint_fast8_t classifs[ptns_to_read*vc->audio_channels];
1416
    uint_fast8_t pass;
1417
    uint_fast8_t ch_used;
1418
    uint_fast8_t i,j,l;
1419
    uint_fast16_t k;
1420

    
1421
    if (vr->type==2) {
1422
        for(j=1;j<ch;++j) {
1423
                do_not_decode[0]&=do_not_decode[j];  // FIXME - clobbering input
1424
        }
1425
        if (do_not_decode[0]) return 0;
1426
        ch_used=1;
1427
    } else {
1428
        ch_used=ch;
1429
    }
1430

    
1431
    AV_DEBUG(" 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
        uint_fast16_t voffset;
1435
        uint_fast16_t partition_count;
1436
        uint_fast16_t j_times_ptns_to_read;
1437

    
1438
        voffset=vr->begin;
1439
        for(partition_count=0;partition_count<ptns_to_read;) {  // SPEC        error
1440
            if (!pass) {
1441
                uint_fast32_t inverse_class = ff_inverse[vr->classifications];
1442
                for(j_times_ptns_to_read=0, j=0;j<ch_used;++j) {
1443
                    if (!do_not_decode[j]) {
1444
                        uint_fast32_t temp=get_vlc2(gb, vc->codebooks[vr->classbook].vlc.table,
1445
                        vc->codebooks[vr->classbook].nb_bits, 3);
1446

    
1447
                        AV_DEBUG("Classword: %d \n", temp);
1448

    
1449
                        assert(vr->classifications > 1 && temp<=65536); //needed for inverse[]
1450
                        for(i=0;i<c_p_c;++i) {
1451
                            uint_fast32_t temp2;
1452

    
1453
                            temp2=(((uint_fast64_t)temp) * inverse_class)>>32;
1454
                            if (partition_count+c_p_c-1-i < ptns_to_read) {
1455
                                classifs[j_times_ptns_to_read+partition_count+c_p_c-1-i]=temp-temp2*vr->classifications;
1456
                            }
1457
                            temp=temp2;
1458
                        }
1459
                    }
1460
                    j_times_ptns_to_read+=ptns_to_read;
1461
                }
1462
            }
1463
            for(i=0;(i<c_p_c) && (partition_count<ptns_to_read);++i) {
1464
                for(j_times_ptns_to_read=0, j=0;j<ch_used;++j) {
1465
                    uint_fast16_t voffs;
1466

    
1467
                    if (!do_not_decode[j]) {
1468
                        uint_fast8_t vqclass=classifs[j_times_ptns_to_read+partition_count];
1469
                        int_fast16_t vqbook=vr->books[vqclass][pass];
1470

    
1471
                        if (vqbook>=0) {
1472
                            uint_fast16_t coffs;
1473
                            unsigned dim= vc->codebooks[vqbook].dimensions; // not uint_fast8_t: 64bit is slower here on amd64
1474
                            uint_fast16_t step= dim==1 ? vr->partition_size
1475
                                              : FASTDIV(vr->partition_size, dim);
1476
                            vorbis_codebook codebook= vc->codebooks[vqbook];
1477

    
1478
                            if (vr->type==0) {
1479

    
1480
                                voffs=voffset+j*vlen;
1481
                                for(k=0;k<step;++k) {
1482
                                    coffs=get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1483
                                    for(l=0;l<dim;++l) {
1484
                                        vec[voffs+k+l*step]+=codebook.codevectors[coffs+l];  // FPMATH
1485
                                    }
1486
                                }
1487
                            }
1488
                            else if (vr->type==1) {
1489
                                voffs=voffset+j*vlen;
1490
                                for(k=0;k<step;++k) {
1491
                                    coffs=get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1492
                                    for(l=0;l<dim;++l, ++voffs) {
1493
                                        vec[voffs]+=codebook.codevectors[coffs+l];  // FPMATH
1494

    
1495
                                        AV_DEBUG(" pass %d offs: %d curr: %f change: %f cv offs.: %d  \n", pass, voffs, vec[voffs], codebook.codevectors[coffs+l], coffs);
1496
                                    }
1497
                                }
1498
                            }
1499
                            else if (vr->type==2 && ch==2 && (voffset&1)==0 && (dim&1)==0) { // most frequent case optimized
1500
                                voffs=voffset>>1;
1501

    
1502
                                if(dim==2) {
1503
                                    for(k=0;k<step;++k) {
1504
                                        coffs=get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 2;
1505
                                        vec[voffs+k     ]+=codebook.codevectors[coffs  ];  // FPMATH
1506
                                        vec[voffs+k+vlen]+=codebook.codevectors[coffs+1];  // FPMATH
1507
                                    }
1508
                                } else
1509
                                for(k=0;k<step;++k) {
1510
                                    coffs=get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
1511
                                    for(l=0;l<dim;l+=2, voffs++) {
1512
                                        vec[voffs     ]+=codebook.codevectors[coffs+l  ];  // FPMATH
1513
                                        vec[voffs+vlen]+=codebook.codevectors[coffs+l+1];  // FPMATH
1514

    
1515
                                        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);
1516
                                    }
1517
                                }
1518

    
1519
                            }
1520
                            else if (vr->type==2) {
1521
                                voffs=voffset;
1522

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

    
1528
                                        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);
1529
                                    }
1530
                                }
1531
                            } else {
1532
                                av_log(vc->avccontext, AV_LOG_ERROR, " Invalid residue type while residue decode?! \n");
1533
                                return 1;
1534
                            }
1535
                        }
1536
                    }
1537
                    j_times_ptns_to_read+=ptns_to_read;
1538
                }
1539
                ++partition_count;
1540
                voffset+=vr->partition_size;
1541
            }
1542
        }
1543
    }
1544
    return 0;
1545
}
1546

    
1547
void vorbis_inverse_coupling(float *mag, float *ang, int blocksize)
1548
{
1549
    int i;
1550
    for(i=0; i<blocksize; i++)
1551
    {
1552
        if (mag[i]>0.0) {
1553
            if (ang[i]>0.0) {
1554
                ang[i]=mag[i]-ang[i];
1555
            } else {
1556
                float temp=ang[i];
1557
                ang[i]=mag[i];
1558
                mag[i]+=temp;
1559
            }
1560
        } else {
1561
            if (ang[i]>0.0) {
1562
                ang[i]+=mag[i];
1563
            } else {
1564
                float temp=ang[i];
1565
                ang[i]=mag[i];
1566
                mag[i]-=temp;
1567
            }
1568
        }
1569
    }
1570
}
1571

    
1572
// Decode the audio packet using the functions above
1573

    
1574
static int vorbis_parse_audio_packet(vorbis_context *vc) {
1575
    GetBitContext *gb=&vc->gb;
1576

    
1577
    uint_fast8_t previous_window=0,next_window=0;
1578
    uint_fast8_t mode_number;
1579
    uint_fast16_t blocksize;
1580
    int_fast32_t i,j;
1581
    uint_fast8_t no_residue[vc->audio_channels];
1582
    uint_fast8_t do_not_decode[vc->audio_channels];
1583
    vorbis_mapping *mapping;
1584
    float *ch_res_ptr=vc->channel_residues;
1585
    float *ch_floor_ptr=vc->channel_floors;
1586
    uint_fast8_t res_chan[vc->audio_channels];
1587
    uint_fast8_t res_num=0;
1588
    int_fast16_t retlen=0;
1589
    uint_fast16_t saved_start=0;
1590
    float fadd_bias = vc->add_bias;
1591

    
1592
    if (get_bits1(gb)) {
1593
        av_log(vc->avccontext, AV_LOG_ERROR, "Not a Vorbis I audio packet.\n");
1594
        return -1; // packet type not audio
1595
    }
1596

    
1597
    if (vc->mode_count==1) {
1598
        mode_number=0;
1599
    } else {
1600
        mode_number=get_bits(gb, ilog(vc->mode_count-1));
1601
    }
1602
    vc->mode_number=mode_number;
1603
    mapping=&vc->mappings[vc->modes[mode_number].mapping];
1604

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

    
1607
    if (vc->modes[mode_number].blockflag) {
1608
        previous_window=get_bits1(gb);
1609
        next_window=get_bits1(gb);
1610
    }
1611

    
1612
    blocksize=vc->blocksize[vc->modes[mode_number].blockflag];
1613
    memset(ch_res_ptr, 0, sizeof(float)*vc->audio_channels*blocksize/2); //FIXME can this be removed ?
1614
    memset(ch_floor_ptr, 0, sizeof(float)*vc->audio_channels*blocksize/2); //FIXME can this be removed ?
1615

    
1616
// Decode floor
1617

    
1618
    for(i=0;i<vc->audio_channels;++i) {
1619
        vorbis_floor *floor;
1620
        if (mapping->submaps>1) {
1621
            floor=&vc->floors[mapping->submap_floor[mapping->mux[i]]];
1622
        } else {
1623
            floor=&vc->floors[mapping->submap_floor[0]];
1624
        }
1625

    
1626
        no_residue[i]=floor->decode(vc, &floor->data, ch_floor_ptr);
1627
        ch_floor_ptr+=blocksize/2;
1628
    }
1629

    
1630
// Nonzero vector propagate
1631

    
1632
    for(i=mapping->coupling_steps-1;i>=0;--i) {
1633
        if (!(no_residue[mapping->magnitude[i]] & no_residue[mapping->angle[i]])) {
1634
            no_residue[mapping->magnitude[i]]=0;
1635
            no_residue[mapping->angle[i]]=0;
1636
        }
1637
    }
1638

    
1639
// Decode residue
1640

    
1641
    for(i=0;i<mapping->submaps;++i) {
1642
        vorbis_residue *residue;
1643
        uint_fast8_t ch=0;
1644

    
1645
        for(j=0;j<vc->audio_channels;++j) {
1646
            if ((mapping->submaps==1) || (i=mapping->mux[j])) {
1647
                res_chan[j]=res_num;
1648
                if (no_residue[j]) {
1649
                    do_not_decode[ch]=1;
1650
                } else {
1651
                    do_not_decode[ch]=0;
1652
                }
1653
                ++ch;
1654
                ++res_num;
1655
            }
1656
        }
1657
        residue=&vc->residues[mapping->submap_residue[i]];
1658
        vorbis_residue_decode(vc, residue, ch, do_not_decode, ch_res_ptr, blocksize/2);
1659

    
1660
        ch_res_ptr+=ch*blocksize/2;
1661
    }
1662

    
1663
// Inverse coupling
1664

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

    
1668
        mag=vc->channel_residues+res_chan[mapping->magnitude[i]]*blocksize/2;
1669
        ang=vc->channel_residues+res_chan[mapping->angle[i]]*blocksize/2;
1670
        vc->dsp.vorbis_inverse_coupling(mag, ang, blocksize/2);
1671
    }
1672

    
1673
// Dotproduct
1674

    
1675
    for(j=0, ch_floor_ptr=vc->channel_floors;j<vc->audio_channels;++j,ch_floor_ptr+=blocksize/2) {
1676
        ch_res_ptr=vc->channel_residues+res_chan[j]*blocksize/2;
1677
        vc->dsp.vector_fmul(ch_floor_ptr, ch_res_ptr, blocksize/2);
1678
    }
1679

    
1680
// MDCT, overlap/add, save data for next overlapping  FPMATH
1681

    
1682
    for(j=0;j<vc->audio_channels;++j) {
1683
        uint_fast8_t step=vc->audio_channels;
1684
        uint_fast16_t k;
1685
        float *saved=vc->saved+j*vc->blocksize[1]/2;
1686
        float *ret=vc->ret;
1687
        const float *lwin=vc->win[1];
1688
        const float *swin=vc->win[0];
1689
        float *buf=vc->buf;
1690
        float *buf_tmp=vc->buf_tmp;
1691

    
1692
        ch_floor_ptr=vc->channel_floors+j*blocksize/2;
1693

    
1694
        saved_start=vc->saved_start;
1695

    
1696
        vc->mdct[0].fft.imdct_calc(&vc->mdct[vc->modes[mode_number].blockflag], buf, ch_floor_ptr, buf_tmp);
1697

    
1698
        //FIXME process channels together, to allow faster simd vector_fmul_add_add?
1699
        if (vc->modes[mode_number].blockflag) {
1700
            // -- overlap/add
1701
            if (previous_window) {
1702
                vc->dsp.vector_fmul_add_add(ret+j, buf, lwin, saved, vc->add_bias, vc->blocksize[1]/2, step);
1703
                retlen=vc->blocksize[1]/2;
1704
            } else {
1705
                int len = (vc->blocksize[1]-vc->blocksize[0])/4;
1706
                buf += len;
1707
                vc->dsp.vector_fmul_add_add(ret+j, buf, swin, saved, vc->add_bias, vc->blocksize[0]/2, step);
1708
                k = vc->blocksize[0]/2*step + j;
1709
                buf += vc->blocksize[0]/2;
1710
                if(vc->exp_bias){
1711
                    for(i=0; i<len; i++, k+=step)
1712
                        ((uint32_t*)ret)[k] = ((uint32_t*)buf)[i] + vc->exp_bias; // ret[k]=buf[i]*(1<<bias)
1713
                } else {
1714
                    for(i=0; i<len; i++, k+=step)
1715
                        ret[k] = buf[i] + fadd_bias;
1716
                }
1717
                buf=vc->buf;
1718
                retlen=vc->blocksize[0]/2+len;
1719
            }
1720
            // -- save
1721
            if (next_window) {
1722
                buf += vc->blocksize[1]/2;
1723
                vc->dsp.vector_fmul_reverse(saved, buf, lwin, vc->blocksize[1]/2);
1724
                saved_start=0;
1725
            } else {
1726
                saved_start=(vc->blocksize[1]-vc->blocksize[0])/4;
1727
                buf += vc->blocksize[1]/2;
1728
                for(i=0; i<saved_start; i++)
1729
                    ((uint32_t*)saved)[i] = ((uint32_t*)buf)[i] + vc->exp_bias;
1730
                vc->dsp.vector_fmul_reverse(saved+saved_start, buf+saved_start, swin, vc->blocksize[0]/2);
1731
            }
1732
        } else {
1733
            // --overlap/add
1734
            if(vc->add_bias) {
1735
                for(k=j, i=0;i<saved_start;++i, k+=step)
1736
                    ret[k] = saved[i] + fadd_bias;
1737
            } else {
1738
                for(k=j, i=0;i<saved_start;++i, k+=step)
1739
                    ret[k] = saved[i];
1740
            }
1741
            vc->dsp.vector_fmul_add_add(ret+k, buf, swin, saved+saved_start, vc->add_bias, vc->blocksize[0]/2, step);
1742
            retlen=saved_start+vc->blocksize[0]/2;
1743
            // -- save
1744
            buf += vc->blocksize[0]/2;
1745
            vc->dsp.vector_fmul_reverse(saved, buf, swin, vc->blocksize[0]/2);
1746
            saved_start=0;
1747
        }
1748
    }
1749
    vc->saved_start=saved_start;
1750

    
1751
    return retlen*vc->audio_channels;
1752
}
1753

    
1754
// Return the decoded audio packet through the standard api
1755

    
1756
static int vorbis_decode_frame(AVCodecContext *avccontext,
1757
                        void *data, int *data_size,
1758
                        uint8_t *buf, int buf_size)
1759
{
1760
    vorbis_context *vc = avccontext->priv_data ;
1761
    GetBitContext *gb = &(vc->gb);
1762

    
1763
    int_fast16_t len;
1764

    
1765
    if(!buf_size){
1766
        return 0;
1767
    }
1768

    
1769
    AV_DEBUG("packet length %d \n", buf_size);
1770

    
1771
    init_get_bits(gb, buf, buf_size*8);
1772

    
1773
    len=vorbis_parse_audio_packet(vc);
1774

    
1775
    if (len<=0) {
1776
        *data_size=0;
1777
        return buf_size;
1778
    }
1779

    
1780
    if (!vc->first_frame) {
1781
        vc->first_frame=1;
1782
        *data_size=0;
1783
        return buf_size ;
1784
    }
1785

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

    
1788
    vc->dsp.float_to_int16(data, vc->ret, len);
1789
    *data_size=len*2;
1790

    
1791
    return buf_size ;
1792
}
1793

    
1794
// Close decoder
1795

    
1796
static int vorbis_decode_close(AVCodecContext *avccontext) {
1797
    vorbis_context *vc = avccontext->priv_data;
1798

    
1799
    vorbis_free(vc);
1800

    
1801
    return 0 ;
1802
}
1803

    
1804
AVCodec vorbis_decoder = {
1805
    "vorbis",
1806
    CODEC_TYPE_AUDIO,
1807
    CODEC_ID_VORBIS,
1808
    sizeof(vorbis_context),
1809
    vorbis_decode_init,
1810
    NULL,
1811
    vorbis_decode_close,
1812
    vorbis_decode_frame,
1813
};
1814