Statistics
| Branch: | Revision:

ffmpeg / libavcodec / aacpsy.c @ 4df5aebb

History | View | Annotate | Download (22.1 KB)

1
/*
2
 * AAC encoder psychoacoustic model
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 psychoacoustic model
25
 */
26

    
27
#include "avcodec.h"
28
#include "aactab.h"
29
#include "psymodel.h"
30

    
31
/***********************************
32
 *              TODOs:
33
 * thresholds linearization after their modifications for attaining given bitrate
34
 * try other bitrate controlling mechanism (maybe use ratecontrol.c?)
35
 * control quality for quality-based output
36
 **********************************/
37

    
38
/**
39
 * constants for 3GPP AAC psychoacoustic model
40
 * @{
41
 */
42
#define PSY_3GPP_SPREAD_LOW  1.5f // spreading factor for ascending threshold spreading  (15 dB/Bark)
43
#define PSY_3GPP_SPREAD_HI   3.0f // spreading factor for descending threshold spreading (30 dB/Bark)
44

    
45
#define PSY_3GPP_RPEMIN      0.01f
46
#define PSY_3GPP_RPELEV      2.0f
47

    
48
/* LAME psy model constants */
49
#define PSY_LAME_FIR_LEN 21         ///< LAME psy model FIR order
50
#define AAC_BLOCK_SIZE_LONG 1024    ///< long block size
51
#define AAC_BLOCK_SIZE_SHORT 128    ///< short block size
52
#define AAC_NUM_BLOCKS_SHORT 8      ///< number of blocks in a short sequence
53
#define PSY_LAME_NUM_SUBBLOCKS 3    ///< Number of sub-blocks in each short block
54

    
55
/**
56
 * @}
57
 */
58

    
59
/**
60
 * information for single band used by 3GPP TS26.403-inspired psychoacoustic model
61
 */
62
typedef struct AacPsyBand{
63
    float energy;    ///< band energy
64
    float ffac;      ///< form factor
65
    float thr;       ///< energy threshold
66
    float min_snr;   ///< minimal SNR
67
    float thr_quiet; ///< threshold in quiet
68
}AacPsyBand;
69

    
70
/**
71
 * single/pair channel context for psychoacoustic model
72
 */
73
typedef struct AacPsyChannel{
74
    AacPsyBand band[128];               ///< bands information
75
    AacPsyBand prev_band[128];          ///< bands information from the previous frame
76

    
77
    float       win_energy;              ///< sliding average of channel energy
78
    float       iir_state[2];            ///< hi-pass IIR filter state
79
    uint8_t     next_grouping;           ///< stored grouping scheme for the next frame (in case of 8 short window sequence)
80
    enum WindowSequence next_window_seq; ///< window sequence to be used in the next frame
81
    /* LAME psy model specific members */
82
    float attack_threshold;              ///< attack threshold for this channel
83
    float prev_energy_subshort[AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS];
84
    int   prev_attack;                   ///< attack value for the last short block in the previous sequence
85
}AacPsyChannel;
86

    
87
/**
88
 * psychoacoustic model frame type-dependent coefficients
89
 */
90
typedef struct AacPsyCoeffs{
91
    float ath       [64]; ///< absolute threshold of hearing per bands
92
    float barks     [64]; ///< Bark value for each spectral band in long frame
93
    float spread_low[64]; ///< spreading factor for low-to-high threshold spreading in long frame
94
    float spread_hi [64]; ///< spreading factor for high-to-low threshold spreading in long frame
95
}AacPsyCoeffs;
96

    
97
/**
98
 * 3GPP TS26.403-inspired psychoacoustic model specific data
99
 */
100
typedef struct AacPsyContext{
101
    AacPsyCoeffs psy_coef[2];
102
    AacPsyChannel *ch;
103
}AacPsyContext;
104

    
105
/**
106
 * LAME psy model preset struct
107
 */
