]> git.sesse.net Git - ffmpeg/blob - libavcodec/aacenc.c
aacenc: Deinterleave input samples before processing.
[ffmpeg] / libavcodec / aacenc.c
1 /*
2  * AAC encoder
3  * Copyright (C) 2008 Konstantin Shishkov
4  *
5  * This file is part of Libav.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 /**
23  * @file
24  * AAC encoder
25  */
26
27 /***********************************
28  *              TODOs:
29  * add sane pulse detection
30  * add temporal noise shaping
31  ***********************************/
32
33 #include "libavutil/opt.h"
34 #include "avcodec.h"
35 #include "put_bits.h"
36 #include "dsputil.h"
37 #include "mpeg4audio.h"
38 #include "kbdwin.h"
39 #include "sinewin.h"
40
41 #include "aac.h"
42 #include "aactab.h"
43 #include "aacenc.h"
44
45 #include "psymodel.h"
46
47 #define AAC_MAX_CHANNELS 6
48
49 #define ERROR_IF(cond, ...) \
50     if (cond) { \
51         av_log(avctx, AV_LOG_ERROR, __VA_ARGS__); \
52         return AVERROR(EINVAL); \
53     }
54
55 float ff_aac_pow34sf_tab[428];
56
57 static const uint8_t swb_size_1024_96[] = {
58     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8,
59     12, 12, 12, 12, 12, 16, 16, 24, 28, 36, 44,
60     64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64
61 };
62
63 static const uint8_t swb_size_1024_64[] = {
64     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8,
65     12, 12, 12, 16, 16, 16, 20, 24, 24, 28, 36,
66     40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40
67 };
68
69 static const uint8_t swb_size_1024_48[] = {
70     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8,
71     12, 12, 12, 12, 16, 16, 20, 20, 24, 24, 28, 28,
72     32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
73     96
74 };
75
76 static const uint8_t swb_size_1024_32[] = {
77     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8,
78     12, 12, 12, 12, 16, 16, 20, 20, 24, 24, 28, 28,
79     32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32
80 };
81
82 static const uint8_t swb_size_1024_24[] = {
83     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
84     12, 12, 12, 12, 16, 16, 16, 20, 20, 24, 24, 28, 28,
85     32, 36, 36, 40, 44, 48, 52, 52, 64, 64, 64, 64, 64
86 };
87
88 static const uint8_t swb_size_1024_16[] = {
89     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
90     12, 12, 12, 12, 12, 12, 12, 12, 12, 16, 16, 16, 16, 20, 20, 20, 24, 24, 28, 28,
91     32, 36, 40, 40, 44, 48, 52, 56, 60, 64, 64, 64
92 };
93
94 static const uint8_t swb_size_1024_8[] = {
95     12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
96     16, 16, 16, 16, 16, 16, 16, 20, 20, 20, 20, 24, 24, 24, 28, 28,
97     32, 36, 36, 40, 44, 48, 52, 56, 60, 64, 80
98 };
99
100 static const uint8_t *swb_size_1024[] = {
101     swb_size_1024_96, swb_size_1024_96, swb_size_1024_64,
102     swb_size_1024_48, swb_size_1024_48, swb_size_1024_32,
103     swb_size_1024_24, swb_size_1024_24, swb_size_1024_16,
104     swb_size_1024_16, swb_size_1024_16, swb_size_1024_8
105 };
106
107 static const uint8_t swb_size_128_96[] = {
108     4, 4, 4, 4, 4, 4, 8, 8, 8, 16, 28, 36
109 };
110
111 static const uint8_t swb_size_128_48[] = {
112     4, 4, 4, 4, 4, 8, 8, 8, 12, 12, 12, 16, 16, 16
113 };
114
115 static const uint8_t swb_size_128_24[] = {
116     4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 12, 12, 16, 16, 20
117 };
118
119 static const uint8_t swb_size_128_16[] = {
120     4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 12, 12, 16, 20, 20
121 };
122
123 static const uint8_t swb_size_128_8[] = {
124     4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 12, 16, 20, 20
125 };
126
127 static const uint8_t *swb_size_128[] = {
128     /* the last entry on the following row is swb_size_128_64 but is a
129        duplicate of swb_size_128_96 */
130     swb_size_128_96, swb_size_128_96, swb_size_128_96,
131     swb_size_128_48, swb_size_128_48, swb_size_128_48,
132     swb_size_128_24, swb_size_128_24, swb_size_128_16,
133     swb_size_128_16, swb_size_128_16, swb_size_128_8
134 };
135
136 /** default channel configurations */
137 static const uint8_t aac_chan_configs[6][5] = {
138  {1, TYPE_SCE},                               // 1 channel  - single channel element
139  {1, TYPE_CPE},                               // 2 channels - channel pair
140  {2, TYPE_SCE, TYPE_CPE},                     // 3 channels - center + stereo
141  {3, TYPE_SCE, TYPE_CPE, TYPE_SCE},           // 4 channels - front center + stereo + back center
142  {3, TYPE_SCE, TYPE_CPE, TYPE_CPE},           // 5 channels - front center + stereo + back stereo
143  {4, TYPE_SCE, TYPE_CPE, TYPE_CPE, TYPE_LFE}, // 6 channels - front center + stereo + back stereo + LFE
144 };
145
146 /**
147  * Table to remap channels from Libav's default order to AAC order.
148  */
149 static const uint8_t aac_chan_maps[AAC_MAX_CHANNELS][AAC_MAX_CHANNELS] = {
150     { 0 },
151     { 0, 1 },
152     { 2, 0, 1 },
153     { 2, 0, 1, 3 },
154     { 2, 0, 1, 3, 4 },
155     { 2, 0, 1, 4, 5, 3 },
156 };
157
158 /**
159  * Make AAC audio config object.
160  * @see 1.6.2.1 "Syntax - AudioSpecificConfig"
161  */
162 static void put_audio_specific_config(AVCodecContext *avctx)
163 {
164     PutBitContext pb;
165     AACEncContext *s = avctx->priv_data;
166
167     init_put_bits(&pb, avctx->extradata, avctx->extradata_size*8);
168     put_bits(&pb, 5, 2); //object type - AAC-LC
169     put_bits(&pb, 4, s->samplerate_index); //sample rate index
170     put_bits(&pb, 4, s->channels);
171     //GASpecificConfig
172     put_bits(&pb, 1, 0); //frame length - 1024 samples
173     put_bits(&pb, 1, 0); //does not depend on core coder
174     put_bits(&pb, 1, 0); //is not extension
175
176     //Explicitly Mark SBR absent
177     put_bits(&pb, 11, 0x2b7); //sync extension
178     put_bits(&pb, 5,  AOT_SBR);
179     put_bits(&pb, 1,  0);
180     flush_put_bits(&pb);
181 }
182
183 static void apply_window_and_mdct(AACEncContext *s, SingleChannelElement *sce,
184                                   float *audio)
185 {
186     int i, k;
187     const float * lwindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
188     const float * swindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
189     const float * pwindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
190     float *output = sce->ret;
191
192     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
193         memcpy(output, sce->saved, sizeof(output[0])*1024);
194         if (sce->ics.window_sequence[0] == LONG_STOP_SEQUENCE) {
195             memset(output, 0, sizeof(output[0]) * 448);
196             for (i = 448; i < 576; i++)
197                 output[i] = sce->saved[i] * pwindow[i - 448];
198         }
199         if (sce->ics.window_sequence[0] != LONG_START_SEQUENCE) {
200             for (i = 0; i < 1024; i++) {
201                 output[i+1024] = audio[i] * lwindow[1024 - i - 1];
202                 sce->saved[i]  = audio[i] * lwindow[i];
203             }
204         } else {
205             memcpy(output + 1024, audio, sizeof(output[0]) * 448);
206             for (; i < 576; i++)
207                 output[i+1024] = audio[i] * swindow[576 - i - 1];
208             memset(output+1024+576, 0, sizeof(output[0]) * 448);
209             memcpy(sce->saved, audio, sizeof(sce->saved[0]) * 1024);
210         }
211         s->mdct1024.mdct_calc(&s->mdct1024, sce->coeffs, output);
212     } else {
213         for (k = 0; k < 1024; k += 128) {
214             for (i = 448 + k; i < 448 + k + 256; i++)
215                 output[i - 448 - k] = (i < 1024)
216                                          ? sce->saved[i]
217                                          : audio[i-1024];
218             s->dsp.vector_fmul        (output,     output, k ?  swindow : pwindow, 128);
219             s->dsp.vector_fmul_reverse(output+128, output+128, swindow, 128);
220             s->mdct128.mdct_calc(&s->mdct128, sce->coeffs + k, output);
221         }
222         memcpy(sce->saved, audio, sizeof(sce->saved[0]) * 1024);
223     }
224 }
225
226 /**
227  * Encode ics_info element.
228  * @see Table 4.6 (syntax of ics_info)
229  */
230 static void put_ics_info(AACEncContext *s, IndividualChannelStream *info)
231 {
232     int w;
233
234     put_bits(&s->pb, 1, 0);                // ics_reserved bit
235     put_bits(&s->pb, 2, info->window_sequence[0]);
236     put_bits(&s->pb, 1, info->use_kb_window[0]);
237     if (info->window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
238         put_bits(&s->pb, 6, info->max_sfb);
239         put_bits(&s->pb, 1, 0);            // no prediction
240     } else {
241         put_bits(&s->pb, 4, info->max_sfb);
242         for (w = 1; w < 8; w++)
243             put_bits(&s->pb, 1, !info->group_len[w]);
244     }
245 }
246
247 /**
248  * Encode MS data.
249  * @see 4.6.8.1 "Joint Coding - M/S Stereo"
250  */
251 static void encode_ms_info(PutBitContext *pb, ChannelElement *cpe)
252 {
253     int i, w;
254
255     put_bits(pb, 2, cpe->ms_mode);
256     if (cpe->ms_mode == 1)
257         for (w = 0; w < cpe->ch[0].ics.num_windows; w += cpe->ch[0].ics.group_len[w])
258             for (i = 0; i < cpe->ch[0].ics.max_sfb; i++)
259                 put_bits(pb, 1, cpe->ms_mask[w*16 + i]);
260 }
261
262 /**
263  * Produce integer coefficients from scalefactors provided by the model.
264  */
265 static void adjust_frame_information(AACEncContext *apc, ChannelElement *cpe, int chans)
266 {
267     int i, w, w2, g, ch;
268     int start, maxsfb, cmaxsfb;
269
270     for (ch = 0; ch < chans; ch++) {
271         IndividualChannelStream *ics = &cpe->ch[ch].ics;
272         start = 0;
273         maxsfb = 0;
274         cpe->ch[ch].pulse.num_pulse = 0;
275         for (w = 0; w < ics->num_windows*16; w += 16) {
276             for (g = 0; g < ics->num_swb; g++) {
277                 //apply M/S
278                 if (cpe->common_window && !ch && cpe->ms_mask[w + g]) {
279                     for (i = 0; i < ics->swb_sizes[g]; i++) {
280                         cpe->ch[0].coeffs[start+i] = (cpe->ch[0].coeffs[start+i] + cpe->ch[1].coeffs[start+i]) / 2.0;
281                         cpe->ch[1].coeffs[start+i] =  cpe->ch[0].coeffs[start+i] - cpe->ch[1].coeffs[start+i];
282                     }
283                 }
284                 start += ics->swb_sizes[g];
285             }
286             for (cmaxsfb = ics->num_swb; cmaxsfb > 0 && cpe->ch[ch].zeroes[w+cmaxsfb-1]; cmaxsfb--)
287                 ;
288             maxsfb = FFMAX(maxsfb, cmaxsfb);
289         }
290         ics->max_sfb = maxsfb;
291
292         //adjust zero bands for window groups
293         for (w = 0; w < ics->num_windows; w += ics->group_len[w]) {
294             for (g = 0; g < ics->max_sfb; g++) {
295                 i = 1;
296                 for (w2 = w; w2 < w + ics->group_len[w]; w2++) {
297                     if (!cpe->ch[ch].zeroes[w2*16 + g]) {
298                         i = 0;
299                         break;
300                     }
301                 }
302                 cpe->ch[ch].zeroes[w*16 + g] = i;
303             }
304         }
305     }
306
307     if (chans > 1 && cpe->common_window) {
308         IndividualChannelStream *ics0 = &cpe->ch[0].ics;
309         IndividualChannelStream *ics1 = &cpe->ch[1].ics;
310         int msc = 0;
311         ics0->max_sfb = FFMAX(ics0->max_sfb, ics1->max_sfb);
312         ics1->max_sfb = ics0->max_sfb;
313         for (w = 0; w < ics0->num_windows*16; w += 16)
314             for (i = 0; i < ics0->max_sfb; i++)
315                 if (cpe->ms_mask[w+i])
316                     msc++;
317         if (msc == 0 || ics0->max_sfb == 0)
318             cpe->ms_mode = 0;
319         else
320             cpe->ms_mode = msc < ics0->max_sfb * ics0->num_windows ? 1 : 2;
321     }
322 }
323
324 /**
325  * Encode scalefactor band coding type.
326  */
327 static void encode_band_info(AACEncContext *s, SingleChannelElement *sce)
328 {
329     int w;
330
331     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
332         s->coder->encode_window_bands_info(s, sce, w, sce->ics.group_len[w], s->lambda);
333 }
334
335 /**
336  * Encode scalefactors.
337  */
338 static void encode_scale_factors(AVCodecContext *avctx, AACEncContext *s,
339                                  SingleChannelElement *sce)
340 {
341     int off = sce->sf_idx[0], diff;
342     int i, w;
343
344     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
345         for (i = 0; i < sce->ics.max_sfb; i++) {
346             if (!sce->zeroes[w*16 + i]) {
347                 diff = sce->sf_idx[w*16 + i] - off + SCALE_DIFF_ZERO;
348                 if (diff < 0 || diff > 120)
349                     av_log(avctx, AV_LOG_ERROR, "Scalefactor difference is too big to be coded\n");
350                 off = sce->sf_idx[w*16 + i];
351                 put_bits(&s->pb, ff_aac_scalefactor_bits[diff], ff_aac_scalefactor_code[diff]);
352             }
353         }
354     }
355 }
356
357 /**
358  * Encode pulse data.
359  */
360 static void encode_pulses(AACEncContext *s, Pulse *pulse)
361 {
362     int i;
363
364     put_bits(&s->pb, 1, !!pulse->num_pulse);
365     if (!pulse->num_pulse)
366         return;
367
368     put_bits(&s->pb, 2, pulse->num_pulse - 1);
369     put_bits(&s->pb, 6, pulse->start);
370     for (i = 0; i < pulse->num_pulse; i++) {
371         put_bits(&s->pb, 5, pulse->pos[i]);
372         put_bits(&s->pb, 4, pulse->amp[i]);
373     }
374 }
375
376 /**
377  * Encode spectral coefficients processed by psychoacoustic model.
378  */
379 static void encode_spectral_coeffs(AACEncContext *s, SingleChannelElement *sce)
380 {
381     int start, i, w, w2;
382
383     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
384         start = 0;
385         for (i = 0; i < sce->ics.max_sfb; i++) {
386             if (sce->zeroes[w*16 + i]) {
387                 start += sce->ics.swb_sizes[i];
388                 continue;
389             }
390             for (w2 = w; w2 < w + sce->ics.group_len[w]; w2++)
391                 s->coder->quantize_and_encode_band(s, &s->pb, sce->coeffs + start + w2*128,
392                                                    sce->ics.swb_sizes[i],
393                                                    sce->sf_idx[w*16 + i],
394                                                    sce->band_type[w*16 + i],
395                                                    s->lambda);
396             start += sce->ics.swb_sizes[i];
397         }
398     }
399 }
400
401 /**
402  * Encode one channel of audio data.
403  */
404 static int encode_individual_channel(AVCodecContext *avctx, AACEncContext *s,
405                                      SingleChannelElement *sce,
406                                      int common_window)
407 {
408     put_bits(&s->pb, 8, sce->sf_idx[0]);
409     if (!common_window)
410         put_ics_info(s, &sce->ics);
411     encode_band_info(s, sce);
412     encode_scale_factors(avctx, s, sce);
413     encode_pulses(s, &sce->pulse);
414     put_bits(&s->pb, 1, 0); //tns
415     put_bits(&s->pb, 1, 0); //ssr
416     encode_spectral_coeffs(s, sce);
417     return 0;
418 }
419
420 /**
421  * Write some auxiliary information about the created AAC file.
422  */
423 static void put_bitstream_info(AVCodecContext *avctx, AACEncContext *s,
424                                const char *name)
425 {
426     int i, namelen, padbits;
427
428     namelen = strlen(name) + 2;
429     put_bits(&s->pb, 3, TYPE_FIL);
430     put_bits(&s->pb, 4, FFMIN(namelen, 15));
431     if (namelen >= 15)
432         put_bits(&s->pb, 8, namelen - 16);
433     put_bits(&s->pb, 4, 0); //extension type - filler
434     padbits = 8 - (put_bits_count(&s->pb) & 7);
435     avpriv_align_put_bits(&s->pb);
436     for (i = 0; i < namelen - 2; i++)
437         put_bits(&s->pb, 8, name[i]);
438     put_bits(&s->pb, 12 - padbits, 0);
439 }
440
441 /*
442  * Deinterleave input samples.
443  * Channels are reordered from Libav's default order to AAC order.
444  */
445 static void deinterleave_input_samples(AACEncContext *s,
446                                        const float *samples)
447 {
448     int ch, i;
449     const int sinc = s->channels;
450     const uint8_t *channel_map = aac_chan_maps[sinc - 1];
451
452     /* deinterleave and remap input samples */
453     for (ch = 0; ch < sinc; ch++) {
454         const float *sptr = samples + channel_map[ch];
455
456         /* copy last 1024 samples of previous frame to the start of the current frame */
457         memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][1024], 1024 * sizeof(s->planar_samples[0][0]));
458
459         /* deinterleave */
460         for (i = 1024; i < 1024 * 2; i++) {
461             s->planar_samples[ch][i] = *sptr;
462             sptr += sinc;
463         }
464     }
465 }
466
467 static int aac_encode_frame(AVCodecContext *avctx,
468                             uint8_t *frame, int buf_size, void *data)
469 {
470     AACEncContext *s = avctx->priv_data;
471     float **samples = s->planar_samples, *samples2, *la;
472     ChannelElement *cpe;
473     int i, ch, w, g, chans, tag, start_ch;
474     int chan_el_counter[4];
475     FFPsyWindowInfo windows[AAC_MAX_CHANNELS];
476
477     if (s->last_frame)
478         return 0;
479
480     if (data) {
481         deinterleave_input_samples(s, data);
482         if (s->psypp)
483             ff_psy_preprocess(s->psypp, s->planar_samples, s->channels);
484     }
485
486     if (!avctx->frame_number)
487         return 0;
488
489     start_ch = 0;
490     for (i = 0; i < s->chan_map[0]; i++) {
491         FFPsyWindowInfo* wi = windows + start_ch;
492         tag      = s->chan_map[i+1];
493         chans    = tag == TYPE_CPE ? 2 : 1;
494         cpe      = &s->cpe[i];
495         for (ch = 0; ch < chans; ch++) {
496             IndividualChannelStream *ics = &cpe->ch[ch].ics;
497             int cur_channel = start_ch + ch;
498             samples2 = &samples[cur_channel][0];
499             la       = samples2 + (448+64);
500             if (!data)
501                 la = NULL;
502             if (tag == TYPE_LFE) {
503                 wi[ch].window_type[0] = ONLY_LONG_SEQUENCE;
504                 wi[ch].window_shape   = 0;
505                 wi[ch].num_windows    = 1;
506                 wi[ch].grouping[0]    = 1;
507
508                 /* Only the lowest 12 coefficients are used in a LFE channel.
509                  * The expression below results in only the bottom 8 coefficients
510                  * being used for 11.025kHz to 16kHz sample rates.
511                  */
512                 ics->num_swb = s->samplerate_index >= 8 ? 1 : 3;
513             } else {
514                 wi[ch] = s->psy.model->window(&s->psy, samples2, la, cur_channel,
515                                               ics->window_sequence[0]);
516             }
517             ics->window_sequence[1] = ics->window_sequence[0];
518             ics->window_sequence[0] = wi[ch].window_type[0];
519             ics->use_kb_window[1]   = ics->use_kb_window[0];
520             ics->use_kb_window[0]   = wi[ch].window_shape;
521             ics->num_windows        = wi[ch].num_windows;
522             ics->swb_sizes          = s->psy.bands    [ics->num_windows == 8];
523             ics->num_swb            = tag == TYPE_LFE ? ics->num_swb : s->psy.num_bands[ics->num_windows == 8];
524             for (w = 0; w < ics->num_windows; w++)
525                 ics->group_len[w] = wi[ch].grouping[w];
526
527             apply_window_and_mdct(s, &cpe->ch[ch], samples2);
528         }
529         start_ch += chans;
530     }
531     do {
532         int frame_bits;
533         init_put_bits(&s->pb, frame, buf_size*8);
534         if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT))
535             put_bitstream_info(avctx, s, LIBAVCODEC_IDENT);
536         start_ch = 0;
537         memset(chan_el_counter, 0, sizeof(chan_el_counter));
538         for (i = 0; i < s->chan_map[0]; i++) {
539             FFPsyWindowInfo* wi = windows + start_ch;
540             const float *coeffs[2];
541             tag      = s->chan_map[i+1];
542             chans    = tag == TYPE_CPE ? 2 : 1;
543             cpe      = &s->cpe[i];
544             put_bits(&s->pb, 3, tag);
545             put_bits(&s->pb, 4, chan_el_counter[tag]++);
546             for (ch = 0; ch < chans; ch++)
547                 coeffs[ch] = cpe->ch[ch].coeffs;
548             s->psy.model->analyze(&s->psy, start_ch, coeffs, wi);
549             for (ch = 0; ch < chans; ch++) {
550                 s->cur_channel = start_ch * 2 + ch;
551                 s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda);
552             }
553             cpe->common_window = 0;
554             if (chans > 1
555                 && wi[0].window_type[0] == wi[1].window_type[0]
556                 && wi[0].window_shape   == wi[1].window_shape) {
557
558                 cpe->common_window = 1;
559                 for (w = 0; w < wi[0].num_windows; w++) {
560                     if (wi[0].grouping[w] != wi[1].grouping[w]) {
561                         cpe->common_window = 0;
562                         break;
563                     }
564                 }
565             }
566             s->cur_channel = start_ch * 2;
567             if (s->options.stereo_mode && cpe->common_window) {
568                 if (s->options.stereo_mode > 0) {
569                     IndividualChannelStream *ics = &cpe->ch[0].ics;
570                     for (w = 0; w < ics->num_windows; w += ics->group_len[w])
571                         for (g = 0;  g < ics->num_swb; g++)
572                             cpe->ms_mask[w*16+g] = 1;
573                 } else if (s->coder->search_for_ms) {
574                     s->coder->search_for_ms(s, cpe, s->lambda);
575                 }
576             }
577             adjust_frame_information(s, cpe, chans);
578             if (chans == 2) {
579                 put_bits(&s->pb, 1, cpe->common_window);
580                 if (cpe->common_window) {
581                     put_ics_info(s, &cpe->ch[0].ics);
582                     encode_ms_info(&s->pb, cpe);
583                 }
584             }
585             for (ch = 0; ch < chans; ch++) {
586                 s->cur_channel = start_ch + ch;
587                 encode_individual_channel(avctx, s, &cpe->ch[ch], cpe->common_window);
588             }
589             start_ch += chans;
590         }
591
592         frame_bits = put_bits_count(&s->pb);
593         if (frame_bits <= 6144 * s->channels - 3) {
594             s->psy.bitres.bits = frame_bits / s->channels;
595             break;
596         }
597
598         s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits;
599
600     } while (1);
601
602     put_bits(&s->pb, 3, TYPE_END);
603     flush_put_bits(&s->pb);
604     avctx->frame_bits = put_bits_count(&s->pb);
605
606     // rate control stuff
607     if (!(avctx->flags & CODEC_FLAG_QSCALE)) {
608         float ratio = avctx->bit_rate * 1024.0f / avctx->sample_rate / avctx->frame_bits;
609         s->lambda *= ratio;
610         s->lambda = FFMIN(s->lambda, 65536.f);
611     }
612
613     if (!data)
614         s->last_frame = 1;
615
616     return put_bits_count(&s->pb)>>3;
617 }
618
619 static av_cold int aac_encode_end(AVCodecContext *avctx)
620 {
621     AACEncContext *s = avctx->priv_data;
622
623     ff_mdct_end(&s->mdct1024);
624     ff_mdct_end(&s->mdct128);
625     ff_psy_end(&s->psy);
626     if (s->psypp)
627         ff_psy_preprocess_end(s->psypp);
628     av_freep(&s->buffer.samples);
629     av_freep(&s->cpe);
630     return 0;
631 }
632
633 static av_cold int dsp_init(AVCodecContext *avctx, AACEncContext *s)
634 {
635     int ret = 0;
636
637     dsputil_init(&s->dsp, avctx);
638
639     // window init
640     ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
641     ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
642     ff_init_ff_sine_windows(10);
643     ff_init_ff_sine_windows(7);
644
645     if (ret = ff_mdct_init(&s->mdct1024, 11, 0, 32768.0))
646         return ret;
647     if (ret = ff_mdct_init(&s->mdct128,   8, 0, 32768.0))
648         return ret;
649
650     return 0;
651 }
652
653 static av_cold int alloc_buffers(AVCodecContext *avctx, AACEncContext *s)
654 {
655     FF_ALLOCZ_OR_GOTO(avctx, s->buffer.samples, 2 * 1024 * s->channels * sizeof(s->buffer.samples[0]), alloc_fail);
656     FF_ALLOCZ_OR_GOTO(avctx, s->cpe, sizeof(ChannelElement) * s->chan_map[0], alloc_fail);
657     FF_ALLOCZ_OR_GOTO(avctx, avctx->extradata, 5 + FF_INPUT_BUFFER_PADDING_SIZE, alloc_fail);
658
659     for(int ch = 0; ch < s->channels; ch++)
660         s->planar_samples[ch] = s->buffer.samples + 2 * 1024 * ch;
661
662     return 0;
663 alloc_fail:
664     return AVERROR(ENOMEM);
665 }
666
667 static av_cold int aac_encode_init(AVCodecContext *avctx)
668 {
669     AACEncContext *s = avctx->priv_data;
670     int i, ret = 0;
671     const uint8_t *sizes[2];
672     uint8_t grouping[AAC_MAX_CHANNELS];
673     int lengths[2];
674
675     avctx->frame_size = 1024;
676
677     for (i = 0; i < 16; i++)
678         if (avctx->sample_rate == avpriv_mpeg4audio_sample_rates[i])
679             break;
680
681     s->channels = avctx->channels;
682
683     ERROR_IF(i == 16,
684              "Unsupported sample rate %d\n", avctx->sample_rate);
685     ERROR_IF(s->channels > AAC_MAX_CHANNELS,
686              "Unsupported number of channels: %d\n", s->channels);
687     ERROR_IF(avctx->profile != FF_PROFILE_UNKNOWN && avctx->profile != FF_PROFILE_AAC_LOW,
688              "Unsupported profile %d\n", avctx->profile);
689     ERROR_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels,
690              "Too many bits per frame requested\n");
691
692     s->samplerate_index = i;
693
694     s->chan_map = aac_chan_configs[s->channels-1];
695
696     if (ret = dsp_init(avctx, s))
697         goto fail;
698
699     if (ret = alloc_buffers(avctx, s))
700         goto fail;
701
702     avctx->extradata_size = 5;
703     put_audio_specific_config(avctx);
704
705     sizes[0]   = swb_size_1024[i];
706     sizes[1]   = swb_size_128[i];
707     lengths[0] = ff_aac_num_swb_1024[i];
708     lengths[1] = ff_aac_num_swb_128[i];
709     for (i = 0; i < s->chan_map[0]; i++)
710         grouping[i] = s->chan_map[i + 1] == TYPE_CPE;
711     if (ret = ff_psy_init(&s->psy, avctx, 2, sizes, lengths, s->chan_map[0], grouping))
712         goto fail;
713     s->psypp = ff_psy_preprocess_init(avctx);
714     s->coder = &ff_aac_coders[2];
715
716     s->lambda = avctx->global_quality ? avctx->global_quality : 120;
717
718     ff_aac_tableinit();
719
720     for (i = 0; i < 428; i++)
721         ff_aac_pow34sf_tab[i] = sqrt(ff_aac_pow2sf_tab[i] * sqrt(ff_aac_pow2sf_tab[i]));
722
723     return 0;
724 fail:
725     aac_encode_end(avctx);
726     return ret;
727 }
728
729 #define AACENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
730 static const AVOption aacenc_options[] = {
731     {"stereo_mode", "Stereo coding method", offsetof(AACEncContext, options.stereo_mode), AV_OPT_TYPE_INT, {.dbl = 0}, -1, 1, AACENC_FLAGS, "stereo_mode"},
732         {"auto",     "Selected by the Encoder", 0, AV_OPT_TYPE_CONST, {.dbl = -1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
733         {"ms_off",   "Disable Mid/Side coding", 0, AV_OPT_TYPE_CONST, {.dbl =  0 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
734         {"ms_force", "Force Mid/Side for the whole frame if possible", 0, AV_OPT_TYPE_CONST, {.dbl =  1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
735     {NULL}
736 };
737
738 static const AVClass aacenc_class = {
739     "AAC encoder",
740     av_default_item_name,
741     aacenc_options,
742     LIBAVUTIL_VERSION_INT,
743 };
744
745 AVCodec ff_aac_encoder = {
746     .name           = "aac",
747     .type           = AVMEDIA_TYPE_AUDIO,
748     .id             = CODEC_ID_AAC,
749     .priv_data_size = sizeof(AACEncContext),
750     .init           = aac_encode_init,
751     .encode         = aac_encode_frame,
752     .close          = aac_encode_end,
753     .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
754     .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_FLT,AV_SAMPLE_FMT_NONE},
755     .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
756     .priv_class = &aacenc_class,
757 };