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