Statistics
| Branch: | Revision:

ffmpeg / libavcodec / vorbis_enc.c @ a7adcf29

History | View | Annotate | Download (34.3 KB)

1
/*
2
 * copyright (c) 2006 Oded Shimon <ods15@ods15.dyndns.org>
3
 *
4
 * This file is part of FFmpeg.
5
 *
6
 * FFmpeg is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * FFmpeg is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with FFmpeg; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
 */
20

    
21
/**
22
 * @file libavcodec/vorbis_enc.c
23
 * Native Vorbis encoder.
24
 * @author Oded Shimon <ods15@ods15.dyndns.org>
25
 */
26

    
27
#include <float.h>
28
#include "avcodec.h"
29
#include "dsputil.h"
30
#include "vorbis.h"
31
#include "vorbis_enc_data.h"
32

    
33
#define BITSTREAM_WRITER_LE
34
#include "put_bits.h"
35

    
36
#undef NDEBUG
37
#include <assert.h>
38

    
39
typedef struct {
40
    int nentries;
41
    uint8_t *lens;
42
    uint32_t *codewords;
43
    int ndimentions;
44
    float min;
45
    float delta;
46
    int seq_p;
47
    int lookup;
48
    int *quantlist;
49
    float *dimentions;
50
    float *pow2;
51
} vorbis_enc_codebook;
52

    
53
typedef struct {
54
    int dim;
55
    int subclass;
56
    int masterbook;
57
    int *books;
58
} vorbis_enc_floor_class;
59

    
60
typedef struct {
61
    int partitions;
62
    int *partition_to_class;
63
    int nclasses;
64
    vorbis_enc_floor_class *classes;
65
    int multiplier;
66
    int rangebits;
67
    int values;
68
    vorbis_floor1_entry *list;
69
} vorbis_enc_floor;
70

    
71
typedef struct {
72
    int type;
73
    int begin;
74
    int end;
75
    int partition_size;
76
    int classifications;
77
    int classbook;
78
    int8_t (*books)[8];
79
    float (*maxes)[2];
80
} vorbis_enc_residue;
81

    
82
typedef struct {
83
    int submaps;
84
    int *mux;
85
    int *floor;
86
    int *residue;
87
    int coupling_steps;
88
    int *magnitude;
89
    int *angle;
90
} vorbis_enc_mapping;
91

    
92
typedef struct {
93
    int blockflag;
94
    int mapping;
95
} vorbis_enc_mode;
96

    
97
typedef struct {
98
    int channels;
99
    int sample_rate;
100
    int log2_blocksize[2];
101
    FFTContext mdct[2];
102
    const float *win[2];
103
    int have_saved;
104
    float *saved;
105
    float *samples;
106
    float *floor;  // also used for tmp values for mdct
107
    float *coeffs; // also used for residue after floor
108
    float quality;
109

    
110
    int ncodebooks;
111
    vorbis_enc_codebook *codebooks;
112

    
113
    int nfloors;
114
    vorbis_enc_floor *floors;
115

    
116
    int nresidues;
117
    vorbis_enc_residue *residues;
118

    
119
    int nmappings;
120
    vorbis_enc_mapping *mappings;
121

    
122
    int nmodes;
123
    vorbis_enc_mode *modes;
124

    
125
    int64_t sample_count;
126
} vorbis_enc_context;
127

    
128
static inline void put_codeword(PutBitContext *pb, vorbis_enc_codebook *cb,
129
                                int entry)
130
{
131
    assert(entry >= 0);
132
    assert(entry < cb->nentries);
133
    assert(cb->lens[entry]);
134
    put_bits(pb, cb->lens[entry], cb->codewords[entry]);
135
}
136

    
137
static int cb_lookup_vals(int lookup, int dimentions, int entries)
138
{
139
    if (lookup == 1)
140
        return ff_vorbis_nth_root(entries, dimentions);
141
    else if (lookup == 2)
142
        return dimentions *entries;
143
    return 0;
144
}
145

    
146
static void ready_codebook(vorbis_enc_codebook *cb)
147
{
148
    int i;
149

    
150
    ff_vorbis_len2vlc(cb->lens, cb->codewords, cb->nentries);
151

    
152
    if (!cb->lookup) {
153
        cb->pow2 = cb->dimentions = NULL;
154
    } else {
155
        int vals = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);
156
        cb->dimentions = av_malloc(sizeof(float) * cb->nentries * cb->ndimentions);
157
        cb->pow2 = av_mallocz(sizeof(float) * cb->nentries);
158
        for (i = 0; i < cb->nentries; i++) {
159
            float last = 0;
160
            int j;
161
            int div = 1;
162
            for (j = 0; j < cb->ndimentions; j++) {
163
                int off;
164
                if (cb->lookup == 1)
165
                    off = (i / div) % vals; // lookup type 1
166
                else
167
                    off = i * cb->ndimentions + j; // lookup type 2
168

    
169
                cb->dimentions[i * cb->ndimentions + j] = last + cb->min + cb->quantlist[off] * cb->delta;
170
                if (cb->seq_p)
171
                    last = cb->dimentions[i * cb->ndimentions + j];
172
                cb->pow2[i] += cb->dimentions[i * cb->ndimentions + j] * cb->dimentions[i * cb->ndimentions + j];
173
                div *= vals;
174
            }
175
            cb->pow2[i] /= 2.;
176
        }
177
    }
