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