GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/vorbisenc.c Lines: 670 755 88.7 %
Date: 2020-08-14 10:39:37 Branches: 338 446 75.8 %

Line Branch Exec Source
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
#include "audio_frame_queue.h"
38
#include "libavfilter/bufferqueue.h"
39
40
#define BITSTREAM_WRITER_LE
41
#include "put_bits.h"
42
43
#undef NDEBUG
44
#include <assert.h>
45
46
typedef struct vorbis_enc_codebook {
47
    int nentries;
48
    uint8_t *lens;
49
    uint32_t *codewords;
50
    int ndimensions;
51
    float min;
52
    float delta;
53
    int seq_p;
54
    int lookup;
55
    int *quantlist;
56
    float *dimensions;
57
    float *pow2;
58
} vorbis_enc_codebook;
59
60
typedef struct vorbis_enc_floor_class {
61
    int dim;
62
    int subclass;
63
    int masterbook;
64
    int *books;
65
} vorbis_enc_floor_class;
66
67
typedef struct vorbis_enc_floor {
68
    int partitions;
69
    int *partition_to_class;
70
    int nclasses;
71
    vorbis_enc_floor_class *classes;
72
    int multiplier;
73
    int rangebits;
74
    int values;
75
    vorbis_floor1_entry *list;
76
} vorbis_enc_floor;
77
78
typedef struct vorbis_enc_residue {
79
    int type;
80
    int begin;
81
    int end;
82
    int partition_size;
83
    int classifications;
84
    int classbook;
85
    int8_t (*books)[8];
86
    float (*maxes)[2];
87
} vorbis_enc_residue;
88
89
typedef struct vorbis_enc_mapping {
90
    int submaps;
91
    int *mux;
92
    int *floor;
93
    int *residue;
94
    int coupling_steps;
95
    int *magnitude;
96
    int *angle;
97
} vorbis_enc_mapping;
98
99
typedef struct vorbis_enc_mode {
100
    int blockflag;
101
    int mapping;
102
} vorbis_enc_mode;
103
104
typedef struct vorbis_enc_context {
105
    int channels;
106
    int sample_rate;
107
    int log2_blocksize[2];
108
    FFTContext mdct[2];
109
    const float *win[2];
110
    int have_saved;
111
    float *saved;
112
    float *samples;
113
    float *floor;  // also used for tmp values for mdct
114
    float *coeffs; // also used for residue after floor
115
    float *scratch; // used for tmp values for psy model
116
    float quality;
117
118
    AudioFrameQueue afq;
119
    struct FFBufQueue bufqueue;
120
121
    int ncodebooks;
122
    vorbis_enc_codebook *codebooks;
123
124
    int nfloors;
125
    vorbis_enc_floor *floors;
126
127
    int nresidues;
128
    vorbis_enc_residue *residues;
129
130
    int nmappings;
131
    vorbis_enc_mapping *mappings;
132
133
    int nmodes;
134
    vorbis_enc_mode *modes;
135
136
    int64_t next_pts;
137
138
    AVFloatDSPContext *fdsp;
139
} vorbis_enc_context;
140
141
#define MAX_CHANNELS     2
142
#define MAX_CODEBOOK_DIM 8
143
144
#define MAX_FLOOR_CLASS_DIM  4
145
#define NUM_FLOOR_PARTITIONS 8
146
#define MAX_FLOOR_VALUES     (MAX_FLOOR_CLASS_DIM*NUM_FLOOR_PARTITIONS+2)
147
148
#define RESIDUE_SIZE           1600
149
#define RESIDUE_PART_SIZE      32
150
#define NUM_RESIDUE_PARTITIONS (RESIDUE_SIZE/RESIDUE_PART_SIZE)
151
152
398666
static inline int put_codeword(PutBitContext *pb, vorbis_enc_codebook *cb,
153
                               int entry)
154
{
155
    av_assert2(entry >= 0);
156
    av_assert2(entry < cb->nentries);
157
    av_assert2(cb->lens[entry]);
158
398666
    if (pb->size_in_bits - put_bits_count(pb) < cb->lens[entry])
159
        return AVERROR(EINVAL);
160
398666
    put_bits(pb, cb->lens[entry], cb->codewords[entry]);
161
398666
    return 0;
162
}
163
164
39
static int cb_lookup_vals(int lookup, int dimensions, int entries)
165
{
166
39
    if (lookup == 1)
167
39
        return ff_vorbis_nth_root(entries, dimensions);
168
    else if (lookup == 2)
169
        return dimensions *entries;
170
    return 0;
171
}
172
173
29
static int ready_codebook(vorbis_enc_codebook *cb)
174
{
175
    int i;
176
177
29
    ff_vorbis_len2vlc(cb->lens, cb->codewords, cb->nentries);
178
179
29
    if (!cb->lookup) {
180
16
        cb->pow2 = cb->dimensions = NULL;
181
    } else {
182
13
        int vals = cb_lookup_vals(cb->lookup, cb->ndimensions, cb->nentries);
183
13
        cb->dimensions = av_malloc_array(cb->nentries, sizeof(float) * cb->ndimensions);
184
13
        cb->pow2 = av_mallocz_array(cb->nentries, sizeof(float));
185

13
        if (!cb->dimensions || !cb->pow2)
186
            return AVERROR(ENOMEM);
187
9354
        for (i = 0; i < cb->nentries; i++) {
188
9341
            float last = 0;
189
            int j;
190
9341
            int div = 1;
191
70051
            for (j = 0; j < cb->ndimensions; j++) {
192
                int off;
193
60710
                if (cb->lookup == 1)
194
60710
                    off = (i / div) % vals; // lookup type 1
195
                else
196
                    off = i * cb->ndimensions + j; // lookup type 2
197
198
60710
                cb->dimensions[i * cb->ndimensions + j] = last + cb->min + cb->quantlist[off] * cb->delta;
199
60710
                if (cb->seq_p)
200
                    last = cb->dimensions[i * cb->ndimensions + j];
201
60710
                cb->pow2[i] += cb->dimensions[i * cb->ndimensions + j] * cb->dimensions[i * cb->ndimensions + j];
202
60710
                div *= vals;
203
            }
204
9341
            cb->pow2[i] /= 2.0;
205
        }
206
    }
207
29
    return 0;
208
}
209
210
1
static int ready_residue(vorbis_enc_residue *rc, vorbis_enc_context *venc)
211
{
212
    int i;
213
1
    av_assert0(rc->type == 2);
214
1
    rc->maxes = av_mallocz_array(rc->classifications, sizeof(float[2]));
215
1
    if (!rc->maxes)
216
        return AVERROR(ENOMEM);
217
11
    for (i = 0; i < rc->classifications; i++) {
218
        int j;
219
        vorbis_enc_codebook * cb;
220
30
        for (j = 0; j < 8; j++)
221
29
            if (rc->books[i][j] != -1)
222
9
                break;
223
10
        if (j == 8) // zero
224
1
            continue;
225
9
        cb = &venc->codebooks[rc->books[i][j]];
226
9
        assert(cb->ndimensions >= 2);
227
9
        assert(cb->lookup);
228
229
8690
        for (j = 0; j < cb->nentries; j++) {
230
            float a;
231
8681
            if (!cb->lens[j])
232
7798
                continue;
233
883
            a = fabs(cb->dimensions[j * cb->ndimensions]);
234
883
            if (a > rc->maxes[i][0])
235
31
                rc->maxes[i][0] = a;
236
883
            a = fabs(cb->dimensions[j * cb->ndimensions + 1]);
237
883
            if (a > rc->maxes[i][1])
238
31
                rc->maxes[i][1] = a;
239
        }
240
    }
241
    // small bias
242
11
    for (i = 0; i < rc->classifications; i++) {
243
10
        rc->maxes[i][0] += 0.8;
244
10
        rc->maxes[i][1] += 0.8;
245
    }
246
1
    return 0;
247
}
248
249
1
static av_cold int dsp_init(AVCodecContext *avctx, vorbis_enc_context *venc)
250
{
251
1
    int ret = 0;
252
253
1
    venc->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
254
1
    if (!venc->fdsp)
255
        return AVERROR(ENOMEM);
256
257
    // init windows
258
1
    venc->win[0] = ff_vorbis_vwin[venc->log2_blocksize[0] - 6];
259
1
    venc->win[1] = ff_vorbis_vwin[venc->log2_blocksize[1] - 6];
260
261
1
    if ((ret = ff_mdct_init(&venc->mdct[0], venc->log2_blocksize[0], 0, 1.0)) < 0)
262
        return ret;
263
1
    if ((ret = ff_mdct_init(&venc->mdct[1], venc->log2_blocksize[1], 0, 1.0)) < 0)
264
        return ret;
265
266
1
    return 0;
267
}
268
269
1
static int create_vorbis_context(vorbis_enc_context *venc,
270
                                 AVCodecContext *avctx)