178
}
179

    
180
static void ready_residue(vorbis_enc_residue *rc, vorbis_enc_context *venc)
181
{
182
    int i;
183
    assert(rc->type == 2);
184
    rc->maxes = av_mallocz(sizeof(float[2]) * rc->classifications);
185
    for (i = 0; i < rc->classifications; i++) {
186
        int j;
187
        vorbis_enc_codebook * cb;
188
        for (j = 0; j < 8; j++)
189
            if (rc->books[i][j] != -1)
190
                break;
191
        if (j == 8) // zero
192
            continue;
193
        cb = &venc->codebooks[rc->books[i][j]];
194
        assert(cb->ndimentions >= 2);
195
        assert(cb->lookup);
196

    
197
        for (j = 0; j < cb->nentries; j++) {
198
            float a;
199
            if (!cb->lens[j])
200
                continue;
201
            a = fabs(cb->dimentions[j * cb->ndimentions]);
202
            if (a > rc->maxes[i][0])
203
                rc->maxes[i][0] = a;
204
            a = fabs(cb->dimentions[j * cb->ndimentions + 1]);
205
            if (a > rc->maxes[i][1])
206
                rc->maxes[i][1] = a;
207
        }
208
    }
209
    // small bias
210
    for (i = 0; i < rc->classifications; i++) {
211
        rc->maxes[i][0] += 0.8;
212
        rc->maxes[i][1] += 0.8;
213
    }
214
}
215

    
216
static void create_vorbis_context(vorbis_enc_context *venc,
217
                                  AVCodecContext *avccontext)
218
{
219
    vorbis_enc_floor   *fc;
220
    vorbis_enc_residue *rc;
221
    vorbis_enc_mapping *mc;
222
    int i, book;
223

    
224
    venc->channels    = avccontext->channels;
225
    venc->sample_rate = avccontext->sample_rate;
226
    venc->log2_blocksize[0] = venc->log2_blocksize[1] = 11;
227

    
228
    venc->ncodebooks = FF_ARRAY_ELEMS(cvectors);
229
    venc->codebooks  = av_malloc(sizeof(vorbis_enc_codebook) * venc->ncodebooks);
230

    
231
    // codebook 0..14 - floor1 book, values 0..255
232
    // codebook 15 residue masterbook
233
    // codebook 16..29 residue
234
    for (book = 0; book < venc->ncodebooks; book++) {
235
        vorbis_enc_codebook *cb = &venc->codebooks[book];
236
        int vals;
237
        cb->ndimentions = cvectors[book].dim;
238
        cb->nentries    = cvectors[book].real_len;
239
        cb->min         = cvectors[book].min;
240
        cb->delta       = cvectors[book].delta;
241
        cb->lookup      = cvectors[book].lookup;
242
        cb->seq_p       = 0;
243

    
244
        cb->lens      = av_malloc(sizeof(uint8_t)  * cb->nentries);
245
        cb->codewords = av_malloc(sizeof(uint32_t) * cb->nentries);
246
        memcpy(cb->lens, cvectors[book].clens, cvectors[book].len);
247
        memset(cb->lens + cvectors[book].len, 0, cb->nentries - cvectors[book].len);
248

    
249
        if (cb->lookup) {
250
            vals = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);
251
            cb->quantlist = av_malloc(sizeof(int) * vals);
252
            for (i = 0; i < vals; i++)
253
                cb->quantlist[i] = cvectors[book].quant[i];
254
        } else {
255
            cb->quantlist = NULL;
256
        }
257
        ready_codebook(cb);
258
    }
259

    
260
    venc->nfloors = 1;
261
    venc->floors  = av_malloc(sizeof(vorbis_enc_floor) * venc->nfloors);
262

    
263
    // just 1 floor
264
    fc = &venc->floors[0];
265
    fc->partitions         = 8;
266
    fc->partition_to_class = av_malloc(sizeof(int) * fc->partitions);
267
    fc->nclasses           = 0;
268
    for (i = 0; i < fc->partitions; i++) {
269
        static const int a[] = {0, 1, 2, 2, 3, 3, 4, 4};
270
        fc->partition_to_class[i] = a[i];
271
        fc->nclasses = FFMAX(fc->nclasses, fc->partition_to_class[i]);
272
    }
273
    fc->nclasses++;
274
    fc->classes = av_malloc(sizeof(vorbis_enc_floor_class) * fc->nclasses);
275
    for (i = 0; i < fc->nclasses; i++) {
276
        vorbis_enc_floor_class * c = &fc->classes[i];
277
        int j, books;
278
        c->dim        = floor_classes[i].dim;
279
        c->subclass   = floor_classes[i].subclass;
280
        c->masterbook = floor_classes[i].masterbook;
281
        books         = (1 << c->subclass);
282
        c->books      = av_malloc(sizeof(int) * books);
283
        for (j = 0; j < books; j++)
284
            c->books[j] = floor_classes[i].nbooks[j];
285
    }
286
    fc->multiplier = 2;
287
    fc->rangebits  = venc->log2_blocksize[0] - 1;
288

    
289
    fc->values = 2;
290
    for (i = 0; i < fc->partitions; i++)
291
        fc->values += fc->classes[fc->partition_to_class[i]].dim;
292

    
293
    fc->list = av_malloc(sizeof(vorbis_floor1_entry) * fc->values);
294
    fc->list[0].x = 0;
295
    fc->list[1].x = 1 << fc->rangebits;
296
    for (i = 2; i < fc->values; i++) {
297
        static const int a[] = {
298
             93, 23,372,  6, 46,186,750, 14, 33, 65,
299
            130,260,556,  3, 10, 18, 28, 39, 55, 79,
300
            111,158,220,312,464,650,850
301
        };
302
        fc->list[i].x = a[i - 2];
303
    }
