Merge commit '4958f35a2ebc307049ff2104ffb944f5f457feb3'
[ffmpeg.git] / libavcodec / ac3enc_template.c
1 /*
2  * AC-3 encoder float/fixed template
3  * Copyright (c) 2000 Fabrice Bellard
4  * Copyright (c) 2006-2011 Justin Ruggles <justin.ruggles@gmail.com>
5  * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 /**
25  * @file
26  * AC-3 encoder float/fixed template
27  */
28
29 #include <stdint.h>
30
31 #include "libavutil/internal.h"
32
33 /* prototypes for static functions in ac3enc_fixed.c and ac3enc_float.c */
34
35 static void scale_coefficients(AC3EncodeContext *s);
36
37 static int normalize_samples(AC3EncodeContext *s);
38
39 static void clip_coefficients(DSPContext *dsp, CoefType *coef, unsigned int len);
40
41 static CoefType calc_cpl_coord(CoefSumType energy_ch, CoefSumType energy_cpl);
42
43 static void sum_square_butterfly(AC3EncodeContext *s, CoefSumType sum[4],
44                                  const CoefType *coef0, const CoefType *coef1,
45                                  int len);
46
47 int AC3_NAME(allocate_sample_buffers)(AC3EncodeContext *s)
48 {
49     int ch;
50
51     FF_ALLOC_OR_GOTO(s->avctx, s->windowed_samples, AC3_WINDOW_SIZE *
52                      sizeof(*s->windowed_samples), alloc_fail);
53     FF_ALLOC_OR_GOTO(s->avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
54                      alloc_fail);
55     for (ch = 0; ch < s->channels; ch++) {
56         FF_ALLOCZ_OR_GOTO(s->avctx, s->planar_samples[ch],
57                           (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
58                           alloc_fail);
59     }
60
61     return 0;
62 alloc_fail:
63     return AVERROR(ENOMEM);
64 }
65
66
67 /*
68  * Copy input samples.
69  * Channels are reordered from FFmpeg's default order to AC-3 order.
70  */
71 static void copy_input_samples(AC3EncodeContext *s, SampleType **samples)
72 {
73     int ch;
74
75     /* copy and remap input samples */
76     for (ch = 0; ch < s->channels; ch++) {
77         /* copy last 256 samples of previous frame to the start of the current frame */
78         memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_BLOCK_SIZE * s->num_blocks],
79                AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
80
81         /* copy new samples for current frame */
82         memcpy(&s->planar_samples[ch][AC3_BLOCK_SIZE],
83                samples[s->channel_map[ch]],
84                AC3_BLOCK_SIZE * s->num_blocks * sizeof(s->planar_samples[0][0]));
85     }
86 }
87
88
89 /*
90  * Apply the MDCT to input samples to generate frequency coefficients.
91  * This applies the KBD window and normalizes the input to reduce precision
92  * loss due to fixed-point calculations.
93  */
94 static void apply_mdct(AC3EncodeContext *s)
95 {
96     int blk, ch;
97
98     for (ch = 0; ch < s->channels; ch++) {
99         for (blk = 0; blk < s->num_blocks; blk++) {
100             AC3Block *block = &s->blocks[blk];
101             const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
102
103 #if CONFIG_AC3ENC_FLOAT
104             s->fdsp.vector_fmul(s->windowed_samples, input_samples,
105                                 s->mdct_window, AC3_WINDOW_SIZE);
106 #else
107             s->ac3dsp.apply_window_int16(s->windowed_samples, input_samples,
108                                          s->mdct_window, AC3_WINDOW_SIZE);
109 #endif
110
111             if (s->fixed_point)
112                 block->coeff_shift[ch+1] = normalize_samples(s);
113
114             s->mdct.mdct_calcw(&s->mdct, block->mdct_coef[ch+1],
115                                s->windowed_samples);
116         }
117     }
118 }
119
120
121 /*
122  * Calculate coupling channel and coupling coordinates.
123  */
124 static void apply_channel_coupling(AC3EncodeContext *s)
125 {
126     LOCAL_ALIGNED_16(CoefType, cpl_coords,      [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]);
127 #if CONFIG_AC3ENC_FLOAT
128     LOCAL_ALIGNED_16(int32_t, fixed_cpl_coords, [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]);
129 #else
130     int32_t (*fixed_cpl_coords)[AC3_MAX_CHANNELS][16] = cpl_coords;
131 #endif
132     int av_uninit(blk), ch, bnd, i, j;
133     CoefSumType energy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
134     int cpl_start, num_cpl_coefs;
135
136     memset(cpl_coords,       0, AC3_MAX_BLOCKS * sizeof(*cpl_coords));
137 #if CONFIG_AC3ENC_FLOAT
138     memset(fixed_cpl_coords, 0, AC3_MAX_BLOCKS * sizeof(*cpl_coords));
139 #endif
140
141     /* align start to 16-byte boundary. align length to multiple of 32.
142         note: coupling start bin % 4 will always be 1 */
143     cpl_start     = s->start_freq[CPL_CH] - 1;
144     num_cpl_coefs = FFALIGN(s->num_cpl_subbands * 12 + 1, 32);
145     cpl_start     = FFMIN(256, cpl_start + num_cpl_coefs) - num_cpl_coefs;
146
147     /* calculate coupling channel from fbw channels */
148     for (blk = 0; blk < s->num_blocks; blk++) {
149         AC3Block *block = &s->blocks[blk];
150         CoefType *cpl_coef = &block->mdct_coef[CPL_CH][cpl_start];
151         if (!block->cpl_in_use)
152             continue;
153         memset(cpl_coef, 0, num_cpl_coefs * sizeof(*cpl_coef));
154         for (ch = 1; ch <= s->fbw_channels; ch++) {
155             CoefType *ch_coef = &block->mdct_coef[ch][cpl_start];
156             if (!block->channel_in_cpl[ch])
157                 continue;
158             for (i = 0; i < num_cpl_coefs; i++)
159                 cpl_coef[i] += ch_coef[i];
160         }
161
162         /* coefficients must be clipped in order to be encoded */
163         clip_coefficients(&s->dsp, cpl_coef, num_cpl_coefs);
164     }
165
166     /* calculate energy in each band in coupling channel and each fbw channel */
167     /* TODO: possibly use SIMD to speed up energy calculation */
168     bnd = 0;
169     i = s->start_freq[CPL_CH];
170     while (i < s->cpl_end_freq) {
171         int band_size = s->cpl_band_sizes[bnd];
172         for (ch = CPL_CH; ch <= s->fbw_channels; ch++) {
173             for (blk = 0; blk < s->num_blocks; blk++) {
174                 AC3Block *block = &s->blocks[blk];
175                 if (!block->cpl_in_use || (ch > CPL_CH && !block->channel_in_cpl[ch]))
176                     continue;
177                 for (j = 0; j < band_size; j++) {
178                     CoefType v = block->mdct_coef[ch][i+j];
179                     MAC_COEF(energy[blk][ch][bnd], v, v);
180                 }
181             }
182         }
183         i += band_size;
184         bnd++;
185     }
186
187     /* calculate coupling coordinates for all blocks for all channels */
188     for (blk = 0; blk < s->num_blocks; blk++) {
189         AC3Block *block  = &s->blocks[blk];
190         if (!block->cpl_in_use)
191             continue;
192         for (ch = 1; ch <= s->fbw_channels; ch++) {
193             if (!block->channel_in_cpl[ch])
194                 continue;
195             for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
196                 cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy[blk][ch][bnd],
197                                                           energy[blk][CPL_CH][bnd]);
198             }
199         }
200     }
201
202     /* determine which blocks to send new coupling coordinates for */
203     for (blk = 0; blk < s->num_blocks; blk++) {
204         AC3Block *block  = &s->blocks[blk];
205         AC3Block *block0 = blk ? &s->blocks[blk-1] : NULL;
206
207         memset(block->new_cpl_coords, 0, sizeof(block->new_cpl_coords));
208
209         if (block->cpl_in_use) {
210             /* send new coordinates if this is the first block, if previous
211              * block did not use coupling but this block does, the channels
212              * using coupling has changed from the previous block, or the
213              * coordinate difference from the last block for any channel is
214              * greater than a threshold value. */
215             if (blk == 0 || !block0->cpl_in_use) {
216                 for (ch = 1; ch <= s->fbw_channels; ch++)
217                     block->new_cpl_coords[ch] = 1;
218             } else {
219                 for (ch = 1; ch <= s->fbw_channels; ch++) {
220                     if (!block->channel_in_cpl[ch])
221                         continue;
222                     if (!block0->channel_in_cpl[ch]) {
223                         block->new_cpl_coords[ch] = 1;
224                     } else {
225                         CoefSumType coord_diff = 0;
226                         for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
227                             coord_diff += FFABS(cpl_coords[blk-1][ch][bnd] -
228                                                 cpl_coords[blk  ][ch][bnd]);
229                         }
230                         coord_diff /= s->num_cpl_bands;
231                         if (coord_diff > NEW_CPL_COORD_THRESHOLD)
232                             block->new_cpl_coords[ch] = 1;
233                     }
234                 }
235             }
236         }
237     }
238
239     /* calculate final coupling coordinates, taking into account reusing of
240        coordinates in successive blocks */
241     for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
242         blk = 0;
243         while (blk < s->num_blocks) {
244             int av_uninit(blk1);
245             AC3Block *block  = &s->blocks[blk];
246
247             if (!block->cpl_in_use) {
248                 blk++;
249                 continue;
250             }
251
252             for (ch = 1; ch <= s->fbw_channels; ch++) {
253                 CoefSumType energy_ch, energy_cpl;
254                 if (!block->channel_in_cpl[ch])
255                     continue;
256                 energy_cpl = energy[blk][CPL_CH][bnd];
257                 energy_ch = energy[blk][ch][bnd];
258                 blk1 = blk+1;
259                 while (!s->blocks[blk1].new_cpl_coords[ch] && blk1 < s->num_blocks) {
260                     if (s->blocks[blk1].cpl_in_use) {
261                         energy_cpl += energy[blk1][CPL_CH][bnd];
262                         energy_ch += energy[blk1][ch][bnd];
263                     }
264                     blk1++;
265                 }
266                 cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy_ch, energy_cpl);
267             }
268             blk = blk1;
269         }
270     }
271
272     /* calculate exponents/mantissas for coupling coordinates */
273     for (blk = 0; blk < s->num_blocks; blk++) {
274         AC3Block *block = &s->blocks[blk];
275         if (!block->cpl_in_use)
276             continue;
277
278 #if CONFIG_AC3ENC_FLOAT
279         s->ac3dsp.float_to_fixed24(fixed_cpl_coords[blk][1],
280                                    cpl_coords[blk][1],
281                                    s->fbw_channels * 16);
282 #endif
283         s->ac3dsp.extract_exponents(block->cpl_coord_exp[1],
284                                     fixed_cpl_coords[blk][1],
285                                     s->fbw_channels * 16);
286
287         for (ch = 1; ch <= s->fbw_channels; ch++) {
288             int bnd, min_exp, max_exp, master_exp;
289
290             if (!block->new_cpl_coords[ch])
291                 continue;
292
293             /* determine master exponent */
294             min_exp = max_exp = block->cpl_coord_exp[ch][0];
295             for (bnd = 1; bnd < s->num_cpl_bands; bnd++) {
296                 int exp = block->cpl_coord_exp[ch][bnd];
297                 min_exp = FFMIN(exp, min_exp);
298                 max_exp = FFMAX(exp, max_exp);
299             }
300             master_exp = ((max_exp - 15) + 2) / 3;
301             master_exp = FFMAX(master_exp, 0);
302             while (min_exp < master_exp * 3)
303                 master_exp--;
304             for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
305                 block->cpl_coord_exp[ch][bnd] = av_clip(block->cpl_coord_exp[ch][bnd] -
306                                                         master_exp * 3, 0, 15);
307             }
308             block->cpl_master_exp[ch] = master_exp;
309
310             /* quantize mantissas */
311             for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
312                 int cpl_exp  = block->cpl_coord_exp[ch][bnd];
313                 int cpl_mant = (fixed_cpl_coords[blk][ch][bnd] << (5 + cpl_exp + master_exp * 3)) >> 24;
314                 if (cpl_exp == 15)
315                     cpl_mant >>= 1;
316                 else
317                     cpl_mant -= 16;
318
319                 block->cpl_coord_mant[ch][bnd] = cpl_mant;
320             }
321         }
322     }
323
324     if (CONFIG_EAC3_ENCODER && s->eac3)
325         ff_eac3_set_cpl_states(s);
326 }
327
328
329 /*
330  * Determine rematrixing flags for each block and band.
331  */
332 static void compute_rematrixing_strategy(AC3EncodeContext *s)
333 {
334     int nb_coefs;
335     int blk, bnd;
336     AC3Block *block, *block0 = NULL;
337
338     if (s->channel_mode != AC3_CHMODE_STEREO)
339         return;
340
341     for (blk = 0; blk < s->num_blocks; blk++) {
342         block = &s->blocks[blk];
343         block->new_rematrixing_strategy = !blk;
344
345         block->num_rematrixing_bands = 4;
346         if (block->cpl_in_use) {
347             block->num_rematrixing_bands -= (s->start_freq[CPL_CH] <= 61);
348             block->num_rematrixing_bands -= (s->start_freq[CPL_CH] == 37);
349             if (blk && block->num_rematrixing_bands != block0->num_rematrixing_bands)
350                 block->new_rematrixing_strategy = 1;
351         }
352         nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
353
354         if (!s->rematrixing_enabled) {
355             block0 = block;
356             continue;
357         }
358
359         for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
360             /* calculate sum of squared coeffs for one band in one block */
361             int start = ff_ac3_rematrix_band_tab[bnd];
362             int end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
363             CoefSumType sum[4];
364             sum_square_butterfly(s, sum, block->mdct_coef[1] + start,
365                                  block->mdct_coef[2] + start, end - start);
366
367             /* compare sums to determine if rematrixing will be used for this band */
368             if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
369                 block->rematrixing_flags[bnd] = 1;
370             else
371                 block->rematrixing_flags[bnd] = 0;
372
373             /* determine if new rematrixing flags will be sent */
374             if (blk &&
375                 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
376                 block->new_rematrixing_strategy = 1;
377             }
378         }
379         block0 = block;
380     }
381 }
382
383
384 int AC3_NAME(encode_frame)(AVCodecContext *avctx, AVPacket *avpkt,
385                            const AVFrame *frame, int *got_packet_ptr)
386 {
387     AC3EncodeContext *s = avctx->priv_data;
388     int ret;
389
390     if (s->options.allow_per_frame_metadata) {
391         ret = ff_ac3_validate_metadata(s);
392         if (ret)
393             return ret;
394     }
395
396     if (s->bit_alloc.sr_code == 1 || s->eac3)
397         ff_ac3_adjust_frame_size(s);
398
399     copy_input_samples(s, (SampleType **)frame->extended_data);
400
401     apply_mdct(s);
402
403     if (s->fixed_point)
404         scale_coefficients(s);
405
406     clip_coefficients(&s->dsp, s->blocks[0].mdct_coef[1],
407                       AC3_MAX_COEFS * s->num_blocks * s->channels);
408
409     s->cpl_on = s->cpl_enabled;
410     ff_ac3_compute_coupling_strategy(s);
411
412     if (s->cpl_on)
413         apply_channel_coupling(s);
414
415     compute_rematrixing_strategy(s);
416
417     if (!s->fixed_point)
418         scale_coefficients(s);
419
420     ff_ac3_apply_rematrixing(s);
421
422     ff_ac3_process_exponents(s);
423
424     ret = ff_ac3_compute_bit_allocation(s);
425     if (ret) {
426         av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
427         return ret;
428     }
429
430     ff_ac3_group_exponents(s);
431
432     ff_ac3_quantize_mantissas(s);
433
434     if ((ret = ff_alloc_packet2(avctx, avpkt, s->frame_size)) < 0)
435         return ret;
436     ff_ac3_output_frame(s, avpkt->data);
437
438     if (frame->pts != AV_NOPTS_VALUE)
439         avpkt->pts = frame->pts - ff_samples_to_time_base(avctx, avctx->delay);
440
441     *got_packet_ptr = 1;
442     return 0;
443 }