108
typedef struct {
109
    int   quality;  ///< Quality to map the rest of the vaules to.
110
     /* This is overloaded to be both kbps per channel in ABR mode, and
111
      * requested quality in constant quality mode.
112
      */
113
    float st_lrm;   ///< short threshold for L, R, and M channels
114
} PsyLamePreset;
115

    
116
/**
117
 * LAME psy model preset table for ABR
118
 */
119
static const PsyLamePreset psy_abr_map[] = {
120
/* TODO: Tuning. These were taken from LAME. */
121
/* kbps/ch st_lrm   */
122
    {  8,  6.60},
123
    { 16,  6.60},
124
    { 24,  6.60},
125
    { 32,  6.60},
126
    { 40,  6.60},
127
    { 48,  6.60},
128
    { 56,  6.60},
129
    { 64,  6.40},
130
    { 80,  6.00},
131
    { 96,  5.60},
132
    {112,  5.20},
133
    {128,  5.20},
134
    {160,  5.20}
135
};
136

    
137
/**
138
* LAME psy model preset table for constant quality
139
*/
140
static const PsyLamePreset psy_vbr_map[] = {
141
/* vbr_q  st_lrm    */
142
    { 0,  4.20},
143
    { 1,  4.20},
144
    { 2,  4.20},
145
    { 3,  4.20},
146
    { 4,  4.20},
147
    { 5,  4.20},
148
    { 6,  4.20},
149
    { 7,  4.20},
150
    { 8,  4.20},
151
    { 9,  4.20},
152
    {10,  4.20}
153
};
154

    
155
/**
156
 * LAME psy model FIR coefficient table
157
 */
158
static const float psy_fir_coeffs[] = {
159
    -8.65163e-18 * 2, -0.00851586 * 2, -6.74764e-18 * 2, 0.0209036 * 2,
160
    -3.36639e-17 * 2, -0.0438162 * 2,  -1.54175e-17 * 2, 0.0931738 * 2,
161
    -5.52212e-17 * 2, -0.313819 * 2
162
};
163

    
164
/**
165
 * calculates the attack threshold for ABR from the above table for the LAME psy model
166
 */
167
static float lame_calc_attack_threshold(int bitrate)
168
{
169
    /* Assume max bitrate to start with */
170
    int lower_range = 12, upper_range = 12;
171
    int lower_range_kbps = psy_abr_map[12].quality;
172
    int upper_range_kbps = psy_abr_map[12].quality;
173
    int i;
174

    
175
    /* Determine which bitrates the value specified falls between.
176
     * If the loop ends without breaking our above assumption of 320kbps was correct.
177
     */
178
    for (i = 1; i < 13; i++) {
179
        if (FFMAX(bitrate, psy_abr_map[i].quality) != bitrate) {
180
            upper_range = i;
181
            upper_range_kbps = psy_abr_map[i    ].quality;
182
            lower_range = i - 1;
183
            lower_range_kbps = psy_abr_map[i - 1].quality;
184
            break; /* Upper range found */
185
        }
186
    }
187

    
188
    /* Determine which range the value specified is closer to */
189
    if ((upper_range_kbps - bitrate) > (bitrate - lower_range_kbps))
190
        return psy_abr_map[lower_range].st_lrm;
191
    return psy_abr_map[upper_range].st_lrm;
192
}
193

    
194
/**
195
 * LAME psy model specific initialization
196
 */
197
static void lame_window_init(AacPsyContext *ctx, AVCodecContext *avctx) {
198
    int i, j;
199

    
200
    for (i = 0; i < avctx->channels; i++) {
201
        AacPsyChannel *pch = &ctx->ch[i];
202

    
203
        if (avctx->flags & CODEC_FLAG_QSCALE)
204
            pch->attack_threshold = psy_vbr_map[avctx->global_quality / FF_QP2LAMBDA].st_lrm;
205
        else
206
            pch->attack_threshold = lame_calc_attack_threshold(avctx->bit_rate / avctx->channels / 1000);
207

    
208
        for (j = 0; j < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; j++)
209
            pch->prev_energy_subshort[j] = 10.0f;
210
    }
211
}
212

    
213
/**
214
 * Calculate Bark value for given line.
215
 */
