Statistics
| Branch: | Revision:

ffmpeg / libavcodec / vorbis_enc.c @ 755bfeab

History | View | Annotate | Download (33.8 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 St, Fifth Floor, Boston, MA  02110-1301  USA
19
 */
20

    
21
/**
22
 * @file 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
#undef NDEBUG
34
#include <assert.h>
35

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

    
50
typedef struct {
51
    int dim;
52
    int subclass;
53
    int masterbook;
54
    int * books;
55
} floor_class_t;
56

    
57
typedef struct {
58
    int partitions;
59
    int * partition_to_class;
60
    int nclasses;
61
    floor_class_t * classes;
62
    int multiplier;
63
    int rangebits;
64
    int values;
65
    floor1_entry_t * list;
66
} floor_t;
67

    
68
typedef struct {
69
    int type;
70
    int begin;
71
    int end;
72
    int partition_size;
73
    int classifications;
74
    int classbook;
75
    int8_t (*books)[8];
76
    float (*maxes)[2];
77
} residue_t;
78

    
79
typedef struct {
80
    int submaps;
81
    int * mux;
82
    int * floor;
83
    int * residue;
84
    int coupling_steps;
85
    int * magnitude;
86
    int * angle;
87
} mapping_t;
88

    
89
typedef struct {
90
    int blockflag;
91
    int mapping;
92
} vorbis_mode_t;
93

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

    
107
    int ncodebooks;
108
    codebook_t * codebooks;
109

    
110
    int nfloors;
111
    floor_t * floors;
112

    
113
    int nresidues;
114
    residue_t * residues;
115

    
116
    int nmappings;
117
    mapping_t * mappings;
118

    
119
    int nmodes;
120
    vorbis_mode_t * modes;
121
} venc_context_t;
122

    
123
typedef struct {
124
    int total;
125
    int total_pos;
126
    int pos;
127
    uint8_t * buf_ptr;
128
} PutBitContext;
129

    
130
static inline void init_put_bits(PutBitContext * pb, uint8_t * buf, int buffer_len) {
131
    pb->total = buffer_len * 8;
132
    pb->total_pos = 0;
133
    pb->pos = 0;
134
    pb->buf_ptr = buf;
135
}
136

    
137
static void put_bits(PutBitContext * pb, int bits, uint64_t val) {
138
    if ((pb->total_pos += bits) >= pb->total) return;
139
    if (!bits) return;
140
    if (pb->pos) {
141
        if (pb->pos > bits) {
142
            *pb->buf_ptr |= val << (8 - pb->pos);
143
            pb->pos -= bits;
144
            bits = 0;
145
        } else {
146
            *pb->buf_ptr++ |= (val << (8 - pb->pos)) & 0xFF;
147
            val >>= pb->pos;
148
            bits -= pb->pos;
149
            pb->pos = 0;
150
        }
151
    }
152
    for (; bits >= 8; bits -= 8) {
153
        *pb->buf_ptr++ = val & 0xFF;
154
        val >>= 8;
155
    }
156
    if (bits) {
157
        *pb->buf_ptr = val;
158
        pb->pos = 8 - bits;
159
    }
160
}
161

    
162
static inline void flush_put_bits(PutBitContext * pb) {
163
}
164

    
165
static inline int put_bits_count(PutBitContext * pb) {
166
    return pb->total_pos;
167
}
168

    
169
static inline void put_codeword(PutBitContext * pb, codebook_t * cb, int entry) {
170
    assert(entry >= 0);
171
    assert(entry < cb->nentries);
172
    assert(cb->lens[entry]);
173
    put_bits(pb, cb->lens[entry], cb->codewords[entry]);
174
}
175

    
176
static int cb_lookup_vals(int lookup, int dimentions, int entries) {
177
    if      (lookup == 1) return ff_vorbis_nth_root(entries, dimentions);
178
    else if (lookup == 2) return dimentions * entries;
179
    return 0;
180
}
181

    
182
static void ready_codebook(codebook_t * cb) {
183
    int i;
184

    
185
    ff_vorbis_len2vlc(cb->lens, cb->codewords, cb->nentries);
186

    
187
    if (!cb->lookup)
188
        cb->pow2 = cb->dimentions = NULL;
189
    else {
190
        int vals = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);
191
        cb->dimentions = av_malloc(sizeof(float) * cb->nentries * cb->ndimentions);
192
        cb->pow2 = av_mallocz(sizeof(float) * cb->nentries);
193
        for (i = 0; i < cb->nentries; i++) {
194
            float last = 0;
195
            int j;
196
            int div = 1;
197
            for (j = 0; j < cb->ndimentions; j++) {
198
                int off;
199
                if (cb->lookup == 1)
200
                    off = (i / div) % vals; // lookup type 1
201
                else
202
                    off = i * cb->ndimentions + j; // lookup type 2
203

    
204
                cb->dimentions[i * cb->ndimentions + j] = last + cb->min + cb->quantlist[off] * cb->delta;
205
                if (cb->seq_p)
206
                    last = cb->dimentions[i * cb->ndimentions + j];
207
                cb->pow2[i] += cb->dimentions[i * cb->ndimentions + j]*cb->dimentions[i * cb->ndimentions + j];
208
                div *= vals;
209
            }
210
            cb->pow2[i] /= 2.;
211
        }
212
    }
213
}
214

    
215
static void ready_residue(residue_t * rc, venc_context_t * venc) {
216
    int i;
217
    assert(rc->type == 2);
218
    rc->maxes = av_mallocz(sizeof(float[2]) * rc->classifications);
219
    for (i = 0; i < rc->classifications; i++) {
220
        int j;
221
        codebook_t * cb;
222
        for (j = 0; j < 8; j++)
223
            if (rc->books[i][j] != -1) break;
224
        if (j == 8) continue; // zero
225
        cb = &venc->codebooks[rc->books[i][j]];
226
        assert(cb->ndimentions >= 2);
227
        assert(cb->lookup);
228

    
229
        for (j = 0; j < cb->nentries; j++) {
230
            float a;
231
            if (!cb->lens[j]) continue;
232
            a = fabs(cb->dimentions[j * cb->ndimentions]);
233
            if (a > rc->maxes[i][0])
234
                rc->maxes[i][0] = a;
235
            a = fabs(cb->dimentions[j * cb->ndimentions + 1]);
236
            if (a > rc->maxes[i][1])
237
                rc->maxes[i][1] = a;
238
        }
239
    }
240
    // small bias
241
    for (i = 0; i < rc->classifications; i++) {
242
        rc->maxes[i][0] += 0.8;
243
        rc->maxes[i][1] += 0.8;
244
    }
245
}
246

    
247
static void create_vorbis_context(venc_context_t * venc, AVCodecContext * avccontext) {
248
    floor_t * fc;
249
    residue_t * rc;
250
    mapping_t * mc;
251
    int i, book;
252

    
253
    venc->channels = avccontext->channels;
254
    venc->sample_rate = avccontext->sample_rate;
255
    venc->log2_blocksize[0] = venc->log2_blocksize[1] = 11;
256

    
257
    venc->ncodebooks = sizeof(cvectors)/sizeof(cvectors[0]);
258
    venc->codebooks = av_malloc(sizeof(codebook_t) * venc->ncodebooks);
259

    
260
    // codebook 0..14 - floor1 book, values 0..255
261
    // codebook 15 residue masterbook
262
    // codebook 16..29 residue
263
    for (book = 0; book < venc->ncodebooks; book++) {
264
        codebook_t * cb = &venc->codebooks[book];
265
        int vals;
266
        cb->ndimentions = cvectors[book].dim;
267
        cb->nentries = cvectors[book].real_len;
268
        cb->min = cvectors[book].min;
269
        cb->delta = cvectors[book].delta;
270
        cb->lookup = cvectors[book].lookup;
271
        cb->seq_p = 0;
272

    
273
        cb->lens = av_malloc(sizeof(uint8_t) * cb->nentries);
274
        cb->codewords = av_malloc(sizeof(uint32_t) * cb->nentries);
275
        memcpy(cb->lens, cvectors[book].clens, cvectors[book].len);
276
        memset(cb->lens + cvectors[book].len, 0, cb->nentries - cvectors[book].len);
277

    
278
        if (cb->lookup) {
279
            vals = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);
280
            cb->quantlist = av_malloc(sizeof(int) * vals);
281
            for (i = 0; i < vals; i++)
282
                cb->quantlist[i] = cvectors[book].quant[i];
283
        } else {
284
            cb->quantlist = NULL;
285
        }
286
        ready_codebook(cb);
287
    }
288

    
289
    venc->nfloors = 1;
290
    venc->floors = av_malloc(sizeof(floor_t) * venc->nfloors);
291

    
292
    // just 1 floor
293
    fc = &venc->floors[0];
294
    fc->partitions = 8;
295
    fc->partition_to_class = av_malloc(sizeof(int) * fc->partitions);
296
    fc->nclasses = 0;
297
    for (i = 0; i < fc->partitions; i++) {
298
        static const int a[] = {0,1,2,2,3,3,4,4};
299
        fc->partition_to_class[i] = a[i];
300
        fc->nclasses = FFMAX(fc->nclasses, fc->partition_to_class[i]);
301
    }
302
    fc->nclasses++;
303
    fc->classes = av_malloc(sizeof(floor_class_t) * fc->nclasses);
304
    for (i = 0; i < fc->nclasses; i++) {
305
        floor_class_t * c = &fc->classes[i];
306
        int j, books;
307
        c->dim = floor_classes[i].dim;
308
        c->subclass = floor_classes[i].subclass;
309
        c->masterbook = floor_classes[i].masterbook;
310
        books = (1 << c->subclass);
311
        c->books = av_malloc(sizeof(int) * books);
312
        for (j = 0; j < books; j++)
313
            c->books[j] = floor_classes[i].nbooks[j];
314
    }
315
    fc->multiplier = 2;
316
    fc->rangebits = venc->log2_blocksize[0] - 1;
317

    
318
    fc->values = 2;
319
    for (i = 0; i < fc->partitions; i++)
320
        fc->values += fc->classes[fc->partition_to_class[i]].dim;
321

    
322
    fc->list = av_malloc(sizeof(floor1_entry_t) * fc->values);
323
    fc->list[0].x = 0;
324
    fc->list[1].x = 1 << fc->rangebits;
325
    for (i = 2; i < fc->values; i++) {
326
        static const int a[] = {
327
             93, 23,372,  6, 46,186,750, 14, 33, 65,
328
            130,260,556,  3, 10, 18, 28, 39, 55, 79,
329
            111,158,220,312,464,650,850
330
        };
331
        fc->list[i].x = a[i - 2];
332
    }
333
    ff_vorbis_ready_floor1_list(fc->list, fc->values);
334

    
335
    venc->nresidues = 1;
336
    venc->residues = av_malloc(sizeof(residue_t) * venc->nresidues);
337

    
338
    // single residue
339
    rc = &venc->residues[0];
340
    rc->type = 2;
341
    rc->begin = 0;
342
    rc->end = 1600;
343
    rc->partition_size = 32;
344
    rc->classifications = 10;
345
    rc->classbook = 15;
346
    rc->books = av_malloc(sizeof(*rc->books) * rc->classifications);
347
    {
348
        static const int8_t a[10][8] = {
349
            { -1, -1, -1, -1, -1, -1, -1, -1, },
350
            { -1, -1, 16, -1, -1, -1, -1, -1, },
351
            { -1, -1, 17, -1, -1, -1, -1, -1, },
352
            { -1, -1, 18, -1, -1, -1, -1, -1, },
353
            { -1, -1, 19, -1, -1, -1, -1, -1, },
354
            { -1, -1, 20, -1, -1, -1, -1, -1, },
355
            { -1, -1, 21, -1, -1, -1, -1, -1, },
356
            { 22, 23, -1, -1, -1, -1, -1, -1, },
357
            { 24, 25, -1, -1, -1, -1, -1, -1, },
358
            { 26, 27, 28, -1, -1, -1, -1, -1, },
359
        };
360
        memcpy(rc->books, a, sizeof a);
361
    }
362
    ready_residue(rc, venc);
363

    
364
    venc->nmappings = 1;
365
    venc->mappings = av_malloc(sizeof(mapping_t) * venc->nmappings);
366

    
367
    // single mapping
368
    mc = &venc->mappings[0];
369
    mc->submaps = 1;
370
    mc->mux = av_malloc(sizeof(int) * venc->channels);
371
    for (i = 0; i < venc->channels; i++)
372
        mc->mux[i] = 0;
373
    mc->floor = av_malloc(sizeof(int) * mc->submaps);
374
    mc->residue = av_malloc(sizeof(int) * mc->submaps);
375
    for (i = 0; i < mc->submaps; i++) {
376
        mc->floor[i] = 0;
377
        mc->residue[i] = 0;
378
    }
379
    mc->coupling_steps = venc->channels == 2 ? 1 : 0;
380
    mc->magnitude = av_malloc(sizeof(int) * mc->coupling_steps);
381
    mc->angle = av_malloc(sizeof(int) * mc->coupling_steps);
382
    if (mc->coupling_steps) {
383
        mc->magnitude[0] = 0;
384
        mc->angle[0] = 1;
385
    }
386

    
387
    venc->nmodes = 1;
388
    venc->modes = av_malloc(sizeof(vorbis_mode_t) * venc->nmodes);
389

    
390
    // single mode
391
    venc->modes[0].blockflag = 0;
392
    venc->modes[0].mapping = 0;
393

    
394
    venc->have_saved = 0;
395
    venc->saved = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
396
    venc->samples = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]));
397
    venc->floor = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
398
    venc->coeffs = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
399

    
400
    venc->win[0] = ff_vorbis_vwin[venc->log2_blocksize[0] - 6];
401
    venc->win[1] = ff_vorbis_vwin[venc->log2_blocksize[1] - 6];
402

    
403
    ff_mdct_init(&venc->mdct[0], venc->log2_blocksize[0], 0);
404
    ff_mdct_init(&venc->mdct[1], venc->log2_blocksize[1], 0);
405
}
406

    
407
static void put_float(PutBitContext * pb, float f) {
408
    int exp, mant;
409
    uint32_t res = 0;
410
    mant = (int)ldexp(frexp(f, &exp), 20);
411
    exp += 788 - 20;
412
    if (mant < 0) { res |= (1 << 31); mant = -mant; }
413
    res |= mant | (exp << 21);
414
    put_bits(pb, 32, res);
415
}
416

    
417
static void put_codebook_header(PutBitContext * pb, codebook_t * cb) {
418
    int i;
419
    int ordered = 0;
420

    
421
    put_bits(pb, 24, 0x564342); //magic
422
    put_bits(pb, 16, cb->ndimentions);
423
    put_bits(pb, 24, cb->nentries);
424

    
425
    for (i = 1; i < cb->nentries; i++)
426
        if (cb->lens[i] < cb->lens[i-1]) break;
427
    if (i == cb->nentries)
428
        ordered = 1;
429

    
430
    put_bits(pb, 1, ordered);
431
    if (ordered) {
432
        int len = cb->lens[0];
433
        put_bits(pb, 5, len - 1);
434
        i = 0;
435
        while (i < cb->nentries) {
436
            int j;
437
            for (j = 0; j+i < cb->nentries; j++)
438
                if (cb->lens[j+i] != len) break;
439
            put_bits(pb, ilog(cb->nentries - i), j);
440
            i += j;
441
            len++;
442
        }
443
    } else {
444
        int sparse = 0;
445
        for (i = 0; i < cb->nentries; i++)
446
            if (!cb->lens[i]) break;
447
        if (i != cb->nentries)
448
            sparse = 1;
449
        put_bits(pb, 1, sparse);
450

    
451
        for (i = 0; i < cb->nentries; i++) {
452
            if (sparse) put_bits(pb, 1, !!cb->lens[i]);
453
            if (cb->lens[i]) put_bits(pb, 5, cb->lens[i] - 1);
454
        }
455
    }
456

    
457
    put_bits(pb, 4, cb->lookup);
458
    if (cb->lookup) {
459
        int tmp = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);
460
        int bits = ilog(cb->quantlist[0]);
461

    
462
        for (i = 1; i < tmp; i++)
463
            bits = FFMAX(bits, ilog(cb->quantlist[i]));
464

    
465
        put_float(pb, cb->min);
466
        put_float(pb, cb->delta);
467

    
468
        put_bits(pb, 4, bits - 1);
469
        put_bits(pb, 1, cb->seq_p);
470

    
471
        for (i = 0; i < tmp; i++)
472
            put_bits(pb, bits, cb->quantlist[i]);
473
    }
474
}
475

    
476
static void put_floor_header(PutBitContext * pb, floor_t * fc) {
477
    int i;
478

    
479
    put_bits(pb, 16, 1); // type, only floor1 is supported
480

    
481
    put_bits(pb, 5, fc->partitions);
482

    
483
    for (i = 0; i < fc->partitions; i++)
484
        put_bits(pb, 4, fc->partition_to_class[i]);
485

    
486
    for (i = 0; i < fc->nclasses; i++) {
487
        int j, books;
488

    
489
        put_bits(pb, 3, fc->classes[i].dim - 1);
490
        put_bits(pb, 2, fc->classes[i].subclass);
491

    
492
        if (fc->classes[i].subclass)
493
            put_bits(pb, 8, fc->classes[i].masterbook);
494

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

    
497
        for (j = 0; j < books; j++)
498
            put_bits(pb, 8, fc->classes[i].books[j] + 1);
499
    }
500

    
501
    put_bits(pb, 2, fc->multiplier - 1);
502
    put_bits(pb, 4, fc->rangebits);
503

    
504
    for (i = 2; i < fc->values; i++)
505
        put_bits(pb, fc->rangebits, fc->list[i].x);
506
}
507

    
508
static void put_residue_header(PutBitContext * pb, residue_t * rc) {
509
    int i;
510

    
511
    put_bits(pb, 16, rc->type);
512

    
513
    put_bits(pb, 24, rc->begin);
514
    put_bits(pb, 24, rc->end);
515
    put_bits(pb, 24, rc->partition_size - 1);
516
    put_bits(pb, 6, rc->classifications - 1);
517
    put_bits(pb, 8, rc->classbook);
518

    
519
    for (i = 0; i < rc->classifications; i++) {
520
        int j, tmp = 0;
521
        for (j = 0; j < 8; j++)
522
            tmp |= (rc->books[i][j] != -1) << j;
523

    
524
        put_bits(pb, 3, tmp & 7);
525
        put_bits(pb, 1, tmp > 7);
526

    
527
        if (tmp > 7)
528
            put_bits(pb, 5, tmp >> 3);
529
    }
530

    
531
    for (i = 0; i < rc->classifications; i++) {
532
        int j;
533
        for (j = 0; j < 8; j++)
534
            if (rc->books[i][j] != -1)
535
                put_bits(pb, 8, rc->books[i][j]);
536
    }
537
}
538

    
539
static int put_main_header(venc_context_t * venc, uint8_t ** out) {
540
    int i;
541
    PutBitContext pb;
542
    uint8_t buffer[50000] = {0}, * p = buffer;
543
    int buffer_len = sizeof buffer;
544
    int len, hlens[3];
545

    
546
    // identification header
547
    init_put_bits(&pb, p, buffer_len);
548
    put_bits(&pb, 8, 1); //magic
549
    for (i = 0; "vorbis"[i]; i++)
550
        put_bits(&pb, 8, "vorbis"[i]);
551
    put_bits(&pb, 32, 0); // version
552
    put_bits(&pb, 8, venc->channels);
553
    put_bits(&pb, 32, venc->sample_rate);
554
    put_bits(&pb, 32, 0); // bitrate
555
    put_bits(&pb, 32, 0); // bitrate
556
    put_bits(&pb, 32, 0); // bitrate
557
    put_bits(&pb, 4, venc->log2_blocksize[0]);
558
    put_bits(&pb, 4, venc->log2_blocksize[1]);
559
    put_bits(&pb, 1, 1); // framing
560

    
561
    flush_put_bits(&pb);
562
    hlens[0] = (put_bits_count(&pb) + 7) / 8;
563
    buffer_len -= hlens[0];
564
    p += hlens[0];
565

    
566
    // comment header
567
    init_put_bits(&pb, p, buffer_len);
568
    put_bits(&pb, 8, 3); //magic
569
    for (i = 0; "vorbis"[i]; i++)
570
        put_bits(&pb, 8, "vorbis"[i]);
571
    put_bits(&pb, 32, 0); // vendor length TODO
572
    put_bits(&pb, 32, 0); // amount of comments
573
    put_bits(&pb, 1, 1); // framing
574

    
575
    flush_put_bits(&pb);
576
    hlens[1] = (put_bits_count(&pb) + 7) / 8;
577
    buffer_len -= hlens[1];
578
    p += hlens[1];
579

    
580
    // setup header
581
    init_put_bits(&pb, p, buffer_len);
582
    put_bits(&pb, 8, 5); //magic
583
    for (i = 0; "vorbis"[i]; i++)
584
        put_bits(&pb, 8, "vorbis"[i]);
585

    
586
    // codebooks
587
    put_bits(&pb, 8, venc->ncodebooks - 1);
588
    for (i = 0; i < venc->ncodebooks; i++)
589
        put_codebook_header(&pb, &venc->codebooks[i]);
590

    
591
    // time domain, reserved, zero
592
    put_bits(&pb, 6, 0);
593
    put_bits(&pb, 16, 0);
594

    
595
    // floors
596
    put_bits(&pb, 6, venc->nfloors - 1);
597
    for (i = 0; i < venc->nfloors; i++)
598
        put_floor_header(&pb, &venc->floors[i]);
599

    
600
    // residues
601
    put_bits(&pb, 6, venc->nresidues - 1);
602
    for (i = 0; i < venc->nresidues; i++)
603
        put_residue_header(&pb, &venc->residues[i]);
604

    
605
    // mappings
606
    put_bits(&pb, 6, venc->nmappings - 1);
607
    for (i = 0; i < venc->nmappings; i++) {
608
        mapping_t * mc = &venc->mappings[i];
609
        int j;
610
        put_bits(&pb, 16, 0); // mapping type
611

    
612
        put_bits(&pb, 1, mc->submaps > 1);
613
        if (mc->submaps > 1)
614
            put_bits(&pb, 4, mc->submaps - 1);
615

    
616
        put_bits(&pb, 1, !!mc->coupling_steps);
617
        if (mc->coupling_steps) {
618
            put_bits(&pb, 8, mc->coupling_steps - 1);
619
            for (j = 0; j < mc->coupling_steps; j++) {
620
                put_bits(&pb, ilog(venc->channels - 1), mc->magnitude[j]);
621
                put_bits(&pb, ilog(venc->channels - 1), mc->angle[j]);
622
            }
623
        }
624

    
625
        put_bits(&pb, 2, 0); // reserved
626

    
627
        if (mc->submaps > 1)
628
            for (j = 0; j < venc->channels; j++)
629
                put_bits(&pb, 4, mc->mux[j]);
630

    
631
        for (j = 0; j < mc->submaps; j++) {
632
            put_bits(&pb, 8, 0); // reserved time configuration
633
            put_bits(&pb, 8, mc->floor[j]);
634
            put_bits(&pb, 8, mc->residue[j]);
635
        }
636
    }
637

    
638
    // modes
639
    put_bits(&pb, 6, venc->nmodes - 1);
640
    for (i = 0; i < venc->nmodes; i++) {
641
        put_bits(&pb, 1, venc->modes[i].blockflag);
642
        put_bits(&pb, 16, 0); // reserved window type
643
        put_bits(&pb, 16, 0); // reserved transform type
644
        put_bits(&pb, 8, venc->modes[i].mapping);
645
    }
646

    
647
    put_bits(&pb, 1, 1); // framing
648

    
649
    flush_put_bits(&pb);
650
    hlens[2] = (put_bits_count(&pb) + 7) / 8;
651

    
652
    len = hlens[0] + hlens[1] + hlens[2];
653
    p = *out = av_mallocz(64 + len + len/255);
654

    
655
    *p++ = 2;
656
    p += av_xiphlacing(p, hlens[0]);
657
    p += av_xiphlacing(p, hlens[1]);
658
    buffer_len = 0;
659
    for (i = 0; i < 3; i++) {
660
        memcpy(p, buffer + buffer_len, hlens[i]);
661
        p += hlens[i];
662
        buffer_len += hlens[i];
663
    }
664

    
665
    return p - *out;
666
}
667

    
668
static float get_floor_average(floor_t * fc, float * coeffs, int i) {
669
    int begin = fc->list[fc->list[FFMAX(i-1, 0)].sort].x;
670
    int end   = fc->list[fc->list[FFMIN(i+1, fc->values - 1)].sort].x;
671
    int j;
672
    float average = 0;
673

    
674
    for (j = begin; j < end; j++)
675
        average += fabs(coeffs[j]);
676
    return average / (end - begin);
677
}
678

    
679
static void floor_fit(venc_context_t * venc, floor_t * fc, float * coeffs, uint_fast16_t * posts, int samples) {
680
    int range = 255 / fc->multiplier + 1;
681
    int i;
682
    float tot_average = 0.;
683
    float averages[fc->values];
684
    for (i = 0; i < fc->values; i++){
685
        averages[i] = get_floor_average(fc, coeffs, i);
686
        tot_average += averages[i];
687
    }
688
    tot_average /= fc->values;
689
    tot_average /= venc->quality;
690

    
691
    for (i = 0; i < fc->values; i++) {
692
        int position = fc->list[fc->list[i].sort].x;
693
        float average = averages[i];
694
        int j;
695

    
696
        average *= pow(tot_average / average, 0.5) * pow(1.25, position/200.); // MAGIC!
697
        for (j = 0; j < range - 1; j++)
698
            if (ff_vorbis_floor1_inverse_db_table[j * fc->multiplier] > average) break;
699
        posts[fc->list[i].sort] = j;
700
    }
701
}
702

    
703
static int render_point(int x0, int y0, int x1, int y1, int x) {
704
    return y0 +  (x - x0) * (y1 - y0) / (x1 - x0);
705
}
706

    
707
static void floor_encode(venc_context_t * venc, floor_t * fc, PutBitContext * pb, uint_fast16_t * posts, float * floor, int samples) {
708
    int range = 255 / fc->multiplier + 1;
709
    int coded[fc->values]; // first 2 values are unused
710
    int i, counter;
711

    
712
    put_bits(pb, 1, 1); // non zero
713
    put_bits(pb, ilog(range - 1), posts[0]);
714
    put_bits(pb, ilog(range - 1), posts[1]);
715
    coded[0] = coded[1] = 1;
716

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

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

    
778
    ff_vorbis_floor1_render_list(fc->list, fc->values, posts, coded, fc->multiplier, floor, samples);
779
}
780

    
781
static float * put_vector(codebook_t * book, PutBitContext * pb, float * num) {
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]) continue;
789
        for (j = 0; j < book->ndimentions; j++)
790
            d -= vec[j] * num[j];
791
        if (distance > d) {
792
            entry = i;
793
            distance = d;
794
        }
795
    }
796
    put_codeword(pb, book, entry);
797
    return &book->dimentions[entry * book->ndimentions];
798
}
799

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

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

    
818
        for (i = 0; i < rc->classifications - 1; i++) {
819
            if (max1 < rc->maxes[i][0] && max2 < rc->maxes[i][1]) break;
820
        }
821
        classes[0][p] = i;
822
    }
823

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

    
844
                    assert(rc->type == 0 || rc->type == 2);
845
                    assert(!(psize % book->ndimentions));
846

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

    
885
static int apply_window_and_mdct(venc_context_t * venc, signed short * audio, int samples) {
886
    int i, j, channel;
887
    const float * win = venc->win[0];
888
    int window_len = 1 << (venc->log2_blocksize[0] - 1);
889
    float n = (float)(1 << venc->log2_blocksize[0]) / 4.;
890
    // FIXME use dsp
891

    
892
    if (!venc->have_saved && !samples) return 0;
893

    
894
    if (venc->have_saved) {
895
        for (channel = 0; channel < venc->channels; channel++) {
896
            memcpy(venc->samples + channel*window_len*2, venc->saved + channel*window_len, sizeof(float)*window_len);
897
        }
898
    } else {
899
        for (channel = 0; channel < venc->channels; channel++) {
900
            memset(venc->samples + channel*window_len*2, 0, sizeof(float)*window_len);
901
        }
902
    }
903

    
904
    if (samples) {
905
        for (channel = 0; channel < venc->channels; channel++) {
906
            float * offset = venc->samples + channel*window_len*2 + window_len;
907
            j = channel;
908
            for (i = 0; i < samples; i++, j += venc->channels)
909
                offset[i] = -audio[j] / 32768. / n * win[window_len - i - 1]; //FIXME find out why the sign has to be fliped
910
        }
911
    } else {
912
        for (channel = 0; channel < venc->channels; channel++) {
913
            memset(venc->samples + channel*window_len*2 + window_len, 0, sizeof(float)*window_len);
914
        }
915
    }
916

    
917
    for (channel = 0; channel < venc->channels; channel++) {
918
        ff_mdct_calc(&venc->mdct[0], venc->coeffs + channel*window_len, venc->samples + channel*window_len*2, venc->floor/*tmp*/);
