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