void ff_aac_update_ltp(AACEncContext *s, SingleChannelElement *sce)
{
    int i, j, lag, samples_num;
    float corr, max_ratio, max_corr;
    float *pred_signal = &sce->ltp_state[0];
    const float *samples = &s->planar_samples[s->cur_channel][1024];

    if (s->profile != FF_PROFILE_AAC_LTP)
        return;

    /* Calculate lag */
    max_corr = 0.0f;
    for (i = 0; i < 2048; i++) {
        float s0 = 0.0f, s1 = 0.0f;
        const int start = FFMAX(0, i - 1024);
        for (j = start; j < 2048; j++) {
            const int idx = j - i + 1024;
            s0 += samples[j]*pred_signal[idx];
            s1 += pred_signal[idx]*pred_signal[idx];
        }
        corr = s1 > 0.0f ? s0/sqrt(s1) : 0.0f;
        if (corr > max_corr) {
            max_corr = corr;
            lag = i;
            max_ratio = corr/(2048-start);
        }
    }

    if (lag < 1)
        return;

    sce->ics.ltp.lag = lag = av_clip_uintp2(lag, 11);
    sce->ics.ltp.coef_idx  = quant_array_idx(max_ratio, ltp_coef, 8);
    sce->ics.ltp.coef      = ltp_coef[sce->ics.ltp.coef_idx];

    /* Predict the new samples */
    samples_num = 1024 + (lag < 1024 ? lag : 1024);
    for (i = 1024; i < samples_num + 1024; i++)
        pred_signal[i] = sce->ics.ltp.coef*pred_signal[i-lag];
    memset(&pred_signal[samples_num], 0, (2048 - samples_num)*sizeof(float));
}