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];
58 struct FFBufQueue bufqueue;
61 enum OpusBandwidth bandwidth;
70 /* Actual energy the decoder will have */
71 float last_quantized_energy[OPUS_MAX_CHANNELS][CELT_MAX_BANDS];
73 DECLARE_ALIGNED(32, float, scratch)[2048];
76 static void opus_write_extradata(AVCodecContext *avctx)
78 uint8_t *bs = avctx->extradata;
80 bytestream_put_buffer(&bs, "OpusHead", 8);
81 bytestream_put_byte (&bs, 0x1);
82 bytestream_put_byte (&bs, avctx->channels);
83 bytestream_put_le16 (&bs, avctx->initial_padding);
84 bytestream_put_le32 (&bs, avctx->sample_rate);
85 bytestream_put_le16 (&bs, 0x0);
86 bytestream_put_byte (&bs, 0x0); /* Default layout */
89 static int opus_gen_toc(OpusEncContext *s, uint8_t *toc, int *size, int *fsize_needed)
91 int i, tmp = 0x0, extended_toc = 0;
92 static const int toc_cfg[][OPUS_MODE_NB][OPUS_BANDWITH_NB] = {
93 /* Silk Hybrid Celt Layer */
94 /* NB MB WB SWB FB NB MB WB SWB FB NB MB WB SWB FB Bandwidth */
95 { { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 17, 0, 21, 25, 29 } }, /* 2.5 ms */
96 { { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 18, 0, 22, 26, 30 } }, /* 5 ms */
97 { { 1, 5, 9, 0, 0 }, { 0, 0, 0, 13, 15 }, { 19, 0, 23, 27, 31 } }, /* 10 ms */
98 { { 2, 6, 10, 0, 0 }, { 0, 0, 0, 14, 16 }, { 20, 0, 24, 28, 32 } }, /* 20 ms */
99 { { 3, 7, 11, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }, /* 40 ms */
100 { { 4, 8, 12, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }, /* 60 ms */
102 int cfg = toc_cfg[s->pkt_framesize][s->mode][s->bandwidth];
106 if (s->pkt_frames == 2) { /* 2 packets */
107 if (s->frame[0].framebits == s->frame[1].framebits) { /* same size */
109 } else { /* different size */
111 *fsize_needed = 1; /* put frame sizes in the packet */
113 } else if (s->pkt_frames > 2) {
117 tmp |= (s->channels > 1) << 2; /* Stereo or mono */
118 tmp |= (cfg - 1) << 3; /* codec configuration */
121 for (i = 0; i < (s->pkt_frames - 1); i++)
122 *fsize_needed |= (s->frame[i].framebits != s->frame[i + 1].framebits);
123 tmp = (*fsize_needed) << 7; /* vbr flag */
124 tmp |= s->pkt_frames; /* frame number - can be 0 as well */
127 *size = 1 + extended_toc;
131 static void celt_frame_setup_input(OpusEncContext *s, CeltFrame *f)
135 const int subframesize = s->avctx->frame_size;
136 int subframes = OPUS_BLOCK_SIZE(s->pkt_framesize) / subframesize;
138 cur = ff_bufqueue_get(&s->bufqueue);
140 for (ch = 0; ch < f->channels; ch++) {
141 CeltBlock *b = &f->block[ch];
142 const void *input = cur->extended_data[ch];
143 size_t bps = av_get_bytes_per_sample(cur->format);
144 memcpy(b->overlap, input, bps*cur->nb_samples);
149 for (sf = 0; sf < subframes; sf++) {
150 if (sf != (subframes - 1))
151 cur = ff_bufqueue_get(&s->bufqueue);
153 cur = ff_bufqueue_peek(&s->bufqueue, 0);
155 for (ch = 0; ch < f->channels; ch++) {
156 CeltBlock *b = &f->block[ch];
157 const void *input = cur->extended_data[ch];
158 const size_t bps = av_get_bytes_per_sample(cur->format);
159 const size_t left = (subframesize - cur->nb_samples)*bps;
160 const size_t len = FFMIN(subframesize, cur->nb_samples)*bps;
161 memcpy(&b->samples[sf*subframesize], input, len);
162 memset(&b->samples[cur->nb_samples], 0, left);
165 /* Last frame isn't popped off and freed yet - we need it for overlap */
166 if (sf != (subframes - 1))
171 /* Apply the pre emphasis filter */
172 static void celt_apply_preemph_filter(OpusEncContext *s, CeltFrame *f)
175 const int subframesize = s->avctx->frame_size;
176 const int subframes = OPUS_BLOCK_SIZE(s->pkt_framesize) / subframesize;
179 for (ch = 0; ch < f->channels; ch++) {
180 CeltBlock *b = &f->block[ch];
181 float m = b->emph_coeff;
182 for (i = 0; i < CELT_OVERLAP; i++) {
183 float sample = b->overlap[i];
184 b->overlap[i] = sample - m;
185 m = sample * CELT_EMPH_COEFF;
190 /* Filter the samples but do not update the last subframe's coeff - overlap ^^^ */
191 for (sf = 0; sf < subframes; sf++) {
192 for (ch = 0; ch < f->channels; ch++) {
193 CeltBlock *b = &f->block[ch];
194 float m = b->emph_coeff;
195 for (i = 0; i < subframesize; i++) {
196 float sample = b->samples[sf*subframesize + i];
197 b->samples[sf*subframesize + i] = sample - m;
198 m = sample * CELT_EMPH_COEFF;
200 if (sf != (subframes - 1))
206 /* Create the window and do the mdct */
207 static void celt_frame_mdct(OpusEncContext *s, CeltFrame *f)
210 float *win = s->scratch;
212 /* I think I can use s->dsp->vector_fmul_window for transients at least */
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 for (i = 0; i < CELT_OVERLAP; i++) {
220 win[ i] = src1[i]*ff_celt_window[i];
221 win[CELT_OVERLAP + i] = src2[i]*ff_celt_window[CELT_OVERLAP - i - 1];
224 s->mdct[0]->mdct(s->mdct[0], b->coeffs + t, win, f->blocks);
228 int blk_len = OPUS_BLOCK_SIZE(f->size), wlen = OPUS_BLOCK_SIZE(f->size + 1);
229 int rwin = blk_len - CELT_OVERLAP, lap_dst = (wlen - blk_len - CELT_OVERLAP) >> 1;
230 for (ch = 0; ch < f->channels; ch++) {
231 CeltBlock *b = &f->block[ch];
233 memset(win, 0, wlen*sizeof(float));
235 memcpy(&win[lap_dst + CELT_OVERLAP], b->samples, rwin*sizeof(float));
237 /* Alignment fucks me over */
238 //s->dsp->vector_fmul(&dst[lap_dst], b->overlap, ff_celt_window, CELT_OVERLAP);
239 //s->dsp->vector_fmul_reverse(&dst[lap_dst + blk_len - CELT_OVERLAP], b->samples, ff_celt_window, CELT_OVERLAP);
241 for (i = 0; i < CELT_OVERLAP; i++) {
242 win[lap_dst + i] = b->overlap[i] *ff_celt_window[i];
243 win[lap_dst + blk_len + i] = b->samples[rwin + i]*ff_celt_window[CELT_OVERLAP - i - 1];
246 s->mdct[f->size]->mdct(s->mdct[f->size], b->coeffs, win, 1);
251 /* Fills the bands and normalizes them */
252 static void celt_frame_map_norm_bands(OpusEncContext *s, CeltFrame *f)
256 for (ch = 0; ch < f->channels; ch++) {
257 CeltBlock *block = &f->block[ch];
258 for (i = 0; i < CELT_MAX_BANDS; i++) {
260 int band_offset = ff_celt_freq_bands[i] << f->size;
261 int band_size = ff_celt_freq_range[i] << f->size;
262 float *coeffs = &block->coeffs[band_offset];
264 for (j = 0; j < band_size; j++)
265 ener += coeffs[j]*coeffs[j];
267 block->lin_energy[i] = sqrtf(ener) + FLT_EPSILON;
268 ener = 1.0f/block->lin_energy[i];
270 for (j = 0; j < band_size; j++)
273 block->energy[i] = log2f(block->lin_energy[i]) - ff_celt_mean_energy[i];
275 /* CELT_ENERGY_SILENCE is what the decoder uses and its not -infinity */
276 block->energy[i] = FFMAX(block->energy[i], CELT_ENERGY_SILENCE);
281 static void celt_enc_tf(OpusRangeCoder *rc, CeltFrame *f)
283 int i, tf_select = 0, diff = 0, tf_changed = 0, tf_select_needed;
284 int bits = f->transient ? 2 : 4;
286 tf_select_needed = ((f->size && (opus_rc_tell(rc) + bits + 1) <= f->framebits));
288 for (i = f->start_band; i < f->end_band; i++) {
289 if ((opus_rc_tell(rc) + bits + tf_select_needed) <= f->framebits) {
290 const int tbit = (diff ^ 1) == f->tf_change[i];
291 ff_opus_rc_enc_log(rc, tbit, bits);
295 bits = f->transient ? 4 : 5;
298 if (tf_select_needed && ff_celt_tf_select[f->size][f->transient][0][tf_changed] !=
299 ff_celt_tf_select[f->size][f->transient][1][tf_changed]) {
300 ff_opus_rc_enc_log(rc, f->tf_select, 1);
301 tf_select = f->tf_select;
304 for (i = f->start_band; i < f->end_band; i++)
305 f->tf_change[i] = ff_celt_tf_select[f->size][f->transient][tf_select][f->tf_change[i]];
308 static void ff_celt_enc_bitalloc(OpusRangeCoder *rc, CeltFrame *f)
310 int i, j, low, high, total, done, bandbits, remaining, tbits_8ths;
311 int skip_startband = f->start_band;
313 int intensitystereo_bit = 0;
314 int dualstereo_bit = 0;
319 int boost[CELT_MAX_BANDS];
320 int trim_offset[CELT_MAX_BANDS];
321 int threshold[CELT_MAX_BANDS];
322 int bits1[CELT_MAX_BANDS];
323 int bits2[CELT_MAX_BANDS];
325 /* Tell the spread to the decoder */
326 if (opus_rc_tell(rc) + 4 <= f->framebits)
327 ff_opus_rc_enc_cdf(rc, f->spread, ff_celt_model_spread);
329 /* Generate static allocation caps */
330 for (i = 0; i < CELT_MAX_BANDS; i++) {
331 cap[i] = (ff_celt_static_caps[f->size][f->channels - 1][i] + 64)
332 * ff_celt_freq_range[i] << (f->channels - 1) << f->size >> 2;
336 tbits_8ths = f->framebits << 3;
337 for (i = f->start_band; i < f->end_band; i++) {
338 int quanta, b_dynalloc, boost_amount = f->alloc_boost[i];
342 quanta = ff_celt_freq_range[i] << (f->channels - 1) << f->size;
343 quanta = FFMIN(quanta << 3, FFMAX(6 << 3, quanta));
344 b_dynalloc = dynalloc;
346 while (opus_rc_tell_frac(rc) + (b_dynalloc << 3) < tbits_8ths && boost[i] < cap[i]) {
347 int is_boost = boost_amount--;
349 ff_opus_rc_enc_log(rc, is_boost, b_dynalloc);
354 tbits_8ths -= quanta;
360 dynalloc = FFMAX(2, dynalloc - 1);
363 /* Put allocation trim */
364 if (opus_rc_tell_frac(rc) + (6 << 3) <= tbits_8ths)
365 ff_opus_rc_enc_cdf(rc, f->alloc_trim, ff_celt_model_alloc_trim);
367 /* Anti-collapse bit reservation */
368 tbits_8ths = (f->framebits << 3) - opus_rc_tell_frac(rc) - 1;
369 f->anticollapse_needed = 0;
370 if (f->transient && f->size >= 2 && tbits_8ths >= ((f->size + 2) << 3))
371 f->anticollapse_needed = 1 << 3;
372 tbits_8ths -= f->anticollapse_needed;
374 /* Band skip bit reservation */
375 if (tbits_8ths >= 1 << 3)
377 tbits_8ths -= skip_bit;
379 /* Intensity/dual stereo bit reservation */
380 if (f->channels == 2) {
381 intensitystereo_bit = ff_celt_log2_frac[f->end_band - f->start_band];
382 if (intensitystereo_bit <= tbits_8ths) {
383 tbits_8ths -= intensitystereo_bit;
384 if (tbits_8ths >= 1 << 3) {
385 dualstereo_bit = 1 << 3;
386 tbits_8ths -= 1 << 3;
389 intensitystereo_bit = 0;
394 for (i = f->start_band; i < f->end_band; i++) {
395 int trim = f->alloc_trim - 5 - f->size;
396 int band = ff_celt_freq_range[i] * (f->end_band - i - 1);
397 int duration = f->size + 3;
398 int scale = duration + f->channels - 1;
400 /* PVQ minimum allocation threshold, below this value the band is
402 threshold[i] = FFMAX(3 * ff_celt_freq_range[i] << duration >> 4,
405 trim_offset[i] = trim * (band << scale) >> 6;
407 if (ff_celt_freq_range[i] << f->size == 1)
408 trim_offset[i] -= f->channels << 3;
413 high = CELT_VECTORS - 1;
414 while (low <= high) {
415 int center = (low + high) >> 1;
418 for (i = f->end_band - 1; i >= f->start_band; i--) {
419 bandbits = ff_celt_freq_range[i] * ff_celt_static_alloc[center][i]
420 << (f->channels - 1) << f->size >> 2;
423 bandbits = FFMAX(0, bandbits + trim_offset[i]);
424 bandbits += boost[i];
426 if (bandbits >= threshold[i] || done) {
428 total += FFMIN(bandbits, cap[i]);
429 } else if (bandbits >= f->channels << 3)
430 total += f->channels << 3;
433 if (total > tbits_8ths)
441 for (i = f->start_band; i < f->end_band; i++) {
442 bits1[i] = ff_celt_freq_range[i] * ff_celt_static_alloc[low][i]
443 << (f->channels - 1) << f->size >> 2;
444 bits2[i] = high >= CELT_VECTORS ? cap[i] :
445 ff_celt_freq_range[i] * ff_celt_static_alloc[high][i]
446 << (f->channels - 1) << f->size >> 2;
449 bits1[i] = FFMAX(0, bits1[i] + trim_offset[i]);
451 bits2[i] = FFMAX(0, bits2[i] + trim_offset[i]);
453 bits1[i] += boost[i];
454 bits2[i] += boost[i];
458 bits2[i] = FFMAX(0, bits2[i] - bits1[i]);
463 high = 1 << CELT_ALLOC_STEPS;
464 for (i = 0; i < CELT_ALLOC_STEPS; i++) {
465 int center = (low + high) >> 1;
468 for (j = f->end_band - 1; j >= f->start_band; j--) {
469 bandbits = bits1[j] + (center * bits2[j] >> CELT_ALLOC_STEPS);
471 if (bandbits >= threshold[j] || done) {
473 total += FFMIN(bandbits, cap[j]);
474 } else if (bandbits >= f->channels << 3)
475 total += f->channels << 3;
477 if (total > tbits_8ths)
485 for (i = f->end_band - 1; i >= f->start_band; i--) {
486 bandbits = bits1[i] + (low * bits2[i] >> CELT_ALLOC_STEPS);
488 if (bandbits >= threshold[i] || done)
491 bandbits = (bandbits >= f->channels << 3) ?
492 f->channels << 3 : 0;
494 bandbits = FFMIN(bandbits, cap[i]);
495 f->pulses[i] = bandbits;
500 for (f->coded_bands = f->end_band; ; f->coded_bands--) {
502 j = f->coded_bands - 1;
504 if (j == skip_startband) {
505 /* all remaining bands are not skipped */
506 tbits_8ths += skip_bit;
510 /* determine the number of bits available for coding "do not skip" markers */
511 remaining = tbits_8ths - total;
512 bandbits = remaining / (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
513 remaining -= bandbits * (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
514 allocation = f->pulses[j] + bandbits * ff_celt_freq_range[j]
515 + FFMAX(0, remaining - (ff_celt_freq_bands[j] - ff_celt_freq_bands[f->start_band]));
517 /* a "do not skip" marker is only coded if the allocation is
518 above the chosen threshold */
519 if (allocation >= FFMAX(threshold[j], (f->channels + 1) << 3)) {
520 const int do_not_skip = f->coded_bands <= f->skip_band_floor;
521 ff_opus_rc_enc_log(rc, do_not_skip, 1);
526 allocation -= 1 << 3;
529 /* the band is skipped, so reclaim its bits */
530 total -= f->pulses[j];
531 if (intensitystereo_bit) {
532 total -= intensitystereo_bit;
533 intensitystereo_bit = ff_celt_log2_frac[j - f->start_band];
534 total += intensitystereo_bit;
537 total += f->pulses[j] = (allocation >= f->channels << 3) ? f->channels << 3 : 0;
540 /* Encode stereo flags */
541 if (intensitystereo_bit) {
542 f->intensity_stereo = FFMIN(f->intensity_stereo, f->coded_bands);
543 ff_opus_rc_enc_uint(rc, f->intensity_stereo, f->coded_bands + 1 - f->start_band);
545 if (f->intensity_stereo <= f->start_band)
546 tbits_8ths += dualstereo_bit; /* no intensity stereo means no dual stereo */
547 else if (dualstereo_bit)
548 ff_opus_rc_enc_log(rc, f->dual_stereo, 1);
550 /* Supply the remaining bits in this frame to lower bands */
551 remaining = tbits_8ths - total;
552 bandbits = remaining / (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
553 remaining -= bandbits * (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
554 for (i = f->start_band; i < f->coded_bands; i++) {
555 int bits = FFMIN(remaining, ff_celt_freq_range[i]);
557 f->pulses[i] += bits + bandbits * ff_celt_freq_range[i];
561 /* Finally determine the allocation */
562 for (i = f->start_band; i < f->coded_bands; i++) {
563 int N = ff_celt_freq_range[i] << f->size;
564 int prev_extra = extrabits;
565 f->pulses[i] += extrabits;
568 int dof; // degrees of freedom
569 int temp; // dof * channels * log(dof)
570 int offset; // fine energy quantization offset, i.e.
571 // extra bits assigned over the standard
573 int fine_bits, max_bits;
575 extrabits = FFMAX(0, f->pulses[i] - cap[i]);
576 f->pulses[i] -= extrabits;
578 /* intensity stereo makes use of an extra degree of freedom */
579 dof = N * f->channels + (f->channels == 2 && N > 2 && !f->dual_stereo && i < f->intensity_stereo);
580 temp = dof * (ff_celt_log_freq_range[i] + (f->size << 3));
581 offset = (temp >> 1) - dof * CELT_FINE_OFFSET;
582 if (N == 2) /* dof=2 is the only case that doesn't fit the model */
585 /* grant an additional bias for the first and second pulses */
586 if (f->pulses[i] + offset < 2 * (dof << 3))
588 else if (f->pulses[i] + offset < 3 * (dof << 3))
591 fine_bits = (f->pulses[i] + offset + (dof << 2)) / (dof << 3);
592 max_bits = FFMIN((f->pulses[i] >> 3) >> (f->channels - 1), CELT_MAX_FINE_BITS);
594 max_bits = FFMAX(max_bits, 0);
596 f->fine_bits[i] = av_clip(fine_bits, 0, max_bits);
598 /* if fine_bits was rounded down or capped,
599 give priority for the final fine energy pass */
600 f->fine_priority[i] = (f->fine_bits[i] * (dof << 3) >= f->pulses[i] + offset);
602 /* the remaining bits are assigned to PVQ */
603 f->pulses[i] -= f->fine_bits[i] << (f->channels - 1) << 3;
605 /* all bits go to fine energy except for the sign bit */
606 extrabits = FFMAX(0, f->pulses[i] - (f->channels << 3));
607 f->pulses[i] -= extrabits;
609 f->fine_priority[i] = 1;
612 /* hand back a limited number of extra fine energy bits to this band */
614 int fineextra = FFMIN(extrabits >> (f->channels + 2),
615 CELT_MAX_FINE_BITS - f->fine_bits[i]);
616 f->fine_bits[i] += fineextra;
618 fineextra <<= f->channels + 2;
619 f->fine_priority[i] = (fineextra >= extrabits - prev_extra);
620 extrabits -= fineextra;
623 f->remaining = extrabits;
625 /* skipped bands dedicate all of their bits for fine energy */
626 for (; i < f->end_band; i++) {
627 f->fine_bits[i] = f->pulses[i] >> (f->channels - 1) >> 3;
629 f->fine_priority[i] = f->fine_bits[i] < 1;
633 static void exp_quant_coarse(OpusRangeCoder *rc, CeltFrame *f,
634 float last_energy[][CELT_MAX_BANDS], int intra)
637 float alpha, beta, prev[2] = { 0, 0 };
638 const uint8_t *pmod = ff_celt_coarse_energy_dist[f->size][intra];
640 /* Inter is really just differential coding */
641 if (opus_rc_tell(rc) + 3 <= f->framebits)
642 ff_opus_rc_enc_log(rc, intra, 3);
648 beta = 1.0f - 4915.0f/32768.0f;
650 alpha = ff_celt_alpha_coef[f->size];
651 beta = 1.0f - ff_celt_beta_coef[f->size];
654 for (i = f->start_band; i < f->end_band; i++) {
655 for (ch = 0; ch < f->channels; ch++) {
656 CeltBlock *block = &f->block[ch];
657 const int left = f->framebits - opus_rc_tell(rc);
658 const float last = FFMAX(-9.0f, last_energy[ch][i]);
659 float diff = block->energy[i] - prev[ch] - last*alpha;
660 int q_en = lrintf(diff);
662 ff_opus_rc_enc_laplace(rc, &q_en, pmod[i << 1] << 7, pmod[(i << 1) + 1] << 6);
663 } else if (left >= 2) {
664 q_en = av_clip(q_en, -1, 1);
665 ff_opus_rc_enc_cdf(rc, 2*q_en + 3*(q_en < 0), ff_celt_model_energy_small);
666 } else if (left >= 1) {
667 q_en = av_clip(q_en, -1, 0);
668 ff_opus_rc_enc_log(rc, (q_en & 1), 1);
671 block->error_energy[i] = q_en - diff;
672 prev[ch] += beta * q_en;
677 static void celt_quant_coarse(OpusRangeCoder *rc, CeltFrame *f,
678 float last_energy[][CELT_MAX_BANDS])
680 uint32_t inter, intra;
681 OPUS_RC_CHECKPOINT_SPAWN(rc);
683 exp_quant_coarse(rc, f, last_energy, 1);
684 intra = OPUS_RC_CHECKPOINT_BITS(rc);
686 OPUS_RC_CHECKPOINT_ROLLBACK(rc);
688 exp_quant_coarse(rc, f, last_energy, 0);
689 inter = OPUS_RC_CHECKPOINT_BITS(rc);
691 if (inter > intra) { /* Unlikely */
692 OPUS_RC_CHECKPOINT_ROLLBACK(rc);
693 exp_quant_coarse(rc, f, last_energy, 1);
697 static void celt_quant_fine(OpusRangeCoder *rc, CeltFrame *f)
700 for (i = f->start_band; i < f->end_band; i++) {
701 if (!f->fine_bits[i])
703 for (ch = 0; ch < f->channels; ch++) {
704 CeltBlock *block = &f->block[ch];
705 int quant, lim = (1 << f->fine_bits[i]);
706 float offset, diff = 0.5f - block->error_energy[i];
707 quant = av_clip(floor(diff*lim), 0, lim - 1);
708 ff_opus_rc_put_raw(rc, quant, f->fine_bits[i]);
709 offset = 0.5f - ((quant + 0.5f) * (1 << (14 - f->fine_bits[i])) / 16384.0f);
710 block->error_energy[i] -= offset;
715 static void celt_quant_final(OpusEncContext *s, OpusRangeCoder *rc, CeltFrame *f)
718 for (priority = 0; priority < 2; priority++) {
719 for (i = f->start_band; i < f->end_band && (f->framebits - opus_rc_tell(rc)) >= f->channels; i++) {
720 if (f->fine_priority[i] != priority || f->fine_bits[i] >= CELT_MAX_FINE_BITS)
722 for (ch = 0; ch < f->channels; ch++) {
723 CeltBlock *block = &f->block[ch];
724 const float err = block->error_energy[i];
725 const float offset = 0.5f * (1 << (14 - f->fine_bits[i] - 1)) / 16384.0f;
726 const int sign = FFABS(err + offset) < FFABS(err - offset);
727 ff_opus_rc_put_raw(rc, sign, 1);
728 block->error_energy[i] -= offset*(1 - 2*sign);
734 static void celt_quant_bands(OpusRangeCoder *rc, CeltFrame *f)
736 float lowband_scratch[8 * 22];
737 float norm[2 * 8 * 100];
739 int totalbits = (f->framebits << 3) - f->anticollapse_needed;
741 int update_lowband = 1;
742 int lowband_offset = 0;
746 for (i = f->start_band; i < f->end_band; i++) {
747 uint32_t cm[2] = { (1 << f->blocks) - 1, (1 << f->blocks) - 1 };
748 int band_offset = ff_celt_freq_bands[i] << f->size;
749 int band_size = ff_celt_freq_range[i] << f->size;
750 float *X = f->block[0].coeffs + band_offset;
751 float *Y = (f->channels == 2) ? f->block[1].coeffs + band_offset : NULL;
753 int consumed = opus_rc_tell_frac(rc);
754 float *norm2 = norm + 8 * 100;
755 int effective_lowband = -1;
758 /* Compute how many bits we want to allocate to this band */
759 if (i != f->start_band)
760 f->remaining -= consumed;
761 f->remaining2 = totalbits - consumed - 1;
762 if (i <= f->coded_bands - 1) {
763 int curr_balance = f->remaining / FFMIN(3, f->coded_bands-i);
764 b = av_clip_uintp2(FFMIN(f->remaining2 + 1, f->pulses[i] + curr_balance), 14);
767 if (ff_celt_freq_bands[i] - ff_celt_freq_range[i] >= ff_celt_freq_bands[f->start_band] &&
768 (update_lowband || lowband_offset == 0))
771 /* Get a conservative estimate of the collapse_mask's for the bands we're
772 going to be folding from. */
773 if (lowband_offset != 0 && (f->spread != CELT_SPREAD_AGGRESSIVE ||
774 f->blocks > 1 || f->tf_change[i] < 0)) {
775 int foldstart, foldend;
777 /* This ensures we never repeat spectral content within one band */
778 effective_lowband = FFMAX(ff_celt_freq_bands[f->start_band],
779 ff_celt_freq_bands[lowband_offset] - ff_celt_freq_range[i]);
780 foldstart = lowband_offset;
781 while (ff_celt_freq_bands[--foldstart] > effective_lowband);
782 foldend = lowband_offset - 1;
783 while (ff_celt_freq_bands[++foldend] < effective_lowband + ff_celt_freq_range[i]);
786 for (j = foldstart; j < foldend; j++) {
787 cm[0] |= f->block[0].collapse_masks[j];
788 cm[1] |= f->block[f->channels - 1].collapse_masks[j];
792 if (f->dual_stereo && i == f->intensity_stereo) {
793 /* Switch off dual stereo to do intensity */
795 for (j = ff_celt_freq_bands[f->start_band] << f->size; j < band_offset; j++)
796 norm[j] = (norm[j] + norm2[j]) / 2;
799 if (f->dual_stereo) {
800 cm[0] = ff_celt_encode_band(f, rc, i, X, NULL, band_size, b / 2, f->blocks,
801 effective_lowband != -1 ? norm + (effective_lowband << f->size) : NULL, f->size,
802 norm + band_offset, 0, 1.0f, lowband_scratch, cm[0]);
804 cm[1] = ff_celt_encode_band(f, rc, i, Y, NULL, band_size, b / 2, f->blocks,
805 effective_lowband != -1 ? norm2 + (effective_lowband << f->size) : NULL, f->size,
806 norm2 + band_offset, 0, 1.0f, lowband_scratch, cm[1]);
808 cm[0] = ff_celt_encode_band(f, rc, i, X, Y, band_size, b, f->blocks,
809 effective_lowband != -1 ? norm + (effective_lowband << f->size) : NULL, f->size,
810 norm + band_offset, 0, 1.0f, lowband_scratch, cm[0] | cm[1]);
814 f->block[0].collapse_masks[i] = (uint8_t)cm[0];
815 f->block[f->channels - 1].collapse_masks[i] = (uint8_t)cm[1];
816 f->remaining += f->pulses[i] + consumed;
818 /* Update the folding position only as long as we have 1 bit/sample depth */
819 update_lowband = (b > band_size << 3);
823 static void celt_encode_frame(OpusEncContext *s, OpusRangeCoder *rc, CeltFrame *f)
827 celt_frame_setup_input(s, f);
828 celt_apply_preemph_filter(s, f);
830 /* Not implemented */
832 celt_frame_mdct(s, f);
833 celt_frame_map_norm_bands(s, f);
835 ff_opus_rc_enc_log(rc, f->silence, 15);
837 if (!f->start_band && opus_rc_tell(rc) + 16 <= f->framebits)
838 ff_opus_rc_enc_log(rc, f->pfilter, 1);
841 /* Not implemented */
844 if (f->size && opus_rc_tell(rc) + 3 <= f->framebits)
845 ff_opus_rc_enc_log(rc, f->transient, 3);
847 celt_quant_coarse(rc, f, s->last_quantized_energy);
849 ff_celt_enc_bitalloc(rc, f);
850 celt_quant_fine (rc, f);
851 celt_quant_bands (rc, f);
853 if (f->anticollapse_needed)
854 ff_opus_rc_put_raw(rc, f->anticollapse, 1);
856 celt_quant_final(s, rc, f);
858 for (ch = 0; ch < f->channels; ch++) {
859 CeltBlock *block = &f->block[ch];
860 for (i = 0; i < CELT_MAX_BANDS; i++)
861 s->last_quantized_energy[ch][i] = block->energy[i] + block->error_energy[i];
865 static void ff_opus_psy_process(OpusEncContext *s, int end, int *need_more)
867 int max_delay_samples = (s->options.max_delay_ms*s->avctx->sample_rate)/1000;
868 int max_bsize = FFMIN(OPUS_SAMPLES_TO_BLOCK_SIZE(max_delay_samples), CELT_BLOCK_960);
871 s->pkt_framesize = max_bsize;
872 s->mode = OPUS_MODE_CELT;
873 s->bandwidth = OPUS_BANDWIDTH_FULLBAND;
875 *need_more = s->bufqueue.available*s->avctx->frame_size < (max_delay_samples + CELT_OVERLAP);
876 /* Don't request more if we start being flushed with NULL frames */
877 *need_more = !end && *need_more;
880 static void ff_opus_psy_celt_frame_setup(OpusEncContext *s, CeltFrame *f, int index)
882 int frame_size = OPUS_BLOCK_SIZE(s->pkt_framesize);
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;
898 f->skip_band_floor = f->end_band;
899 f->intensity_stereo = f->end_band;
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);
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);
909 static void opus_packet_assembler(OpusEncContext *s, AVPacket *avpkt)
911 int i, offset, fsize_needed;
914 opus_gen_toc(s, avpkt->data, &offset, &fsize_needed);
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;
921 avpkt->size = offset;
924 /* Used as overlap for the first frame and padding for the last encoded packet */
925 static AVFrame *spawn_empty_frame(OpusEncContext *s)
928 AVFrame *f = av_frame_alloc();
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)) {
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);
945 static int opus_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
946 const AVFrame *frame, int *got_packet_ptr)
948 OpusEncContext *s = avctx->priv_data;
949 int i, ret, frame_size, need_more, alloc_size = 0;
951 if (frame) { /* Add new frame to queue */
952 if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
954 ff_bufqueue_add(avctx, &s->bufqueue, av_frame_clone(frame));
956 if (!s->afq.remaining_samples)
957 return 0; /* We've been flushed and there's nothing left to encode */
960 /* Run the psychoacoustic system */
961 ff_opus_psy_process(s, !frame, &need_more);
963 /* Get more samples for lookahead/encoding */
967 frame_size = OPUS_BLOCK_SIZE(s->pkt_framesize);
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);
979 return AVERROR(ENOMEM);
980 ff_bufqueue_add(avctx, &s->bufqueue, empty);
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;
991 /* Worst case toc + the frame lengths if needed */
992 alloc_size += 2 + s->pkt_frames*2;
994 if ((ret = ff_alloc_packet2(avctx, avpkt, alloc_size, 0)) < 0)
997 /* Assemble packet */
998 opus_packet_assembler(s, avpkt);
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);
1005 return AVERROR(ENOMEM);
1006 AV_WL32(&side[4], s->pkt_frames*frame_size - avpkt->duration + 120);
1009 *got_packet_ptr = 1;
1014 static av_cold int opus_encode_end(AVCodecContext *avctx)
1017 OpusEncContext *s = avctx->priv_data;
1019 for (i = 0; i < CELT_BLOCK_NB; i++)
1020 ff_mdct15_uninit(&s->mdct[i]);
1023 av_freep(&s->frame);
1025 ff_af_queue_close(&s->afq);
1026 ff_bufqueue_discard_all(&s->bufqueue);
1027 av_freep(&avctx->extradata);
1032 static av_cold int opus_encode_init(AVCodecContext *avctx)
1035 OpusEncContext *s = avctx->priv_data;
1038 s->channels = avctx->channels;
1040 /* Opus allows us to change the framesize on each packet (and each packet may
1041 * have multiple frames in it) but we can't change the codec's frame size on
1042 * runtime, so fix it to the lowest possible number of samples and use a queue
1043 * to accumulate AVFrames until we have enough to encode whatever the encoder
1044 * decides is the best */
1045 avctx->frame_size = 120;
1046 /* Initial padding will change if SILK is ever supported */
1047 avctx->initial_padding = 120;
1049 avctx->cutoff = !avctx->cutoff ? 20000 : avctx->cutoff;
1051 if (!avctx->bit_rate) {
1052 int coupled = ff_opus_default_coupled_streams[s->channels - 1];
1053 avctx->bit_rate = coupled*(96000) + (s->channels - coupled*2)*(48000);
1054 } else if (avctx->bit_rate < 6000 || avctx->bit_rate > 255000 * s->channels) {
1055 int64_t clipped_rate = av_clip(avctx->bit_rate, 6000, 255000 * s->channels);
1056 av_log(avctx, AV_LOG_ERROR, "Unsupported bitrate %"PRId64" kbps, clipping to %"PRId64" kbps\n",
1057 avctx->bit_rate/1000, clipped_rate/1000);
1058 avctx->bit_rate = clipped_rate;
1061 /* Frame structs and range coder buffers */
1062 s->frame = av_malloc(OPUS_MAX_FRAMES_PER_PACKET*sizeof(CeltFrame));
1064 return AVERROR(ENOMEM);
1065 s->rc = av_malloc(OPUS_MAX_FRAMES_PER_PACKET*sizeof(OpusRangeCoder));
1067 return AVERROR(ENOMEM);
1070 avctx->extradata_size = 19;
1071 avctx->extradata = av_malloc(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
1072 if (!avctx->extradata)
1073 return AVERROR(ENOMEM);
1074 opus_write_extradata(avctx);
1076 ff_af_queue_init(avctx, &s->afq);
1078 if (!(s->dsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT)))
1079 return AVERROR(ENOMEM);
1081 /* I have no idea why a base scaling factor of 68 works, could be the twiddles */
1082 for (i = 0; i < CELT_BLOCK_NB; i++)
1083 if ((ret = ff_mdct15_init(&s->mdct[i], 0, i + 3, 68 << (CELT_BLOCK_NB - 1 - i))))
1084 return AVERROR(ENOMEM);
1086 for (i = 0; i < OPUS_MAX_FRAMES_PER_PACKET; i++)
1087 s->frame[i].block[0].emph_coeff = s->frame[i].block[1].emph_coeff = 0.0f;
1089 /* Zero out previous energy (matters for inter first frame) */
1090 for (ch = 0; ch < s->channels; ch++)
1091 for (i = 0; i < CELT_MAX_BANDS; i++)
1092 s->last_quantized_energy[ch][i] = 0.0f;
1094 /* Allocate an empty frame to use as overlap for the first frame of audio */
1095 ff_bufqueue_add(avctx, &s->bufqueue, spawn_empty_frame(s));
1096 if (!ff_bufqueue_peek(&s->bufqueue, 0))
1097 return AVERROR(ENOMEM);
1102 #define OPUSENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1103 static const AVOption opusenc_options[] = {
1104 { "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 },
1108 static const AVClass opusenc_class = {
1109 .class_name = "Opus encoder",
1110 .item_name = av_default_item_name,
1111 .option = opusenc_options,
1112 .version = LIBAVUTIL_VERSION_INT,
1115 static const AVCodecDefault opusenc_defaults[] = {
1117 { "compression_level", "10" },
1121 AVCodec ff_opus_encoder = {
1123 .long_name = NULL_IF_CONFIG_SMALL("Opus"),
1124 .type = AVMEDIA_TYPE_AUDIO,
1125 .id = AV_CODEC_ID_OPUS,
1126 .defaults = opusenc_defaults,
1127 .priv_class = &opusenc_class,
1128 .priv_data_size = sizeof(OpusEncContext),
1129 .init = opus_encode_init,
1130 .encode2 = opus_encode_frame,
1131 .close = opus_encode_end,
1132 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP,
1133 .capabilities = AV_CODEC_CAP_EXPERIMENTAL | AV_CODEC_CAP_SMALL_LAST_FRAME | AV_CODEC_CAP_DELAY,
1134 .supported_samplerates = (const int []){ 48000, 0 },
1135 .channel_layouts = (const uint64_t []){ AV_CH_LAYOUT_MONO,
1136 AV_CH_LAYOUT_STEREO, 0 },
1137 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
1138 AV_SAMPLE_FMT_NONE },