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.

903 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 = AV_RL16(extradata + 10);
  288. if (avctx->internal)
  289. avctx->internal->skip_samples = avctx->delay;
  290. channels = avctx->extradata ? extradata[9] : (avctx->channels == 1) ? 1 : 2;
  291. if (!channels) {
  292. av_log(avctx, AV_LOG_ERROR, "Zero channel count specified in the extradata\n");
  293. return AVERROR_INVALIDDATA;
  294. }
  295. s->gain_i = AV_RL16(extradata + 16);
  296. if (s->gain_i)
  297. s->gain = ff_exp10(s->gain_i / (20.0 * 256));
  298. map_type = extradata[18];
  299. if (!map_type) {
  300. if (channels > 2) {
  301. av_log(avctx, AV_LOG_ERROR,
  302. "Channel mapping 0 is only specified for up to 2 channels\n");
  303. return AVERROR_INVALIDDATA;
  304. }
  305. layout = (channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
  306. streams = 1;
  307. stereo_streams = channels - 1;
  308. channel_map = default_channel_map;
  309. } else if (map_type == 1 || map_type == 2 || map_type == 255) {
  310. if (extradata_size < 21 + channels) {
  311. av_log(avctx, AV_LOG_ERROR, "Invalid extradata size: %d\n",
  312. extradata_size);
  313. return AVERROR_INVALIDDATA;
  314. }
  315. streams = extradata[19];
  316. stereo_streams = extradata[20];
  317. if (!streams || stereo_streams > streams ||
  318. streams + stereo_streams > 255) {
  319. av_log(avctx, AV_LOG_ERROR,
  320. "Invalid stream/stereo stream count: %d/%d\n", streams, stereo_streams);
  321. return AVERROR_INVALIDDATA;
  322. }
  323. if (map_type == 1) {
  324. if (channels > 8) {
  325. av_log(avctx, AV_LOG_ERROR,
  326. "Channel mapping 1 is only specified for up to 8 channels\n");
  327. return AVERROR_INVALIDDATA;
  328. }
  329. layout = ff_vorbis_channel_layouts[channels - 1];
  330. channel_reorder = channel_reorder_vorbis;
  331. } else if (map_type == 2) {
  332. int ambisonic_order = ff_sqrt(channels) - 1;
  333. if (channels != ((ambisonic_order + 1) * (ambisonic_order + 1)) &&
  334. channels != ((ambisonic_order + 1) * (ambisonic_order + 1) + 2)) {
  335. av_log(avctx, AV_LOG_ERROR,
  336. "Channel mapping 2 is only specified for channel counts"
  337. " which can be written as (n + 1)^2 or (n + 1)^2 + 2"
  338. " for nonnegative integer n\n");
  339. return AVERROR_INVALIDDATA;
  340. }
  341. if (channels > 227) {
  342. av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
  343. return AVERROR_INVALIDDATA;
  344. }
  345. layout = 0;
  346. } else
  347. layout = 0;
  348. channel_map = extradata + 21;
  349. } else {
  350. avpriv_request_sample(avctx, "Mapping type %d", map_type);
  351. return AVERROR_PATCHWELCOME;
  352. }
  353. s->channel_maps = av_mallocz_array(channels, sizeof(*s->channel_maps));
  354. if (!s->channel_maps)
  355. return AVERROR(ENOMEM);
  356. for (i = 0; i < channels; i++) {
  357. ChannelMap *map = &s->channel_maps[i];
  358. uint8_t idx = channel_map[channel_reorder(channels, i)];
  359. if (idx == 255) {
  360. map->silence = 1;
  361. continue;
  362. } else if (idx >= streams + stereo_streams) {
  363. av_log(avctx, AV_LOG_ERROR,
  364. "Invalid channel map for output channel %d: %d\n", i, idx);
  365. av_freep(&s->channel_maps);
  366. return AVERROR_INVALIDDATA;
  367. }
  368. /* check that we did not see this index yet */
  369. map->copy = 0;
  370. for (j = 0; j < i; j++)
  371. if (channel_map[channel_reorder(channels, j)] == idx) {
  372. map->copy = 1;
  373. map->copy_idx = j;
  374. break;
  375. }
  376. if (idx < 2 * stereo_streams) {
  377. map->stream_idx = idx / 2;
  378. map->channel_idx = idx & 1;
  379. } else {
  380. map->stream_idx = idx - stereo_streams;
  381. map->channel_idx = 0;
  382. }
  383. }
  384. avctx->channels = channels;
  385. avctx->channel_layout = layout;
  386. s->nb_streams = streams;
  387. s->nb_stereo_streams = stereo_streams;
  388. return 0;
  389. }
  390. void ff_celt_quant_bands(CeltFrame *f, OpusRangeCoder *rc)
  391. {
  392. float lowband_scratch[8 * 22];
  393. float norm1[2 * 8 * 100];
  394. float *norm2 = norm1 + 8 * 100;
  395. int totalbits = (f->framebits << 3) - f->anticollapse_needed;
  396. int update_lowband = 1;
  397. int lowband_offset = 0;
  398. int i, j;
  399. for (i = f->start_band; i < f->end_band; i++) {
  400. uint32_t cm[2] = { (1 << f->blocks) - 1, (1 << f->blocks) - 1 };
  401. int band_offset = ff_celt_freq_bands[i] << f->size;
  402. int band_size = ff_celt_freq_range[i] << f->size;
  403. float *X = f->block[0].coeffs + band_offset;
  404. float *Y = (f->channels == 2) ? f->block[1].coeffs + band_offset : NULL;
  405. float *norm_loc1, *norm_loc2;
  406. int consumed = opus_rc_tell_frac(rc);
  407. int effective_lowband = -1;
  408. int b = 0;
  409. /* Compute how many bits we want to allocate to this band */
  410. if (i != f->start_band)
  411. f->remaining -= consumed;
  412. f->remaining2 = totalbits - consumed - 1;
  413. if (i <= f->coded_bands - 1) {
  414. int curr_balance = f->remaining / FFMIN(3, f->coded_bands-i);
  415. b = av_clip_uintp2(FFMIN(f->remaining2 + 1, f->pulses[i] + curr_balance), 14);
  416. }
  417. if ((ff_celt_freq_bands[i] - ff_celt_freq_range[i] >= ff_celt_freq_bands[f->start_band] ||
  418. i == f->start_band + 1) && (update_lowband || lowband_offset == 0))
  419. lowband_offset = i;
  420. if (i == f->start_band + 1) {
  421. /* Special Hybrid Folding (RFC 8251 section 9). Copy the first band into
  422. the second to ensure the second band never has to use the LCG. */
  423. int count = (ff_celt_freq_range[i] - ff_celt_freq_range[i-1]) << f->size;
  424. memcpy(&norm1[band_offset], &norm1[band_offset - count], count * sizeof(float));
  425. if (f->channels == 2)
  426. memcpy(&norm2[band_offset], &norm2[band_offset - count], count * sizeof(float));
  427. }
  428. /* Get a conservative estimate of the collapse_mask's for the bands we're
  429. going to be folding from. */
  430. if (lowband_offset != 0 && (f->spread != CELT_SPREAD_AGGRESSIVE ||
  431. f->blocks > 1 || f->tf_change[i] < 0)) {
  432. int foldstart, foldend;
  433. /* This ensures we never repeat spectral content within one band */
  434. effective_lowband = FFMAX(ff_celt_freq_bands[f->start_band],
  435. ff_celt_freq_bands[lowband_offset] - ff_celt_freq_range[i]);
  436. foldstart = lowband_offset;
  437. while (ff_celt_freq_bands[--foldstart] > effective_lowband);
  438. foldend = lowband_offset - 1;
  439. while (++foldend < i && ff_celt_freq_bands[foldend] < effective_lowband + ff_celt_freq_range[i]);
  440. cm[0] = cm[1] = 0;
  441. for (j = foldstart; j < foldend; j++) {
  442. cm[0] |= f->block[0].collapse_masks[j];
  443. cm[1] |= f->block[f->channels - 1].collapse_masks[j];
  444. }
  445. }
  446. if (f->dual_stereo && i == f->intensity_stereo) {
  447. /* Switch off dual stereo to do intensity */
  448. f->dual_stereo = 0;
  449. for (j = ff_celt_freq_bands[f->start_band] << f->size; j < band_offset; j++)
  450. norm1[j] = (norm1[j] + norm2[j]) / 2;
  451. }
  452. norm_loc1 = effective_lowband != -1 ? norm1 + (effective_lowband << f->size) : NULL;
  453. norm_loc2 = effective_lowband != -1 ? norm2 + (effective_lowband << f->size) : NULL;
  454. if (f->dual_stereo) {
  455. cm[0] = f->pvq->quant_band(f->pvq, f, rc, i, X, NULL, band_size, b >> 1,
  456. f->blocks, norm_loc1, f->size,
  457. norm1 + band_offset, 0, 1.0f,
  458. lowband_scratch, cm[0]);
  459. cm[1] = f->pvq->quant_band(f->pvq, f, rc, i, Y, NULL, band_size, b >> 1,
  460. f->blocks, norm_loc2, f->size,
  461. norm2 + band_offset, 0, 1.0f,
  462. lowband_scratch, cm[1]);
  463. } else {
  464. cm[0] = f->pvq->quant_band(f->pvq, f, rc, i, X, Y, band_size, b >> 0,
  465. f->blocks, norm_loc1, f->size,
  466. norm1 + band_offset, 0, 1.0f,
  467. lowband_scratch, cm[0] | cm[1]);
  468. cm[1] = cm[0];
  469. }
  470. f->block[0].collapse_masks[i] = (uint8_t)cm[0];
  471. f->block[f->channels - 1].collapse_masks[i] = (uint8_t)cm[1];
  472. f->remaining += f->pulses[i] + consumed;
  473. /* Update the folding position only as long as we have 1 bit/sample depth */
  474. update_lowband = (b > band_size << 3);
  475. }
  476. }
  477. #define NORMC(bits) ((bits) << (f->channels - 1) << f->size >> 2)
  478. void ff_celt_bitalloc(CeltFrame *f, OpusRangeCoder *rc, int encode)
  479. {
  480. int i, j, low, high, total, done, bandbits, remaining, tbits_8ths;
  481. int skip_startband = f->start_band;
  482. int skip_bit = 0;
  483. int intensitystereo_bit = 0;
  484. int dualstereo_bit = 0;
  485. int dynalloc = 6;
  486. int extrabits = 0;
  487. int boost[CELT_MAX_BANDS] = { 0 };
  488. int trim_offset[CELT_MAX_BANDS];
  489. int threshold[CELT_MAX_BANDS];
  490. int bits1[CELT_MAX_BANDS];
  491. int bits2[CELT_MAX_BANDS];
  492. /* Spread */
  493. if (opus_rc_tell(rc) + 4 <= f->framebits) {
  494. if (encode)
  495. ff_opus_rc_enc_cdf(rc, f->spread, ff_celt_model_spread);
  496. else
  497. f->spread = ff_opus_rc_dec_cdf(rc, ff_celt_model_spread);
  498. } else {
  499. f->spread = CELT_SPREAD_NORMAL;
  500. }
  501. /* Initialize static allocation caps */
  502. for (i = 0; i < CELT_MAX_BANDS; i++)
  503. f->caps[i] = NORMC((ff_celt_static_caps[f->size][f->channels - 1][i] + 64) * ff_celt_freq_range[i]);
  504. /* Band boosts */
  505. tbits_8ths = f->framebits << 3;
  506. for (i = f->start_band; i < f->end_band; i++) {
  507. int quanta = ff_celt_freq_range[i] << (f->channels - 1) << f->size;
  508. int b_dynalloc = dynalloc;
  509. int boost_amount = f->alloc_boost[i];
  510. quanta = FFMIN(quanta << 3, FFMAX(6 << 3, quanta));
  511. while (opus_rc_tell_frac(rc) + (b_dynalloc << 3) < tbits_8ths && boost[i] < f->caps[i]) {
  512. int is_boost;
  513. if (encode) {
  514. is_boost = boost_amount--;
  515. ff_opus_rc_enc_log(rc, is_boost, b_dynalloc);
  516. } else {
  517. is_boost = ff_opus_rc_dec_log(rc, b_dynalloc);
  518. }
  519. if (!is_boost)
  520. break;
  521. boost[i] += quanta;
  522. tbits_8ths -= quanta;
  523. b_dynalloc = 1;
  524. }
  525. if (boost[i])
  526. dynalloc = FFMAX(dynalloc - 1, 2);
  527. }
  528. /* Allocation trim */
  529. if (!encode)
  530. f->alloc_trim = 5;
  531. if (opus_rc_tell_frac(rc) + (6 << 3) <= tbits_8ths)
  532. if (encode)
  533. ff_opus_rc_enc_cdf(rc, f->alloc_trim, ff_celt_model_alloc_trim);
  534. else
  535. f->alloc_trim = ff_opus_rc_dec_cdf(rc, ff_celt_model_alloc_trim);
  536. /* Anti-collapse bit reservation */
  537. tbits_8ths = (f->framebits << 3) - opus_rc_tell_frac(rc) - 1;
  538. f->anticollapse_needed = 0;
  539. if (f->transient && f->size >= 2 && tbits_8ths >= ((f->size + 2) << 3))
  540. f->anticollapse_needed = 1 << 3;
  541. tbits_8ths -= f->anticollapse_needed;
  542. /* Band skip bit reservation */
  543. if (tbits_8ths >= 1 << 3)
  544. skip_bit = 1 << 3;
  545. tbits_8ths -= skip_bit;
  546. /* Intensity/dual stereo bit reservation */
  547. if (f->channels == 2) {
  548. intensitystereo_bit = ff_celt_log2_frac[f->end_band - f->start_band];
  549. if (intensitystereo_bit <= tbits_8ths) {
  550. tbits_8ths -= intensitystereo_bit;
  551. if (tbits_8ths >= 1 << 3) {
  552. dualstereo_bit = 1 << 3;
  553. tbits_8ths -= 1 << 3;
  554. }
  555. } else {
  556. intensitystereo_bit = 0;
  557. }
  558. }
  559. /* Trim offsets */
  560. for (i = f->start_band; i < f->end_band; i++) {
  561. int trim = f->alloc_trim - 5 - f->size;
  562. int band = ff_celt_freq_range[i] * (f->end_band - i - 1);
  563. int duration = f->size + 3;
  564. int scale = duration + f->channels - 1;
  565. /* PVQ minimum allocation threshold, below this value the band is
  566. * skipped */
  567. threshold[i] = FFMAX(3 * ff_celt_freq_range[i] << duration >> 4,
  568. f->channels << 3);
  569. trim_offset[i] = trim * (band << scale) >> 6;
  570. if (ff_celt_freq_range[i] << f->size == 1)
  571. trim_offset[i] -= f->channels << 3;
  572. }
  573. /* Bisection */
  574. low = 1;
  575. high = CELT_VECTORS - 1;
  576. while (low <= high) {
  577. int center = (low + high) >> 1;
  578. done = total = 0;
  579. for (i = f->end_band - 1; i >= f->start_band; i--) {
  580. bandbits = NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[center][i]);
  581. if (bandbits)
  582. bandbits = FFMAX(bandbits + trim_offset[i], 0);
  583. bandbits += boost[i];
  584. if (bandbits >= threshold[i] || done) {
  585. done = 1;
  586. total += FFMIN(bandbits, f->caps[i]);
  587. } else if (bandbits >= f->channels << 3) {
  588. total += f->channels << 3;
  589. }
  590. }
  591. if (total > tbits_8ths)
  592. high = center - 1;
  593. else
  594. low = center + 1;
  595. }
  596. high = low--;
  597. /* Bisection */
  598. for (i = f->start_band; i < f->end_band; i++) {
  599. bits1[i] = NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[low][i]);
  600. bits2[i] = high >= CELT_VECTORS ? f->caps[i] :
  601. NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[high][i]);
  602. if (bits1[i])
  603. bits1[i] = FFMAX(bits1[i] + trim_offset[i], 0);
  604. if (bits2[i])
  605. bits2[i] = FFMAX(bits2[i] + trim_offset[i], 0);
  606. if (low)
  607. bits1[i] += boost[i];
  608. bits2[i] += boost[i];
  609. if (boost[i])
  610. skip_startband = i;
  611. bits2[i] = FFMAX(bits2[i] - bits1[i], 0);
  612. }
  613. /* Bisection */
  614. low = 0;
  615. high = 1 << CELT_ALLOC_STEPS;
  616. for (i = 0; i < CELT_ALLOC_STEPS; i++) {
  617. int center = (low + high) >> 1;
  618. done = total = 0;
  619. for (j = f->end_band - 1; j >= f->start_band; j--) {
  620. bandbits = bits1[j] + (center * bits2[j] >> CELT_ALLOC_STEPS);
  621. if (bandbits >= threshold[j] || done) {
  622. done = 1;
  623. total += FFMIN(bandbits, f->caps[j]);
  624. } else if (bandbits >= f->channels << 3)
  625. total += f->channels << 3;
  626. }
  627. if (total > tbits_8ths)
  628. high = center;
  629. else
  630. low = center;
  631. }
  632. /* Bisection */
  633. done = total = 0;
  634. for (i = f->end_band - 1; i >= f->start_band; i--) {
  635. bandbits = bits1[i] + (low * bits2[i] >> CELT_ALLOC_STEPS);
  636. if (bandbits >= threshold[i] || done)
  637. done = 1;
  638. else
  639. bandbits = (bandbits >= f->channels << 3) ?
  640. f->channels << 3 : 0;
  641. bandbits = FFMIN(bandbits, f->caps[i]);
  642. f->pulses[i] = bandbits;
  643. total += bandbits;
  644. }
  645. /* Band skipping */
  646. for (f->coded_bands = f->end_band; ; f->coded_bands--) {
  647. int allocation;
  648. j = f->coded_bands - 1;
  649. if (j == skip_startband) {
  650. /* all remaining bands are not skipped */
  651. tbits_8ths += skip_bit;
  652. break;
  653. }
  654. /* determine the number of bits available for coding "do not skip" markers */
  655. remaining = tbits_8ths - total;
  656. bandbits = remaining / (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
  657. remaining -= bandbits * (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
  658. allocation = f->pulses[j] + bandbits * ff_celt_freq_range[j];
  659. allocation += FFMAX(remaining - (ff_celt_freq_bands[j] - ff_celt_freq_bands[f->start_band]), 0);
  660. /* a "do not skip" marker is only coded if the allocation is
  661. * above the chosen threshold */
  662. if (allocation >= FFMAX(threshold[j], (f->channels + 1) << 3)) {
  663. int do_not_skip;
  664. if (encode) {
  665. do_not_skip = f->coded_bands <= f->skip_band_floor;
  666. ff_opus_rc_enc_log(rc, do_not_skip, 1);
  667. } else {
  668. do_not_skip = ff_opus_rc_dec_log(rc, 1);
  669. }
  670. if (do_not_skip)
  671. break;
  672. total += 1 << 3;
  673. allocation -= 1 << 3;
  674. }
  675. /* the band is skipped, so reclaim its bits */
  676. total -= f->pulses[j];
  677. if (intensitystereo_bit) {
  678. total -= intensitystereo_bit;
  679. intensitystereo_bit = ff_celt_log2_frac[j - f->start_band];
  680. total += intensitystereo_bit;
  681. }
  682. total += f->pulses[j] = (allocation >= f->channels << 3) ? f->channels << 3 : 0;
  683. }
  684. /* IS start band */
  685. if (encode) {
  686. if (intensitystereo_bit) {
  687. f->intensity_stereo = FFMIN(f->intensity_stereo, f->coded_bands);
  688. ff_opus_rc_enc_uint(rc, f->intensity_stereo, f->coded_bands + 1 - f->start_band);
  689. }
  690. } else {
  691. f->intensity_stereo = f->dual_stereo = 0;
  692. if (intensitystereo_bit)
  693. f->intensity_stereo = f->start_band + ff_opus_rc_dec_uint(rc, f->coded_bands + 1 - f->start_band);
  694. }
  695. /* DS flag */
  696. if (f->intensity_stereo <= f->start_band)
  697. tbits_8ths += dualstereo_bit; /* no intensity stereo means no dual stereo */
  698. else if (dualstereo_bit)
  699. if (encode)
  700. ff_opus_rc_enc_log(rc, f->dual_stereo, 1);
  701. else
  702. f->dual_stereo = ff_opus_rc_dec_log(rc, 1);
  703. /* Supply the remaining bits in this frame to lower bands */
  704. remaining = tbits_8ths - total;
  705. bandbits = remaining / (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
  706. remaining -= bandbits * (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
  707. for (i = f->start_band; i < f->coded_bands; i++) {
  708. const int bits = FFMIN(remaining, ff_celt_freq_range[i]);
  709. f->pulses[i] += bits + bandbits * ff_celt_freq_range[i];
  710. remaining -= bits;
  711. }
  712. /* Finally determine the allocation */
  713. for (i = f->start_band; i < f->coded_bands; i++) {
  714. int N = ff_celt_freq_range[i] << f->size;
  715. int prev_extra = extrabits;
  716. f->pulses[i] += extrabits;
  717. if (N > 1) {
  718. int dof; /* degrees of freedom */
  719. int temp; /* dof * channels * log(dof) */
  720. int fine_bits;
  721. int max_bits;
  722. int offset; /* fine energy quantization offset, i.e.
  723. * extra bits assigned over the standard
  724. * totalbits/dof */
  725. extrabits = FFMAX(f->pulses[i] - f->caps[i], 0);
  726. f->pulses[i] -= extrabits;
  727. /* intensity stereo makes use of an extra degree of freedom */
  728. dof = N * f->channels + (f->channels == 2 && N > 2 && !f->dual_stereo && i < f->intensity_stereo);
  729. temp = dof * (ff_celt_log_freq_range[i] + (f->size << 3));
  730. offset = (temp >> 1) - dof * CELT_FINE_OFFSET;
  731. if (N == 2) /* dof=2 is the only case that doesn't fit the model */
  732. offset += dof << 1;
  733. /* grant an additional bias for the first and second pulses */
  734. if (f->pulses[i] + offset < 2 * (dof << 3))
  735. offset += temp >> 2;
  736. else if (f->pulses[i] + offset < 3 * (dof << 3))
  737. offset += temp >> 3;
  738. fine_bits = (f->pulses[i] + offset + (dof << 2)) / (dof << 3);
  739. max_bits = FFMIN((f->pulses[i] >> 3) >> (f->channels - 1), CELT_MAX_FINE_BITS);
  740. max_bits = FFMAX(max_bits, 0);
  741. f->fine_bits[i] = av_clip(fine_bits, 0, max_bits);
  742. /* If fine_bits was rounded down or capped,
  743. * give priority for the final fine energy pass */
  744. f->fine_priority[i] = (f->fine_bits[i] * (dof << 3) >= f->pulses[i] + offset);
  745. /* the remaining bits are assigned to PVQ */
  746. f->pulses[i] -= f->fine_bits[i] << (f->channels - 1) << 3;
  747. } else {
  748. /* all bits go to fine energy except for the sign bit */
  749. extrabits = FFMAX(f->pulses[i] - (f->channels << 3), 0);
  750. f->pulses[i] -= extrabits;
  751. f->fine_bits[i] = 0;
  752. f->fine_priority[i] = 1;
  753. }
  754. /* hand back a limited number of extra fine energy bits to this band */
  755. if (extrabits > 0) {
  756. int fineextra = FFMIN(extrabits >> (f->channels + 2),
  757. CELT_MAX_FINE_BITS - f->fine_bits[i]);
  758. f->fine_bits[i] += fineextra;
  759. fineextra <<= f->channels + 2;
  760. f->fine_priority[i] = (fineextra >= extrabits - prev_extra);
  761. extrabits -= fineextra;
  762. }
  763. }
  764. f->remaining = extrabits;
  765. /* skipped bands dedicate all of their bits for fine energy */
  766. for (; i < f->end_band; i++) {
  767. f->fine_bits[i] = f->pulses[i] >> (f->channels - 1) >> 3;
  768. f->pulses[i] = 0;
  769. f->fine_priority[i] = f->fine_bits[i] < 1;
  770. }
  771. }