2 * The simplest mpeg audio layer 2 encoder
3 * Copyright (c) 2000, 2001 Fabrice Bellard
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 * The simplest mpeg audio layer 2 encoder.
27 #include "libavutil/channel_layout.h"
33 #define FRAC_BITS 15 /* fractional bits for sb_samples and dct */
34 #define WFRAC_BITS 14 /* fractional bits for window */
36 #include "mpegaudio.h"
37 #include "mpegaudiodsp.h"
38 #include "mpegaudiodata.h"
39 #include "mpegaudiotab.h"
41 /* currently, cannot change these constants (need to modify
42 quantization stage) */
43 #define MUL(a,b) (((int64_t)(a) * (int64_t)(b)) >> FRAC_BITS)
45 #define SAMPLES_BUF_SIZE 4096
47 typedef struct MpegAudioContext {
50 int lsf; /* 1 if mpeg2 low bitrate selected */
51 int bitrate_index; /* bit rate */
53 int frame_size; /* frame size, in bits, without padding */
54 /* padding computation */
55 int frame_frac, frame_frac_incr, do_padding;
56 short samples_buf[MPA_MAX_CHANNELS][SAMPLES_BUF_SIZE]; /* buffer for filter */
57 int samples_offset[MPA_MAX_CHANNELS]; /* offset in samples_buf */
58 int sb_samples[MPA_MAX_CHANNELS][3][12][SBLIMIT];
59 unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3]; /* scale factors */
60 /* code to group 3 scale factors */
61 unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
62 int sblimit; /* number of used subbands */
63 const unsigned char *alloc_table;
64 int16_t filter_bank[512];
65 int scale_factor_table[64];
66 unsigned char scale_diff_table[128];
68 float scale_factor_inv_table[64];
70 int8_t scale_factor_shift[64];
71 unsigned short scale_factor_mult[64];
73 unsigned short total_quant_bits[17]; /* total number of bits per allocation group */
76 static av_cold int MPA_encode_init(AVCodecContext *avctx)
78 MpegAudioContext *s = avctx->priv_data;
79 int freq = avctx->sample_rate;
80 int bitrate = avctx->bit_rate;
81 int channels = avctx->channels;
85 if (channels <= 0 || channels > 2){
86 av_log(avctx, AV_LOG_ERROR, "encoding %d channel(s) is not allowed in mp2\n", channels);
87 return AVERROR(EINVAL);
89 bitrate = bitrate / 1000;
90 s->nb_channels = channels;
91 avctx->frame_size = MPA_FRAME_SIZE;
92 avctx->initial_padding = 512 - 32 + 1;
97 if (avpriv_mpa_freq_tab[i] == freq)
99 if ((avpriv_mpa_freq_tab[i] / 2) == freq) {
105 av_log(avctx, AV_LOG_ERROR, "Sampling rate %d is not allowed in mp2\n", freq);
106 return AVERROR(EINVAL);
110 /* encoding bitrate & frequency */
112 if (avpriv_mpa_bitrate_tab[s->lsf][1][i] == bitrate)
115 if (i == 15 && !avctx->bit_rate) {
117 bitrate = avpriv_mpa_bitrate_tab[s->lsf][1][i];
118 avctx->bit_rate = bitrate * 1000;
121 av_log(avctx, AV_LOG_ERROR, "bitrate %d is not allowed in mp2\n", bitrate);
122 return AVERROR(EINVAL);
124 s->bitrate_index = i;
126 /* compute total header size & pad bit */
128 a = (float)(bitrate * 1000 * MPA_FRAME_SIZE) / (freq * 8.0);
129 s->frame_size = ((int)a) * 8;
131 /* frame fractional size to compute padding */
133 s->frame_frac_incr = (int)((a - floor(a)) * 65536.0);
135 /* select the right allocation table */
136 table = ff_mpa_l2_select_table(bitrate, s->nb_channels, freq, s->lsf);
138 /* number of used subbands */
139 s->sblimit = ff_mpa_sblimit_table[table];
140 s->alloc_table = ff_mpa_alloc_tables[table];
142 ff_dlog(avctx, "%d kb/s, %d Hz, frame_size=%d bits, table=%d, padincr=%x\n",
143 bitrate, freq, s->frame_size, table, s->frame_frac_incr);
145 for(i=0;i<s->nb_channels;i++)
146 s->samples_offset[i] = 0;
150 v = ff_mpa_enwindow[i];
152 v = (v + (1 << (16 - WFRAC_BITS - 1))) >> (16 - WFRAC_BITS);
154 s->filter_bank[i] = v;
158 s->filter_bank[512 - i] = v;
162 v = (int)(exp2((3 - i) / 3.0) * (1 << 20));
165 s->scale_factor_table[i] = v;
167 s->scale_factor_inv_table[i] = exp2(-(3 - i) / 3.0) / (float)(1 << 20);
170 s->scale_factor_shift[i] = 21 - P - (i / 3);
171 s->scale_factor_mult[i] = (1 << P) * exp2((i % 3) / 3.0);
186 s->scale_diff_table[i] = v;
190 v = ff_mpa_quant_bits[i];
195 s->total_quant_bits[i] = 12 * v;
201 /* 32 point floating point IDCT without 1/sqrt(2) coef zero scaling */
202 static void idct32(int *out, int *tab)
206 const int *xp = costab32;
208 for(j=31;j>=3;j-=2) tab[j] += tab[j - 2];
247 x3 = MUL(t[16], FIX(M_SQRT2*0.5));
251 x2 = MUL(-(t[24] + t[8]), FIX(M_SQRT2*0.5));
252 x1 = MUL((t[8] - x2), xp[0]);
253 x2 = MUL((t[8] + x2), xp[1]);
266 xr = MUL(t[28],xp[0]);
270 xr = MUL(t[4],xp[1]);
271 t[ 4] = (t[24] - xr);
272 t[24] = (t[24] + xr);
274 xr = MUL(t[20],xp[2]);
278 xr = MUL(t[12],xp[3]);
279 t[12] = (t[16] - xr);
280 t[16] = (t[16] + xr);
285 for (i = 0; i < 4; i++) {
286 xr = MUL(tab[30-i*4],xp[0]);
287 tab[30-i*4] = (tab[i*4] - xr);
288 tab[ i*4] = (tab[i*4] + xr);
290 xr = MUL(tab[ 2+i*4],xp[1]);
291 tab[ 2+i*4] = (tab[28-i*4] - xr);
292 tab[28-i*4] = (tab[28-i*4] + xr);
294 xr = MUL(tab[31-i*4],xp[0]);
295 tab[31-i*4] = (tab[1+i*4] - xr);
296 tab[ 1+i*4] = (tab[1+i*4] + xr);
298 xr = MUL(tab[ 3+i*4],xp[1]);
299 tab[ 3+i*4] = (tab[29-i*4] - xr);
300 tab[29-i*4] = (tab[29-i*4] + xr);
308 xr = MUL(t1[0], *xp);
317 out[i] = tab[bitinv32[i]];
321 #define WSHIFT (WFRAC_BITS + 15 - FRAC_BITS)
323 static void filter(MpegAudioContext *s, int ch, const short *samples, int incr)
326 int sum, offset, i, j;
331 offset = s->samples_offset[ch];
332 out = &s->sb_samples[ch][0][0][0];
334 /* 32 samples at once */
336 s->samples_buf[ch][offset + (31 - i)] = samples[0];
341 p = s->samples_buf[ch] + offset;
345 sum = p[0*64] * q[0*64];
346 sum += p[1*64] * q[1*64];
347 sum += p[2*64] * q[2*64];
348 sum += p[3*64] * q[3*64];
349 sum += p[4*64] * q[4*64];
350 sum += p[5*64] * q[5*64];
351 sum += p[6*64] * q[6*64];
352 sum += p[7*64] * q[7*64];
357 tmp1[0] = tmp[16] >> WSHIFT;
358 for( i=1; i<=16; i++ ) tmp1[i] = (tmp[i+16]+tmp[16-i]) >> WSHIFT;
359 for( i=17; i<=31; i++ ) tmp1[i] = (tmp[i+16]-tmp[80-i]) >> WSHIFT;
363 /* advance of 32 samples */
366 /* handle the wrap around */
368 memmove(s->samples_buf[ch] + SAMPLES_BUF_SIZE - (512 - 32),
369 s->samples_buf[ch], (512 - 32) * 2);
370 offset = SAMPLES_BUF_SIZE - 512;
373 s->samples_offset[ch] = offset;
376 static void compute_scale_factors(MpegAudioContext *s,
377 unsigned char scale_code[SBLIMIT],
378 unsigned char scale_factors[SBLIMIT][3],
379 int sb_samples[3][12][SBLIMIT],
382 int *p, vmax, v, n, i, j, k, code;
384 unsigned char *sf = &scale_factors[0][0];
386 for(j=0;j<sblimit;j++) {
388 /* find the max absolute value */
389 p = &sb_samples[i][0][j];
397 /* compute the scale factor index using log 2 computations */
400 /* n is the position of the MSB of vmax. now
401 use at most 2 compares to find the index */
402 index = (21 - n) * 3 - 3;
404 while (vmax <= s->scale_factor_table[index+1])
407 index = 0; /* very unlikely case of overflow */
410 index = 62; /* value 63 is not allowed */
413 ff_dlog(NULL, "%2d:%d in=%x %x %d\n",
414 j, i, vmax, s->scale_factor_table[index], index);
415 /* store the scale factor */
416 av_assert2(index >=0 && index <= 63);
420 /* compute the transmission factor : look if the scale factors
421 are close enough to each other */
422 d1 = s->scale_diff_table[sf[0] - sf[1] + 64];
423 d2 = s->scale_diff_table[sf[1] - sf[2] + 64];
425 /* handle the 25 cases */
426 switch(d1 * 5 + d2) {
458 sf[1] = sf[2] = sf[0];
463 sf[0] = sf[1] = sf[2];
469 sf[0] = sf[2] = sf[1];
475 sf[1] = sf[2] = sf[0];
478 av_assert2(0); //cannot happen
479 code = 0; /* kill warning */
482 ff_dlog(NULL, "%d: %2d %2d %2d %d %d -> %d\n", j,
483 sf[0], sf[1], sf[2], d1, d2, code);
484 scale_code[j] = code;
489 /* The most important function : psycho acoustic module. In this
490 encoder there is basically none, so this is the worst you can do,
491 but also this is the simpler. */
492 static void psycho_acoustic_model(MpegAudioContext *s, short smr[SBLIMIT])
496 for(i=0;i<s->sblimit;i++) {
497 smr[i] = (int)(fixed_smr[i] * 10);
502 #define SB_NOTALLOCATED 0
503 #define SB_ALLOCATED 1
506 /* Try to maximize the smr while using a number of bits inferior to
507 the frame size. I tried to make the code simpler, faster and
508 smaller than other encoders :-) */
509 static void compute_bit_allocation(MpegAudioContext *s,
510 short smr1[MPA_MAX_CHANNELS][SBLIMIT],
511 unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT],
514 int i, ch, b, max_smr, max_ch, max_sb, current_frame_size, max_frame_size;
516 short smr[MPA_MAX_CHANNELS][SBLIMIT];
517 unsigned char subband_status[MPA_MAX_CHANNELS][SBLIMIT];
518 const unsigned char *alloc;
520 memcpy(smr, smr1, s->nb_channels * sizeof(short) * SBLIMIT);
521 memset(subband_status, SB_NOTALLOCATED, s->nb_channels * SBLIMIT);
522 memset(bit_alloc, 0, s->nb_channels * SBLIMIT);
524 /* compute frame size and padding */
525 max_frame_size = s->frame_size;
526 s->frame_frac += s->frame_frac_incr;
527 if (s->frame_frac >= 65536) {
528 s->frame_frac -= 65536;
535 /* compute the header + bit alloc size */
536 current_frame_size = 32;
537 alloc = s->alloc_table;
538 for(i=0;i<s->sblimit;i++) {
540 current_frame_size += incr * s->nb_channels;
544 /* look for the subband with the largest signal to mask ratio */
548 for(ch=0;ch<s->nb_channels;ch++) {
549 for(i=0;i<s->sblimit;i++) {
550 if (smr[ch][i] > max_smr && subband_status[ch][i] != SB_NOMORE) {
551 max_smr = smr[ch][i];
559 ff_dlog(NULL, "current=%d max=%d max_sb=%d max_ch=%d alloc=%d\n",
560 current_frame_size, max_frame_size, max_sb, max_ch,
561 bit_alloc[max_ch][max_sb]);
563 /* find alloc table entry (XXX: not optimal, should use
565 alloc = s->alloc_table;
566 for(i=0;i<max_sb;i++) {
567 alloc += 1 << alloc[0];
570 if (subband_status[max_ch][max_sb] == SB_NOTALLOCATED) {
571 /* nothing was coded for this band: add the necessary bits */
572 incr = 2 + nb_scale_factors[s->scale_code[max_ch][max_sb]] * 6;
573 incr += s->total_quant_bits[alloc[1]];
575 /* increments bit allocation */
576 b = bit_alloc[max_ch][max_sb];
577 incr = s->total_quant_bits[alloc[b + 1]] -
578 s->total_quant_bits[alloc[b]];
581 if (current_frame_size + incr <= max_frame_size) {
582 /* can increase size */
583 b = ++bit_alloc[max_ch][max_sb];
584 current_frame_size += incr;
585 /* decrease smr by the resolution we added */
586 smr[max_ch][max_sb] = smr1[max_ch][max_sb] - quant_snr[alloc[b]];
587 /* max allocation size reached ? */
588 if (b == ((1 << alloc[0]) - 1))
589 subband_status[max_ch][max_sb] = SB_NOMORE;
591 subband_status[max_ch][max_sb] = SB_ALLOCATED;
593 /* cannot increase the size of this subband */
594 subband_status[max_ch][max_sb] = SB_NOMORE;
597 *padding = max_frame_size - current_frame_size;
598 av_assert0(*padding >= 0);
602 * Output the MPEG audio layer 2 frame. Note how the code is small
603 * compared to other encoders :-)
605 static void encode_frame(MpegAudioContext *s,
606 unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT],
609 int i, j, k, l, bit_alloc_bits, b, ch;
612 PutBitContext *p = &s->pb;
616 put_bits(p, 12, 0xfff);
617 put_bits(p, 1, 1 - s->lsf); /* 1 = MPEG-1 ID, 0 = MPEG-2 lsf ID */
618 put_bits(p, 2, 4-2); /* layer 2 */
619 put_bits(p, 1, 1); /* no error protection */
620 put_bits(p, 4, s->bitrate_index);
621 put_bits(p, 2, s->freq_index);
622 put_bits(p, 1, s->do_padding); /* use padding */
623 put_bits(p, 1, 0); /* private_bit */
624 put_bits(p, 2, s->nb_channels == 2 ? MPA_STEREO : MPA_MONO);
625 put_bits(p, 2, 0); /* mode_ext */
626 put_bits(p, 1, 0); /* no copyright */
627 put_bits(p, 1, 1); /* original */
628 put_bits(p, 2, 0); /* no emphasis */
632 for(i=0;i<s->sblimit;i++) {
633 bit_alloc_bits = s->alloc_table[j];
634 for(ch=0;ch<s->nb_channels;ch++) {
635 put_bits(p, bit_alloc_bits, bit_alloc[ch][i]);
637 j += 1 << bit_alloc_bits;
641 for(i=0;i<s->sblimit;i++) {
642 for(ch=0;ch<s->nb_channels;ch++) {
643 if (bit_alloc[ch][i])
644 put_bits(p, 2, s->scale_code[ch][i]);
649 for(i=0;i<s->sblimit;i++) {
650 for(ch=0;ch<s->nb_channels;ch++) {
651 if (bit_alloc[ch][i]) {
652 sf = &s->scale_factors[ch][i][0];
653 switch(s->scale_code[ch][i]) {
655 put_bits(p, 6, sf[0]);
656 put_bits(p, 6, sf[1]);
657 put_bits(p, 6, sf[2]);
661 put_bits(p, 6, sf[0]);
662 put_bits(p, 6, sf[2]);
665 put_bits(p, 6, sf[0]);
672 /* quantization & write sub band samples */
677 for(i=0;i<s->sblimit;i++) {
678 bit_alloc_bits = s->alloc_table[j];
679 for(ch=0;ch<s->nb_channels;ch++) {
680 b = bit_alloc[ch][i];
682 int qindex, steps, m, sample, bits;
683 /* we encode 3 sub band samples of the same sub band at a time */
684 qindex = s->alloc_table[j+b];
685 steps = ff_mpa_quant_steps[qindex];
687 sample = s->sb_samples[ch][k][l + m][i];
688 /* divide by scale factor */
692 a = (float)sample * s->scale_factor_inv_table[s->scale_factors[ch][i][k]];
693 q[m] = (int)((a + 1.0) * steps * 0.5);
697 int q1, e, shift, mult;
698 e = s->scale_factors[ch][i][k];
699 shift = s->scale_factor_shift[e];
700 mult = s->scale_factor_mult[e];
702 /* normalize to P bits */
704 q1 = sample * (1 << -shift);
706 q1 = sample >> shift;
707 q1 = (q1 * mult) >> P;
711 q[m] = (q1 * (unsigned)steps) >> (P + 1);
716 av_assert2(q[m] >= 0 && q[m] < steps);
718 bits = ff_mpa_quant_bits[qindex];
720 /* group the 3 values to save bits */
722 q[0] + steps * (q[1] + steps * q[2]));
724 put_bits(p, bits, q[0]);
725 put_bits(p, bits, q[1]);
726 put_bits(p, bits, q[2]);
730 /* next subband in alloc table */
731 j += 1 << bit_alloc_bits;
737 for(i=0;i<padding;i++)
741 static int MPA_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
742 const AVFrame *frame, int *got_packet_ptr)
744 MpegAudioContext *s = avctx->priv_data;
745 const int16_t *samples = (const int16_t *)frame->data[0];
746 short smr[MPA_MAX_CHANNELS][SBLIMIT];
747 unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
750 for(i=0;i<s->nb_channels;i++) {
751 filter(s, i, samples + i, s->nb_channels);
754 for(i=0;i<s->nb_channels;i++) {
755 compute_scale_factors(s, s->scale_code[i], s->scale_factors[i],
756 s->sb_samples[i], s->sblimit);
758 for(i=0;i<s->nb_channels;i++) {
759 psycho_acoustic_model(s, smr[i]);
761 compute_bit_allocation(s, smr, bit_alloc, &padding);
763 if ((ret = ff_alloc_packet2(avctx, avpkt, MPA_MAX_CODED_FRAME_SIZE, 0)) < 0)
766 init_put_bits(&s->pb, avpkt->data, avpkt->size);
768 encode_frame(s, bit_alloc, padding);
771 flush_put_bits(&s->pb);
772 avpkt->size = put_bytes_output(&s->pb);
774 if (frame->pts != AV_NOPTS_VALUE)
775 avpkt->pts = frame->pts - ff_samples_to_time_base(avctx, avctx->initial_padding);
781 static const AVCodecDefault mp2_defaults[] = {