304
    ff_vorbis_ready_floor1_list(fc->list, fc->values);
305

    
306
    venc->nresidues = 1;
307
    venc->residues  = av_malloc(sizeof(vorbis_enc_residue) * venc->nresidues);
308

    
309
    // single residue
310
    rc = &venc->residues[0];
311
    rc->type            = 2;
312
    rc->begin           = 0;
313
    rc->end             = 1600;
314
    rc->partition_size  = 32;
315
    rc->classifications = 10;
316
    rc->classbook       = 15;
317
    rc->books           = av_malloc(sizeof(*rc->books) * rc->classifications);
318
    {
319
        static const int8_t a[10][8] = {
320
            { -1, -1, -1, -1, -1, -1, -1, -1, },
321
            { -1, -1, 16, -1, -1, -1, -1, -1, },
322
            { -1, -1, 17, -1, -1, -1, -1, -1, },
323
            { -1, -1, 18, -1, -1, -1, -1, -1, },
324
            { -1, -1, 19, -1, -1, -1, -1, -1, },
325
            { -1, -1, 20, -1, -1, -1, -1, -1, },
326
            { -1, -1, 21, -1, -1, -1, -1, -1, },
327
            { 22, 23, -1, -1, -1, -1, -1, -1, },
328
            { 24, 25, -1, -1, -1, -1, -1, -1, },
329
            { 26, 27, 28, -1, -1, -1, -1, -1, },
330
        };
331
        memcpy(rc->books, a, sizeof a);
332
    }
333
    ready_residue(rc, venc);
334

    
335
    venc->nmappings = 1;
336
    venc->mappings  = av_malloc(sizeof(vorbis_enc_mapping) * venc->nmappings);
337

    
338
    // single mapping
339
    mc = &venc->mappings[0];
340
    mc->submaps = 1;
341
    mc->mux     = av_malloc(sizeof(int) * venc->channels);
342
    for (i = 0; i < venc->channels; i++)
343
        mc->mux[i] = 0;
344
    mc->floor   = av_malloc(sizeof(int) * mc->submaps);
345
    mc->residue = av_malloc(sizeof(int) * mc->submaps);
346
    for (i = 0; i < mc->submaps; i++) {
347
        mc->floor[i]   = 0;
348
        mc->residue[i] = 0;
349
    }
350
    mc->coupling_steps = venc->channels == 2 ? 1 : 0;
351
    mc->magnitude      = av_malloc(sizeof(int) * mc->coupling_steps);
352
    mc->angle          = av_malloc(sizeof(int) * mc->coupling_steps);
353
    if (mc->coupling_steps) {
354
        mc->magnitude[0] = 0;
355
        mc->angle[0]     = 1;
356
    }
357

    
358
    venc->nmodes = 1;
359
    venc->modes  = av_malloc(sizeof(vorbis_enc_mode) * venc->nmodes);
360

    
361
    // single mode
362
    venc->modes[0].blockflag = 0;
363
    venc->modes[0].mapping   = 0;
364

    
365
    venc->have_saved = 0;
366
    venc->saved      = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
367
    venc->samples    = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]));
368
    venc->floor      = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
369
    venc->coeffs     = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
370

    
371
    venc->win[0] = ff_vorbis_vwin[venc->log2_blocksize[0] - 6];
372
    venc->win[1] = ff_vorbis_vwin[venc->log2_blocksize[1] - 6];
373

    
374
    ff_mdct_init(&venc->mdct[0], venc->log2_blocksize[0], 0, 1.0);
375
    ff_mdct_init(&venc->mdct[1], venc->log2_blocksize[1], 0, 1.0);
376
}
377

    
378
static void put_float(PutBitContext *pb, float f)
379
{
380
    int exp, mant;
381
    uint32_t res = 0;
382
    mant = (int)ldexp(frexp(f, &exp), 20);
383
    exp += 788 - 20;
384
    if (mant < 0) {
385
        res |= (1 << 31);
386
        mant = -mant;
387
    }
388
    res |= mant | (exp << 21);
389
    put_bits(pb, 32, res);
390
}
391

    
392
static void put_codebook_header(PutBitContext *pb, vorbis_enc_codebook *cb)
393
{
394
    int i;
395
    int ordered = 0;
396

    
397
    put_bits(pb, 24, 0x564342); //magic
398
    put_bits(pb, 16, cb->ndimentions);
399
    put_bits(pb, 24, cb->nentries);
400

    
401
    for (i = 1; i < cb->nentries; i++)
402
        if (cb->lens[i] < cb->lens[i-1])
403
            break;
404
    if (i == cb->nentries)
405
        ordered = 1;
406

    
407
    put_bits(pb, 1, ordered);
408
    if (ordered) {
409
        int len = cb->lens[0];
410
        put_bits(pb, 5, len - 1);
411
        i = 0;
412
        while (i < cb->nentries) {
413
            int j;
414
            for (j = 0; j+i < cb->nentries; j++)
415
                if (cb->lens[j+i] != len)
416
                    break;
417
            put_bits(pb, ilog(cb->nentries - i), j);
418
            i += j;
419
            len++;
420
        }
421
    } else {
422
        int sparse = 0;
423
        for (i = 0; i < cb->nentries; i++)
424
            if (!cb->lens[i])
425
                break;
426
        if (i != cb->nentries)
427
            sparse = 1;
428
        put_bits(pb, 1, sparse);
429

    
430
        for (i = 0; i < cb->nentries; i++) {
431
            if (sparse)
432
                put_bits(pb, 1, !!cb->lens[i]);
433
            if (cb->lens[i])
434
                put_bits(pb, 5, cb->lens[i] - 1);
435
        }
436
    }
437

    
438
    put_bits(pb, 4, cb->lookup);
439
    if (cb->lookup) {
440
        int tmp  = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);
441
        int bits = ilog(cb->quantlist[0]);
442

    
443
        for (i = 1; i < tmp; i++)
444
            bits = FFMAX(bits, ilog(cb->quantlist[i]));
445

    
446
        put_float(pb, cb->min);
447
        put_float(pb, cb->delta);
448

    
449
        put_bits(pb, 4, bits - 1);
450
        put_bits(pb, 1, cb->seq_p);
451

    
452
        for (i = 0; i < tmp; i++)
453
            put_bits(pb, bits, cb->quantlist[i]);
454
    }
