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