Statistics
| Branch: | Revision:

ffmpeg / libavcodec / aacpsy.c @ 2912e87a

History | View | Annotate | Download (22 KB)

1
/*
2
 * AAC encoder psychoacoustic model
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 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_THR_SPREAD_HI   1.5f // spreading factor for low-to-hi threshold spreading  (15 dB/Bark)
43
#define PSY_3GPP_THR_SPREAD_LOW  3.0f // spreading factor for hi-to-low 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 thr;       ///< energy threshold
65
    float thr_quiet; ///< threshold in quiet
66
}AacPsyBand;
67

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
243
    minath = ath(3410, ATH_ADD);
244
    for (j = 0; j < 2; j++) {
245
        AacPsyCoeffs *coeffs = pctx->psy_coef[j];
246
        const uint8_t *band_sizes = ctx->bands[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 += band_sizes[g];
252
            bark = calc_bark((i-1) * line_to_frequency);
253
            coeffs[g].barks = (bark + prev) / 2.0;
254
            prev = bark;
255
        }
256
        for (g = 0; g < ctx->num_bands[j] - 1; g++) {
257
            AacPsyCoeffs *coeff = &coeffs[g];
258
            float bark_width = coeffs[g+1].barks - coeffs->barks;
259
            coeff->spread_low[0] = pow(10.0, -bark_width * PSY_3GPP_THR_SPREAD_LOW);
260
            coeff->spread_hi [0] = pow(10.0, -bark_width * PSY_3GPP_THR_SPREAD_HI);
261
        }
262
        start = 0;
263
        for (g = 0; g < ctx->num_bands[j]; g++) {
264
            minscale = ath(start * line_to_frequency, ATH_ADD);
265
            for (i = 1; i < band_sizes[g]; i++)
266
                minscale = FFMIN(minscale, ath((start + i) * line_to_frequency, ATH_ADD));
267
            coeffs[g].ath = minscale - minath;
268
            start += band_sizes[g];
269
        }
270
    }
271

    
272
    pctx->ch = av_mallocz(sizeof(AacPsyChannel) * ctx->avctx->channels);
273

    
274
    lame_window_init(pctx, ctx->avctx);
275

    
276
    return 0;
277
}
278

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

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

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

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

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

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

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

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

    
385
    return wi;
386
}
387

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

    
402
    //calculate energies, initial thresholds and related values - 5.4.2 "Threshold Calculation"
403
    for (w = 0; w < wi->num_windows*16; w += 16) {
404
        for (g = 0; g < num_bands; g++) {
405
            AacPsyBand *band = &pch->band[w+g];
406
            band->energy = 0.0f;
407
            for (i = 0; i < band_sizes[g]; i++)
408
                band->energy += coefs[start+i] * coefs[start+i];
409
            band->thr     = band->energy * 0.001258925f;
410
            start        += band_sizes[g];
411
        }
412
    }
413
    //modify thresholds and energies - spread, threshold in quiet, pre-echo control
414
    for (w = 0; w < wi->num_windows*16; w += 16) {
415
        AacPsyBand *bands = &pch->band[w];
416
        //5.4.2.3 "Spreading" & 5.4.3 "Spreaded Energy Calculation"
417
        for (g = 1; g < num_bands; g++)
418
            bands[g].thr = FFMAX(bands[g].thr, bands[g-1].thr * coeffs[g].spread_hi[0]);
419
        for (g = num_bands - 2; g >= 0; g--)
420
            bands[g].thr = FFMAX(bands[g].thr, bands[g+1].thr * coeffs[g].spread_low[0]);
421
        //5.4.2.4 "Threshold in quiet"
422
        for (g = 0; g < num_bands; g++) {
423
            AacPsyBand *band = &bands[g];
424
            band->thr_quiet = band->thr = FFMAX(band->thr, coeffs[g].ath);
425
            //5.4.2.5 "Pre-echo control"
426
            if (!(wi->window_type[0] == LONG_STOP_SEQUENCE || (wi->window_type[1] == LONG_START_SEQUENCE && !w)))
427
                band->thr = FFMAX(PSY_3GPP_RPEMIN*band->thr, FFMIN(band->thr,
428
                                  PSY_3GPP_RPELEV*pch->prev_band[w+g].thr_quiet));
429
        }
430
    }
431

    
432
    for (w = 0; w < wi->num_windows*16; w += 16) {
433
        for (g = 0; g < num_bands; g++) {
434
            AacPsyBand *band     = &pch->band[w+g];
435
            FFPsyBand  *psy_band = &ctx->psy_bands[channel*PSY_MAX_BANDS+w+g];
436

    
437
            psy_band->threshold = band->thr;
438
            psy_band->energy    = band->energy;
439
        }
440
    }
441

    
442
    memcpy(pch->prev_band, pch->band, sizeof(pch->band));
443
}
444

    
445
static av_cold void psy_3gpp_end(FFPsyContext *apc)
446
{
447
    AacPsyContext *pctx = (AacPsyContext*) apc->model_priv_data;
448
    av_freep(&pctx->ch);
449
    av_freep(&apc->model_priv_data);
450
}
451

    
452
static void lame_apply_block_type(AacPsyChannel *ctx, FFPsyWindowInfo *wi, int uselongblock)
453
{
454
    int blocktype = ONLY_LONG_SEQUENCE;
455
    if (uselongblock) {
456
        if (ctx->next_window_seq == EIGHT_SHORT_SEQUENCE)
457
            blocktype = LONG_STOP_SEQUENCE;
458
    } else {
459
        blocktype = EIGHT_SHORT_SEQUENCE;
460
        if (ctx->next_window_seq == ONLY_LONG_SEQUENCE)
461
            ctx->next_window_seq = LONG_START_SEQUENCE;
462
        if (ctx->next_window_seq == LONG_STOP_SEQUENCE)
463
            ctx->next_window_seq = EIGHT_SHORT_SEQUENCE;
464
    }
465

    
466
    wi->window_type[0] = ctx->next_window_seq;
467
    ctx->next_window_seq = blocktype;
468
}
469

    
470
static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx,
471
                                       const int16_t *audio, const int16_t *la,
472
                                       int channel, int prev_type)
473
{
474
    AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
475
    AacPsyChannel *pch  = &pctx->ch[channel];
476
    int grouping     = 0;
477
    int uselongblock = 1;
478
    int attacks[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
479
    int i;
480
    FFPsyWindowInfo wi;
481

    
482
    memset(&wi, 0, sizeof(wi));
483
    if (la) {
484
        float hpfsmpl[AAC_BLOCK_SIZE_LONG];
485
        float const *pf = hpfsmpl;
486
        float attack_intensity[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];
487
        float energy_subshort[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];
488
        float energy_short[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
489
        int chans = ctx->avctx->channels;
490
        const int16_t *firbuf = la + (AAC_BLOCK_SIZE_SHORT/4 - PSY_LAME_FIR_LEN) * chans;
491
        int j, att_sum = 0;
492

    
493
        /* LAME comment: apply high pass filter of fs/4 */