455
}
456

    
457
static void put_floor_header(PutBitContext *pb, vorbis_enc_floor *fc)
458
{
459
    int i;
460

    
461
    put_bits(pb, 16, 1); // type, only floor1 is supported
462

    
463
    put_bits(pb, 5, fc->partitions);
464

    
465
    for (i = 0; i < fc->partitions; i++)
466
        put_bits(pb, 4, fc->partition_to_class[i]);
467

    
468
    for (i = 0; i < fc->nclasses; i++) {
469
        int j, books;
470

    
471
        put_bits(pb, 3, fc->classes[i].dim - 1);
472
        put_bits(pb, 2, fc->classes[i].subclass);
473

    
474
        if (fc->classes[i].subclass)
475
            put_bits(pb, 8, fc->classes[i].masterbook);
476

    
477
        books = (1 << fc->classes[i].subclass);
478

    
479
        for (j = 0; j < books; j++)
480
            put_bits(pb, 8, fc->classes[i].books[j] + 1);
481
    }
482

    
483
    put_bits(pb, 2, fc->multiplier - 1);
484
    put_bits(pb, 4, fc->rangebits);
485

    
486
    for (i = 2; i < fc->values; i++)
487
        put_bits(pb, fc->rangebits, fc->list[i].x);
488
}
489

    
490
static void put_residue_header(PutBitContext *pb, vorbis_enc_residue *rc)
491
{
492
    int i;
493

    
494
    put_bits(pb, 16, rc->type);
495

    
496
    put_bits(pb, 24, rc->begin);
497
    put_bits(pb, 24, rc->end);
498
    put_bits(pb, 24, rc->partition_size - 1);
499
    put_bits(pb, 6, rc->classifications - 1);
500
    put_bits(pb, 8, rc->classbook);
501

    
502
    for (i = 0; i < rc->classifications; i++) {
503
        int j, tmp = 0;
504
        for (j = 0; j < 8; j++)
505
            tmp |= (rc->books[i][j] != -1) << j;
506

    
507
        put_bits(pb, 3, tmp & 7);
508
        put_bits(pb, 1, tmp > 7);
509

    
510
        if (tmp > 7)
511
            put_bits(pb, 5, tmp >> 3);
512
    }
513

    
514
    for (i = 0; i < rc->classifications; i++) {
515
        int j;
516
        for (j = 0; j < 8; j++)
517
            if (rc->books[i][j] != -1)
518
                put_bits(pb, 8, rc->books[i][j]);
519
    }
520
}
521

    
522
static int put_main_header(vorbis_enc_context *venc, uint8_t **out)
523
{
524
    int i;
525
    PutBitContext pb;
526
    uint8_t buffer[50000] = {0}, *p = buffer;
527
    int buffer_len = sizeof buffer;
528
    int len, hlens[3];
529

    
530
    // identification header
531
    init_put_bits(&pb, p, buffer_len);
532
    put_bits(&pb, 8, 1); //magic
533
    for (i = 0; "vorbis"[i]; i++)
534
        put_bits(&pb, 8, "vorbis"[i]);
535
    put_bits(&pb, 32, 0); // version
536
    put_bits(&pb,  8, venc->channels);
537
    put_bits(&pb, 32, venc->sample_rate);
538
    put_bits(&pb, 32, 0); // bitrate
539
    put_bits(&pb, 32, 0); // bitrate
540
    put_bits(&pb, 32, 0); // bitrate
541
    put_bits(&pb,  4, venc->log2_blocksize[0]);
542
    put_bits(&pb,  4, venc->log2_blocksize[1]);
543
    put_bits(&pb,  1, 1); // framing
544

    
545
    flush_put_bits(&pb);
546
    hlens[0] = (put_bits_count(&pb) + 7) / 8;
547
    buffer_len -= hlens[0];
548
    p += hlens[0];
549

    
550
    // comment header
551
    init_put_bits(&pb, p, buffer_len);
552
    put_bits(&pb, 8, 3); //magic
553
    for (i = 0; "vorbis"[i]; i++)
554
        put_bits(&pb, 8, "vorbis"[i]);
555
    put_bits(&pb, 32, 0); // vendor length TODO
556
    put_bits(&pb, 32, 0); // amount of comments
557
    put_bits(&pb,  1, 1); // framing
558

    
559
    flush_put_bits(&pb);
560
    hlens[1] = (put_bits_count(&pb) + 7) / 8;
561
    buffer_len -= hlens[1];
562
    p += hlens[1];
563

    
564
    // setup header
565
    init_put_bits(&pb, p, buffer_len);
566
    put_bits(&pb, 8, 5); //magic
567
    for (i = 0; "vorbis"[i]; i++)
568
        put_bits(&pb, 8, "vorbis"[i]);
569

    
570
    // codebooks
571
    put_bits(&pb, 8, venc->ncodebooks - 1);
572
    for (i = 0; i < venc->ncodebooks; i++)
573
        put_codebook_header(&pb, &venc->codebooks[i]);
574

    
575
    // time domain, reserved, zero
576
    put_bits(&pb,  6, 0);
577
    put_bits(&pb, 16, 0);
578

    
579
    // floors
580
    put_bits(&pb, 6, venc->nfloors - 1);
581
    for (i = 0; i < venc->nfloors; i++)
582
        put_floor_header(&pb, &venc->floors[i]);
583

    
584
    // residues
585
    put_bits(&pb, 6, venc->nresidues - 1);
586
    for (i = 0; i < venc->nresidues; i++)
587
        put_residue_header(&pb, &venc->residues[i]);
588

    
589
    // mappings
590
    put_bits(&pb, 6, venc->nmappings - 1);
591
    for (i = 0; i < venc->nmappings; i++) {
592
        vorbis_enc_mapping *mc = &venc->mappings[i];
593
        int j;
594
        put_bits(&pb, 16, 0); // mapping type
595

    
596
        put_bits(&pb, 1, mc->submaps > 1);
597
        if (mc->submaps > 1)
598
            put_bits(&pb, 4, mc->submaps - 1);
599

    
600
        put_bits(&pb, 1, !!mc->coupling_steps);
601
        if (mc->coupling_steps) {
602
            put_bits(&pb, 8, mc->coupling_steps - 1);
603
            for (j = 0; j < mc->coupling_steps; j++) {
604
                put_bits(&pb, ilog(venc->channels - 1), mc->magnitude[j]);
605
                put_bits(&pb, ilog(venc->channels - 1), mc->angle[j]);
606
            }
607
        }
608

    
609
        put_bits(&pb, 2, 0); // reserved
610

    
611
        if (mc->submaps > 1)
612
            for (j = 0; j < venc->channels; j++)
613
                put_bits(&pb, 4, mc->mux[j]);
614

    
615
        for (j = 0; j < mc->submaps; j++) {
616
            put_bits(&pb, 8, 0); // reserved time configuration
617
            put_bits(&pb, 8, mc->floor[j]);
618
            put_bits(&pb, 8, mc->residue[j]);
619
        }
620
    }
621

    
622
    // modes
623
    put_bits(&pb, 6, venc->nmodes - 1);
624
    for (i = 0; i < venc->nmodes; i++) {
625
        put_bits(&pb, 1, venc->modes[i].blockflag);
626
        put_bits(&pb, 16, 0); // reserved window type
627
        put_bits(&pb, 16, 0); // reserved transform type
628
        put_bits(&pb, 8, venc->modes[i].mapping);
629
    }
630

    
631
    put_bits(&pb, 1, 1); // framing
632

    
633
    flush_put_bits(&pb);
634
    hlens[2] = (put_bits_count(&pb) + 7) / 8;
635

    
636
    len = hlens[0] + hlens[1] + hlens[2];
637
    p = *out = av_mallocz(64 + len + len/255);
638

    
639
    *p++ = 2;
640
    p += av_xiphlacing(p, hlens[0]);
641
    p += av_xiphlacing(p, hlens[1]);
642
    buffer_len = 0;
643
    for (i = 0; i < 3; i++) {
644
        memcpy(p, buffer + buffer_len, hlens[i]);
645
        p += hlens[i];
646
        buffer_len += hlens[i];
647
    }
648

    
649
    return p - *out;
650
}
651

    
652
static float get_floor_average(vorbis_enc_floor * fc, float *coeffs, int i)
653
{
654
    int begin = fc->list[fc->list[FFMAX(i-1, 0)].sort].x;
655
    int end   = fc->list[fc->list[FFMIN(i+1, fc->values - 1)].sort].x;
656
    int j;
657
    float average = 0;
658

    
659
    for (j = begin; j < end; j++)
660
        average += fabs(coeffs[j]);
661
    return average / (end - begin);
662
}
663

    
664
static void floor_fit(vorbis_enc_context *venc, vorbis_enc_floor *fc,
665
                      float *coeffs, uint_fast16_t *posts, int samples)
