2 * Copyright (c) 2012 Andrew D'Addesio
3 * Copyright (c) 2013-2014 Mozilla Corporation
5 * This file is part of FFmpeg.
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.
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.
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
24 * Opus decoder/parser shared code
29 #include "libavutil/error.h"
30 #include "libavutil/ffmath.h"
32 #include "opus_celt.h"
36 static const uint16_t opus_frame_duration[32] = {
49 * Read a 1- or 2-byte frame length
51 static inline int xiph_lacing_16bit(const uint8_t **ptr, const uint8_t *end)
56 return AVERROR_INVALIDDATA;
60 return AVERROR_INVALIDDATA;
67 * Read a multi-byte length (used for code 3 packet padding size)
69 static inline int xiph_lacing_full(const uint8_t **ptr, const uint8_t *end)
75 if (*ptr >= end || val > INT_MAX - 254)
76 return AVERROR_INVALIDDATA;
88 * Parse Opus packet info from raw packet data
90 int ff_opus_parse_packet(OpusPacket *pkt, const uint8_t *buf, int buf_size,
93 const uint8_t *ptr = buf;
94 const uint8_t *end = buf + buf_size;
103 pkt->code = (i ) & 0x3;
104 pkt->stereo = (i >> 2) & 0x1;
105 pkt->config = (i >> 3) & 0x1F;
107 /* code 2 and code 3 packets have at least 1 byte after the TOC */
108 if (pkt->code >= 2 && buf_size < 2)
114 pkt->frame_count = 1;
117 if (self_delimiting) {
118 int len = xiph_lacing_16bit(&ptr, end);
119 if (len < 0 || len > end - ptr)
122 buf_size = end - buf;
125 frame_bytes = end - ptr;
126 if (frame_bytes > MAX_FRAME_SIZE)
128 pkt->frame_offset[0] = ptr - buf;
129 pkt->frame_size[0] = frame_bytes;
132 /* 2 frames, equal size */
133 pkt->frame_count = 2;
136 if (self_delimiting) {
137 int len = xiph_lacing_16bit(&ptr, end);
138 if (len < 0 || 2 * len > end - ptr)
141 buf_size = end - buf;
144 frame_bytes = end - ptr;
145 if (frame_bytes & 1 || frame_bytes >> 1 > MAX_FRAME_SIZE)
147 pkt->frame_offset[0] = ptr - buf;
148 pkt->frame_size[0] = frame_bytes >> 1;
149 pkt->frame_offset[1] = pkt->frame_offset[0] + pkt->frame_size[0];
150 pkt->frame_size[1] = frame_bytes >> 1;
153 /* 2 frames, different sizes */
154 pkt->frame_count = 2;
157 /* read 1st frame size */
158 frame_bytes = xiph_lacing_16bit(&ptr, end);
162 if (self_delimiting) {
163 int len = xiph_lacing_16bit(&ptr, end);
164 if (len < 0 || len + frame_bytes > end - ptr)
166 end = ptr + frame_bytes + len;
167 buf_size = end - buf;
170 pkt->frame_offset[0] = ptr - buf;
171 pkt->frame_size[0] = frame_bytes;
173 /* calculate 2nd frame size */
174 frame_bytes = end - ptr - pkt->frame_size[0];
175 if (frame_bytes < 0 || frame_bytes > MAX_FRAME_SIZE)
177 pkt->frame_offset[1] = pkt->frame_offset[0] + pkt->frame_size[0];
178 pkt->frame_size[1] = frame_bytes;
181 /* 1 to 48 frames, can be different sizes */
183 pkt->frame_count = (i ) & 0x3F;
184 padding = (i >> 6) & 0x01;
185 pkt->vbr = (i >> 7) & 0x01;
187 if (pkt->frame_count == 0 || pkt->frame_count > MAX_FRAMES)
190 /* read padding size */
192 padding = xiph_lacing_full(&ptr, end);
197 /* read frame sizes */
199 /* for VBR, all frames except the final one have their size coded
200 in the bitstream. the last frame size is implicit. */
202 for (i = 0; i < pkt->frame_count - 1; i++) {
203 frame_bytes = xiph_lacing_16bit(&ptr, end);
206 pkt->frame_size[i] = frame_bytes;
207 total_bytes += frame_bytes;
210 if (self_delimiting) {
211 int len = xiph_lacing_16bit(&ptr, end);
212 if (len < 0 || len + total_bytes + padding > end - ptr)
214 end = ptr + total_bytes + len + padding;
215 buf_size = end - buf;
218 frame_bytes = end - ptr - padding;
219 if (total_bytes > frame_bytes)
221 pkt->frame_offset[0] = ptr - buf;
222 for (i = 1; i < pkt->frame_count; i++)
223 pkt->frame_offset[i] = pkt->frame_offset[i-1] + pkt->frame_size[i-1];
224 pkt->frame_size[pkt->frame_count-1] = frame_bytes - total_bytes;
226 /* for CBR, the remaining packet bytes are divided evenly between
228 if (self_delimiting) {
229 frame_bytes = xiph_lacing_16bit(&ptr, end);
230 if (frame_bytes < 0 || pkt->frame_count * frame_bytes + padding > end - ptr)
232 end = ptr + pkt->frame_count * frame_bytes + padding;
233 buf_size = end - buf;
235 frame_bytes = end - ptr - padding;
236 if (frame_bytes % pkt->frame_count ||
237 frame_bytes / pkt->frame_count > MAX_FRAME_SIZE)
239 frame_bytes /= pkt->frame_count;
242 pkt->frame_offset[0] = ptr - buf;
243 pkt->frame_size[0] = frame_bytes;
244 for (i = 1; i < pkt->frame_count; i++) {
245 pkt->frame_offset[i] = pkt->frame_offset[i-1] + pkt->frame_size[i-1];
246 pkt->frame_size[i] = frame_bytes;
251 pkt->packet_size = buf_size;
252 pkt->data_size = pkt->packet_size - padding;
254 /* total packet duration cannot be larger than 120ms */
255 pkt->frame_duration = opus_frame_duration[pkt->config];
256 if (pkt->frame_duration * pkt->frame_count > MAX_PACKET_DUR)
259 /* set mode and bandwidth */
260 if (pkt->config < 12) {
261 pkt->mode = OPUS_MODE_SILK;
262 pkt->bandwidth = pkt->config >> 2;
263 } else if (pkt->config < 16) {
264 pkt->mode = OPUS_MODE_HYBRID;
265 pkt->bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND + (pkt->config >= 14);
267 pkt->mode = OPUS_MODE_CELT;
268 pkt->bandwidth = (pkt->config - 16) >> 2;
269 /* skip medium band */
277 memset(pkt, 0, sizeof(*pkt));
278 return AVERROR_INVALIDDATA;
281 static int channel_reorder_vorbis(int nb_channels, int channel_idx)
283 return ff_vorbis_channel_layout_offsets[nb_channels - 1][channel_idx];
286 static int channel_reorder_unknown(int nb_channels, int channel_idx)
291 av_cold int ff_opus_parse_extradata(AVCodecContext *avctx,
294 static const uint8_t default_channel_map[2] = { 0, 1 };
296 int (*channel_reorder)(int, int) = channel_reorder_unknown;
298 const uint8_t *extradata, *channel_map;
300 int version, channels, map_type, streams, stereo_streams, i, j;
303 if (!avctx->extradata) {
304 if (avctx->channels > 2) {
305 av_log(avctx, AV_LOG_ERROR,
306 "Multichannel configuration without extradata.\n");
307 return AVERROR(EINVAL);
309 extradata = opus_default_extradata;
310 extradata_size = sizeof(opus_default_extradata);
312 extradata = avctx->extradata;
313 extradata_size = avctx->extradata_size;
316 if (extradata_size < 19) {
317 av_log(avctx, AV_LOG_ERROR, "Invalid extradata size: %d\n",
319 return AVERROR_INVALIDDATA;
322 version = extradata[8];
324 avpriv_request_sample(avctx, "Extradata version %d", version);
325 return AVERROR_PATCHWELCOME;
328 avctx->delay = AV_RL16(extradata + 10);
330 channels = avctx->extradata ? extradata[9] : (avctx->channels == 1) ? 1 : 2;
332 av_log(avctx, AV_LOG_ERROR, "Zero channel count specified in the extradata\n");
333 return AVERROR_INVALIDDATA;
336 s->gain_i = AV_RL16(extradata + 16);
338 s->gain = ff_exp10(s->gain_i / (20.0 * 256));
340 map_type = extradata[18];
343 av_log(avctx, AV_LOG_ERROR,
344 "Channel mapping 0 is only specified for up to 2 channels\n");
345 return AVERROR_INVALIDDATA;
347 layout = (channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
349 stereo_streams = channels - 1;
350 channel_map = default_channel_map;
351 } else if (map_type == 1 || map_type == 2 || map_type == 255) {
352 if (extradata_size < 21 + channels) {
353 av_log(avctx, AV_LOG_ERROR, "Invalid extradata size: %d\n",
355 return AVERROR_INVALIDDATA;
358 streams = extradata[19];
359 stereo_streams = extradata[20];
360 if (!streams || stereo_streams > streams ||
361 streams + stereo_streams > 255) {
362 av_log(avctx, AV_LOG_ERROR,
363 "Invalid stream/stereo stream count: %d/%d\n", streams, stereo_streams);
364 return AVERROR_INVALIDDATA;
369 av_log(avctx, AV_LOG_ERROR,
370 "Channel mapping 1 is only specified for up to 8 channels\n");
371 return AVERROR_INVALIDDATA;
373 layout = ff_vorbis_channel_layouts[channels - 1];
374 channel_reorder = channel_reorder_vorbis;
375 } else if (map_type == 2) {
376 int ambisonic_order = ff_sqrt(channels) - 1;
377 if (channels != ((ambisonic_order + 1) * (ambisonic_order + 1)) &&
378 channels != ((ambisonic_order + 1) * (ambisonic_order + 1) + 2)) {
379 av_log(avctx, AV_LOG_ERROR,
380 "Channel mapping 2 is only specified for channel counts"
381 " which can be written as (n + 1)^2 or (n + 1)^2 + 2"
382 " for nonnegative integer n\n");
383 return AVERROR_INVALIDDATA;
385 if (channels > 227) {
386 av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
387 return AVERROR_INVALIDDATA;
393 channel_map = extradata + 21;
395 avpriv_request_sample(avctx, "Mapping type %d", map_type);
396 return AVERROR_PATCHWELCOME;
399 s->channel_maps = av_mallocz_array(channels, sizeof(*s->channel_maps));
400 if (!s->channel_maps)
401 return AVERROR(ENOMEM);
403 for (i = 0; i < channels; i++) {
404 ChannelMap *map = &s->channel_maps[i];
405 uint8_t idx = channel_map[channel_reorder(channels, i)];
410 } else if (idx >= streams + stereo_streams) {
411 av_log(avctx, AV_LOG_ERROR,
412 "Invalid channel map for output channel %d: %d\n", i, idx);
413 av_freep(&s->channel_maps);
414 return AVERROR_INVALIDDATA;
417 /* check that we did not see this index yet */
419 for (j = 0; j < i; j++)
420 if (channel_map[channel_reorder(channels, j)] == idx) {
426 if (idx < 2 * stereo_streams) {
427 map->stream_idx = idx / 2;
428 map->channel_idx = idx & 1;
430 map->stream_idx = idx - stereo_streams;
431 map->channel_idx = 0;
435 avctx->channels = channels;
436 avctx->channel_layout = layout;
437 s->nb_streams = streams;
438 s->nb_stereo_streams = stereo_streams;
443 void ff_celt_quant_bands(CeltFrame *f, OpusRangeCoder *rc)
445 float lowband_scratch[8 * 22];
446 float norm1[2 * 8 * 100];
447 float *norm2 = norm1 + 8 * 100;
449 int totalbits = (f->framebits << 3) - f->anticollapse_needed;
451 int update_lowband = 1;
452 int lowband_offset = 0;
456 for (i = f->start_band; i < f->end_band; i++) {
457 uint32_t cm[2] = { (1 << f->blocks) - 1, (1 << f->blocks) - 1 };
458 int band_offset = ff_celt_freq_bands[i] << f->size;
459 int band_size = ff_celt_freq_range[i] << f->size;
460 float *X = f->block[0].coeffs + band_offset;
461 float *Y = (f->channels == 2) ? f->block[1].coeffs + band_offset : NULL;
462 float *norm_loc1, *norm_loc2;
464 int consumed = opus_rc_tell_frac(rc);
465 int effective_lowband = -1;
468 /* Compute how many bits we want to allocate to this band */
469 if (i != f->start_band)
470 f->remaining -= consumed;
471 f->remaining2 = totalbits - consumed - 1;
472 if (i <= f->coded_bands - 1) {
473 int curr_balance = f->remaining / FFMIN(3, f->coded_bands-i);
474 b = av_clip_uintp2(FFMIN(f->remaining2 + 1, f->pulses[i] + curr_balance), 14);
477 if ((ff_celt_freq_bands[i] - ff_celt_freq_range[i] >= ff_celt_freq_bands[f->start_band] ||
478 i == f->start_band + 1) && (update_lowband || lowband_offset == 0))
481 if (i == f->start_band + 1) {
482 /* Special Hybrid Folding (RFC 8251 section 9). Copy the first band into
483 the second to ensure the second band never has to use the LCG. */
484 int count = (ff_celt_freq_range[i] - ff_celt_freq_range[i-1]) << f->size;
486 memcpy(&norm1[band_offset], &norm1[band_offset - count], count * sizeof(float));
488 if (f->channels == 2)
489 memcpy(&norm2[band_offset], &norm2[band_offset - count], count * sizeof(float));
492 /* Get a conservative estimate of the collapse_mask's for the bands we're
493 going to be folding from. */
494 if (lowband_offset != 0 && (f->spread != CELT_SPREAD_AGGRESSIVE ||
495 f->blocks > 1 || f->tf_change[i] < 0)) {
496 int foldstart, foldend;
498 /* This ensures we never repeat spectral content within one band */
499 effective_lowband = FFMAX(ff_celt_freq_bands[f->start_band],
500 ff_celt_freq_bands[lowband_offset] - ff_celt_freq_range[i]);
501 foldstart = lowband_offset;
502 while (ff_celt_freq_bands[--foldstart] > effective_lowband);
503 foldend = lowband_offset - 1;
504 while (++foldend < i && ff_celt_freq_bands[foldend] < effective_lowband + ff_celt_freq_range[i]);
507 for (j = foldstart; j < foldend; j++) {
508 cm[0] |= f->block[0].collapse_masks[j];
509 cm[1] |= f->block[f->channels - 1].collapse_masks[j];
513 if (f->dual_stereo && i == f->intensity_stereo) {
514 /* Switch off dual stereo to do intensity */
516 for (j = ff_celt_freq_bands[f->start_band] << f->size; j < band_offset; j++)
517 norm1[j] = (norm1[j] + norm2[j]) / 2;
520 norm_loc1 = effective_lowband != -1 ? norm1 + (effective_lowband << f->size) : NULL;
521 norm_loc2 = effective_lowband != -1 ? norm2 + (effective_lowband << f->size) : NULL;
523 if (f->dual_stereo) {
524 cm[0] = f->pvq->quant_band(f->pvq, f, rc, i, X, NULL, band_size, b >> 1,
525 f->blocks, norm_loc1, f->size,
526 norm1 + band_offset, 0, 1.0f,
527 lowband_scratch, cm[0]);
529 cm[1] = f->pvq->quant_band(f->pvq, f, rc, i, Y, NULL, band_size, b >> 1,
530 f->blocks, norm_loc2, f->size,
531 norm2 + band_offset, 0, 1.0f,
532 lowband_scratch, cm[1]);
534 cm[0] = f->pvq->quant_band(f->pvq, f, rc, i, X, Y, band_size, b >> 0,
535 f->blocks, norm_loc1, f->size,
536 norm1 + band_offset, 0, 1.0f,
537 lowband_scratch, cm[0] | cm[1]);
541 f->block[0].collapse_masks[i] = (uint8_t)cm[0];
542 f->block[f->channels - 1].collapse_masks[i] = (uint8_t)cm[1];
543 f->remaining += f->pulses[i] + consumed;
545 /* Update the folding position only as long as we have 1 bit/sample depth */
546 update_lowband = (b > band_size << 3);
550 #define NORMC(bits) ((bits) << (f->channels - 1) << f->size >> 2)
552 void ff_celt_bitalloc(CeltFrame *f, OpusRangeCoder *rc, int encode)
554 int i, j, low, high, total, done, bandbits, remaining, tbits_8ths;
555 int skip_startband = f->start_band;
557 int intensitystereo_bit = 0;
558 int dualstereo_bit = 0;
562 int boost[CELT_MAX_BANDS] = { 0 };
563 int trim_offset[CELT_MAX_BANDS];
564 int threshold[CELT_MAX_BANDS];
565 int bits1[CELT_MAX_BANDS];
566 int bits2[CELT_MAX_BANDS];
569 if (opus_rc_tell(rc) + 4 <= f->framebits) {
571 ff_opus_rc_enc_cdf(rc, f->spread, ff_celt_model_spread);
573 f->spread = ff_opus_rc_dec_cdf(rc, ff_celt_model_spread);
575 f->spread = CELT_SPREAD_NORMAL;
578 /* Initialize static allocation caps */
579 for (i = 0; i < CELT_MAX_BANDS; i++)
580 f->caps[i] = NORMC((ff_celt_static_caps[f->size][f->channels - 1][i] + 64) * ff_celt_freq_range[i]);
583 tbits_8ths = f->framebits << 3;
584 for (i = f->start_band; i < f->end_band; i++) {
585 int quanta = ff_celt_freq_range[i] << (f->channels - 1) << f->size;
586 int b_dynalloc = dynalloc;
587 int boost_amount = f->alloc_boost[i];
588 quanta = FFMIN(quanta << 3, FFMAX(6 << 3, quanta));
590 while (opus_rc_tell_frac(rc) + (b_dynalloc << 3) < tbits_8ths && boost[i] < f->caps[i]) {
593 is_boost = boost_amount--;
594 ff_opus_rc_enc_log(rc, is_boost, b_dynalloc);
596 is_boost = ff_opus_rc_dec_log(rc, b_dynalloc);
603 tbits_8ths -= quanta;
609 dynalloc = FFMAX(dynalloc - 1, 2);
612 /* Allocation trim */
613 if (opus_rc_tell_frac(rc) + (6 << 3) <= tbits_8ths)
615 ff_opus_rc_enc_cdf(rc, f->alloc_trim, ff_celt_model_alloc_trim);
617 f->alloc_trim = ff_opus_rc_dec_cdf(rc, ff_celt_model_alloc_trim);
619 /* Anti-collapse bit reservation */
620 tbits_8ths = (f->framebits << 3) - opus_rc_tell_frac(rc) - 1;
621 f->anticollapse_needed = 0;
622 if (f->transient && f->size >= 2 && tbits_8ths >= ((f->size + 2) << 3))
623 f->anticollapse_needed = 1 << 3;
624 tbits_8ths -= f->anticollapse_needed;
626 /* Band skip bit reservation */
627 if (tbits_8ths >= 1 << 3)
629 tbits_8ths -= skip_bit;
631 /* Intensity/dual stereo bit reservation */
632 if (f->channels == 2) {
633 intensitystereo_bit = ff_celt_log2_frac[f->end_band - f->start_band];
634 if (intensitystereo_bit <= tbits_8ths) {
635 tbits_8ths -= intensitystereo_bit;
636 if (tbits_8ths >= 1 << 3) {
637 dualstereo_bit = 1 << 3;
638 tbits_8ths -= 1 << 3;
641 intensitystereo_bit = 0;
646 for (i = f->start_band; i < f->end_band; i++) {
647 int trim = f->alloc_trim - 5 - f->size;
648 int band = ff_celt_freq_range[i] * (f->end_band - i - 1);
649 int duration = f->size + 3;
650 int scale = duration + f->channels - 1;
652 /* PVQ minimum allocation threshold, below this value the band is
654 threshold[i] = FFMAX(3 * ff_celt_freq_range[i] << duration >> 4,
657 trim_offset[i] = trim * (band << scale) >> 6;
659 if (ff_celt_freq_range[i] << f->size == 1)
660 trim_offset[i] -= f->channels << 3;
665 high = CELT_VECTORS - 1;
666 while (low <= high) {
667 int center = (low + high) >> 1;
670 for (i = f->end_band - 1; i >= f->start_band; i--) {
671 bandbits = NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[center][i]);
674 bandbits = FFMAX(bandbits + trim_offset[i], 0);
675 bandbits += boost[i];
677 if (bandbits >= threshold[i] || done) {
679 total += FFMIN(bandbits, f->caps[i]);
680 } else if (bandbits >= f->channels << 3) {
681 total += f->channels << 3;
685 if (total > tbits_8ths)
693 for (i = f->start_band; i < f->end_band; i++) {
694 bits1[i] = NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[low][i]);
695 bits2[i] = high >= CELT_VECTORS ? f->caps[i] :
696 NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[high][i]);
699 bits1[i] = FFMAX(bits1[i] + trim_offset[i], 0);
701 bits2[i] = FFMAX(bits2[i] + trim_offset[i], 0);
704 bits1[i] += boost[i];
705 bits2[i] += boost[i];
709 bits2[i] = FFMAX(bits2[i] - bits1[i], 0);
714 high = 1 << CELT_ALLOC_STEPS;
715 for (i = 0; i < CELT_ALLOC_STEPS; i++) {
716 int center = (low + high) >> 1;
719 for (j = f->end_band - 1; j >= f->start_band; j--) {
720 bandbits = bits1[j] + (center * bits2[j] >> CELT_ALLOC_STEPS);
722 if (bandbits >= threshold[j] || done) {
724 total += FFMIN(bandbits, f->caps[j]);
725 } else if (bandbits >= f->channels << 3)
726 total += f->channels << 3;
728 if (total > tbits_8ths)
736 for (i = f->end_band - 1; i >= f->start_band; i--) {
737 bandbits = bits1[i] + (low * bits2[i] >> CELT_ALLOC_STEPS);
739 if (bandbits >= threshold[i] || done)
742 bandbits = (bandbits >= f->channels << 3) ?
743 f->channels << 3 : 0;
745 bandbits = FFMIN(bandbits, f->caps[i]);
746 f->pulses[i] = bandbits;
751 for (f->coded_bands = f->end_band; ; f->coded_bands--) {
753 j = f->coded_bands - 1;
755 if (j == skip_startband) {
756 /* all remaining bands are not skipped */
757 tbits_8ths += skip_bit;
761 /* determine the number of bits available for coding "do not skip" markers */
762 remaining = tbits_8ths - total;
763 bandbits = remaining / (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
764 remaining -= bandbits * (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
765 allocation = f->pulses[j] + bandbits * ff_celt_freq_range[j];
766 allocation += FFMAX(remaining - (ff_celt_freq_bands[j] - ff_celt_freq_bands[f->start_band]), 0);
768 /* a "do not skip" marker is only coded if the allocation is
769 * above the chosen threshold */
770 if (allocation >= FFMAX(threshold[j], (f->channels + 1) << 3)) {
773 do_not_skip = f->coded_bands <= f->skip_band_floor;
774 ff_opus_rc_enc_log(rc, do_not_skip, 1);
776 do_not_skip = ff_opus_rc_dec_log(rc, 1);
783 allocation -= 1 << 3;
786 /* the band is skipped, so reclaim its bits */
787 total -= f->pulses[j];
788 if (intensitystereo_bit) {
789 total -= intensitystereo_bit;
790 intensitystereo_bit = ff_celt_log2_frac[j - f->start_band];
791 total += intensitystereo_bit;
794 total += f->pulses[j] = (allocation >= f->channels << 3) ? f->channels << 3 : 0;
799 if (intensitystereo_bit) {
800 f->intensity_stereo = FFMIN(f->intensity_stereo, f->coded_bands);
801 ff_opus_rc_enc_uint(rc, f->intensity_stereo, f->coded_bands + 1 - f->start_band);
804 f->intensity_stereo = f->dual_stereo = 0;
805 if (intensitystereo_bit)
806 f->intensity_stereo = f->start_band + ff_opus_rc_dec_uint(rc, f->coded_bands + 1 - f->start_band);
810 if (f->intensity_stereo <= f->start_band)
811 tbits_8ths += dualstereo_bit; /* no intensity stereo means no dual stereo */
812 else if (dualstereo_bit)
814 ff_opus_rc_enc_log(rc, f->dual_stereo, 1);
816 f->dual_stereo = ff_opus_rc_dec_log(rc, 1);
818 /* Supply the remaining bits in this frame to lower bands */
819 remaining = tbits_8ths - total;
820 bandbits = remaining / (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
821 remaining -= bandbits * (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
822 for (i = f->start_band; i < f->coded_bands; i++) {
823 const int bits = FFMIN(remaining, ff_celt_freq_range[i]);
824 f->pulses[i] += bits + bandbits * ff_celt_freq_range[i];
828 /* Finally determine the allocation */
829 for (i = f->start_band; i < f->coded_bands; i++) {
830 int N = ff_celt_freq_range[i] << f->size;
831 int prev_extra = extrabits;
832 f->pulses[i] += extrabits;
835 int dof; /* degrees of freedom */
836 int temp; /* dof * channels * log(dof) */
839 int offset; /* fine energy quantization offset, i.e.
840 * extra bits assigned over the standard
843 extrabits = FFMAX(f->pulses[i] - f->caps[i], 0);
844 f->pulses[i] -= extrabits;
846 /* intensity stereo makes use of an extra degree of freedom */
847 dof = N * f->channels + (f->channels == 2 && N > 2 && !f->dual_stereo && i < f->intensity_stereo);
848 temp = dof * (ff_celt_log_freq_range[i] + (f->size << 3));
849 offset = (temp >> 1) - dof * CELT_FINE_OFFSET;
850 if (N == 2) /* dof=2 is the only case that doesn't fit the model */
853 /* grant an additional bias for the first and second pulses */
854 if (f->pulses[i] + offset < 2 * (dof << 3))
856 else if (f->pulses[i] + offset < 3 * (dof << 3))
859 fine_bits = (f->pulses[i] + offset + (dof << 2)) / (dof << 3);
860 max_bits = FFMIN((f->pulses[i] >> 3) >> (f->channels - 1), CELT_MAX_FINE_BITS);
861 max_bits = FFMAX(max_bits, 0);
862 f->fine_bits[i] = av_clip(fine_bits, 0, max_bits);
864 /* If fine_bits was rounded down or capped,
865 * give priority for the final fine energy pass */
866 f->fine_priority[i] = (f->fine_bits[i] * (dof << 3) >= f->pulses[i] + offset);
868 /* the remaining bits are assigned to PVQ */
869 f->pulses[i] -= f->fine_bits[i] << (f->channels - 1) << 3;
871 /* all bits go to fine energy except for the sign bit */
872 extrabits = FFMAX(f->pulses[i] - (f->channels << 3), 0);
873 f->pulses[i] -= extrabits;
875 f->fine_priority[i] = 1;
878 /* hand back a limited number of extra fine energy bits to this band */
880 int fineextra = FFMIN(extrabits >> (f->channels + 2),
881 CELT_MAX_FINE_BITS - f->fine_bits[i]);
882 f->fine_bits[i] += fineextra;
884 fineextra <<= f->channels + 2;
885 f->fine_priority[i] = (fineextra >= extrabits - prev_extra);
886 extrabits -= fineextra;
889 f->remaining = extrabits;
891 /* skipped bands dedicate all of their bits for fine energy */
892 for (; i < f->end_band; i++) {
893 f->fine_bits[i] = f->pulses[i] >> (f->channels - 1) >> 3;
895 f->fine_priority[i] = f->fine_bits[i] < 1;