216
static av_cold float calc_bark(float f)
217
{
218
    return 13.3f * atanf(0.00076f * f) + 3.5f * atanf((f / 7500.0f) * (f / 7500.0f));
219
}
220

    
221
#define ATH_ADD 4
222
/**
223
 * Calculate ATH value for given frequency.
224
 * Borrowed from Lame.
225
 */
226
static av_cold float ath(float f, float add)
227
{
228
    f /= 1000.0f;
229
    return    3.64 * pow(f, -0.8)
230
            - 6.8  * exp(-0.6  * (f - 3.4) * (f - 3.4))
231
            + 6.0  * exp(-0.15 * (f - 8.7) * (f - 8.7))
232
            + (0.6 + 0.04 * add) * 0.001 * f * f * f * f;
233
}
234

    
235
static av_cold int psy_3gpp_init(FFPsyContext *ctx) {
236
    AacPsyContext *pctx;
237
    float bark;
238
    int i, j, g, start;
239
    float prev, minscale, minath;
240

    
241
    ctx->model_priv_data = av_mallocz(sizeof(AacPsyContext));
242
    pctx = (AacPsyContext*) ctx->model_priv_data;
243

    
244
    minath = ath(3410, ATH_ADD);
245
    for (j = 0; j < 2; j++) {
246
        AacPsyCoeffs *coeffs = &pctx->psy_coef[j];
247
        float line_to_frequency = ctx->avctx->sample_rate / (j ? 256.f : 2048.0f);
248
        i = 0;
249
        prev = 0.0;
250
        for (g = 0; g < ctx->num_bands[j]; g++) {
251
            i += ctx->bands[j][g];
252
            bark = calc_bark((i-1) * line_to_frequency);
253
            coeffs->barks[g] = (bark + prev) / 2.0;
254
            prev = bark;
255
        }
256
        for (g = 0; g < ctx->num_bands[j] - 1; g++) {
257
            coeffs->spread_low[g] = pow(10.0, -(coeffs->barks[g+1] - coeffs->barks[g]) * PSY_3GPP_SPREAD_LOW);
258
            coeffs->spread_hi [g] = pow(10.0, -(coeffs->barks[g+1] - coeffs->barks[g]) * PSY_3GPP_SPREAD_HI);
259
        }
260
        start = 0;
261
        for (g = 0; g < ctx->num_bands[j]; g++) {
262
            minscale = ath(start * line_to_frequency, ATH_ADD);
263
            for (i = 1; i < ctx->bands[j][g]; i++)
264
                minscale = FFMIN(minscale, ath((start + i) * line_to_frequency, ATH_ADD));
265
            coeffs->ath[g] = minscale - minath;
266
            start += ctx->bands[j][g];
267
        }
268
    }
269

    
270
    pctx->ch = av_mallocz(sizeof(AacPsyChannel) * ctx->avctx->channels);
271

    
272
    lame_window_init(pctx, ctx->avctx);
273

    
274
    return 0;
275
}
276

    
277
/**
278
 * IIR filter used in block switching decision
279
 */
280
static float iir_filter(int in, float state[2])
281
{
282
    float ret;
283

    
284
    ret = 0.7548f * (in - state[0]) + 0.5095f * state[1];
285
    state[0] = in;
286
    state[1] = ret;
287
    return ret;
288
}
289

    
290
/**
291
 * window grouping information stored as bits (0 - new group, 1 - group continues)
292
 */
