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