3 * Copyright (c) 2017 Rostislav Pehlivanov <atomnuker@gmail.com>
5 * This file is part of FFmpeg.
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.
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.
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
22 #include "opus_celt.h"
26 #include "libavutil/float_dsp.h"
27 #include "libavutil/opt.h"
29 #include "bytestream.h"
30 #include "audio_frame_queue.h"
32 /* Determines the maximum delay the psychoacoustic system will use for lookahead */
33 #define FF_BUFQUEUE_SIZE 145
34 #include "libavfilter/bufferqueue.h"
36 #define OPUS_MAX_LOOKAHEAD ((FF_BUFQUEUE_SIZE - 1)*2.5f)
38 #define OPUS_MAX_CHANNELS 2
40 /* 120 ms / 2.5 ms = 48 frames (extremely improbable, but the encoder'll work) */
41 #define OPUS_MAX_FRAMES_PER_PACKET 48
43 #define OPUS_BLOCK_SIZE(x) (2 * 15 * (1 << ((x) + 2)))
45 #define OPUS_SAMPLES_TO_BLOCK_SIZE(x) (ff_log2((x) / (2 * 15)) - 2)
47 typedef struct OpusEncOptions {
51 typedef struct OpusEncContext {
53 OpusEncOptions options;
54 AVCodecContext *avctx;
56 AVFloatDSPContext *dsp;
57 MDCT15Context *mdct[CELT_BLOCK_NB];
59 struct FFBufQueue bufqueue;
62 enum OpusBandwidth bandwidth;
71 /* Actual energy the decoder will have */
72 float last_quantized_energy[OPUS_MAX_CHANNELS][CELT_MAX_BANDS];
74 DECLARE_ALIGNED(32, float, scratch)[2048];
77 static void opus_write_extradata(AVCodecContext *avctx)
79 uint8_t *bs = avctx->extradata;
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 */
90 static int opus_gen_toc(OpusEncContext *s, uint8_t *toc, int *size, int *fsize_needed)
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 */
103 int cfg = toc_cfg[s->pkt_framesize][s->mode][s->bandwidth];
107 if (s->pkt_frames == 2) { /* 2 packets */
108 if (s->frame[0].framebits == s->frame[1].framebits) { /* same size */
110 } else { /* different size */
112 *fsize_needed = 1; /* put frame sizes in the packet */
114 } else if (s->pkt_frames > 2) {
118 tmp |= (s->channels > 1) << 2; /* Stereo or mono */
119 tmp |= (cfg - 1) << 3; /* codec configuration */
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 */
128 *size = 1 + extended_toc;
132 static void celt_frame_setup_input(OpusEncContext *s, CeltFrame *f)
136 const int subframesize = s->avctx->frame_size;
137 int subframes = OPUS_BLOCK_SIZE(s->pkt_framesize) / subframesize;
139 cur = ff_bufqueue_get(&s->bufqueue);
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);
150 for (sf = 0; sf < subframes; sf++) {
151 if (sf != (subframes - 1))
152 cur = ff_bufqueue_get(&s->bufqueue);
154 cur = ff_bufqueue_peek(&s->bufqueue, 0);
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);
166 /* Last frame isn't popped off and freed yet - we need it for overlap */
167 if (sf != (subframes - 1))
172 /* Apply the pre emphasis filter */
173 static void celt_apply_preemph_filter(OpusEncContext *s, CeltFrame *f)
176 const int subframesize = s->avctx->frame_size;
177 const int subframes = OPUS_BLOCK_SIZE(s->pkt_framesize) / subframesize;
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;
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;
201 if (sf != (subframes - 1))
207 /* Create the window and do the mdct */
208 static void celt_frame_mdct(OpusEncContext *s, CeltFrame *f)
211 float *win = s->scratch;
213 /* I think I can use s->dsp->vector_fmul_window for transients at least */
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];
225 s->mdct[0]->mdct(s->mdct[0], b->coeffs + t, win, f->blocks);
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];
234 memset(win, 0, wlen*sizeof(float));
236 memcpy(&win[lap_dst + CELT_OVERLAP], b->samples, rwin*sizeof(float));
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);
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];
247 s->mdct[f->size]->mdct(s->mdct[f->size], b->coeffs, win, 1);
252 /* Fills the bands and normalizes them */
253 static void celt_frame_map_norm_bands(OpusEncContext *s, CeltFrame *f)
257 for (ch = 0; ch < f->channels; ch++) {
258 CeltBlock *block = &f->block[ch];
259 for (i = 0; i < CELT_MAX_BANDS; i++) {
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];
265 for (j = 0; j < band_size; j++)
266 ener += coeffs[j]*coeffs[j];
268 block->lin_energy[i] = sqrtf(ener) + FLT_EPSILON;
269 ener = 1.0f/block->lin_energy[i];
271 for (j = 0; j < band_size; j++)
274 block->energy[i] = log2f(block->lin_energy[i]) - ff_celt_mean_energy[i];
276 /* CELT_ENERGY_SILENCE is what the decoder uses and its not -infinity */
277 block->energy[i] = FFMAX(block->energy[i], CELT_ENERGY_SILENCE);
282 static void celt_enc_tf(OpusRangeCoder *rc, CeltFrame *f)
284 int i, tf_select = 0, diff = 0, tf_changed = 0, tf_select_needed;
285 int bits = f->transient ? 2 : 4;
287 tf_select_needed = ((f->size && (opus_rc_tell(rc) + bits + 1) <= f->framebits));
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);
296 bits = f->transient ? 4 : 5;
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;
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]];
309 static void ff_celt_enc_bitalloc(OpusRangeCoder *rc, CeltFrame *f)
311 int i, j, low, high, total, done, bandbits, remaining, tbits_8ths;
312 int skip_startband = f->start_band;
314 int intensitystereo_bit = 0;
315 int dualstereo_bit = 0;
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];
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);
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;
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];
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;
347 while (opus_rc_tell_frac(rc) + (b_dynalloc << 3) < tbits_8ths && boost[i] < cap[i]) {
348 int is_boost = boost_amount--;
350 ff_opus_rc_enc_log(rc, is_boost, b_dynalloc);
355 tbits_8ths -= quanta;
361 dynalloc = FFMAX(2, dynalloc - 1);
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);
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;
375 /* Band skip bit reservation */
376 if (tbits_8ths >= 1 << 3)
378 tbits_8ths -= skip_bit;
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;
390 intensitystereo_bit = 0;
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;
401 /* PVQ minimum allocation threshold, below this value the band is
403 threshold[i] = FFMAX(3 * ff_celt_freq_range[i] << duration >> 4,
406 trim_offset[i] = trim * (band << scale) >> 6;
408 if (ff_celt_freq_range[i] << f->size == 1)
409 trim_offset[i] -= f->channels << 3;
414 high = CELT_VECTORS - 1;
415 while (low <= high) {
416 int center = (low + high) >> 1;
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;
424 bandbits = FFMAX(0, bandbits + trim_offset[i]);
425 bandbits += boost[i];
427 if (bandbits >= threshold[i] || done) {
429 total += FFMIN(bandbits, cap[i]);
430 } else if (bandbits >= f->channels << 3)
431 total += f->channels << 3;
434 if (total > tbits_8ths)
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;
450 bits1[i] = FFMAX(0, bits1[i] + trim_offset[i]);
452 bits2[i] = FFMAX(0, bits2[i] + trim_offset[i]);
454 bits1[i] += boost[i];
455 bits2[i] += boost[i];
459 bits2[i] = FFMAX(0, bits2[i] - bits1[i]);
464 high = 1 << CELT_ALLOC_STEPS;
465 for (i = 0; i < CELT_ALLOC_STEPS; i++) {
466 int center = (low + high) >> 1;
469 for (j = f->end_band - 1; j >= f->start_band; j--) {
470 bandbits = bits1[j] + (center * bits2[j] >> CELT_ALLOC_STEPS);
472 if (bandbits >= threshold[j] || done) {
474 total += FFMIN(bandbits, cap[j]);
475 } else if (bandbits >= f->channels << 3)
476 total += f->channels << 3;
478 if (total > tbits_8ths)
486 for (i = f->end_band - 1; i >= f->start_band; i--) {
487 bandbits = bits1[i] + (low * bits2[i] >> CELT_ALLOC_STEPS);
489 if (bandbits >= threshold[i] || done)
492 bandbits = (bandbits >= f->channels << 3) ?
493 f->channels << 3 : 0;
495 bandbits = FFMIN(bandbits, cap[i]);
496 f->pulses[i] = bandbits;
501 for (f->coded_bands = f->end_band; ; f->coded_bands--) {
503 j = f->coded_bands - 1;
505 if (j == skip_startband) {
506 /* all remaining bands are not skipped */
507 tbits_8ths += skip_bit;
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]));
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);
527 allocation -= 1 << 3;
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;
538 total += f->pulses[j] = (allocation >= f->channels << 3) ? f->channels << 3 : 0;
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);
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);
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]);
558 f->pulses[i] += bits + bandbits * ff_celt_freq_range[i];
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;
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
574 int fine_bits, max_bits;
576 extrabits = FFMAX(0, f->pulses[i] - cap[i]);
577 f->pulses[i] -= extrabits;
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 */
586 /* grant an additional bias for the first and second pulses */
587 if (f->pulses[i] + offset < 2 * (dof << 3))
589 else if (f->pulses[i] + offset < 3 * (dof << 3))
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);
595 max_bits = FFMAX(max_bits, 0);
597 f->fine_bits[i] = av_clip(fine_bits, 0, max_bits);
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);
603 /* the remaining bits are assigned to PVQ */
604 f->pulses[i] -= f->fine_bits[i] << (f->channels - 1) << 3;
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;
610 f->fine_priority[i] = 1;
613 /* hand back a limited number of extra fine energy bits to this band */
615 int fineextra = FFMIN(extrabits >> (f->channels + 2),
616 CELT_MAX_FINE_BITS - f->fine_bits[i]);
617 f->fine_bits[i] += fineextra;
619 fineextra <<= f->channels + 2;
620 f->fine_priority[i] = (fineextra >= extrabits - prev_extra);
621 extrabits -= fineextra;
624 f->remaining = extrabits;
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;
630 f->fine_priority[i] = f->fine_bits[i] < 1;
634 static void exp_quant_coarse(OpusRangeCoder *rc, CeltFrame *f,
635 float last_energy[][CELT_MAX_BANDS], int intra)
638 float alpha, beta, prev[2] = { 0, 0 };
639 const uint8_t *pmod = ff_celt_coarse_energy_dist[f->size][intra];
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);
649 beta = 1.0f - 4915.0f/32768.0f;
651 alpha = ff_celt_alpha_coef[f->size];
652 beta = 1.0f - ff_celt_beta_coef[f->size];
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);
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);
672 block->error_energy[i] = q_en - diff;
673 prev[ch] += beta * q_en;
678 static void celt_quant_coarse(OpusRangeCoder *rc, CeltFrame *f,
679 float last_energy[][CELT_MAX_BANDS])
681 uint32_t inter, intra;
682 OPUS_RC_CHECKPOINT_SPAWN(rc);
684 exp_quant_coarse(rc, f, last_energy, 1);
685 intra = OPUS_RC_CHECKPOINT_BITS(rc);
687 OPUS_RC_CHECKPOINT_ROLLBACK(rc);
689 exp_quant_coarse(rc, f, last_energy, 0);
690 inter = OPUS_RC_CHECKPOINT_BITS(rc);
692 if (inter > intra) { /* Unlikely */
693 OPUS_RC_CHECKPOINT_ROLLBACK(rc);
694 exp_quant_coarse(rc, f, last_energy, 1);
698 static void celt_quant_fine(OpusRangeCoder *rc, CeltFrame *f)
701 for (i = f->start_band; i < f->end_band; i++) {
702 if (!f->fine_bits[i])
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;
716 static void celt_quant_final(OpusEncContext *s, OpusRangeCoder *rc, CeltFrame *f)
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)
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);
735 static void celt_quant_bands(OpusRangeCoder *rc, CeltFrame *f)
737 float lowband_scratch[8 * 22];
738 float norm[2 * 8 * 100];
740 int totalbits = (f->framebits << 3) - f->anticollapse_needed;
742 int update_lowband = 1;
743 int lowband_offset = 0;
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;
754 int consumed = opus_rc_tell_frac(rc);
755 float *norm2 = norm + 8 * 100;
756 int effective_lowband = -1;
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);
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))
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;
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]);
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];
793 if (f->dual_stereo && i == f->intensity_stereo) {
794 /* Switch off dual stereo to do intensity */
796 for (j = ff_celt_freq_bands[f->start_band] << f->size; j < band_offset; j++)
797 norm[j] = (norm[j] + norm2[j]) / 2;
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]);
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]);
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]);
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;
819 /* Update the folding position only as long as we have 1 bit/sample depth */
820 update_lowband = (b > band_size << 3);
824 static void celt_encode_frame(OpusEncContext *s, OpusRangeCoder *rc, CeltFrame *f)
828 celt_frame_setup_input(s, f);
829 celt_apply_preemph_filter(s, f);
831 /* Not implemented */
833 celt_frame_mdct(s, f);
834 celt_frame_map_norm_bands(s, f);
836 ff_opus_rc_enc_log(rc, f->silence, 15);
838 if (!f->start_band && opus_rc_tell(rc) + 16 <= f->framebits)
839 ff_opus_rc_enc_log(rc, f->pfilter, 1);
842 /* Not implemented */
845 if (f->size && opus_rc_tell(rc) + 3 <= f->framebits)
846 ff_opus_rc_enc_log(rc, f->transient, 3);
848 celt_quant_coarse(rc, f, s->last_quantized_energy);
850 ff_celt_enc_bitalloc(rc, f);
851 celt_quant_fine (rc, f);
852 celt_quant_bands (rc, f);
854 if (f->anticollapse_needed)
855 ff_opus_rc_put_raw(rc, f->anticollapse, 1);
857 celt_quant_final(s, rc, f);
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];
866 static void ff_opus_psy_process(OpusEncContext *s, int end, int *need_more)
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);
872 s->pkt_framesize = max_bsize;
873 s->mode = OPUS_MODE_CELT;
874 s->bandwidth = OPUS_BANDWIDTH_FULLBAND;
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;
881 static void ff_opus_psy_celt_frame_setup(OpusEncContext *s, CeltFrame *f, int index)
883 int frame_size = OPUS_BLOCK_SIZE(s->pkt_framesize);
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;
900 f->skip_band_floor = f->end_band;
901 f->intensity_stereo = f->end_band;
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);
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);
911 static void opus_packet_assembler(OpusEncContext *s, AVPacket *avpkt)
913 int i, offset, fsize_needed;
916 opus_gen_toc(s, avpkt->data, &offset, &fsize_needed);
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;
923 avpkt->size = offset;
926 /* Used as overlap for the first frame and padding for the last encoded packet */
927 static AVFrame *spawn_empty_frame(OpusEncContext *s)
930 AVFrame *f = av_frame_alloc();
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)) {
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);
947 static int opus_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
948 const AVFrame *frame, int *got_packet_ptr)
950 OpusEncContext *s = avctx->priv_data;
951 int i, ret, frame_size, need_more, alloc_size = 0;
953 if (frame) { /* Add new frame to queue */
954 if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
956 ff_bufqueue_add(avctx, &s->bufqueue, av_frame_clone(frame));
958 if (!s->afq.remaining_samples)
959 return 0; /* We've been flushed and there's nothing left to encode */
962 /* Run the psychoacoustic system */
963 ff_opus_psy_process(s, !frame, &need_more);
965 /* Get more samples for lookahead/encoding */
969 frame_size = OPUS_BLOCK_SIZE(s->pkt_framesize);
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);
981 return AVERROR(ENOMEM);
982 ff_bufqueue_add(avctx, &s->bufqueue, empty);
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;
993 /* Worst case toc + the frame lengths if needed */
994 alloc_size += 2 + s->pkt_frames*2;
996 if ((ret = ff_alloc_packet2(avctx, avpkt, alloc_size, 0)) < 0)
999 /* Assemble packet */
1000 opus_packet_assembler(s, avpkt);
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);
1007 return AVERROR(ENOMEM);
1008 AV_WL32(&side[4], s->pkt_frames*frame_size - avpkt->duration + 120);
1011 *got_packet_ptr = 1;
1016 static av_cold int opus_encode_end(AVCodecContext *avctx)
1019 OpusEncContext *s = avctx->priv_data;
1021 for (i = 0; i < CELT_BLOCK_NB; i++)
1022 ff_mdct15_uninit(&s->mdct[i]);
1024 ff_celt_pvq_uninit(&s->pvq);
1026 av_freep(&s->frame);
1028 ff_af_queue_close(&s->afq);
1029 ff_bufqueue_discard_all(&s->bufqueue);
1030 av_freep(&avctx->extradata);
1035 static av_cold int opus_encode_init(AVCodecContext *avctx)
1038 OpusEncContext *s = avctx->priv_data;
1041 s->channels = avctx->channels;
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;
1052 avctx->cutoff = !avctx->cutoff ? 20000 : avctx->cutoff;
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;
1064 /* Frame structs and range coder buffers */
1065 s->frame = av_malloc(OPUS_MAX_FRAMES_PER_PACKET*sizeof(CeltFrame));
1067 return AVERROR(ENOMEM);
1068 s->rc = av_malloc(OPUS_MAX_FRAMES_PER_PACKET*sizeof(OpusRangeCoder));
1070 return AVERROR(ENOMEM);
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);
1079 ff_af_queue_init(avctx, &s->afq);
1081 if ((ret = ff_celt_pvq_init(&s->pvq)) < 0)
1084 if (!(s->dsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT)))
1085 return AVERROR(ENOMEM);
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);
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;
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;
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);
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 },
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,
1123 static const AVCodecDefault opusenc_defaults[] = {
1125 { "compression_level", "10" },
1129 AVCodec ff_opus_encoder = {
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 },