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.

899 lines
31KB

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