]> git.sesse.net Git - ffmpeg/blob - libavcodec/vorbis_enc.c
a629f2f5fad806538312342b99053078e9a01042
[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] = 9;
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 = 3;
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         fc->list[i].x = a[i - 2];
360     }
361     ready_floor(fc);
362
363     venc->nresidues = 1;
364     venc->residues = av_malloc(sizeof(residue_t) * venc->nresidues);
365
366     // single residue
367     rc = &venc->residues[0];
368     rc->type = 0;
369     rc->begin = 0;
370     rc->end = 1 << (venc->blocksize[0] - 1);
371     rc->partition_size = 64;
372     rc->classifications = 2;
373     rc->classbook = 1;
374     rc->books = av_malloc(sizeof(int[8]) * rc->classifications);
375     for (i = 0; i < rc->classifications; i++) {
376         int j;
377         for (j = 0; j < 8; j++) rc->books[i][j] = 2 + j;
378         rc->books[i][0] = rc->books[i][1] = rc->books[i][2] = rc->books[i][3] = -1;
379     }
380
381     venc->nmappings = 1;
382     venc->mappings = av_malloc(sizeof(mapping_t) * venc->nmappings);
383
384     // single mapping
385     mc = &venc->mappings[0];
386     mc->submaps = 1;
387     mc->mux = av_malloc(sizeof(int) * venc->channels);
388     for (i = 0; i < venc->channels; i++) mc->mux[i] = 0;
389     mc->floor = av_malloc(sizeof(int) * mc->submaps);
390     mc->residue = av_malloc(sizeof(int) * mc->submaps);
391     for (i = 0; i < mc->submaps; i++) {
392         mc->floor[i] = 0;
393         mc->residue[i] = 0;
394     }
395     mc->coupling_steps = venc->channels == 2 ? 1 : 0;
396     mc->magnitude = av_malloc(sizeof(int) * mc->coupling_steps);
397     mc->angle = av_malloc(sizeof(int) * mc->coupling_steps);
398     if (mc->coupling_steps) {
399         mc->magnitude[0] = 0;
400         mc->angle[0] = 1;
401     }
402
403     venc->nmodes = 1;
404     venc->modes = av_malloc(sizeof(vorbis_mode_t) * venc->nmodes);
405
406     // single mode
407     venc->modes[0].blockflag = 0;
408     venc->modes[0].mapping = 0;
409
410     venc->have_saved = 0;
411     venc->saved = av_malloc(sizeof(float) * venc->channels * (1 << venc->blocksize[1]) / 2);
412     venc->samples = av_malloc(sizeof(float) * venc->channels * (1 << venc->blocksize[1]));
413     venc->floor = av_malloc(sizeof(float) * venc->channels * (1 << venc->blocksize[1]) / 2);
414     venc->coeffs = av_malloc(sizeof(float) * venc->channels * (1 << venc->blocksize[1]) / 2);
415
416     {
417         const float *vwin[8]={ vwin64, vwin128, vwin256, vwin512, vwin1024, vwin2048, vwin4096, vwin8192 };
418         venc->win[0] = vwin[venc->blocksize[0] - 6];
419         venc->win[1] = vwin[venc->blocksize[1] - 6];
420     }
421
422     ff_mdct_init(&venc->mdct[0], venc->blocksize[0], 0);
423     ff_mdct_init(&venc->mdct[1], venc->blocksize[1], 0);
424 }
425
426 static void put_float(PutBitContext * pb, float f) {
427     int exp, mant;
428     uint32_t res = 0;
429     mant = (int)ldexp(frexp(f, &exp), 20);
430     exp += 788 - 20;
431     if (mant < 0) { res |= (1 << 31); mant = -mant; }
432     res |= mant | (exp << 21);
433     put_bits(pb, 32, res);
434 }
435
436 static void put_codebook_header(PutBitContext * pb, codebook_t * cb) {
437     int i;
438     int ordered = 0;
439
440     put_bits(pb, 24, 0x564342); //magic
441     put_bits(pb, 16, cb->ndimentions);
442     put_bits(pb, 24, cb->nentries);
443
444     for (i = 1; i < cb->nentries; i++) if (cb->entries[i].len < cb->entries[i-1].len) break;
445     if (i == cb->nentries) ordered = 1;
446
447     put_bits(pb, 1, ordered);
448     if (ordered) {
449         int len = cb->entries[0].len;
450         put_bits(pb, 5, len - 1);
451         i = 0;
452         while (i < cb->nentries) {
453             int j;
454             for (j = 0; j+i < cb->nentries; j++) if (cb->entries[j+i].len != len) break;
455             put_bits(pb, ilog(cb->nentries - i), j);
456             i += j;
457             len++;
458         }
459     } else {
460         int sparse = 0;
461         for (i = 0; i < cb->nentries; i++) if (!cb->entries[i].len) break;
462         if (i != cb->nentries) sparse = 1;
463         put_bits(pb, 1, sparse);
464
465         for (i = 0; i < cb->nentries; i++) {
466             if (sparse) put_bits(pb, 1, !!cb->entries[i].len);
467             if (cb->entries[i].len) put_bits(pb, 5, cb->entries[i].len - 1);
468         }
469     }
470
471     put_bits(pb, 4, cb->lookup);
472     if (cb->lookup) {
473         int tmp = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);
474         int bits = ilog(cb->quantlist[0]);
475
476         for (i = 1; i < tmp; i++) bits = FFMAX(bits, ilog(cb->quantlist[i]));
477
478         put_float(pb, cb->min);
479         put_float(pb, cb->delta);
480
481         put_bits(pb, 4, bits - 1);
482         put_bits(pb, 1, cb->seq_p);
483
484         for (i = 0; i < tmp; i++) put_bits(pb, bits, cb->quantlist[i]);
485     }
486 }
487
488 static void put_floor_header(PutBitContext * pb, floor_t * fc) {
489     int i;
490
491     put_bits(pb, 16, 1); // type, only floor1 is supported
492
493     put_bits(pb, 5, fc->partitions);
494
495     for (i = 0; i < fc->partitions; i++) put_bits(pb, 4, fc->partition_to_class[i]);
496
497     for (i = 0; i < fc->nclasses; i++) {
498         int j, books;
499
500         put_bits(pb, 3, fc->classes[i].dim - 1);
501         put_bits(pb, 2, fc->classes[i].subclass);
502
503         if (fc->classes[i].subclass) put_bits(pb, 8, fc->classes[i].masterbook);
504
505         books = (1 << fc->classes[i].subclass);
506
507         for (j = 0; j < books; j++) put_bits(pb, 8, fc->classes[i].books[j] + 1);
508     }
509
510     put_bits(pb, 2, fc->multiplier - 1);
511     put_bits(pb, 4, fc->rangebits);
512
513     for (i = 2; i < fc->values; i++) put_bits(pb, fc->rangebits, fc->list[i].x);
514 }
515
516 static void put_residue_header(PutBitContext * pb, residue_t * rc) {
517     int i;
518
519     put_bits(pb, 16, rc->type);
520
521     put_bits(pb, 24, rc->begin);
522     put_bits(pb, 24, rc->end);
523     put_bits(pb, 24, rc->partition_size - 1);
524     put_bits(pb, 6, rc->classifications - 1);
525     put_bits(pb, 8, rc->classbook);
526
527     for (i = 0; i < rc->classifications; i++) {
528         int j, tmp = 0;
529         for (j = 0; j < 8; j++) tmp |= (rc->books[i][j] != -1) << j;
530
531         put_bits(pb, 3, tmp & 7);
532         put_bits(pb, 1, tmp > 7);
533
534         if (tmp > 7) put_bits(pb, 5, tmp >> 3);
535     }
536
537     for (i = 0; i < rc->classifications; i++) {
538         int j;
539         for (j = 0; j < 8; j++)
540             if (rc->books[i][j] != -1)
541                 put_bits(pb, 8, rc->books[i][j]);
542     }
543 }
544
545 static int put_main_header(venc_context_t * venc, uint8_t ** out) {
546     int i;
547     PutBitContext pb;
548     uint8_t buffer[50000] = {0}, * p = buffer;
549     int buffer_len = sizeof buffer;
550     int len, hlens[3];
551
552     // identification header
553     init_put_bits(&pb, p, buffer_len);
554     put_bits(&pb, 8, 1); //magic
555     for (i = 0; "vorbis"[i]; i++) put_bits(&pb, 8, "vorbis"[i]);
556     put_bits(&pb, 32, 0); // version
557     put_bits(&pb, 8, venc->channels);
558     put_bits(&pb, 32, venc->sample_rate);
559     put_bits(&pb, 32, 0); // bitrate
560     put_bits(&pb, 32, 0); // bitrate
561     put_bits(&pb, 32, 0); // bitrate
562     put_bits(&pb, 4, venc->blocksize[0]);
563     put_bits(&pb, 4, venc->blocksize[1]);
564     put_bits(&pb, 1, 1); // framing
565
566     flush_put_bits(&pb);
567     hlens[0] = (put_bits_count(&pb) + 7) / 8;
568     buffer_len -= hlens[0];
569     p += hlens[0];
570
571     // comment header
572     init_put_bits(&pb, p, buffer_len);
573     put_bits(&pb, 8, 3); //magic
574     for (i = 0; "vorbis"[i]; i++) put_bits(&pb, 8, "vorbis"[i]);
575     put_bits(&pb, 32, 0); // vendor length TODO
576     put_bits(&pb, 32, 0); // amount of comments
577     put_bits(&pb, 1, 1); // framing
578
579     flush_put_bits(&pb);
580     hlens[1] = (put_bits_count(&pb) + 7) / 8;
581     buffer_len -= hlens[1];
582     p += hlens[1];
583
584     // setup header
585     init_put_bits(&pb, p, buffer_len);
586     put_bits(&pb, 8, 5); //magic
587     for (i = 0; "vorbis"[i]; i++) put_bits(&pb, 8, "vorbis"[i]);
588
589     // codebooks
590     put_bits(&pb, 8, venc->ncodebooks - 1);
591     for (i = 0; i < venc->ncodebooks; i++) put_codebook_header(&pb, &venc->codebooks[i]);
592
593     // time domain, reserved, zero
594     put_bits(&pb, 6, 0);
595     put_bits(&pb, 16, 0);
596
597     // floors
598     put_bits(&pb, 6, venc->nfloors - 1);
599     for (i = 0; i < venc->nfloors; i++) put_floor_header(&pb, &venc->floors[i]);
600
601     // residues
602     put_bits(&pb, 6, venc->nresidues - 1);
603     for (i = 0; i < venc->nresidues; i++) put_residue_header(&pb, &venc->residues[i]);
604
605     // mappings
606     put_bits(&pb, 6, venc->nmappings - 1);
607     for (i = 0; i < venc->nmappings; i++) {
608         mapping_t * mc = &venc->mappings[i];
609         int j;
610         put_bits(&pb, 16, 0); // mapping type
611
612         put_bits(&pb, 1, mc->submaps > 1);
613         if (mc->submaps > 1) put_bits(&pb, 4, mc->submaps - 1);
614
615         put_bits(&pb, 1, !!mc->coupling_steps);
616         if (mc->coupling_steps) {
617             put_bits(&pb, 8, mc->coupling_steps - 1);
618             for (j = 0; j < mc->coupling_steps; j++) {
619                 put_bits(&pb, ilog(venc->channels - 1), mc->magnitude[j]);
620                 put_bits(&pb, ilog(venc->channels - 1), mc->angle[j]);
621             }
622         }
623
624         put_bits(&pb, 2, 0); // reserved
625
626         if (mc->submaps > 1) for (j = 0; j < venc->channels; j++) put_bits(&pb, 4, mc->mux[j]);
627
628         for (j = 0; j < mc->submaps; j++) {
629             put_bits(&pb, 8, 0); // reserved time configuration
630             put_bits(&pb, 8, mc->floor[j]);
631             put_bits(&pb, 8, mc->residue[j]);
632         }
633     }
634
635     // modes
636     put_bits(&pb, 6, venc->nmodes - 1);
637     for (i = 0; i < venc->nmodes; i++) {
638         put_bits(&pb, 1, venc->modes[i].blockflag);
639         put_bits(&pb, 16, 0); // reserved window type
640         put_bits(&pb, 16, 0); // reserved transform type
641         put_bits(&pb, 8, venc->modes[i].mapping);
642     }
643
644     put_bits(&pb, 1, 1); // framing
645
646     flush_put_bits(&pb);
647     hlens[2] = (put_bits_count(&pb) + 7) / 8;
648
649     len = hlens[0] + hlens[1] + hlens[2];
650     p = *out = av_mallocz(64 + len + len/255);
651
652     *p++ = 2;
653     p += av_xiphlacing(p, hlens[0]);
654     p += av_xiphlacing(p, hlens[1]);
655     buffer_len = 0;
656     for (i = 0; i < 3; i++) {
657         memcpy(p, buffer + buffer_len, hlens[i]);
658         p += hlens[i];
659         buffer_len += hlens[i];
660     }
661
662     return p - *out;
663 }
664
665 static void floor_fit(venc_context_t * venc, floor_t * fc, float * coeffs, int * posts, int samples) {
666     int range = 255 / fc->multiplier + 1;
667     int i;
668     for (i = 0; i < fc->values; i++) {
669         int position = fc->list[fc->list[i].sort].x;
670         int begin = fc->list[fc->list[FFMAX(i-1, 0)].sort].x;
671         int end   = fc->list[fc->list[FFMIN(i+1, fc->values - 1)].sort].x;
672         int j;
673         float average = 0;
674         begin = (position + begin) / 2;
675         end   = (position + end  ) / 2;
676
677         assert(end <= samples);
678         for (j = begin; j < end; j++) average += fabs(coeffs[j]);
679         average /= end - begin;
680         average /= 32; // MAGIC!
681         for (j = 0; j < range - 1; j++) if (floor1_inverse_db_table[j * fc->multiplier] > average) break;
682         posts[fc->list[i].sort] = j;
683     }
684 }
685
686 static int render_point(int x0, int y0, int x1, int y1, int x) {
687     return y0 +  (x - x0) * (y1 - y0) / (x1 - x0);
688 }
689
690 static void render_line(int x0, int y0, int x1, int y1, float * buf, int n) {
691     int dy = y1 - y0;
692     int adx = x1 - x0;
693     int ady = FFMAX(dy, -dy);
694     int base = dy / adx;
695     int x = x0;
696     int y = y0;
697     int err = 0;
698     int sy;
699     if (dy < 0) sy = base - 1;
700     else sy = base + 1;
701     ady = ady - FFMAX(base, -base) * adx;
702     if (x >= n) return;
703     buf[x] = floor1_inverse_db_table[y];
704     for (x = x0 + 1; x < x1; x++) {
705         if (x >= n) return;
706         err += ady;
707         if (err >= adx) {
708             err -= adx;
709             y += sy;
710         } else {
711             y += base;
712         }
713         buf[x] = floor1_inverse_db_table[y];
714     }
715 }
716
717 static void floor_encode(venc_context_t * venc, floor_t * fc, PutBitContext * pb, int * posts, float * floor, int samples) {
718     int range = 255 / fc->multiplier + 1;
719     int coded[fc->values]; // first 2 values are unused
720     int i, counter;
721     int lx, ly;
722
723     put_bits(pb, 1, 1); // non zero
724     put_bits(pb, ilog(range - 1), posts[0]);
725     put_bits(pb, ilog(range - 1), posts[1]);
726
727     for (i = 2; i < fc->values; i++) {
728         int predicted = render_point(fc->list[fc->list[i].low].x,
729                                      posts[fc->list[i].low],
730                                      fc->list[fc->list[i].high].x,
731                                      posts[fc->list[i].high],
732                                      fc->list[i].x);
733         int highroom = range - predicted;
734         int lowroom = predicted;
735         int room = FFMIN(highroom, lowroom);
736         if (predicted == posts[i]) {
737             coded[i] = 0; // must be used later as flag!
738             continue;
739         } else {
740             if (!coded[fc->list[i].low]) coded[fc->list[i].low] = -1;
741             if (!coded[fc->list[i].high]) coded[fc->list[i].high] = -1;
742         }
743         if (posts[i] > predicted) {
744             if (posts[i] - predicted > room) coded[i] = posts[i] - predicted + lowroom;
745             else coded[i] = (posts[i] - predicted) << 1;
746         } else {
747             if (predicted - posts[i] > room) coded[i] = predicted - posts[i] + highroom - 1;
748             else coded[i] = ((predicted - posts[i]) << 1) - 1;
749         }
750     }
751
752     counter = 2;
753     for (i = 0; i < fc->partitions; i++) {
754         floor_class_t * c = &fc->classes[fc->partition_to_class[i]];
755         int k, cval = 0, csub = 1<<c->subclass;
756         if (c->subclass) {
757             codebook_t * book = &venc->codebooks[c->masterbook];
758             int cshift = 0;
759             for (k = 0; k < c->dim; k++) {
760                 int l;
761                 for (l = 0; l < csub; l++) {
762                     int maxval = 1;
763                     if (c->books[l] != -1) maxval = venc->codebooks[c->books[l]].nentries;
764                     // coded could be -1, but this still works, cause thats 0
765                     if (coded[counter + k] < maxval) break;
766                 }
767                 assert(l != csub);
768                 cval |= l << cshift;
769                 cshift += c->subclass;
770             }
771             assert(cval < book->nentries);
772             put_bits(pb, book->entries[cval].len, book->entries[cval].codeword);
773         }
774         for (k = 0; k < c->dim; k++) {
775             codebook_t * book = &venc->codebooks[c->books[cval & (csub-1)]];
776             int entry = coded[counter++];
777             cval >>= c->subclass;
778             if (entry == -1) entry = 0;
779             assert(entry < book->nentries);
780             assert(entry >= 0);
781             put_bits(pb, book->entries[entry].len, book->entries[entry].codeword);
782         }
783     }
784
785     lx = 0;
786     ly = posts[0] * fc->multiplier; // sorted 0 is still 0
787     coded[0] = coded[1] = 1;
788     for (i = 1; i < fc->values; i++) {
789         int pos = fc->list[i].sort;
790         if (coded[pos]) {
791             render_line(lx, ly, fc->list[pos].x, posts[pos] * fc->multiplier, floor, samples);
792             lx = fc->list[pos].x;
793             ly = posts[pos] * fc->multiplier;
794         }
795         if (lx >= samples) break;
796     }
797     if (lx < samples) render_line(lx, ly, samples, ly, floor, samples);
798 }
799
800 static float * put_vector(codebook_t * book, PutBitContext * pb, float * num) {
801     int i;
802     int entry = -1;
803     float distance = 0;
804     assert(book->dimentions);
805     for (i = 0; i < book->nentries; i++) {
806         float d = 0.;
807         int j;
808         for (j = 0; j < book->ndimentions; j++) {
809             float a = (book->dimentions[i * book->ndimentions + j] - num[j]);
810             d += a*a;
811         }
812         if (entry == -1 || distance > d) {
813             entry = i;
814             distance = d;
815         }
816     }
817     put_bits(pb, book->entries[entry].len, book->entries[entry].codeword);
818     return &book->dimentions[entry * book->ndimentions];
819 }
820
821 static void residue_encode(venc_context_t * venc, residue_t * rc, PutBitContext * pb, float * coeffs, int samples, int channels) {
822     int pass, i, j, p, k;
823     int psize = rc->partition_size;
824     int partitions = (rc->end - rc->begin) / psize;
825     int classes[channels][partitions];
826     int classwords = venc->codebooks[rc->classbook].ndimentions;
827     int real_ch = channels;
828
829     if (rc->type == 2) channels = 1;
830
831     for (pass = 0; pass < 8; pass++) {
832         p = 0;
833         while (p < partitions) {
834             if (pass == 0) for (j = 0; j < channels; j++) {
835                 codebook_t * book = &venc->codebooks[rc->classbook];
836                 int entry = 0;
837                 put_bits(pb, book->entries[entry].len, book->entries[entry].codeword);
838                 for (i = classwords; i--; ) {
839                     classes[j][p + i] = entry % rc->classifications;
840                     entry /= rc->classifications;
841                 }
842             }
843             for (i = 0; i < classwords && p < partitions; i++, p++) {
844                 for (j = 0; j < channels; j++) {
845                     int nbook = rc->books[classes[j][p]][pass];
846                     codebook_t * book = &venc->codebooks[nbook];
847                     float * buf = coeffs + samples*j + rc->begin + p*psize;
848                     if (nbook == -1) continue;
849
850                     assert(rc->type == 0 || rc->type == 2);
851                     assert(!(psize % book->ndimentions));
852
853                     if (rc->type == 0) {
854                         for (k = 0; k < psize; k += book->ndimentions) {
855                             float * a = put_vector(book, pb, &buf[k]);
856                             int l;
857                             for (l = 0; l < book->ndimentions; l++) buf[k + l] -= a[l];
858                         }
859                     } else {
860                         for (k = 0; k < psize; k += book->ndimentions) {
861                             int dim = book->ndimentions, s = rc->begin + p * psize, l;
862                             float vec[dim], * a = vec;
863                             for (l = s + k; l < s + k + dim; l++)
864                                 *a++ = coeffs[(l % real_ch) * samples + l / real_ch];
865                             a = put_vector(book, pb, vec);
866                             for (l = s + k; l < s + k + dim; l++)
867                                 coeffs[(l % real_ch) * samples + l / real_ch] -= *a++;
868                         }
869                     }
870                 }
871             }
872         }
873     }
874 }
875
876 static int window(venc_context_t * venc, signed short * audio, int samples) {
877     int i, j, channel;
878     const float * win = venc->win[0];
879     int window_len = 1 << (venc->blocksize[0] - 1);
880     float n = (float)(1 << venc->blocksize[0]) / 4.;
881     // FIXME use dsp
882
883     if (!venc->have_saved && !samples) return 0;
884
885     if (venc->have_saved) {
886         for (channel = 0; channel < venc->channels; channel++) {
887             memcpy(venc->samples + channel*window_len*2, venc->saved + channel*window_len, sizeof(float)*window_len);
888         }
889     } else {
890         for (channel = 0; channel < venc->channels; channel++) {
891             memset(venc->samples + channel*window_len*2, 0, sizeof(float)*window_len);
892         }
893     }
894
895     if (samples) {
896         for (channel = 0; channel < venc->channels; channel++) {
897             float * offset = venc->samples + channel*window_len*2 + window_len;
898             j = channel;
899             for (i = 0; i < samples; i++, j += venc->channels)
900                 offset[i] = audio[j] / 32768. / n * win[window_len - i - 1];
901         }
902     } else {
903         for (channel = 0; channel < venc->channels; channel++) {
904             memset(venc->samples + channel*window_len*2 + window_len, 0, sizeof(float)*window_len);
905         }
906     }
907
908     for (channel = 0; channel < venc->channels; channel++) {
909         ff_mdct_calc(&venc->mdct[0], venc->coeffs + channel*window_len, venc->samples + channel*window_len*2, venc->floor/*tmp*/);
910     }
911
912     if (samples) {
913         for (channel = 0; channel < venc->channels; channel++) {
914             float * offset = venc->saved + channel*window_len;
915             j = channel;
916             for (i = 0; i < samples; i++, j += venc->channels)
917                 offset[i] = audio[j] / 32768. / n * win[i];
918         }
919         venc->have_saved = 1;
920     } else {
921         venc->have_saved = 0;
922     }
923     return 1;
924 }
925
926 static int vorbis_encode_init(AVCodecContext * avccontext)
927 {
928     venc_context_t * venc = avccontext->priv_data;
929
930     create_vorbis_context(venc, avccontext);
931
932     //if (avccontext->flags & CODEC_FLAG_QSCALE) avccontext->global_quality / (float)FF_QP2LAMBDA); else avccontext->bit_rate;
933     //if(avccontext->cutoff > 0) cfreq = avccontext->cutoff / 1000.0;
934
935     avccontext->extradata_size = put_main_header(venc, (uint8_t**)&avccontext->extradata);
936
937     avccontext->frame_size = 1 << (venc->blocksize[0] - 1);
938
939     avccontext->coded_frame = avcodec_alloc_frame();
940     avccontext->coded_frame->key_frame = 1;
941
942     return 0;
943 }
944
945 static int vorbis_encode_frame(AVCodecContext * avccontext, unsigned char * packets, int buf_size, void *data)
946 {
947     venc_context_t * venc = avccontext->priv_data;
948     signed short * audio = data;
949     int samples = data ? avccontext->frame_size : 0;
950     vorbis_mode_t * mode;
951     mapping_t * mapping;
952     PutBitContext pb;
953     int i;
954
955     if (!window(venc, audio, samples)) return 0;
956     samples = 1 << (venc->blocksize[0] - 1);
957
958     init_put_bits(&pb, packets, buf_size);
959
960     put_bits(&pb, 1, 0); // magic bit
961
962     put_bits(&pb, ilog(venc->nmodes - 1), 0); // 0 bits, the mode
963
964     mode = &venc->modes[0];
965     mapping = &venc->mappings[mode->mapping];
966     if (mode->blockflag) {
967         put_bits(&pb, 1, 0);
968         put_bits(&pb, 1, 0);
969     }
970
971     for (i = 0; i < venc->channels; i++) {
972         floor_t * fc = &venc->floors[mapping->floor[mapping->mux[i]]];
973         int posts[fc->values];
974         floor_fit(venc, fc, &venc->coeffs[i * samples], posts, samples);
975         floor_encode(venc, fc, &pb, posts, &venc->floor[i * samples], samples);
976     }
977
978     for (i = 0; i < venc->channels; i++) {
979         int j;
980         for (j = 0; j < samples; j++) {
981             venc->coeffs[i * samples + j] /= venc->floor[i * samples + j];
982         }
983     }
984
985     for (i = 0; i < mapping->coupling_steps; i++) {
986         float * mag = venc->coeffs + mapping->magnitude[i] * samples;
987         float * ang = venc->coeffs + mapping->angle[i] * samples;
988         int j;
989         for (j = 0; j < samples; j++) {
990             float m = mag[j];
991             float a = ang[j];
992             if (m > 0) {
993                 ang[j] = m - a;
994                 if (a > m) mag[j] = a;
995                 else mag[j] = m;
996             } else {
997                 ang[j] = a - m;
998                 if (a > m) mag[j] = m;
999                 else mag[j] = a;
1000             }
1001         }
1002     }
1003
1004     residue_encode(venc, &venc->residues[mapping->residue[mapping->mux[0]]], &pb, venc->coeffs, samples, venc->channels);
1005
1006     return (put_bits_count(&pb) + 7) / 8;
1007 }
1008
1009
1010 static int vorbis_encode_close(AVCodecContext * avccontext)
1011 {
1012     venc_context_t * venc = avccontext->priv_data;
1013     int i;
1014
1015     if (venc->codebooks) for (i = 0; i < venc->ncodebooks; i++) {
1016         av_freep(&venc->codebooks[i].entries);
1017         av_freep(&venc->codebooks[i].quantlist);
1018         av_freep(&venc->codebooks[i].dimentions);
1019     }
1020     av_freep(&venc->codebooks);
1021
1022     if (venc->floors) for (i = 0; i < venc->nfloors; i++) {
1023         int j;
1024         av_freep(&venc->floors[i].classes);
1025         if (venc->floors[i].classes)
1026             for (j = 0; j < venc->floors[i].nclasses; j++)
1027                 av_freep(&venc->floors[i].classes[j].books);
1028         av_freep(&venc->floors[i].partition_to_class);
1029         av_freep(&venc->floors[i].list);
1030     }
1031     av_freep(&venc->floors);
1032
1033     if (venc->residues) for (i = 0; i < venc->nresidues; i++) {
1034         av_freep(&venc->residues[i].books);
1035     }
1036     av_freep(&venc->residues);
1037
1038     if (venc->mappings) for (i = 0; i < venc->nmappings; i++) {
1039         av_freep(&venc->mappings[i].mux);
1040         av_freep(&venc->mappings[i].floor);
1041         av_freep(&venc->mappings[i].residue);
1042     }
1043     av_freep(&venc->mappings);
1044
1045     av_freep(&venc->modes);
1046
1047     av_freep(&venc->saved);
1048     av_freep(&venc->samples);
1049     av_freep(&venc->floor);
1050     av_freep(&venc->coeffs);
1051
1052     ff_mdct_end(&venc->mdct[0]);
1053     ff_mdct_end(&venc->mdct[1]);
1054
1055     av_freep(&avccontext->coded_frame);
1056     av_freep(&avccontext->extradata);
1057
1058     return 0 ;
1059 }
1060
1061 AVCodec vorbis_encoder = {
1062     "vorbis",
1063     CODEC_TYPE_AUDIO,
1064     CODEC_ID_VORBIS,
1065     sizeof(venc_context_t),
1066     vorbis_encode_init,
1067     vorbis_encode_frame,
1068     vorbis_encode_close,
1069     .capabilities= CODEC_CAP_DELAY,
1070 };