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