293
static const uint8_t window_grouping[9] = {
294
    0xB6, 0x6C, 0xD8, 0xB2, 0x66, 0xC6, 0x96, 0x36, 0x36
295
};
296

    
297
/**
298
 * Tell encoder which window types to use.
299
 * @see 3GPP TS26.403 5.4.1 "Blockswitching"
300
 */
301
static FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx,
302
                                       const int16_t *audio, const int16_t *la,
303
                                       int channel, int prev_type)
304
{
305
    int i, j;
306
    int br               = ctx->avctx->bit_rate / ctx->avctx->channels;
307
    int attack_ratio     = br <= 16000 ? 18 : 10;
308
    AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
309
    AacPsyChannel *pch  = &pctx->ch[channel];
310
    uint8_t grouping     = 0;
311
    int next_type        = pch->next_window_seq;
312
    FFPsyWindowInfo wi;
313

    
314
    memset(&wi, 0, sizeof(wi));
315
    if (la) {
316
        float s[8], v;
317
        int switch_to_eight = 0;
318
        float sum = 0.0, sum2 = 0.0;
319
        int attack_n = 0;
320
        int stay_short = 0;
321
        for (i = 0; i < 8; i++) {
322
            for (j = 0; j < 128; j++) {
323
                v = iir_filter(la[(i*128+j)*ctx->avctx->channels], pch->iir_state);
324
                sum += v*v;
325
            }
326
            s[i]  = sum;
327
            sum2 += sum;
328
        }
329
        for (i = 0; i < 8; i++) {
330
            if (s[i] > pch->win_energy * attack_ratio) {
331
                attack_n        = i + 1;
332
                switch_to_eight = 1;
333
                break;
334
            }
335
        }
336
        pch->win_energy = pch->win_energy*7/8 + sum2/64;
337

    
338
        wi.window_type[1] = prev_type;
339
        switch (prev_type) {
340
        case ONLY_LONG_SEQUENCE:
341
            wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;
342
            next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : ONLY_LONG_SEQUENCE;
343
            break;
344
        case LONG_START_SEQUENCE:
345
            wi.window_type[0] = EIGHT_SHORT_SEQUENCE;
346
            grouping = pch->next_grouping;
347
            next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
348
            break;
349
        case LONG_STOP_SEQUENCE:
350
            wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;
351
            next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : ONLY_LONG_SEQUENCE;
352
            break;
353
        case EIGHT_SHORT_SEQUENCE:
354
            stay_short = next_type == EIGHT_SHORT_SEQUENCE || switch_to_eight;
355
            wi.window_type[0] = stay_short ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
356
            grouping = next_type == EIGHT_SHORT_SEQUENCE ? pch->next_grouping : 0;
357
            next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
358
            break;
359
        }
360

    
361
        pch->next_grouping = window_grouping[attack_n];
362
        pch->next_window_seq = next_type;
363
    } else {
364
        for (i = 0; i < 3; i++)
365
            wi.window_type[i] = prev_type;
366
        grouping = (prev_type == EIGHT_SHORT_SEQUENCE) ? window_grouping[0] : 0;
367
    }
368

    
369
    wi.window_shape   = 1;
370
    if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {
371
        wi.num_windows = 1;
372
        wi.grouping[0] = 1;
373
    } else {
374
        int lastgrp = 0;
375
        wi.num_windows = 8;
376
        for (i = 0; i < 8; i++) {
377
            if (!((grouping >> i) & 1))
378
                lastgrp = i;
379
            wi.grouping[lastgrp]++;
380
        }
381
    }
382

    
383
    return wi;
384
}
385

    
386
/**
387
 * Calculate band thresholds as suggested in 3GPP TS26.403
388
 */
389
static void psy_3gpp_analyze(FFPsyContext *ctx, int channel,
390
                             const float *coefs, const FFPsyWindowInfo *wi)
