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