opus.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. /*
  2. * Copyright (c) 2012 Andrew D'Addesio
  3. * Copyright (c) 2013-2014 Mozilla Corporation
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * Opus decoder/parser shared code
  24. */
  25. #include <stdint.h>
  26. #include "libavutil/error.h"
  27. #include "libavutil/ffmath.h"
  28. #include "opus_celt.h"
  29. #include "opustab.h"
  30. #include "vorbis.h"
  31. static const uint16_t opus_frame_duration[32] = {
  32. 480, 960, 1920, 2880,
  33. 480, 960, 1920, 2880,
  34. 480, 960, 1920, 2880,
  35. 480, 960,
  36. 480, 960,
  37. 120, 240, 480, 960,
  38. 120, 240, 480, 960,
  39. 120, 240, 480, 960,
  40. 120, 240, 480, 960,
  41. };
  42. /**
  43. * Read a 1- or 2-byte frame length
  44. */
  45. static inline int xiph_lacing_16bit(const uint8_t **ptr, const uint8_t *end)
  46. {
  47. int val;
  48. if (*ptr >= end)
  49. return AVERROR_INVALIDDATA;
  50. val = *(*ptr)++;
  51. if (val >= 252) {
  52. if (*ptr >= end)
  53. return AVERROR_INVALIDDATA;
  54. val += 4 * *(*ptr)++;
  55. }
  56. return val;
  57. }
  58. /**
  59. * Read a multi-byte length (used for code 3 packet padding size)
  60. */
  61. static inline int xiph_lacing_full(const uint8_t **ptr, const uint8_t *end)
  62. {
  63. int val = 0;
  64. int next;
  65. while (1) {
  66. if (*ptr >= end || val > INT_MAX - 254)
  67. return AVERROR_INVALIDDATA;
  68. next = *(*ptr)++;
  69. val += next;
  70. if (next < 255)
  71. break;
  72. else
  73. val--;
  74. }
  75. return val;
  76. }
  77. /**
  78. * Parse Opus packet info from raw packet data
  79. */
  80. int ff_opus_parse_packet(OpusPacket *pkt, const uint8_t *buf, int buf_size,
  81. int self_delimiting)
  82. {
  83. const uint8_t *ptr = buf;
  84. const uint8_t *end = buf + buf_size;
  85. int padding = 0;
  86. int frame_bytes, i;
  87. if (buf_size < 1)
  88. goto fail;
  89. /* TOC byte */
  90. i = *ptr++;
  91. pkt->code = (i ) & 0x3;
  92. pkt->stereo = (i >> 2) & 0x1;
  93. pkt->config = (i >> 3) & 0x1F;
  94. /* code 2 and code 3 packets have at least 1 byte after the TOC */
  95. if (pkt->code >= 2 && buf_size < 2)
  96. goto fail;
  97. switch (pkt->code) {
  98. case 0:
  99. /* 1 frame */
  100. pkt->frame_count = 1;
  101. pkt->vbr = 0;
  102. if (self_delimiting) {
  103. int len = xiph_lacing_16bit(&ptr, end);
  104. if (len < 0 || len > end - ptr)
  105. goto fail;
  106. end = ptr + len;
  107. buf_size = end - buf;
  108. }
  109. frame_bytes = end - ptr;
  110. if (frame_bytes > MAX_FRAME_SIZE)
  111. goto fail;
  112. pkt->frame_offset[0] = ptr - buf;
  113. pkt->frame_size[0] = frame_bytes;
  114. break;
  115. case 1:
  116. /* 2 frames, equal size */
  117. pkt->frame_count = 2;
  118. pkt->vbr = 0;
  119. if (self_delimiting) {
  120. int len = xiph_lacing_16bit(&ptr, end);
  121. if (len < 0 || 2 * len > end - ptr)
  122. goto fail;
  123. end = ptr + 2 * len;
  124. buf_size = end - buf;
  125. }
  126. frame_bytes = end - ptr;
  127. if (frame_bytes & 1 || frame_bytes >> 1 > MAX_FRAME_SIZE)
  128. goto fail;
  129. pkt->frame_offset[0] = ptr - buf;
  130. pkt->frame_size[0] = frame_bytes >> 1;
  131. pkt->frame_offset[1] = pkt->frame_offset[0] + pkt->frame_size[0];
  132. pkt->frame_size[1] = frame_bytes >> 1;
  133. break;
  134. case 2:
  135. /* 2 frames, different sizes */
  136. pkt->frame_count = 2;
  137. pkt->vbr = 1;
  138. /* read 1st frame size */
  139. frame_bytes = xiph_lacing_16bit(&ptr, end);
  140. if (frame_bytes < 0)
  141. goto fail;
  142. if (self_delimiting) {
  143. int len = xiph_lacing_16bit(&ptr, end);
  144. if (len < 0 || len + frame_bytes > end - ptr)
  145. goto fail;
  146. end = ptr + frame_bytes + len;
  147. buf_size = end - buf;
  148. }
  149. pkt->frame_offset[0] = ptr - buf;
  150. pkt->frame_size[0] = frame_bytes;
  151. /* calculate 2nd frame size */
  152. frame_bytes = end - ptr - pkt->frame_size[0];
  153. if (frame_bytes < 0 || frame_bytes > MAX_FRAME_SIZE)
  154. goto fail;
  155. pkt->frame_offset[1] = pkt->frame_offset[0] + pkt->frame_size[0];
  156. pkt->frame_size[1] = frame_bytes;
  157. break;
  158. case 3:
  159. /* 1 to 48 frames, can be different sizes */
  160. i = *ptr++;
  161. pkt->frame_count = (i ) & 0x3F;
  162. padding = (i >> 6) & 0x01;
  163. pkt->vbr = (i >> 7) & 0x01;
  164. if (pkt->frame_count == 0 || pkt->frame_count > MAX_FRAMES)
  165. goto fail;
  166. /* read padding size */
  167. if (padding) {
  168. padding = xiph_lacing_full(&ptr, end);
  169. if (padding < 0)
  170. goto fail;
  171. }
  172. /* read frame sizes */
  173. if (pkt->vbr) {
  174. /* for VBR, all frames except the final one have their size coded
  175. in the bitstream. the last frame size is implicit. */
  176. int total_bytes = 0;
  177. for (i = 0; i < pkt->frame_count - 1; i++) {
  178. frame_bytes = xiph_lacing_16bit(&ptr, end);
  179. if (frame_bytes < 0)
  180. goto fail;
  181. pkt->frame_size[i] = frame_bytes;
  182. total_bytes += frame_bytes;
  183. }
  184. if (self_delimiting) {
  185. int len = xiph_lacing_16bit(&ptr, end);
  186. if (len < 0 || len + total_bytes + padding > end - ptr)
  187. goto fail;
  188. end = ptr + total_bytes + len + padding;
  189. buf_size = end - buf;
  190. }
  191. frame_bytes = end - ptr - padding;
  192. if (total_bytes > frame_bytes)
  193. goto fail;
  194. pkt->frame_offset[0] = ptr - buf;
  195. for (i = 1; i < pkt->frame_count; i++)
  196. pkt->frame_offset[i] = pkt->frame_offset[i-1] + pkt->frame_size[i-1];
  197. pkt->frame_size[pkt->frame_count-1] = frame_bytes - total_bytes;
  198. } else {
  199. /* for CBR, the remaining packet bytes are divided evenly between
  200. the frames */
  201. if (self_delimiting) {
  202. frame_bytes = xiph_lacing_16bit(&ptr, end);
  203. if (frame_bytes < 0 || pkt->frame_count * frame_bytes + padding > end - ptr)
  204. goto fail;
  205. end = ptr + pkt->frame_count * frame_bytes + padding;
  206. buf_size = end - buf;
  207. } else {
  208. frame_bytes = end - ptr - padding;
  209. if (frame_bytes % pkt->frame_count ||
  210. frame_bytes / pkt->frame_count > MAX_FRAME_SIZE)
  211. goto fail;
  212. frame_bytes /= pkt->frame_count;
  213. }
  214. pkt->frame_offset[0] = ptr - buf;
  215. pkt->frame_size[0] = frame_bytes;
  216. for (i = 1; i < pkt->frame_count; i++) {
  217. pkt->frame_offset[i] = pkt->frame_offset[i-1] + pkt->frame_size[i-1];
  218. pkt->frame_size[i] = frame_bytes;
  219. }
  220. }
  221. }
  222. pkt->packet_size = buf_size;
  223. pkt->data_size = pkt->packet_size - padding;
  224. /* total packet duration cannot be larger than 120ms */
  225. pkt->frame_duration = opus_frame_duration[pkt->config];
  226. if (pkt->frame_duration * pkt->frame_count > MAX_PACKET_DUR)
  227. goto fail;
  228. /* set mode and bandwidth */
  229. if (pkt->config < 12) {
  230. pkt->mode = OPUS_MODE_SILK;
  231. pkt->bandwidth = pkt->config >> 2;
  232. } else if (pkt->config < 16) {
  233. pkt->mode = OPUS_MODE_HYBRID;
  234. pkt->bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND + (pkt->config >= 14);
  235. } else {
  236. pkt->mode = OPUS_MODE_CELT;
  237. pkt->bandwidth = (pkt->config - 16) >> 2;
  238. /* skip medium band */
  239. if (pkt->bandwidth)
  240. pkt->bandwidth++;
  241. }
  242. return 0;
  243. fail:
  244. memset(pkt, 0, sizeof(*pkt));
  245. return AVERROR_INVALIDDATA;
  246. }
  247. static int channel_reorder_vorbis(int nb_channels, int channel_idx)
  248. {
  249. return ff_vorbis_channel_layout_offsets[nb_channels - 1][channel_idx];
  250. }
  251. static int channel_reorder_unknown(int nb_channels, int channel_idx)
  252. {
  253. return channel_idx;
  254. }
  255. av_cold int ff_opus_parse_extradata(AVCodecContext *avctx,
  256. OpusContext *s)
  257. {
  258. static const uint8_t default_channel_map[2] = { 0, 1 };
  259. int (*channel_reorder)(int, int) = channel_reorder_unknown;
  260. const uint8_t *extradata, *channel_map;
  261. int extradata_size;
  262. int version, channels, map_type, streams, stereo_streams, i, j;
  263. uint64_t layout;
  264. if (!avctx->extradata) {
  265. if (avctx->channels > 2) {
  266. av_log(avctx, AV_LOG_ERROR,
  267. "Multichannel configuration without extradata.\n");
  268. return AVERROR(EINVAL);
  269. }
  270. extradata = opus_default_extradata;
  271. extradata_size = sizeof(opus_default_extradata);
  272. } else {
  273. extradata = avctx->extradata;
  274. extradata_size = avctx->extradata_size;
  275. }
  276. if (extradata_size < 19) {
  277. av_log(avctx, AV_LOG_ERROR, "Invalid extradata size: %d\n",
  278. extradata_size);
  279. return AVERROR_INVALIDDATA;
  280. }
  281. version = extradata[8];
  282. if (version > 15) {
  283. avpriv_request_sample(avctx, "Extradata version %d", version);
  284. return AVERROR_PATCHWELCOME;
  285. }
  286. avctx->delay = AV_RL16(extradata + 10);
  287. channels = avctx->extradata ? extradata[9] : (avctx->channels == 1) ? 1 : 2;
  288. if (!channels) {
  289. av_log(avctx, AV_LOG_ERROR, "Zero channel count specified in the extradata\n");
  290. return AVERROR_INVALIDDATA;
  291. }
  292. s->gain_i = AV_RL16(extradata + 16);
  293. if (s->gain_i)
  294. s->gain = ff_exp10(s->gain_i / (20.0 * 256));
  295. map_type = extradata[18];
  296. if (!map_type) {
  297. if (channels > 2) {
  298. av_log(avctx, AV_LOG_ERROR,
  299. "Channel mapping 0 is only specified for up to 2 channels\n");
  300. return AVERROR_INVALIDDATA;
  301. }
  302. layout = (channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
  303. streams = 1;
  304. stereo_streams = channels - 1;
  305. channel_map = default_channel_map;
  306. } else if (map_type == 1 || map_type == 2 || map_type == 255) {
  307. if (extradata_size < 21 + channels) {
  308. av_log(avctx, AV_LOG_ERROR, "Invalid extradata size: %d\n",
  309. extradata_size);
  310. return AVERROR_INVALIDDATA;
  311. }
  312. streams = extradata[19];
  313. stereo_streams = extradata[20];
  314. if (!streams || stereo_streams > streams ||
  315. streams + stereo_streams > 255) {
  316. av_log(avctx, AV_LOG_ERROR,
  317. "Invalid stream/stereo stream count: %d/%d\n", streams, stereo_streams);
  318. return AVERROR_INVALIDDATA;
  319. }
  320. if (map_type == 1) {
  321. if (channels > 8) {
  322. av_log(avctx, AV_LOG_ERROR,
  323. "Channel mapping 1 is only specified for up to 8 channels\n");
  324. return AVERROR_INVALIDDATA;
  325. }
  326. layout = ff_vorbis_channel_layouts[channels - 1];
  327. channel_reorder = channel_reorder_vorbis;
  328. } else if (map_type == 2) {
  329. int ambisonic_order = ff_sqrt(channels) - 1;
  330. if (channels != ((ambisonic_order + 1) * (ambisonic_order + 1)) &&
  331. channels != ((ambisonic_order + 1) * (ambisonic_order + 1) + 2)) {
  332. av_log(avctx, AV_LOG_ERROR,
  333. "Channel mapping 2 is only specified for channel counts"
  334. " which can be written as (n + 1)^2 or (n + 1)^2 + 2"
  335. " for nonnegative integer n\n");
  336. return AVERROR_INVALIDDATA;
  337. }
  338. if (channels > 227) {
  339. av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
  340. return AVERROR_INVALIDDATA;
  341. }
  342. layout = 0;
  343. } else
  344. layout = 0;
  345. channel_map = extradata + 21;
  346. } else {
  347. avpriv_request_sample(avctx, "Mapping type %d", map_type);
  348. return AVERROR_PATCHWELCOME;
  349. }
  350. s->channel_maps = av_mallocz_array(channels, sizeof(*s->channel_maps));
  351. if (!s->channel_maps)
  352. return AVERROR(ENOMEM);
  353. for (i = 0; i < channels; i++) {
  354. ChannelMap *map = &s->channel_maps[i];
  355. uint8_t idx = channel_map[channel_reorder(channels, i)];
  356. if (idx == 255) {
  357. map->silence = 1;
  358. continue;
  359. } else if (idx >= streams + stereo_streams) {
  360. av_log(avctx, AV_LOG_ERROR,
  361. "Invalid channel map for output channel %d: %d\n", i, idx);
  362. av_freep(&s->channel_maps);
  363. return AVERROR_INVALIDDATA;
  364. }
  365. /* check that we did not see this index yet */
  366. map->copy = 0;
  367. for (j = 0; j < i; j++)
  368. if (channel_map[channel_reorder(channels, j)] == idx) {
  369. map->copy = 1;
  370. map->copy_idx = j;
  371. break;
  372. }
  373. if (idx < 2 * stereo_streams) {
  374. map->stream_idx = idx / 2;
  375. map->channel_idx = idx & 1;
  376. } else {
  377. map->stream_idx = idx - stereo_streams;
  378. map->channel_idx = 0;
  379. }
  380. }
  381. avctx->channels = channels;
  382. avctx->channel_layout = layout;
  383. s->nb_streams = streams;
  384. s->nb_stereo_streams = stereo_streams;
  385. return 0;
  386. }
  387. void ff_celt_quant_bands(CeltFrame *f, OpusRangeCoder *rc)
  388. {
  389. float lowband_scratch[8 * 22];
  390. float norm1[2 * 8 * 100];
  391. float *norm2 = norm1 + 8 * 100;
  392. int totalbits = (f->framebits << 3) - f->anticollapse_needed;
  393. int update_lowband = 1;
  394. int lowband_offset = 0;
  395. int i, j;
  396. for (i = f->start_band; i < f->end_band; i++) {
  397. uint32_t cm[2] = { (1 << f->blocks) - 1, (1 << f->blocks) - 1 };
  398. int band_offset = ff_celt_freq_bands[i] << f->size;
  399. int band_size = ff_celt_freq_range[i] << f->size;
  400. float *X = f->block[0].coeffs + band_offset;
  401. float *Y = (f->channels == 2) ? f->block[1].coeffs + band_offset : NULL;
  402. float *norm_loc1, *norm_loc2;
  403. int consumed = opus_rc_tell_frac(rc);
  404. int effective_lowband = -1;
  405. int b = 0;
  406. /* Compute how many bits we want to allocate to this band */
  407. if (i != f->start_band)
  408. f->remaining -= consumed;
  409. f->remaining2 = totalbits - consumed - 1;
  410. if (i <= f->coded_bands - 1) {
  411. int curr_balance = f->remaining / FFMIN(3, f->coded_bands-i);
  412. b = av_clip_uintp2(FFMIN(f->remaining2 + 1, f->pulses[i] + curr_balance), 14);
  413. }
  414. if ((ff_celt_freq_bands[i] - ff_celt_freq_range[i] >= ff_celt_freq_bands[f->start_band] ||
  415. i == f->start_band + 1) && (update_lowband || lowband_offset == 0))
  416. lowband_offset = i;
  417. if (i == f->start_band + 1) {
  418. /* Special Hybrid Folding (RFC 8251 section 9). Copy the first band into
  419. the second to ensure the second band never has to use the LCG. */
  420. int count = (ff_celt_freq_range[i] - ff_celt_freq_range[i-1]) << f->size;
  421. memcpy(&norm1[band_offset], &norm1[band_offset - count], count * sizeof(float));
  422. if (f->channels == 2)
  423. memcpy(&norm2[band_offset], &norm2[band_offset - count], count * sizeof(float));
  424. }
  425. /* Get a conservative estimate of the collapse_mask's for the bands we're
  426. going to be folding from. */
  427. if (lowband_offset != 0 && (f->spread != CELT_SPREAD_AGGRESSIVE ||
  428. f->blocks > 1 || f->tf_change[i] < 0)) {
  429. int foldstart, foldend;
  430. /* This ensures we never repeat spectral content within one band */
  431. effective_lowband = FFMAX(ff_celt_freq_bands[f->start_band],
  432. ff_celt_freq_bands[lowband_offset] - ff_celt_freq_range[i]);
  433. foldstart = lowband_offset;
  434. while (ff_celt_freq_bands[--foldstart] > effective_lowband);
  435. foldend = lowband_offset - 1;
  436. while (++foldend < i && ff_celt_freq_bands[foldend] < effective_lowband + ff_celt_freq_range[i]);
  437. cm[0] = cm[1] = 0;
  438. for (j = foldstart; j < foldend; j++) {
  439. cm[0] |= f->block[0].collapse_masks[j];
  440. cm[1] |= f->block[f->channels - 1].collapse_masks[j];
  441. }
  442. }
  443. if (f->dual_stereo && i == f->intensity_stereo) {
  444. /* Switch off dual stereo to do intensity */
  445. f->dual_stereo = 0;
  446. for (j = ff_celt_freq_bands[f->start_band] << f->size; j < band_offset; j++)
  447. norm1[j] = (norm1[j] + norm2[j]) / 2;
  448. }
  449. norm_loc1 = effective_lowband != -1 ? norm1 + (effective_lowband << f->size) : NULL;
  450. norm_loc2 = effective_lowband != -1 ? norm2 + (effective_lowband << f->size) : NULL;
  451. if (f->dual_stereo) {
  452. cm[0] = f->pvq->quant_band(f->pvq, f, rc, i, X, NULL, band_size, b >> 1,
  453. f->blocks, norm_loc1, f->size,
  454. norm1 + band_offset, 0, 1.0f,
  455. lowband_scratch, cm[0]);
  456. cm[1] = f->pvq->quant_band(f->pvq, f, rc, i, Y, NULL, band_size, b >> 1,
  457. f->blocks, norm_loc2, f->size,
  458. norm2 + band_offset, 0, 1.0f,
  459. lowband_scratch, cm[1]);
  460. } else {
  461. cm[0] = f->pvq->quant_band(f->pvq, f, rc, i, X, Y, band_size, b >> 0,
  462. f->blocks, norm_loc1, f->size,
  463. norm1 + band_offset, 0, 1.0f,
  464. lowband_scratch, cm[0] | cm[1]);
  465. cm[1] = cm[0];
  466. }
  467. f->block[0].collapse_masks[i] = (uint8_t)cm[0];
  468. f->block[f->channels - 1].collapse_masks[i] = (uint8_t)cm[1];
  469. f->remaining += f->pulses[i] + consumed;
  470. /* Update the folding position only as long as we have 1 bit/sample depth */
  471. update_lowband = (b > band_size << 3);
  472. }
  473. }
  474. #define NORMC(bits) ((bits) << (f->channels - 1) << f->size >> 2)
  475. void ff_celt_bitalloc(CeltFrame *f, OpusRangeCoder *rc, int encode)
  476. {
  477. int i, j, low, high, total, done, bandbits, remaining, tbits_8ths;
  478. int skip_startband = f->start_band;
  479. int skip_bit = 0;
  480. int intensitystereo_bit = 0;
  481. int dualstereo_bit = 0;
  482. int dynalloc = 6;
  483. int extrabits = 0;
  484. int boost[CELT_MAX_BANDS] = { 0 };
  485. int trim_offset[CELT_MAX_BANDS];
  486. int threshold[CELT_MAX_BANDS];
  487. int bits1[CELT_MAX_BANDS];
  488. int bits2[CELT_MAX_BANDS];
  489. /* Spread */
  490. if (opus_rc_tell(rc) + 4 <= f->framebits) {
  491. if (encode)
  492. ff_opus_rc_enc_cdf(rc, f->spread, ff_celt_model_spread);
  493. else
  494. f->spread = ff_opus_rc_dec_cdf(rc, ff_celt_model_spread);
  495. } else {
  496. f->spread = CELT_SPREAD_NORMAL;
  497. }
  498. /* Initialize static allocation caps */
  499. for (i = 0; i < CELT_MAX_BANDS; i++)
  500. f->caps[i] = NORMC((ff_celt_static_caps[f->size][f->channels - 1][i] + 64) * ff_celt_freq_range[i]);
  501. /* Band boosts */
  502. tbits_8ths = f->framebits << 3;
  503. for (i = f->start_band; i < f->end_band; i++) {
  504. int quanta = ff_celt_freq_range[i] << (f->channels - 1) << f->size;
  505. int b_dynalloc = dynalloc;
  506. int boost_amount = f->alloc_boost[i];
  507. quanta = FFMIN(quanta << 3, FFMAX(6 << 3, quanta));
  508. while (opus_rc_tell_frac(rc) + (b_dynalloc << 3) < tbits_8ths && boost[i] < f->caps[i]) {
  509. int is_boost;
  510. if (encode) {
  511. is_boost = boost_amount--;
  512. ff_opus_rc_enc_log(rc, is_boost, b_dynalloc);
  513. } else {
  514. is_boost = ff_opus_rc_dec_log(rc, b_dynalloc);
  515. }
  516. if (!is_boost)
  517. break;
  518. boost[i] += quanta;
  519. tbits_8ths -= quanta;
  520. b_dynalloc = 1;
  521. }
  522. if (boost[i])
  523. dynalloc = FFMAX(dynalloc - 1, 2);
  524. }
  525. /* Allocation trim */
  526. if (opus_rc_tell_frac(rc) + (6 << 3) <= tbits_8ths)
  527. if (encode)
  528. ff_opus_rc_enc_cdf(rc, f->alloc_trim, ff_celt_model_alloc_trim);
  529. else
  530. f->alloc_trim = ff_opus_rc_dec_cdf(rc, ff_celt_model_alloc_trim);
  531. /* Anti-collapse bit reservation */
  532. tbits_8ths = (f->framebits << 3) - opus_rc_tell_frac(rc) - 1;
  533. f->anticollapse_needed = 0;
  534. if (f->transient && f->size >= 2 && tbits_8ths >= ((f->size + 2) << 3))
  535. f->anticollapse_needed = 1 << 3;
  536. tbits_8ths -= f->anticollapse_needed;
  537. /* Band skip bit reservation */
  538. if (tbits_8ths >= 1 << 3)
  539. skip_bit = 1 << 3;
  540. tbits_8ths -= skip_bit;
  541. /* Intensity/dual stereo bit reservation */
  542. if (f->channels == 2) {
  543. intensitystereo_bit = ff_celt_log2_frac[f->end_band - f->start_band];
  544. if (intensitystereo_bit <= tbits_8ths) {
  545. tbits_8ths -= intensitystereo_bit;
  546. if (tbits_8ths >= 1 << 3) {
  547. dualstereo_bit = 1 << 3;
  548. tbits_8ths -= 1 << 3;
  549. }
  550. } else {
  551. intensitystereo_bit = 0;
  552. }
  553. }
  554. /* Trim offsets */
  555. for (i = f->start_band; i < f->end_band; i++) {
  556. int trim = f->alloc_trim - 5 - f->size;
  557. int band = ff_celt_freq_range[i] * (f->end_band - i - 1);
  558. int duration = f->size + 3;
  559. int scale = duration + f->channels - 1;
  560. /* PVQ minimum allocation threshold, below this value the band is
  561. * skipped */
  562. threshold[i] = FFMAX(3 * ff_celt_freq_range[i] << duration >> 4,
  563. f->channels << 3);
  564. trim_offset[i] = trim * (band << scale) >> 6;
  565. if (ff_celt_freq_range[i] << f->size == 1)
  566. trim_offset[i] -= f->channels << 3;
  567. }
  568. /* Bisection */
  569. low = 1;
  570. high = CELT_VECTORS - 1;
  571. while (low <= high) {
  572. int center = (low + high) >> 1;
  573. done = total = 0;
  574. for (i = f->end_band - 1; i >= f->start_band; i--) {
  575. bandbits = NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[center][i]);
  576. if (bandbits)
  577. bandbits = FFMAX(bandbits + trim_offset[i], 0);
  578. bandbits += boost[i];
  579. if (bandbits >= threshold[i] || done) {
  580. done = 1;
  581. total += FFMIN(bandbits, f->caps[i]);
  582. } else if (bandbits >= f->channels << 3) {
  583. total += f->channels << 3;
  584. }
  585. }
  586. if (total > tbits_8ths)
  587. high = center - 1;
  588. else
  589. low = center + 1;
  590. }
  591. high = low--;
  592. /* Bisection */
  593. for (i = f->start_band; i < f->end_band; i++) {
  594. bits1[i] = NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[low][i]);
  595. bits2[i] = high >= CELT_VECTORS ? f->caps[i] :
  596. NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[high][i]);
  597. if (bits1[i])
  598. bits1[i] = FFMAX(bits1[i] + trim_offset[i], 0);
  599. if (bits2[i])
  600. bits2[i] = FFMAX(bits2[i] + trim_offset[i], 0);
  601. if (low)
  602. bits1[i] += boost[i];
  603. bits2[i] += boost[i];
  604. if (boost[i])
  605. skip_startband = i;
  606. bits2[i] = FFMAX(bits2[i] - bits1[i], 0);
  607. }
  608. /* Bisection */
  609. low = 0;
  610. high = 1 << CELT_ALLOC_STEPS;
  611. for (i = 0; i < CELT_ALLOC_STEPS; i++) {
  612. int center = (low + high) >> 1;
  613. done = total = 0;
  614. for (j = f->end_band - 1; j >= f->start_band; j--) {
  615. bandbits = bits1[j] + (center * bits2[j] >> CELT_ALLOC_STEPS);
  616. if (bandbits >= threshold[j] || done) {
  617. done = 1;
  618. total += FFMIN(bandbits, f->caps[j]);
  619. } else if (bandbits >= f->channels << 3)
  620. total += f->channels << 3;
  621. }
  622. if (total > tbits_8ths)
  623. high = center;
  624. else
  625. low = center;
  626. }
  627. /* Bisection */
  628. done = total = 0;
  629. for (i = f->end_band - 1; i >= f->start_band; i--) {
  630. bandbits = bits1[i] + (low * bits2[i] >> CELT_ALLOC_STEPS);
  631. if (bandbits >= threshold[i] || done)
  632. done = 1;
  633. else
  634. bandbits = (bandbits >= f->channels << 3) ?
  635. f->channels << 3 : 0;
  636. bandbits = FFMIN(bandbits, f->caps[i]);
  637. f->pulses[i] = bandbits;
  638. total += bandbits;
  639. }
  640. /* Band skipping */
  641. for (f->coded_bands = f->end_band; ; f->coded_bands--) {
  642. int allocation;
  643. j = f->coded_bands - 1;
  644. if (j == skip_startband) {
  645. /* all remaining bands are not skipped */
  646. tbits_8ths += skip_bit;
  647. break;
  648. }
  649. /* determine the number of bits available for coding "do not skip" markers */
  650. remaining = tbits_8ths - total;
  651. bandbits = remaining / (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
  652. remaining -= bandbits * (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
  653. allocation = f->pulses[j] + bandbits * ff_celt_freq_range[j];
  654. allocation += FFMAX(remaining - (ff_celt_freq_bands[j] - ff_celt_freq_bands[f->start_band]), 0);
  655. /* a "do not skip" marker is only coded if the allocation is
  656. * above the chosen threshold */
  657. if (allocation >= FFMAX(threshold[j], (f->channels + 1) << 3)) {
  658. int do_not_skip;
  659. if (encode) {
  660. do_not_skip = f->coded_bands <= f->skip_band_floor;
  661. ff_opus_rc_enc_log(rc, do_not_skip, 1);
  662. } else {
  663. do_not_skip = ff_opus_rc_dec_log(rc, 1);
  664. }
  665. if (do_not_skip)
  666. break;
  667. total += 1 << 3;
  668. allocation -= 1 << 3;
  669. }
  670. /* the band is skipped, so reclaim its bits */
  671. total -= f->pulses[j];
  672. if (intensitystereo_bit) {
  673. total -= intensitystereo_bit;
  674. intensitystereo_bit = ff_celt_log2_frac[j - f->start_band];
  675. total += intensitystereo_bit;
  676. }
  677. total += f->pulses[j] = (allocation >= f->channels << 3) ? f->channels << 3 : 0;
  678. }
  679. /* IS start band */
  680. if (encode) {
  681. if (intensitystereo_bit) {
  682. f->intensity_stereo = FFMIN(f->intensity_stereo, f->coded_bands);
  683. ff_opus_rc_enc_uint(rc, f->intensity_stereo, f->coded_bands + 1 - f->start_band);
  684. }
  685. } else {
  686. f->intensity_stereo = f->dual_stereo = 0;
  687. if (intensitystereo_bit)
  688. f->intensity_stereo = f->start_band + ff_opus_rc_dec_uint(rc, f->coded_bands + 1 - f->start_band);
  689. }
  690. /* DS flag */
  691. if (f->intensity_stereo <= f->start_band)
  692. tbits_8ths += dualstereo_bit; /* no intensity stereo means no dual stereo */
  693. else if (dualstereo_bit)
  694. if (encode)
  695. ff_opus_rc_enc_log(rc, f->dual_stereo, 1);
  696. else
  697. f->dual_stereo = ff_opus_rc_dec_log(rc, 1);
  698. /* Supply the remaining bits in this frame to lower bands */
  699. remaining = tbits_8ths - total;
  700. bandbits = remaining / (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
  701. remaining -= bandbits * (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
  702. for (i = f->start_band; i < f->coded_bands; i++) {
  703. const int bits = FFMIN(remaining, ff_celt_freq_range[i]);
  704. f->pulses[i] += bits + bandbits * ff_celt_freq_range[i];
  705. remaining -= bits;
  706. }
  707. /* Finally determine the allocation */
  708. for (i = f->start_band; i < f->coded_bands; i++) {
  709. int N = ff_celt_freq_range[i] << f->size;
  710. int prev_extra = extrabits;
  711. f->pulses[i] += extrabits;
  712. if (N > 1) {
  713. int dof; /* degrees of freedom */
  714. int temp; /* dof * channels * log(dof) */
  715. int fine_bits;
  716. int max_bits;
  717. int offset; /* fine energy quantization offset, i.e.
  718. * extra bits assigned over the standard
  719. * totalbits/dof */
  720. extrabits = FFMAX(f->pulses[i] - f->caps[i], 0);
  721. f->pulses[i] -= extrabits;
  722. /* intensity stereo makes use of an extra degree of freedom */
  723. dof = N * f->channels + (f->channels == 2 && N > 2 && !f->dual_stereo && i < f->intensity_stereo);
  724. temp = dof * (ff_celt_log_freq_range[i] + (f->size << 3));
  725. offset = (temp >> 1) - dof * CELT_FINE_OFFSET;
  726. if (N == 2) /* dof=2 is the only case that doesn't fit the model */
  727. offset += dof << 1;
  728. /* grant an additional bias for the first and second pulses */
  729. if (f->pulses[i] + offset < 2 * (dof << 3))
  730. offset += temp >> 2;
  731. else if (f->pulses[i] + offset < 3 * (dof << 3))
  732. offset += temp >> 3;
  733. fine_bits = (f->pulses[i] + offset + (dof << 2)) / (dof << 3);
  734. max_bits = FFMIN((f->pulses[i] >> 3) >> (f->channels - 1), CELT_MAX_FINE_BITS);
  735. max_bits = FFMAX(max_bits, 0);
  736. f->fine_bits[i] = av_clip(fine_bits, 0, max_bits);
  737. /* If fine_bits was rounded down or capped,
  738. * give priority for the final fine energy pass */
  739. f->fine_priority[i] = (f->fine_bits[i] * (dof << 3) >= f->pulses[i] + offset);
  740. /* the remaining bits are assigned to PVQ */
  741. f->pulses[i] -= f->fine_bits[i] << (f->channels - 1) << 3;
  742. } else {
  743. /* all bits go to fine energy except for the sign bit */
  744. extrabits = FFMAX(f->pulses[i] - (f->channels << 3), 0);
  745. f->pulses[i] -= extrabits;
  746. f->fine_bits[i] = 0;
  747. f->fine_priority[i] = 1;
  748. }
  749. /* hand back a limited number of extra fine energy bits to this band */
  750. if (extrabits > 0) {
  751. int fineextra = FFMIN(extrabits >> (f->channels + 2),
  752. CELT_MAX_FINE_BITS - f->fine_bits[i]);
  753. f->fine_bits[i] += fineextra;
  754. fineextra <<= f->channels + 2;
  755. f->fine_priority[i] = (fineextra >= extrabits - prev_extra);
  756. extrabits -= fineextra;
  757. }
  758. }
  759. f->remaining = extrabits;
  760. /* skipped bands dedicate all of their bits for fine energy */
  761. for (; i < f->end_band; i++) {
  762. f->fine_bits[i] = f->pulses[i] >> (f->channels - 1) >> 3;
  763. f->pulses[i] = 0;
  764. f->fine_priority[i] = f->fine_bits[i] < 1;
  765. }
  766. }