391
{
392
    AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
393
    AacPsyChannel *pch  = &pctx->ch[channel];
394
    int start = 0;
395
    int i, w, g;
396
    const int num_bands       = ctx->num_bands[wi->num_windows == 8];
397
    const uint8_t* band_sizes = ctx->bands[wi->num_windows == 8];
398
    AacPsyCoeffs *coeffs     = &pctx->psy_coef[wi->num_windows == 8];
399

    
400
    //calculate energies, initial thresholds and related values - 5.4.2 "Threshold Calculation"
401
    for (w = 0; w < wi->num_windows*16; w += 16) {
402
        for (g = 0; g < num_bands; g++) {
403
            AacPsyBand *band = &pch->band[w+g];
404
            band->energy = 0.0f;
405
            for (i = 0; i < band_sizes[g]; i++)
406
                band->energy += coefs[start+i] * coefs[start+i];
407
            band->energy *= 1.0f / (512*512);
408
            band->thr     = band->energy * 0.001258925f;
409
            start        += band_sizes[g];
410

    
411
            ctx->psy_bands[channel*PSY_MAX_BANDS+w+g].energy = band->energy;
412
        }
413
    }
414
    //modify thresholds - spread, threshold in quiet - 5.4.3 "Spreaded Energy Calculation"
415
    for (w = 0; w < wi->num_windows*16; w += 16) {
416
        AacPsyBand *band = &pch->band[w];
417
        for (g = 1; g < num_bands; g++)
418
            band[g].thr = FFMAX(band[g].thr, band[g-1].thr * coeffs->spread_low[g-1]);
419
        for (g = num_bands - 2; g >= 0; g--)
420
            band[g].thr = FFMAX(band[g].thr, band[g+1].thr * coeffs->spread_hi [g]);
421
        for (g = 0; g < num_bands; g++) {
422
            band[g].thr_quiet = band[g].thr = FFMAX(band[g].thr, coeffs->ath[g]);
423
            if (!(wi->window_type[0] == LONG_STOP_SEQUENCE || (wi->window_type[1] == LONG_START_SEQUENCE && !w)))
424
                band[g].thr = FFMAX(PSY_3GPP_RPEMIN*band[g].thr, FFMIN(band[g].thr,
425
                                    PSY_3GPP_RPELEV*pch->prev_band[w+g].thr_quiet));
426

    
427
            ctx->psy_bands[channel*PSY_MAX_BANDS+w+g].threshold = band[g].thr;
428
        }
429
    }
430
    memcpy(pch->prev_band, pch->band, sizeof(pch->band));
431
}
432

    
433
static av_cold void psy_3gpp_end(FFPsyContext *apc)
434
{
435
    AacPsyContext *pctx = (AacPsyContext*) apc->model_priv_data;
436
    av_freep(&pctx->ch);
437
    av_freep(&apc->model_priv_data);
438
}
439

    
440
static void lame_apply_block_type(AacPsyChannel *ctx, FFPsyWindowInfo *wi, int uselongblock)
441
{
442
    int blocktype = ONLY_LONG_SEQUENCE;
443
    if (uselongblock) {
444
        if (ctx->next_window_seq == EIGHT_SHORT_SEQUENCE)
445
            blocktype = LONG_STOP_SEQUENCE;
446
    } else {
447
        blocktype = EIGHT_SHORT_SEQUENCE;
448
        if (ctx->next_window_seq == ONLY_LONG_SEQUENCE)
449
            ctx->next_window_seq = LONG_START_SEQUENCE;
450
        if (ctx->next_window_seq == LONG_STOP_SEQUENCE)
451
            ctx->next_window_seq = EIGHT_SHORT_SEQUENCE;
452
    }
453

    
454
    wi->window_type[0] = ctx->next_window_seq;
455
    ctx->next_window_seq = blocktype;
456
}
457

    
458
static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx,
459
                                       const int16_t *audio, const int16_t *la,
460
                                       int channel, int prev_type)
