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/audioconvert.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"
39 /* currently, cannot change these constants (need to modify
40 quantization stage) */
41 #define MUL(a,b) (((int64_t)(a) * (int64_t)(b)) >> FRAC_BITS)
43 #define SAMPLES_BUF_SIZE 4096
45 typedef struct MpegAudioContext {
48 int lsf; /* 1 if mpeg2 low bitrate selected */
49 int bitrate_index; /* bit rate */
51 int frame_size; /* frame size, in bits, without padding */
52 /* padding computation */
53 int frame_frac, frame_frac_incr, do_padding;
54 short samples_buf[MPA_MAX_CHANNELS][SAMPLES_BUF_SIZE]; /* buffer for filter */
55 int samples_offset[MPA_MAX_CHANNELS]; /* offset in samples_buf */
56 int sb_samples[MPA_MAX_CHANNELS][3][12][SBLIMIT];
57 unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3]; /* scale factors */
58 /* code to group 3 scale factors */
59 unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
60 int sblimit; /* number of used subbands */
61 const unsigned char *alloc_table;
64 /* define it to use floats in quantization (I don't like floats !) */
67 #include "mpegaudiodata.h"
68 #include "mpegaudiotab.h"
70 static av_cold int MPA_encode_init(AVCodecContext *avctx)
72 MpegAudioContext *s = avctx->priv_data;
73 int freq = avctx->sample_rate;
74 int bitrate = avctx->bit_rate;
75 int channels = avctx->channels;
79 if (channels <= 0 || channels > 2){
80 av_log(avctx, AV_LOG_ERROR, "encoding %d channel(s) is not allowed in mp2\n", channels);
81 return AVERROR(EINVAL);
83 bitrate = bitrate / 1000;
84 s->nb_channels = channels;
85 avctx->frame_size = MPA_FRAME_SIZE;
86 avctx->delay = 512 - 32 + 1;
91 if (avpriv_mpa_freq_tab[i] == freq)
93 if ((avpriv_mpa_freq_tab[i] / 2) == freq) {
99 av_log(avctx, AV_LOG_ERROR, "Sampling rate %d is not allowed in mp2\n", freq);
100 return AVERROR(EINVAL);
104 /* encoding bitrate & frequency */
106 if (avpriv_mpa_bitrate_tab[s->lsf][1][i] == bitrate)
110 av_log(avctx, AV_LOG_ERROR, "bitrate %d is not allowed in mp2\n", bitrate);
111 return AVERROR(EINVAL);
113 s->bitrate_index = i;
115 /* compute total header size & pad bit */
117 a = (float)(bitrate * 1000 * MPA_FRAME_SIZE) / (freq * 8.0);
118 s->frame_size = ((int)a) * 8;
120 /* frame fractional size to compute padding */
122 s->frame_frac_incr = (int)((a - floor(a)) * 65536.0);
124 /* select the right allocation table */
125 table = ff_mpa_l2_select_table(bitrate, s->nb_channels, freq, s->lsf);
127 /* number of used subbands */
128 s->sblimit = ff_mpa_sblimit_table[table];
129 s->alloc_table = ff_mpa_alloc_tables[table];
131 av_dlog(avctx, "%d kb/s, %d Hz, frame_size=%d bits, table=%d, padincr=%x\n",
132 bitrate, freq, s->frame_size, table, s->frame_frac_incr);
134 for(i=0;i<s->nb_channels;i++)
135 s->samples_offset[i] = 0;
139 v = ff_mpa_enwindow[i];
141 v = (v + (1 << (16 - WFRAC_BITS - 1))) >> (16 - WFRAC_BITS);
147 filter_bank[512 - i] = v;
151 v = (int)(pow(2.0, (3 - i) / 3.0) * (1 << 20));
154 scale_factor_table[i] = v;
156 scale_factor_inv_table[i] = pow(2.0, -(3 - i) / 3.0) / (float)(1 << 20);
159 scale_factor_shift[i] = 21 - P - (i / 3);
160 scale_factor_mult[i] = (1 << P) * pow(2.0, (i % 3) / 3.0);
175 scale_diff_table[i] = v;
179 v = ff_mpa_quant_bits[i];
184 total_quant_bits[i] = 12 * v;
187 #if FF_API_OLD_ENCODE_AUDIO
188 avctx->coded_frame= avcodec_alloc_frame();
189 if (!avctx->coded_frame)
190 return AVERROR(ENOMEM);
196 /* 32 point floating point IDCT without 1/sqrt(2) coef zero scaling */
197 static void idct32(int *out, int *tab)
201 const int *xp = costab32;
203 for(j=31;j>=3;j-=2) tab[j] += tab[j - 2];
242 x3 = MUL(t[16], FIX(SQRT2*0.5));
246 x2 = MUL(-(t[24] + t[8]), FIX(SQRT2*0.5));
247 x1 = MUL((t[8] - x2), xp[0]);
248 x2 = MUL((t[8] + x2), xp[1]);
261 xr = MUL(t[28],xp[0]);
265 xr = MUL(t[4],xp[1]);
266 t[ 4] = (t[24] - xr);
267 t[24] = (t[24] + xr);
269 xr = MUL(t[20],xp[2]);
273 xr = MUL(t[12],xp[3]);
274 t[12] = (t[16] - xr);
275 t[16] = (t[16] + xr);
280 for (i = 0; i < 4; i++) {
281 xr = MUL(tab[30-i*4],xp[0]);
282 tab[30-i*4] = (tab[i*4] - xr);
283 tab[ i*4] = (tab[i*4] + xr);
285 xr = MUL(tab[ 2+i*4],xp[1]);
286 tab[ 2+i*4] = (tab[28-i*4] - xr);
287 tab[28-i*4] = (tab[28-i*4] + xr);
289 xr = MUL(tab[31-i*4],xp[0]);
290 tab[31-i*4] = (tab[1+i*4] - xr);
291 tab[ 1+i*4] = (tab[1+i*4] + xr);
293 xr = MUL(tab[ 3+i*4],xp[1]);
294 tab[ 3+i*4] = (tab[29-i*4] - xr);
295 tab[29-i*4] = (tab[29-i*4] + xr);
303 xr = MUL(t1[0], *xp);
312 out[i] = tab[bitinv32[i]];
316 #define WSHIFT (WFRAC_BITS + 15 - FRAC_BITS)
318 static void filter(MpegAudioContext *s, int ch, const short *samples, int incr)
321 int sum, offset, i, j;
326 offset = s->samples_offset[ch];
327 out = &s->sb_samples[ch][0][0][0];
329 /* 32 samples at once */
331 s->samples_buf[ch][offset + (31 - i)] = samples[0];
336 p = s->samples_buf[ch] + offset;
340 sum = p[0*64] * q[0*64];
341 sum += p[1*64] * q[1*64];
342 sum += p[2*64] * q[2*64];
343 sum += p[3*64] * q[3*64];
344 sum += p[4*64] * q[4*64];
345 sum += p[5*64] * q[5*64];
346 sum += p[6*64] * q[6*64];
347 sum += p[7*64] * q[7*64];
352 tmp1[0] = tmp[16] >> WSHIFT;
353 for( i=1; i<=16; i++ ) tmp1[i] = (tmp[i+16]+tmp[16-i]) >> WSHIFT;
354 for( i=17; i<=31; i++ ) tmp1[i] = (tmp[i+16]-tmp[80-i]) >> WSHIFT;
358 /* advance of 32 samples */
361 /* handle the wrap around */
363 memmove(s->samples_buf[ch] + SAMPLES_BUF_SIZE - (512 - 32),
364 s->samples_buf[ch], (512 - 32) * 2);
365 offset = SAMPLES_BUF_SIZE - 512;
368 s->samples_offset[ch] = offset;
371 static void compute_scale_factors(unsigned char scale_code[SBLIMIT],
372 unsigned char scale_factors[SBLIMIT][3],
373 int sb_samples[3][12][SBLIMIT],
376 int *p, vmax, v, n, i, j, k, code;
378 unsigned char *sf = &scale_factors[0][0];
380 for(j=0;j<sblimit;j++) {
382 /* find the max absolute value */
383 p = &sb_samples[i][0][j];
391 /* compute the scale factor index using log 2 computations */
394 /* n is the position of the MSB of vmax. now
395 use at most 2 compares to find the index */
396 index = (21 - n) * 3 - 3;
398 while (vmax <= scale_factor_table[index+1])
401 index = 0; /* very unlikely case of overflow */
404 index = 62; /* value 63 is not allowed */
407 av_dlog(NULL, "%2d:%d in=%x %x %d\n",
408 j, i, vmax, scale_factor_table[index], index);
409 /* store the scale factor */
410 av_assert2(index >=0 && index <= 63);
414 /* compute the transmission factor : look if the scale factors
415 are close enough to each other */
416 d1 = scale_diff_table[sf[0] - sf[1] + 64];
417 d2 = scale_diff_table[sf[1] - sf[2] + 64];
419 /* handle the 25 cases */
420 switch(d1 * 5 + d2) {
452 sf[1] = sf[2] = sf[0];
457 sf[0] = sf[1] = sf[2];
463 sf[0] = sf[2] = sf[1];
469 sf[1] = sf[2] = sf[0];
472 av_assert2(0); //cannot happen
473 code = 0; /* kill warning */
476 av_dlog(NULL, "%d: %2d %2d %2d %d %d -> %d\n", j,
477 sf[0], sf[1], sf[2], d1, d2, code);
478 scale_code[j] = code;
483 /* The most important function : psycho acoustic module. In this
484 encoder there is basically none, so this is the worst you can do,
485 but also this is the simpler. */
486 static void psycho_acoustic_model(MpegAudioContext *s, short smr[SBLIMIT])
490 for(i=0;i<s->sblimit;i++) {
491 smr[i] = (int)(fixed_smr[i] * 10);
496 #define SB_NOTALLOCATED 0
497 #define SB_ALLOCATED 1
500 /* Try to maximize the smr while using a number of bits inferior to
501 the frame size. I tried to make the code simpler, faster and
502 smaller than other encoders :-) */
503 static void compute_bit_allocation(MpegAudioContext *s,
504 short smr1[MPA_MAX_CHANNELS][SBLIMIT],
505 unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT],
508 int i, ch, b, max_smr, max_ch, max_sb, current_frame_size, max_frame_size;
510 short smr[MPA_MAX_CHANNELS][SBLIMIT];
511 unsigned char subband_status[MPA_MAX_CHANNELS][SBLIMIT];
512 const unsigned char *alloc;
514 memcpy(smr, smr1, s->nb_channels * sizeof(short) * SBLIMIT);
515 memset(subband_status, SB_NOTALLOCATED, s->nb_channels * SBLIMIT);
516 memset(bit_alloc, 0, s->nb_channels * SBLIMIT);
518 /* compute frame size and padding */
519 max_frame_size = s->frame_size;
520 s->frame_frac += s->frame_frac_incr;
521 if (s->frame_frac >= 65536) {
522 s->frame_frac -= 65536;
529 /* compute the header + bit alloc size */
530 current_frame_size = 32;
531 alloc = s->alloc_table;
532 for(i=0;i<s->sblimit;i++) {
534 current_frame_size += incr * s->nb_channels;
538 /* look for the subband with the largest signal to mask ratio */
542 for(ch=0;ch<s->nb_channels;ch++) {
543 for(i=0;i<s->sblimit;i++) {
544 if (smr[ch][i] > max_smr && subband_status[ch][i] != SB_NOMORE) {
545 max_smr = smr[ch][i];
553 av_dlog(NULL, "current=%d max=%d max_sb=%d max_ch=%d alloc=%d\n",
554 current_frame_size, max_frame_size, max_sb, max_ch,
555 bit_alloc[max_ch][max_sb]);
557 /* find alloc table entry (XXX: not optimal, should use
559 alloc = s->alloc_table;
560 for(i=0;i<max_sb;i++) {
561 alloc += 1 << alloc[0];
564 if (subband_status[max_ch][max_sb] == SB_NOTALLOCATED) {
565 /* nothing was coded for this band: add the necessary bits */
566 incr = 2 + nb_scale_factors[s->scale_code[max_ch][max_sb]] * 6;
567 incr += total_quant_bits[alloc[1]];
569 /* increments bit allocation */
570 b = bit_alloc[max_ch][max_sb];
571 incr = total_quant_bits[alloc[b + 1]] -
572 total_quant_bits[alloc[b]];
575 if (current_frame_size + incr <= max_frame_size) {
576 /* can increase size */
577 b = ++bit_alloc[max_ch][max_sb];
578 current_frame_size += incr;
579 /* decrease smr by the resolution we added */
580 smr[max_ch][max_sb] = smr1[max_ch][max_sb] - quant_snr[alloc[b]];
581 /* max allocation size reached ? */
582 if (b == ((1 << alloc[0]) - 1))
583 subband_status[max_ch][max_sb] = SB_NOMORE;
585 subband_status[max_ch][max_sb] = SB_ALLOCATED;
587 /* cannot increase the size of this subband */
588 subband_status[max_ch][max_sb] = SB_NOMORE;
591 *padding = max_frame_size - current_frame_size;
592 av_assert0(*padding >= 0);
596 * Output the mpeg audio layer 2 frame. Note how the code is small
597 * compared to other encoders :-)
599 static void encode_frame(MpegAudioContext *s,
600 unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT],
603 int i, j, k, l, bit_alloc_bits, b, ch;
606 PutBitContext *p = &s->pb;
610 put_bits(p, 12, 0xfff);
611 put_bits(p, 1, 1 - s->lsf); /* 1 = mpeg1 ID, 0 = mpeg2 lsf ID */
612 put_bits(p, 2, 4-2); /* layer 2 */
613 put_bits(p, 1, 1); /* no error protection */
614 put_bits(p, 4, s->bitrate_index);
615 put_bits(p, 2, s->freq_index);
616 put_bits(p, 1, s->do_padding); /* use padding */
617 put_bits(p, 1, 0); /* private_bit */
618 put_bits(p, 2, s->nb_channels == 2 ? MPA_STEREO : MPA_MONO);
619 put_bits(p, 2, 0); /* mode_ext */
620 put_bits(p, 1, 0); /* no copyright */
621 put_bits(p, 1, 1); /* original */
622 put_bits(p, 2, 0); /* no emphasis */
626 for(i=0;i<s->sblimit;i++) {
627 bit_alloc_bits = s->alloc_table[j];
628 for(ch=0;ch<s->nb_channels;ch++) {
629 put_bits(p, bit_alloc_bits, bit_alloc[ch][i]);
631 j += 1 << bit_alloc_bits;
635 for(i=0;i<s->sblimit;i++) {
636 for(ch=0;ch<s->nb_channels;ch++) {
637 if (bit_alloc[ch][i])
638 put_bits(p, 2, s->scale_code[ch][i]);
643 for(i=0;i<s->sblimit;i++) {
644 for(ch=0;ch<s->nb_channels;ch++) {
645 if (bit_alloc[ch][i]) {
646 sf = &s->scale_factors[ch][i][0];
647 switch(s->scale_code[ch][i]) {
649 put_bits(p, 6, sf[0]);
650 put_bits(p, 6, sf[1]);
651 put_bits(p, 6, sf[2]);
655 put_bits(p, 6, sf[0]);
656 put_bits(p, 6, sf[2]);
659 put_bits(p, 6, sf[0]);
666 /* quantization & write sub band samples */
671 for(i=0;i<s->sblimit;i++) {
672 bit_alloc_bits = s->alloc_table[j];
673 for(ch=0;ch<s->nb_channels;ch++) {
674 b = bit_alloc[ch][i];
676 int qindex, steps, m, sample, bits;
677 /* we encode 3 sub band samples of the same sub band at a time */
678 qindex = s->alloc_table[j+b];
679 steps = ff_mpa_quant_steps[qindex];
681 sample = s->sb_samples[ch][k][l + m][i];
682 /* divide by scale factor */
686 a = (float)sample * scale_factor_inv_table[s->scale_factors[ch][i][k]];
687 q[m] = (int)((a + 1.0) * steps * 0.5);
691 int q1, e, shift, mult;
692 e = s->scale_factors[ch][i][k];
693 shift = scale_factor_shift[e];
694 mult = scale_factor_mult[e];
696 /* normalize to P bits */
698 q1 = sample << (-shift);
700 q1 = sample >> shift;
701 q1 = (q1 * mult) >> P;
702 q[m] = ((q1 + (1 << P)) * steps) >> (P + 1);
707 av_assert2(q[m] >= 0 && q[m] < steps);
709 bits = ff_mpa_quant_bits[qindex];
711 /* group the 3 values to save bits */
713 q[0] + steps * (q[1] + steps * q[2]));
715 put_bits(p, bits, q[0]);
716 put_bits(p, bits, q[1]);
717 put_bits(p, bits, q[2]);
721 /* next subband in alloc table */
722 j += 1 << bit_alloc_bits;
728 for(i=0;i<padding;i++)
735 static int MPA_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
736 const AVFrame *frame, int *got_packet_ptr)
738 MpegAudioContext *s = avctx->priv_data;
739 const int16_t *samples = (const int16_t *)frame->data[0];
740 short smr[MPA_MAX_CHANNELS][SBLIMIT];
741 unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
744 for(i=0;i<s->nb_channels;i++) {
745 filter(s, i, samples + i, s->nb_channels);
748 for(i=0;i<s->nb_channels;i++) {
749 compute_scale_factors(s->scale_code[i], s->scale_factors[i],
750 s->sb_samples[i], s->sblimit);
752 for(i=0;i<s->nb_channels;i++) {
753 psycho_acoustic_model(s, smr[i]);
755 compute_bit_allocation(s, smr, bit_alloc, &padding);
757 if ((ret = ff_alloc_packet2(avctx, avpkt, MPA_MAX_CODED_FRAME_SIZE)))
760 init_put_bits(&s->pb, avpkt->data, avpkt->size);
762 encode_frame(s, bit_alloc, padding);
764 if (frame->pts != AV_NOPTS_VALUE)
765 avpkt->pts = frame->pts - ff_samples_to_time_base(avctx, avctx->delay);
767 avpkt->size = put_bits_count(&s->pb) / 8;
772 static av_cold int MPA_encode_close(AVCodecContext *avctx)
774 #if FF_API_OLD_ENCODE_AUDIO
775 av_freep(&avctx->coded_frame);
780 static const AVCodecDefault mp2_defaults[] = {
785 AVCodec ff_mp2_encoder = {
787 .type = AVMEDIA_TYPE_AUDIO,
788 .id = AV_CODEC_ID_MP2,
789 .priv_data_size = sizeof(MpegAudioContext),
790 .init = MPA_encode_init,
791 .encode2 = MPA_encode_frame,
792 .close = MPA_encode_close,
793 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
794 AV_SAMPLE_FMT_NONE },
795 .supported_samplerates = (const int[]){
796 44100, 48000, 32000, 22050, 24000, 16000, 0
798 .channel_layouts = (const uint64_t[]){ AV_CH_LAYOUT_MONO,
801 .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
802 .defaults = mp2_defaults,