2 * The simplest mpeg audio layer 2 encoder
3 * Copyright (c) 2000, 2001 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; 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.
31 #define FRAC_BITS 15 /* fractional bits for sb_samples and dct */
32 #define WFRAC_BITS 14 /* fractional bits for window */
34 #include "mpegaudio.h"
36 /* currently, cannot change these constants (need to modify
37 quantization stage) */
38 #define MUL(a,b) (((int64_t)(a) * (int64_t)(b)) >> FRAC_BITS)
40 #define SAMPLES_BUF_SIZE 4096
42 typedef struct MpegAudioContext {
45 int lsf; /* 1 if mpeg2 low bitrate selected */
46 int bitrate_index; /* bit rate */
48 int frame_size; /* frame size, in bits, without padding */
49 /* padding computation */
50 int frame_frac, frame_frac_incr, do_padding;
51 short samples_buf[MPA_MAX_CHANNELS][SAMPLES_BUF_SIZE]; /* buffer for filter */
52 int samples_offset[MPA_MAX_CHANNELS]; /* offset in samples_buf */
53 int sb_samples[MPA_MAX_CHANNELS][3][12][SBLIMIT];
54 unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3]; /* scale factors */
55 /* code to group 3 scale factors */
56 unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
57 int sblimit; /* number of used subbands */
58 const unsigned char *alloc_table;
61 /* define it to use floats in quantization (I don't like floats !) */
64 #include "mpegaudiodata.h"
65 #include "mpegaudiotab.h"
67 static av_cold int MPA_encode_init(AVCodecContext *avctx)
69 MpegAudioContext *s = avctx->priv_data;
70 int freq = avctx->sample_rate;
71 int bitrate = avctx->bit_rate;
72 int channels = avctx->channels;
76 if (channels <= 0 || channels > 2){
77 av_log(avctx, AV_LOG_ERROR, "encoding %d channel(s) is not allowed in mp2\n", channels);
80 bitrate = bitrate / 1000;
81 s->nb_channels = channels;
82 avctx->frame_size = MPA_FRAME_SIZE;
87 if (avpriv_mpa_freq_tab[i] == freq)
89 if ((avpriv_mpa_freq_tab[i] / 2) == freq) {
95 av_log(avctx, AV_LOG_ERROR, "Sampling rate %d is not allowed in mp2\n", freq);
100 /* encoding bitrate & frequency */
102 if (avpriv_mpa_bitrate_tab[s->lsf][1][i] == bitrate)
106 av_log(avctx, AV_LOG_ERROR, "bitrate %d is not allowed in mp2\n", bitrate);
109 s->bitrate_index = i;
111 /* compute total header size & pad bit */
113 a = (float)(bitrate * 1000 * MPA_FRAME_SIZE) / (freq * 8.0);
114 s->frame_size = ((int)a) * 8;
116 /* frame fractional size to compute padding */
118 s->frame_frac_incr = (int)((a - floor(a)) * 65536.0);
120 /* select the right allocation table */
121 table = ff_mpa_l2_select_table(bitrate, s->nb_channels, freq, s->lsf);
123 /* number of used subbands */
124 s->sblimit = ff_mpa_sblimit_table[table];
125 s->alloc_table = ff_mpa_alloc_tables[table];
127 av_dlog(avctx, "%d kb/s, %d Hz, frame_size=%d bits, table=%d, padincr=%x\n",
128 bitrate, freq, s->frame_size, table, s->frame_frac_incr);
130 for(i=0;i<s->nb_channels;i++)
131 s->samples_offset[i] = 0;
135 v = ff_mpa_enwindow[i];
137 v = (v + (1 << (16 - WFRAC_BITS - 1))) >> (16 - WFRAC_BITS);
143 filter_bank[512 - i] = v;
147 v = (int)(pow(2.0, (3 - i) / 3.0) * (1 << 20));
150 scale_factor_table[i] = v;
152 scale_factor_inv_table[i] = pow(2.0, -(3 - i) / 3.0) / (float)(1 << 20);
155 scale_factor_shift[i] = 21 - P - (i / 3);
156 scale_factor_mult[i] = (1 << P) * pow(2.0, (i % 3) / 3.0);
171 scale_diff_table[i] = v;
175 v = ff_mpa_quant_bits[i];
180 total_quant_bits[i] = 12 * v;
183 avctx->coded_frame= avcodec_alloc_frame();
184 avctx->coded_frame->key_frame= 1;
189 /* 32 point floating point IDCT without 1/sqrt(2) coef zero scaling */
190 static void idct32(int *out, int *tab)
194 const int *xp = costab32;
196 for(j=31;j>=3;j-=2) tab[j] += tab[j - 2];
235 x3 = MUL(t[16], FIX(SQRT2*0.5));
239 x2 = MUL(-(t[24] + t[8]), FIX(SQRT2*0.5));
240 x1 = MUL((t[8] - x2), xp[0]);
241 x2 = MUL((t[8] + x2), xp[1]);
254 xr = MUL(t[28],xp[0]);
258 xr = MUL(t[4],xp[1]);
259 t[ 4] = (t[24] - xr);
260 t[24] = (t[24] + xr);
262 xr = MUL(t[20],xp[2]);
266 xr = MUL(t[12],xp[3]);
267 t[12] = (t[16] - xr);
268 t[16] = (t[16] + xr);
273 for (i = 0; i < 4; i++) {
274 xr = MUL(tab[30-i*4],xp[0]);
275 tab[30-i*4] = (tab[i*4] - xr);
276 tab[ i*4] = (tab[i*4] + xr);
278 xr = MUL(tab[ 2+i*4],xp[1]);
279 tab[ 2+i*4] = (tab[28-i*4] - xr);
280 tab[28-i*4] = (tab[28-i*4] + xr);
282 xr = MUL(tab[31-i*4],xp[0]);
283 tab[31-i*4] = (tab[1+i*4] - xr);
284 tab[ 1+i*4] = (tab[1+i*4] + xr);
286 xr = MUL(tab[ 3+i*4],xp[1]);
287 tab[ 3+i*4] = (tab[29-i*4] - xr);
288 tab[29-i*4] = (tab[29-i*4] + xr);
296 xr = MUL(t1[0], *xp);
305 out[i] = tab[bitinv32[i]];
309 #define WSHIFT (WFRAC_BITS + 15 - FRAC_BITS)
311 static void filter(MpegAudioContext *s, int ch, const short *samples, int incr)
314 int sum, offset, i, j;
319 offset = s->samples_offset[ch];
320 out = &s->sb_samples[ch][0][0][0];
322 /* 32 samples at once */
324 s->samples_buf[ch][offset + (31 - i)] = samples[0];
329 p = s->samples_buf[ch] + offset;
333 sum = p[0*64] * q[0*64];
334 sum += p[1*64] * q[1*64];
335 sum += p[2*64] * q[2*64];
336 sum += p[3*64] * q[3*64];
337 sum += p[4*64] * q[4*64];
338 sum += p[5*64] * q[5*64];
339 sum += p[6*64] * q[6*64];
340 sum += p[7*64] * q[7*64];
345 tmp1[0] = tmp[16] >> WSHIFT;
346 for( i=1; i<=16; i++ ) tmp1[i] = (tmp[i+16]+tmp[16-i]) >> WSHIFT;
347 for( i=17; i<=31; i++ ) tmp1[i] = (tmp[i+16]-tmp[80-i]) >> WSHIFT;
351 /* advance of 32 samples */
354 /* handle the wrap around */
356 memmove(s->samples_buf[ch] + SAMPLES_BUF_SIZE - (512 - 32),
357 s->samples_buf[ch], (512 - 32) * 2);
358 offset = SAMPLES_BUF_SIZE - 512;
361 s->samples_offset[ch] = offset;
364 static void compute_scale_factors(unsigned char scale_code[SBLIMIT],
365 unsigned char scale_factors[SBLIMIT][3],
366 int sb_samples[3][12][SBLIMIT],
369 int *p, vmax, v, n, i, j, k, code;
371 unsigned char *sf = &scale_factors[0][0];
373 for(j=0;j<sblimit;j++) {
375 /* find the max absolute value */
376 p = &sb_samples[i][0][j];
384 /* compute the scale factor index using log 2 computations */
387 /* n is the position of the MSB of vmax. now
388 use at most 2 compares to find the index */
389 index = (21 - n) * 3 - 3;
391 while (vmax <= scale_factor_table[index+1])
394 index = 0; /* very unlikely case of overflow */
397 index = 62; /* value 63 is not allowed */
400 av_dlog(NULL, "%2d:%d in=%x %x %d\n",
401 j, i, vmax, scale_factor_table[index], index);
402 /* store the scale factor */
403 assert(index >=0 && index <= 63);
407 /* compute the transmission factor : look if the scale factors
408 are close enough to each other */
409 d1 = scale_diff_table[sf[0] - sf[1] + 64];
410 d2 = scale_diff_table[sf[1] - sf[2] + 64];
412 /* handle the 25 cases */
413 switch(d1 * 5 + d2) {
445 sf[1] = sf[2] = sf[0];
450 sf[0] = sf[1] = sf[2];
456 sf[0] = sf[2] = sf[1];
462 sf[1] = sf[2] = sf[0];
465 assert(0); //cannot happen
466 code = 0; /* kill warning */
469 av_dlog(NULL, "%d: %2d %2d %2d %d %d -> %d\n", j,
470 sf[0], sf[1], sf[2], d1, d2, code);
471 scale_code[j] = code;
476 /* The most important function : psycho acoustic module. In this
477 encoder there is basically none, so this is the worst you can do,
478 but also this is the simpler. */
479 static void psycho_acoustic_model(MpegAudioContext *s, short smr[SBLIMIT])
483 for(i=0;i<s->sblimit;i++) {
484 smr[i] = (int)(fixed_smr[i] * 10);
489 #define SB_NOTALLOCATED 0
490 #define SB_ALLOCATED 1
493 /* Try to maximize the smr while using a number of bits inferior to
494 the frame size. I tried to make the code simpler, faster and
495 smaller than other encoders :-) */
496 static void compute_bit_allocation(MpegAudioContext *s,
497 short smr1[MPA_MAX_CHANNELS][SBLIMIT],
498 unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT],
501 int i, ch, b, max_smr, max_ch, max_sb, current_frame_size, max_frame_size;
503 short smr[MPA_MAX_CHANNELS][SBLIMIT];
504 unsigned char subband_status[MPA_MAX_CHANNELS][SBLIMIT];
505 const unsigned char *alloc;
507 memcpy(smr, smr1, s->nb_channels * sizeof(short) * SBLIMIT);
508 memset(subband_status, SB_NOTALLOCATED, s->nb_channels * SBLIMIT);
509 memset(bit_alloc, 0, s->nb_channels * SBLIMIT);
511 /* compute frame size and padding */
512 max_frame_size = s->frame_size;
513 s->frame_frac += s->frame_frac_incr;
514 if (s->frame_frac >= 65536) {
515 s->frame_frac -= 65536;
522 /* compute the header + bit alloc size */
523 current_frame_size = 32;
524 alloc = s->alloc_table;
525 for(i=0;i<s->sblimit;i++) {
527 current_frame_size += incr * s->nb_channels;
531 /* look for the subband with the largest signal to mask ratio */
535 for(ch=0;ch<s->nb_channels;ch++) {
536 for(i=0;i<s->sblimit;i++) {
537 if (smr[ch][i] > max_smr && subband_status[ch][i] != SB_NOMORE) {
538 max_smr = smr[ch][i];
546 av_dlog(NULL, "current=%d max=%d max_sb=%d max_ch=%d alloc=%d\n",
547 current_frame_size, max_frame_size, max_sb, max_ch,
548 bit_alloc[max_ch][max_sb]);
550 /* find alloc table entry (XXX: not optimal, should use
552 alloc = s->alloc_table;
553 for(i=0;i<max_sb;i++) {
554 alloc += 1 << alloc[0];
557 if (subband_status[max_ch][max_sb] == SB_NOTALLOCATED) {
558 /* nothing was coded for this band: add the necessary bits */
559 incr = 2 + nb_scale_factors[s->scale_code[max_ch][max_sb]] * 6;
560 incr += total_quant_bits[alloc[1]];
562 /* increments bit allocation */
563 b = bit_alloc[max_ch][max_sb];
564 incr = total_quant_bits[alloc[b + 1]] -
565 total_quant_bits[alloc[b]];
568 if (current_frame_size + incr <= max_frame_size) {
569 /* can increase size */
570 b = ++bit_alloc[max_ch][max_sb];
571 current_frame_size += incr;
572 /* decrease smr by the resolution we added */
573 smr[max_ch][max_sb] = smr1[max_ch][max_sb] - quant_snr[alloc[b]];
574 /* max allocation size reached ? */
575 if (b == ((1 << alloc[0]) - 1))
576 subband_status[max_ch][max_sb] = SB_NOMORE;
578 subband_status[max_ch][max_sb] = SB_ALLOCATED;
580 /* cannot increase the size of this subband */
581 subband_status[max_ch][max_sb] = SB_NOMORE;
584 *padding = max_frame_size - current_frame_size;
585 assert(*padding >= 0);
589 * Output the mpeg audio layer 2 frame. Note how the code is small
590 * compared to other encoders :-)
592 static void encode_frame(MpegAudioContext *s,
593 unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT],
596 int i, j, k, l, bit_alloc_bits, b, ch;
599 PutBitContext *p = &s->pb;
603 put_bits(p, 12, 0xfff);
604 put_bits(p, 1, 1 - s->lsf); /* 1 = mpeg1 ID, 0 = mpeg2 lsf ID */
605 put_bits(p, 2, 4-2); /* layer 2 */
606 put_bits(p, 1, 1); /* no error protection */
607 put_bits(p, 4, s->bitrate_index);
608 put_bits(p, 2, s->freq_index);
609 put_bits(p, 1, s->do_padding); /* use padding */
610 put_bits(p, 1, 0); /* private_bit */
611 put_bits(p, 2, s->nb_channels == 2 ? MPA_STEREO : MPA_MONO);
612 put_bits(p, 2, 0); /* mode_ext */
613 put_bits(p, 1, 0); /* no copyright */
614 put_bits(p, 1, 1); /* original */
615 put_bits(p, 2, 0); /* no emphasis */
619 for(i=0;i<s->sblimit;i++) {
620 bit_alloc_bits = s->alloc_table[j];
621 for(ch=0;ch<s->nb_channels;ch++) {
622 put_bits(p, bit_alloc_bits, bit_alloc[ch][i]);
624 j += 1 << bit_alloc_bits;
628 for(i=0;i<s->sblimit;i++) {
629 for(ch=0;ch<s->nb_channels;ch++) {
630 if (bit_alloc[ch][i])
631 put_bits(p, 2, s->scale_code[ch][i]);
636 for(i=0;i<s->sblimit;i++) {
637 for(ch=0;ch<s->nb_channels;ch++) {
638 if (bit_alloc[ch][i]) {
639 sf = &s->scale_factors[ch][i][0];
640 switch(s->scale_code[ch][i]) {
642 put_bits(p, 6, sf[0]);
643 put_bits(p, 6, sf[1]);
644 put_bits(p, 6, sf[2]);
648 put_bits(p, 6, sf[0]);
649 put_bits(p, 6, sf[2]);
652 put_bits(p, 6, sf[0]);
659 /* quantization & write sub band samples */
664 for(i=0;i<s->sblimit;i++) {
665 bit_alloc_bits = s->alloc_table[j];
666 for(ch=0;ch<s->nb_channels;ch++) {
667 b = bit_alloc[ch][i];
669 int qindex, steps, m, sample, bits;
670 /* we encode 3 sub band samples of the same sub band at a time */
671 qindex = s->alloc_table[j+b];
672 steps = ff_mpa_quant_steps[qindex];
674 sample = s->sb_samples[ch][k][l + m][i];
675 /* divide by scale factor */
679 a = (float)sample * scale_factor_inv_table[s->scale_factors[ch][i][k]];
680 q[m] = (int)((a + 1.0) * steps * 0.5);
684 int q1, e, shift, mult;
685 e = s->scale_factors[ch][i][k];
686 shift = scale_factor_shift[e];
687 mult = scale_factor_mult[e];
689 /* normalize to P bits */
691 q1 = sample << (-shift);
693 q1 = sample >> shift;
694 q1 = (q1 * mult) >> P;
695 q[m] = ((q1 + (1 << P)) * steps) >> (P + 1);
700 assert(q[m] >= 0 && q[m] < steps);
702 bits = ff_mpa_quant_bits[qindex];
704 /* group the 3 values to save bits */
706 q[0] + steps * (q[1] + steps * q[2]));
708 put_bits(p, bits, q[0]);
709 put_bits(p, bits, q[1]);
710 put_bits(p, bits, q[2]);
714 /* next subband in alloc table */
715 j += 1 << bit_alloc_bits;
721 for(i=0;i<padding;i++)
728 static int MPA_encode_frame(AVCodecContext *avctx,
729 unsigned char *frame, int buf_size, void *data)
731 MpegAudioContext *s = avctx->priv_data;
732 const short *samples = data;
733 short smr[MPA_MAX_CHANNELS][SBLIMIT];
734 unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
737 for(i=0;i<s->nb_channels;i++) {
738 filter(s, i, samples + i, s->nb_channels);
741 for(i=0;i<s->nb_channels;i++) {
742 compute_scale_factors(s->scale_code[i], s->scale_factors[i],
743 s->sb_samples[i], s->sblimit);
745 for(i=0;i<s->nb_channels;i++) {
746 psycho_acoustic_model(s, smr[i]);
748 compute_bit_allocation(s, smr, bit_alloc, &padding);
750 init_put_bits(&s->pb, frame, MPA_MAX_CODED_FRAME_SIZE);
752 encode_frame(s, bit_alloc, padding);
754 return put_bits_ptr(&s->pb) - s->pb.buf;
757 static av_cold int MPA_encode_close(AVCodecContext *avctx)
759 av_freep(&avctx->coded_frame);
763 static const AVCodecDefault mp2_defaults[] = {
768 AVCodec ff_mp2_encoder = {
770 .type = AVMEDIA_TYPE_AUDIO,
772 .priv_data_size = sizeof(MpegAudioContext),
773 .init = MPA_encode_init,
774 .encode = MPA_encode_frame,
775 .close = MPA_encode_close,
776 .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
777 .supported_samplerates= (const int[]){44100, 48000, 32000, 22050, 24000, 16000, 0},
778 .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
779 .defaults = mp2_defaults,