666
{
667
    int range = 255 / fc->multiplier + 1;
668
    int i;
669
    float tot_average = 0.;
670
    float averages[fc->values];
671
    for (i = 0; i < fc->values; i++) {
672
        averages[i] = get_floor_average(fc, coeffs, i);
673
        tot_average += averages[i];
674
    }
675
    tot_average /= fc->values;
676
    tot_average /= venc->quality;
677

    
678
    for (i = 0; i < fc->values; i++) {
679
        int position  = fc->list[fc->list[i].sort].x;
680
        float average = averages[i];
681
        int j;
682

    
683
        average *= pow(tot_average / average, 0.5) * pow(1.25, position/200.); // MAGIC!
684
        for (j = 0; j < range - 1; j++)
685
            if (ff_vorbis_floor1_inverse_db_table[j * fc->multiplier] > average)
686
                break;
687
        posts[fc->list[i].sort] = j;
688
    }
689
}
690

    
691
static int render_point(int x0, int y0, int x1, int y1, int x)
692
{
693
    return y0 +  (x - x0) * (y1 - y0) / (x1 - x0);
694
}
695

    
696
static void floor_encode(vorbis_enc_context *venc, vorbis_enc_floor *fc,
697
                         PutBitContext *pb, uint_fast16_t *posts,
698
                         float *floor, int samples)