271
{
272
    vorbis_enc_floor   *fc;
273
    vorbis_enc_residue *rc;
274
    vorbis_enc_mapping *mc;
275
    int i, book, ret;
276
277
1
    venc->channels    = avctx->channels;
278
1
    venc->sample_rate = avctx->sample_rate;
279
1
    venc->log2_blocksize[0] = venc->log2_blocksize[1] = 11;
280
281
1
    venc->ncodebooks = FF_ARRAY_ELEMS(cvectors);
282
1
    venc->codebooks  = av_malloc(sizeof(vorbis_enc_codebook) * venc->ncodebooks);
283
1
    if (!venc->codebooks)
284
        return AVERROR(ENOMEM);
285
286
    // codebook 0..14 - floor1 book, values 0..255
287
    // codebook 15 residue masterbook
288
    // codebook 16..29 residue
289
30
    for (book = 0; book < venc->ncodebooks; book++) {
290
29
        vorbis_enc_codebook *cb = &venc->codebooks[book];
291
        int vals;
292
29
        cb->ndimensions = cvectors[book].dim;
293
29
        cb->nentries    = cvectors[book].real_len;
294
29
        cb->min         = cvectors[book].min;
295
29
        cb->delta       = cvectors[book].delta;
296
29
        cb->lookup      = cvectors[book].lookup;
297
29
        cb->seq_p       = 0;
298
299
29
        cb->lens      = av_malloc_array(cb->nentries, sizeof(uint8_t));
300
29
        cb->codewords = av_malloc_array(cb->nentries, sizeof(uint32_t));
301

29
        if (!cb->lens || !cb->codewords)
302
            return AVERROR(ENOMEM);
303
29
        memcpy(cb->lens, cvectors[book].clens, cvectors[book].len);
304
29
        memset(cb->lens + cvectors[book].len, 0, cb->nentries - cvectors[book].len);
305
306
29
        if (cb->lookup) {
307
13
            vals = cb_lookup_vals(cb->lookup, cb->ndimensions, cb->nentries);
308
13
            cb->quantlist = av_malloc_array(vals, sizeof(int));
309
13
            if (!cb->quantlist)
310
                return AVERROR(ENOMEM);
311
138
            for (i = 0; i < vals; i++)
312
125
                cb->quantlist[i] = cvectors[book].quant[i];
313
        } else {
314
16
            cb->quantlist = NULL;
315
        }
316
29
        if ((ret = ready_codebook(cb)) < 0)
317
            return ret;
318
    }
319
320
1
    venc->nfloors = 1;
321
1
    venc->floors  = av_malloc(sizeof(vorbis_enc_floor) * venc->nfloors);
322
1
    if (!venc->floors)
323
        return AVERROR(ENOMEM);
324
325
    // just 1 floor
326
1
    fc = &venc->floors[0];
327
1
    fc->partitions         = NUM_FLOOR_PARTITIONS;
328
1
    fc->partition_to_class = av_malloc(sizeof(int) * fc->partitions);
329
1
    if (!fc->partition_to_class)
330
        return AVERROR(ENOMEM);
331
1
    fc->nclasses           = 0;
332
9
    for (i = 0; i < fc->partitions; i++) {
333
        static const int a[] = {0, 1, 2, 2, 3, 3, 4, 4};
334
8
        fc->partition_to_class[i] = a[i];
335
8
        fc->nclasses = FFMAX(fc->nclasses, fc->partition_to_class[i]);
336
    }
337
1
    fc->nclasses++;
338
1
    fc->classes = av_malloc_array(fc->nclasses, sizeof(vorbis_enc_floor_class));
339
1
    if (!fc->classes)
340
        return AVERROR(ENOMEM);
341
6
    for (i = 0; i < fc->nclasses; i++) {
342
5
        vorbis_enc_floor_class * c = &fc->classes[i];
343
        int j, books;
344
5
        c->dim        = floor_classes[i].dim;
345
5
        c->subclass   = floor_classes[i].subclass;
346
5
        c->masterbook = floor_classes[i].masterbook;
347
5
        books         = (1 << c->subclass);
348
5
        c->books      = av_malloc_array(books, sizeof(int));
349
5
        if (!c->books)
350
            return AVERROR(ENOMEM);
351
18
        for (j = 0; j < books; j++)
352
13
            c->books[j] = floor_classes[i].nbooks[j];
353
    }
354
1
    fc->multiplier = 2;
355
1
    fc->rangebits  = venc->log2_blocksize[1] - 1;
356
357
1
    fc->values = 2;
358
9
    for (i = 0; i < fc->partitions; i++)
359
8
        fc->values += fc->classes[fc->partition_to_class[i]].dim;
360
361
1
    fc->list = av_malloc_array(fc->values, sizeof(vorbis_floor1_entry));
362
1
    if (!fc->list)
363
        return AVERROR(ENOMEM);
364
1
    fc->list[0].x = 0;
365
1
    fc->list[1].x = 1 << fc->rangebits;
366
28
    for (i = 2; i < fc->values; i++) {
367
        static const int a[] = {
368
             93, 23,372,  6, 46,186,750, 14, 33, 65,
369
            130,260,556,  3, 10, 18, 28, 39, 55, 79,
370
            111,158,220,312,464,650,850
371
        };
372
27
        fc->list[i].x = a[i - 2];
373
    }
374
1
    if (ff_vorbis_ready_floor1_list(avctx, fc->list, fc->values))
375
        return AVERROR_BUG;
376
377
1
    venc->nresidues = 1;
378
1
    venc->residues  = av_malloc(sizeof(vorbis_enc_residue) * venc->nresidues);
379
1
    if (!venc->residues)
380
        return AVERROR(ENOMEM);
381
382
    // single residue
383
1
    rc = &venc->residues[0];
384
1
    rc->type            = 2;
385
1
    rc->begin           = 0;
386
1
    rc->end             = 1600;
387
1
    rc->partition_size  = 32;
388
1
    rc->classifications = 10;
389
1
    rc->classbook       = 15;
390
1
    rc->books           = av_malloc(sizeof(*rc->books) * rc->classifications);
391
1
    if (!rc->books)
392
        return AVERROR(ENOMEM);
393
    {
394
        static const int8_t a[10][8] = {
395
            { -1, -1, -1, -1, -1, -1, -1, -1, },
396
            { -1, -1, 16, -1, -1, -1, -1, -1, },
397
            { -1, -1, 17, -1, -1, -1, -1, -1, },
398
            { -1, -1, 18, -1, -1, -1, -1, -1, },
399
            { -1, -1, 19, -1, -1, -1, -1, -1, },
400
            { -1, -1, 20, -1, -1, -1, -1, -1, },
401
            { -1, -1, 21, -1, -1, -1, -1, -1, },
402
            { 22, 23, -1, -1, -1, -1, -1, -1, },
403
            { 24, 25, -1, -1, -1, -1, -1, -1, },
404
            { 26, 27, 28, -1, -1, -1, -1, -1, },
405
        };
406
1
        memcpy(rc->books, a, sizeof a);
407
    }
408
1
    if ((ret = ready_residue(rc, venc)) < 0)
409
        return ret;
410
411
1
    venc->nmappings = 1;
412
1
    venc->mappings  = av_malloc(sizeof(vorbis_enc_mapping) * venc->nmappings);
413
1
    if (!venc->mappings)
414
        return AVERROR(ENOMEM);
415
416
    // single mapping
417
1
    mc = &venc->mappings[0];
418
1
    mc->submaps = 1;
419
1
    mc->mux     = av_malloc(sizeof(int) * venc->channels);
420
1
    if (!mc->mux)
421
        return AVERROR(ENOMEM);
422
3
    for (i = 0; i < venc->channels; i++)
423
2
        mc->mux[i] = 0;
424
1
    mc->floor   = av_malloc(sizeof(int) * mc->submaps);
425
1
    mc->residue = av_malloc(sizeof(int) * mc->submaps);
426

1
    if (!mc->floor || !mc->residue)
427
        return AVERROR(ENOMEM);
428
2
    for (i = 0; i < mc->submaps; i++) {
429
1
        mc->floor[i]   = 0;
430
1
        mc->residue[i] = 0;
431
    }
432
1
    mc->coupling_steps = venc->channels == 2 ? 1 : 0;
433
1
    mc->magnitude      = av_malloc(sizeof(int) * mc->coupling_steps);
434
1
    mc->angle          = av_malloc(sizeof(int) * mc->coupling_steps);
435

1
    if (!mc->magnitude || !mc->angle)
436
        return AVERROR(ENOMEM);
437
1
    if (mc->coupling_steps) {
438
1
        mc->magnitude[0] = 0;
439
1
        mc->angle[0]     = 1;
440
    }
441
442
1
    venc->nmodes = 2;
443
1
    venc->modes  = av_malloc(sizeof(vorbis_enc_mode) * venc->nmodes);
444
1
    if (!venc->modes)
445
        return AVERROR(ENOMEM);
446
447
    // Short block
448
1
    venc->modes[0].blockflag = 0;
449
1
    venc->modes[0].mapping   = 0;
450
    // Long block
451
1
    venc->modes[1].blockflag = 1;
452
1
    venc->modes[1].mapping   = 0;
453
454
1
    venc->have_saved = 0;
455
1
    venc->saved      = av_malloc_array(sizeof(float) * venc->channels, (1 << venc->log2_blocksize[1]) / 2);
456
1
    venc->samples    = av_malloc_array(sizeof(float) * venc->channels, (1 << venc->log2_blocksize[1]));
457
1
    venc->floor      = av_malloc_array(sizeof(float) * venc->channels, (1 << venc->log2_blocksize[1]) / 2);
458
1
    venc->coeffs     = av_malloc_array(sizeof(float) * venc->channels, (1 << venc->log2_blocksize[1]) / 2);
459
1
    venc->scratch    = av_malloc_array(sizeof(float) * venc->channels, (1 << venc->log2_blocksize[1]));
460
461


1
    if (!venc->saved || !venc->samples || !venc->floor || !venc->coeffs || !venc->scratch)
462
        return AVERROR(ENOMEM);
463
464
1
    if ((ret = dsp_init(avctx, venc)) < 0)
465
        return ret;
466
467
1
    return 0;
468
}
469
470
26
static void put_float(PutBitContext *pb, float f)
471
{
472
    int exp, mant;
473
26
    uint32_t res = 0;
474
26
    mant = (int)ldexp(frexp(f, &exp), 20);
475
26
    exp += 788 - 20;
476
26
    if (mant < 0) {
477
13
        res |= (1U << 31);
478
13
        mant = -mant;
479
    }
480
26
    res |= mant | (exp << 21);
481
26
    put_bits32(pb, res);
482
26
}
483
484
29
static void put_codebook_header(PutBitContext *pb, vorbis_enc_codebook *cb)
485
{
486
    int i;
487
29
    int ordered = 0;
488
489
29
    put_bits(pb, 24, 0x564342); //magic
490
29
    put_bits(pb, 16, cb->ndimensions);
491
29
    put_bits(pb, 24, cb->nentries);
492
493
161
    for (i = 1; i < cb->nentries; i++)
494
161
        if (cb->lens[i] < cb->lens[i-1])
495
29
            break;
496
29
    if (i == cb->nentries)
497
        ordered = 1;
498
499
29
    put_bits(pb, 1, ordered);
500
29
    if (ordered) {
501
        int len = cb->lens[0];
502
        put_bits(pb, 5, len - 1);
503
        i = 0;
504
        while (i < cb->nentries) {
505
            int j;
506
            for (j = 0; j+i < cb->nentries; j++)
507
                if (cb->lens[j+i] != len)
508
                    break;
509
            put_bits(pb, ilog(cb->nentries - i), j);
510
            i += j;
511
            len++;
512
        }
513
    } else {
514
29
        int sparse = 0;
515
2102
        for (i = 0; i < cb->nentries; i++)
516
2080
            if (!cb->lens[i])
517
7
                break;
518
29
        if (i != cb->nentries)
519
7
            sparse = 1;
520
29
        put_bits(pb, 1, sparse);
521
522
10452
        for (i = 0; i < cb->nentries; i++) {
523
10423
            if (sparse)
524
8431
                put_bits(pb, 1, !!cb->lens[i]);
525
10423
            if (cb->lens[i])
526
2625
                put_bits(pb, 5, cb->lens[i] - 1);
527
        }
528
    }
529
530
29
    put_bits(pb, 4, cb->lookup);
531
29
    if (cb->lookup) {
532
13
        int tmp  = cb_lookup_vals(cb->lookup, cb->ndimensions, cb->nentries);
533
13
        int bits = ilog(cb->quantlist[0]);
534
535
125
        for (i = 1; i < tmp; i++)
536
112
            bits = FFMAX(bits, ilog(cb->quantlist[i]));
537
538
13
        put_float(pb, cb->min);
539
13
        put_float(pb, cb->delta);
540
541
13
        put_bits(pb, 4, bits - 1);
542
13
        put_bits(pb, 1, cb->seq_p);
543
544
138
        for (i = 0; i < tmp; i++)
545
125
            put_bits(pb, bits, cb->quantlist[i]);
546
    }
547
29
}
548
549
1
static void put_floor_header(PutBitContext *pb, vorbis_enc_floor *fc)
550
{
551
    int i;
552
553
1
    put_bits(pb, 16, 1); // type, only floor1 is supported
554
555
1
    put_bits(pb, 5, fc->partitions);
556
557
9
    for (i = 0; i < fc->partitions; i++)
558
8
        put_bits(pb, 4, fc->partition_to_class[i]);
559
560
6
    for (i = 0; i < fc->nclasses; i++) {
561
        int j, books;
562
563
5
        put_bits(pb, 3, fc->classes[i].dim - 1);
564
5
        put_bits(pb, 2, fc->classes[i].subclass);
565
566
5
        if (fc->classes[i].subclass)
567
4
            put_bits(pb, 8, fc->classes[i].masterbook);
568
569
5
        books = (1 << fc->classes[i].subclass);
570
571
18
        for (j = 0; j < books; j++)
572
13
            put_bits(pb, 8, fc->classes[i].books[j] + 1);
573
    }
574
575
1
    put_bits(pb, 2, fc->multiplier - 1);
576
1
    put_bits(pb, 4, fc->rangebits);
577
578
28
    for (i = 2; i < fc->values; i++)
579
27
        put_bits(pb, fc->rangebits, fc->list[i].x);
580
1
}
581
582
1
static void put_residue_header(PutBitContext *pb, vorbis_enc_residue *rc)
583
{
584
    int i;
585
586
1
    put_bits(pb, 16, rc->type);
587
588
1
    put_bits(pb, 24, rc->begin);
589
1
    put_bits(pb, 24, rc->end);
590
1
    put_bits(pb, 24, rc->partition_size - 1);
591
1
    put_bits(pb, 6, rc->classifications - 1);
592
1
    put_bits(pb, 8, rc->classbook);
593
594
11
    for (i = 0; i < rc->classifications; i++) {
595
10
        int j, tmp = 0;
596
90
        for (j = 0; j < 8; j++)
597
80
            tmp |= (rc->books[i][j] != -1) << j;
598
599
10
        put_bits(pb, 3, tmp & 7);
600
10
        put_bits(pb, 1, tmp > 7);
601
602
10
        if (tmp > 7)
603
            put_bits(pb, 5, tmp >> 3);
604
    }
605
606
11
    for (i = 0; i < rc->classifications; i++) {
607
        int j;
608
90
        for (j = 0; j < 8; j++)
609
80
            if (rc->books[i][j] != -1)
610
13
                put_bits(pb, 8, rc->books[i][j]);
611
    }
612
1
}
613
614
1
static int put_main_header(vorbis_enc_context *venc, uint8_t **out)
615
{
616
    int i;
617
    PutBitContext pb;
618
    int len, hlens[3];
619
1
    int buffer_len = 50000;
620
1
    uint8_t *buffer = av_mallocz(buffer_len), *p = buffer;
621
1
    if (!buffer)
622
        return AVERROR(ENOMEM);
623
624
    // identification header
625
1
    init_put_bits(&pb, p, buffer_len);
626
1
    put_bits(&pb, 8, 1); //magic
627
7
    for (i = 0; "vorbis"[i]; i++)
628
6
        put_bits(&pb, 8, "vorbis"[i]);
629
1
    put_bits32(&pb, 0); // version
630
1
    put_bits(&pb,  8, venc->channels);
631
1
    put_bits32(&pb, venc->sample_rate);
632
1
    put_bits32(&pb, 0); // bitrate
633
1
    put_bits32(&pb, 0); // bitrate
634
1
    put_bits32(&pb, 0); // bitrate
635
1
    put_bits(&pb,  4, venc->log2_blocksize[0]);
636
1
    put_bits(&pb,  4, venc->log2_blocksize[1]);
637
1
    put_bits(&pb,  1, 1); // framing
638
639
1
    flush_put_bits(&pb);
640
1
    hlens[0] = put_bits_count(&pb) >> 3;
641
1
    buffer_len -= hlens[0];
642
1
    p += hlens[0];
643
644
    // comment header
645
1
    init_put_bits(&pb, p, buffer_len);
646
1
    put_bits(&pb, 8, 3); //magic
647
7
    for (i = 0; "vorbis"[i]; i++)
648
6
        put_bits(&pb, 8, "vorbis"[i]);
649
1
    put_bits32(&pb, 0); // vendor length TODO
650
1
    put_bits32(&pb, 0); // amount of comments
651
1
    put_bits(&pb,  1, 1); // framing
652
653
1
    flush_put_bits(&pb);
654
1
    hlens[1] = put_bits_count(&pb) >> 3;
655
1
    buffer_len -= hlens[1];
656
1
    p += hlens[1];
657
658
    // setup header
659
1
    init_put_bits(&pb, p, buffer_len);
660
1
    put_bits(&pb, 8, 5); //magic
661
7
    for (i = 0; "vorbis"[i]; i++)
662
6
        put_bits(&pb, 8, "vorbis"[i]);
663
664
    // codebooks
665
1
    put_bits(&pb, 8, venc->ncodebooks - 1);
666
30
    for (i = 0; i < venc->ncodebooks; i++)
667
29
        put_codebook_header(&pb, &venc->codebooks[i]);
668
669
    // time domain, reserved, zero
670
1
    put_bits(&pb,  6, 0);
671
1
    put_bits(&pb, 16, 0);
672
673
    // floors
674
1
    put_bits(&pb, 6, venc->nfloors - 1);
675
2
    for (i = 0; i < venc->nfloors; i++)
676
1
        put_floor_header(&pb, &venc->floors[i]);
677
678
    // residues
679
1
    put_bits(&pb, 6, venc->nresidues - 1);
680
2
    for (i = 0; i < venc->nresidues; i++)
681
1
        put_residue_header(&pb, &venc->residues[i]);
682
683
    // mappings
684
1
    put_bits(&pb, 6, venc->nmappings - 1);
685
2
    for (i = 0; i < venc->nmappings; i++) {
686
1
        vorbis_enc_mapping *mc = &venc->mappings[i];
687
        int j;
688
1
        put_bits(&pb, 16, 0); // mapping type
689
690
1
        put_bits(&pb, 1, mc->submaps > 1);
691
1
        if (mc->submaps > 1)
692
            put_bits(&pb, 4, mc->submaps - 1);
693
694
1
        put_bits(&pb, 1, !!mc->coupling_steps);
695
1
        if (mc->coupling_steps) {
696
1
            put_bits(&pb, 8, mc->coupling_steps - 1);
697
2
            for (j = 0; j < mc->coupling_steps; j++) {
698
1
                put_bits(&pb, ilog(venc->channels - 1), mc->magnitude[j]);
699
1
                put_bits(&pb, ilog(venc->channels - 1), mc->angle[j]);
700
            }
701
        }
702
703
1
        put_bits(&pb, 2, 0); // reserved
704
705
1
        if (mc->submaps > 1)
706
            for (j = 0; j < venc->channels; j++)
707
                put_bits(&pb, 4, mc->mux[j]);
708
709
2
        for (j = 0; j < mc->submaps; j++) {
710
1
            put_bits(&pb, 8, 0); // reserved time configuration
711
1
            put_bits(&pb, 8, mc->floor[j]);
712
1
            put_bits(&pb, 8, mc->residue[j]);
713
        }
714
    }
715
716
    // modes
717
1
    put_bits(&pb, 6, venc->nmodes - 1);
718
3
    for (i = 0; i < venc->nmodes; i++) {
719
2
        put_bits(&pb, 1, venc->modes[i].blockflag);
720
2
        put_bits(&pb, 16, 0); // reserved window type
721
2
        put_bits(&pb, 16, 0); // reserved transform type
722
2
        put_bits(&pb, 8, venc->modes[i].mapping);
723
    }
724
725
1
    put_bits(&pb, 1, 1); // framing
726
727
1
    flush_put_bits(&pb);
728
1
    hlens[2] = put_bits_count(&pb) >> 3;
729
730
1
    len = hlens[0] + hlens[1] + hlens[2];
731
1
    p = *out = av_mallocz(64 + len + len/255);
732
1
    if (!p)
733
        return AVERROR(ENOMEM);
734
735
1
    *p++ = 2;
736
1
    p += av_xiphlacing(p, hlens[0]);
737
1
    p += av_xiphlacing(p, hlens[1]);
738
1
    buffer_len = 0;
739
4
    for (i = 0; i < 3; i++) {
740
3
        memcpy(p, buffer + buffer_len, hlens[i]);
741
3
        p += hlens[i];
742
3
        buffer_len += hlens[i];
743
    }
744
745
1
    av_freep(&buffer);
746
1
    return p - *out;
747
}
748
749
23780
static float get_floor_average(vorbis_enc_floor * fc, float *coeffs, int i)
750
{
751
23780
    int begin = fc->list[fc->list[FFMAX(i-1, 0)].sort].x;
752
23780
    int end   = fc->list[fc->list[FFMIN(i+1, fc->values - 1)].sort].x;
753
    int j;
754
23780
    float average = 0;
755
756
1703140
    for (j = begin; j < end; j++)
757
1679360
        average += fabs(coeffs[j]);
758
23780
    return average / (end - begin);
759
}
760
761
820
static void floor_fit(vorbis_enc_context *venc, vorbis_enc_floor *fc,
762
                      float *coeffs, uint16_t *posts, int samples)
