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