494
        for (i = 0; i < AAC_BLOCK_SIZE_LONG; i++) {
495
            float sum1, sum2;
496
            sum1 = firbuf[(i + ((PSY_LAME_FIR_LEN - 1) / 2)) * chans];
497
            sum2 = 0.0;
498
            for (j = 0; j < ((PSY_LAME_FIR_LEN - 1) / 2) - 1; j += 2) {
499
                sum1 += psy_fir_coeffs[j] * (firbuf[(i + j) * chans] + firbuf[(i + PSY_LAME_FIR_LEN - j) * chans]);
500
                sum2 += psy_fir_coeffs[j + 1] * (firbuf[(i + j + 1) * chans] + firbuf[(i + PSY_LAME_FIR_LEN - j - 1) * chans]);
501
            }
502
            hpfsmpl[i] = sum1 + sum2;
503
        }
504

    
505
        /* Calculate the energies of each sub-shortblock */
506
        for (i = 0; i < PSY_LAME_NUM_SUBBLOCKS; i++) {
507
            energy_subshort[i] = pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 1) * PSY_LAME_NUM_SUBBLOCKS)];
508
            assert(pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 2) * PSY_LAME_NUM_SUBBLOCKS + 1)] > 0);
509
            attack_intensity[i] = energy_subshort[i] / pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 2) * PSY_LAME_NUM_SUBBLOCKS + 1)];
510
            energy_short[0] += energy_subshort[i];
511
        }
512

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

    
537
        /* compare energy between sub-short blocks */
538
        for (i = 0; i < (AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS; i++)
539
            if (!attacks[i / PSY_LAME_NUM_SUBBLOCKS])
540
                if (attack_intensity[i] > pch->attack_threshold)
541
                    attacks[i / PSY_LAME_NUM_SUBBLOCKS] = (i % PSY_LAME_NUM_SUBBLOCKS) + 1;
542

    
543
        /* should have energy change between short blocks, in order to avoid periodic signals */
544
        /* Good samples to show the effect are Trumpet test songs */
545
        /* GB: tuned (1) to avoid too many short blocks for test sample TRUMPET */
546
        /* RH: tuned (2) to let enough short blocks through for test sample FSOL and SNAPS */
547
        for (i = 1; i < AAC_NUM_BLOCKS_SHORT + 1; i++) {
548
            float const u = energy_short[i - 1];
549
            float const v = energy_short[i];
550
            float const m = FFMAX(u, v);
551
            if (m < 40000) {                          /* (2) */
552
                if (u < 1.7f * v && v < 1.7f * u) {   /* (1) */
553
                    if (i == 1 && attacks[0] < attacks[i])
554
                        attacks[0] = 0;
555
                    attacks[i] = 0;
556
                }
557
            }
558
            att_sum += attacks[i];
559
        }
560

    
561
        if (attacks[0] <= pch->prev_attack)
562
            attacks[0] = 0;
563

    
564
        att_sum += attacks[0];
565
        /* 3 below indicates the previous attack happened in the last sub-block of the previous sequence */
566
        if (pch->prev_attack == 3 || att_sum) {
567
            uselongblock = 0;
568

    
569
            for (i = 1; i < AAC_NUM_BLOCKS_SHORT + 1; i++)
570
                if (attacks[i] && attacks[i-1])
571
                    attacks[i] = 0;
572
        }
573
    } else {
574
        /* We have no lookahead info, so just use same type as the previous sequence. */
575
        uselongblock = !(prev_type == EIGHT_SHORT_SEQUENCE);
576
    }
577

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

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

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

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

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

    
616
    return wi;
617
}
618

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