763
{
764
820
    int range = 255 / fc->multiplier + 1;
765
    int i;
766
820
    float tot_average = 0.0;
767
    float averages[MAX_FLOOR_VALUES];
768
24600
    for (i = 0; i < fc->values; i++) {
769
23780
        averages[i] = get_floor_average(fc, coeffs, i);
770
23780
        tot_average += averages[i];
771
    }
772
820
    tot_average /= fc->values;
773
820
    tot_average /= venc->quality;
774
775
24600
    for (i = 0; i < fc->values; i++) {
776
23780
        int position  = fc->list[fc->list[i].sort].x;
777
23780
        float average = averages[i];
778
        int j;
779
780
23780
        average = sqrt(tot_average * average) * pow(1.25f, position*0.005f); // MAGIC!
781
1576156
        for (j = 0; j < range - 1; j++)
782
1576156
            if (ff_vorbis_floor1_inverse_db_table[j * fc->multiplier] > average)
783
23780
                break;
784
23780
        posts[fc->list[i].sort] = j;
785
    }
786
820
}
787
788
22140
static int render_point(int x0, int y0, int x1, int y1, int x)
789
{
790
22140
    return y0 +  (x - x0) * (y1 - y0) / (x1 - x0);
791
}
792
793
820
static int floor_encode(vorbis_enc_context *venc, vorbis_enc_floor *fc,
794
                        PutBitContext *pb, uint16_t *posts,
795
                        float *floor, int samples)
