You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1140 lines
41KB

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