OSDN Git Service

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