]> git.sesse.net Git - ffmpeg/blob - libavcodec/aacenc.c
lavc: remove disabled FF_API_ANTIALIAS_ALGO cruft.
[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 #define WINDOW_FUNC(type) \
184 static void apply_ ##type ##_window(DSPContext *dsp, SingleChannelElement *sce, const float *audio)
185
186 WINDOW_FUNC(only_long)
187 {
188     const float *lwindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
189     const float *pwindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
190     float *out = sce->ret;
191
192     dsp->vector_fmul        (out,        audio,        lwindow, 1024);
193     dsp->vector_fmul_reverse(out + 1024, audio + 1024, pwindow, 1024);
194 }
195
196 WINDOW_FUNC(long_start)
197 {
198     const float *lwindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
199     const float *swindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
200     float *out = sce->ret;
201
202     dsp->vector_fmul(out, audio, lwindow, 1024);
203     memcpy(out + 1024, audio, sizeof(out[0]) * 448);
204     dsp->vector_fmul_reverse(out + 1024 + 448, audio, swindow, 128);
205     memset(out + 1024 + 576, 0, sizeof(out[0]) * 448);
206 }
207
208 WINDOW_FUNC(long_stop)
209 {
210     const float *lwindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
211     const float *swindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
212     float *out = sce->ret;
213
214     memset(out, 0, sizeof(out[0]) * 448);
215     dsp->vector_fmul(out + 448, audio + 448, swindow, 128);
216     memcpy(out + 576, audio + 576, sizeof(out[0]) * 448);
217     dsp->vector_fmul_reverse(out + 1024, audio + 1024, lwindow, 1024);
218 }
219
220 WINDOW_FUNC(eight_short)
221 {
222     const float *swindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
223     const float *pwindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
224     const float *in = audio + 448;
225     float *out = sce->ret;
226
227     for (int w = 0; w < 8; w++) {
228         dsp->vector_fmul        (out, in, w ? pwindow : swindow, 128);
229         out += 128;
230         in  += 128;
231         dsp->vector_fmul_reverse(out, in, swindow, 128);
232         out += 128;
233     }
234 }
235
236 static void (*const apply_window[4])(DSPContext *dsp, SingleChannelElement *sce, const float *audio) = {
237     [ONLY_LONG_SEQUENCE]   = apply_only_long_window,
238     [LONG_START_SEQUENCE]  = apply_long_start_window,
239     [EIGHT_SHORT_SEQUENCE] = apply_eight_short_window,
240     [LONG_STOP_SEQUENCE]   = apply_long_stop_window
241 };
242
243 static void apply_window_and_mdct(AACEncContext *s, SingleChannelElement *sce,
244                                   float *audio)
245 {
246     int i;
247     float *output = sce->ret;
248
249     apply_window[sce->ics.window_sequence[0]](&s->dsp, sce, audio);
250
251     if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE)
252         s->mdct1024.mdct_calc(&s->mdct1024, sce->coeffs, output);
253     else
254         for (i = 0; i < 1024; i += 128)
255             s->mdct128.mdct_calc(&s->mdct128, sce->coeffs + i, output + i*2);
256     memcpy(audio, audio + 1024, sizeof(audio[0]) * 1024);
257 }
258
259 /**
260  * Encode ics_info element.
261  * @see Table 4.6 (syntax of ics_info)
262  */
263 static void put_ics_info(AACEncContext *s, IndividualChannelStream *info)
264 {
265     int w;
266
267     put_bits(&s->pb, 1, 0);                // ics_reserved bit
268     put_bits(&s->pb, 2, info->window_sequence[0]);
269     put_bits(&s->pb, 1, info->use_kb_window[0]);
270     if (info->window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
271         put_bits(&s->pb, 6, info->max_sfb);
272         put_bits(&s->pb, 1, 0);            // no prediction
273     } else {
274         put_bits(&s->pb, 4, info->max_sfb);
275         for (w = 1; w < 8; w++)
276             put_bits(&s->pb, 1, !info->group_len[w]);
277     }
278 }
279
280 /**
281  * Encode MS data.
282  * @see 4.6.8.1 "Joint Coding - M/S Stereo"
283  */
284 static void encode_ms_info(PutBitContext *pb, ChannelElement *cpe)
285 {
286     int i, w;
287
288     put_bits(pb, 2, cpe->ms_mode);
289     if (cpe->ms_mode == 1)
290         for (w = 0; w < cpe->ch[0].ics.num_windows; w += cpe->ch[0].ics.group_len[w])
291             for (i = 0; i < cpe->ch[0].ics.max_sfb; i++)
292                 put_bits(pb, 1, cpe->ms_mask[w*16 + i]);
293 }
294
295 /**
296  * Produce integer coefficients from scalefactors provided by the model.
297  */
298 static void adjust_frame_information(AACEncContext *apc, ChannelElement *cpe, int chans)
299 {
300     int i, w, w2, g, ch;
301     int start, maxsfb, cmaxsfb;
302
303     for (ch = 0; ch < chans; ch++) {
304         IndividualChannelStream *ics = &cpe->ch[ch].ics;
305         start = 0;
306         maxsfb = 0;
307         cpe->ch[ch].pulse.num_pulse = 0;
308         for (w = 0; w < ics->num_windows*16; w += 16) {
309             for (g = 0; g < ics->num_swb; g++) {
310                 //apply M/S
311                 if (cpe->common_window && !ch && cpe->ms_mask[w + g]) {
312                     for (i = 0; i < ics->swb_sizes[g]; i++) {
313                         cpe->ch[0].coeffs[start+i] = (cpe->ch[0].coeffs[start+i] + cpe->ch[1].coeffs[start+i]) / 2.0;
314                         cpe->ch[1].coeffs[start+i] =  cpe->ch[0].coeffs[start+i] - cpe->ch[1].coeffs[start+i];
315                     }
316                 }
317                 start += ics->swb_sizes[g];
318             }
319             for (cmaxsfb = ics->num_swb; cmaxsfb > 0 && cpe->ch[ch].zeroes[w+cmaxsfb-1]; cmaxsfb--)
320                 ;
321             maxsfb = FFMAX(maxsfb, cmaxsfb);
322         }
323         ics->max_sfb = maxsfb;
324
325         //adjust zero bands for window groups
326         for (w = 0; w < ics->num_windows; w += ics->group_len[w]) {
327             for (g = 0; g < ics->max_sfb; g++) {
328                 i = 1;
329                 for (w2 = w; w2 < w + ics->group_len[w]; w2++) {
330                     if (!cpe->ch[ch].zeroes[w2*16 + g]) {
331                         i = 0;
332                         break;
333                     }
334                 }
335                 cpe->ch[ch].zeroes[w*16 + g] = i;
336             }
337         }
338     }
339
340     if (chans > 1 && cpe->common_window) {
341         IndividualChannelStream *ics0 = &cpe->ch[0].ics;
342         IndividualChannelStream *ics1 = &cpe->ch[1].ics;
343         int msc = 0;
344         ics0->max_sfb = FFMAX(ics0->max_sfb, ics1->max_sfb);
345         ics1->max_sfb = ics0->max_sfb;
346         for (w = 0; w < ics0->num_windows*16; w += 16)
347             for (i = 0; i < ics0->max_sfb; i++)
348                 if (cpe->ms_mask[w+i])
349                     msc++;
350         if (msc == 0 || ics0->max_sfb == 0)
351             cpe->ms_mode = 0;
352         else
353             cpe->ms_mode = msc < ics0->max_sfb * ics0->num_windows ? 1 : 2;
354     }
355 }
356
357 /**
358  * Encode scalefactor band coding type.
359  */
360 static void encode_band_info(AACEncContext *s, SingleChannelElement *sce)
361 {
362     int w;
363
364     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
365         s->coder->encode_window_bands_info(s, sce, w, sce->ics.group_len[w], s->lambda);
366 }
367
368 /**
369  * Encode scalefactors.
370  */
371 static void encode_scale_factors(AVCodecContext *avctx, AACEncContext *s,
372                                  SingleChannelElement *sce)
373 {
374     int off = sce->sf_idx[0], diff;
375     int i, w;
376
377     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
378         for (i = 0; i < sce->ics.max_sfb; i++) {
379             if (!sce->zeroes[w*16 + i]) {
380                 diff = sce->sf_idx[w*16 + i] - off + SCALE_DIFF_ZERO;
381                 if (diff < 0 || diff > 120)
382                     av_log(avctx, AV_LOG_ERROR, "Scalefactor difference is too big to be coded\n");
383                 off = sce->sf_idx[w*16 + i];
384                 put_bits(&s->pb, ff_aac_scalefactor_bits[diff], ff_aac_scalefactor_code[diff]);
385             }
386         }
387     }
388 }
389
390 /**
391  * Encode pulse data.
392  */
393 static void encode_pulses(AACEncContext *s, Pulse *pulse)
394 {
395     int i;
396
397     put_bits(&s->pb, 1, !!pulse->num_pulse);
398     if (!pulse->num_pulse)
399         return;
400
401     put_bits(&s->pb, 2, pulse->num_pulse - 1);
402     put_bits(&s->pb, 6, pulse->start);
403     for (i = 0; i < pulse->num_pulse; i++) {
404         put_bits(&s->pb, 5, pulse->pos[i]);
405         put_bits(&s->pb, 4, pulse->amp[i]);
406     }
407 }
408
409 /**
410  * Encode spectral coefficients processed by psychoacoustic model.
411  */
412 static void encode_spectral_coeffs(AACEncContext *s, SingleChannelElement *sce)
413 {
414     int start, i, w, w2;
415
416     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
417         start = 0;
418         for (i = 0; i < sce->ics.max_sfb; i++) {
419             if (sce->zeroes[w*16 + i]) {
420                 start += sce->ics.swb_sizes[i];
421                 continue;
422             }
423             for (w2 = w; w2 < w + sce->ics.group_len[w]; w2++)
424                 s->coder->quantize_and_encode_band(s, &s->pb, sce->coeffs + start + w2*128,
425                                                    sce->ics.swb_sizes[i],
426                                                    sce->sf_idx[w*16 + i],
427                                                    sce->band_type[w*16 + i],
428                                                    s->lambda);
429             start += sce->ics.swb_sizes[i];
430         }
431     }
432 }
433
434 /**
435  * Encode one channel of audio data.
436  */
437 static int encode_individual_channel(AVCodecContext *avctx, AACEncContext *s,
438                                      SingleChannelElement *sce,
439                                      int common_window)
440 {
441     put_bits(&s->pb, 8, sce->sf_idx[0]);
442     if (!common_window)
443         put_ics_info(s, &sce->ics);
444     encode_band_info(s, sce);
445     encode_scale_factors(avctx, s, sce);
446     encode_pulses(s, &sce->pulse);
447     put_bits(&s->pb, 1, 0); //tns
448     put_bits(&s->pb, 1, 0); //ssr
449     encode_spectral_coeffs(s, sce);
450     return 0;
451 }
452
453 /**
454  * Write some auxiliary information about the created AAC file.
455  */
456 static void put_bitstream_info(AVCodecContext *avctx, AACEncContext *s,
457                                const char *name)
458 {
459     int i, namelen, padbits;
460
461     namelen = strlen(name) + 2;
462     put_bits(&s->pb, 3, TYPE_FIL);
463     put_bits(&s->pb, 4, FFMIN(namelen, 15));
464     if (namelen >= 15)
465         put_bits(&s->pb, 8, namelen - 14);
466     put_bits(&s->pb, 4, 0); //extension type - filler
467     padbits = -put_bits_count(&s->pb) & 7;
468     avpriv_align_put_bits(&s->pb);
469     for (i = 0; i < namelen - 2; i++)
470         put_bits(&s->pb, 8, name[i]);
471     put_bits(&s->pb, 12 - padbits, 0);
472 }
473
474 /*
475  * Deinterleave input samples.
476  * Channels are reordered from Libav's default order to AAC order.
477  */
478 static void deinterleave_input_samples(AACEncContext *s,
479                                        const float *samples)
480 {
481     int ch, i;
482     const int sinc = s->channels;
483     const uint8_t *channel_map = aac_chan_maps[sinc - 1];
484
485     /* deinterleave and remap input samples */
486     for (ch = 0; ch < sinc; ch++) {
487         const float *sptr = samples + channel_map[ch];
488
489         /* copy last 1024 samples of previous frame to the start of the current frame */
490         memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][1024], 1024 * sizeof(s->planar_samples[0][0]));
491
492         /* deinterleave */
493         for (i = 1024; i < 1024 * 2; i++) {
494             s->planar_samples[ch][i] = *sptr;
495             sptr += sinc;
496         }
497     }
498 }
499
500 static int aac_encode_frame(AVCodecContext *avctx,
501                             uint8_t *frame, int buf_size, void *data)
502 {
503     AACEncContext *s = avctx->priv_data;
504     float **samples = s->planar_samples, *samples2, *la, *overlap;
505     ChannelElement *cpe;
506     int i, ch, w, g, chans, tag, start_ch;
507     int chan_el_counter[4];
508     FFPsyWindowInfo windows[AAC_MAX_CHANNELS];
509
510     if (s->last_frame)
511         return 0;
512
513     if (data) {
514         deinterleave_input_samples(s, data);
515         if (s->psypp)
516             ff_psy_preprocess(s->psypp, s->planar_samples, s->channels);
517     }
518
519     if (!avctx->frame_number)
520         return 0;
521
522     start_ch = 0;
523     for (i = 0; i < s->chan_map[0]; i++) {
524         FFPsyWindowInfo* wi = windows + start_ch;
525         tag      = s->chan_map[i+1];
526         chans    = tag == TYPE_CPE ? 2 : 1;
527         cpe      = &s->cpe[i];
528         for (ch = 0; ch < chans; ch++) {
529             IndividualChannelStream *ics = &cpe->ch[ch].ics;
530             int cur_channel = start_ch + ch;
531             overlap  = &samples[cur_channel][0];
532             samples2 = overlap + 1024;
533             la       = samples2 + (448+64);
534             if (!data)
535                 la = NULL;
536             if (tag == TYPE_LFE) {
537                 wi[ch].window_type[0] = ONLY_LONG_SEQUENCE;
538                 wi[ch].window_shape   = 0;
539                 wi[ch].num_windows    = 1;
540                 wi[ch].grouping[0]    = 1;
541
542                 /* Only the lowest 12 coefficients are used in a LFE channel.
543                  * The expression below results in only the bottom 8 coefficients
544                  * being used for 11.025kHz to 16kHz sample rates.
545                  */
546                 ics->num_swb = s->samplerate_index >= 8 ? 1 : 3;
547             } else {
548                 wi[ch] = s->psy.model->window(&s->psy, samples2, la, cur_channel,
549                                               ics->window_sequence[0]);
550             }
551             ics->window_sequence[1] = ics->window_sequence[0];
552             ics->window_sequence[0] = wi[ch].window_type[0];
553             ics->use_kb_window[1]   = ics->use_kb_window[0];
554             ics->use_kb_window[0]   = wi[ch].window_shape;
555             ics->num_windows        = wi[ch].num_windows;
556             ics->swb_sizes          = s->psy.bands    [ics->num_windows == 8];
557             ics->num_swb            = tag == TYPE_LFE ? ics->num_swb : s->psy.num_bands[ics->num_windows == 8];
558             for (w = 0; w < ics->num_windows; w++)
559                 ics->group_len[w] = wi[ch].grouping[w];
560
561             apply_window_and_mdct(s, &cpe->ch[ch], overlap);
562         }
563         start_ch += chans;
564     }
565     do {
566         int frame_bits;
567         init_put_bits(&s->pb, frame, buf_size*8);
568         if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT))
569             put_bitstream_info(avctx, s, LIBAVCODEC_IDENT);
570         start_ch = 0;
571         memset(chan_el_counter, 0, sizeof(chan_el_counter));
572         for (i = 0; i < s->chan_map[0]; i++) {
573             FFPsyWindowInfo* wi = windows + start_ch;
574             const float *coeffs[2];
575             tag      = s->chan_map[i+1];
576             chans    = tag == TYPE_CPE ? 2 : 1;
577             cpe      = &s->cpe[i];
578             put_bits(&s->pb, 3, tag);
579             put_bits(&s->pb, 4, chan_el_counter[tag]++);
580             for (ch = 0; ch < chans; ch++)
581                 coeffs[ch] = cpe->ch[ch].coeffs;
582             s->psy.model->analyze(&s->psy, start_ch, coeffs, wi);
583             for (ch = 0; ch < chans; ch++) {
584                 s->cur_channel = start_ch * 2 + ch;
585                 s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda);
586             }
587             cpe->common_window = 0;
588             if (chans > 1
589                 && wi[0].window_type[0] == wi[1].window_type[0]
590                 && wi[0].window_shape   == wi[1].window_shape) {
591
592                 cpe->common_window = 1;
593                 for (w = 0; w < wi[0].num_windows; w++) {
594                     if (wi[0].grouping[w] != wi[1].grouping[w]) {
595                         cpe->common_window = 0;
596                         break;
597                     }
598                 }
599             }
600             s->cur_channel = start_ch * 2;
601             if (s->options.stereo_mode && cpe->common_window) {
602                 if (s->options.stereo_mode > 0) {
603                     IndividualChannelStream *ics = &cpe->ch[0].ics;
604                     for (w = 0; w < ics->num_windows; w += ics->group_len[w])
605                         for (g = 0;  g < ics->num_swb; g++)
606                             cpe->ms_mask[w*16+g] = 1;
607                 } else if (s->coder->search_for_ms) {
608                     s->coder->search_for_ms(s, cpe, s->lambda);
609                 }
610             }
611             adjust_frame_information(s, cpe, chans);
612             if (chans == 2) {
613                 put_bits(&s->pb, 1, cpe->common_window);
614                 if (cpe->common_window) {
615                     put_ics_info(s, &cpe->ch[0].ics);
616                     encode_ms_info(&s->pb, cpe);
617                 }
618             }
619             for (ch = 0; ch < chans; ch++) {
620                 s->cur_channel = start_ch + ch;
621                 encode_individual_channel(avctx, s, &cpe->ch[ch], cpe->common_window);
622             }
623             start_ch += chans;
624         }
625
626         frame_bits = put_bits_count(&s->pb);
627         if (frame_bits <= 6144 * s->channels - 3) {
628             s->psy.bitres.bits = frame_bits / s->channels;
629             break;
630         }
631
632         s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits;
633
634     } while (1);
635
636     put_bits(&s->pb, 3, TYPE_END);
637     flush_put_bits(&s->pb);
638     avctx->frame_bits = put_bits_count(&s->pb);
639
640     // rate control stuff
641     if (!(avctx->flags & CODEC_FLAG_QSCALE)) {
642         float ratio = avctx->bit_rate * 1024.0f / avctx->sample_rate / avctx->frame_bits;
643         s->lambda *= ratio;
644         s->lambda = FFMIN(s->lambda, 65536.f);
645     }
646
647     if (!data)
648         s->last_frame = 1;
649
650     return put_bits_count(&s->pb)>>3;
651 }
652
653 static av_cold int aac_encode_end(AVCodecContext *avctx)
654 {
655     AACEncContext *s = avctx->priv_data;
656
657     ff_mdct_end(&s->mdct1024);
658     ff_mdct_end(&s->mdct128);
659     ff_psy_end(&s->psy);
660     if (s->psypp)
661         ff_psy_preprocess_end(s->psypp);
662     av_freep(&s->buffer.samples);
663     av_freep(&s->cpe);
664     return 0;
665 }
666
667 static av_cold int dsp_init(AVCodecContext *avctx, AACEncContext *s)
668 {
669     int ret = 0;
670
671     dsputil_init(&s->dsp, avctx);
672
673     // window init
674     ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
675     ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
676     ff_init_ff_sine_windows(10);
677     ff_init_ff_sine_windows(7);
678
679     if (ret = ff_mdct_init(&s->mdct1024, 11, 0, 32768.0))
680         return ret;
681     if (ret = ff_mdct_init(&s->mdct128,   8, 0, 32768.0))
682         return ret;
683
684     return 0;
685 }
686
687 static av_cold int alloc_buffers(AVCodecContext *avctx, AACEncContext *s)
688 {
689     FF_ALLOCZ_OR_GOTO(avctx, s->buffer.samples, 3 * 1024 * s->channels * sizeof(s->buffer.samples[0]), alloc_fail);
690     FF_ALLOCZ_OR_GOTO(avctx, s->cpe, sizeof(ChannelElement) * s->chan_map[0], alloc_fail);
691     FF_ALLOCZ_OR_GOTO(avctx, avctx->extradata, 5 + FF_INPUT_BUFFER_PADDING_SIZE, alloc_fail);
692
693     for(int ch = 0; ch < s->channels; ch++)
694         s->planar_samples[ch] = s->buffer.samples + 3 * 1024 * ch;
695
696     return 0;
697 alloc_fail:
698     return AVERROR(ENOMEM);
699 }
700
701 static av_cold int aac_encode_init(AVCodecContext *avctx)
702 {
703     AACEncContext *s = avctx->priv_data;
704     int i, ret = 0;
705     const uint8_t *sizes[2];
706     uint8_t grouping[AAC_MAX_CHANNELS];
707     int lengths[2];
708
709     avctx->frame_size = 1024;
710
711     for (i = 0; i < 16; i++)
712         if (avctx->sample_rate == avpriv_mpeg4audio_sample_rates[i])
713             break;
714
715     s->channels = avctx->channels;
716
717     ERROR_IF(i == 16,
718              "Unsupported sample rate %d\n", avctx->sample_rate);
719     ERROR_IF(s->channels > AAC_MAX_CHANNELS,
720              "Unsupported number of channels: %d\n", s->channels);
721     ERROR_IF(avctx->profile != FF_PROFILE_UNKNOWN && avctx->profile != FF_PROFILE_AAC_LOW,
722              "Unsupported profile %d\n", avctx->profile);
723     ERROR_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels,
724              "Too many bits per frame requested\n");
725
726     s->samplerate_index = i;
727
728     s->chan_map = aac_chan_configs[s->channels-1];
729
730     if (ret = dsp_init(avctx, s))
731         goto fail;
732
733     if (ret = alloc_buffers(avctx, s))
734         goto fail;
735
736     avctx->extradata_size = 5;
737     put_audio_specific_config(avctx);
738
739     sizes[0]   = swb_size_1024[i];
740     sizes[1]   = swb_size_128[i];
741     lengths[0] = ff_aac_num_swb_1024[i];
742     lengths[1] = ff_aac_num_swb_128[i];
743     for (i = 0; i < s->chan_map[0]; i++)
744         grouping[i] = s->chan_map[i + 1] == TYPE_CPE;
745     if (ret = ff_psy_init(&s->psy, avctx, 2, sizes, lengths, s->chan_map[0], grouping))
746         goto fail;
747     s->psypp = ff_psy_preprocess_init(avctx);
748     s->coder = &ff_aac_coders[2];
749
750     s->lambda = avctx->global_quality ? avctx->global_quality : 120;
751
752     ff_aac_tableinit();
753
754     for (i = 0; i < 428; i++)
755         ff_aac_pow34sf_tab[i] = sqrt(ff_aac_pow2sf_tab[i] * sqrt(ff_aac_pow2sf_tab[i]));
756
757     return 0;
758 fail:
759     aac_encode_end(avctx);
760     return ret;
761 }
762
763 #define AACENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
764 static const AVOption aacenc_options[] = {
765     {"stereo_mode", "Stereo coding method", offsetof(AACEncContext, options.stereo_mode), AV_OPT_TYPE_INT, {.dbl = 0}, -1, 1, AACENC_FLAGS, "stereo_mode"},
766         {"auto",     "Selected by the Encoder", 0, AV_OPT_TYPE_CONST, {.dbl = -1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
767         {"ms_off",   "Disable Mid/Side coding", 0, AV_OPT_TYPE_CONST, {.dbl =  0 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
768         {"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"},
769     {NULL}
770 };
771
772 static const AVClass aacenc_class = {
773     "AAC encoder",
774     av_default_item_name,
775     aacenc_options,
776     LIBAVUTIL_VERSION_INT,
777 };
778
779 AVCodec ff_aac_encoder = {
780     .name           = "aac",
781     .type           = AVMEDIA_TYPE_AUDIO,
782     .id             = CODEC_ID_AAC,
783     .priv_data_size = sizeof(AACEncContext),
784     .init           = aac_encode_init,
785     .encode         = aac_encode_frame,
786     .close          = aac_encode_end,
787     .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
788     .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_FLT,AV_SAMPLE_FMT_NONE},
789     .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
790     .priv_class = &aacenc_class,
791 };