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"
37 static const uint16_t opus_frame_duration[32] = {
50 * Read a 1- or 2-byte frame length
52 static inline int xiph_lacing_16bit(const uint8_t **ptr, const uint8_t *end)
57 return AVERROR_INVALIDDATA;
61 return AVERROR_INVALIDDATA;
68 * Read a multi-byte length (used for code 3 packet padding size)
70 static inline int xiph_lacing_full(const uint8_t **ptr, const uint8_t *end)
76 if (*ptr >= end || val > INT_MAX - 254)
77 return AVERROR_INVALIDDATA;
89 * Parse Opus packet info from raw packet data
91 int ff_opus_parse_packet(OpusPacket *pkt, const uint8_t *buf, int buf_size,
94 const uint8_t *ptr = buf;
95 const uint8_t *end = buf + buf_size;
104 pkt->code = (i ) & 0x3;
105 pkt->stereo = (i >> 2) & 0x1;
106 pkt->config = (i >> 3) & 0x1F;
108 /* code 2 and code 3 packets have at least 1 byte after the TOC */
109 if (pkt->code >= 2 && buf_size < 2)
115 pkt->frame_count = 1;
118 if (self_delimiting) {
119 int len = xiph_lacing_16bit(&ptr, end);
120 if (len < 0 || len > end - ptr)
123 buf_size = end - buf;
126 frame_bytes = end - ptr;
127 if (frame_bytes > MAX_FRAME_SIZE)
129 pkt->frame_offset[0] = ptr - buf;
130 pkt->frame_size[0] = frame_bytes;
133 /* 2 frames, equal size */
134 pkt->frame_count = 2;
137 if (self_delimiting) {
138 int len = xiph_lacing_16bit(&ptr, end);
139 if (len < 0 || 2 * len > end - ptr)
142 buf_size = end - buf;
145 frame_bytes = end - ptr;
146 if (frame_bytes & 1 || frame_bytes >> 1 > MAX_FRAME_SIZE)
148 pkt->frame_offset[0] = ptr - buf;
149 pkt->frame_size[0] = frame_bytes >> 1;
150 pkt->frame_offset[1] = pkt->frame_offset[0] + pkt->frame_size[0];
151 pkt->frame_size[1] = frame_bytes >> 1;
154 /* 2 frames, different sizes */
155 pkt->frame_count = 2;
158 /* read 1st frame size */
159 frame_bytes = xiph_lacing_16bit(&ptr, end);
163 if (self_delimiting) {
164 int len = xiph_lacing_16bit(&ptr, end);
165 if (len < 0 || len + frame_bytes > end - ptr)
167 end = ptr + frame_bytes + len;
168 buf_size = end - buf;
171 pkt->frame_offset[0] = ptr - buf;
172 pkt->frame_size[0] = frame_bytes;
174 /* calculate 2nd frame size */
175 frame_bytes = end - ptr - pkt->frame_size[0];
176 if (frame_bytes < 0 || frame_bytes > MAX_FRAME_SIZE)
178 pkt->frame_offset[1] = pkt->frame_offset[0] + pkt->frame_size[0];
179 pkt->frame_size[1] = frame_bytes;
182 /* 1 to 48 frames, can be different sizes */
184 pkt->frame_count = (i ) & 0x3F;
185 padding = (i >> 6) & 0x01;
186 pkt->vbr = (i >> 7) & 0x01;
188 if (pkt->frame_count == 0 || pkt->frame_count > MAX_FRAMES)
191 /* read padding size */
193 padding = xiph_lacing_full(&ptr, end);
198 /* read frame sizes */
200 /* for VBR, all frames except the final one have their size coded
201 in the bitstream. the last frame size is implicit. */
203 for (i = 0; i < pkt->frame_count - 1; i++) {
204 frame_bytes = xiph_lacing_16bit(&ptr, end);
207 pkt->frame_size[i] = frame_bytes;
208 total_bytes += frame_bytes;
211 if (self_delimiting) {
212 int len = xiph_lacing_16bit(&ptr, end);
213 if (len < 0 || len + total_bytes + padding > end - ptr)
215 end = ptr + total_bytes + len + padding;
216 buf_size = end - buf;
219 frame_bytes = end - ptr - padding;
220 if (total_bytes > frame_bytes)
222 pkt->frame_offset[0] = ptr - buf;
223 for (i = 1; i < pkt->frame_count; i++)
224 pkt->frame_offset[i] = pkt->frame_offset[i-1] + pkt->frame_size[i-1];
225 pkt->frame_size[pkt->frame_count-1] = frame_bytes - total_bytes;
227 /* for CBR, the remaining packet bytes are divided evenly between
229 if (self_delimiting) {
230 frame_bytes = xiph_lacing_16bit(&ptr, end);
231 if (frame_bytes < 0 || pkt->frame_count * frame_bytes + padding > end - ptr)
233 end = ptr + pkt->frame_count * frame_bytes + padding;
234 buf_size = end - buf;
236 frame_bytes = end - ptr - padding;
237 if (frame_bytes % pkt->frame_count ||
238 frame_bytes / pkt->frame_count > MAX_FRAME_SIZE)
240 frame_bytes /= pkt->frame_count;
243 pkt->frame_offset[0] = ptr - buf;
244 pkt->frame_size[0] = frame_bytes;
245 for (i = 1; i < pkt->frame_count; i++) {
246 pkt->frame_offset[i] = pkt->frame_offset[i-1] + pkt->frame_size[i-1];
247 pkt->frame_size[i] = frame_bytes;
252 pkt->packet_size = buf_size;
253 pkt->data_size = pkt->packet_size - padding;
255 /* total packet duration cannot be larger than 120ms */
256 pkt->frame_duration = opus_frame_duration[pkt->config];
257 if (pkt->frame_duration * pkt->frame_count > MAX_PACKET_DUR)
260 /* set mode and bandwidth */
261 if (pkt->config < 12) {
262 pkt->mode = OPUS_MODE_SILK;
263 pkt->bandwidth = pkt->config >> 2;
264 } else if (pkt->config < 16) {
265 pkt->mode = OPUS_MODE_HYBRID;
266 pkt->bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND + (pkt->config >= 14);
268 pkt->mode = OPUS_MODE_CELT;
269 pkt->bandwidth = (pkt->config - 16) >> 2;
270 /* skip medium band */
278 memset(pkt, 0, sizeof(*pkt));
279 return AVERROR_INVALIDDATA;
282 static int channel_reorder_vorbis(int nb_channels, int channel_idx)
284 return ff_vorbis_channel_layout_offsets[nb_channels - 1][channel_idx];
287 static int channel_reorder_unknown(int nb_channels, int channel_idx)
292 av_cold int ff_opus_parse_extradata(AVCodecContext *avctx,
295 static const uint8_t default_channel_map[2] = { 0, 1 };
297 int (*channel_reorder)(int, int) = channel_reorder_unknown;
299 const uint8_t *extradata, *channel_map;
301 int version, channels, map_type, streams, stereo_streams, i, j;
304 if (!avctx->extradata) {
305 if (avctx->channels > 2) {
306 av_log(avctx, AV_LOG_ERROR,
307 "Multichannel configuration without extradata.\n");
308 return AVERROR(EINVAL);
310 extradata = opus_default_extradata;
311 extradata_size = sizeof(opus_default_extradata);
313 extradata = avctx->extradata;
314 extradata_size = avctx->extradata_size;
317 if (extradata_size < 19) {
318 av_log(avctx, AV_LOG_ERROR, "Invalid extradata size: %d\n",
320 return AVERROR_INVALIDDATA;
323 version = extradata[8];
325 avpriv_request_sample(avctx, "Extradata version %d", version);
326 return AVERROR_PATCHWELCOME;
329 avctx->delay = avctx->internal->skip_samples = AV_RL16(extradata + 10);
331 channels = avctx->extradata ? extradata[9] : (avctx->channels == 1) ? 1 : 2;
333 av_log(avctx, AV_LOG_ERROR, "Zero channel count specified in the extradata\n");
334 return AVERROR_INVALIDDATA;
337 s->gain_i = AV_RL16(extradata + 16);
339 s->gain = ff_exp10(s->gain_i / (20.0 * 256));
341 map_type = extradata[18];
344 av_log(avctx, AV_LOG_ERROR,
345 "Channel mapping 0 is only specified for up to 2 channels\n");
346 return AVERROR_INVALIDDATA;
348 layout = (channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
350 stereo_streams = channels - 1;
351 channel_map = default_channel_map;
352 } else if (map_type == 1 || map_type == 2 || map_type == 255) {
353 if (extradata_size < 21 + channels) {
354 av_log(avctx, AV_LOG_ERROR, "Invalid extradata size: %d\n",
356 return AVERROR_INVALIDDATA;
359 streams = extradata[19];
360 stereo_streams = extradata[20];
361 if (!streams || stereo_streams > streams ||
362 streams + stereo_streams > 255) {
363 av_log(avctx, AV_LOG_ERROR,
364 "Invalid stream/stereo stream count: %d/%d\n", streams, stereo_streams);
365 return AVERROR_INVALIDDATA;
370 av_log(avctx, AV_LOG_ERROR,
371 "Channel mapping 1 is only specified for up to 8 channels\n");
372 return AVERROR_INVALIDDATA;
374 layout = ff_vorbis_channel_layouts[channels - 1];
375 channel_reorder = channel_reorder_vorbis;
376 } else if (map_type == 2) {
377 int ambisonic_order = ff_sqrt(channels) - 1;
378 if (channels != ((ambisonic_order + 1) * (ambisonic_order + 1)) &&
379 channels != ((ambisonic_order + 1) * (ambisonic_order + 1) + 2)) {
380 av_log(avctx, AV_LOG_ERROR,
381 "Channel mapping 2 is only specified for channel counts"
382 " which can be written as (n + 1)^2 or (n + 1)^2 + 2"
383 " for nonnegative integer n\n");
384 return AVERROR_INVALIDDATA;
386 if (channels > 227) {
387 av_log(avctx, AV_LOG_ERROR, "Too many channels\n");
388 return AVERROR_INVALIDDATA;
394 channel_map = extradata + 21;
396 avpriv_request_sample(avctx, "Mapping type %d", map_type);
397 return AVERROR_PATCHWELCOME;
400 s->channel_maps = av_mallocz_array(channels, sizeof(*s->channel_maps));
401 if (!s->channel_maps)
402 return AVERROR(ENOMEM);
404 for (i = 0; i < channels; i++) {
405 ChannelMap *map = &s->channel_maps[i];
406 uint8_t idx = channel_map[channel_reorder(channels, i)];
411 } else if (idx >= streams + stereo_streams) {
412 av_log(avctx, AV_LOG_ERROR,
413 "Invalid channel map for output channel %d: %d\n", i, idx);
414 av_freep(&s->channel_maps);
415 return AVERROR_INVALIDDATA;
418 /* check that we did not see this index yet */
420 for (j = 0; j < i; j++)
421 if (channel_map[channel_reorder(channels, j)] == idx) {
427 if (idx < 2 * stereo_streams) {
428 map->stream_idx = idx / 2;
429 map->channel_idx = idx & 1;
431 map->stream_idx = idx - stereo_streams;
432 map->channel_idx = 0;
436 avctx->channels = channels;
437 avctx->channel_layout = layout;
438 s->nb_streams = streams;
439 s->nb_stereo_streams = stereo_streams;
444 void ff_celt_quant_bands(CeltFrame *f, OpusRangeCoder *rc)
446 float lowband_scratch[8 * 22];
447 float norm1[2 * 8 * 100];
448 float *norm2 = norm1 + 8 * 100;
450 int totalbits = (f->framebits << 3) - f->anticollapse_needed;
452 int update_lowband = 1;
453 int lowband_offset = 0;
457 for (i = f->start_band; i < f->end_band; i++) {
458 uint32_t cm[2] = { (1 << f->blocks) - 1, (1 << f->blocks) - 1 };
459 int band_offset = ff_celt_freq_bands[i] << f->size;
460 int band_size = ff_celt_freq_range[i] << f->size;
461 float *X = f->block[0].coeffs + band_offset;
462 float *Y = (f->channels == 2) ? f->block[1].coeffs + band_offset : NULL;
463 float *norm_loc1, *norm_loc2;
465 int consumed = opus_rc_tell_frac(rc);
466 int effective_lowband = -1;
469 /* Compute how many bits we want to allocate to this band */
470 if (i != f->start_band)
471 f->remaining -= consumed;
472 f->remaining2 = totalbits - consumed - 1;
473 if (i <= f->coded_bands - 1) {
474 int curr_balance = f->remaining / FFMIN(3, f->coded_bands-i);
475 b = av_clip_uintp2(FFMIN(f->remaining2 + 1, f->pulses[i] + curr_balance), 14);
478 if ((ff_celt_freq_bands[i] - ff_celt_freq_range[i] >= ff_celt_freq_bands[f->start_band] ||
479 i == f->start_band + 1) && (update_lowband || lowband_offset == 0))
482 if (i == f->start_band + 1) {
483 /* Special Hybrid Folding (RFC 8251 section 9). Copy the first band into
484 the second to ensure the second band never has to use the LCG. */
485 int count = (ff_celt_freq_range[i] - ff_celt_freq_range[i-1]) << f->size;
487 memcpy(&norm1[band_offset], &norm1[band_offset - count], count * sizeof(float));
489 if (f->channels == 2)
490 memcpy(&norm2[band_offset], &norm2[band_offset - count], count * sizeof(float));
493 /* Get a conservative estimate of the collapse_mask's for the bands we're
494 going to be folding from. */
495 if (lowband_offset != 0 && (f->spread != CELT_SPREAD_AGGRESSIVE ||
496 f->blocks > 1 || f->tf_change[i] < 0)) {
497 int foldstart, foldend;
499 /* This ensures we never repeat spectral content within one band */
500 effective_lowband = FFMAX(ff_celt_freq_bands[f->start_band],
501 ff_celt_freq_bands[lowband_offset] - ff_celt_freq_range[i]);
502 foldstart = lowband_offset;
503 while (ff_celt_freq_bands[--foldstart] > effective_lowband);
504 foldend = lowband_offset - 1;
505 while (++foldend < i && ff_celt_freq_bands[foldend] < effective_lowband + ff_celt_freq_range[i]);
508 for (j = foldstart; j < foldend; j++) {
509 cm[0] |= f->block[0].collapse_masks[j];
510 cm[1] |= f->block[f->channels - 1].collapse_masks[j];
514 if (f->dual_stereo && i == f->intensity_stereo) {
515 /* Switch off dual stereo to do intensity */
517 for (j = ff_celt_freq_bands[f->start_band] << f->size; j < band_offset; j++)
518 norm1[j] = (norm1[j] + norm2[j]) / 2;
521 norm_loc1 = effective_lowband != -1 ? norm1 + (effective_lowband << f->size) : NULL;
522 norm_loc2 = effective_lowband != -1 ? norm2 + (effective_lowband << f->size) : NULL;
524 if (f->dual_stereo) {
525 cm[0] = f->pvq->quant_band(f->pvq, f, rc, i, X, NULL, band_size, b >> 1,
526 f->blocks, norm_loc1, f->size,
527 norm1 + band_offset, 0, 1.0f,
528 lowband_scratch, cm[0]);
530 cm[1] = f->pvq->quant_band(f->pvq, f, rc, i, Y, NULL, band_size, b >> 1,
531 f->blocks, norm_loc2, f->size,
532 norm2 + band_offset, 0, 1.0f,
533 lowband_scratch, cm[1]);
535 cm[0] = f->pvq->quant_band(f->pvq, f, rc, i, X, Y, band_size, b >> 0,
536 f->blocks, norm_loc1, f->size,
537 norm1 + band_offset, 0, 1.0f,
538 lowband_scratch, cm[0] | cm[1]);
542 f->block[0].collapse_masks[i] = (uint8_t)cm[0];
543 f->block[f->channels - 1].collapse_masks[i] = (uint8_t)cm[1];
544 f->remaining += f->pulses[i] + consumed;
546 /* Update the folding position only as long as we have 1 bit/sample depth */
547 update_lowband = (b > band_size << 3);
551 #define NORMC(bits) ((bits) << (f->channels - 1) << f->size >> 2)
553 void ff_celt_bitalloc(CeltFrame *f, OpusRangeCoder *rc, int encode)
555 int i, j, low, high, total, done, bandbits, remaining, tbits_8ths;
556 int skip_startband = f->start_band;
558 int intensitystereo_bit = 0;
559 int dualstereo_bit = 0;
563 int boost[CELT_MAX_BANDS] = { 0 };
564 int trim_offset[CELT_MAX_BANDS];
565 int threshold[CELT_MAX_BANDS];
566 int bits1[CELT_MAX_BANDS];
567 int bits2[CELT_MAX_BANDS];
570 if (opus_rc_tell(rc) + 4 <= f->framebits) {
572 ff_opus_rc_enc_cdf(rc, f->spread, ff_celt_model_spread);
574 f->spread = ff_opus_rc_dec_cdf(rc, ff_celt_model_spread);
576 f->spread = CELT_SPREAD_NORMAL;
579 /* Initialize static allocation caps */
580 for (i = 0; i < CELT_MAX_BANDS; i++)
581 f->caps[i] = NORMC((ff_celt_static_caps[f->size][f->channels - 1][i] + 64) * ff_celt_freq_range[i]);
584 tbits_8ths = f->framebits << 3;
585 for (i = f->start_band; i < f->end_band; i++) {
586 int quanta = ff_celt_freq_range[i] << (f->channels - 1) << f->size;
587 int b_dynalloc = dynalloc;
588 int boost_amount = f->alloc_boost[i];
589 quanta = FFMIN(quanta << 3, FFMAX(6 << 3, quanta));
591 while (opus_rc_tell_frac(rc) + (b_dynalloc << 3) < tbits_8ths && boost[i] < f->caps[i]) {
594 is_boost = boost_amount--;
595 ff_opus_rc_enc_log(rc, is_boost, b_dynalloc);
597 is_boost = ff_opus_rc_dec_log(rc, b_dynalloc);
604 tbits_8ths -= quanta;
610 dynalloc = FFMAX(dynalloc - 1, 2);
613 /* Allocation trim */
614 if (opus_rc_tell_frac(rc) + (6 << 3) <= tbits_8ths)
616 ff_opus_rc_enc_cdf(rc, f->alloc_trim, ff_celt_model_alloc_trim);
618 f->alloc_trim = ff_opus_rc_dec_cdf(rc, ff_celt_model_alloc_trim);
620 /* Anti-collapse bit reservation */
621 tbits_8ths = (f->framebits << 3) - opus_rc_tell_frac(rc) - 1;
622 f->anticollapse_needed = 0;
623 if (f->transient && f->size >= 2 && tbits_8ths >= ((f->size + 2) << 3))
624 f->anticollapse_needed = 1 << 3;
625 tbits_8ths -= f->anticollapse_needed;
627 /* Band skip bit reservation */
628 if (tbits_8ths >= 1 << 3)
630 tbits_8ths -= skip_bit;
632 /* Intensity/dual stereo bit reservation */
633 if (f->channels == 2) {
634 intensitystereo_bit = ff_celt_log2_frac[f->end_band - f->start_band];
635 if (intensitystereo_bit <= tbits_8ths) {
636 tbits_8ths -= intensitystereo_bit;
637 if (tbits_8ths >= 1 << 3) {
638 dualstereo_bit = 1 << 3;
639 tbits_8ths -= 1 << 3;
642 intensitystereo_bit = 0;
647 for (i = f->start_band; i < f->end_band; i++) {
648 int trim = f->alloc_trim - 5 - f->size;
649 int band = ff_celt_freq_range[i] * (f->end_band - i - 1);
650 int duration = f->size + 3;
651 int scale = duration + f->channels - 1;
653 /* PVQ minimum allocation threshold, below this value the band is
655 threshold[i] = FFMAX(3 * ff_celt_freq_range[i] << duration >> 4,
658 trim_offset[i] = trim * (band << scale) >> 6;
660 if (ff_celt_freq_range[i] << f->size == 1)
661 trim_offset[i] -= f->channels << 3;
666 high = CELT_VECTORS - 1;
667 while (low <= high) {
668 int center = (low + high) >> 1;
671 for (i = f->end_band - 1; i >= f->start_band; i--) {
672 bandbits = NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[center][i]);
675 bandbits = FFMAX(bandbits + trim_offset[i], 0);
676 bandbits += boost[i];
678 if (bandbits >= threshold[i] || done) {
680 total += FFMIN(bandbits, f->caps[i]);
681 } else if (bandbits >= f->channels << 3) {
682 total += f->channels << 3;
686 if (total > tbits_8ths)
694 for (i = f->start_band; i < f->end_band; i++) {
695 bits1[i] = NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[low][i]);
696 bits2[i] = high >= CELT_VECTORS ? f->caps[i] :
697 NORMC(ff_celt_freq_range[i] * ff_celt_static_alloc[high][i]);
700 bits1[i] = FFMAX(bits1[i] + trim_offset[i], 0);
702 bits2[i] = FFMAX(bits2[i] + trim_offset[i], 0);
705 bits1[i] += boost[i];
706 bits2[i] += boost[i];
710 bits2[i] = FFMAX(bits2[i] - bits1[i], 0);
715 high = 1 << CELT_ALLOC_STEPS;
716 for (i = 0; i < CELT_ALLOC_STEPS; i++) {
717 int center = (low + high) >> 1;
720 for (j = f->end_band - 1; j >= f->start_band; j--) {
721 bandbits = bits1[j] + (center * bits2[j] >> CELT_ALLOC_STEPS);
723 if (bandbits >= threshold[j] || done) {
725 total += FFMIN(bandbits, f->caps[j]);
726 } else if (bandbits >= f->channels << 3)
727 total += f->channels << 3;
729 if (total > tbits_8ths)
737 for (i = f->end_band - 1; i >= f->start_band; i--) {
738 bandbits = bits1[i] + (low * bits2[i] >> CELT_ALLOC_STEPS);
740 if (bandbits >= threshold[i] || done)
743 bandbits = (bandbits >= f->channels << 3) ?
744 f->channels << 3 : 0;
746 bandbits = FFMIN(bandbits, f->caps[i]);
747 f->pulses[i] = bandbits;
752 for (f->coded_bands = f->end_band; ; f->coded_bands--) {
754 j = f->coded_bands - 1;
756 if (j == skip_startband) {
757 /* all remaining bands are not skipped */
758 tbits_8ths += skip_bit;
762 /* determine the number of bits available for coding "do not skip" markers */
763 remaining = tbits_8ths - total;
764 bandbits = remaining / (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
765 remaining -= bandbits * (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
766 allocation = f->pulses[j] + bandbits * ff_celt_freq_range[j];
767 allocation += FFMAX(remaining - (ff_celt_freq_bands[j] - ff_celt_freq_bands[f->start_band]), 0);
769 /* a "do not skip" marker is only coded if the allocation is
770 * above the chosen threshold */
771 if (allocation >= FFMAX(threshold[j], (f->channels + 1) << 3)) {
774 do_not_skip = f->coded_bands <= f->skip_band_floor;
775 ff_opus_rc_enc_log(rc, do_not_skip, 1);
777 do_not_skip = ff_opus_rc_dec_log(rc, 1);
784 allocation -= 1 << 3;
787 /* the band is skipped, so reclaim its bits */
788 total -= f->pulses[j];
789 if (intensitystereo_bit) {
790 total -= intensitystereo_bit;
791 intensitystereo_bit = ff_celt_log2_frac[j - f->start_band];
792 total += intensitystereo_bit;
795 total += f->pulses[j] = (allocation >= f->channels << 3) ? f->channels << 3 : 0;
800 if (intensitystereo_bit) {
801 f->intensity_stereo = FFMIN(f->intensity_stereo, f->coded_bands);
802 ff_opus_rc_enc_uint(rc, f->intensity_stereo, f->coded_bands + 1 - f->start_band);
805 f->intensity_stereo = f->dual_stereo = 0;
806 if (intensitystereo_bit)
807 f->intensity_stereo = f->start_band + ff_opus_rc_dec_uint(rc, f->coded_bands + 1 - f->start_band);
811 if (f->intensity_stereo <= f->start_band)
812 tbits_8ths += dualstereo_bit; /* no intensity stereo means no dual stereo */
813 else if (dualstereo_bit)
815 ff_opus_rc_enc_log(rc, f->dual_stereo, 1);
817 f->dual_stereo = ff_opus_rc_dec_log(rc, 1);
819 /* Supply the remaining bits in this frame to lower bands */
820 remaining = tbits_8ths - total;
821 bandbits = remaining / (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
822 remaining -= bandbits * (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
823 for (i = f->start_band; i < f->coded_bands; i++) {
824 const int bits = FFMIN(remaining, ff_celt_freq_range[i]);
825 f->pulses[i] += bits + bandbits * ff_celt_freq_range[i];
829 /* Finally determine the allocation */
830 for (i = f->start_band; i < f->coded_bands; i++) {
831 int N = ff_celt_freq_range[i] << f->size;
832 int prev_extra = extrabits;
833 f->pulses[i] += extrabits;
836 int dof; /* degrees of freedom */
837 int temp; /* dof * channels * log(dof) */
840 int offset; /* fine energy quantization offset, i.e.
841 * extra bits assigned over the standard
844 extrabits = FFMAX(f->pulses[i] - f->caps[i], 0);
845 f->pulses[i] -= extrabits;
847 /* intensity stereo makes use of an extra degree of freedom */
848 dof = N * f->channels + (f->channels == 2 && N > 2 && !f->dual_stereo && i < f->intensity_stereo);
849 temp = dof * (ff_celt_log_freq_range[i] + (f->size << 3));
850 offset = (temp >> 1) - dof * CELT_FINE_OFFSET;
851 if (N == 2) /* dof=2 is the only case that doesn't fit the model */
854 /* grant an additional bias for the first and second pulses */
855 if (f->pulses[i] + offset < 2 * (dof << 3))
857 else if (f->pulses[i] + offset < 3 * (dof << 3))
860 fine_bits = (f->pulses[i] + offset + (dof << 2)) / (dof << 3);
861 max_bits = FFMIN((f->pulses[i] >> 3) >> (f->channels - 1), CELT_MAX_FINE_BITS);
862 max_bits = FFMAX(max_bits, 0);
863 f->fine_bits[i] = av_clip(fine_bits, 0, max_bits);
865 /* If fine_bits was rounded down or capped,
866 * give priority for the final fine energy pass */
867 f->fine_priority[i] = (f->fine_bits[i] * (dof << 3) >= f->pulses[i] + offset);
869 /* the remaining bits are assigned to PVQ */
870 f->pulses[i] -= f->fine_bits[i] << (f->channels - 1) << 3;
872 /* all bits go to fine energy except for the sign bit */
873 extrabits = FFMAX(f->pulses[i] - (f->channels << 3), 0);
874 f->pulses[i] -= extrabits;
876 f->fine_priority[i] = 1;
879 /* hand back a limited number of extra fine energy bits to this band */
881 int fineextra = FFMIN(extrabits >> (f->channels + 2),
882 CELT_MAX_FINE_BITS - f->fine_bits[i]);
883 f->fine_bits[i] += fineextra;
885 fineextra <<= f->channels + 2;
886 f->fine_priority[i] = (fineextra >= extrabits - prev_extra);
887 extrabits -= fineextra;
890 f->remaining = extrabits;
892 /* skipped bands dedicate all of their bits for fine energy */
893 for (; i < f->end_band; i++) {
894 f->fine_bits[i] = f->pulses[i] >> (f->channels - 1) >> 3;
896 f->fine_priority[i] = f->fine_bits[i] < 1;