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