]> git.sesse.net Git - ffmpeg/blob - libavcodec/opusenc.c
lavf/movenc: support GPMF track (gpmd) remuxing
[ffmpeg] / libavcodec / opusenc.c
1 /*
2  * Opus encoder
3  * Copyright (c) 2017 Rostislav Pehlivanov <atomnuker@gmail.com>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "opus_celt.h"
23 #include "opus_pvq.h"
24 #include "opustab.h"
25
26 #include "libavutil/float_dsp.h"
27 #include "libavutil/opt.h"
28 #include "internal.h"
29 #include "bytestream.h"
30 #include "audio_frame_queue.h"
31
32 /* Determines the maximum delay the psychoacoustic system will use for lookahead */
33 #define FF_BUFQUEUE_SIZE 145
34 #include "libavfilter/bufferqueue.h"
35
36 #define OPUS_MAX_LOOKAHEAD ((FF_BUFQUEUE_SIZE - 1)*2.5f)
37
38 #define OPUS_MAX_CHANNELS 2
39
40 /* 120 ms / 2.5 ms = 48 frames (extremely improbable, but the encoder'll work) */
41 #define OPUS_MAX_FRAMES_PER_PACKET 48
42
43 #define OPUS_BLOCK_SIZE(x) (2 * 15 * (1 << ((x) + 2)))
44
45 #define OPUS_SAMPLES_TO_BLOCK_SIZE(x) (ff_log2((x) / (2 * 15)) - 2)
46
47 typedef struct OpusEncOptions {
48     float max_delay_ms;
49 } OpusEncOptions;
50
51 typedef struct OpusEncContext {
52     AVClass *av_class;
53     OpusEncOptions options;
54     AVCodecContext *avctx;
55     AudioFrameQueue afq;
56     AVFloatDSPContext *dsp;
57     MDCT15Context *mdct[CELT_BLOCK_NB];
58     CeltPVQ *pvq;
59     struct FFBufQueue bufqueue;
60
61     enum OpusMode mode;
62     enum OpusBandwidth bandwidth;
63     int pkt_framesize;
64     int pkt_frames;
65
66     int channels;
67
68     CeltFrame *frame;
69     OpusRangeCoder *rc;
70
71     /* Actual energy the decoder will have */
72     float last_quantized_energy[OPUS_MAX_CHANNELS][CELT_MAX_BANDS];
73
74     DECLARE_ALIGNED(32, float, scratch)[2048];
75 } OpusEncContext;
76
77 static void opus_write_extradata(AVCodecContext *avctx)
78 {
79     uint8_t *bs = avctx->extradata;
80
81     bytestream_put_buffer(&bs, "OpusHead", 8);
82     bytestream_put_byte  (&bs, 0x1);
83     bytestream_put_byte  (&bs, avctx->channels);
84     bytestream_put_le16  (&bs, avctx->initial_padding);
85     bytestream_put_le32  (&bs, avctx->sample_rate);
86     bytestream_put_le16  (&bs, 0x0);
87     bytestream_put_byte  (&bs, 0x0); /* Default layout */
88 }
89
90 static int opus_gen_toc(OpusEncContext *s, uint8_t *toc, int *size, int *fsize_needed)
91 {
92     int i, tmp = 0x0, extended_toc = 0;
93     static const int toc_cfg[][OPUS_MODE_NB][OPUS_BANDWITH_NB] = {
94         /*  Silk                    Hybrid                  Celt                    Layer     */
95         /*  NB  MB  WB SWB  FB      NB  MB  WB SWB  FB      NB  MB  WB SWB  FB      Bandwidth */
96         { {  0,  0,  0,  0,  0 }, {  0,  0,  0,  0,  0 }, { 17,  0, 21, 25, 29 } }, /* 2.5 ms */
97         { {  0,  0,  0,  0,  0 }, {  0,  0,  0,  0,  0 }, { 18,  0, 22, 26, 30 } }, /*   5 ms */
98         { {  1,  5,  9,  0,  0 }, {  0,  0,  0, 13, 15 }, { 19,  0, 23, 27, 31 } }, /*  10 ms */
99         { {  2,  6, 10,  0,  0 }, {  0,  0,  0, 14, 16 }, { 20,  0, 24, 28, 32 } }, /*  20 ms */
100         { {  3,  7, 11,  0,  0 }, {  0,  0,  0,  0,  0 }, {  0,  0,  0,  0,  0 } }, /*  40 ms */
101         { {  4,  8, 12,  0,  0 }, {  0,  0,  0,  0,  0 }, {  0,  0,  0,  0,  0 } }, /*  60 ms */
102     };
103     int cfg = toc_cfg[s->pkt_framesize][s->mode][s->bandwidth];
104     *fsize_needed = 0;
105     if (!cfg)
106         return 1;
107     if (s->pkt_frames == 2) {                                          /* 2 packets */
108         if (s->frame[0].framebits == s->frame[1].framebits) {          /* same size */
109             tmp = 0x1;
110         } else {                                                  /* different size */
111             tmp = 0x2;
112             *fsize_needed = 1;                     /* put frame sizes in the packet */
113         }
114     } else if (s->pkt_frames > 2) {
115         tmp = 0x3;
116         extended_toc = 1;
117     }
118     tmp |= (s->channels > 1) << 2;                                /* Stereo or mono */
119     tmp |= (cfg - 1)         << 3;                           /* codec configuration */
120     *toc++ = tmp;
121     if (extended_toc) {
122         for (i = 0; i < (s->pkt_frames - 1); i++)
123             *fsize_needed |= (s->frame[i].framebits != s->frame[i + 1].framebits);
124         tmp = (*fsize_needed) << 7;                                     /* vbr flag */
125         tmp |= s->pkt_frames;                    /* frame number - can be 0 as well */
126         *toc++ = tmp;
127     }
128     *size = 1 + extended_toc;
129     return 0;
130 }
131
132 static void celt_frame_setup_input(OpusEncContext *s, CeltFrame *f)
133 {
134     int sf, ch;
135     AVFrame *cur = NULL;
136     const int subframesize = s->avctx->frame_size;
137     int subframes = OPUS_BLOCK_SIZE(s->pkt_framesize) / subframesize;
138
139     cur = ff_bufqueue_get(&s->bufqueue);
140
141     for (ch = 0; ch < f->channels; ch++) {
142         CeltBlock *b = &f->block[ch];
143         const void *input = cur->extended_data[ch];
144         size_t bps = av_get_bytes_per_sample(cur->format);
145         memcpy(b->overlap, input, bps*cur->nb_samples);
146     }
147
148     av_frame_free(&cur);
149
150     for (sf = 0; sf < subframes; sf++) {
151         if (sf != (subframes - 1))
152             cur = ff_bufqueue_get(&s->bufqueue);
153         else
154             cur = ff_bufqueue_peek(&s->bufqueue, 0);
155
156         for (ch = 0; ch < f->channels; ch++) {
157             CeltBlock *b = &f->block[ch];
158             const void *input = cur->extended_data[ch];
159             const size_t bps  = av_get_bytes_per_sample(cur->format);
160             const size_t left = (subframesize - cur->nb_samples)*bps;
161             const size_t len  = FFMIN(subframesize, cur->nb_samples)*bps;
162             memcpy(&b->samples[sf*subframesize], input, len);
163             memset(&b->samples[cur->nb_samples], 0, left);
164         }
165
166         /* Last frame isn't popped off and freed yet - we need it for overlap */
167         if (sf != (subframes - 1))
168             av_frame_free(&cur);
169     }
170 }
171
172 /* Apply the pre emphasis filter */
173 static void celt_apply_preemph_filter(OpusEncContext *s, CeltFrame *f)
174 {
175     int i, sf, ch;
176     const int subframesize = s->avctx->frame_size;
177     const int subframes = OPUS_BLOCK_SIZE(s->pkt_framesize) / subframesize;
178
179     /* Filter overlap */
180     for (ch = 0; ch < f->channels; ch++) {
181         CeltBlock *b = &f->block[ch];
182         float m = b->emph_coeff;
183         for (i = 0; i < CELT_OVERLAP; i++) {
184             float sample = b->overlap[i];
185             b->overlap[i] = sample - m;
186             m = sample * CELT_EMPH_COEFF;
187         }
188         b->emph_coeff = m;
189     }
190
191     /* Filter the samples but do not update the last subframe's coeff - overlap ^^^ */
192     for (sf = 0; sf < subframes; sf++) {
193         for (ch = 0; ch < f->channels; ch++) {
194             CeltBlock *b = &f->block[ch];
195             float m = b->emph_coeff;
196             for (i = 0; i < subframesize; i++) {
197                 float sample = b->samples[sf*subframesize + i];
198                 b->samples[sf*subframesize + i] = sample - m;
199                 m = sample * CELT_EMPH_COEFF;
200             }
201             if (sf != (subframes - 1))
202                 b->emph_coeff = m;
203         }
204     }
205 }
206
207 /* Create the window and do the mdct */
208 static void celt_frame_mdct(OpusEncContext *s, CeltFrame *f)
209 {
210     int t, ch;
211     float *win = s->scratch, *temp = s->scratch + 1920;
212
213     if (f->transient) {
214         for (ch = 0; ch < f->channels; ch++) {
215             CeltBlock *b = &f->block[ch];
216             float *src1 = b->overlap;
217             for (t = 0; t < f->blocks; t++) {
218                 float *src2 = &b->samples[CELT_OVERLAP*t];
219                 s->dsp->vector_fmul(win, src1, ff_celt_window, 128);
220                 s->dsp->vector_fmul_reverse(&win[CELT_OVERLAP], src2,
221                                             ff_celt_window - 8, 128);
222                 src1 = src2;
223                 s->mdct[0]->mdct(s->mdct[0], b->coeffs + t, win, f->blocks);
224             }
225         }
226     } else {
227         int blk_len = OPUS_BLOCK_SIZE(f->size), wlen = OPUS_BLOCK_SIZE(f->size + 1);
228         int rwin = blk_len - CELT_OVERLAP, lap_dst = (wlen - blk_len - CELT_OVERLAP) >> 1;
229         memset(win, 0, wlen*sizeof(float));
230         for (ch = 0; ch < f->channels; ch++) {
231             CeltBlock *b = &f->block[ch];
232
233             /* Overlap */
234             s->dsp->vector_fmul(temp, b->overlap, ff_celt_window, 128);
235             memcpy(win + lap_dst, temp, CELT_OVERLAP*sizeof(float));
236
237             /* Samples, flat top window */
238             memcpy(&win[lap_dst + CELT_OVERLAP], b->samples, rwin*sizeof(float));
239
240             /* Samples, windowed */
241             s->dsp->vector_fmul_reverse(temp, b->samples + rwin,
242                                         ff_celt_window - 8, 128);
243             memcpy(win + lap_dst + blk_len, temp, CELT_OVERLAP*sizeof(float));
244
245             s->mdct[f->size]->mdct(s->mdct[f->size], b->coeffs, win, 1);
246         }
247     }
248 }
249
250 /* Fills the bands and normalizes them */
251 static void celt_frame_map_norm_bands(OpusEncContext *s, CeltFrame *f)
252 {
253     int i, j, ch;
254
255     for (ch = 0; ch < f->channels; ch++) {
256         CeltBlock *block = &f->block[ch];
257         for (i = 0; i < CELT_MAX_BANDS; i++) {
258             float ener = 0.0f;
259             int band_offset = ff_celt_freq_bands[i] << f->size;
260             int band_size   = ff_celt_freq_range[i] << f->size;
261             float *coeffs   = &block->coeffs[band_offset];
262
263             for (j = 0; j < band_size; j++)
264                 ener += coeffs[j]*coeffs[j];
265
266             block->lin_energy[i] = sqrtf(ener) + FLT_EPSILON;
267             ener = 1.0f/block->lin_energy[i];
268
269             for (j = 0; j < band_size; j++)
270                 coeffs[j] *= ener;
271
272             block->energy[i] = log2f(block->lin_energy[i]) - ff_celt_mean_energy[i];
273
274             /* CELT_ENERGY_SILENCE is what the decoder uses and its not -infinity */
275             block->energy[i] = FFMAX(block->energy[i], CELT_ENERGY_SILENCE);
276         }
277     }
278 }
279
280 static void celt_enc_tf(OpusRangeCoder *rc, CeltFrame *f)
281 {
282     int i, tf_select = 0, diff = 0, tf_changed = 0, tf_select_needed;
283     int bits = f->transient ? 2 : 4;
284
285     tf_select_needed = ((f->size && (opus_rc_tell(rc) + bits + 1) <= f->framebits));
286
287     for (i = f->start_band; i < f->end_band; i++) {
288         if ((opus_rc_tell(rc) + bits + tf_select_needed) <= f->framebits) {
289             const int tbit = (diff ^ 1) == f->tf_change[i];
290             ff_opus_rc_enc_log(rc, tbit, bits);
291             diff ^= tbit;
292             tf_changed |= diff;
293         }
294         bits = f->transient ? 4 : 5;
295     }
296
297     if (tf_select_needed && ff_celt_tf_select[f->size][f->transient][0][tf_changed] !=
298                             ff_celt_tf_select[f->size][f->transient][1][tf_changed]) {
299         ff_opus_rc_enc_log(rc, f->tf_select, 1);
300         tf_select = f->tf_select;
301     }
302
303     for (i = f->start_band; i < f->end_band; i++)
304         f->tf_change[i] = ff_celt_tf_select[f->size][f->transient][tf_select][f->tf_change[i]];
305 }
306
307 static void ff_celt_enc_bitalloc(OpusRangeCoder *rc, CeltFrame *f)
308 {
309     int i, j, low, high, total, done, bandbits, remaining, tbits_8ths;
310     int skip_startband      = f->start_band;
311     int skip_bit            = 0;
312     int intensitystereo_bit = 0;
313     int dualstereo_bit      = 0;
314     int dynalloc            = 6;
315     int extrabits           = 0;
316
317     int *cap = f->caps;
318     int boost[CELT_MAX_BANDS];
319     int trim_offset[CELT_MAX_BANDS];
320     int threshold[CELT_MAX_BANDS];
321     int bits1[CELT_MAX_BANDS];
322     int bits2[CELT_MAX_BANDS];
323
324     /* Tell the spread to the decoder */
325     if (opus_rc_tell(rc) + 4 <= f->framebits)
326         ff_opus_rc_enc_cdf(rc, f->spread, ff_celt_model_spread);
327
328     /* Generate static allocation caps */
329     for (i = 0; i < CELT_MAX_BANDS; i++) {
330         cap[i] = (ff_celt_static_caps[f->size][f->channels - 1][i] + 64)
331                  * ff_celt_freq_range[i] << (f->channels - 1) << f->size >> 2;
332     }
333
334     /* Band boosts */
335     tbits_8ths = f->framebits << 3;
336     for (i = f->start_band; i < f->end_band; i++) {
337         int quanta, b_dynalloc, boost_amount = f->alloc_boost[i];
338
339         boost[i] = 0;
340
341         quanta = ff_celt_freq_range[i] << (f->channels - 1) << f->size;
342         quanta = FFMIN(quanta << 3, FFMAX(6 << 3, quanta));
343         b_dynalloc = dynalloc;
344
345         while (opus_rc_tell_frac(rc) + (b_dynalloc << 3) < tbits_8ths && boost[i] < cap[i]) {
346             int is_boost = boost_amount--;
347
348             ff_opus_rc_enc_log(rc, is_boost, b_dynalloc);
349             if (!is_boost)
350                 break;
351
352             boost[i]   += quanta;
353             tbits_8ths -= quanta;
354
355             b_dynalloc = 1;
356         }
357
358         if (boost[i])
359             dynalloc = FFMAX(2, dynalloc - 1);
360     }
361
362     /* Put allocation trim */
363     if (opus_rc_tell_frac(rc) + (6 << 3) <= tbits_8ths)
364         ff_opus_rc_enc_cdf(rc, f->alloc_trim, ff_celt_model_alloc_trim);
365
366     /* Anti-collapse bit reservation */
367     tbits_8ths = (f->framebits << 3) - opus_rc_tell_frac(rc) - 1;
368     f->anticollapse_needed = 0;
369     if (f->transient && f->size >= 2 && tbits_8ths >= ((f->size + 2) << 3))
370         f->anticollapse_needed = 1 << 3;
371     tbits_8ths -= f->anticollapse_needed;
372
373     /* Band skip bit reservation */
374     if (tbits_8ths >= 1 << 3)
375         skip_bit = 1 << 3;
376     tbits_8ths -= skip_bit;
377
378     /* Intensity/dual stereo bit reservation */
379     if (f->channels == 2) {
380         intensitystereo_bit = ff_celt_log2_frac[f->end_band - f->start_band];
381         if (intensitystereo_bit <= tbits_8ths) {
382             tbits_8ths -= intensitystereo_bit;
383             if (tbits_8ths >= 1 << 3) {
384                 dualstereo_bit = 1 << 3;
385                 tbits_8ths -= 1 << 3;
386             }
387         } else {
388             intensitystereo_bit = 0;
389         }
390     }
391
392     /* Trim offsets */
393     for (i = f->start_band; i < f->end_band; i++) {
394         int trim     = f->alloc_trim - 5 - f->size;
395         int band     = ff_celt_freq_range[i] * (f->end_band - i - 1);
396         int duration = f->size + 3;
397         int scale    = duration + f->channels - 1;
398
399         /* PVQ minimum allocation threshold, below this value the band is
400          * skipped */
401         threshold[i] = FFMAX(3 * ff_celt_freq_range[i] << duration >> 4,
402                              f->channels << 3);
403
404         trim_offset[i] = trim * (band << scale) >> 6;
405
406         if (ff_celt_freq_range[i] << f->size == 1)
407             trim_offset[i] -= f->channels << 3;
408     }
409
410     /* Bisection */
411     low  = 1;
412     high = CELT_VECTORS - 1;
413     while (low <= high) {
414         int center = (low + high) >> 1;
415         done = total = 0;
416
417         for (i = f->end_band - 1; i >= f->start_band; i--) {
418             bandbits = ff_celt_freq_range[i] * ff_celt_static_alloc[center][i]
419                        << (f->channels - 1) << f->size >> 2;
420
421             if (bandbits)
422                 bandbits = FFMAX(0, bandbits + trim_offset[i]);
423             bandbits += boost[i];
424
425             if (bandbits >= threshold[i] || done) {
426                 done = 1;
427                 total += FFMIN(bandbits, cap[i]);
428             } else if (bandbits >= f->channels << 3)
429                 total += f->channels << 3;
430         }
431
432         if (total > tbits_8ths)
433             high = center - 1;
434         else
435             low = center + 1;
436     }
437     high = low--;
438
439     /* Bisection */
440     for (i = f->start_band; i < f->end_band; i++) {
441         bits1[i] = ff_celt_freq_range[i] * ff_celt_static_alloc[low][i]
442                    << (f->channels - 1) << f->size >> 2;
443         bits2[i] = high >= CELT_VECTORS ? cap[i] :
444                    ff_celt_freq_range[i] * ff_celt_static_alloc[high][i]
445                    << (f->channels - 1) << f->size >> 2;
446
447         if (bits1[i])
448             bits1[i] = FFMAX(0, bits1[i] + trim_offset[i]);
449         if (bits2[i])
450             bits2[i] = FFMAX(0, bits2[i] + trim_offset[i]);
451         if (low)
452             bits1[i] += boost[i];
453         bits2[i] += boost[i];
454
455         if (boost[i])
456             skip_startband = i;
457         bits2[i] = FFMAX(0, bits2[i] - bits1[i]);
458     }
459
460     /* Bisection */
461     low  = 0;
462     high = 1 << CELT_ALLOC_STEPS;
463     for (i = 0; i < CELT_ALLOC_STEPS; i++) {
464         int center = (low + high) >> 1;
465         done = total = 0;
466
467         for (j = f->end_band - 1; j >= f->start_band; j--) {
468             bandbits = bits1[j] + (center * bits2[j] >> CELT_ALLOC_STEPS);
469
470             if (bandbits >= threshold[j] || done) {
471                 done = 1;
472                 total += FFMIN(bandbits, cap[j]);
473             } else if (bandbits >= f->channels << 3)
474                 total += f->channels << 3;
475         }
476         if (total > tbits_8ths)
477             high = center;
478         else
479             low = center;
480     }
481
482     /* Bisection */
483     done = total = 0;
484     for (i = f->end_band - 1; i >= f->start_band; i--) {
485         bandbits = bits1[i] + (low * bits2[i] >> CELT_ALLOC_STEPS);
486
487         if (bandbits >= threshold[i] || done)
488             done = 1;
489         else
490             bandbits = (bandbits >= f->channels << 3) ?
491                        f->channels << 3 : 0;
492
493         bandbits     = FFMIN(bandbits, cap[i]);
494         f->pulses[i] = bandbits;
495         total      += bandbits;
496     }
497
498     /* Band skipping */
499     for (f->coded_bands = f->end_band; ; f->coded_bands--) {
500         int allocation;
501         j = f->coded_bands - 1;
502
503         if (j == skip_startband) {
504             /* all remaining bands are not skipped */
505             tbits_8ths += skip_bit;
506             break;
507         }
508
509         /* determine the number of bits available for coding "do not skip" markers */
510         remaining   = tbits_8ths - total;
511         bandbits    = remaining / (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
512         remaining  -= bandbits  * (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
513         allocation  = f->pulses[j] + bandbits * ff_celt_freq_range[j]
514                       + FFMAX(0, remaining - (ff_celt_freq_bands[j] - ff_celt_freq_bands[f->start_band]));
515
516         /* a "do not skip" marker is only coded if the allocation is
517            above the chosen threshold */
518         if (allocation >= FFMAX(threshold[j], (f->channels + 1) << 3)) {
519             const int do_not_skip = f->coded_bands <= f->skip_band_floor;
520             ff_opus_rc_enc_log(rc, do_not_skip, 1);
521             if (do_not_skip)
522                 break;
523
524             total      += 1 << 3;
525             allocation -= 1 << 3;
526         }
527
528         /* the band is skipped, so reclaim its bits */
529         total -= f->pulses[j];
530         if (intensitystereo_bit) {
531             total -= intensitystereo_bit;
532             intensitystereo_bit = ff_celt_log2_frac[j - f->start_band];
533             total += intensitystereo_bit;
534         }
535
536         total += f->pulses[j] = (allocation >= f->channels << 3) ? f->channels << 3 : 0;
537     }
538
539     /* Encode stereo flags */
540     if (intensitystereo_bit) {
541         f->intensity_stereo = FFMIN(f->intensity_stereo, f->coded_bands);
542         ff_opus_rc_enc_uint(rc, f->intensity_stereo, f->coded_bands + 1 - f->start_band);
543     }
544     if (f->intensity_stereo <= f->start_band)
545         tbits_8ths += dualstereo_bit; /* no intensity stereo means no dual stereo */
546     else if (dualstereo_bit)
547         ff_opus_rc_enc_log(rc, f->dual_stereo, 1);
548
549     /* Supply the remaining bits in this frame to lower bands */
550     remaining = tbits_8ths - total;
551     bandbits  = remaining / (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
552     remaining -= bandbits * (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
553     for (i = f->start_band; i < f->coded_bands; i++) {
554         int bits = FFMIN(remaining, ff_celt_freq_range[i]);
555
556         f->pulses[i] += bits + bandbits * ff_celt_freq_range[i];
557         remaining    -= bits;
558     }
559
560     /* Finally determine the allocation */
561     for (i = f->start_band; i < f->coded_bands; i++) {
562         int N = ff_celt_freq_range[i] << f->size;
563         int prev_extra = extrabits;
564         f->pulses[i] += extrabits;
565
566         if (N > 1) {
567             int dof;        // degrees of freedom
568             int temp;       // dof * channels * log(dof)
569             int offset;     // fine energy quantization offset, i.e.
570                             // extra bits assigned over the standard
571                             // totalbits/dof
572             int fine_bits, max_bits;
573
574             extrabits = FFMAX(0, f->pulses[i] - cap[i]);
575             f->pulses[i] -= extrabits;
576
577             /* intensity stereo makes use of an extra degree of freedom */
578             dof = N * f->channels + (f->channels == 2 && N > 2 && !f->dual_stereo && i < f->intensity_stereo);
579             temp = dof * (ff_celt_log_freq_range[i] + (f->size << 3));
580             offset = (temp >> 1) - dof * CELT_FINE_OFFSET;
581             if (N == 2) /* dof=2 is the only case that doesn't fit the model */
582                 offset += dof << 1;
583
584             /* grant an additional bias for the first and second pulses */
585             if (f->pulses[i] + offset < 2 * (dof << 3))
586                 offset += temp >> 2;
587             else if (f->pulses[i] + offset < 3 * (dof << 3))
588                 offset += temp >> 3;
589
590             fine_bits = (f->pulses[i] + offset + (dof << 2)) / (dof << 3);
591             max_bits  = FFMIN((f->pulses[i] >> 3) >> (f->channels - 1), CELT_MAX_FINE_BITS);
592
593             max_bits  = FFMAX(max_bits, 0);
594
595             f->fine_bits[i] = av_clip(fine_bits, 0, max_bits);
596
597             /* if fine_bits was rounded down or capped,
598                give priority for the final fine energy pass */
599             f->fine_priority[i] = (f->fine_bits[i] * (dof << 3) >= f->pulses[i] + offset);
600
601             /* the remaining bits are assigned to PVQ */
602             f->pulses[i] -= f->fine_bits[i] << (f->channels - 1) << 3;
603         } else {
604             /* all bits go to fine energy except for the sign bit */
605             extrabits = FFMAX(0, f->pulses[i] - (f->channels << 3));
606             f->pulses[i] -= extrabits;
607             f->fine_bits[i] = 0;
608             f->fine_priority[i] = 1;
609         }
610
611         /* hand back a limited number of extra fine energy bits to this band */
612         if (extrabits > 0) {
613             int fineextra = FFMIN(extrabits >> (f->channels + 2),
614                                   CELT_MAX_FINE_BITS - f->fine_bits[i]);
615             f->fine_bits[i] += fineextra;
616
617             fineextra <<= f->channels + 2;
618             f->fine_priority[i] = (fineextra >= extrabits - prev_extra);
619             extrabits -= fineextra;
620         }
621     }
622     f->remaining = extrabits;
623
624     /* skipped bands dedicate all of their bits for fine energy */
625     for (; i < f->end_band; i++) {
626         f->fine_bits[i]     = f->pulses[i] >> (f->channels - 1) >> 3;
627         f->pulses[i]        = 0;
628         f->fine_priority[i] = f->fine_bits[i] < 1;
629     }
630 }
631
632 static void exp_quant_coarse(OpusRangeCoder *rc, CeltFrame *f,
633                              float last_energy[][CELT_MAX_BANDS], int intra)
634 {
635     int i, ch;
636     float alpha, beta, prev[2] = { 0, 0 };
637     const uint8_t *pmod = ff_celt_coarse_energy_dist[f->size][intra];
638
639     /* Inter is really just differential coding */
640     if (opus_rc_tell(rc) + 3 <= f->framebits)
641         ff_opus_rc_enc_log(rc, intra, 3);
642     else
643         intra = 0;
644
645     if (intra) {
646         alpha = 0.0f;
647         beta  = 1.0f - (4915.0f/32768.0f);
648     } else {
649         alpha = ff_celt_alpha_coef[f->size];
650         beta  = ff_celt_beta_coef[f->size];
651     }
652
653     for (i = f->start_band; i < f->end_band; i++) {
654         for (ch = 0; ch < f->channels; ch++) {
655             CeltBlock *block = &f->block[ch];
656             const int left = f->framebits - opus_rc_tell(rc);
657             const float last = FFMAX(-9.0f, last_energy[ch][i]);
658             float diff = block->energy[i] - prev[ch] - last*alpha;
659             int q_en = lrintf(diff);
660             if (left >= 15) {
661                 ff_opus_rc_enc_laplace(rc, &q_en, pmod[i << 1] << 7, pmod[(i << 1) + 1] << 6);
662             } else if (left >= 2) {
663                 q_en = av_clip(q_en, -1, 1);
664                 ff_opus_rc_enc_cdf(rc, 2*q_en + 3*(q_en < 0), ff_celt_model_energy_small);
665             } else if (left >= 1) {
666                 q_en = av_clip(q_en, -1, 0);
667                 ff_opus_rc_enc_log(rc, (q_en & 1), 1);
668             } else q_en = -1;
669
670             block->error_energy[i] = q_en - diff;
671             prev[ch] += beta * q_en;
672         }
673     }
674 }
675
676 static void celt_quant_coarse(OpusRangeCoder *rc, CeltFrame *f,
677                               float last_energy[][CELT_MAX_BANDS])
678 {
679     uint32_t inter, intra;
680     OPUS_RC_CHECKPOINT_SPAWN(rc);
681
682     exp_quant_coarse(rc, f, last_energy, 1);
683     intra = OPUS_RC_CHECKPOINT_BITS(rc);
684
685     OPUS_RC_CHECKPOINT_ROLLBACK(rc);
686
687     exp_quant_coarse(rc, f, last_energy, 0);
688     inter = OPUS_RC_CHECKPOINT_BITS(rc);
689
690     if (inter > intra) { /* Unlikely */
691         OPUS_RC_CHECKPOINT_ROLLBACK(rc);
692         exp_quant_coarse(rc, f, last_energy, 1);
693     }
694 }
695
696 static void celt_quant_fine(OpusRangeCoder *rc, CeltFrame *f)
697 {
698     int i, ch;
699     for (i = f->start_band; i < f->end_band; i++) {
700         if (!f->fine_bits[i])
701             continue;
702         for (ch = 0; ch < f->channels; ch++) {
703             CeltBlock *block = &f->block[ch];
704             int quant, lim = (1 << f->fine_bits[i]);
705             float offset, diff = 0.5f - block->error_energy[i];
706             quant = av_clip(floor(diff*lim), 0, lim - 1);
707             ff_opus_rc_put_raw(rc, quant, f->fine_bits[i]);
708             offset = 0.5f - ((quant + 0.5f) * (1 << (14 - f->fine_bits[i])) / 16384.0f);
709             block->error_energy[i] -= offset;
710         }
711     }
712 }
713
714 static void celt_quant_final(OpusEncContext *s, OpusRangeCoder *rc, CeltFrame *f)
715 {
716     int i, ch, priority;
717     for (priority = 0; priority < 2; priority++) {
718         for (i = f->start_band; i < f->end_band && (f->framebits - opus_rc_tell(rc)) >= f->channels; i++) {
719             if (f->fine_priority[i] != priority || f->fine_bits[i] >= CELT_MAX_FINE_BITS)
720                 continue;
721             for (ch = 0; ch < f->channels; ch++) {
722                 CeltBlock *block = &f->block[ch];
723                 const float err = block->error_energy[i];
724                 const float offset = 0.5f * (1 << (14 - f->fine_bits[i] - 1)) / 16384.0f;
725                 const int sign = FFABS(err + offset) < FFABS(err - offset);
726                 ff_opus_rc_put_raw(rc, sign, 1);
727                 block->error_energy[i] -= offset*(1 - 2*sign);
728             }
729         }
730     }
731 }
732
733 static void celt_quant_bands(OpusRangeCoder *rc, CeltFrame *f)
734 {
735     float lowband_scratch[8 * 22];
736     float norm[2 * 8 * 100];
737
738     int totalbits = (f->framebits << 3) - f->anticollapse_needed;
739
740     int update_lowband = 1;
741     int lowband_offset = 0;
742
743     int i, j;
744
745     for (i = f->start_band; i < f->end_band; i++) {
746         uint32_t cm[2] = { (1 << f->blocks) - 1, (1 << f->blocks) - 1 };
747         int band_offset = ff_celt_freq_bands[i] << f->size;
748         int band_size   = ff_celt_freq_range[i] << f->size;
749         float *X = f->block[0].coeffs + band_offset;
750         float *Y = (f->channels == 2) ? f->block[1].coeffs + band_offset : NULL;
751
752         int consumed = opus_rc_tell_frac(rc);
753         float *norm2 = norm + 8 * 100;
754         int effective_lowband = -1;
755         int b = 0;
756
757         /* Compute how many bits we want to allocate to this band */
758         if (i != f->start_band)
759             f->remaining -= consumed;
760         f->remaining2 = totalbits - consumed - 1;
761         if (i <= f->coded_bands - 1) {
762             int curr_balance = f->remaining / FFMIN(3, f->coded_bands-i);
763             b = av_clip_uintp2(FFMIN(f->remaining2 + 1, f->pulses[i] + curr_balance), 14);
764         }
765
766         if (ff_celt_freq_bands[i] - ff_celt_freq_range[i] >= ff_celt_freq_bands[f->start_band] &&
767             (update_lowband || lowband_offset == 0))
768             lowband_offset = i;
769
770         /* Get a conservative estimate of the collapse_mask's for the bands we're
771         going to be folding from. */
772         if (lowband_offset != 0 && (f->spread != CELT_SPREAD_AGGRESSIVE ||
773                                     f->blocks > 1 || f->tf_change[i] < 0)) {
774             int foldstart, foldend;
775
776             /* This ensures we never repeat spectral content within one band */
777             effective_lowband = FFMAX(ff_celt_freq_bands[f->start_band],
778                                       ff_celt_freq_bands[lowband_offset] - ff_celt_freq_range[i]);
779             foldstart = lowband_offset;
780             while (ff_celt_freq_bands[--foldstart] > effective_lowband);
781             foldend = lowband_offset - 1;
782             while (ff_celt_freq_bands[++foldend] < effective_lowband + ff_celt_freq_range[i]);
783
784             cm[0] = cm[1] = 0;
785             for (j = foldstart; j < foldend; j++) {
786                 cm[0] |= f->block[0].collapse_masks[j];
787                 cm[1] |= f->block[f->channels - 1].collapse_masks[j];
788             }
789         }
790
791         if (f->dual_stereo && i == f->intensity_stereo) {
792             /* Switch off dual stereo to do intensity */
793             f->dual_stereo = 0;
794             for (j = ff_celt_freq_bands[f->start_band] << f->size; j < band_offset; j++)
795                 norm[j] = (norm[j] + norm2[j]) / 2;
796         }
797
798         if (f->dual_stereo) {
799             cm[0] = f->pvq->encode_band(f->pvq, f, rc, i, X, NULL, band_size, b / 2, f->blocks,
800                                         effective_lowband != -1 ? norm + (effective_lowband << f->size) : NULL, f->size,
801                                         norm + band_offset, 0, 1.0f, lowband_scratch, cm[0]);
802
803             cm[1] = f->pvq->encode_band(f->pvq, f, rc, i, Y, NULL, band_size, b / 2, f->blocks,
804                                         effective_lowband != -1 ? norm2 + (effective_lowband << f->size) : NULL, f->size,
805                                         norm2 + band_offset, 0, 1.0f, lowband_scratch, cm[1]);
806         } else {
807             cm[0] = f->pvq->encode_band(f->pvq, f, rc, i, X, Y, band_size, b, f->blocks,
808                                         effective_lowband != -1 ? norm + (effective_lowband << f->size) : NULL, f->size,
809                                         norm + band_offset, 0, 1.0f, lowband_scratch, cm[0] | cm[1]);
810             cm[1] = cm[0];
811         }
812
813         f->block[0].collapse_masks[i]               = (uint8_t)cm[0];
814         f->block[f->channels - 1].collapse_masks[i] = (uint8_t)cm[1];
815         f->remaining += f->pulses[i] + consumed;
816
817         /* Update the folding position only as long as we have 1 bit/sample depth */
818         update_lowband = (b > band_size << 3);
819     }
820 }
821
822 static void celt_encode_frame(OpusEncContext *s, OpusRangeCoder *rc, CeltFrame *f)
823 {
824     int i, ch;
825
826     celt_frame_setup_input(s, f);
827     celt_apply_preemph_filter(s, f);
828     if (f->pfilter) {
829         /* Not implemented */
830     }
831     celt_frame_mdct(s, f);
832     celt_frame_map_norm_bands(s, f);
833
834     ff_opus_rc_enc_log(rc, f->silence, 15);
835
836     if (!f->start_band && opus_rc_tell(rc) + 16 <= f->framebits)
837         ff_opus_rc_enc_log(rc, f->pfilter, 1);
838
839     if (f->pfilter) {
840         /* Not implemented */
841     }
842
843     if (f->size && opus_rc_tell(rc) + 3 <= f->framebits)
844         ff_opus_rc_enc_log(rc, f->transient, 3);
845
846     celt_quant_coarse(rc, f, s->last_quantized_energy);
847     celt_enc_tf      (rc, f);
848     ff_celt_enc_bitalloc(rc, f);
849     celt_quant_fine  (rc, f);
850     celt_quant_bands (rc, f);
851
852     if (f->anticollapse_needed)
853         ff_opus_rc_put_raw(rc, f->anticollapse, 1);
854
855     celt_quant_final(s, rc, f);
856
857     for (ch = 0; ch < f->channels; ch++) {
858         CeltBlock *block = &f->block[ch];
859         for (i = 0; i < CELT_MAX_BANDS; i++)
860             s->last_quantized_energy[ch][i] = block->energy[i] + block->error_energy[i];
861     }
862 }
863
864 static void ff_opus_psy_process(OpusEncContext *s, int end, int *need_more)
865 {
866     int max_delay_samples = (s->options.max_delay_ms*s->avctx->sample_rate)/1000;
867     int max_bsize = FFMIN(OPUS_SAMPLES_TO_BLOCK_SIZE(max_delay_samples), CELT_BLOCK_960);
868
869     s->pkt_frames = 1;
870     s->pkt_framesize = max_bsize;
871     s->mode = OPUS_MODE_CELT;
872     s->bandwidth = OPUS_BANDWIDTH_FULLBAND;
873
874     *need_more = s->bufqueue.available*s->avctx->frame_size < (max_delay_samples + CELT_OVERLAP);
875     /* Don't request more if we start being flushed with NULL frames */
876     *need_more = !end && *need_more;
877 }
878
879 static void ff_opus_psy_celt_frame_setup(OpusEncContext *s, CeltFrame *f, int index)
880 {
881     int frame_size = OPUS_BLOCK_SIZE(s->pkt_framesize);
882
883     f->avctx = s->avctx;
884     f->dsp = s->dsp;
885     f->pvq = s->pvq;
886     f->start_band = (s->mode == OPUS_MODE_HYBRID) ? 17 : 0;
887     f->end_band = ff_celt_band_end[s->bandwidth];
888     f->channels = s->channels;
889     f->size = s->pkt_framesize;
890
891     /* Decisions */
892     f->silence = 0;
893     f->pfilter = 0;
894     f->transient = 0;
895     f->tf_select = 0;
896     f->anticollapse = 0;
897     f->alloc_trim = 5;
898     f->skip_band_floor = f->end_band;
899     f->intensity_stereo = f->end_band;
900     f->dual_stereo = 0;
901     f->spread = CELT_SPREAD_NORMAL;
902     memset(f->tf_change, 0, sizeof(int)*CELT_MAX_BANDS);
903     memset(f->alloc_boost, 0, sizeof(int)*CELT_MAX_BANDS);
904
905     f->blocks = f->transient ? frame_size/CELT_OVERLAP : 1;
906     f->framebits = FFALIGN(lrintf((double)s->avctx->bit_rate/(s->avctx->sample_rate/frame_size)), 8);
907 }
908
909 static void opus_packet_assembler(OpusEncContext *s, AVPacket *avpkt)
910 {
911     int i, offset, fsize_needed;
912
913     /* Write toc */
914     opus_gen_toc(s, avpkt->data, &offset, &fsize_needed);
915
916     for (i = 0; i < s->pkt_frames; i++) {
917         ff_opus_rc_enc_end(&s->rc[i], avpkt->data + offset, s->frame[i].framebits >> 3);
918         offset += s->frame[i].framebits >> 3;
919     }
920
921     avpkt->size = offset;
922 }
923
924 /* Used as overlap for the first frame and padding for the last encoded packet */
925 static AVFrame *spawn_empty_frame(OpusEncContext *s)
926 {
927     int i;
928     AVFrame *f = av_frame_alloc();
929     if (!f)
930         return NULL;
931     f->format         = s->avctx->sample_fmt;
932     f->nb_samples     = s->avctx->frame_size;
933     f->channel_layout = s->avctx->channel_layout;
934     if (av_frame_get_buffer(f, 4)) {
935         av_frame_free(&f);
936         return NULL;
937     }
938     for (i = 0; i < s->channels; i++) {
939         size_t bps = av_get_bytes_per_sample(f->format);
940         memset(f->extended_data[i], 0, bps*f->nb_samples);
941     }
942     return f;
943 }
944
945 static int opus_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
946                              const AVFrame *frame, int *got_packet_ptr)
947 {
948     OpusEncContext *s = avctx->priv_data;
949     int i, ret, frame_size, need_more, alloc_size = 0;
950
951     if (frame) { /* Add new frame to queue */
952         if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
953             return ret;
954         ff_bufqueue_add(avctx, &s->bufqueue, av_frame_clone(frame));
955     } else {
956         if (!s->afq.remaining_samples)
957             return 0; /* We've been flushed and there's nothing left to encode */
958     }
959
960     /* Run the psychoacoustic system */
961     ff_opus_psy_process(s, !frame, &need_more);
962
963     /* Get more samples for lookahead/encoding */
964     if (need_more)
965         return 0;
966
967     frame_size = OPUS_BLOCK_SIZE(s->pkt_framesize);
968
969     if (!frame) {
970         /* This can go negative, that's not a problem, we only pad if positive */
971         int pad_empty = s->pkt_frames*(frame_size/s->avctx->frame_size) - s->bufqueue.available + 1;
972         /* Pad with empty 2.5 ms frames to whatever framesize was decided,
973          * this should only happen at the very last flush frame. The frames
974          * allocated here will be freed (because they have no other references)
975          * after they get used by celt_frame_setup_input() */
976         for (i = 0; i < pad_empty; i++) {
977             AVFrame *empty = spawn_empty_frame(s);
978             if (!empty)
979                 return AVERROR(ENOMEM);
980             ff_bufqueue_add(avctx, &s->bufqueue, empty);
981         }
982     }
983
984     for (i = 0; i < s->pkt_frames; i++) {
985         ff_opus_rc_enc_init(&s->rc[i]);
986         ff_opus_psy_celt_frame_setup(s, &s->frame[i], i);
987         celt_encode_frame(s, &s->rc[i], &s->frame[i]);
988         alloc_size += s->frame[i].framebits >> 3;
989     }
990
991     /* Worst case toc + the frame lengths if needed */
992     alloc_size += 2 + s->pkt_frames*2;
993
994     if ((ret = ff_alloc_packet2(avctx, avpkt, alloc_size, 0)) < 0)
995         return ret;
996
997     /* Assemble packet */
998     opus_packet_assembler(s, avpkt);
999
1000     /* Remove samples from queue and skip if needed */
1001     ff_af_queue_remove(&s->afq, s->pkt_frames*frame_size, &avpkt->pts, &avpkt->duration);
1002     if (s->pkt_frames*frame_size > avpkt->duration) {
1003         uint8_t *side = av_packet_new_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
1004         if (!side)
1005             return AVERROR(ENOMEM);
1006         AV_WL32(&side[4], s->pkt_frames*frame_size - avpkt->duration + 120);
1007     }
1008
1009     *got_packet_ptr = 1;
1010
1011     return 0;
1012 }
1013
1014 static av_cold int opus_encode_end(AVCodecContext *avctx)
1015 {
1016     int i;
1017     OpusEncContext *s = avctx->priv_data;
1018
1019     for (i = 0; i < CELT_BLOCK_NB; i++)
1020         ff_mdct15_uninit(&s->mdct[i]);
1021
1022     ff_celt_pvq_uninit(&s->pvq);
1023     av_freep(&s->dsp);
1024     av_freep(&s->frame);
1025     av_freep(&s->rc);
1026     ff_af_queue_close(&s->afq);
1027     ff_bufqueue_discard_all(&s->bufqueue);
1028     av_freep(&avctx->extradata);
1029
1030     return 0;
1031 }
1032
1033 static av_cold int opus_encode_init(AVCodecContext *avctx)
1034 {
1035     int i, ch, ret;
1036     OpusEncContext *s = avctx->priv_data;
1037
1038     s->avctx = avctx;
1039     s->channels = avctx->channels;
1040
1041     /* Opus allows us to change the framesize on each packet (and each packet may
1042      * have multiple frames in it) but we can't change the codec's frame size on
1043      * runtime, so fix it to the lowest possible number of samples and use a queue
1044      * to accumulate AVFrames until we have enough to encode whatever the encoder
1045      * decides is the best */
1046     avctx->frame_size = 120;
1047     /* Initial padding will change if SILK is ever supported */
1048     avctx->initial_padding = 120;
1049
1050     if (!avctx->bit_rate) {
1051         int coupled = ff_opus_default_coupled_streams[s->channels - 1];
1052         avctx->bit_rate = coupled*(96000) + (s->channels - coupled*2)*(48000);
1053     } else if (avctx->bit_rate < 6000 || avctx->bit_rate > 255000 * s->channels) {
1054         int64_t clipped_rate = av_clip(avctx->bit_rate, 6000, 255000 * s->channels);
1055         av_log(avctx, AV_LOG_ERROR, "Unsupported bitrate %"PRId64" kbps, clipping to %"PRId64" kbps\n",
1056                avctx->bit_rate/1000, clipped_rate/1000);
1057         avctx->bit_rate = clipped_rate;
1058     }
1059
1060     /* Frame structs and range coder buffers */
1061     s->frame = av_malloc(OPUS_MAX_FRAMES_PER_PACKET*sizeof(CeltFrame));
1062     if (!s->frame)
1063         return AVERROR(ENOMEM);
1064     s->rc = av_malloc(OPUS_MAX_FRAMES_PER_PACKET*sizeof(OpusRangeCoder));
1065     if (!s->rc)
1066         return AVERROR(ENOMEM);
1067
1068     /* Extradata */
1069     avctx->extradata_size = 19;
1070     avctx->extradata = av_malloc(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
1071     if (!avctx->extradata)
1072         return AVERROR(ENOMEM);
1073     opus_write_extradata(avctx);
1074
1075     ff_af_queue_init(avctx, &s->afq);
1076
1077     if ((ret = ff_celt_pvq_init(&s->pvq)) < 0)
1078         return ret;
1079
1080     if (!(s->dsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT)))
1081         return AVERROR(ENOMEM);
1082
1083     /* I have no idea why a base scaling factor of 68 works, could be the twiddles */
1084     for (i = 0; i < CELT_BLOCK_NB; i++)
1085         if ((ret = ff_mdct15_init(&s->mdct[i], 0, i + 3, 68 << (CELT_BLOCK_NB - 1 - i))))
1086             return AVERROR(ENOMEM);
1087
1088     for (i = 0; i < OPUS_MAX_FRAMES_PER_PACKET; i++) {
1089         s->frame[i].block[0].emph_coeff = s->frame[i].block[1].emph_coeff = 0.0f;
1090         s->frame[i].seed = 0;
1091     }
1092
1093     /* Zero out previous energy (matters for inter first frame) */
1094     for (ch = 0; ch < s->channels; ch++)
1095         for (i = 0; i < CELT_MAX_BANDS; i++)
1096             s->last_quantized_energy[ch][i] = 0.0f;
1097
1098     /* Allocate an empty frame to use as overlap for the first frame of audio */
1099     ff_bufqueue_add(avctx, &s->bufqueue, spawn_empty_frame(s));
1100     if (!ff_bufqueue_peek(&s->bufqueue, 0))
1101         return AVERROR(ENOMEM);
1102
1103     return 0;
1104 }
1105
1106 #define OPUSENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1107 static const AVOption opusenc_options[] = {
1108     { "opus_delay", "Maximum delay (and lookahead) in milliseconds", offsetof(OpusEncContext, options.max_delay_ms), AV_OPT_TYPE_FLOAT, { .dbl = OPUS_MAX_LOOKAHEAD }, 2.5f, OPUS_MAX_LOOKAHEAD, OPUSENC_FLAGS },
1109     { NULL },
1110 };
1111
1112 static const AVClass opusenc_class = {
1113     .class_name = "Opus encoder",
1114     .item_name  = av_default_item_name,
1115     .option     = opusenc_options,
1116     .version    = LIBAVUTIL_VERSION_INT,
1117 };
1118
1119 static const AVCodecDefault opusenc_defaults[] = {
1120     { "b", "0" },
1121     { "compression_level", "10" },
1122     { NULL },
1123 };
1124
1125 AVCodec ff_opus_encoder = {
1126     .name           = "opus",
1127     .long_name      = NULL_IF_CONFIG_SMALL("Opus"),
1128     .type           = AVMEDIA_TYPE_AUDIO,
1129     .id             = AV_CODEC_ID_OPUS,
1130     .defaults       = opusenc_defaults,
1131     .priv_class     = &opusenc_class,
1132     .priv_data_size = sizeof(OpusEncContext),
1133     .init           = opus_encode_init,
1134     .encode2        = opus_encode_frame,
1135     .close          = opus_encode_end,
1136     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP,
1137     .capabilities   = AV_CODEC_CAP_EXPERIMENTAL | AV_CODEC_CAP_SMALL_LAST_FRAME | AV_CODEC_CAP_DELAY,
1138     .supported_samplerates = (const int []){ 48000, 0 },
1139     .channel_layouts = (const uint64_t []){ AV_CH_LAYOUT_MONO,
1140                                             AV_CH_LAYOUT_STEREO, 0 },
1141     .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
1142                                                      AV_SAMPLE_FMT_NONE },
1143 };