796
{
797
820
    int range = 255 / fc->multiplier + 1;
798
    int coded[MAX_FLOOR_VALUES]; // first 2 values are unused
799
    int i, counter;
800
801
820
    if (pb->size_in_bits - put_bits_count(pb) < 1 + 2 * ilog(range - 1))
802
        return AVERROR(EINVAL);
803
820
    put_bits(pb, 1, 1); // non zero
804
820
    put_bits(pb, ilog(range - 1), posts[0]);
805
820
    put_bits(pb, ilog(range - 1), posts[1]);
806
820
    coded[0] = coded[1] = 1;
807
808
22960
    for (i = 2; i < fc->values; i++) {
809
22140
        int predicted = render_point(fc->list[fc->list[i].low].x,
810
22140
                                     posts[fc->list[i].low],
811
22140
                                     fc->list[fc->list[i].high].x,
812
22140
                                     posts[fc->list[i].high],
813
22140
                                     fc->list[i].x);
814
22140
        int highroom = range - predicted;
815
22140
        int lowroom = predicted;
816
22140
        int room = FFMIN(highroom, lowroom);
817
22140
        if (predicted == posts[i]) {
818
5963
            coded[i] = 0; // must be used later as flag!
819
5963
            continue;
820
        } else {
821
16177
            if (!coded[fc->list[i].low ])
822
485
                coded[fc->list[i].low ] = -1;
823
16177
            if (!coded[fc->list[i].high])
824
1008
                coded[fc->list[i].high] = -1;
825
        }
826
16177
        if (posts[i] > predicted) {
827
6140
            if (posts[i] - predicted > room)
828
                coded[i] = posts[i] - predicted + lowroom;
829
            else
830
6140
                coded[i] = (posts[i] - predicted) << 1;
831
        } else {
832
10037
            if (predicted - posts[i] > room)
833
                coded[i] = predicted - posts[i] + highroom - 1;
834
            else
835
10037
                coded[i] = ((predicted - posts[i]) << 1) - 1;
836
        }
837
    }
838
839
820
    counter = 2;
840
7380
    for (i = 0; i < fc->partitions; i++) {
841
6560
        vorbis_enc_floor_class * c = &fc->classes[fc->partition_to_class[i]];
842
6560
        int k, cval = 0, csub = 1<<c->subclass;
843
6560
        if (c->subclass) {
844
5740
            vorbis_enc_codebook * book = &venc->codebooks[c->masterbook];
845
5740
            int cshift = 0;
846
25420
            for (k = 0; k < c->dim; k++) {
847
                int l;
848
26945
                for (l = 0; l < csub; l++) {
849
26945
                    int maxval = 1;
850
26945
                    if (c->books[l] != -1)
851
15465
                        maxval = venc->codebooks[c->books[l]].nentries;
852
                    // coded could be -1, but this still works, cause that is 0
853
26945
                    if (coded[counter + k] < maxval)
854
19680
                        break;
855
                }
856
19680
                assert(l != csub);
857
19680
                cval   |= l << cshift;
858
19680
                cshift += c->subclass;
859
            }
860
5740
            if (put_codeword(pb, book, cval))
861
                return AVERROR(EINVAL);
862
        }
863
28700
        for (k = 0; k < c->dim; k++) {
864
22140
            int book  = c->books[cval & (csub-1)];
865
22140
            int entry = coded[counter++];
866
22140
            cval >>= c->subclass;
867
22140
            if (book == -1)
868
4216
                continue;
869
17924
            if (entry == -1)
870
1493
                entry = 0;
871
17924
            if (put_codeword(pb, &venc->codebooks[book], entry))
872
                return AVERROR(EINVAL);
873
        }
874
    }
875
876
820
    ff_vorbis_floor1_render_list(fc->list, fc->values, posts, coded,
877
                                 fc->multiplier, floor, samples);
878
879
820
    return 0;
880
}
881
882
364752
static float *put_vector(vorbis_enc_codebook *book, PutBitContext *pb,
883
                         float *num)