699
{
700
    int range = 255 / fc->multiplier + 1;
701
    int coded[fc->values]; // first 2 values are unused
702
    int i, counter;
703

    
704
    put_bits(pb, 1, 1); // non zero
705
    put_bits(pb, ilog(range - 1), posts[0]);
706
    put_bits(pb, ilog(range - 1), posts[1]);
707
    coded[0] = coded[1] = 1;
708

    
709
    for (i = 2; i < fc->values; i++) {
710
        int predicted = render_point(fc->list[fc->list[i].low].x,
711
                                     posts[fc->list[i].low],
712
                                     fc->list[fc->list[i].high].x,
713
                                     posts[fc->list[i].high],
714
                                     fc->list[i].x);
715
        int highroom = range - predicted;
716
        int lowroom = predicted;
717
        int room = FFMIN(highroom, lowroom);
718
        if (predicted == posts[i]) {
719
            coded[i] = 0; // must be used later as flag!
720
            continue;
721
        } else {
722
            if (!coded[fc->list[i].low ])
723
                coded[fc->list[i].low ] = -1;
724
            if (!coded[fc->list[i].high])
725
                coded[fc->list[i].high] = -1;
726
        }
727
        if (posts[i] > predicted) {
728
            if (posts[i] - predicted > room)
729
                coded[i] = posts[i] - predicted + lowroom;
730
            else
731
                coded[i] = (posts[i] - predicted) << 1;
732
        } else {
733
            if (predicted - posts[i] > room)
734
                coded[i] = predicted - posts[i] + highroom - 1;
735
            else
736
                coded[i] = ((predicted - posts[i]) << 1) - 1;
737
        }
738
    }
739

    
740
    counter = 2;
741
    for (i = 0; i < fc->partitions; i++) {
742
        vorbis_enc_floor_class * c = &fc->classes[fc->partition_to_class[i]];
743
        int k, cval = 0, csub = 1<<c->subclass;
744
        if (c->subclass) {
745
            vorbis_enc_codebook * book = &venc->codebooks[c->masterbook];
746
            int cshift = 0;
747
            for (k = 0; k < c->dim; k++) {
748
                int l;
749
                for (l = 0; l < csub; l++) {
750
                    int maxval = 1;
751
                    if (c->books[l] != -1)
752
                        maxval = venc->codebooks[c->books[l]].nentries;
753
                    // coded could be -1, but this still works, cause that is 0
754
                    if (coded[counter + k] < maxval)
755
                        break;
756
                }
757
                assert(l != csub);
758
                cval   |= l << cshift;
759
                cshift += c->subclass;
760
            }
761
            put_codeword(pb, book, cval);
762
        }
763
        for (k = 0; k < c->dim; k++) {
764
            int book  = c->books[cval & (csub-1)];
765
            int entry = coded[counter++];
766
            cval >>= c->subclass;
767
            if (book == -1)
768
                continue;
769
            if (entry == -1)
770
                entry = 0;
771
            put_codeword(pb, &venc->codebooks[book], entry);
772
        }
773
    }
774

    
775
    ff_vorbis_floor1_render_list(fc->list, fc->values, posts, coded,
776
                                 fc->multiplier, floor, samples);
777
}
778

    
779
static float *put_vector(vorbis_enc_codebook *book, PutBitContext *pb,
780
                         float *num)
781
{
782
    int i, entry = -1;
783
    float distance = FLT_MAX;
784
    assert(book->dimentions);
785
    for (i = 0; i < book->nentries; i++) {
786
        float * vec = book->dimentions + i * book->ndimentions, d = book->pow2[i];
787
        int j;
788
        if (!book->lens[i])
789
            continue;
790
        for (j = 0; j < book->ndimentions; j++)
791
            d -= vec[j] * num[j];
792
        if (distance > d) {
793
            entry    = i;
794
            distance = d;
795
        }
796
    }
797
    put_codeword(pb, book, entry);
798
    return &book->dimentions[entry * book->ndimentions];
799
}
800

    
801
static void residue_encode(vorbis_enc_context *venc, vorbis_enc_residue *rc,
802
                           PutBitContext *pb, float *coeffs, int samples,
803
                           int real_ch)