461
{
462
    AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
463
    AacPsyChannel *pch  = &pctx->ch[channel];
464
    int grouping     = 0;
465
    int uselongblock = 1;
466
    int attacks[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
467
    int i;
468
    FFPsyWindowInfo wi;
469

    
470
    memset(&wi, 0, sizeof(wi));
471
    if (la) {
472
        float hpfsmpl[AAC_BLOCK_SIZE_LONG];
473
        float const *pf = hpfsmpl;
474
        float attack_intensity[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];
475
        float energy_subshort[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];
476
        float energy_short[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
477
        int chans = ctx->avctx->channels;
478
        const int16_t *firbuf = la + (AAC_BLOCK_SIZE_SHORT/4 - PSY_LAME_FIR_LEN) * chans;
479
        int j, att_sum = 0;
480

    
481
        /* LAME comment: apply high pass filter of fs/4 */
482
        for (i = 0; i < AAC_BLOCK_SIZE_LONG; i++) {
483
            float sum1, sum2;
484
            sum1 = firbuf[(i + ((PSY_LAME_FIR_LEN - 1) / 2)) * chans];
485
            sum2 = 0.0;
486
            for (j = 0; j < ((PSY_LAME_FIR_LEN - 1) / 2) - 1; j += 2) {
487
                sum1 += psy_fir_coeffs[j] * (firbuf[(i + j) * chans] + firbuf[(i + PSY_LAME_FIR_LEN - j) * chans]);
488
                sum2 += psy_fir_coeffs[j + 1] * (firbuf[(i + j + 1) * chans] + firbuf[(i + PSY_LAME_FIR_LEN - j - 1) * chans]);
489
            }
490
            hpfsmpl[i] = sum1 + sum2;
491
        }
492

    
493
        /* Calculate the energies of each sub-shortblock */
494
        for (i = 0; i < PSY_LAME_NUM_SUBBLOCKS; i++) {
495
            energy_subshort[i] = pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 1) * PSY_LAME_NUM_SUBBLOCKS)];
496
            assert(pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 2) * PSY_LAME_NUM_SUBBLOCKS + 1)] > 0);
497
            attack_intensity[i] = energy_subshort[i] / pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 2) * PSY_LAME_NUM_SUBBLOCKS + 1)];
498
            energy_short[0] += energy_subshort[i];
499
        }
500

    
501
        for (i = 0; i < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; i++) {
502
            float const *const pfe = pf + AAC_BLOCK_SIZE_LONG / (AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS);
503
            float p = 1.0f;
504
            for (; pf < pfe; pf++)
505
                if (p < fabsf(*pf))
506
                    p = fabsf(*pf);
507
            pch->prev_energy_subshort[i] = energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS] = p;
508
            energy_short[1 + i / PSY_LAME_NUM_SUBBLOCKS] += p;
509
            /* FIXME: The indexes below are [i + 3 - 2] in the LAME source.
510
             *          Obviously the 3 and 2 have some significance, or this would be just [i + 1]
511
             *          (which is what we use here). What the 3 stands for is ambigious, as it is both
512
             *          number of short blocks, and the number of sub-short blocks.
513
             *          It seems that LAME is comparing each sub-block to sub-block + 1 in the
514
             *          previous block.
515
             */
516
            if (p > energy_subshort[i + 1])
517
                p = p / energy_subshort[i + 1];
518
            else if (energy_subshort[i + 1] > p * 10.0f)
519
                p = energy_subshort[i + 1] / (p * 10.0f);
520
            else
521
                p = 0.0;
522
            attack_intensity[i + PSY_LAME_NUM_SUBBLOCKS] = p;
523
        }
524

    
525
        /* compare energy between sub-short blocks */