884
{
885
364752
    int i, entry = -1;
886
364752
    float distance = FLT_MAX;
887
364752
    assert(book->dimensions);
888
123406368
    for (i = 0; i < book->nentries; i++) {
889
123041616
        float * vec = book->dimensions + i * book->ndimensions, d = book->pow2[i];
890
        int j;
891
123041616
        if (!book->lens[i])
892
78355072
            continue;
893
142975504
        for (j = 0; j < book->ndimensions; j++)
894
98288960
            d -= vec[j] * num[j];
895
44686544
        if (distance > d) {
896
1511239
            entry    = i;
897
1511239
            distance = d;
898
        }
899
    }
900
364752
    if (put_codeword(pb, book, entry))
901
        return NULL;
902
364752
    return &book->dimensions[entry * book->ndimensions];
903
}
904
905
410
static int residue_encode(vorbis_enc_context *venc, vorbis_enc_residue *rc,
906
                          PutBitContext *pb, float *coeffs, int samples,
907
                          int real_ch)
908
{
909
    int pass, i, j, p, k;
910
410
    int psize      = rc->partition_size;
911
410
    int partitions = (rc->end - rc->begin) / psize;
912
410
    int channels   = (rc->type == 2) ? 1 : real_ch;
913
    int classes[MAX_CHANNELS][NUM_RESIDUE_PARTITIONS];
914
410
    int classwords = venc->codebooks[rc->classbook].ndimensions;
915
916
410
    av_assert0(rc->type == 2);
917
410
    av_assert0(real_ch == 2);
918
20910
    for (p = 0; p < partitions; p++) {
919
20500
        float max1 = 0.0, max2 = 0.0;
920
20500
        int s = rc->begin + p * psize;
921
348500
        for (k = s; k < s + psize; k += 2) {
922
328000
            max1 = FFMAX(max1, fabs(coeffs[          k / real_ch]));
923
328000
            max2 = FFMAX(max2, fabs(coeffs[samples + k / real_ch]));
924
        }
925
926
121706
        for (i = 0; i < rc->classifications - 1; i++)
927

120465
            if (max1 < rc->maxes[i][0] && max2 < rc->maxes[i][1])
928
19259
                break;
929
20500
        classes[0][p] = i;
930
    }
931
932
3690
    for (pass = 0; pass < 8; pass++) {
933
3280
        p = 0;
934
85280
        while (p < partitions) {
935
82000
            if (pass == 0)
936
20500
                for (j = 0; j < channels; j++) {
937
10250
                    vorbis_enc_codebook * book = &venc->codebooks[rc->classbook];
938
10250
                    int entry = 0;
939
30750
                    for (i = 0; i < classwords; i++) {
940
20500
                        entry *= rc->classifications;
941
20500
                        entry += classes[j][p + i];
942
                    }
943
10250
                    if (put_codeword(pb, book, entry))
944
                        return AVERROR(EINVAL);
945
                }
946

246000
            for (i = 0; i < classwords && p < partitions; i++, p++) {
947
328000
                for (j = 0; j < channels; j++) {
948
164000
                    int nbook = rc->books[classes[j][p]][pass];
949
164000
                    vorbis_enc_codebook * book = &venc->codebooks[nbook];
950
164000
                    float *buf = coeffs + samples*j + rc->begin + p*psize;
951
164000
                    if (nbook == -1)
952
137514
                        continue;
953
954

26486
                    assert(rc->type == 0 || rc->type == 2);
955
26486
                    assert(!(psize % book->ndimensions));
956
957
26486
                    if (rc->type == 0) {
958
                        for (k = 0; k < psize; k += book->ndimensions) {
959
                            int l;
960
                            float *a = put_vector(book, pb, &buf[k]);
961
                            if (!a)
962
                                return AVERROR(EINVAL);
963
                            for (l = 0; l < book->ndimensions; l++)
964
                                buf[k + l] -= a[l];
965
                        }
966
                    } else {
967
26486
                        int s = rc->begin + p * psize, a1, b1;
968
26486
                        a1 = (s % real_ch) * samples;
969
26486
                        b1 =  s / real_ch;
970
26486
                        s  = real_ch * samples;
971
391238
                        for (k = 0; k < psize; k += book->ndimensions) {
972
364752
                            int dim, a2 = a1, b2 = b1;
973
364752
                            float vec[MAX_CODEBOOK_DIM], *pv = vec;
974
1212304
                            for (dim = book->ndimensions; dim--; ) {
975
847552
                                *pv++ = coeffs[a2 + b2];
976
847552
                                if ((a2 += samples) == s) {
977
423776
                                    a2 = 0;
978
423776
                                    b2++;
979
                                }
980
                            }
981
364752
                            pv = put_vector(book, pb, vec);
982
364752
                            if (!pv)
983
                                return AVERROR(EINVAL);
984
1212304
                            for (dim = book->ndimensions; dim--; ) {
985
847552
                                coeffs[a1 + b1] -= *pv++;
986
847552
                                if ((a1 += samples) == s) {
987
423776
                                    a1 = 0;
988
423776
                                    b1++;
989
                                }
990
                            }
991
                        }
992
                    }
993
                }
994
            }
995
        }
996
    }
997
410
    return 0;
998
}
999
1000
410
static int apply_window_and_mdct(vorbis_enc_context *venc)
1001
{
1002
    int channel;
1003
410
    const float * win = venc->win[1];
1004
410
    int window_len = 1 << (venc->log2_blocksize[1] - 1);
1005
410
    float n = (float)(1 << venc->log2_blocksize[1]) / 4.0;
1006
410
    AVFloatDSPContext *fdsp = venc->fdsp;
1007
1008
1230
    for (channel = 0; channel < venc->channels; channel++) {
1009
820
        float *offset = venc->samples + channel * window_len * 2;
1010
1011
820
        fdsp->vector_fmul(offset, offset, win, window_len);
1012
820
        fdsp->vector_fmul_scalar(offset, offset, 1/n, window_len);
1013
1014
820
        offset += window_len;
1015
1016
820
        fdsp->vector_fmul_reverse(offset, offset, win, window_len);
1017
820
        fdsp->vector_fmul_scalar(offset, offset, 1/n, window_len);
1018
1019
820
        venc->mdct[1].mdct_calc(&venc->mdct[1], venc->coeffs + channel * window_len,
1020
820
                     venc->samples + channel * window_len * 2);
1021
    }
1022
410
    return 1;
1023
}
1024
1025
/* Used for padding the last encoded packet */
1026
13
static AVFrame *spawn_empty_frame(AVCodecContext *avctx, int channels)
1027
{
1028
13
    AVFrame *f = av_frame_alloc();
1029
    int ch;
1030
1031
13
    if (!f)
1032
        return NULL;
1033
1034
13
    f->format = avctx->sample_fmt;
1035
13
    f->nb_samples = avctx->frame_size;
1036
13
    f->channel_layout = avctx->channel_layout;
1037
1038
13
    if (av_frame_get_buffer(f, 4)) {
1039
        av_frame_free(&f);
1040
        return NULL;
1041
    }
1042
1043
39
    for (ch = 0; ch < channels; ch++) {
1044
26
        size_t bps = av_get_bytes_per_sample(f->format);
1045
26
        memset(f->extended_data[ch], 0, bps * f->nb_samples);
1046
    }
1047
13
    return f;
1048
}
1049
1050
/* Set up audio samples for psy analysis and window/mdct */
1051
410
static void move_audio(vorbis_enc_context *venc, int sf_size)
1052
{
1053
410
    AVFrame *cur = NULL;
1054
410
    int frame_size = 1 << (venc->log2_blocksize[1] - 1);
1055
410
    int subframes = frame_size / sf_size;
1056
    int sf, ch;
1057
1058
    /* Copy samples from last frame into current frame */
1059
410
    if (venc->have_saved)
1060
1227
        for (ch = 0; ch < venc->channels; ch++)
1061
818
            memcpy(venc->samples + 2 * ch * frame_size,
1062
818
                   venc->saved + ch * frame_size, sizeof(float) * frame_size);
1063
    else
1064
3
        for (ch = 0; ch < venc->channels; ch++)
1065
2
            memset(venc->samples + 2 * ch * frame_size, 0, sizeof(float) * frame_size);
1066
1067
6970
    for (sf = 0; sf < subframes; sf++) {
1068
6560
        cur = ff_bufqueue_get(&venc->bufqueue);
1069
1070
19680
        for (ch = 0; ch < venc->channels; ch++) {
1071
13120
            float *offset = venc->samples + 2 * ch * frame_size + frame_size;
1072
13120
            float *save = venc->saved + ch * frame_size;
1073
13120
            const float *input = (float *) cur->extended_data[ch];
1074
13120
            const size_t len  = cur->nb_samples * sizeof(float);
1075
1076
13120
            memcpy(offset + sf*sf_size, input, len);
1077
13120
            memcpy(save + sf*sf_size, input, len);   // Move samples for next frame
1078
        }
1079
6560
        av_frame_free(&cur);
1080
    }
1081
410
    venc->have_saved = 1;
1082
410
    memcpy(venc->scratch, venc->samples, 2 * venc->channels * frame_size);
1083
410
}
1084
1085
6549
static int vorbis_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1086
                               const AVFrame *frame, int *got_packet_ptr)
