libavcodec/amrwbdec.c
Go to the documentation of this file.
00001 /*
00002  * AMR wideband decoder
00003  * Copyright (c) 2010 Marcelo Galvao Povoa
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A particular PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00027 #include "libavutil/lfg.h"
00028 
00029 #include "avcodec.h"
00030 #include "get_bits.h"
00031 #include "lsp.h"
00032 #include "celp_math.h"
00033 #include "celp_filters.h"
00034 #include "acelp_filters.h"
00035 #include "acelp_vectors.h"
00036 #include "acelp_pitch_delay.h"
00037 
00038 #define AMR_USE_16BIT_TABLES
00039 #include "amr.h"
00040 
00041 #include "amrwbdata.h"
00042 
00043 typedef struct {
00044     AVFrame                              avframe; 
00045     AMRWBFrame                             frame; 
00046     enum Mode                        fr_cur_mode; 
00047     uint8_t                           fr_quality; 
00048     float                      isf_cur[LP_ORDER]; 
00049     float                   isf_q_past[LP_ORDER]; 
00050     float               isf_past_final[LP_ORDER]; 
00051     double                      isp[4][LP_ORDER]; 
00052     double               isp_sub4_past[LP_ORDER]; 
00053 
00054     float                   lp_coef[4][LP_ORDER]; 
00055 
00056     uint8_t                       base_pitch_lag; 
00057     uint8_t                        pitch_lag_int; 
00058 
00059     float excitation_buf[AMRWB_P_DELAY_MAX + LP_ORDER + 2 + AMRWB_SFR_SIZE]; 
00060     float                            *excitation; 
00061 
00062     float           pitch_vector[AMRWB_SFR_SIZE]; 
00063     float           fixed_vector[AMRWB_SFR_SIZE]; 
00064 
00065     float                    prediction_error[4]; 
00066     float                          pitch_gain[6]; 
00067     float                          fixed_gain[2]; 
00068 
00069     float                              tilt_coef; 
00070 
00071     float                 prev_sparse_fixed_gain; 
00072     uint8_t                    prev_ir_filter_nr; 
00073     float                           prev_tr_gain; 
00074 
00075     float samples_az[LP_ORDER + AMRWB_SFR_SIZE];         
00076     float samples_up[UPS_MEM_SIZE + AMRWB_SFR_SIZE];     
00077     float samples_hb[LP_ORDER_16k + AMRWB_SFR_SIZE_16k]; 
00078 
00079     float          hpf_31_mem[2], hpf_400_mem[2]; 
00080     float                           demph_mem[1]; 
00081     float               bpf_6_7_mem[HB_FIR_SIZE]; 
00082     float                 lpf_7_mem[HB_FIR_SIZE]; 
00083 
00084     AVLFG                                   prng; 
00085     uint8_t                          first_frame; 
00086 } AMRWBContext;
00087 
00088 static av_cold int amrwb_decode_init(AVCodecContext *avctx)
00089 {
00090     AMRWBContext *ctx = avctx->priv_data;
00091     int i;
00092 
00093     avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
00094 
00095     av_lfg_init(&ctx->prng, 1);
00096 
00097     ctx->excitation  = &ctx->excitation_buf[AMRWB_P_DELAY_MAX + LP_ORDER + 1];
00098     ctx->first_frame = 1;
00099 
00100     for (i = 0; i < LP_ORDER; i++)
00101         ctx->isf_past_final[i] = isf_init[i] * (1.0f / (1 << 15));
00102 
00103     for (i = 0; i < 4; i++)
00104         ctx->prediction_error[i] = MIN_ENERGY;
00105 
00106     avcodec_get_frame_defaults(&ctx->avframe);
00107     avctx->coded_frame = &ctx->avframe;
00108 
00109     return 0;
00110 }
00111 
00121 static int decode_mime_header(AMRWBContext *ctx, const uint8_t *buf)
00122 {
00123     GetBitContext gb;
00124     init_get_bits(&gb, buf, 8);
00125 
00126     /* Decode frame header (1st octet) */
00127     skip_bits(&gb, 1);  // padding bit
00128     ctx->fr_cur_mode  = get_bits(&gb, 4);
00129     ctx->fr_quality   = get_bits1(&gb);
00130     skip_bits(&gb, 2);  // padding bits
00131 
00132     return 1;
00133 }
00134 
00142 static void decode_isf_indices_36b(uint16_t *ind, float *isf_q)
00143 {
00144     int i;
00145 
00146     for (i = 0; i < 9; i++)
00147         isf_q[i]      = dico1_isf[ind[0]][i]      * (1.0f / (1 << 15));
00148 
00149     for (i = 0; i < 7; i++)
00150         isf_q[i + 9]  = dico2_isf[ind[1]][i]      * (1.0f / (1 << 15));
00151 
00152     for (i = 0; i < 5; i++)
00153         isf_q[i]     += dico21_isf_36b[ind[2]][i] * (1.0f / (1 << 15));
00154 
00155     for (i = 0; i < 4; i++)
00156         isf_q[i + 5] += dico22_isf_36b[ind[3]][i] * (1.0f / (1 << 15));
00157 
00158     for (i = 0; i < 7; i++)
00159         isf_q[i + 9] += dico23_isf_36b[ind[4]][i] * (1.0f / (1 << 15));
00160 }
00161 
00169 static void decode_isf_indices_46b(uint16_t *ind, float *isf_q)
00170 {
00171     int i;
00172 
00173     for (i = 0; i < 9; i++)
00174         isf_q[i]       = dico1_isf[ind[0]][i]  * (1.0f / (1 << 15));
00175 
00176     for (i = 0; i < 7; i++)
00177         isf_q[i + 9]   = dico2_isf[ind[1]][i]  * (1.0f / (1 << 15));
00178 
00179     for (i = 0; i < 3; i++)
00180         isf_q[i]      += dico21_isf[ind[2]][i] * (1.0f / (1 << 15));
00181 
00182     for (i = 0; i < 3; i++)
00183         isf_q[i + 3]  += dico22_isf[ind[3]][i] * (1.0f / (1 << 15));
00184 
00185     for (i = 0; i < 3; i++)
00186         isf_q[i + 6]  += dico23_isf[ind[4]][i] * (1.0f / (1 << 15));
00187 
00188     for (i = 0; i < 3; i++)
00189         isf_q[i + 9]  += dico24_isf[ind[5]][i] * (1.0f / (1 << 15));
00190 
00191     for (i = 0; i < 4; i++)
00192         isf_q[i + 12] += dico25_isf[ind[6]][i] * (1.0f / (1 << 15));
00193 }
00194 
00203 static void isf_add_mean_and_past(float *isf_q, float *isf_past)
00204 {
00205     int i;
00206     float tmp;
00207 
00208     for (i = 0; i < LP_ORDER; i++) {
00209         tmp = isf_q[i];
00210         isf_q[i] += isf_mean[i] * (1.0f / (1 << 15));
00211         isf_q[i] += PRED_FACTOR * isf_past[i];
00212         isf_past[i] = tmp;
00213     }
00214 }
00215 
00223 static void interpolate_isp(double isp_q[4][LP_ORDER], const double *isp4_past)
00224 {
00225     int i, k;
00226 
00227     for (k = 0; k < 3; k++) {
00228         float c = isfp_inter[k];
00229         for (i = 0; i < LP_ORDER; i++)
00230             isp_q[k][i] = (1.0 - c) * isp4_past[i] + c * isp_q[3][i];
00231     }
00232 }
00233 
00245 static void decode_pitch_lag_high(int *lag_int, int *lag_frac, int pitch_index,
00246                                   uint8_t *base_lag_int, int subframe)
00247 {
00248     if (subframe == 0 || subframe == 2) {
00249         if (pitch_index < 376) {
00250             *lag_int  = (pitch_index + 137) >> 2;
00251             *lag_frac = pitch_index - (*lag_int << 2) + 136;
00252         } else if (pitch_index < 440) {
00253             *lag_int  = (pitch_index + 257 - 376) >> 1;
00254             *lag_frac = (pitch_index - (*lag_int << 1) + 256 - 376) << 1;
00255             /* the actual resolution is 1/2 but expressed as 1/4 */
00256         } else {
00257             *lag_int  = pitch_index - 280;
00258             *lag_frac = 0;
00259         }
00260         /* minimum lag for next subframe */
00261         *base_lag_int = av_clip(*lag_int - 8 - (*lag_frac < 0),
00262                                 AMRWB_P_DELAY_MIN, AMRWB_P_DELAY_MAX - 15);
00263         // XXX: the spec states clearly that *base_lag_int should be
00264         // the nearest integer to *lag_int (minus 8), but the ref code
00265         // actually always uses its floor, I'm following the latter
00266     } else {
00267         *lag_int  = (pitch_index + 1) >> 2;
00268         *lag_frac = pitch_index - (*lag_int << 2);
00269         *lag_int += *base_lag_int;
00270     }
00271 }
00272 
00278 static void decode_pitch_lag_low(int *lag_int, int *lag_frac, int pitch_index,
00279                                  uint8_t *base_lag_int, int subframe, enum Mode mode)
00280 {
00281     if (subframe == 0 || (subframe == 2 && mode != MODE_6k60)) {
00282         if (pitch_index < 116) {
00283             *lag_int  = (pitch_index + 69) >> 1;
00284             *lag_frac = (pitch_index - (*lag_int << 1) + 68) << 1;
00285         } else {
00286             *lag_int  = pitch_index - 24;
00287             *lag_frac = 0;
00288         }
00289         // XXX: same problem as before
00290         *base_lag_int = av_clip(*lag_int - 8 - (*lag_frac < 0),
00291                                 AMRWB_P_DELAY_MIN, AMRWB_P_DELAY_MAX - 15);
00292     } else {
00293         *lag_int  = (pitch_index + 1) >> 1;
00294         *lag_frac = (pitch_index - (*lag_int << 1)) << 1;
00295         *lag_int += *base_lag_int;
00296     }
00297 }
00298 
00307 static void decode_pitch_vector(AMRWBContext *ctx,
00308                                 const AMRWBSubFrame *amr_subframe,
00309                                 const int subframe)
00310 {
00311     int pitch_lag_int, pitch_lag_frac;
00312     int i;
00313     float *exc     = ctx->excitation;
00314     enum Mode mode = ctx->fr_cur_mode;
00315 
00316     if (mode <= MODE_8k85) {
00317         decode_pitch_lag_low(&pitch_lag_int, &pitch_lag_frac, amr_subframe->adap,
00318                               &ctx->base_pitch_lag, subframe, mode);
00319     } else
00320         decode_pitch_lag_high(&pitch_lag_int, &pitch_lag_frac, amr_subframe->adap,
00321                               &ctx->base_pitch_lag, subframe);
00322 
00323     ctx->pitch_lag_int = pitch_lag_int;
00324     pitch_lag_int += pitch_lag_frac > 0;
00325 
00326     /* Calculate the pitch vector by interpolating the past excitation at the
00327        pitch lag using a hamming windowed sinc function */
00328     ff_acelp_interpolatef(exc, exc + 1 - pitch_lag_int,
00329                           ac_inter, 4,
00330                           pitch_lag_frac + (pitch_lag_frac > 0 ? 0 : 4),
00331                           LP_ORDER, AMRWB_SFR_SIZE + 1);
00332 
00333     /* Check which pitch signal path should be used
00334      * 6k60 and 8k85 modes have the ltp flag set to 0 */
00335     if (amr_subframe->ltp) {
00336         memcpy(ctx->pitch_vector, exc, AMRWB_SFR_SIZE * sizeof(float));
00337     } else {
00338         for (i = 0; i < AMRWB_SFR_SIZE; i++)
00339             ctx->pitch_vector[i] = 0.18 * exc[i - 1] + 0.64 * exc[i] +
00340                                    0.18 * exc[i + 1];
00341         memcpy(exc, ctx->pitch_vector, AMRWB_SFR_SIZE * sizeof(float));
00342     }
00343 }
00344 
00346 #define BIT_STR(x,lsb,len) (((x) >> (lsb)) & ((1 << (len)) - 1))
00347 
00349 #define BIT_POS(x, p) (((x) >> (p)) & 1)
00350 
00364 static inline void decode_1p_track(int *out, int code, int m, int off)
00365 {
00366     int pos = BIT_STR(code, 0, m) + off; 
00367 
00368     out[0] = BIT_POS(code, m) ? -pos : pos;
00369 }
00370 
00371 static inline void decode_2p_track(int *out, int code, int m, int off) 
00372 {
00373     int pos0 = BIT_STR(code, m, m) + off;
00374     int pos1 = BIT_STR(code, 0, m) + off;
00375 
00376     out[0] = BIT_POS(code, 2*m) ? -pos0 : pos0;
00377     out[1] = BIT_POS(code, 2*m) ? -pos1 : pos1;
00378     out[1] = pos0 > pos1 ? -out[1] : out[1];
00379 }
00380 
00381 static void decode_3p_track(int *out, int code, int m, int off) 
00382 {
00383     int half_2p = BIT_POS(code, 2*m - 1) << (m - 1);
00384 
00385     decode_2p_track(out, BIT_STR(code, 0, 2*m - 1),
00386                     m - 1, off + half_2p);
00387     decode_1p_track(out + 2, BIT_STR(code, 2*m, m + 1), m, off);
00388 }
00389 
00390 static void decode_4p_track(int *out, int code, int m, int off) 
00391 {
00392     int half_4p, subhalf_2p;
00393     int b_offset = 1 << (m - 1);
00394 
00395     switch (BIT_STR(code, 4*m - 2, 2)) { /* case ID (2 bits) */
00396     case 0: /* 0 pulses in A, 4 pulses in B or vice versa */
00397         half_4p = BIT_POS(code, 4*m - 3) << (m - 1); // which has 4 pulses
00398         subhalf_2p = BIT_POS(code, 2*m - 3) << (m - 2);
00399 
00400         decode_2p_track(out, BIT_STR(code, 0, 2*m - 3),
00401                         m - 2, off + half_4p + subhalf_2p);
00402         decode_2p_track(out + 2, BIT_STR(code, 2*m - 2, 2*m - 1),
00403                         m - 1, off + half_4p);
00404         break;
00405     case 1: /* 1 pulse in A, 3 pulses in B */
00406         decode_1p_track(out, BIT_STR(code,  3*m - 2, m),
00407                         m - 1, off);
00408         decode_3p_track(out + 1, BIT_STR(code, 0, 3*m - 2),
00409                         m - 1, off + b_offset);
00410         break;
00411     case 2: /* 2 pulses in each half */
00412         decode_2p_track(out, BIT_STR(code, 2*m - 1, 2*m - 1),
00413                         m - 1, off);
00414         decode_2p_track(out + 2, BIT_STR(code, 0, 2*m - 1),
00415                         m - 1, off + b_offset);
00416         break;
00417     case 3: /* 3 pulses in A, 1 pulse in B */
00418         decode_3p_track(out, BIT_STR(code, m, 3*m - 2),
00419                         m - 1, off);
00420         decode_1p_track(out + 3, BIT_STR(code, 0, m),
00421                         m - 1, off + b_offset);
00422         break;
00423     }
00424 }
00425 
00426 static void decode_5p_track(int *out, int code, int m, int off) 
00427 {
00428     int half_3p = BIT_POS(code, 5*m - 1) << (m - 1);
00429 
00430     decode_3p_track(out, BIT_STR(code, 2*m + 1, 3*m - 2),
00431                     m - 1, off + half_3p);
00432 
00433     decode_2p_track(out + 3, BIT_STR(code, 0, 2*m + 1), m, off);
00434 }
00435 
00436 static void decode_6p_track(int *out, int code, int m, int off) 
00437 {
00438     int b_offset = 1 << (m - 1);
00439     /* which half has more pulses in cases 0 to 2 */
00440     int half_more  = BIT_POS(code, 6*m - 5) << (m - 1);
00441     int half_other = b_offset - half_more;
00442 
00443     switch (BIT_STR(code, 6*m - 4, 2)) { /* case ID (2 bits) */
00444     case 0: /* 0 pulses in A, 6 pulses in B or vice versa */
00445         decode_1p_track(out, BIT_STR(code, 0, m),
00446                         m - 1, off + half_more);
00447         decode_5p_track(out + 1, BIT_STR(code, m, 5*m - 5),
00448                         m - 1, off + half_more);
00449         break;
00450     case 1: /* 1 pulse in A, 5 pulses in B or vice versa */
00451         decode_1p_track(out, BIT_STR(code, 0, m),
00452                         m - 1, off + half_other);
00453         decode_5p_track(out + 1, BIT_STR(code, m, 5*m - 5),
00454                         m - 1, off + half_more);
00455         break;
00456     case 2: /* 2 pulses in A, 4 pulses in B or vice versa */
00457         decode_2p_track(out, BIT_STR(code, 0, 2*m - 1),
00458                         m - 1, off + half_other);
00459         decode_4p_track(out + 2, BIT_STR(code, 2*m - 1, 4*m - 4),
00460                         m - 1, off + half_more);
00461         break;
00462     case 3: /* 3 pulses in A, 3 pulses in B */
00463         decode_3p_track(out, BIT_STR(code, 3*m - 2, 3*m - 2),
00464                         m - 1, off);
00465         decode_3p_track(out + 3, BIT_STR(code, 0, 3*m - 2),
00466                         m - 1, off + b_offset);
00467         break;
00468     }
00469 }
00470 
00480 static void decode_fixed_vector(float *fixed_vector, const uint16_t *pulse_hi,
00481                                 const uint16_t *pulse_lo, const enum Mode mode)
00482 {
00483     /* sig_pos stores for each track the decoded pulse position indexes
00484      * (1-based) multiplied by its corresponding amplitude (+1 or -1) */
00485     int sig_pos[4][6];
00486     int spacing = (mode == MODE_6k60) ? 2 : 4;
00487     int i, j;
00488 
00489     switch (mode) {
00490     case MODE_6k60:
00491         for (i = 0; i < 2; i++)
00492             decode_1p_track(sig_pos[i], pulse_lo[i], 5, 1);
00493         break;
00494     case MODE_8k85:
00495         for (i = 0; i < 4; i++)
00496             decode_1p_track(sig_pos[i], pulse_lo[i], 4, 1);
00497         break;
00498     case MODE_12k65:
00499         for (i = 0; i < 4; i++)
00500             decode_2p_track(sig_pos[i], pulse_lo[i], 4, 1);
00501         break;
00502     case MODE_14k25:
00503         for (i = 0; i < 2; i++)
00504             decode_3p_track(sig_pos[i], pulse_lo[i], 4, 1);
00505         for (i = 2; i < 4; i++)
00506             decode_2p_track(sig_pos[i], pulse_lo[i], 4, 1);
00507         break;
00508     case MODE_15k85:
00509         for (i = 0; i < 4; i++)
00510             decode_3p_track(sig_pos[i], pulse_lo[i], 4, 1);
00511         break;
00512     case MODE_18k25:
00513         for (i = 0; i < 4; i++)
00514             decode_4p_track(sig_pos[i], (int) pulse_lo[i] +
00515                            ((int) pulse_hi[i] << 14), 4, 1);
00516         break;
00517     case MODE_19k85:
00518         for (i = 0; i < 2; i++)
00519             decode_5p_track(sig_pos[i], (int) pulse_lo[i] +
00520                            ((int) pulse_hi[i] << 10), 4, 1);
00521         for (i = 2; i < 4; i++)
00522             decode_4p_track(sig_pos[i], (int) pulse_lo[i] +
00523                            ((int) pulse_hi[i] << 14), 4, 1);
00524         break;
00525     case MODE_23k05:
00526     case MODE_23k85:
00527         for (i = 0; i < 4; i++)
00528             decode_6p_track(sig_pos[i], (int) pulse_lo[i] +
00529                            ((int) pulse_hi[i] << 11), 4, 1);
00530         break;
00531     }
00532 
00533     memset(fixed_vector, 0, sizeof(float) * AMRWB_SFR_SIZE);
00534 
00535     for (i = 0; i < 4; i++)
00536         for (j = 0; j < pulses_nb_per_mode_tr[mode][i]; j++) {
00537             int pos = (FFABS(sig_pos[i][j]) - 1) * spacing + i;
00538 
00539             fixed_vector[pos] += sig_pos[i][j] < 0 ? -1.0 : 1.0;
00540         }
00541 }
00542 
00551 static void decode_gains(const uint8_t vq_gain, const enum Mode mode,
00552                          float *fixed_gain_factor, float *pitch_gain)
00553 {
00554     const int16_t *gains = (mode <= MODE_8k85 ? qua_gain_6b[vq_gain] :
00555                                                 qua_gain_7b[vq_gain]);
00556 
00557     *pitch_gain        = gains[0] * (1.0f / (1 << 14));
00558     *fixed_gain_factor = gains[1] * (1.0f / (1 << 11));
00559 }
00560 
00567 // XXX: Spec states this procedure should be applied when the pitch
00568 // lag is less than 64, but this checking seems absent in reference and AMR-NB
00569 static void pitch_sharpening(AMRWBContext *ctx, float *fixed_vector)
00570 {
00571     int i;
00572 
00573     /* Tilt part */
00574     for (i = AMRWB_SFR_SIZE - 1; i != 0; i--)
00575         fixed_vector[i] -= fixed_vector[i - 1] * ctx->tilt_coef;
00576 
00577     /* Periodicity enhancement part */
00578     for (i = ctx->pitch_lag_int; i < AMRWB_SFR_SIZE; i++)
00579         fixed_vector[i] += fixed_vector[i - ctx->pitch_lag_int] * 0.85;
00580 }
00581 
00588 // XXX: There is something wrong with the precision here! The magnitudes
00589 // of the energies are not correct. Please check the reference code carefully
00590 static float voice_factor(float *p_vector, float p_gain,
00591                           float *f_vector, float f_gain)
00592 {
00593     double p_ener = (double) ff_dot_productf(p_vector, p_vector,
00594                                              AMRWB_SFR_SIZE) * p_gain * p_gain;
00595     double f_ener = (double) ff_dot_productf(f_vector, f_vector,
00596                                              AMRWB_SFR_SIZE) * f_gain * f_gain;
00597 
00598     return (p_ener - f_ener) / (p_ener + f_ener);
00599 }
00600 
00611 static float *anti_sparseness(AMRWBContext *ctx,
00612                               float *fixed_vector, float *buf)
00613 {
00614     int ir_filter_nr;
00615 
00616     if (ctx->fr_cur_mode > MODE_8k85) // no filtering in higher modes
00617         return fixed_vector;
00618 
00619     if (ctx->pitch_gain[0] < 0.6) {
00620         ir_filter_nr = 0;      // strong filtering
00621     } else if (ctx->pitch_gain[0] < 0.9) {
00622         ir_filter_nr = 1;      // medium filtering
00623     } else
00624         ir_filter_nr = 2;      // no filtering
00625 
00626     /* detect 'onset' */
00627     if (ctx->fixed_gain[0] > 3.0 * ctx->fixed_gain[1]) {
00628         if (ir_filter_nr < 2)
00629             ir_filter_nr++;
00630     } else {
00631         int i, count = 0;
00632 
00633         for (i = 0; i < 6; i++)
00634             if (ctx->pitch_gain[i] < 0.6)
00635                 count++;
00636 
00637         if (count > 2)
00638             ir_filter_nr = 0;
00639 
00640         if (ir_filter_nr > ctx->prev_ir_filter_nr + 1)
00641             ir_filter_nr--;
00642     }
00643 
00644     /* update ir filter strength history */
00645     ctx->prev_ir_filter_nr = ir_filter_nr;
00646 
00647     ir_filter_nr += (ctx->fr_cur_mode == MODE_8k85);
00648 
00649     if (ir_filter_nr < 2) {
00650         int i;
00651         const float *coef = ir_filters_lookup[ir_filter_nr];
00652 
00653         /* Circular convolution code in the reference
00654          * decoder was modified to avoid using one
00655          * extra array. The filtered vector is given by:
00656          *
00657          * c2(n) = sum(i,0,len-1){ c(i) * coef( (n - i + len) % len ) }
00658          */
00659 
00660         memset(buf, 0, sizeof(float) * AMRWB_SFR_SIZE);
00661         for (i = 0; i < AMRWB_SFR_SIZE; i++)
00662             if (fixed_vector[i])
00663                 ff_celp_circ_addf(buf, buf, coef, i, fixed_vector[i],
00664                                   AMRWB_SFR_SIZE);
00665         fixed_vector = buf;
00666     }
00667 
00668     return fixed_vector;
00669 }
00670 
00675 static float stability_factor(const float *isf, const float *isf_past)
00676 {
00677     int i;
00678     float acc = 0.0;
00679 
00680     for (i = 0; i < LP_ORDER - 1; i++)
00681         acc += (isf[i] - isf_past[i]) * (isf[i] - isf_past[i]);
00682 
00683     // XXX: This part is not so clear from the reference code
00684     // the result is more accurate changing the "/ 256" to "* 512"
00685     return FFMAX(0.0, 1.25 - acc * 0.8 * 512);
00686 }
00687 
00699 static float noise_enhancer(float fixed_gain, float *prev_tr_gain,
00700                             float voice_fac,  float stab_fac)
00701 {
00702     float sm_fac = 0.5 * (1 - voice_fac) * stab_fac;
00703     float g0;
00704 
00705     // XXX: the following fixed-point constants used to in(de)crement
00706     // gain by 1.5dB were taken from the reference code, maybe it could
00707     // be simpler
00708     if (fixed_gain < *prev_tr_gain) {
00709         g0 = FFMIN(*prev_tr_gain, fixed_gain + fixed_gain *
00710                      (6226 * (1.0f / (1 << 15)))); // +1.5 dB
00711     } else
00712         g0 = FFMAX(*prev_tr_gain, fixed_gain *
00713                     (27536 * (1.0f / (1 << 15)))); // -1.5 dB
00714 
00715     *prev_tr_gain = g0; // update next frame threshold
00716 
00717     return sm_fac * g0 + (1 - sm_fac) * fixed_gain;
00718 }
00719 
00726 static void pitch_enhancer(float *fixed_vector, float voice_fac)
00727 {
00728     int i;
00729     float cpe  = 0.125 * (1 + voice_fac);
00730     float last = fixed_vector[0]; // holds c(i - 1)
00731 
00732     fixed_vector[0] -= cpe * fixed_vector[1];
00733 
00734     for (i = 1; i < AMRWB_SFR_SIZE - 1; i++) {
00735         float cur = fixed_vector[i];
00736 
00737         fixed_vector[i] -= cpe * (last + fixed_vector[i + 1]);
00738         last = cur;
00739     }
00740 
00741     fixed_vector[AMRWB_SFR_SIZE - 1] -= cpe * last;
00742 }
00743 
00754 static void synthesis(AMRWBContext *ctx, float *lpc, float *excitation,
00755                       float fixed_gain, const float *fixed_vector,
00756                       float *samples)
00757 {
00758     ff_weighted_vector_sumf(excitation, ctx->pitch_vector, fixed_vector,
00759                             ctx->pitch_gain[0], fixed_gain, AMRWB_SFR_SIZE);
00760 
00761     /* emphasize pitch vector contribution in low bitrate modes */
00762     if (ctx->pitch_gain[0] > 0.5 && ctx->fr_cur_mode <= MODE_8k85) {
00763         int i;
00764         float energy = ff_dot_productf(excitation, excitation,
00765                                        AMRWB_SFR_SIZE);
00766 
00767         // XXX: Weird part in both ref code and spec. A unknown parameter
00768         // {beta} seems to be identical to the current pitch gain
00769         float pitch_factor = 0.25 * ctx->pitch_gain[0] * ctx->pitch_gain[0];
00770 
00771         for (i = 0; i < AMRWB_SFR_SIZE; i++)
00772             excitation[i] += pitch_factor * ctx->pitch_vector[i];
00773 
00774         ff_scale_vector_to_given_sum_of_squares(excitation, excitation,
00775                                                 energy, AMRWB_SFR_SIZE);
00776     }
00777 
00778     ff_celp_lp_synthesis_filterf(samples, lpc, excitation,
00779                                  AMRWB_SFR_SIZE, LP_ORDER);
00780 }
00781 
00791 static void de_emphasis(float *out, float *in, float m, float mem[1])
00792 {
00793     int i;
00794 
00795     out[0] = in[0] + m * mem[0];
00796 
00797     for (i = 1; i < AMRWB_SFR_SIZE; i++)
00798          out[i] = in[i] + out[i - 1] * m;
00799 
00800     mem[0] = out[AMRWB_SFR_SIZE - 1];
00801 }
00802 
00811 static void upsample_5_4(float *out, const float *in, int o_size)
00812 {
00813     const float *in0 = in - UPS_FIR_SIZE + 1;
00814     int i, j, k;
00815     int int_part = 0, frac_part;
00816 
00817     i = 0;
00818     for (j = 0; j < o_size / 5; j++) {
00819         out[i] = in[int_part];
00820         frac_part = 4;
00821         i++;
00822 
00823         for (k = 1; k < 5; k++) {
00824             out[i] = ff_dot_productf(in0 + int_part, upsample_fir[4 - frac_part],
00825                                      UPS_MEM_SIZE);
00826             int_part++;
00827             frac_part--;
00828             i++;
00829         }
00830     }
00831 }
00832 
00842 static float find_hb_gain(AMRWBContext *ctx, const float *synth,
00843                           uint16_t hb_idx, uint8_t vad)
00844 {
00845     int wsp = (vad > 0);
00846     float tilt;
00847 
00848     if (ctx->fr_cur_mode == MODE_23k85)
00849         return qua_hb_gain[hb_idx] * (1.0f / (1 << 14));
00850 
00851     tilt = ff_dot_productf(synth, synth + 1, AMRWB_SFR_SIZE - 1) /
00852            ff_dot_productf(synth, synth, AMRWB_SFR_SIZE);
00853 
00854     /* return gain bounded by [0.1, 1.0] */
00855     return av_clipf((1.0 - FFMAX(0.0, tilt)) * (1.25 - 0.25 * wsp), 0.1, 1.0);
00856 }
00857 
00867 static void scaled_hb_excitation(AMRWBContext *ctx, float *hb_exc,
00868                                  const float *synth_exc, float hb_gain)
00869 {
00870     int i;
00871     float energy = ff_dot_productf(synth_exc, synth_exc, AMRWB_SFR_SIZE);
00872 
00873     /* Generate a white-noise excitation */
00874     for (i = 0; i < AMRWB_SFR_SIZE_16k; i++)
00875         hb_exc[i] = 32768.0 - (uint16_t) av_lfg_get(&ctx->prng);
00876 
00877     ff_scale_vector_to_given_sum_of_squares(hb_exc, hb_exc,
00878                                             energy * hb_gain * hb_gain,
00879                                             AMRWB_SFR_SIZE_16k);
00880 }
00881 
00885 static float auto_correlation(float *diff_isf, float mean, int lag)
00886 {
00887     int i;
00888     float sum = 0.0;
00889 
00890     for (i = 7; i < LP_ORDER - 2; i++) {
00891         float prod = (diff_isf[i] - mean) * (diff_isf[i - lag] - mean);
00892         sum += prod * prod;
00893     }
00894     return sum;
00895 }
00896 
00904 static void extrapolate_isf(float isf[LP_ORDER_16k])
00905 {
00906     float diff_isf[LP_ORDER - 2], diff_mean;
00907     float *diff_hi = diff_isf - LP_ORDER + 1; // diff array for extrapolated indexes
00908     float corr_lag[3];
00909     float est, scale;
00910     int i, i_max_corr;
00911 
00912     isf[LP_ORDER_16k - 1] = isf[LP_ORDER - 1];
00913 
00914     /* Calculate the difference vector */
00915     for (i = 0; i < LP_ORDER - 2; i++)
00916         diff_isf[i] = isf[i + 1] - isf[i];
00917 
00918     diff_mean = 0.0;
00919     for (i = 2; i < LP_ORDER - 2; i++)
00920         diff_mean += diff_isf[i] * (1.0f / (LP_ORDER - 4));
00921 
00922     /* Find which is the maximum autocorrelation */
00923     i_max_corr = 0;
00924     for (i = 0; i < 3; i++) {
00925         corr_lag[i] = auto_correlation(diff_isf, diff_mean, i + 2);
00926 
00927         if (corr_lag[i] > corr_lag[i_max_corr])
00928             i_max_corr = i;
00929     }
00930     i_max_corr++;
00931 
00932     for (i = LP_ORDER - 1; i < LP_ORDER_16k - 1; i++)
00933         isf[i] = isf[i - 1] + isf[i - 1 - i_max_corr]
00934                             - isf[i - 2 - i_max_corr];
00935 
00936     /* Calculate an estimate for ISF(18) and scale ISF based on the error */
00937     est   = 7965 + (isf[2] - isf[3] - isf[4]) / 6.0;
00938     scale = 0.5 * (FFMIN(est, 7600) - isf[LP_ORDER - 2]) /
00939             (isf[LP_ORDER_16k - 2] - isf[LP_ORDER - 2]);
00940 
00941     for (i = LP_ORDER - 1; i < LP_ORDER_16k - 1; i++)
00942         diff_hi[i] = scale * (isf[i] - isf[i - 1]);
00943 
00944     /* Stability insurance */
00945     for (i = LP_ORDER; i < LP_ORDER_16k - 1; i++)
00946         if (diff_hi[i] + diff_hi[i - 1] < 5.0) {
00947             if (diff_hi[i] > diff_hi[i - 1]) {
00948                 diff_hi[i - 1] = 5.0 - diff_hi[i];
00949             } else
00950                 diff_hi[i] = 5.0 - diff_hi[i - 1];
00951         }
00952 
00953     for (i = LP_ORDER - 1; i < LP_ORDER_16k - 1; i++)
00954         isf[i] = isf[i - 1] + diff_hi[i] * (1.0f / (1 << 15));
00955 
00956     /* Scale the ISF vector for 16000 Hz */
00957     for (i = 0; i < LP_ORDER_16k - 1; i++)
00958         isf[i] *= 0.8;
00959 }
00960 
00970 static void lpc_weighting(float *out, const float *lpc, float gamma, int size)
00971 {
00972     int i;
00973     float fac = gamma;
00974 
00975     for (i = 0; i < size; i++) {
00976         out[i] = lpc[i] * fac;
00977         fac   *= gamma;
00978     }
00979 }
00980 
00992 static void hb_synthesis(AMRWBContext *ctx, int subframe, float *samples,
00993                          const float *exc, const float *isf, const float *isf_past)
00994 {
00995     float hb_lpc[LP_ORDER_16k];
00996     enum Mode mode = ctx->fr_cur_mode;
00997 
00998     if (mode == MODE_6k60) {
00999         float e_isf[LP_ORDER_16k]; // ISF vector for extrapolation
01000         double e_isp[LP_ORDER_16k];
01001 
01002         ff_weighted_vector_sumf(e_isf, isf_past, isf, isfp_inter[subframe],
01003                                 1.0 - isfp_inter[subframe], LP_ORDER);
01004 
01005         extrapolate_isf(e_isf);
01006 
01007         e_isf[LP_ORDER_16k - 1] *= 2.0;
01008         ff_acelp_lsf2lspd(e_isp, e_isf, LP_ORDER_16k);
01009         ff_amrwb_lsp2lpc(e_isp, hb_lpc, LP_ORDER_16k);
01010 
01011         lpc_weighting(hb_lpc, hb_lpc, 0.9, LP_ORDER_16k);
01012     } else {
01013         lpc_weighting(hb_lpc, ctx->lp_coef[subframe], 0.6, LP_ORDER);
01014     }
01015 
01016     ff_celp_lp_synthesis_filterf(samples, hb_lpc, exc, AMRWB_SFR_SIZE_16k,
01017                                  (mode == MODE_6k60) ? LP_ORDER_16k : LP_ORDER);
01018 }
01019 
01031 static void hb_fir_filter(float *out, const float fir_coef[HB_FIR_SIZE + 1],
01032                           float mem[HB_FIR_SIZE], const float *in)
01033 {
01034     int i, j;
01035     float data[AMRWB_SFR_SIZE_16k + HB_FIR_SIZE]; // past and current samples
01036 
01037     memcpy(data, mem, HB_FIR_SIZE * sizeof(float));
01038     memcpy(data + HB_FIR_SIZE, in, AMRWB_SFR_SIZE_16k * sizeof(float));
01039 
01040     for (i = 0; i < AMRWB_SFR_SIZE_16k; i++) {
01041         out[i] = 0.0;
01042         for (j = 0; j <= HB_FIR_SIZE; j++)
01043             out[i] += data[i + j] * fir_coef[j];
01044     }
01045 
01046     memcpy(mem, data + AMRWB_SFR_SIZE_16k, HB_FIR_SIZE * sizeof(float));
01047 }
01048 
01052 static void update_sub_state(AMRWBContext *ctx)
01053 {
01054     memmove(&ctx->excitation_buf[0], &ctx->excitation_buf[AMRWB_SFR_SIZE],
01055             (AMRWB_P_DELAY_MAX + LP_ORDER + 1) * sizeof(float));
01056 
01057     memmove(&ctx->pitch_gain[1], &ctx->pitch_gain[0], 5 * sizeof(float));
01058     memmove(&ctx->fixed_gain[1], &ctx->fixed_gain[0], 1 * sizeof(float));
01059 
01060     memmove(&ctx->samples_az[0], &ctx->samples_az[AMRWB_SFR_SIZE],
01061             LP_ORDER * sizeof(float));
01062     memmove(&ctx->samples_up[0], &ctx->samples_up[AMRWB_SFR_SIZE],
01063             UPS_MEM_SIZE * sizeof(float));
01064     memmove(&ctx->samples_hb[0], &ctx->samples_hb[AMRWB_SFR_SIZE_16k],
01065             LP_ORDER_16k * sizeof(float));
01066 }
01067 
01068 static int amrwb_decode_frame(AVCodecContext *avctx, void *data,
01069                               int *got_frame_ptr, AVPacket *avpkt)
01070 {
01071     AMRWBContext *ctx  = avctx->priv_data;
01072     AMRWBFrame   *cf   = &ctx->frame;
01073     const uint8_t *buf = avpkt->data;
01074     int buf_size       = avpkt->size;
01075     int expected_fr_size, header_size;
01076     float *buf_out;
01077     float spare_vector[AMRWB_SFR_SIZE];      // extra stack space to hold result from anti-sparseness processing
01078     float fixed_gain_factor;                 // fixed gain correction factor (gamma)
01079     float *synth_fixed_vector;               // pointer to the fixed vector that synthesis should use
01080     float synth_fixed_gain;                  // the fixed gain that synthesis should use
01081     float voice_fac, stab_fac;               // parameters used for gain smoothing
01082     float synth_exc[AMRWB_SFR_SIZE];         // post-processed excitation for synthesis
01083     float hb_exc[AMRWB_SFR_SIZE_16k];        // excitation for the high frequency band
01084     float hb_samples[AMRWB_SFR_SIZE_16k];    // filtered high-band samples from synthesis
01085     float hb_gain;
01086     int sub, i, ret;
01087 
01088     /* get output buffer */
01089     ctx->avframe.nb_samples = 4 * AMRWB_SFR_SIZE_16k;
01090     if ((ret = avctx->get_buffer(avctx, &ctx->avframe)) < 0) {
01091         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
01092         return ret;
01093     }
01094     buf_out = (float *)ctx->avframe.data[0];
01095 
01096     header_size      = decode_mime_header(ctx, buf);
01097     if (ctx->fr_cur_mode > MODE_SID) {
01098         av_log(avctx, AV_LOG_ERROR,
01099                "Invalid mode %d\n", ctx->fr_cur_mode);
01100         return AVERROR_INVALIDDATA;
01101     }
01102     expected_fr_size = ((cf_sizes_wb[ctx->fr_cur_mode] + 7) >> 3) + 1;
01103 
01104     if (buf_size < expected_fr_size) {
01105         av_log(avctx, AV_LOG_ERROR,
01106             "Frame too small (%d bytes). Truncated file?\n", buf_size);
01107         *got_frame_ptr = 0;
01108         return AVERROR_INVALIDDATA;
01109     }
01110 
01111     if (!ctx->fr_quality || ctx->fr_cur_mode > MODE_SID)
01112         av_log(avctx, AV_LOG_ERROR, "Encountered a bad or corrupted frame\n");
01113 
01114     if (ctx->fr_cur_mode == MODE_SID) { /* Comfort noise frame */
01115         av_log_missing_feature(avctx, "SID mode", 1);
01116         return -1;
01117     }
01118 
01119     ff_amr_bit_reorder((uint16_t *) &ctx->frame, sizeof(AMRWBFrame),
01120         buf + header_size, amr_bit_orderings_by_mode[ctx->fr_cur_mode]);
01121 
01122     /* Decode the quantized ISF vector */
01123     if (ctx->fr_cur_mode == MODE_6k60) {
01124         decode_isf_indices_36b(cf->isp_id, ctx->isf_cur);
01125     } else {
01126         decode_isf_indices_46b(cf->isp_id, ctx->isf_cur);
01127     }
01128 
01129     isf_add_mean_and_past(ctx->isf_cur, ctx->isf_q_past);
01130     ff_set_min_dist_lsf(ctx->isf_cur, MIN_ISF_SPACING, LP_ORDER - 1);
01131 
01132     stab_fac = stability_factor(ctx->isf_cur, ctx->isf_past_final);
01133 
01134     ctx->isf_cur[LP_ORDER - 1] *= 2.0;
01135     ff_acelp_lsf2lspd(ctx->isp[3], ctx->isf_cur, LP_ORDER);
01136 
01137     /* Generate a ISP vector for each subframe */
01138     if (ctx->first_frame) {
01139         ctx->first_frame = 0;
01140         memcpy(ctx->isp_sub4_past, ctx->isp[3], LP_ORDER * sizeof(double));
01141     }
01142     interpolate_isp(ctx->isp, ctx->isp_sub4_past);
01143 
01144     for (sub = 0; sub < 4; sub++)
01145         ff_amrwb_lsp2lpc(ctx->isp[sub], ctx->lp_coef[sub], LP_ORDER);
01146 
01147     for (sub = 0; sub < 4; sub++) {
01148         const AMRWBSubFrame *cur_subframe = &cf->subframe[sub];
01149         float *sub_buf = buf_out + sub * AMRWB_SFR_SIZE_16k;
01150 
01151         /* Decode adaptive codebook (pitch vector) */
01152         decode_pitch_vector(ctx, cur_subframe, sub);
01153         /* Decode innovative codebook (fixed vector) */
01154         decode_fixed_vector(ctx->fixed_vector, cur_subframe->pul_ih,
01155                             cur_subframe->pul_il, ctx->fr_cur_mode);
01156 
01157         pitch_sharpening(ctx, ctx->fixed_vector);
01158 
01159         decode_gains(cur_subframe->vq_gain, ctx->fr_cur_mode,
01160                      &fixed_gain_factor, &ctx->pitch_gain[0]);
01161 
01162         ctx->fixed_gain[0] =
01163             ff_amr_set_fixed_gain(fixed_gain_factor,
01164                        ff_dot_productf(ctx->fixed_vector, ctx->fixed_vector,
01165                                        AMRWB_SFR_SIZE) / AMRWB_SFR_SIZE,
01166                        ctx->prediction_error,
01167                        ENERGY_MEAN, energy_pred_fac);
01168 
01169         /* Calculate voice factor and store tilt for next subframe */
01170         voice_fac      = voice_factor(ctx->pitch_vector, ctx->pitch_gain[0],
01171                                       ctx->fixed_vector, ctx->fixed_gain[0]);
01172         ctx->tilt_coef = voice_fac * 0.25 + 0.25;
01173 
01174         /* Construct current excitation */
01175         for (i = 0; i < AMRWB_SFR_SIZE; i++) {
01176             ctx->excitation[i] *= ctx->pitch_gain[0];
01177             ctx->excitation[i] += ctx->fixed_gain[0] * ctx->fixed_vector[i];
01178             ctx->excitation[i] = truncf(ctx->excitation[i]);
01179         }
01180 
01181         /* Post-processing of excitation elements */
01182         synth_fixed_gain = noise_enhancer(ctx->fixed_gain[0], &ctx->prev_tr_gain,
01183                                           voice_fac, stab_fac);
01184 
01185         synth_fixed_vector = anti_sparseness(ctx, ctx->fixed_vector,
01186                                              spare_vector);
01187 
01188         pitch_enhancer(synth_fixed_vector, voice_fac);
01189 
01190         synthesis(ctx, ctx->lp_coef[sub], synth_exc, synth_fixed_gain,
01191                   synth_fixed_vector, &ctx->samples_az[LP_ORDER]);
01192 
01193         /* Synthesis speech post-processing */
01194         de_emphasis(&ctx->samples_up[UPS_MEM_SIZE],
01195                     &ctx->samples_az[LP_ORDER], PREEMPH_FAC, ctx->demph_mem);
01196 
01197         ff_acelp_apply_order_2_transfer_function(&ctx->samples_up[UPS_MEM_SIZE],
01198             &ctx->samples_up[UPS_MEM_SIZE], hpf_zeros, hpf_31_poles,
01199             hpf_31_gain, ctx->hpf_31_mem, AMRWB_SFR_SIZE);
01200 
01201         upsample_5_4(sub_buf, &ctx->samples_up[UPS_FIR_SIZE],
01202                      AMRWB_SFR_SIZE_16k);
01203 
01204         /* High frequency band (6.4 - 7.0 kHz) generation part */
01205         ff_acelp_apply_order_2_transfer_function(hb_samples,
01206             &ctx->samples_up[UPS_MEM_SIZE], hpf_zeros, hpf_400_poles,
01207             hpf_400_gain, ctx->hpf_400_mem, AMRWB_SFR_SIZE);
01208 
01209         hb_gain = find_hb_gain(ctx, hb_samples,
01210                                cur_subframe->hb_gain, cf->vad);
01211 
01212         scaled_hb_excitation(ctx, hb_exc, synth_exc, hb_gain);
01213 
01214         hb_synthesis(ctx, sub, &ctx->samples_hb[LP_ORDER_16k],
01215                      hb_exc, ctx->isf_cur, ctx->isf_past_final);
01216 
01217         /* High-band post-processing filters */
01218         hb_fir_filter(hb_samples, bpf_6_7_coef, ctx->bpf_6_7_mem,
01219                       &ctx->samples_hb[LP_ORDER_16k]);
01220 
01221         if (ctx->fr_cur_mode == MODE_23k85)
01222             hb_fir_filter(hb_samples, lpf_7_coef, ctx->lpf_7_mem,
01223                           hb_samples);
01224 
01225         /* Add the low and high frequency bands */
01226         for (i = 0; i < AMRWB_SFR_SIZE_16k; i++)
01227             sub_buf[i] = (sub_buf[i] + hb_samples[i]) * (1.0f / (1 << 15));
01228 
01229         /* Update buffers and history */
01230         update_sub_state(ctx);
01231     }
01232 
01233     /* update state for next frame */
01234     memcpy(ctx->isp_sub4_past, ctx->isp[3], LP_ORDER * sizeof(ctx->isp[3][0]));
01235     memcpy(ctx->isf_past_final, ctx->isf_cur, LP_ORDER * sizeof(float));
01236 
01237     *got_frame_ptr   = 1;
01238     *(AVFrame *)data = ctx->avframe;
01239 
01240     return expected_fr_size;
01241 }
01242 
01243 AVCodec ff_amrwb_decoder = {
01244     .name           = "amrwb",
01245     .type           = AVMEDIA_TYPE_AUDIO,
01246     .id             = CODEC_ID_AMR_WB,
01247     .priv_data_size = sizeof(AMRWBContext),
01248     .init           = amrwb_decode_init,
01249     .decode         = amrwb_decode_frame,
01250     .capabilities   = CODEC_CAP_DR1,
01251     .long_name      = NULL_IF_CONFIG_SMALL("Adaptive Multi-Rate WideBand"),
01252     .sample_fmts    = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_FLT,AV_SAMPLE_FMT_NONE},
01253 };