919
    }
920

    
921
    if (samples) {
922
        for (channel = 0; channel < venc->channels; channel++) {
923
            float * offset = venc->saved + channel*window_len;
924
            j = channel;
925
            for (i = 0; i < samples; i++, j += venc->channels)
926
                offset[i] = -audio[j] / 32768. / n * win[i]; //FIXME find out why the sign has to be fliped
927
        }
928
        venc->have_saved = 1;
929
    } else {
930
        venc->have_saved = 0;
931
    }
932
    return 1;
933
}
934

    
935
static int vorbis_encode_init(AVCodecContext * avccontext)
936
{
937
    venc_context_t * venc = avccontext->priv_data;
938

    
939
    if (avccontext->channels != 2) {
940
        av_log(avccontext, AV_LOG_ERROR, "Current FFmpeg Vorbis encoder only supports 2 channels.\n");
941
        return -1;
942
    }
943

    
944
    create_vorbis_context(venc, avccontext);
945

    
946
    if (avccontext->flags & CODEC_FLAG_QSCALE)
947
        venc->quality = avccontext->global_quality / (float)FF_QP2LAMBDA / 10.;
948
    else
949
        venc->quality = 1.;
950
    venc->quality *= venc->quality;
951

    
952
    avccontext->extradata_size = put_main_header(venc, (uint8_t**)&avccontext->extradata);
953

    
954
    avccontext->frame_size = 1 << (venc->log2_blocksize[0] - 1);
955

    
956
    avccontext->coded_frame = avcodec_alloc_frame();
957
    avccontext->coded_frame->key_frame = 1;
958

    
959
    return 0;
960
}
961

    
962
static int vorbis_encode_frame(AVCodecContext * avccontext, unsigned char * packets, int buf_size, void *data)
963
{
964
    venc_context_t * venc = avccontext->priv_data;
965
    signed short * audio = data;
966
    int samples = data ? avccontext->frame_size : 0;
967
    vorbis_mode_t * mode;
968
    mapping_t * mapping;
969
    PutBitContext pb;
970
    int i;
971

    
972
    if (!apply_window_and_mdct(venc, audio, samples)) return 0;
973
    samples = 1 << (venc->log2_blocksize[0] - 1);
974

    
975
    init_put_bits(&pb, packets, buf_size);
976

    
977
    put_bits(&pb, 1, 0); // magic bit
978

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

    
981
    mode = &venc->modes[0];
982
    mapping = &venc->mappings[mode->mapping];
983
    if (mode->blockflag) {
984
        put_bits(&pb, 1, 0);
985
        put_bits(&pb, 1, 0);
986
    }
987

    
988
    for (i = 0; i < venc->channels; i++) {
989
        floor_t * fc = &venc->floors[mapping->floor[mapping->mux[i]]];
990
        uint_fast16_t posts[fc->values];
991
        floor_fit(venc, fc, &venc->coeffs[i * samples], posts, samples);
992
        floor_encode(venc, fc, &pb, posts, &venc->floor[i * samples], samples);
993
    }
994

    
995
    for (i = 0; i < venc->channels * samples; i++) {
996
        venc->coeffs[i] /= venc->floor[i];
997
    }
998

    
999
    for (i = 0; i < mapping->coupling_steps; i++) {
1000
        float * mag = venc->coeffs + mapping->magnitude[i] * samples;
1001
        float * ang = venc->coeffs + mapping->angle[i] * samples;
1002
        int j;
1003
        for (j = 0; j < samples; j++) {
1004
            float a = ang[j];
1005
            ang[j] -= mag[j];
1006
            if (mag[j] > 0) ang[j] = -ang[j];
1007
            if (ang[j] < 0) mag[j] = a;
1008
        }
1009
    }
1010

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

    
1013
    flush_put_bits(&pb);
1014
    return (put_bits_count(&pb) + 7) / 8;
1015
}
1016

    
1017

    
1018
static int vorbis_encode_close(AVCodecContext * avccontext)
1019
{
1020
    venc_context_t * venc = avccontext->priv_data;
1021
    int i;
1022

    
1023
    if (venc->codebooks)
1024
        for (i = 0; i < venc->ncodebooks; i++) {
1025
            av_freep(&venc->codebooks[i].lens);
1026
            av_freep(&venc->codebooks[i].codewords);
1027
            av_freep(&venc->codebooks[i].quantlist);
1028
            av_freep(&venc->codebooks[i].dimentions);
1029
            av_freep(&venc->codebooks[i].pow2);
1030
        }
1031
    av_freep(&venc->codebooks);
1032

    
1033
    if (venc->floors)
1034
        for (i = 0; i < venc->nfloors; i++) {
1035
            int j;
1036
            if (venc->floors[i].classes)
1037
                for (j = 0; j < venc->floors[i].nclasses; j++)
1038
                    av_freep(&venc->floors[i].classes[j].books);
1039
            av_freep(&venc->floors[i].classes);
1040
            av_freep(&venc->floors[i].partition_to_class);
1041
            av_freep(&venc->floors[i].list);
1042
        }
1043
    av_freep(&venc->floors);
1044

    
1045
    if (venc->residues)
1046
        for (i = 0; i < venc->nresidues; i++) {
1047
            av_freep(&venc->residues[i].books);
1048
            av_freep(&venc->residues[i].maxes);
1049
        }
1050
    av_freep(&venc->residues);
1051

    
1052
    if (venc->mappings)
1053
        for (i = 0; i < venc->nmappings; i++) {
1054
            av_freep(&venc->mappings[i].mux);
1055
            av_freep(&venc->mappings[i].floor);
1056
            av_freep(&venc->mappings[i].residue);
1057
            av_freep(&venc->mappings[i].magnitude);
1058
            av_freep(&venc->mappings[i].angle);
1059
        }
1060
    av_freep(&venc->mappings);
1061

    
1062
    av_freep(&venc->modes);
1063

    
1064
    av_freep(&venc->saved);
1065
    av_freep(&venc->samples);
1066
    av_freep(&venc->floor);
1067
    av_freep(&venc->coeffs);
1068

    
1069
    ff_mdct_end(&venc->mdct[0]);
1070
    ff_mdct_end(&venc->mdct[1]);
1071

    
1072
    av_freep(&avccontext->coded_frame);
1073
    av_freep(&avccontext->extradata);
1074

    
1075
    return 0 ;
1076
}
1077

    
1078
AVCodec vorbis_encoder = {
1079
    "vorbis",
1080
    CODEC_TYPE_AUDIO,
1081
    CODEC_ID_VORBIS,
1082
    sizeof(venc_context_t),
1083
    vorbis_encode_init,
1084
    vorbis_encode_frame,
1085
    vorbis_encode_close,
1086
    .capabilities= CODEC_CAP_DELAY,
1087
};