]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavcodec/vorbis_enc.c
Original Commit: r72 | ods15 | 2006-09-28 21:00:47 +0300 (Thu, 28 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     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                 av_log(NULL, AV_LOG_ERROR, "%d %d %d %d\n", venc->channels, ilog(venc->channels - 1), mc->magnitude[j], mc->angle[j]);
620                 put_bits(&pb, ilog(venc->channels - 1), mc->magnitude[j]);
621                 put_bits(&pb, ilog(venc->channels - 1), mc->angle[j]);
622             }
623         }
624
625         put_bits(&pb, 2, 0); // reserved
626
627         if (mc->submaps > 1) for (j = 0; j < venc->channels; j++) put_bits(&pb, 4, mc->mux[j]);
628
629         for (j = 0; j < mc->submaps; j++) {
630             put_bits(&pb, 8, 0); // reserved time configuration
631             put_bits(&pb, 8, mc->floor[j]);
632             put_bits(&pb, 8, mc->residue[j]);
633         }
634     }
635
636     // modes
637     put_bits(&pb, 6, venc->nmodes - 1);
638     for (i = 0; i < venc->nmodes; i++) {
639         put_bits(&pb, 1, venc->modes[i].blockflag);
640         put_bits(&pb, 16, 0); // reserved window type
641         put_bits(&pb, 16, 0); // reserved transform type
642         put_bits(&pb, 8, venc->modes[i].mapping);
643     }
644
645     put_bits(&pb, 1, 1); // framing
646
647     flush_put_bits(&pb);
648     hlens[2] = (put_bits_count(&pb) + 7) / 8;
649
650     len = hlens[0] + hlens[1] + hlens[2];
651     p = *out = av_mallocz(64 + len + len/255);
652
653     *p++ = 2;
654     p += av_xiphlacing(p, hlens[0]);
655     p += av_xiphlacing(p, hlens[1]);
656     buffer_len = 0;
657     for (i = 0; i < 3; i++) {
658         memcpy(p, buffer + buffer_len, hlens[i]);
659         p += hlens[i];
660         buffer_len += hlens[i];
661     }
662
663     return p - *out;
664 }
665
666 static void floor_fit(venc_context_t * venc, floor_t * fc, float * coeffs, int * posts, int samples) {
667     int range = 255 / fc->multiplier + 1;
668     int i;
669     for (i = 0; i < fc->values; i++) {
670         int position = fc->list[fc->list[i].sort].x;
671         int begin = fc->list[fc->list[FFMAX(i-1, 0)].sort].x;
672         int end   = fc->list[fc->list[FFMIN(i+1, fc->values - 1)].sort].x;
673         int j;
674         float average = 0;
675         begin = (position + begin) / 2;
676         end   = (position + end  ) / 2;
677
678         assert(end <= samples);
679         for (j = begin; j < end; j++) average += fabs(coeffs[j]);
680         average /= end - begin;
681         average /= 32; // MAGIC!
682         for (j = 0; j < range - 1; j++) if (floor1_inverse_db_table[j * fc->multiplier] > average) break;
683         posts[fc->list[i].sort] = j;
684     }
685 }
686
687 static int render_point(int x0, int y0, int x1, int y1, int x) {
688     return y0 +  (x - x0) * (y1 - y0) / (x1 - x0);
689 }
690
691 static void render_line(int x0, int y0, int x1, int y1, float * buf, int n) {
692     int dy = y1 - y0;
693     int adx = x1 - x0;
694     int ady = FFMAX(dy, -dy);
695     int base = dy / adx;
696     int x = x0;
697     int y = y0;
698     int err = 0;
699     int sy;
700     if (dy < 0) sy = base - 1;
701     else sy = base + 1;
702     ady = ady - FFMAX(base, -base) * adx;
703     if (x >= n) return;
704     buf[x] = floor1_inverse_db_table[y];
705     for (x = x0 + 1; x < x1; x++) {
706         if (x >= n) return;
707         err += ady;
708         if (err >= adx) {
709             err -= adx;
710             y += sy;
711         } else {
712             y += base;
713         }
714         buf[x] = floor1_inverse_db_table[y];
715     }
716 }
717
718 static void floor_encode(venc_context_t * venc, floor_t * fc, PutBitContext * pb, int * posts, float * floor, int samples) {
719     int range = 255 / fc->multiplier + 1;
720     int coded[fc->values]; // first 2 values are unused
721     int i, counter;
722     int lx, ly;
723
724     put_bits(pb, 1, 1); // non zero
725     put_bits(pb, ilog(range - 1), posts[0]);
726     put_bits(pb, ilog(range - 1), posts[1]);
727
728     for (i = 2; i < fc->values; i++) {
729         int predicted = render_point(fc->list[fc->list[i].low].x,
730                                      posts[fc->list[i].low],
731                                      fc->list[fc->list[i].high].x,
732                                      posts[fc->list[i].high],
733                                      fc->list[i].x);
734         int highroom = range - predicted;
735         int lowroom = predicted;
736         int room = FFMIN(highroom, lowroom);
737         if (predicted == posts[i]) {
738             coded[i] = 0; // must be used later as flag!
739             continue;
740         } else {
741             if (!coded[fc->list[i].low]) coded[fc->list[i].low] = -1;
742             if (!coded[fc->list[i].high]) coded[fc->list[i].high] = -1;
743         }
744         if (posts[i] > predicted) {
745             if (posts[i] - predicted > room) coded[i] = posts[i] - predicted + lowroom;
746             else coded[i] = (posts[i] - predicted) << 1;
747         } else {
748             if (predicted - posts[i] > room) coded[i] = predicted - posts[i] + highroom - 1;
749             else coded[i] = ((predicted - posts[i]) << 1) - 1;
750         }
751     }
752
753     counter = 2;
754     for (i = 0; i < fc->partitions; i++) {
755         floor_class_t * c = &fc->classes[fc->partition_to_class[i]];
756         codebook_t * book = &venc->codebooks[c->books[0]];
757         int k;
758         assert(!c->subclass);
759         for (k = 0; k < c->dim; k++) {
760             int entry = coded[counter++];
761             if (entry == -1) entry = 0;
762             assert(entry < book->nentries);
763             assert(entry >= 0);
764             put_bits(pb, book->entries[entry].len, book->entries[entry].codeword);
765         }
766     }
767
768     lx = 0;
769     ly = posts[0] * fc->multiplier; // sorted 0 is still 0
770     coded[0] = coded[1] = 1;
771     for (i = 1; i < fc->values; i++) {
772         int pos = fc->list[i].sort;
773         if (coded[pos]) {
774             render_line(lx, ly, fc->list[pos].x, posts[pos] * fc->multiplier, floor, samples);
775             lx = fc->list[pos].x;
776             ly = posts[pos] * fc->multiplier;
777         }
778         if (lx >= samples) break;
779     }
780     if (lx < samples) render_line(lx, ly, samples, ly, floor, samples);
781 }
782
783 static float * put_vector(codebook_t * book, PutBitContext * pb, float * num) {
784     int i;
785     int entry = -1;
786     float distance = 0;
787     assert(book->dimentions);
788     for (i = 0; i < book->nentries; i++) {
789         float d = 0.;
790         int j;
791         for (j = 0; j < book->ndimentions; j++) {
792             float a = (book->dimentions[i * book->ndimentions + j] - num[j]);
793             d += a*a;
794         }
795         if (entry == -1 || distance > d) {
796             entry = i;
797             distance = d;
798         }
799     }
800     put_bits(pb, book->entries[entry].len, book->entries[entry].codeword);
801     return &book->dimentions[entry * book->ndimentions];
802 }
803
804 static void residue_encode(venc_context_t * venc, residue_t * rc, PutBitContext * pb, float * coeffs, int samples, int channels) {
805     int pass, i, j, p, k;
806     int psize = rc->partition_size;
807     int partitions = (rc->end - rc->begin) / psize;
808     int classes[channels][partitions];
809     int classwords = venc->codebooks[rc->classbook].ndimentions;
810     int real_ch = channels;
811
812     if (rc->type == 2) channels = 1;
813
814     for (pass = 0; pass < 8; pass++) {
815         p = 0;
816         while (p < partitions) {
817             if (pass == 0) for (j = 0; j < channels; j++) {
818                 codebook_t * book = &venc->codebooks[rc->classbook];
819                 int entry = 0;
820                 put_bits(pb, book->entries[entry].len, book->entries[entry].codeword);
821                 for (i = classwords; i--; ) {
822                     classes[j][p + i] = entry % rc->classifications;
823                     entry /= rc->classifications;
824                 }
825             }
826             for (i = 0; i < classwords && p < partitions; i++, p++) {
827                 for (j = 0; j < channels; j++) {
828                     int nbook = rc->books[classes[j][p]][pass];
829                     codebook_t * book = &venc->codebooks[nbook];
830                     float * buf = coeffs + samples*j + rc->begin + p*psize;
831                     if (nbook == -1) continue;
832
833                     assert(rc->type == 0 || rc->type == 2);
834                     assert(!(psize % book->ndimentions));
835
836                     if (rc->type == 0) {
837                         for (k = 0; k < psize; k += book->ndimentions) {
838                             float * a = put_vector(book, pb, &buf[k]);
839                             int l;
840                             for (l = 0; l < book->ndimentions; l++) buf[k + l] -= a[l];
841                         }
842                     } else {
843                         for (k = 0; k < psize; k += book->ndimentions) {
844                             int dim = book->ndimentions, s = rc->begin + p * psize, l;
845                             float vec[dim], * pvec = vec, * a;
846                             for (l = s + k; l < s + k + dim; l++)
847                                 *pvec++ = coeffs[(l % real_ch) * samples + l / real_ch];
848                             a = put_vector(book, pb, vec);
849                             for (l = s + k; l < s + k + dim; l++)
850                                 coeffs[(l % real_ch) * samples + l / real_ch] -= *a++;
851                         }
852                     }
853                 }
854             }
855         }
856     }
857 }
858
859 static int window(venc_context_t * venc, signed short * audio, int samples) {
860     int i, j, channel;
861     const float * win = venc->win[0];
862     int window_len = 1 << (venc->blocksize[0] - 1);
863     float n = (float)(1 << venc->blocksize[0]) / 4.;
864     // FIXME use dsp
865
866     if (!venc->have_saved && !samples) return 0;
867
868     if (venc->have_saved) {
869         for (channel = 0; channel < venc->channels; channel++) {
870             memcpy(venc->samples + channel*window_len*2, venc->saved + channel*window_len, sizeof(float)*window_len);
871         }
872     } else {
873         for (channel = 0; channel < venc->channels; channel++) {
874             memset(venc->samples + channel*window_len*2, 0, sizeof(float)*window_len);
875         }
876     }
877
878     if (samples) {
879         for (channel = 0; channel < venc->channels; channel++) {
880             float * offset = venc->samples + channel*window_len*2 + window_len;
881             j = channel;
882             for (i = 0; i < samples; i++, j += venc->channels)
883                 offset[i] = audio[j] / 32768. / n * win[window_len - i - 1];
884         }
885     } else {
886         for (channel = 0; channel < venc->channels; channel++) {
887             memset(venc->samples + channel*window_len*2 + window_len, 0, sizeof(float)*window_len);
888         }
889     }
890
891     for (channel = 0; channel < venc->channels; channel++) {
892         ff_mdct_calc(&venc->mdct[0], venc->coeffs + channel*window_len, venc->samples + channel*window_len*2, venc->floor/*tmp*/);
893     }
894
895     if (samples) {
896         for (channel = 0; channel < venc->channels; channel++) {
897             float * offset = venc->saved + channel*window_len;
898             j = channel;
899             for (i = 0; i < samples; i++, j += venc->channels)
900                 offset[i] = audio[j] / 32768. / n * win[i];
901         }
902         venc->have_saved = 1;
903     } else {
904         venc->have_saved = 0;
905     }
906     return 1;
907 }
908
909 static int vorbis_encode_init(AVCodecContext * avccontext)
910 {
911     venc_context_t * venc = avccontext->priv_data;
912
913     create_vorbis_context(venc, avccontext);
914
915     //if (avccontext->flags & CODEC_FLAG_QSCALE) avccontext->global_quality / (float)FF_QP2LAMBDA); else avccontext->bit_rate;
916     //if(avccontext->cutoff > 0) cfreq = avccontext->cutoff / 1000.0;
917
918     avccontext->extradata_size = put_main_header(venc, (uint8_t**)&avccontext->extradata);
919
920     avccontext->frame_size = 1 << (venc->blocksize[0] - 1);
921
922     avccontext->coded_frame = avcodec_alloc_frame();
923     avccontext->coded_frame->key_frame = 1;
924
925     return 0;
926 }
927
928 static int vorbis_encode_frame(AVCodecContext * avccontext, unsigned char * packets, int buf_size, void *data)
929 {
930     venc_context_t * venc = avccontext->priv_data;
931     signed short * audio = data;
932     int samples = data ? avccontext->frame_size : 0;
933     vorbis_mode_t * mode;
934     mapping_t * mapping;
935     PutBitContext pb;
936     int i;
937
938     if (!window(venc, audio, samples)) return 0;
939     samples = 1 << (venc->blocksize[0] - 1);
940
941     init_put_bits(&pb, packets, buf_size);
942
943     put_bits(&pb, 1, 0); // magic bit
944
945     put_bits(&pb, ilog(venc->nmodes - 1), 0); // 0 bits, the mode
946
947     mode = &venc->modes[0];
948     mapping = &venc->mappings[mode->mapping];
949     if (mode->blockflag) {
950         put_bits(&pb, 1, 0);
951         put_bits(&pb, 1, 0);
952     }
953
954     for (i = 0; i < venc->channels; i++) {
955         floor_t * fc = &venc->floors[mapping->floor[mapping->mux[i]]];
956         int posts[fc->values];
957         floor_fit(venc, fc, &venc->coeffs[i * samples], posts, samples);
958         floor_encode(venc, fc, &pb, posts, &venc->floor[i * samples], samples);
959     }
960
961     for (i = 0; i < venc->channels; i++) {
962         int j;
963         for (j = 0; j < samples; j++) {
964             venc->coeffs[i * samples + j] /= venc->floor[i * samples + j];
965         }
966     }
967
968     for (i = 0; i < mapping->coupling_steps; i++) {
969         float * mag = venc->coeffs + mapping->magnitude[i] * samples;
970         float * ang = venc->coeffs + mapping->angle[i] * samples;
971         int j;
972         for (j = 0; j < samples; j++) {
973             float m = mag[j];
974             float a = ang[j];
975             if (m > 0) {
976                 ang[j] = m - a;
977                 if (a > m) mag[j] = a;
978                 else mag[j] = m;
979             } else {
980                 ang[j] = a - m;
981                 if (a > m) mag[j] = m;
982                 else mag[j] = a;
983             }
984         }
985     }
986
987     residue_encode(venc, &venc->residues[mapping->residue[mapping->mux[0]]], &pb, venc->coeffs, samples, venc->channels);
988
989     return (put_bits_count(&pb) + 7) / 8;
990 }
991
992
993 static int vorbis_encode_close(AVCodecContext * avccontext)
994 {
995     venc_context_t * venc = avccontext->priv_data;
996     int i;
997
998     if (venc->codebooks) for (i = 0; i < venc->ncodebooks; i++) {
999         av_freep(&venc->codebooks[i].entries);
1000         av_freep(&venc->codebooks[i].quantlist);
1001         av_freep(&venc->codebooks[i].dimentions);
1002     }
1003     av_freep(&venc->codebooks);
1004
1005     if (venc->floors) for (i = 0; i < venc->nfloors; i++) {
1006         int j;
1007         av_freep(&venc->floors[i].classes);
1008         if (venc->floors[i].classes)
1009             for (j = 0; j < venc->floors[i].nclasses; j++)
1010                 av_freep(&venc->floors[i].classes[j].books);
1011         av_freep(&venc->floors[i].partition_to_class);
1012         av_freep(&venc->floors[i].list);
1013     }
1014     av_freep(&venc->floors);
1015
1016     if (venc->residues) for (i = 0; i < venc->nresidues; i++) {
1017         av_freep(&venc->residues[i].books);
1018     }
1019     av_freep(&venc->residues);
1020
1021     if (venc->mappings) for (i = 0; i < venc->nmappings; i++) {
1022         av_freep(&venc->mappings[i].mux);
1023         av_freep(&venc->mappings[i].floor);
1024         av_freep(&venc->mappings[i].residue);
1025     }
1026     av_freep(&venc->mappings);
1027
1028     av_freep(&venc->modes);
1029
1030     av_freep(&venc->saved);
1031     av_freep(&venc->samples);
1032     av_freep(&venc->floor);
1033     av_freep(&venc->coeffs);
1034
1035     ff_mdct_end(&venc->mdct[0]);
1036     ff_mdct_end(&venc->mdct[1]);
1037
1038     av_freep(&avccontext->coded_frame);
1039     av_freep(&avccontext->extradata);
1040
1041     return 0 ;
1042 }
1043
1044 AVCodec vorbis_encoder = {
1045     "vorbis",
1046     CODEC_TYPE_AUDIO,
1047     CODEC_ID_VORBIS,
1048     sizeof(venc_context_t),
1049     vorbis_encode_init,
1050     vorbis_encode_frame,
1051     vorbis_encode_close,
1052     .capabilities= CODEC_CAP_DELAY,
1053 };