enc.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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 <float.h>
  22. #include "encode.h"
  23. #include "enc.h"
  24. #include "pvq.h"
  25. #include "enc_psy.h"
  26. #include "tab.h"
  27. #include "libavutil/channel_layout.h"
  28. #include "libavutil/float_dsp.h"
  29. #include "libavutil/mem.h"
  30. #include "libavutil/mem_internal.h"
  31. #include "libavutil/opt.h"
  32. #include "bytestream.h"
  33. #include "audio_frame_queue.h"
  34. #include "codec_internal.h"
  35. typedef struct OpusEncContext {
  36. AVClass *av_class;
  37. OpusEncOptions options;
  38. OpusPsyContext psyctx;
  39. AVCodecContext *avctx;
  40. AudioFrameQueue afq;
  41. AVFloatDSPContext *dsp;
  42. AVTXContext *tx[CELT_BLOCK_NB];
  43. av_tx_fn tx_fn[CELT_BLOCK_NB];
  44. CeltPVQ *pvq;
  45. struct FFBufQueue bufqueue;
  46. uint8_t enc_id[64];
  47. int enc_id_bits;
  48. OpusPacketInfo packet;
  49. int channels;
  50. CeltFrame *frame;
  51. OpusRangeCoder *rc;
  52. /* Actual energy the decoder will have */
  53. float last_quantized_energy[OPUS_MAX_CHANNELS][CELT_MAX_BANDS];
  54. DECLARE_ALIGNED(32, float, scratch)[2048];
  55. } OpusEncContext;
  56. static void opus_write_extradata(AVCodecContext *avctx)
  57. {
  58. uint8_t *bs = avctx->extradata;
  59. bytestream_put_buffer(&bs, "OpusHead", 8);
  60. bytestream_put_byte (&bs, 0x1);
  61. bytestream_put_byte (&bs, avctx->ch_layout.nb_channels);
  62. bytestream_put_le16 (&bs, avctx->initial_padding);
  63. bytestream_put_le32 (&bs, avctx->sample_rate);
  64. bytestream_put_le16 (&bs, 0x0);
  65. bytestream_put_byte (&bs, 0x0); /* Default layout */
  66. }
  67. static int opus_gen_toc(OpusEncContext *s, uint8_t *toc, int *size, int *fsize_needed)
  68. {
  69. int tmp = 0x0, extended_toc = 0;
  70. static const int toc_cfg[][OPUS_MODE_NB][OPUS_BANDWITH_NB] = {
  71. /* Silk Hybrid Celt Layer */
  72. /* NB MB WB SWB FB NB MB WB SWB FB NB MB WB SWB FB Bandwidth */
  73. { { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 17, 0, 21, 25, 29 } }, /* 2.5 ms */
  74. { { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 18, 0, 22, 26, 30 } }, /* 5 ms */
  75. { { 1, 5, 9, 0, 0 }, { 0, 0, 0, 13, 15 }, { 19, 0, 23, 27, 31 } }, /* 10 ms */
  76. { { 2, 6, 10, 0, 0 }, { 0, 0, 0, 14, 16 }, { 20, 0, 24, 28, 32 } }, /* 20 ms */
  77. { { 3, 7, 11, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }, /* 40 ms */
  78. { { 4, 8, 12, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }, /* 60 ms */
  79. };
  80. int cfg = toc_cfg[s->packet.framesize][s->packet.mode][s->packet.bandwidth];
  81. *fsize_needed = 0;
  82. if (!cfg)
  83. return 1;
  84. if (s->packet.frames == 2) { /* 2 packets */
  85. if (s->frame[0].framebits == s->frame[1].framebits) { /* same size */
  86. tmp = 0x1;
  87. } else { /* different size */
  88. tmp = 0x2;
  89. *fsize_needed = 1; /* put frame sizes in the packet */
  90. }
  91. } else if (s->packet.frames > 2) {
  92. tmp = 0x3;
  93. extended_toc = 1;
  94. }
  95. tmp |= (s->channels > 1) << 2; /* Stereo or mono */
  96. tmp |= (cfg - 1) << 3; /* codec configuration */
  97. *toc++ = tmp;
  98. if (extended_toc) {
  99. for (int i = 0; i < (s->packet.frames - 1); i++)
  100. *fsize_needed |= (s->frame[i].framebits != s->frame[i + 1].framebits);
  101. tmp = (*fsize_needed) << 7; /* vbr flag */
  102. tmp |= (0) << 6; /* padding flag */
  103. tmp |= s->packet.frames;
  104. *toc++ = tmp;
  105. }
  106. *size = 1 + extended_toc;
  107. return 0;
  108. }
  109. static void celt_frame_setup_input(OpusEncContext *s, CeltFrame *f)
  110. {
  111. AVFrame *cur = NULL;
  112. const int subframesize = s->avctx->frame_size;
  113. int subframes = OPUS_BLOCK_SIZE(s->packet.framesize) / subframesize;
  114. cur = ff_bufqueue_get(&s->bufqueue);
  115. for (int ch = 0; ch < f->channels; ch++) {
  116. CeltBlock *b = &f->block[ch];
  117. const void *input = cur->extended_data[ch];
  118. size_t bps = av_get_bytes_per_sample(cur->format);
  119. memcpy(b->overlap, input, bps*cur->nb_samples);
  120. }
  121. av_frame_free(&cur);
  122. for (int sf = 0; sf < subframes; sf++) {
  123. if (sf != (subframes - 1))
  124. cur = ff_bufqueue_get(&s->bufqueue);
  125. else
  126. cur = ff_bufqueue_peek(&s->bufqueue, 0);
  127. for (int ch = 0; ch < f->channels; ch++) {
  128. CeltBlock *b = &f->block[ch];
  129. const void *input = cur->extended_data[ch];
  130. const size_t bps = av_get_bytes_per_sample(cur->format);
  131. const size_t left = (subframesize - cur->nb_samples)*bps;
  132. const size_t len = FFMIN(subframesize, cur->nb_samples)*bps;
  133. memcpy(&b->samples[sf*subframesize], input, len);
  134. memset(&b->samples[cur->nb_samples], 0, left);
  135. }
  136. /* Last frame isn't popped off and freed yet - we need it for overlap */
  137. if (sf != (subframes - 1))
  138. av_frame_free(&cur);
  139. }
  140. }
  141. /* Apply the pre emphasis filter */
  142. static void celt_apply_preemph_filter(OpusEncContext *s, CeltFrame *f)
  143. {
  144. const int subframesize = s->avctx->frame_size;
  145. const int subframes = OPUS_BLOCK_SIZE(s->packet.framesize) / subframesize;
  146. const float c = ff_opus_deemph_weights[0];
  147. /* Filter overlap */
  148. for (int ch = 0; ch < f->channels; ch++) {
  149. CeltBlock *b = &f->block[ch];
  150. float m = b->emph_coeff;
  151. for (int i = 0; i < CELT_OVERLAP; i++) {
  152. float sample = b->overlap[i];
  153. b->overlap[i] = sample - m;
  154. m = sample * c;
  155. }
  156. b->emph_coeff = m;
  157. }
  158. /* Filter the samples but do not update the last subframe's coeff - overlap ^^^ */
  159. for (int sf = 0; sf < subframes; sf++) {
  160. for (int ch = 0; ch < f->channels; ch++) {
  161. CeltBlock *b = &f->block[ch];
  162. float m = b->emph_coeff;
  163. for (int i = 0; i < subframesize; i++) {
  164. float sample = b->samples[sf*subframesize + i];
  165. b->samples[sf*subframesize + i] = sample - m;
  166. m = sample * c;
  167. }
  168. if (sf != (subframes - 1))
  169. b->emph_coeff = m;
  170. }
  171. }
  172. }
  173. /* Create the window and do the mdct */
  174. static void celt_frame_mdct(OpusEncContext *s, CeltFrame *f)
  175. {
  176. float *win = s->scratch, *temp = s->scratch + 1920;
  177. if (f->transient) {
  178. for (int ch = 0; ch < f->channels; ch++) {
  179. CeltBlock *b = &f->block[ch];
  180. float *src1 = b->overlap;
  181. for (int t = 0; t < f->blocks; t++) {
  182. float *src2 = &b->samples[CELT_OVERLAP*t];
  183. s->dsp->vector_fmul(win, src1, ff_celt_window, 128);
  184. s->dsp->vector_fmul_reverse(&win[CELT_OVERLAP], src2,
  185. ff_celt_window_padded, 128);
  186. src1 = src2;
  187. s->tx_fn[0](s->tx[0], b->coeffs + t, win, sizeof(float)*f->blocks);
  188. }
  189. }
  190. } else {
  191. int blk_len = OPUS_BLOCK_SIZE(f->size), wlen = OPUS_BLOCK_SIZE(f->size + 1);
  192. int rwin = blk_len - CELT_OVERLAP, lap_dst = (wlen - blk_len - CELT_OVERLAP) >> 1;
  193. memset(win, 0, wlen*sizeof(float));
  194. for (int ch = 0; ch < f->channels; ch++) {
  195. CeltBlock *b = &f->block[ch];
  196. /* Overlap */
  197. s->dsp->vector_fmul(temp, b->overlap, ff_celt_window, 128);
  198. memcpy(win + lap_dst, temp, CELT_OVERLAP*sizeof(float));
  199. /* Samples, flat top window */
  200. memcpy(&win[lap_dst + CELT_OVERLAP], b->samples, rwin*sizeof(float));
  201. /* Samples, windowed */
  202. s->dsp->vector_fmul_reverse(temp, b->samples + rwin,
  203. ff_celt_window_padded, 128);
  204. memcpy(win + lap_dst + blk_len, temp, CELT_OVERLAP*sizeof(float));
  205. s->tx_fn[f->size](s->tx[f->size], b->coeffs, win, sizeof(float));
  206. }
  207. }
  208. for (int ch = 0; ch < f->channels; ch++) {
  209. CeltBlock *block = &f->block[ch];
  210. for (int i = 0; i < CELT_MAX_BANDS; i++) {
  211. float ener = 0.0f;
  212. int band_offset = ff_celt_freq_bands[i] << f->size;
  213. int band_size = ff_celt_freq_range[i] << f->size;
  214. float *coeffs = &block->coeffs[band_offset];
  215. for (int j = 0; j < band_size; j++)
  216. ener += coeffs[j]*coeffs[j];
  217. block->lin_energy[i] = sqrtf(ener) + FLT_EPSILON;
  218. ener = 1.0f/block->lin_energy[i];
  219. for (int j = 0; j < band_size; j++)
  220. coeffs[j] *= ener;
  221. block->energy[i] = log2f(block->lin_energy[i]) - ff_celt_mean_energy[i];
  222. /* CELT_ENERGY_SILENCE is what the decoder uses and its not -infinity */
  223. block->energy[i] = FFMAX(block->energy[i], CELT_ENERGY_SILENCE);
  224. }
  225. }
  226. }
  227. static void celt_enc_tf(CeltFrame *f, OpusRangeCoder *rc)
  228. {
  229. int tf_select = 0, diff = 0, tf_changed = 0, tf_select_needed;
  230. int bits = f->transient ? 2 : 4;
  231. tf_select_needed = ((f->size && (opus_rc_tell(rc) + bits + 1) <= f->framebits));
  232. for (int i = f->start_band; i < f->end_band; i++) {
  233. if ((opus_rc_tell(rc) + bits + tf_select_needed) <= f->framebits) {
  234. const int tbit = (diff ^ 1) == f->tf_change[i];
  235. ff_opus_rc_enc_log(rc, tbit, bits);
  236. diff ^= tbit;
  237. tf_changed |= diff;
  238. }
  239. bits = f->transient ? 4 : 5;
  240. }
  241. if (tf_select_needed && ff_celt_tf_select[f->size][f->transient][0][tf_changed] !=
  242. ff_celt_tf_select[f->size][f->transient][1][tf_changed]) {
  243. ff_opus_rc_enc_log(rc, f->tf_select, 1);
  244. tf_select = f->tf_select;
  245. }
  246. for (int i = f->start_band; i < f->end_band; i++)
  247. f->tf_change[i] = ff_celt_tf_select[f->size][f->transient][tf_select][f->tf_change[i]];
  248. }
  249. static void celt_enc_quant_pfilter(OpusRangeCoder *rc, CeltFrame *f)
  250. {
  251. float gain = f->pf_gain;
  252. int txval, octave = f->pf_octave, period = f->pf_period, tapset = f->pf_tapset;
  253. ff_opus_rc_enc_log(rc, f->pfilter, 1);
  254. if (!f->pfilter)
  255. return;
  256. /* Octave */
  257. txval = FFMIN(octave, 6);
  258. ff_opus_rc_enc_uint(rc, txval, 6);
  259. octave = txval;
  260. /* Period */
  261. txval = av_clip(period - (16 << octave) + 1, 0, (1 << (4 + octave)) - 1);
  262. ff_opus_rc_put_raw(rc, period, 4 + octave);
  263. period = txval + (16 << octave) - 1;
  264. /* Gain */
  265. txval = FFMIN(((int)(gain / 0.09375f)) - 1, 7);
  266. ff_opus_rc_put_raw(rc, txval, 3);
  267. gain = 0.09375f * (txval + 1);
  268. /* Tapset */
  269. if ((opus_rc_tell(rc) + 2) <= f->framebits)
  270. ff_opus_rc_enc_cdf(rc, tapset, ff_celt_model_tapset);
  271. else
  272. tapset = 0;
  273. /* Finally create the coeffs */
  274. for (int i = 0; i < 2; i++) {
  275. CeltBlock *block = &f->block[i];
  276. block->pf_period_new = FFMAX(period, CELT_POSTFILTER_MINPERIOD);
  277. block->pf_gains_new[0] = gain * ff_celt_postfilter_taps[tapset][0];
  278. block->pf_gains_new[1] = gain * ff_celt_postfilter_taps[tapset][1];
  279. block->pf_gains_new[2] = gain * ff_celt_postfilter_taps[tapset][2];
  280. }
  281. }
  282. static void exp_quant_coarse(OpusRangeCoder *rc, CeltFrame *f,
  283. float last_energy[][CELT_MAX_BANDS], int intra)
  284. {
  285. float alpha, beta, prev[2] = { 0, 0 };
  286. const uint8_t *pmod = ff_celt_coarse_energy_dist[f->size][intra];
  287. /* Inter is really just differential coding */
  288. if (opus_rc_tell(rc) + 3 <= f->framebits)
  289. ff_opus_rc_enc_log(rc, intra, 3);
  290. else
  291. intra = 0;
  292. if (intra) {
  293. alpha = 0.0f;
  294. beta = 1.0f - (4915.0f/32768.0f);
  295. } else {
  296. alpha = ff_celt_alpha_coef[f->size];
  297. beta = ff_celt_beta_coef[f->size];
  298. }
  299. for (int i = f->start_band; i < f->end_band; i++) {
  300. for (int ch = 0; ch < f->channels; ch++) {
  301. CeltBlock *block = &f->block[ch];
  302. const int left = f->framebits - opus_rc_tell(rc);
  303. const float last = FFMAX(-9.0f, last_energy[ch][i]);
  304. float diff = block->energy[i] - prev[ch] - last*alpha;
  305. int q_en = lrintf(diff);
  306. if (left >= 15) {
  307. ff_opus_rc_enc_laplace(rc, &q_en, pmod[i << 1] << 7, pmod[(i << 1) + 1] << 6);
  308. } else if (left >= 2) {
  309. q_en = av_clip(q_en, -1, 1);
  310. ff_opus_rc_enc_cdf(rc, 2*q_en + 3*(q_en < 0), ff_celt_model_energy_small);
  311. } else if (left >= 1) {
  312. q_en = av_clip(q_en, -1, 0);
  313. ff_opus_rc_enc_log(rc, (q_en & 1), 1);
  314. } else q_en = -1;
  315. block->error_energy[i] = q_en - diff;
  316. prev[ch] += beta * q_en;
  317. }
  318. }
  319. }
  320. static void celt_quant_coarse(CeltFrame *f, OpusRangeCoder *rc,
  321. float last_energy[][CELT_MAX_BANDS])
  322. {
  323. uint32_t inter, intra;
  324. OPUS_RC_CHECKPOINT_SPAWN(rc);
  325. exp_quant_coarse(rc, f, last_energy, 1);
  326. intra = OPUS_RC_CHECKPOINT_BITS(rc);
  327. OPUS_RC_CHECKPOINT_ROLLBACK(rc);
  328. exp_quant_coarse(rc, f, last_energy, 0);
  329. inter = OPUS_RC_CHECKPOINT_BITS(rc);
  330. if (inter > intra) { /* Unlikely */
  331. OPUS_RC_CHECKPOINT_ROLLBACK(rc);
  332. exp_quant_coarse(rc, f, last_energy, 1);
  333. }
  334. }
  335. static void celt_quant_fine(CeltFrame *f, OpusRangeCoder *rc)
  336. {
  337. for (int i = f->start_band; i < f->end_band; i++) {
  338. if (!f->fine_bits[i])
  339. continue;
  340. for (int ch = 0; ch < f->channels; ch++) {
  341. CeltBlock *block = &f->block[ch];
  342. int quant, lim = (1 << f->fine_bits[i]);
  343. float offset, diff = 0.5f - block->error_energy[i];
  344. quant = av_clip(floor(diff*lim), 0, lim - 1);
  345. ff_opus_rc_put_raw(rc, quant, f->fine_bits[i]);
  346. offset = 0.5f - ((quant + 0.5f) * (1 << (14 - f->fine_bits[i])) / 16384.0f);
  347. block->error_energy[i] -= offset;
  348. }
  349. }
  350. }
  351. static void celt_quant_final(OpusEncContext *s, OpusRangeCoder *rc, CeltFrame *f)
  352. {
  353. for (int priority = 0; priority < 2; priority++) {
  354. for (int i = f->start_band; i < f->end_band && (f->framebits - opus_rc_tell(rc)) >= f->channels; i++) {
  355. if (f->fine_priority[i] != priority || f->fine_bits[i] >= CELT_MAX_FINE_BITS)
  356. continue;
  357. for (int ch = 0; ch < f->channels; ch++) {
  358. CeltBlock *block = &f->block[ch];
  359. const float err = block->error_energy[i];
  360. const float offset = 0.5f * (1 << (14 - f->fine_bits[i] - 1)) / 16384.0f;
  361. const int sign = FFABS(err + offset) < FFABS(err - offset);
  362. ff_opus_rc_put_raw(rc, sign, 1);
  363. block->error_energy[i] -= offset*(1 - 2*sign);
  364. }
  365. }
  366. }
  367. }
  368. static void celt_encode_frame(OpusEncContext *s, OpusRangeCoder *rc,
  369. CeltFrame *f, int index)
  370. {
  371. ff_opus_rc_enc_init(rc);
  372. ff_opus_psy_celt_frame_init(&s->psyctx, f, index);
  373. celt_frame_setup_input(s, f);
  374. if (f->silence) {
  375. if (f->framebits >= 16)
  376. ff_opus_rc_enc_log(rc, 1, 15); /* Silence (if using explicit signalling) */
  377. for (int ch = 0; ch < s->channels; ch++)
  378. memset(s->last_quantized_energy[ch], 0.0f, sizeof(float)*CELT_MAX_BANDS);
  379. return;
  380. }
  381. /* Filters */
  382. celt_apply_preemph_filter(s, f);
  383. if (f->pfilter) {
  384. ff_opus_rc_enc_log(rc, 0, 15);
  385. celt_enc_quant_pfilter(rc, f);
  386. }
  387. /* Transform */
  388. celt_frame_mdct(s, f);
  389. /* Need to handle transient/non-transient switches at any point during analysis */
  390. while (ff_opus_psy_celt_frame_process(&s->psyctx, f, index))
  391. celt_frame_mdct(s, f);
  392. ff_opus_rc_enc_init(rc);
  393. /* Silence */
  394. ff_opus_rc_enc_log(rc, 0, 15);
  395. /* Pitch filter */
  396. if (!f->start_band && opus_rc_tell(rc) + 16 <= f->framebits)
  397. celt_enc_quant_pfilter(rc, f);
  398. /* Transient flag */
  399. if (f->size && opus_rc_tell(rc) + 3 <= f->framebits)
  400. ff_opus_rc_enc_log(rc, f->transient, 3);
  401. /* Main encoding */
  402. celt_quant_coarse (f, rc, s->last_quantized_energy);
  403. celt_enc_tf (f, rc);
  404. ff_celt_bitalloc (f, rc, 1);
  405. celt_quant_fine (f, rc);
  406. ff_celt_quant_bands(f, rc);
  407. /* Anticollapse bit */
  408. if (f->anticollapse_needed)
  409. ff_opus_rc_put_raw(rc, f->anticollapse, 1);
  410. /* Final per-band energy adjustments from leftover bits */
  411. celt_quant_final(s, rc, f);
  412. for (int ch = 0; ch < f->channels; ch++) {
  413. CeltBlock *block = &f->block[ch];
  414. for (int i = 0; i < CELT_MAX_BANDS; i++)
  415. s->last_quantized_energy[ch][i] = block->energy[i] + block->error_energy[i];
  416. }
  417. }
  418. static inline int write_opuslacing(uint8_t *dst, int v)
  419. {
  420. dst[0] = FFMIN(v - FFALIGN(v - 255, 4), v);
  421. dst[1] = v - dst[0] >> 2;
  422. return 1 + (v >= 252);
  423. }
  424. static void opus_packet_assembler(OpusEncContext *s, AVPacket *avpkt)
  425. {
  426. int offset, fsize_needed;
  427. /* Write toc */
  428. opus_gen_toc(s, avpkt->data, &offset, &fsize_needed);
  429. /* Frame sizes if needed */
  430. if (fsize_needed) {
  431. for (int i = 0; i < s->packet.frames - 1; i++) {
  432. offset += write_opuslacing(avpkt->data + offset,
  433. s->frame[i].framebits >> 3);
  434. }
  435. }
  436. /* Packets */
  437. for (int i = 0; i < s->packet.frames; i++) {
  438. ff_opus_rc_enc_end(&s->rc[i], avpkt->data + offset,
  439. s->frame[i].framebits >> 3);
  440. offset += s->frame[i].framebits >> 3;
  441. }
  442. avpkt->size = offset;
  443. }
  444. /* Used as overlap for the first frame and padding for the last encoded packet */
  445. static AVFrame *spawn_empty_frame(OpusEncContext *s)
  446. {
  447. AVFrame *f = av_frame_alloc();
  448. int ret;
  449. if (!f)
  450. return NULL;
  451. f->format = s->avctx->sample_fmt;
  452. f->nb_samples = s->avctx->frame_size;
  453. ret = av_channel_layout_copy(&f->ch_layout, &s->avctx->ch_layout);
  454. if (ret < 0) {
  455. av_frame_free(&f);
  456. return NULL;
  457. }
  458. if (av_frame_get_buffer(f, 4)) {
  459. av_frame_free(&f);
  460. return NULL;
  461. }
  462. for (int i = 0; i < s->channels; i++) {
  463. size_t bps = av_get_bytes_per_sample(f->format);
  464. memset(f->extended_data[i], 0, bps*f->nb_samples);
  465. }
  466. return f;
  467. }
  468. static int opus_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  469. const AVFrame *frame, int *got_packet_ptr)
  470. {
  471. OpusEncContext *s = avctx->priv_data;
  472. int ret, frame_size, alloc_size = 0;
  473. if (frame) { /* Add new frame to queue */
  474. if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
  475. return ret;
  476. ff_bufqueue_add(avctx, &s->bufqueue, av_frame_clone(frame));
  477. } else {
  478. ff_opus_psy_signal_eof(&s->psyctx);
  479. if (!s->afq.remaining_samples || !avctx->frame_num)
  480. return 0; /* We've been flushed and there's nothing left to encode */
  481. }
  482. /* Run the psychoacoustic system */
  483. if (ff_opus_psy_process(&s->psyctx, &s->packet))
  484. return 0;
  485. frame_size = OPUS_BLOCK_SIZE(s->packet.framesize);
  486. if (!frame) {
  487. /* This can go negative, that's not a problem, we only pad if positive */
  488. int pad_empty = s->packet.frames*(frame_size/s->avctx->frame_size) - s->bufqueue.available + 1;
  489. /* Pad with empty 2.5 ms frames to whatever framesize was decided,
  490. * this should only happen at the very last flush frame. The frames
  491. * allocated here will be freed (because they have no other references)
  492. * after they get used by celt_frame_setup_input() */
  493. for (int i = 0; i < pad_empty; i++) {
  494. AVFrame *empty = spawn_empty_frame(s);
  495. if (!empty)
  496. return AVERROR(ENOMEM);
  497. ff_bufqueue_add(avctx, &s->bufqueue, empty);
  498. }
  499. }
  500. for (int i = 0; i < s->packet.frames; i++) {
  501. celt_encode_frame(s, &s->rc[i], &s->frame[i], i);
  502. alloc_size += s->frame[i].framebits >> 3;
  503. }
  504. /* Worst case toc + the frame lengths if needed */
  505. alloc_size += 2 + s->packet.frames*2;
  506. if ((ret = ff_alloc_packet(avctx, avpkt, alloc_size)) < 0)
  507. return ret;
  508. /* Assemble packet */
  509. opus_packet_assembler(s, avpkt);
  510. /* Update the psychoacoustic system */
  511. ff_opus_psy_postencode_update(&s->psyctx, s->frame);
  512. /* Remove samples from queue and skip if needed */
  513. ff_af_queue_remove(&s->afq, s->packet.frames*frame_size, &avpkt->pts, &avpkt->duration);
  514. if (s->packet.frames*frame_size > avpkt->duration) {
  515. uint8_t *side = av_packet_new_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
  516. if (!side)
  517. return AVERROR(ENOMEM);
  518. AV_WL32(&side[4], s->packet.frames*frame_size - avpkt->duration + 120);
  519. }
  520. *got_packet_ptr = 1;
  521. return 0;
  522. }
  523. static av_cold int opus_encode_end(AVCodecContext *avctx)
  524. {
  525. OpusEncContext *s = avctx->priv_data;
  526. for (int i = 0; i < CELT_BLOCK_NB; i++)
  527. av_tx_uninit(&s->tx[i]);
  528. ff_celt_pvq_uninit(&s->pvq);
  529. av_freep(&s->dsp);
  530. av_freep(&s->frame);
  531. av_freep(&s->rc);
  532. ff_af_queue_close(&s->afq);
  533. ff_opus_psy_end(&s->psyctx);
  534. ff_bufqueue_discard_all(&s->bufqueue);
  535. return 0;
  536. }
  537. static av_cold int opus_encode_init(AVCodecContext *avctx)
  538. {
  539. int ret, max_frames;
  540. OpusEncContext *s = avctx->priv_data;
  541. s->avctx = avctx;
  542. s->channels = avctx->ch_layout.nb_channels;
  543. /* Opus allows us to change the framesize on each packet (and each packet may
  544. * have multiple frames in it) but we can't change the codec's frame size on
  545. * runtime, so fix it to the lowest possible number of samples and use a queue
  546. * to accumulate AVFrames until we have enough to encode whatever the encoder
  547. * decides is the best */
  548. avctx->frame_size = 120;
  549. /* Initial padding will change if SILK is ever supported */
  550. avctx->initial_padding = 120;
  551. if (!avctx->bit_rate) {
  552. int coupled = ff_opus_default_coupled_streams[s->channels - 1];
  553. avctx->bit_rate = coupled*(96000) + (s->channels - coupled*2)*(48000);
  554. } else if (avctx->bit_rate < 6000 || avctx->bit_rate > 255000 * s->channels) {
  555. int64_t clipped_rate = av_clip(avctx->bit_rate, 6000, 255000 * s->channels);
  556. av_log(avctx, AV_LOG_ERROR, "Unsupported bitrate %"PRId64" kbps, clipping to %"PRId64" kbps\n",
  557. avctx->bit_rate/1000, clipped_rate/1000);
  558. avctx->bit_rate = clipped_rate;
  559. }
  560. /* Extradata */
  561. avctx->extradata_size = 19;
  562. avctx->extradata = av_malloc(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
  563. if (!avctx->extradata)
  564. return AVERROR(ENOMEM);
  565. opus_write_extradata(avctx);
  566. ff_af_queue_init(avctx, &s->afq);
  567. if ((ret = ff_celt_pvq_init(&s->pvq, 1)) < 0)
  568. return ret;
  569. if (!(s->dsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT)))
  570. return AVERROR(ENOMEM);
  571. /* I have no idea why a base scaling factor of 68 works, could be the twiddles */
  572. for (int i = 0; i < CELT_BLOCK_NB; i++) {
  573. const float scale = 68 << (CELT_BLOCK_NB - 1 - i);
  574. if ((ret = av_tx_init(&s->tx[i], &s->tx_fn[i], AV_TX_FLOAT_MDCT, 0, 15 << (i + 3), &scale, 0)))
  575. return AVERROR(ENOMEM);
  576. }
  577. /* Zero out previous energy (matters for inter first frame) */
  578. for (int ch = 0; ch < s->channels; ch++)
  579. memset(s->last_quantized_energy[ch], 0.0f, sizeof(float)*CELT_MAX_BANDS);
  580. /* Allocate an empty frame to use as overlap for the first frame of audio */
  581. ff_bufqueue_add(avctx, &s->bufqueue, spawn_empty_frame(s));
  582. if (!ff_bufqueue_peek(&s->bufqueue, 0))
  583. return AVERROR(ENOMEM);
  584. if ((ret = ff_opus_psy_init(&s->psyctx, s->avctx, &s->bufqueue, &s->options)))
  585. return ret;
  586. /* Frame structs and range coder buffers */
  587. max_frames = ceilf(FFMIN(s->options.max_delay_ms, 120.0f)/2.5f);
  588. s->frame = av_malloc(max_frames*sizeof(CeltFrame));
  589. if (!s->frame)
  590. return AVERROR(ENOMEM);
  591. s->rc = av_malloc(max_frames*sizeof(OpusRangeCoder));
  592. if (!s->rc)
  593. return AVERROR(ENOMEM);
  594. for (int i = 0; i < max_frames; i++) {
  595. s->frame[i].dsp = s->dsp;
  596. s->frame[i].avctx = s->avctx;
  597. s->frame[i].seed = 0;
  598. s->frame[i].pvq = s->pvq;
  599. s->frame[i].apply_phase_inv = s->options.apply_phase_inv;
  600. s->frame[i].block[0].emph_coeff = s->frame[i].block[1].emph_coeff = 0.0f;
  601. }
  602. return 0;
  603. }
  604. #define OPUSENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
  605. static const AVOption opusenc_options[] = {
  606. { "opus_delay", "Maximum delay in milliseconds", offsetof(OpusEncContext, options.max_delay_ms), AV_OPT_TYPE_FLOAT, { .dbl = OPUS_MAX_LOOKAHEAD }, 2.5f, OPUS_MAX_LOOKAHEAD, OPUSENC_FLAGS, .unit = "max_delay_ms" },
  607. { "apply_phase_inv", "Apply intensity stereo phase inversion", offsetof(OpusEncContext, options.apply_phase_inv), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, OPUSENC_FLAGS, .unit = "apply_phase_inv" },
  608. { NULL },
  609. };
  610. static const AVClass opusenc_class = {
  611. .class_name = "Opus encoder",
  612. .item_name = av_default_item_name,
  613. .option = opusenc_options,
  614. .version = LIBAVUTIL_VERSION_INT,
  615. };
  616. static const FFCodecDefault opusenc_defaults[] = {
  617. { "b", "0" },
  618. { "compression_level", "10" },
  619. { NULL },
  620. };
  621. const FFCodec ff_opus_encoder = {
  622. .p.name = "opus",
  623. CODEC_LONG_NAME("Opus"),
  624. .p.type = AVMEDIA_TYPE_AUDIO,
  625. .p.id = AV_CODEC_ID_OPUS,
  626. .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
  627. AV_CODEC_CAP_SMALL_LAST_FRAME | AV_CODEC_CAP_EXPERIMENTAL,
  628. .defaults = opusenc_defaults,
  629. .p.priv_class = &opusenc_class,
  630. .priv_data_size = sizeof(OpusEncContext),
  631. .init = opus_encode_init,
  632. FF_CODEC_ENCODE_CB(opus_encode_frame),
  633. .close = opus_encode_end,
  634. .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
  635. CODEC_SAMPLERATES(48000),
  636. CODEC_CH_LAYOUTS(AV_CHANNEL_LAYOUT_MONO, AV_CHANNEL_LAYOUT_STEREO),
  637. CODEC_SAMPLEFMTS(AV_SAMPLE_FMT_FLTP),
  638. };