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 "bitstream.h"
35
36#undef NDEBUG
37#include <assert.h>
38
39typedef 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
53typedef struct {
54    int dim;
55    int subclass;
56    int masterbook;
57    int * books;
58} vorbis_enc_floor_class;
59
60typedef 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
71typedef 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
82typedef 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
92typedef struct {
93    int blockflag;
94    int mapping;
95} vorbis_enc_mode;
96
97typedef struct {
98    int channels;
99    int sample_rate;
100    int log2_blocksize[2];
101    MDCTContext 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
128static inline void put_codeword(PutBitContext * pb, vorbis_enc_codebook * cb, int entry) {
129    assert(entry >= 0);
130    assert(entry < cb->nentries);
131    assert(cb->lens[entry]);
132    put_bits(pb, cb->lens[entry], cb->codewords[entry]);
133}
134
135static int cb_lookup_vals(int lookup, int dimentions, int entries) {
136    if      (lookup == 1) return ff_vorbis_nth_root(entries, dimentions);
137    else if (lookup == 2) return dimentions * entries;
138    return 0;
139}
140
141static void ready_codebook(vorbis_enc_codebook * cb) {
142    int i;
143
144    ff_vorbis_len2vlc(cb->lens, cb->codewords, cb->nentries);
145
146    if (!cb->lookup)
147        cb->pow2 = cb->dimentions = NULL;
148    else {
149        int vals = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);
150        cb->dimentions = av_malloc(sizeof(float) * cb->nentries * cb->ndimentions);
151        cb->pow2 = av_mallocz(sizeof(float) * cb->nentries);
152        for (i = 0; i < cb->nentries; i++) {
153            float last = 0;
154            int j;
155            int div = 1;
156            for (j = 0; j < cb->ndimentions; j++) {
157                int off;
158                if (cb->lookup == 1)
159                    off = (i / div) % vals; // lookup type 1
160                else
161                    off = i * cb->ndimentions + j; // lookup type 2
162
163                cb->dimentions[i * cb->ndimentions + j] = last + cb->min + cb->quantlist[off] * cb->delta;
164                if (cb->seq_p)
165                    last = cb->dimentions[i * cb->ndimentions + j];
166                cb->pow2[i] += cb->dimentions[i * cb->ndimentions + j]*cb->dimentions[i * cb->ndimentions + j];
167                div *= vals;
168            }
169            cb->pow2[i] /= 2.;
170        }
171    }
172}
173
174static void ready_residue(vorbis_enc_residue * rc, vorbis_enc_context * venc) {
175    int i;
176    assert(rc->type == 2);
177    rc->maxes = av_mallocz(sizeof(float[2]) * rc->classifications);
178    for (i = 0; i < rc->classifications; i++) {
179        int j;
180        vorbis_enc_codebook * cb;
181        for (j = 0; j < 8; j++)
182            if (rc->books[i][j] != -1) break;
183        if (j == 8) continue; // zero
184        cb = &venc->codebooks[rc->books[i][j]];
185        assert(cb->ndimentions >= 2);
186        assert(cb->lookup);
187
188        for (j = 0; j < cb->nentries; j++) {
189            float a;
190            if (!cb->lens[j]) continue;
191            a = fabs(cb->dimentions[j * cb->ndimentions]);
192            if (a > rc->maxes[i][0])
193                rc->maxes[i][0] = a;
194            a = fabs(cb->dimentions[j * cb->ndimentions + 1]);
195            if (a > rc->maxes[i][1])
196                rc->maxes[i][1] = a;
197        }
198    }
199    // small bias
200    for (i = 0; i < rc->classifications; i++) {
201        rc->maxes[i][0] += 0.8;
202        rc->maxes[i][1] += 0.8;
203    }
204}
205
206static void create_vorbis_context(vorbis_enc_context * venc, AVCodecContext * avccontext) {
207    vorbis_enc_floor * fc;
208    vorbis_enc_residue * rc;
209    vorbis_enc_mapping * mc;
210    int i, book;
211
212    venc->channels = avccontext->channels;
213    venc->sample_rate = avccontext->sample_rate;
214    venc->log2_blocksize[0] = venc->log2_blocksize[1] = 11;
215
216    venc->ncodebooks = FF_ARRAY_ELEMS(cvectors);
217    venc->codebooks = av_malloc(sizeof(vorbis_enc_codebook) * venc->ncodebooks);
218
219    // codebook 0..14 - floor1 book, values 0..255
220    // codebook 15 residue masterbook
221    // codebook 16..29 residue
222    for (book = 0; book < venc->ncodebooks; book++) {
223        vorbis_enc_codebook * cb = &venc->codebooks[book];
224        int vals;
225        cb->ndimentions = cvectors[book].dim;
226        cb->nentries = cvectors[book].real_len;
227        cb->min = cvectors[book].min;
228        cb->delta = cvectors[book].delta;
229        cb->lookup = cvectors[book].lookup;
230        cb->seq_p = 0;
231
232        cb->lens = av_malloc(sizeof(uint8_t) * cb->nentries);
233        cb->codewords = av_malloc(sizeof(uint32_t) * cb->nentries);
234        memcpy(cb->lens, cvectors[book].clens, cvectors[book].len);
235        memset(cb->lens + cvectors[book].len, 0, cb->nentries - cvectors[book].len);
236
237        if (cb->lookup) {
238            vals = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);
239            cb->quantlist = av_malloc(sizeof(int) * vals);
240            for (i = 0; i < vals; i++)
241                cb->quantlist[i] = cvectors[book].quant[i];
242        } else {
243            cb->quantlist = NULL;
244        }
245        ready_codebook(cb);
246    }
247
248    venc->nfloors = 1;
249    venc->floors = av_malloc(sizeof(vorbis_enc_floor) * venc->nfloors);
250
251    // just 1 floor
252    fc = &venc->floors[0];
253    fc->partitions = 8;
254    fc->partition_to_class = av_malloc(sizeof(int) * fc->partitions);
255    fc->nclasses = 0;
256    for (i = 0; i < fc->partitions; i++) {
257        static const int a[] = {0,1,2,2,3,3,4,4};
258        fc->partition_to_class[i] = a[i];
259        fc->nclasses = FFMAX(fc->nclasses, fc->partition_to_class[i]);
260    }
261    fc->nclasses++;
262    fc->classes = av_malloc(sizeof(vorbis_enc_floor_class) * fc->nclasses);
263    for (i = 0; i < fc->nclasses; i++) {
264        vorbis_enc_floor_class * c = &fc->classes[i];
265        int j, books;
266        c->dim = floor_classes[i].dim;
267        c->subclass = floor_classes[i].subclass;
268        c->masterbook = floor_classes[i].masterbook;
269        books = (1 << c->subclass);
270        c->books = av_malloc(sizeof(int) * books);
271        for (j = 0; j < books; j++)
272            c->books[j] = floor_classes[i].nbooks[j];
273    }
274    fc->multiplier = 2;
275    fc->rangebits = venc->log2_blocksize[0] - 1;
276
277    fc->values = 2;
278    for (i = 0; i < fc->partitions; i++)
279        fc->values += fc->classes[fc->partition_to_class[i]].dim;
280
281    fc->list = av_malloc(sizeof(vorbis_floor1_entry) * fc->values);
282    fc->list[0].x = 0;
283    fc->list[1].x = 1 << fc->rangebits;
284    for (i = 2; i < fc->values; i++) {
285        static const int a[] = {
286             93, 23,372,  6, 46,186,750, 14, 33, 65,
287            130,260,556,  3, 10, 18, 28, 39, 55, 79,
288            111,158,220,312,464,650,850
289        };
290        fc->list[i].x = a[i - 2];
291    }
292    ff_vorbis_ready_floor1_list(fc->list, fc->values);
293
294    venc->nresidues = 1;
295    venc->residues = av_malloc(sizeof(vorbis_enc_residue) * venc->nresidues);
296
297    // single residue
298    rc = &venc->residues[0];
299    rc->type = 2;
300    rc->begin = 0;
301    rc->end = 1600;
302    rc->partition_size = 32;
303    rc->classifications = 10;
304    rc->classbook = 15;
305    rc->books = av_malloc(sizeof(*rc->books) * rc->classifications);
306    {
307        static const int8_t a[10][8] = {
308            { -1, -1, -1, -1, -1, -1, -1, -1, },
309            { -1, -1, 16, -1, -1, -1, -1, -1, },
310            { -1, -1, 17, -1, -1, -1, -1, -1, },
311            { -1, -1, 18, -1, -1, -1, -1, -1, },
312            { -1, -1, 19, -1, -1, -1, -1, -1, },
313            { -1, -1, 20, -1, -1, -1, -1, -1, },
314            { -1, -1, 21, -1, -1, -1, -1, -1, },
315            { 22, 23, -1, -1, -1, -1, -1, -1, },
316            { 24, 25, -1, -1, -1, -1, -1, -1, },
317            { 26, 27, 28, -1, -1, -1, -1, -1, },
318        };
319        memcpy(rc->books, a, sizeof a);
320    }
321    ready_residue(rc, venc);
322
323    venc->nmappings = 1;
324    venc->mappings = av_malloc(sizeof(vorbis_enc_mapping) * venc->nmappings);
325
326    // single mapping
327    mc = &venc->mappings[0];
328    mc->submaps = 1;
329    mc->mux = av_malloc(sizeof(int) * venc->channels);
330    for (i = 0; i < venc->channels; i++)
331        mc->mux[i] = 0;
332    mc->floor = av_malloc(sizeof(int) * mc->submaps);
333    mc->residue = av_malloc(sizeof(int) * mc->submaps);
334    for (i = 0; i < mc->submaps; i++) {
335        mc->floor[i] = 0;
336        mc->residue[i] = 0;
337    }
338    mc->coupling_steps = venc->channels == 2 ? 1 : 0;
339    mc->magnitude = av_malloc(sizeof(int) * mc->coupling_steps);
340    mc->angle = av_malloc(sizeof(int) * mc->coupling_steps);
341    if (mc->coupling_steps) {
342        mc->magnitude[0] = 0;
343        mc->angle[0] = 1;
344    }
345
346    venc->nmodes = 1;
347    venc->modes = av_malloc(sizeof(vorbis_enc_mode) * venc->nmodes);
348
349    // single mode
350    venc->modes[0].blockflag = 0;
351    venc->modes[0].mapping = 0;
352
353    venc->have_saved = 0;
354    venc->saved = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
355    venc->samples = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]));
356    venc->floor = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
357    venc->coeffs = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
358
359    venc->win[0] = ff_vorbis_vwin[venc->log2_blocksize[0] - 6];
360    venc->win[1] = ff_vorbis_vwin[venc->log2_blocksize[1] - 6];
361
362    ff_mdct_init(&venc->mdct[0], venc->log2_blocksize[0], 0);
363    ff_mdct_init(&venc->mdct[1], venc->log2_blocksize[1], 0);
364}
365
366static void put_float(PutBitContext * pb, float f) {
367    int exp, mant;
368    uint32_t res = 0;
369    mant = (int)ldexp(frexp(f, &exp), 20);
370    exp += 788 - 20;
371    if (mant < 0) { res |= (1 << 31); mant = -mant; }
372    res |= mant | (exp << 21);
373    put_bits(pb, 32, res);
374}
375
376static void put_codebook_header(PutBitContext * pb, vorbis_enc_codebook * cb) {
377    int i;
378    int ordered = 0;
379
380    put_bits(pb, 24, 0x564342); //magic
381    put_bits(pb, 16, cb->ndimentions);
382    put_bits(pb, 24, cb->nentries);
383
384    for (i = 1; i < cb->nentries; i++)
385        if (cb->lens[i] < cb->lens[i-1]) break;
386    if (i == cb->nentries)
387        ordered = 1;
388
389    put_bits(pb, 1, ordered);
390    if (ordered) {
391        int len = cb->lens[0];
392        put_bits(pb, 5, len - 1);
393        i = 0;
394        while (i < cb->nentries) {
395            int j;
396            for (j = 0; j+i < cb->nentries; j++)
397                if (cb->lens[j+i] != len) break;
398            put_bits(pb, ilog(cb->nentries - i), j);
399            i += j;
400            len++;
401        }
402    } else {
403        int sparse = 0;
404        for (i = 0; i < cb->nentries; i++)
405            if (!cb->lens[i]) break;
406        if (i != cb->nentries)
407            sparse = 1;
408        put_bits(pb, 1, sparse);
409
410        for (i = 0; i < cb->nentries; i++) {
411            if (sparse) put_bits(pb, 1, !!cb->lens[i]);
412            if (cb->lens[i]) put_bits(pb, 5, cb->lens[i] - 1);
413        }
414    }
415
416    put_bits(pb, 4, cb->lookup);
417    if (cb->lookup) {
418        int tmp = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);
419        int bits = ilog(cb->quantlist[0]);
420
421        for (i = 1; i < tmp; i++)
422            bits = FFMAX(bits, ilog(cb->quantlist[i]));
423
424        put_float(pb, cb->min);
425        put_float(pb, cb->delta);
426
427        put_bits(pb, 4, bits - 1);
428        put_bits(pb, 1, cb->seq_p);
429
430        for (i = 0; i < tmp; i++)
431            put_bits(pb, bits, cb->quantlist[i]);
432    }
433}
434
435static void put_floor_header(PutBitContext * pb, vorbis_enc_floor * fc) {
436    int i;
437
438    put_bits(pb, 16, 1); // type, only floor1 is supported
439
440    put_bits(pb, 5, fc->partitions);
441
442    for (i = 0; i < fc->partitions; i++)
443        put_bits(pb, 4, fc->partition_to_class[i]);
444
445    for (i = 0; i < fc->nclasses; i++) {
446        int j, books;
447
448        put_bits(pb, 3, fc->classes[i].dim - 1);
449        put_bits(pb, 2, fc->classes[i].subclass);
450
451        if (fc->classes[i].subclass)
452            put_bits(pb, 8, fc->classes[i].masterbook);
453
454        books = (1 << fc->classes[i].subclass);
455
456        for (j = 0; j < books; j++)
457            put_bits(pb, 8, fc->classes[i].books[j] + 1);
458    }
459
460    put_bits(pb, 2, fc->multiplier - 1);
461    put_bits(pb, 4, fc->rangebits);
462
463    for (i = 2; i < fc->values; i++)
464        put_bits(pb, fc->rangebits, fc->list[i].x);
465}
466
467static void put_residue_header(PutBitContext * pb, vorbis_enc_residue * rc) {
468    int i;
469
470    put_bits(pb, 16, rc->type);
471
472    put_bits(pb, 24, rc->begin);
473    put_bits(pb, 24, rc->end);
474    put_bits(pb, 24, rc->partition_size - 1);
475    put_bits(pb, 6, rc->classifications - 1);
476    put_bits(pb, 8, rc->classbook);
477
478    for (i = 0; i < rc->classifications; i++) {
479        int j, tmp = 0;
480        for (j = 0; j < 8; j++)
481            tmp |= (rc->books[i][j] != -1) << j;
482
483        put_bits(pb, 3, tmp & 7);
484        put_bits(pb, 1, tmp > 7);
485
486        if (tmp > 7)
487            put_bits(pb, 5, tmp >> 3);
488    }
489
490    for (i = 0; i < rc->classifications; i++) {
491        int j;
492        for (j = 0; j < 8; j++)
493            if (rc->books[i][j] != -1)
494                put_bits(pb, 8, rc->books[i][j]);
495    }
496}
497
498static int put_main_header(vorbis_enc_context * venc, uint8_t ** out) {
499    int i;
500    PutBitContext pb;
501    uint8_t buffer[50000] = {0}, * p = buffer;
502    int buffer_len = sizeof buffer;
503    int len, hlens[3];
504
505    // identification header
506    init_put_bits(&pb, p, buffer_len);
507    put_bits(&pb, 8, 1); //magic
508    for (i = 0; "vorbis"[i]; i++)
509        put_bits(&pb, 8, "vorbis"[i]);
510    put_bits(&pb, 32, 0); // version
511    put_bits(&pb, 8, venc->channels);
512    put_bits(&pb, 32, venc->sample_rate);
513    put_bits(&pb, 32, 0); // bitrate
514    put_bits(&pb, 32, 0); // bitrate
515    put_bits(&pb, 32, 0); // bitrate
516    put_bits(&pb, 4, venc->log2_blocksize[0]);
517    put_bits(&pb, 4, venc->log2_blocksize[1]);
518    put_bits(&pb, 1, 1); // framing
519
520    flush_put_bits(&pb);
521    hlens[0] = (put_bits_count(&pb) + 7) / 8;
522    buffer_len -= hlens[0];
523    p += hlens[0];
524
525    // comment header
526    init_put_bits(&pb, p, buffer_len);
527    put_bits(&pb, 8, 3); //magic
528    for (i = 0; "vorbis"[i]; i++)
529        put_bits(&pb, 8, "vorbis"[i]);
530    put_bits(&pb, 32, 0); // vendor length TODO
531    put_bits(&pb, 32, 0); // amount of comments
532    put_bits(&pb, 1, 1); // framing
533
534    flush_put_bits(&pb);
535    hlens[1] = (put_bits_count(&pb) + 7) / 8;
536    buffer_len -= hlens[1];
537    p += hlens[1];
538
539    // setup header
540    init_put_bits(&pb, p, buffer_len);
541    put_bits(&pb, 8, 5); //magic
542    for (i = 0; "vorbis"[i]; i++)
543        put_bits(&pb, 8, "vorbis"[i]);
544
545    // codebooks
546    put_bits(&pb, 8, venc->ncodebooks - 1);
547    for (i = 0; i < venc->ncodebooks; i++)
548        put_codebook_header(&pb, &venc->codebooks[i]);
549
550    // time domain, reserved, zero
551    put_bits(&pb, 6, 0);
552    put_bits(&pb, 16, 0);
553
554    // floors
555    put_bits(&pb, 6, venc->nfloors - 1);
556    for (i = 0; i < venc->nfloors; i++)
557        put_floor_header(&pb, &venc->floors[i]);
558
559    // residues
560    put_bits(&pb, 6, venc->nresidues - 1);
561    for (i = 0; i < venc->nresidues; i++)
562        put_residue_header(&pb, &venc->residues[i]);
563
564    // mappings
565    put_bits(&pb, 6, venc->nmappings - 1);
566    for (i = 0; i < venc->nmappings; i++) {
567        vorbis_enc_mapping * mc = &venc->mappings[i];
568        int j;
569        put_bits(&pb, 16, 0); // mapping type
570
571        put_bits(&pb, 1, mc->submaps > 1);
572        if (mc->submaps > 1)
573            put_bits(&pb, 4, mc->submaps - 1);
574
575        put_bits(&pb, 1, !!mc->coupling_steps);
576        if (mc->coupling_steps) {
577            put_bits(&pb, 8, mc->coupling_steps - 1);
578            for (j = 0; j < mc->coupling_steps; j++) {
579                put_bits(&pb, ilog(venc->channels - 1), mc->magnitude[j]);
580                put_bits(&pb, ilog(venc->channels - 1), mc->angle[j]);
581            }
582        }
583
584        put_bits(&pb, 2, 0); // reserved
585
586        if (mc->submaps > 1)
587            for (j = 0; j < venc->channels; j++)
588                put_bits(&pb, 4, mc->mux[j]);
589
590        for (j = 0; j < mc->submaps; j++) {
591            put_bits(&pb, 8, 0); // reserved time configuration
592            put_bits(&pb, 8, mc->floor[j]);
593            put_bits(&pb, 8, mc->residue[j]);
594        }
595    }
596
597    // modes
598    put_bits(&pb, 6, venc->nmodes - 1);
599    for (i = 0; i < venc->nmodes; i++) {
600        put_bits(&pb, 1, venc->modes[i].blockflag);
601        put_bits(&pb, 16, 0); // reserved window type
602        put_bits(&pb, 16, 0); // reserved transform type
603        put_bits(&pb, 8, venc->modes[i].mapping);
604    }
605
606    put_bits(&pb, 1, 1); // framing
607
608    flush_put_bits(&pb);
609    hlens[2] = (put_bits_count(&pb) + 7) / 8;
610
611    len = hlens[0] + hlens[1] + hlens[2];
612    p = *out = av_mallocz(64 + len + len/255);
613
614    *p++ = 2;
615    p += av_xiphlacing(p, hlens[0]);
616    p += av_xiphlacing(p, hlens[1]);
617    buffer_len = 0;
618    for (i = 0; i < 3; i++) {
619        memcpy(p, buffer + buffer_len, hlens[i]);
620        p += hlens[i];
621        buffer_len += hlens[i];
622    }
623
624    return p - *out;
625}
626
627static float get_floor_average(vorbis_enc_floor * fc, float * coeffs, int i) {
628    int begin = fc->list[fc->list[FFMAX(i-1, 0)].sort].x;
629    int end   = fc->list[fc->list[FFMIN(i+1, fc->values - 1)].sort].x;
630    int j;
631    float average = 0;
632
633    for (j = begin; j < end; j++)
634        average += fabs(coeffs[j]);
635    return average / (end - begin);
636}
637
638static void floor_fit(vorbis_enc_context * venc, vorbis_enc_floor * fc, float * coeffs, uint_fast16_t * posts, int samples) {
639    int range = 255 / fc->multiplier + 1;
640    int i;
641    float tot_average = 0.;
642    float averages[fc->values];
643    for (i = 0; i < fc->values; i++){
644        averages[i] = get_floor_average(fc, coeffs, i);
645        tot_average += averages[i];
646    }
647    tot_average /= fc->values;
648    tot_average /= venc->quality;
649
650    for (i = 0; i < fc->values; i++) {
651        int position = fc->list[fc->list[i].sort].x;
652        float average = averages[i];
653        int j;
654
655        average *= pow(tot_average / average, 0.5) * pow(1.25, position/200.); // MAGIC!
656        for (j = 0; j < range - 1; j++)
657            if (ff_vorbis_floor1_inverse_db_table[j * fc->multiplier] > average) break;
658        posts[fc->list[i].sort] = j;
659    }
660}
661
662static int render_point(int x0, int y0, int x1, int y1, int x) {
663    return y0 +  (x - x0) * (y1 - y0) / (x1 - x0);
664}
665
666static void floor_encode(vorbis_enc_context * venc, vorbis_enc_floor * fc, PutBitContext * pb, uint_fast16_t * posts, float * floor, int samples) {
667    int range = 255 / fc->multiplier + 1;
668    int coded[fc->values]; // first 2 values are unused
669    int i, counter;
670
671    put_bits(pb, 1, 1); // non zero
672    put_bits(pb, ilog(range - 1), posts[0]);
673    put_bits(pb, ilog(range - 1), posts[1]);
674    coded[0] = coded[1] = 1;
675
676    for (i = 2; i < fc->values; i++) {
677        int predicted = render_point(fc->list[fc->list[i].low].x,
678                                     posts[fc->list[i].low],
679                                     fc->list[fc->list[i].high].x,
680                                     posts[fc->list[i].high],
681                                     fc->list[i].x);
682        int highroom = range - predicted;
683        int lowroom = predicted;
684        int room = FFMIN(highroom, lowroom);
685        if (predicted == posts[i]) {
686            coded[i] = 0; // must be used later as flag!
687            continue;
688        } else {
689            if (!coded[fc->list[i].low ]) coded[fc->list[i].low ] = -1;
690            if (!coded[fc->list[i].high]) coded[fc->list[i].high] = -1;
691        }
692        if (posts[i] > predicted) {
693            if (posts[i] - predicted > room)
694                coded[i] = posts[i] - predicted + lowroom;
695            else
696                coded[i] = (posts[i] - predicted) << 1;
697        } else {
698            if (predicted - posts[i] > room)
699                coded[i] = predicted - posts[i] + highroom - 1;
700            else
701                coded[i] = ((predicted - posts[i]) << 1) - 1;
702        }
703    }
704
705    counter = 2;
706    for (i = 0; i < fc->partitions; i++) {
707        vorbis_enc_floor_class * c = &fc->classes[fc->partition_to_class[i]];
708        int k, cval = 0, csub = 1<<c->subclass;
709        if (c->subclass) {
710            vorbis_enc_codebook * book = &venc->codebooks[c->masterbook];
711            int cshift = 0;
712            for (k = 0; k < c->dim; k++) {
713                int l;
714                for (l = 0; l < csub; l++) {
715                    int maxval = 1;
716                    if (c->books[l] != -1)
717                        maxval = venc->codebooks[c->books[l]].nentries;
718                    // coded could be -1, but this still works, cause that is 0
719                    if (coded[counter + k] < maxval) break;
720                }
721                assert(l != csub);
722                cval |= l << cshift;
723                cshift += c->subclass;
724            }
725            put_codeword(pb, book, cval);
726        }
727        for (k = 0; k < c->dim; k++) {
728            int book = c->books[cval & (csub-1)];
729            int entry = coded[counter++];
730            cval >>= c->subclass;
731            if (book == -1) continue;
732            if (entry == -1) entry = 0;
733            put_codeword(pb, &venc->codebooks[book], entry);
734        }
735    }
736
737    ff_vorbis_floor1_render_list(fc->list, fc->values, posts, coded, fc->multiplier, floor, samples);
738}
739
740static float * put_vector(vorbis_enc_codebook * book, PutBitContext * pb, float * num) {
741    int i, entry = -1;
742    float distance = FLT_MAX;
743    assert(book->dimentions);
744    for (i = 0; i < book->nentries; i++) {
745        float * vec = book->dimentions + i * book->ndimentions, d = book->pow2[i];
746        int j;
747        if (!book->lens[i]) continue;
748        for (j = 0; j < book->ndimentions; j++)
749            d -= vec[j] * num[j];
750        if (distance > d) {
751            entry = i;
752            distance = d;
753        }
754    }
755    put_codeword(pb, book, entry);
756    return &book->dimentions[entry * book->ndimentions];
757}
758
759static void residue_encode(vorbis_enc_context * venc, vorbis_enc_residue * rc, PutBitContext * pb, float * coeffs, int samples, int real_ch) {
760    int pass, i, j, p, k;
761    int psize = rc->partition_size;
762    int partitions = (rc->end - rc->begin) / psize;
763    int channels = (rc->type == 2) ? 1 : real_ch;
764    int classes[channels][partitions];
765    int classwords = venc->codebooks[rc->classbook].ndimentions;
766
767    assert(rc->type == 2);
768    assert(real_ch == 2);
769    for (p = 0; p < partitions; p++) {
770        float max1 = 0., max2 = 0.;
771        int s = rc->begin + p * psize;
772        for (k = s; k < s + psize; k += 2) {
773            max1 = FFMAX(max1, fabs(coeffs[          k / real_ch]));
774            max2 = FFMAX(max2, fabs(coeffs[samples + k / real_ch]));
775        }
776
777        for (i = 0; i < rc->classifications - 1; i++) {
778            if (max1 < rc->maxes[i][0] && max2 < rc->maxes[i][1]) break;
779        }
780        classes[0][p] = i;
781    }
782
783    for (pass = 0; pass < 8; pass++) {
784        p = 0;
785        while (p < partitions) {
786            if (pass == 0)
787                for (j = 0; j < channels; j++) {
788                    vorbis_enc_codebook * book = &venc->codebooks[rc->classbook];
789                    int entry = 0;
790                    for (i = 0; i < classwords; i++) {
791                        entry *= rc->classifications;
792                        entry += classes[j][p + i];
793                    }
794                    put_codeword(pb, book, entry);
795                }
796            for (i = 0; i < classwords && p < partitions; i++, p++) {
797                for (j = 0; j < channels; j++) {
798                    int nbook = rc->books[classes[j][p]][pass];
799                    vorbis_enc_codebook * book = &venc->codebooks[nbook];
800                    float * buf = coeffs + samples*j + rc->begin + p*psize;
801                    if (nbook == -1) continue;
802
803                    assert(rc->type == 0 || rc->type == 2);
804                    assert(!(psize % book->ndimentions));
805
806                    if (rc->type == 0) {
807                        for (k = 0; k < psize; k += book->ndimentions) {
808                            float * a = put_vector(book, pb, &buf[k]);
809                            int l;
810                            for (l = 0; l < book->ndimentions; l++)
811                                buf[k + l] -= a[l];
812                        }
813                    } else {
814                        int s = rc->begin + p * psize, a1, b1;
815                        a1 = (s % real_ch) * samples;
816                        b1 =  s / real_ch;
817                        s = real_ch * samples;
818                        for (k = 0; k < psize; k += book->ndimentions) {
819                            int dim, a2 = a1, b2 = b1;
820                            float vec[book->ndimentions], * pv = vec;
821                            for (dim = book->ndimentions; dim--; ) {
822                                *pv++ = coeffs[a2 + b2];
823                                if ((a2 += samples) == s) {
824                                    a2=0;
825                                    b2++;
826                                }
827                            }
828                            pv = put_vector(book, pb, vec);
829                            for (dim = book->ndimentions; dim--; ) {
830                                coeffs[a1 + b1] -= *pv++;
831                                if ((a1 += samples) == s) {
832                                    a1=0;
833                                    b1++;
834                                }
835                            }
836                        }
837                    }
838                }
839            }
840        }
841    }
842}
843
844static int apply_window_and_mdct(vorbis_enc_context * venc, signed short * audio, int samples) {
845    int i, j, channel;
846    const float * win = venc->win[0];
847    int window_len = 1 << (venc->log2_blocksize[0] - 1);
848    float n = (float)(1 << venc->log2_blocksize[0]) / 4.;
849    // FIXME use dsp
850
851    if (!venc->have_saved && !samples) return 0;
852
853    if (venc->have_saved) {
854        for (channel = 0; channel < venc->channels; channel++) {
855            memcpy(venc->samples + channel*window_len*2, venc->saved + channel*window_len, sizeof(float)*window_len);
856        }
857    } else {
858        for (channel = 0; channel < venc->channels; channel++) {
859            memset(venc->samples + channel*window_len*2, 0, sizeof(float)*window_len);
860        }
861    }
862
863    if (samples) {
864        for (channel = 0; channel < venc->channels; channel++) {
865            float * offset = venc->samples + channel*window_len*2 + window_len;
866            j = channel;
867            for (i = 0; i < samples; i++, j += venc->channels)
868                offset[i] = -audio[j] / 32768. / n * win[window_len - i - 1]; //FIXME find out why the sign has to be fliped
869        }
870    } else {
871        for (channel = 0; channel < venc->channels; channel++) {
872            memset(venc->samples + channel*window_len*2 + window_len, 0, sizeof(float)*window_len);
873        }
874    }
875
876    for (channel = 0; channel < venc->channels; channel++) {
877        ff_mdct_calc(&venc->mdct[0], venc->coeffs + channel*window_len, venc->samples + channel*window_len*2);
878    }
879
880    if (samples) {
881        for (channel = 0; channel < venc->channels; channel++) {
882            float * offset = venc->saved + channel*window_len;
883            j = channel;
884            for (i = 0; i < samples; i++, j += venc->channels)
885                offset[i] = -audio[j] / 32768. / n * win[i]; //FIXME find out why the sign has to be fliped
886        }
887        venc->have_saved = 1;
888    } else {
889        venc->have_saved = 0;
890    }
891    return 1;
892}
893
894static av_cold int vorbis_encode_init(AVCodecContext * avccontext)
895{
896    vorbis_enc_context * venc = avccontext->priv_data;
897
898    if (avccontext->channels != 2) {
899        av_log(avccontext, AV_LOG_ERROR, "Current FFmpeg Vorbis encoder only supports 2 channels.\n");
900        return -1;
901    }
902
903    create_vorbis_context(venc, avccontext);
904
905    if (avccontext->flags & CODEC_FLAG_QSCALE)
906        venc->quality = avccontext->global_quality / (float)FF_QP2LAMBDA / 10.;
907    else
908        venc->quality = 1.;
909    venc->quality *= venc->quality;
910
911    avccontext->extradata_size = put_main_header(venc, (uint8_t**)&avccontext->extradata);
912
913    avccontext->frame_size = 1 << (venc->log2_blocksize[0] - 1);
914
915    avccontext->coded_frame = avcodec_alloc_frame();
916    avccontext->coded_frame->key_frame = 1;
917
918    return 0;
919}
920
921static int vorbis_encode_frame(AVCodecContext * avccontext, unsigned char * packets, int buf_size, void *data)
922{
923    vorbis_enc_context * venc = avccontext->priv_data;
924    signed short * audio = data;
925    int samples = data ? avccontext->frame_size : 0;
926    vorbis_enc_mode * mode;
927    vorbis_enc_mapping * mapping;
928    PutBitContext pb;
929    int i;
930
931    if (!apply_window_and_mdct(venc, audio, samples)) return 0;
932    samples = 1 << (venc->log2_blocksize[0] - 1);
933
934    init_put_bits(&pb, packets, buf_size);
935
936    put_bits(&pb, 1, 0); // magic bit
937
938    put_bits(&pb, ilog(venc->nmodes - 1), 0); // 0 bits, the mode
939
940    mode = &venc->modes[0];
941    mapping = &venc->mappings[mode->mapping];
942    if (mode->blockflag) {
943        put_bits(&pb, 1, 0);
944        put_bits(&pb, 1, 0);
945    }
946
947    for (i = 0; i < venc->channels; i++) {
948        vorbis_enc_floor * fc = &venc->floors[mapping->floor[mapping->mux[i]]];
949        uint_fast16_t posts[fc->values];
950        floor_fit(venc, fc, &venc->coeffs[i * samples], posts, samples);
951        floor_encode(venc, fc, &pb, posts, &venc->floor[i * samples], samples);
952    }
953
954    for (i = 0; i < venc->channels * samples; i++) {
955        venc->coeffs[i] /= venc->floor[i];
956    }
957
958    for (i = 0; i < mapping->coupling_steps; i++) {
959        float * mag = venc->coeffs + mapping->magnitude[i] * samples;
960        float * ang = venc->coeffs + mapping->angle[i] * samples;
961        int j;
962        for (j = 0; j < samples; j++) {
963            float a = ang[j];
964            ang[j] -= mag[j];
965            if (mag[j] > 0) ang[j] = -ang[j];
966            if (ang[j] < 0) mag[j] = a;
967        }
968    }
969
970    residue_encode(venc, &venc->residues[mapping->residue[mapping->mux[0]]], &pb, venc->coeffs, samples, venc->channels);
971
972    avccontext->coded_frame->pts = venc->sample_count;
973    venc->sample_count += avccontext->frame_size;
974    flush_put_bits(&pb);
975    return (put_bits_count(&pb) + 7) / 8;
976}
977
978
979static av_cold int vorbis_encode_close(AVCodecContext * avccontext)
980{
981    vorbis_enc_context * venc = avccontext->priv_data;
982    int i;
983
984    if (venc->codebooks)
985        for (i = 0; i < venc->ncodebooks; i++) {
986            av_freep(&venc->codebooks[i].lens);
987            av_freep(&venc->codebooks[i].codewords);
988            av_freep(&venc->codebooks[i].quantlist);
989            av_freep(&venc->codebooks[i].dimentions);
990            av_freep(&venc->codebooks[i].pow2);
991        }
992    av_freep(&venc->codebooks);
993
994    if (venc->floors)
995        for (i = 0; i < venc->nfloors; i++) {
996            int j;
997            if (venc->floors[i].classes)
998                for (j = 0; j < venc->floors[i].nclasses; j++)
999                    av_freep(&venc->floors[i].classes[j].books);
1000            av_freep(&venc->floors[i].classes);
1001            av_freep(&venc->floors[i].partition_to_class);
1002            av_freep(&venc->floors[i].list);
1003        }
1004    av_freep(&venc->floors);
1005
1006    if (venc->residues)
1007        for (i = 0; i < venc->nresidues; i++) {
1008            av_freep(&venc->residues[i].books);
1009            av_freep(&venc->residues[i].maxes);
1010        }
1011    av_freep(&venc->residues);
1012
1013    if (venc->mappings)
1014        for (i = 0; i < venc->nmappings; i++) {
1015            av_freep(&venc->mappings[i].mux);
1016            av_freep(&venc->mappings[i].floor);
1017            av_freep(&venc->mappings[i].residue);
1018            av_freep(&venc->mappings[i].magnitude);
1019            av_freep(&venc->mappings[i].angle);
1020        }
1021    av_freep(&venc->mappings);
1022
1023    av_freep(&venc->modes);
1024
1025    av_freep(&venc->saved);
1026    av_freep(&venc->samples);
1027    av_freep(&venc->floor);
1028    av_freep(&venc->coeffs);
1029
1030    ff_mdct_end(&venc->mdct[0]);
1031    ff_mdct_end(&venc->mdct[1]);
1032
1033    av_freep(&avccontext->coded_frame);
1034    av_freep(&avccontext->extradata);
1035
1036    return 0 ;
1037}
1038
1039AVCodec vorbis_encoder = {
1040    "vorbis",
1041    CODEC_TYPE_AUDIO,
1042    CODEC_ID_VORBIS,
1043    sizeof(vorbis_enc_context),
1044    vorbis_encode_init,
1045    vorbis_encode_frame,
1046    vorbis_encode_close,
1047    .capabilities= CODEC_CAP_DELAY,
1048    .sample_fmts = (enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
1049    .long_name = NULL_IF_CONFIG_SMALL("Vorbis"),
1050};
1051