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