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