804
{
805
    int pass, i, j, p, k;
806
    int psize      = rc->partition_size;
807
    int partitions = (rc->end - rc->begin) / psize;
808
    int channels   = (rc->type == 2) ? 1 : real_ch;
809
    int classes[channels][partitions];
810
    int classwords = venc->codebooks[rc->classbook].ndimentions;
811

    
812
    assert(rc->type == 2);
813
    assert(real_ch == 2);
814
    for (p = 0; p < partitions; p++) {
815
        float max1 = 0., max2 = 0.;
816
        int s = rc->begin + p * psize;
817
        for (k = s; k < s + psize; k += 2) {
818
            max1 = FFMAX(max1, fabs(coeffs[          k / real_ch]));
819
            max2 = FFMAX(max2, fabs(coeffs[samples + k / real_ch]));
820
        }
821

    
822
        for (i = 0; i < rc->classifications - 1; i++)
823
            if (max1 < rc->maxes[i][0] && max2 < rc->maxes[i][1])
824
                break;
825
        classes[0][p] = i;
826
    }
827

    
828
    for (pass = 0; pass < 8; pass++) {
829
        p = 0;
830
        while (p < partitions) {
831
            if (pass == 0)
832
                for (j = 0; j < channels; j++) {
833
                    vorbis_enc_codebook * book = &venc->codebooks[rc->classbook];
834
                    int entry = 0;
835
                    for (i = 0; i < classwords; i++) {
836
                        entry *= rc->classifications;
837
                        entry += classes[j][p + i];
838
                    }
839
                    put_codeword(pb, book, entry);
840
                }
841
            for (i = 0; i < classwords && p < partitions; i++, p++) {
842
                for (j = 0; j < channels; j++) {
843
                    int nbook = rc->books[classes[j][p]][pass];
844
                    vorbis_enc_codebook * book = &venc->codebooks[nbook];
845
                    float *buf = coeffs + samples*j + rc->begin + p*psize;
846
                    if (nbook == -1)
847
                        continue;
848

    
849
                    assert(rc->type == 0 || rc->type == 2);
850
                    assert(!(psize % book->ndimentions));
851

    
852
                    if (rc->type == 0) {
853
                        for (k = 0; k < psize; k += book->ndimentions) {
854
                            float *a = put_vector(book, pb, &buf[k]);
855
                            int l;
856
                            for (l = 0; l < book->ndimentions; l++)
857
                                buf[k + l] -= a[l];
858
                        }
859
                    } else {
860
                        int s = rc->begin + p * psize, a1, b1;
861
                        a1 = (s % real_ch) * samples;
862
                        b1 =  s / real_ch;
863
                        s  = real_ch * samples;
864
                        for (k = 0; k < psize; k += book->ndimentions) {
865
                            int dim, a2 = a1, b2 = b1;
866
                            float vec[book->ndimentions], *pv = vec;
867
                            for (dim = book->ndimentions; dim--; ) {
868
                                *pv++ = coeffs[a2 + b2];
869
                                if ((a2 += samples) == s) {
870
                                    a2 = 0;
871
                                    b2++;
872
                                }
873
                            }
874
                            pv = put_vector(book, pb, vec);
875
                            for (dim = book->ndimentions; dim--; ) {
876
                                coeffs[a1 + b1] -= *pv++;
877
                                if ((a1 += samples) == s) {
878
                                    a1 = 0;
879
                                    b1++;
880
                                }
881
                            }
882
                        }
883
                    }
884
                }
885
            }
886
        }
887
    }
888
}
889

    
890
static int apply_window_and_mdct(vorbis_enc_context *venc, signed short *audio,
891
                                 int samples)
892
{
893
    int i, j, channel;
894
    const float * win = venc->win[0];
895
    int window_len = 1 << (venc->log2_blocksize[0] - 1);
896
    float n = (float)(1 << venc->log2_blocksize[0]) / 4.;
897
    // FIXME use dsp
898

    
899
    if (!venc->have_saved && !samples)
900
        return 0;
901

    
902
    if (venc->have_saved) {
903
        for (channel = 0; channel < venc->channels; channel++)
904
            memcpy(venc->samples + channel * window_len * 2,
905
                   venc->saved + channel * window_len, sizeof(float) * window_len);
906
    } else {
907
        for (channel = 0; channel < venc->channels; channel++)
908
            memset(venc->samples + channel * window_len * 2, 0,
909
                   sizeof(float) * window_len);
910
    }
911

    
912
    if (samples) {
913
        for (channel = 0; channel < venc->channels; channel++) {
914
            float * offset = venc->samples + channel*window_len*2 + window_len;
915
            j = channel;
916
            for (i = 0; i < samples; i++, j += venc->channels)
917
                offset[i] = -audio[j] / 32768. / n * win[window_len - i - 1]; //FIXME find out why the sign has to be fliped
918
        }
919
    } else {
920
        for (channel = 0; channel < venc->channels; channel++)
921
            memset(venc->samples + channel * window_len * 2 + window_len,
922
                   0, sizeof(float) * window_len);
923
    }
924

    
925
    for (channel = 0; channel < venc->channels; channel++)
926
        ff_mdct_calc(&venc->mdct[0], venc->coeffs + channel * window_len,
927
                     venc->samples + channel * window_len * 2);
928

    
929
    if (samples) {
930
        for (channel = 0; channel < venc->channels; channel++) {
931
            float *offset = venc->saved + channel * window_len;
932
            j = channel;
933
            for (i = 0; i < samples; i++, j += venc->channels)
934
                offset[i] = -audio[j] / 32768. / n * win[i]; //FIXME find out why the sign has to be fliped
935
        }
936
        venc->have_saved = 1;
937
    } else {
938
        venc->have_saved = 0;
939
    }
940
    return 1;
941
}
942

    
943
static av_cold int vorbis_encode_init(AVCodecContext *avccontext)
944
{
945
    vorbis_enc_context *venc = avccontext->priv_data;
946

    
947
    if (avccontext->channels != 2) {
948
        av_log(avccontext, AV_LOG_ERROR, "Current FFmpeg Vorbis encoder only supports 2 channels.\n");
949
        return -1;
950
    }
951

    
952
    create_vorbis_context(venc, avccontext);
953

    
954
    if (avccontext->flags & CODEC_FLAG_QSCALE)
955
        venc->quality = avccontext->global_quality / (float)FF_QP2LAMBDA / 10.;
956
    else
957
        venc->quality = 1.;
958
    venc->quality *= venc->quality;
959

    
960
    avccontext->extradata_size = put_main_header(venc, (uint8_t**)&avccontext->extradata);
961

    
962
    avccontext->frame_size     = 1 << (venc->log2_blocksize[0] - 1);
963

    
964
    avccontext->coded_frame            = avcodec_alloc_frame();
965
    avccontext->coded_frame->key_frame = 1;
966

    
967
    return 0;
968
}
969

    
970
static int vorbis_encode_frame(AVCodecContext *avccontext,
971
                               unsigned char *packets,
972
                               int buf_size, void *data)