526
        for (i = 0; i < (AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS; i++)
527
            if (!attacks[i / PSY_LAME_NUM_SUBBLOCKS])
528
                if (attack_intensity[i] > pch->attack_threshold)
529
                    attacks[i / PSY_LAME_NUM_SUBBLOCKS] = (i % PSY_LAME_NUM_SUBBLOCKS) + 1;
530

    
531
        /* should have energy change between short blocks, in order to avoid periodic signals */
532
        /* Good samples to show the effect are Trumpet test songs */
533
        /* GB: tuned (1) to avoid too many short blocks for test sample TRUMPET */
534
        /* RH: tuned (2) to let enough short blocks through for test sample FSOL and SNAPS */
535
        for (i = 1; i < AAC_NUM_BLOCKS_SHORT + 1; i++) {
536
            float const u = energy_short[i - 1];
537
            float const v = energy_short[i];
538
            float const m = FFMAX(u, v);
539
            if (m < 40000) {                          /* (2) */
540
                if (u < 1.7f * v && v < 1.7f * u) {   /* (1) */
541
                    if (i == 1 && attacks[0] < attacks[i])
542
                        attacks[0] = 0;
543
                    attacks[i] = 0;
544
                }
545
            }
546
            att_sum += attacks[i];
547
        }
548

    
549
        if (attacks[0] <= pch->prev_attack)
550
            attacks[0] = 0;
551

    
552
        att_sum += attacks[0];
553
        /* 3 below indicates the previous attack happened in the last sub-block of the previous sequence */
554
        if (pch->prev_attack == 3 || att_sum) {
555
            uselongblock = 0;
556

    
557
            if (attacks[1] && attacks[0])
558
                attacks[1] = 0;
559
            if (attacks[2] && attacks[1])
560
                attacks[2] = 0;
561
            if (attacks[3] && attacks[2])
562
                attacks[3] = 0;
563
            if (attacks[4] && attacks[3])
564
                attacks[4] = 0;
565
            if (attacks[5] && attacks[4])
566
                attacks[5] = 0;
567
            if (attacks[6] && attacks[5])
568
                attacks[6] = 0;
569
            if (attacks[7] && attacks[6])
570
                attacks[7] = 0;
571
            if (attacks[8] && attacks[7])
572
                attacks[8] = 0;
573
        }
574
    } else {
575
        /* We have no lookahead info, so just use same type as the previous sequence. */
576
        uselongblock = !(prev_type == EIGHT_SHORT_SEQUENCE);
577
    }
578

    
579
    lame_apply_block_type(pch, &wi, uselongblock);
580

    
581
    wi.window_type[1] = prev_type;
582
    if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {
583
        wi.num_windows  = 1;
584
        wi.grouping[0]  = 1;
585
        if (wi.window_type[0] == LONG_START_SEQUENCE)
586
            wi.window_shape = 0;
587
        else
588
            wi.window_shape = 1;
589
    } else {
590
        int lastgrp = 0;
591

    
592
        wi.num_windows = 8;
593
        wi.window_shape = 0;
594
        for (i = 0; i < 8; i++) {
595
            if (!((pch->next_grouping >> i) & 1))
596
                lastgrp = i;
597
            wi.grouping[lastgrp]++;
598
        }
599
    }
600

    
601
    /* Determine grouping, based on the location of the first attack, and save for
602
     * the next frame.
603
     * FIXME: Move this to analysis.
604
     * TODO: Tune groupings depending on attack location
605
     * TODO: Handle more than one attack in a group
606
     */
607
    for (i = 0; i < 9; i++) {
608
        if (attacks[i]) {
609
            grouping = i;
610
            break;
611
        }
612
    }
613
    pch->next_grouping = window_grouping[grouping];
614

    
615
    pch->prev_attack = attacks[8];
616

    
617
    return wi;
618
}
619

    
620
const FFPsyModel ff_aac_psy_model =
621
{
622
    .name    = "3GPP TS 26.403-inspired model",
623
    .init    = psy_3gpp_init,
624
    .window  = psy_lame_window,
625
    .analyze = psy_3gpp_analyze,
626
    .end     = psy_3gpp_end,
627
};