1087
{
1088
6549
    vorbis_enc_context *venc = avctx->priv_data;
1089
    int i, ret, need_more;
1090
6549
    int frame_size = 1 << (venc->log2_blocksize[1] - 1);
1091
    vorbis_enc_mode *mode;
1092
    vorbis_enc_mapping *mapping;
1093
    PutBitContext pb;
1094
1095
6549
    if (frame) {
1096
        AVFrame *clone;
1097
6547
        if ((ret = ff_af_queue_add(&venc->afq, frame)) < 0)
1098
            return ret;
1099
6547
        clone = av_frame_clone(frame);
1100
6547
        if (!clone)
1101
            return AVERROR(ENOMEM);
1102
6547
        ff_bufqueue_add(avctx, &venc->bufqueue, clone);
1103
    } else
1104
2
        if (!venc->afq.remaining_samples)
1105
1
            return 0;
1106
1107
6548
    need_more = venc->bufqueue.available * avctx->frame_size < frame_size;
1108

6548
    need_more = frame && need_more;
1109
6548
    if (need_more)
1110
6138
        return 0;
1111
1112
    /* Pad the bufqueue with empty frames for encoding the last packet. */
1113
410
    if (!frame) {
1114
1
        if (venc->bufqueue.available * avctx->frame_size < frame_size) {
1115
1
            int frames_needed = (frame_size/avctx->frame_size) - venc->bufqueue.available;
1116
            int i;
1117
1118
14
            for (i = 0; i < frames_needed; i++) {
1119
13
               AVFrame *empty = spawn_empty_frame(avctx, venc->channels);
1120
13
               if (!empty)
1121
                   return AVERROR(ENOMEM);
1122
1123
13
               ff_bufqueue_add(avctx, &venc->bufqueue, empty);
1124
            }
1125
        }
1126
    }
1127
1128
410
    move_audio(venc, avctx->frame_size);
1129
1130
410
    if (!apply_window_and_mdct(venc))
1131
        return 0;
1132
1133
410
    if ((ret = ff_alloc_packet2(avctx, avpkt, 8192, 0)) < 0)
1134
        return ret;
1135
1136
410
    init_put_bits(&pb, avpkt->data, avpkt->size);
1137
1138
410
    if (pb.size_in_bits - put_bits_count(&pb) < 1 + ilog(venc->nmodes - 1)) {
1139
        av_log(avctx, AV_LOG_ERROR, "output buffer is too small\n");
1140
        return AVERROR(EINVAL);
1141
    }
1142
1143
410
    put_bits(&pb, 1, 0); // magic bit
1144
1145
410
    put_bits(&pb, ilog(venc->nmodes - 1), 1); // Mode for current frame
1146
1147
410
    mode    = &venc->modes[1];
1148
410
    mapping = &venc->mappings[mode->mapping];
1149
410
    if (mode->blockflag) {
1150
410
        put_bits(&pb, 1, 1); // Previous windowflag
1151
410
        put_bits(&pb, 1, 1); // Next windowflag
1152
    }
1153
1154
1230
    for (i = 0; i < venc->channels; i++) {
1155
820
        vorbis_enc_floor *fc = &venc->floors[mapping->floor[mapping->mux[i]]];
1156
        uint16_t posts[MAX_FLOOR_VALUES];
1157
820
        floor_fit(venc, fc, &venc->coeffs[i * frame_size], posts, frame_size);
1158
820
        if (floor_encode(venc, fc, &pb, posts, &venc->floor[i * frame_size], frame_size)) {
1159
            av_log(avctx, AV_LOG_ERROR, "output buffer is too small\n");
1160
            return AVERROR(EINVAL);
1161
        }
1162
    }
1163
1164
840090
    for (i = 0; i < venc->channels * frame_size; i++)
1165
839680
        venc->coeffs[i] /= venc->floor[i];
1166
1167
820
    for (i = 0; i < mapping->coupling_steps; i++) {
1168
410
        float *mag = venc->coeffs + mapping->magnitude[i] * frame_size;
1169
410
        float *ang = venc->coeffs + mapping->angle[i]     * frame_size;
1170
        int j;
1171
420250
        for (j = 0; j < frame_size; j++) {
1172
419840
            float a = ang[j];
1173
419840
            ang[j] -= mag[j];
1174
419840
            if (mag[j] > 0)
1175
209740
                ang[j] = -ang[j];
1176
419840
            if (ang[j] < 0)
1177
166370
                mag[j] = a;
1178
        }
1179
    }
1180
1181
410
    if (residue_encode(venc, &venc->residues[mapping->residue[mapping->mux[0]]],
1182
                       &pb, venc->coeffs, frame_size, venc->channels)) {
1183
        av_log(avctx, AV_LOG_ERROR, "output buffer is too small\n");
1184
        return AVERROR(EINVAL);
1185
    }
1186
1187
410
    flush_put_bits(&pb);
1188
410
    avpkt->size = put_bits_count(&pb) >> 3;
1189
1190
410
    ff_af_queue_remove(&venc->afq, frame_size, &avpkt->pts, &avpkt->duration);
1191
1192
410
    if (frame_size > avpkt->duration) {
1193
1
        uint8_t *side = av_packet_new_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
1194
1
        if (!side)
1195
            return AVERROR(ENOMEM);
1196
1
        AV_WL32(&side[4], frame_size - avpkt->duration);
1197
    }
1198
1199
410
    *got_packet_ptr = 1;
1200
410
    return 0;
1201
}
1202
1203
1204
1
static av_cold int vorbis_encode_close(AVCodecContext *avctx)
1205
{
1206
1
    vorbis_enc_context *venc = avctx->priv_data;
1207
    int i;
1208
1209
1
    if (venc->codebooks)
1210
30
        for (i = 0; i < venc->ncodebooks; i++) {
1211
29
            av_freep(&venc->codebooks[i].lens);
1212
29
            av_freep(&venc->codebooks[i].codewords);
1213
29
            av_freep(&venc->codebooks[i].quantlist);
1214
29
            av_freep(&venc->codebooks[i].dimensions);
1215
29
            av_freep(&venc->codebooks[i].pow2);
1216
        }
1217
1
    av_freep(&venc->codebooks);
1218
1219
1
    if (venc->floors)
1220
2
        for (i = 0; i < venc->nfloors; i++) {
1221
            int j;
1222
1
            if (venc->floors[i].classes)
1223
6
                for (j = 0; j < venc->floors[i].nclasses; j++)
1224
5
                    av_freep(&venc->floors[i].classes[j].books);
1225
1
            av_freep(&venc->floors[i].classes);
1226
1
            av_freep(&venc->floors[i].partition_to_class);
1227
1
            av_freep(&venc->floors[i].list);
1228
        }
1229
1
    av_freep(&venc->floors);
1230
1231
1
    if (venc->residues)
1232
2
        for (i = 0; i < venc->nresidues; i++) {
1233
1
            av_freep(&venc->residues[i].books);
1234
1
            av_freep(&venc->residues[i].maxes);
1235
        }
1236
1
    av_freep(&venc->residues);
1237
1238
1
    if (venc->mappings)
1239
2
        for (i = 0; i < venc->nmappings; i++) {
1240
1
            av_freep(&venc->mappings[i].mux);
1241
1
            av_freep(&venc->mappings[i].floor);
1242
1
            av_freep(&venc->mappings[i].residue);
1243
1
            av_freep(&venc->mappings[i].magnitude);
1244
1
            av_freep(&venc->mappings[i].angle);
1245
        }
1246
1
    av_freep(&venc->mappings);
1247
1248
1
    av_freep(&venc->modes);
1249
1250
1
    av_freep(&venc->saved);
1251
1
    av_freep(&venc->samples);
1252
1
    av_freep(&venc->floor);
1253
1
    av_freep(&venc->coeffs);
1254
1
    av_freep(&venc->scratch);
1255
1
    av_freep(&venc->fdsp);
1256
1257
1
    ff_mdct_end(&venc->mdct[0]);
1258
1
    ff_mdct_end(&venc->mdct[1]);
1259
1
    ff_af_queue_close(&venc->afq);
1260
1
    ff_bufqueue_discard_all(&venc->bufqueue);
1261
1262
1
    av_freep(&avctx->extradata);
1263
1264
1
    return 0 ;
1265
}
1266
1267
1
static av_cold int vorbis_encode_init(AVCodecContext *avctx)
1268
{
1269
1
    vorbis_enc_context *venc = avctx->priv_data;
1270
    int ret;
1271
1272
1
    if (avctx->channels != 2) {
1273
        av_log(avctx, AV_LOG_ERROR, "Current FFmpeg Vorbis encoder only supports 2 channels.\n");
1274
        return -1;
1275
    }
1276
1277
1
    if ((ret = create_vorbis_context(venc, avctx)) < 0)
1278
        goto error;
1279
1280
1
    avctx->bit_rate = 0;
1281
1
    if (avctx->flags & AV_CODEC_FLAG_QSCALE)
1282
        venc->quality = avctx->global_quality / (float)FF_QP2LAMBDA;
1283
    else
1284
1
        venc->quality = 8;
1285
1
    venc->quality *= venc->quality;
1286
1287
1
    if ((ret = put_main_header(venc, (uint8_t**)&avctx->extradata)) < 0)
1288
        goto error;
1289
1
    avctx->extradata_size = ret;
1290
1291
1
    avctx->frame_size = 64;
1292
1293
1
    ff_af_queue_init(avctx, &venc->afq);
1294
1295
1
    return 0;
1296
error:
1297
    vorbis_encode_close(avctx);
1298
    return ret;
1299
}
1300
1301
AVCodec ff_vorbis_encoder = {
1302
    .name           = "vorbis",
1303
    .long_name      = NULL_IF_CONFIG_SMALL("Vorbis"),
1304
    .type           = AVMEDIA_TYPE_AUDIO,
1305
    .id             = AV_CODEC_ID_VORBIS,
1306
    .priv_data_size = sizeof(vorbis_enc_context),
1307
    .init           = vorbis_encode_init,
1308
    .encode2        = vorbis_encode_frame,
1309
    .close          = vorbis_encode_close,
1310
    .capabilities   = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_EXPERIMENTAL,
1311
    .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
1312
                                                     AV_SAMPLE_FMT_NONE },
1313
};