973
{
974
    vorbis_enc_context *venc = avccontext->priv_data;
975
    signed short *audio = data;
976
    int samples = data ? avccontext->frame_size : 0;
977
    vorbis_enc_mode *mode;
978
    vorbis_enc_mapping *mapping;
979
    PutBitContext pb;
980
    int i;
981

    
982
    if (!apply_window_and_mdct(venc, audio, samples))
983
        return 0;
984
    samples = 1 << (venc->log2_blocksize[0] - 1);
985

    
986
    init_put_bits(&pb, packets, buf_size);
987

    
988
    put_bits(&pb, 1, 0); // magic bit
989

    
990
    put_bits(&pb, ilog(venc->nmodes - 1), 0); // 0 bits, the mode
991

    
992
    mode    = &venc->modes[0];
993
    mapping = &venc->mappings[mode->mapping];
994
    if (mode->blockflag) {
995
        put_bits(&pb, 1, 0);
996
        put_bits(&pb, 1, 0);
997
    }
998

    
999
    for (i = 0; i < venc->channels; i++) {
1000
        vorbis_enc_floor *fc = &venc->floors[mapping->floor[mapping->mux[i]]];
1001
        uint_fast16_t posts[fc->values];
1002
        floor_fit(venc, fc, &venc->coeffs[i * samples], posts, samples);
1003
        floor_encode(venc, fc, &pb, posts, &venc->floor[i * samples], samples);
1004
    }
1005

    
1006
    for (i = 0; i < venc->channels * samples; i++)
1007
        venc->coeffs[i] /= venc->floor[i];
1008

    
1009
    for (i = 0; i < mapping->coupling_steps; i++) {
1010
        float *mag = venc->coeffs + mapping->magnitude[i] * samples;
1011
        float *ang = venc->coeffs + mapping->angle[i]     * samples;
1012
        int j;
1013
        for (j = 0; j < samples; j++) {
1014
            float a = ang[j];
1015
            ang[j] -= mag[j];
1016
            if (mag[j] > 0)
1017
                ang[j] = -ang[j];
1018
            if (ang[j] < 0)
1019
                mag[j] = a;
1020
        }
1021
    }
1022

    
1023
    residue_encode(venc, &venc->residues[mapping->residue[mapping->mux[0]]],
1024
                   &pb, venc->coeffs, samples, venc->channels);
1025

    
1026
    avccontext->coded_frame->pts = venc->sample_count;
1027
    venc->sample_count += avccontext->frame_size;
1028
    flush_put_bits(&pb);
1029
    return (put_bits_count(&pb) + 7) / 8;
1030
}
1031

    
1032

    
1033
static av_cold int vorbis_encode_close(AVCodecContext *avccontext)
1034
{
1035
    vorbis_enc_context *venc = avccontext->priv_data;
1036
    int i;
1037

    
1038
    if (venc->codebooks)
1039
        for (i = 0; i < venc->ncodebooks; i++) {
1040
            av_freep(&venc->codebooks[i].lens);
1041
            av_freep(&venc->codebooks[i].codewords);
1042
            av_freep(&venc->codebooks[i].quantlist);
1043
            av_freep(&venc->codebooks[i].dimentions);
1044
            av_freep(&venc->codebooks[i].pow2);
1045
        }
1046
    av_freep(&venc->codebooks);
1047

    
1048
    if (venc->floors)
1049
        for (i = 0; i < venc->nfloors; i++) {
1050
            int j;
1051
            if (venc->floors[i].classes)
1052
                for (j = 0; j < venc->floors[i].nclasses; j++)
1053
                    av_freep(&venc->floors[i].classes[j].books);
1054
            av_freep(&venc->floors[i].classes);
1055
            av_freep(&venc->floors[i].partition_to_class);
1056
            av_freep(&venc->floors[i].list);
1057
        }
1058
    av_freep(&venc->floors);
1059

    
1060
    if (venc->residues)
1061
        for (i = 0; i < venc->nresidues; i++) {
1062
            av_freep(&venc->residues[i].books);
1063
            av_freep(&venc->residues[i].maxes);
1064
        }
1065
    av_freep(&venc->residues);
1066

    
1067
    if (venc->mappings)
1068
        for (i = 0; i < venc->nmappings; i++) {
1069
            av_freep(&venc->mappings[i].mux);
1070
            av_freep(&venc->mappings[i].floor);
1071
            av_freep(&venc->mappings[i].residue);
1072
            av_freep(&venc->mappings[i].magnitude);
1073
            av_freep(&venc->mappings[i].angle);
1074
        }
1075
    av_freep(&venc->mappings);
1076

    
1077
    av_freep(&venc->modes);
1078

    
1079
    av_freep(&venc->saved);
1080
    av_freep(&venc->samples);
1081
    av_freep(&venc->floor);
1082
    av_freep(&venc->coeffs);
1083

    
1084
    ff_mdct_end(&venc->mdct[0]);
1085
    ff_mdct_end(&venc->mdct[1]);
1086

    
1087
    av_freep(&avccontext->coded_frame);
1088
    av_freep(&avccontext->extradata);
1089

    
1090
    return 0 ;
1091
}
1092

    
1093
AVCodec vorbis_encoder = {
1094
    "vorbis",
1095
    CODEC_TYPE_AUDIO,
1096
    CODEC_ID_VORBIS,
1097
    sizeof(vorbis_enc_context),
1098
    vorbis_encode_init,
1099
    vorbis_encode_frame,
1100
    vorbis_encode_close,
1101
    .capabilities= CODEC_CAP_DELAY,
1102
    .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
1103
    .long_name = NULL_IF_CONFIG_SMALL("Vorbis"),
1104
};