libavcodec/amrnbdec.c
Go to the documentation of this file.
00001 /*
00002  * AMR narrowband decoder
00003  * Copyright (c) 2006-2007 Robert Swain
00004  * Copyright (c) 2009 Colin McQuillan
00005  *
00006  * This file is part of Libav.
00007  *
00008  * Libav is free software; you can redistribute it and/or
00009  * modify it under the terms of the GNU Lesser General Public
00010  * License as published by the Free Software Foundation; either
00011  * version 2.1 of the License, or (at your option) any later version.
00012  *
00013  * Libav is distributed in the hope that it will be useful,
00014  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00015  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00016  * Lesser General Public License for more details.
00017  *
00018  * You should have received a copy of the GNU Lesser General Public
00019  * License along with Libav; if not, write to the Free Software
00020  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00021  */
00022 
00023 
00043 #include <string.h>
00044 #include <math.h>
00045 
00046 #include "avcodec.h"
00047 #include "internal.h"
00048 #include "get_bits.h"
00049 #include "libavutil/common.h"
00050 #include "celp_math.h"
00051 #include "celp_filters.h"
00052 #include "acelp_filters.h"
00053 #include "acelp_vectors.h"
00054 #include "acelp_pitch_delay.h"
00055 #include "lsp.h"
00056 #include "amr.h"
00057 
00058 #include "amrnbdata.h"
00059 
00060 #define AMR_BLOCK_SIZE              160   ///< samples per frame
00061 #define AMR_SAMPLE_BOUND        32768.0   ///< threshold for synthesis overflow
00062 
00072 #define AMR_SAMPLE_SCALE  (2.0 / 32768.0)
00073 
00075 #define PRED_FAC_MODE_12k2             0.65
00076 
00077 #define LSF_R_FAC          (8000.0 / 32768.0) ///< LSF residual tables to Hertz
00078 #define MIN_LSF_SPACING    (50.0488 / 8000.0) ///< Ensures stability of LPC filter
00079 #define PITCH_LAG_MIN_MODE_12k2          18   ///< Lower bound on decoded lag search in 12.2kbit/s mode
00080 
00082 #define MIN_ENERGY -14.0
00083 
00089 #define SHARP_MAX 0.79449462890625
00090 
00092 #define AMR_TILT_RESPONSE   22
00093 
00094 #define AMR_TILT_GAMMA_T   0.8
00095 
00096 #define AMR_AGC_ALPHA      0.9
00097 
00098 typedef struct AMRContext {
00099     AVFrame                         avframe; 
00100     AMRNBFrame                        frame; 
00101     uint8_t             bad_frame_indicator; 
00102     enum Mode                cur_frame_mode;
00103 
00104     int16_t     prev_lsf_r[LP_FILTER_ORDER]; 
00105     double          lsp[4][LP_FILTER_ORDER]; 
00106     double   prev_lsp_sub4[LP_FILTER_ORDER]; 
00107 
00108     float         lsf_q[4][LP_FILTER_ORDER]; 
00109     float          lsf_avg[LP_FILTER_ORDER]; 
00110 
00111     float           lpc[4][LP_FILTER_ORDER]; 
00112 
00113     uint8_t                   pitch_lag_int; 
00114 
00115     float excitation_buf[PITCH_DELAY_MAX + LP_FILTER_ORDER + 1 + AMR_SUBFRAME_SIZE]; 
00116     float                       *excitation; 
00117 
00118     float   pitch_vector[AMR_SUBFRAME_SIZE]; 
00119     float   fixed_vector[AMR_SUBFRAME_SIZE]; 
00120 
00121     float               prediction_error[4]; 
00122     float                     pitch_gain[5]; 
00123     float                     fixed_gain[5]; 
00124 
00125     float                              beta; 
00126     uint8_t                      diff_count; 
00127     uint8_t                      hang_count; 
00128 
00129     float            prev_sparse_fixed_gain; 
00130     uint8_t               prev_ir_filter_nr; 
00131     uint8_t                 ir_filter_onset; 
00132 
00133     float                postfilter_mem[10]; 
00134     float                          tilt_mem; 
00135     float                    postfilter_agc; 
00136     float                  high_pass_mem[2]; 
00137 
00138     float samples_in[LP_FILTER_ORDER + AMR_SUBFRAME_SIZE]; 
00139 
00140 } AMRContext;
00141 
00143 static void weighted_vector_sumd(double *out, const double *in_a,
00144                                  const double *in_b, double weight_coeff_a,
00145                                  double weight_coeff_b, int length)
00146 {
00147     int i;
00148 
00149     for (i = 0; i < length; i++)
00150         out[i] = weight_coeff_a * in_a[i]
00151                + weight_coeff_b * in_b[i];
00152 }
00153 
00154 static av_cold int amrnb_decode_init(AVCodecContext *avctx)
00155 {
00156     AMRContext *p = avctx->priv_data;
00157     int i;
00158 
00159     avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
00160 
00161     // p->excitation always points to the same position in p->excitation_buf
00162     p->excitation = &p->excitation_buf[PITCH_DELAY_MAX + LP_FILTER_ORDER + 1];
00163 
00164     for (i = 0; i < LP_FILTER_ORDER; i++) {
00165         p->prev_lsp_sub4[i] =    lsp_sub4_init[i] * 1000 / (float)(1 << 15);
00166         p->lsf_avg[i] = p->lsf_q[3][i] = lsp_avg_init[i] / (float)(1 << 15);
00167     }
00168 
00169     for (i = 0; i < 4; i++)
00170         p->prediction_error[i] = MIN_ENERGY;
00171 
00172     avcodec_get_frame_defaults(&p->avframe);
00173     avctx->coded_frame = &p->avframe;
00174 
00175     return 0;
00176 }
00177 
00178 
00190 static enum Mode unpack_bitstream(AMRContext *p, const uint8_t *buf,
00191                                   int buf_size)
00192 {
00193     GetBitContext gb;
00194     enum Mode mode;
00195 
00196     init_get_bits(&gb, buf, buf_size * 8);
00197 
00198     // Decode the first octet.
00199     skip_bits(&gb, 1);                        // padding bit
00200     mode = get_bits(&gb, 4);                  // frame type
00201     p->bad_frame_indicator = !get_bits1(&gb); // quality bit
00202     skip_bits(&gb, 2);                        // two padding bits
00203 
00204     if (mode >= N_MODES || buf_size < frame_sizes_nb[mode] + 1) {
00205         return NO_DATA;
00206     }
00207 
00208     if (mode < MODE_DTX)
00209         ff_amr_bit_reorder((uint16_t *) &p->frame, sizeof(AMRNBFrame), buf + 1,
00210                            amr_unpacking_bitmaps_per_mode[mode]);
00211 
00212     return mode;
00213 }
00214 
00215 
00218 
00226 static void interpolate_lsf(float lsf_q[4][LP_FILTER_ORDER], float *lsf_new)
00227 {
00228     int i;
00229 
00230     for (i = 0; i < 4; i++)
00231         ff_weighted_vector_sumf(lsf_q[i], lsf_q[3], lsf_new,
00232                                 0.25 * (3 - i), 0.25 * (i + 1),
00233                                 LP_FILTER_ORDER);
00234 }
00235 
00247 static void lsf2lsp_for_mode12k2(AMRContext *p, double lsp[LP_FILTER_ORDER],
00248                                  const float lsf_no_r[LP_FILTER_ORDER],
00249                                  const int16_t *lsf_quantizer[5],
00250                                  const int quantizer_offset,
00251                                  const int sign, const int update)
00252 {
00253     int16_t lsf_r[LP_FILTER_ORDER]; // residual LSF vector
00254     float lsf_q[LP_FILTER_ORDER]; // quantified LSF vector
00255     int i;
00256 
00257     for (i = 0; i < LP_FILTER_ORDER >> 1; i++)
00258         memcpy(&lsf_r[i << 1], &lsf_quantizer[i][quantizer_offset],
00259                2 * sizeof(*lsf_r));
00260 
00261     if (sign) {
00262         lsf_r[4] *= -1;
00263         lsf_r[5] *= -1;
00264     }
00265 
00266     if (update)
00267         memcpy(p->prev_lsf_r, lsf_r, LP_FILTER_ORDER * sizeof(*lsf_r));
00268 
00269     for (i = 0; i < LP_FILTER_ORDER; i++)
00270         lsf_q[i] = lsf_r[i] * (LSF_R_FAC / 8000.0) + lsf_no_r[i] * (1.0 / 8000.0);
00271 
00272     ff_set_min_dist_lsf(lsf_q, MIN_LSF_SPACING, LP_FILTER_ORDER);
00273 
00274     if (update)
00275         interpolate_lsf(p->lsf_q, lsf_q);
00276 
00277     ff_acelp_lsf2lspd(lsp, lsf_q, LP_FILTER_ORDER);
00278 }
00279 
00285 static void lsf2lsp_5(AMRContext *p)
00286 {
00287     const uint16_t *lsf_param = p->frame.lsf;
00288     float lsf_no_r[LP_FILTER_ORDER]; // LSFs without the residual vector
00289     const int16_t *lsf_quantizer[5];
00290     int i;
00291 
00292     lsf_quantizer[0] = lsf_5_1[lsf_param[0]];
00293     lsf_quantizer[1] = lsf_5_2[lsf_param[1]];
00294     lsf_quantizer[2] = lsf_5_3[lsf_param[2] >> 1];
00295     lsf_quantizer[3] = lsf_5_4[lsf_param[3]];
00296     lsf_quantizer[4] = lsf_5_5[lsf_param[4]];
00297 
00298     for (i = 0; i < LP_FILTER_ORDER; i++)
00299         lsf_no_r[i] = p->prev_lsf_r[i] * LSF_R_FAC * PRED_FAC_MODE_12k2 + lsf_5_mean[i];
00300 
00301     lsf2lsp_for_mode12k2(p, p->lsp[1], lsf_no_r, lsf_quantizer, 0, lsf_param[2] & 1, 0);
00302     lsf2lsp_for_mode12k2(p, p->lsp[3], lsf_no_r, lsf_quantizer, 2, lsf_param[2] & 1, 1);
00303 
00304     // interpolate LSP vectors at subframes 1 and 3
00305     weighted_vector_sumd(p->lsp[0], p->prev_lsp_sub4, p->lsp[1], 0.5, 0.5, LP_FILTER_ORDER);
00306     weighted_vector_sumd(p->lsp[2], p->lsp[1]       , p->lsp[3], 0.5, 0.5, LP_FILTER_ORDER);
00307 }
00308 
00314 static void lsf2lsp_3(AMRContext *p)
00315 {
00316     const uint16_t *lsf_param = p->frame.lsf;
00317     int16_t lsf_r[LP_FILTER_ORDER]; // residual LSF vector
00318     float lsf_q[LP_FILTER_ORDER]; // quantified LSF vector
00319     const int16_t *lsf_quantizer;
00320     int i, j;
00321 
00322     lsf_quantizer = (p->cur_frame_mode == MODE_7k95 ? lsf_3_1_MODE_7k95 : lsf_3_1)[lsf_param[0]];
00323     memcpy(lsf_r, lsf_quantizer, 3 * sizeof(*lsf_r));
00324 
00325     lsf_quantizer = lsf_3_2[lsf_param[1] << (p->cur_frame_mode <= MODE_5k15)];
00326     memcpy(lsf_r + 3, lsf_quantizer, 3 * sizeof(*lsf_r));
00327 
00328     lsf_quantizer = (p->cur_frame_mode <= MODE_5k15 ? lsf_3_3_MODE_5k15 : lsf_3_3)[lsf_param[2]];
00329     memcpy(lsf_r + 6, lsf_quantizer, 4 * sizeof(*lsf_r));
00330 
00331     // calculate mean-removed LSF vector and add mean
00332     for (i = 0; i < LP_FILTER_ORDER; i++)
00333         lsf_q[i] = (lsf_r[i] + p->prev_lsf_r[i] * pred_fac[i]) * (LSF_R_FAC / 8000.0) + lsf_3_mean[i] * (1.0 / 8000.0);
00334 
00335     ff_set_min_dist_lsf(lsf_q, MIN_LSF_SPACING, LP_FILTER_ORDER);
00336 
00337     // store data for computing the next frame's LSFs
00338     interpolate_lsf(p->lsf_q, lsf_q);
00339     memcpy(p->prev_lsf_r, lsf_r, LP_FILTER_ORDER * sizeof(*lsf_r));
00340 
00341     ff_acelp_lsf2lspd(p->lsp[3], lsf_q, LP_FILTER_ORDER);
00342 
00343     // interpolate LSP vectors at subframes 1, 2 and 3
00344     for (i = 1; i <= 3; i++)
00345         for(j = 0; j < LP_FILTER_ORDER; j++)
00346             p->lsp[i-1][j] = p->prev_lsp_sub4[j] +
00347                 (p->lsp[3][j] - p->prev_lsp_sub4[j]) * 0.25 * i;
00348 }
00349 
00351 
00352 
00355 
00359 static void decode_pitch_lag_1_6(int *lag_int, int *lag_frac, int pitch_index,
00360                                  const int prev_lag_int, const int subframe)
00361 {
00362     if (subframe == 0 || subframe == 2) {
00363         if (pitch_index < 463) {
00364             *lag_int  = (pitch_index + 107) * 10923 >> 16;
00365             *lag_frac = pitch_index - *lag_int * 6 + 105;
00366         } else {
00367             *lag_int  = pitch_index - 368;
00368             *lag_frac = 0;
00369         }
00370     } else {
00371         *lag_int  = ((pitch_index + 5) * 10923 >> 16) - 1;
00372         *lag_frac = pitch_index - *lag_int * 6 - 3;
00373         *lag_int += av_clip(prev_lag_int - 5, PITCH_LAG_MIN_MODE_12k2,
00374                             PITCH_DELAY_MAX - 9);
00375     }
00376 }
00377 
00378 static void decode_pitch_vector(AMRContext *p,
00379                                 const AMRNBSubframe *amr_subframe,
00380                                 const int subframe)
00381 {
00382     int pitch_lag_int, pitch_lag_frac;
00383     enum Mode mode = p->cur_frame_mode;
00384 
00385     if (p->cur_frame_mode == MODE_12k2) {
00386         decode_pitch_lag_1_6(&pitch_lag_int, &pitch_lag_frac,
00387                              amr_subframe->p_lag, p->pitch_lag_int,
00388                              subframe);
00389     } else
00390         ff_decode_pitch_lag(&pitch_lag_int, &pitch_lag_frac,
00391                             amr_subframe->p_lag,
00392                             p->pitch_lag_int, subframe,
00393                             mode != MODE_4k75 && mode != MODE_5k15,
00394                             mode <= MODE_6k7 ? 4 : (mode == MODE_7k95 ? 5 : 6));
00395 
00396     p->pitch_lag_int = pitch_lag_int; // store previous lag in a uint8_t
00397 
00398     pitch_lag_frac <<= (p->cur_frame_mode != MODE_12k2);
00399 
00400     pitch_lag_int += pitch_lag_frac > 0;
00401 
00402     /* Calculate the pitch vector by interpolating the past excitation at the
00403        pitch lag using a b60 hamming windowed sinc function.   */
00404     ff_acelp_interpolatef(p->excitation, p->excitation + 1 - pitch_lag_int,
00405                           ff_b60_sinc, 6,
00406                           pitch_lag_frac + 6 - 6*(pitch_lag_frac > 0),
00407                           10, AMR_SUBFRAME_SIZE);
00408 
00409     memcpy(p->pitch_vector, p->excitation, AMR_SUBFRAME_SIZE * sizeof(float));
00410 }
00411 
00413 
00414 
00417 
00421 static void decode_10bit_pulse(int code, int pulse_position[8],
00422                                int i1, int i2, int i3)
00423 {
00424     // coded using 7+3 bits with the 3 LSBs being, individually, the LSB of 1 of
00425     // the 3 pulses and the upper 7 bits being coded in base 5
00426     const uint8_t *positions = base_five_table[code >> 3];
00427     pulse_position[i1] = (positions[2] << 1) + ( code       & 1);
00428     pulse_position[i2] = (positions[1] << 1) + ((code >> 1) & 1);
00429     pulse_position[i3] = (positions[0] << 1) + ((code >> 2) & 1);
00430 }
00431 
00439 static void decode_8_pulses_31bits(const int16_t *fixed_index,
00440                                    AMRFixed *fixed_sparse)
00441 {
00442     int pulse_position[8];
00443     int i, temp;
00444 
00445     decode_10bit_pulse(fixed_index[4], pulse_position, 0, 4, 1);
00446     decode_10bit_pulse(fixed_index[5], pulse_position, 2, 6, 5);
00447 
00448     // coded using 5+2 bits with the 2 LSBs being, individually, the LSB of 1 of
00449     // the 2 pulses and the upper 5 bits being coded in base 5
00450     temp = ((fixed_index[6] >> 2) * 25 + 12) >> 5;
00451     pulse_position[3] = temp % 5;
00452     pulse_position[7] = temp / 5;
00453     if (pulse_position[7] & 1)
00454         pulse_position[3] = 4 - pulse_position[3];
00455     pulse_position[3] = (pulse_position[3] << 1) + ( fixed_index[6]       & 1);
00456     pulse_position[7] = (pulse_position[7] << 1) + ((fixed_index[6] >> 1) & 1);
00457 
00458     fixed_sparse->n = 8;
00459     for (i = 0; i < 4; i++) {
00460         const int pos1   = (pulse_position[i]     << 2) + i;
00461         const int pos2   = (pulse_position[i + 4] << 2) + i;
00462         const float sign = fixed_index[i] ? -1.0 : 1.0;
00463         fixed_sparse->x[i    ] = pos1;
00464         fixed_sparse->x[i + 4] = pos2;
00465         fixed_sparse->y[i    ] = sign;
00466         fixed_sparse->y[i + 4] = pos2 < pos1 ? -sign : sign;
00467     }
00468 }
00469 
00485 static void decode_fixed_sparse(AMRFixed *fixed_sparse, const uint16_t *pulses,
00486                                 const enum Mode mode, const int subframe)
00487 {
00488     assert(MODE_4k75 <= mode && mode <= MODE_12k2);
00489 
00490     if (mode == MODE_12k2) {
00491         ff_decode_10_pulses_35bits(pulses, fixed_sparse, gray_decode, 5, 3);
00492     } else if (mode == MODE_10k2) {
00493         decode_8_pulses_31bits(pulses, fixed_sparse);
00494     } else {
00495         int *pulse_position = fixed_sparse->x;
00496         int i, pulse_subset;
00497         const int fixed_index = pulses[0];
00498 
00499         if (mode <= MODE_5k15) {
00500             pulse_subset      = ((fixed_index >> 3) & 8)     + (subframe << 1);
00501             pulse_position[0] = ( fixed_index       & 7) * 5 + track_position[pulse_subset];
00502             pulse_position[1] = ((fixed_index >> 3) & 7) * 5 + track_position[pulse_subset + 1];
00503             fixed_sparse->n = 2;
00504         } else if (mode == MODE_5k9) {
00505             pulse_subset      = ((fixed_index & 1) << 1) + 1;
00506             pulse_position[0] = ((fixed_index >> 1) & 7) * 5 + pulse_subset;
00507             pulse_subset      = (fixed_index  >> 4) & 3;
00508             pulse_position[1] = ((fixed_index >> 6) & 7) * 5 + pulse_subset + (pulse_subset == 3 ? 1 : 0);
00509             fixed_sparse->n = pulse_position[0] == pulse_position[1] ? 1 : 2;
00510         } else if (mode == MODE_6k7) {
00511             pulse_position[0] = (fixed_index        & 7) * 5;
00512             pulse_subset      = (fixed_index  >> 2) & 2;
00513             pulse_position[1] = ((fixed_index >> 4) & 7) * 5 + pulse_subset + 1;
00514             pulse_subset      = (fixed_index  >> 6) & 2;
00515             pulse_position[2] = ((fixed_index >> 8) & 7) * 5 + pulse_subset + 2;
00516             fixed_sparse->n = 3;
00517         } else { // mode <= MODE_7k95
00518             pulse_position[0] = gray_decode[ fixed_index        & 7];
00519             pulse_position[1] = gray_decode[(fixed_index >> 3)  & 7] + 1;
00520             pulse_position[2] = gray_decode[(fixed_index >> 6)  & 7] + 2;
00521             pulse_subset      = (fixed_index >> 9) & 1;
00522             pulse_position[3] = gray_decode[(fixed_index >> 10) & 7] + pulse_subset + 3;
00523             fixed_sparse->n = 4;
00524         }
00525         for (i = 0; i < fixed_sparse->n; i++)
00526             fixed_sparse->y[i] = (pulses[1] >> i) & 1 ? 1.0 : -1.0;
00527     }
00528 }
00529 
00538 static void pitch_sharpening(AMRContext *p, int subframe, enum Mode mode,
00539                              AMRFixed *fixed_sparse)
00540 {
00541     // The spec suggests the current pitch gain is always used, but in other
00542     // modes the pitch and codebook gains are joinly quantized (sec 5.8.2)
00543     // so the codebook gain cannot depend on the quantized pitch gain.
00544     if (mode == MODE_12k2)
00545         p->beta = FFMIN(p->pitch_gain[4], 1.0);
00546 
00547     fixed_sparse->pitch_lag  = p->pitch_lag_int;
00548     fixed_sparse->pitch_fac  = p->beta;
00549 
00550     // Save pitch sharpening factor for the next subframe
00551     // MODE_4k75 only updates on the 2nd and 4th subframes - this follows from
00552     // the fact that the gains for two subframes are jointly quantized.
00553     if (mode != MODE_4k75 || subframe & 1)
00554         p->beta = av_clipf(p->pitch_gain[4], 0.0, SHARP_MAX);
00555 }
00557 
00558 
00561 
00574 static float fixed_gain_smooth(AMRContext *p , const float *lsf,
00575                                const float *lsf_avg, const enum Mode mode)
00576 {
00577     float diff = 0.0;
00578     int i;
00579 
00580     for (i = 0; i < LP_FILTER_ORDER; i++)
00581         diff += fabs(lsf_avg[i] - lsf[i]) / lsf_avg[i];
00582 
00583     // If diff is large for ten subframes, disable smoothing for a 40-subframe
00584     // hangover period.
00585     p->diff_count++;
00586     if (diff <= 0.65)
00587         p->diff_count = 0;
00588 
00589     if (p->diff_count > 10) {
00590         p->hang_count = 0;
00591         p->diff_count--; // don't let diff_count overflow
00592     }
00593 
00594     if (p->hang_count < 40) {
00595         p->hang_count++;
00596     } else if (mode < MODE_7k4 || mode == MODE_10k2) {
00597         const float smoothing_factor = av_clipf(4.0 * diff - 1.6, 0.0, 1.0);
00598         const float fixed_gain_mean = (p->fixed_gain[0] + p->fixed_gain[1] +
00599                                        p->fixed_gain[2] + p->fixed_gain[3] +
00600                                        p->fixed_gain[4]) * 0.2;
00601         return smoothing_factor * p->fixed_gain[4] +
00602                (1.0 - smoothing_factor) * fixed_gain_mean;
00603     }
00604     return p->fixed_gain[4];
00605 }
00606 
00616 static void decode_gains(AMRContext *p, const AMRNBSubframe *amr_subframe,
00617                          const enum Mode mode, const int subframe,
00618                          float *fixed_gain_factor)
00619 {
00620     if (mode == MODE_12k2 || mode == MODE_7k95) {
00621         p->pitch_gain[4]   = qua_gain_pit [amr_subframe->p_gain    ]
00622             * (1.0 / 16384.0);
00623         *fixed_gain_factor = qua_gain_code[amr_subframe->fixed_gain]
00624             * (1.0 /  2048.0);
00625     } else {
00626         const uint16_t *gains;
00627 
00628         if (mode >= MODE_6k7) {
00629             gains = gains_high[amr_subframe->p_gain];
00630         } else if (mode >= MODE_5k15) {
00631             gains = gains_low [amr_subframe->p_gain];
00632         } else {
00633             // gain index is only coded in subframes 0,2 for MODE_4k75
00634             gains = gains_MODE_4k75[(p->frame.subframe[subframe & 2].p_gain << 1) + (subframe & 1)];
00635         }
00636 
00637         p->pitch_gain[4]   = gains[0] * (1.0 / 16384.0);
00638         *fixed_gain_factor = gains[1] * (1.0 /  4096.0);
00639     }
00640 }
00641 
00643 
00644 
00647 
00658 static void apply_ir_filter(float *out, const AMRFixed *in,
00659                             const float *filter)
00660 {
00661     float filter1[AMR_SUBFRAME_SIZE],     
00662           filter2[AMR_SUBFRAME_SIZE];
00663     int   lag = in->pitch_lag;
00664     float fac = in->pitch_fac;
00665     int i;
00666 
00667     if (lag < AMR_SUBFRAME_SIZE) {
00668         ff_celp_circ_addf(filter1, filter, filter, lag, fac,
00669                           AMR_SUBFRAME_SIZE);
00670 
00671         if (lag < AMR_SUBFRAME_SIZE >> 1)
00672             ff_celp_circ_addf(filter2, filter, filter1, lag, fac,
00673                               AMR_SUBFRAME_SIZE);
00674     }
00675 
00676     memset(out, 0, sizeof(float) * AMR_SUBFRAME_SIZE);
00677     for (i = 0; i < in->n; i++) {
00678         int   x = in->x[i];
00679         float y = in->y[i];
00680         const float *filterp;
00681 
00682         if (x >= AMR_SUBFRAME_SIZE - lag) {
00683             filterp = filter;
00684         } else if (x >= AMR_SUBFRAME_SIZE - (lag << 1)) {
00685             filterp = filter1;
00686         } else
00687             filterp = filter2;
00688 
00689         ff_celp_circ_addf(out, out, filterp, x, y, AMR_SUBFRAME_SIZE);
00690     }
00691 }
00692 
00705 static const float *anti_sparseness(AMRContext *p, AMRFixed *fixed_sparse,
00706                                     const float *fixed_vector,
00707                                     float fixed_gain, float *out)
00708 {
00709     int ir_filter_nr;
00710 
00711     if (p->pitch_gain[4] < 0.6) {
00712         ir_filter_nr = 0;      // strong filtering
00713     } else if (p->pitch_gain[4] < 0.9) {
00714         ir_filter_nr = 1;      // medium filtering
00715     } else
00716         ir_filter_nr = 2;      // no filtering
00717 
00718     // detect 'onset'
00719     if (fixed_gain > 2.0 * p->prev_sparse_fixed_gain) {
00720         p->ir_filter_onset = 2;
00721     } else if (p->ir_filter_onset)
00722         p->ir_filter_onset--;
00723 
00724     if (!p->ir_filter_onset) {
00725         int i, count = 0;
00726 
00727         for (i = 0; i < 5; i++)
00728             if (p->pitch_gain[i] < 0.6)
00729                 count++;
00730         if (count > 2)
00731             ir_filter_nr = 0;
00732 
00733         if (ir_filter_nr > p->prev_ir_filter_nr + 1)
00734             ir_filter_nr--;
00735     } else if (ir_filter_nr < 2)
00736         ir_filter_nr++;
00737 
00738     // Disable filtering for very low level of fixed_gain.
00739     // Note this step is not specified in the technical description but is in
00740     // the reference source in the function Ph_disp.
00741     if (fixed_gain < 5.0)
00742         ir_filter_nr = 2;
00743 
00744     if (p->cur_frame_mode != MODE_7k4 && p->cur_frame_mode < MODE_10k2
00745          && ir_filter_nr < 2) {
00746         apply_ir_filter(out, fixed_sparse,
00747                         (p->cur_frame_mode == MODE_7k95 ?
00748                              ir_filters_lookup_MODE_7k95 :
00749                              ir_filters_lookup)[ir_filter_nr]);
00750         fixed_vector = out;
00751     }
00752 
00753     // update ir filter strength history
00754     p->prev_ir_filter_nr       = ir_filter_nr;
00755     p->prev_sparse_fixed_gain  = fixed_gain;
00756 
00757     return fixed_vector;
00758 }
00759 
00761 
00762 
00765 
00776 static int synthesis(AMRContext *p, float *lpc,
00777                      float fixed_gain, const float *fixed_vector,
00778                      float *samples, uint8_t overflow)
00779 {
00780     int i;
00781     float excitation[AMR_SUBFRAME_SIZE];
00782 
00783     // if an overflow has been detected, the pitch vector is scaled down by a
00784     // factor of 4
00785     if (overflow)
00786         for (i = 0; i < AMR_SUBFRAME_SIZE; i++)
00787             p->pitch_vector[i] *= 0.25;
00788 
00789     ff_weighted_vector_sumf(excitation, p->pitch_vector, fixed_vector,
00790                             p->pitch_gain[4], fixed_gain, AMR_SUBFRAME_SIZE);
00791 
00792     // emphasize pitch vector contribution
00793     if (p->pitch_gain[4] > 0.5 && !overflow) {
00794         float energy = ff_dot_productf(excitation, excitation,
00795                                        AMR_SUBFRAME_SIZE);
00796         float pitch_factor =
00797             p->pitch_gain[4] *
00798             (p->cur_frame_mode == MODE_12k2 ?
00799                 0.25 * FFMIN(p->pitch_gain[4], 1.0) :
00800                 0.5  * FFMIN(p->pitch_gain[4], SHARP_MAX));
00801 
00802         for (i = 0; i < AMR_SUBFRAME_SIZE; i++)
00803             excitation[i] += pitch_factor * p->pitch_vector[i];
00804 
00805         ff_scale_vector_to_given_sum_of_squares(excitation, excitation, energy,
00806                                                 AMR_SUBFRAME_SIZE);
00807     }
00808 
00809     ff_celp_lp_synthesis_filterf(samples, lpc, excitation, AMR_SUBFRAME_SIZE,
00810                                  LP_FILTER_ORDER);
00811 
00812     // detect overflow
00813     for (i = 0; i < AMR_SUBFRAME_SIZE; i++)
00814         if (fabsf(samples[i]) > AMR_SAMPLE_BOUND) {
00815             return 1;
00816         }
00817 
00818     return 0;
00819 }
00820 
00822 
00823 
00826 
00832 static void update_state(AMRContext *p)
00833 {
00834     memcpy(p->prev_lsp_sub4, p->lsp[3], LP_FILTER_ORDER * sizeof(p->lsp[3][0]));
00835 
00836     memmove(&p->excitation_buf[0], &p->excitation_buf[AMR_SUBFRAME_SIZE],
00837             (PITCH_DELAY_MAX + LP_FILTER_ORDER + 1) * sizeof(float));
00838 
00839     memmove(&p->pitch_gain[0], &p->pitch_gain[1], 4 * sizeof(float));
00840     memmove(&p->fixed_gain[0], &p->fixed_gain[1], 4 * sizeof(float));
00841 
00842     memmove(&p->samples_in[0], &p->samples_in[AMR_SUBFRAME_SIZE],
00843             LP_FILTER_ORDER * sizeof(float));
00844 }
00845 
00847 
00848 
00851 
00858 static float tilt_factor(float *lpc_n, float *lpc_d)
00859 {
00860     float rh0, rh1; // autocorrelation at lag 0 and 1
00861 
00862     // LP_FILTER_ORDER prior zeros are needed for ff_celp_lp_synthesis_filterf
00863     float impulse_buffer[LP_FILTER_ORDER + AMR_TILT_RESPONSE] = { 0 };
00864     float *hf = impulse_buffer + LP_FILTER_ORDER; // start of impulse response
00865 
00866     hf[0] = 1.0;
00867     memcpy(hf + 1, lpc_n, sizeof(float) * LP_FILTER_ORDER);
00868     ff_celp_lp_synthesis_filterf(hf, lpc_d, hf, AMR_TILT_RESPONSE,
00869                                  LP_FILTER_ORDER);
00870 
00871     rh0 = ff_dot_productf(hf, hf,     AMR_TILT_RESPONSE);
00872     rh1 = ff_dot_productf(hf, hf + 1, AMR_TILT_RESPONSE - 1);
00873 
00874     // The spec only specifies this check for 12.2 and 10.2 kbit/s
00875     // modes. But in the ref source the tilt is always non-negative.
00876     return rh1 >= 0.0 ? rh1 / rh0 * AMR_TILT_GAMMA_T : 0.0;
00877 }
00878 
00887 static void postfilter(AMRContext *p, float *lpc, float *buf_out)
00888 {
00889     int i;
00890     float *samples          = p->samples_in + LP_FILTER_ORDER; // Start of input
00891 
00892     float speech_gain       = ff_dot_productf(samples, samples,
00893                                               AMR_SUBFRAME_SIZE);
00894 
00895     float pole_out[AMR_SUBFRAME_SIZE + LP_FILTER_ORDER];  // Output of pole filter
00896     const float *gamma_n, *gamma_d;                       // Formant filter factor table
00897     float lpc_n[LP_FILTER_ORDER], lpc_d[LP_FILTER_ORDER]; // Transfer function coefficients
00898 
00899     if (p->cur_frame_mode == MODE_12k2 || p->cur_frame_mode == MODE_10k2) {
00900         gamma_n = ff_pow_0_7;
00901         gamma_d = ff_pow_0_75;
00902     } else {
00903         gamma_n = ff_pow_0_55;
00904         gamma_d = ff_pow_0_7;
00905     }
00906 
00907     for (i = 0; i < LP_FILTER_ORDER; i++) {
00908          lpc_n[i] = lpc[i] * gamma_n[i];
00909          lpc_d[i] = lpc[i] * gamma_d[i];
00910     }
00911 
00912     memcpy(pole_out, p->postfilter_mem, sizeof(float) * LP_FILTER_ORDER);
00913     ff_celp_lp_synthesis_filterf(pole_out + LP_FILTER_ORDER, lpc_d, samples,
00914                                  AMR_SUBFRAME_SIZE, LP_FILTER_ORDER);
00915     memcpy(p->postfilter_mem, pole_out + AMR_SUBFRAME_SIZE,
00916            sizeof(float) * LP_FILTER_ORDER);
00917 
00918     ff_celp_lp_zero_synthesis_filterf(buf_out, lpc_n,
00919                                       pole_out + LP_FILTER_ORDER,
00920                                       AMR_SUBFRAME_SIZE, LP_FILTER_ORDER);
00921 
00922     ff_tilt_compensation(&p->tilt_mem, tilt_factor(lpc_n, lpc_d), buf_out,
00923                          AMR_SUBFRAME_SIZE);
00924 
00925     ff_adaptive_gain_control(buf_out, buf_out, speech_gain, AMR_SUBFRAME_SIZE,
00926                              AMR_AGC_ALPHA, &p->postfilter_agc);
00927 }
00928 
00930 
00931 static int amrnb_decode_frame(AVCodecContext *avctx, void *data,
00932                               int *got_frame_ptr, AVPacket *avpkt)
00933 {
00934 
00935     AMRContext *p = avctx->priv_data;        // pointer to private data
00936     const uint8_t *buf = avpkt->data;
00937     int buf_size       = avpkt->size;
00938     float *buf_out;                          // pointer to the output data buffer
00939     int i, subframe, ret;
00940     float fixed_gain_factor;
00941     AMRFixed fixed_sparse = {0};             // fixed vector up to anti-sparseness processing
00942     float spare_vector[AMR_SUBFRAME_SIZE];   // extra stack space to hold result from anti-sparseness processing
00943     float synth_fixed_gain;                  // the fixed gain that synthesis should use
00944     const float *synth_fixed_vector;         // pointer to the fixed vector that synthesis should use
00945 
00946     /* get output buffer */
00947     p->avframe.nb_samples = AMR_BLOCK_SIZE;
00948     if ((ret = ff_get_buffer(avctx, &p->avframe)) < 0) {
00949         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00950         return ret;
00951     }
00952     buf_out = (float *)p->avframe.data[0];
00953 
00954     p->cur_frame_mode = unpack_bitstream(p, buf, buf_size);
00955     if (p->cur_frame_mode == NO_DATA) {
00956         av_log(avctx, AV_LOG_ERROR, "Corrupt bitstream\n");
00957         return AVERROR_INVALIDDATA;
00958     }
00959     if (p->cur_frame_mode == MODE_DTX) {
00960         av_log_missing_feature(avctx, "dtx mode", 1);
00961         return -1;
00962     }
00963 
00964     if (p->cur_frame_mode == MODE_12k2) {
00965         lsf2lsp_5(p);
00966     } else
00967         lsf2lsp_3(p);
00968 
00969     for (i = 0; i < 4; i++)
00970         ff_acelp_lspd2lpc(p->lsp[i], p->lpc[i], 5);
00971 
00972     for (subframe = 0; subframe < 4; subframe++) {
00973         const AMRNBSubframe *amr_subframe = &p->frame.subframe[subframe];
00974 
00975         decode_pitch_vector(p, amr_subframe, subframe);
00976 
00977         decode_fixed_sparse(&fixed_sparse, amr_subframe->pulses,
00978                             p->cur_frame_mode, subframe);
00979 
00980         // The fixed gain (section 6.1.3) depends on the fixed vector
00981         // (section 6.1.2), but the fixed vector calculation uses
00982         // pitch sharpening based on the on the pitch gain (section 6.1.3).
00983         // So the correct order is: pitch gain, pitch sharpening, fixed gain.
00984         decode_gains(p, amr_subframe, p->cur_frame_mode, subframe,
00985                      &fixed_gain_factor);
00986 
00987         pitch_sharpening(p, subframe, p->cur_frame_mode, &fixed_sparse);
00988 
00989         if (fixed_sparse.pitch_lag == 0) {
00990             av_log(avctx, AV_LOG_ERROR, "The file is corrupted, pitch_lag = 0 is not allowed\n");
00991             return AVERROR_INVALIDDATA;
00992         }
00993         ff_set_fixed_vector(p->fixed_vector, &fixed_sparse, 1.0,
00994                             AMR_SUBFRAME_SIZE);
00995 
00996         p->fixed_gain[4] =
00997             ff_amr_set_fixed_gain(fixed_gain_factor,
00998                        ff_dot_productf(p->fixed_vector, p->fixed_vector,
00999                                        AMR_SUBFRAME_SIZE)/AMR_SUBFRAME_SIZE,
01000                        p->prediction_error,
01001                        energy_mean[p->cur_frame_mode], energy_pred_fac);
01002 
01003         // The excitation feedback is calculated without any processing such
01004         // as fixed gain smoothing. This isn't mentioned in the specification.
01005         for (i = 0; i < AMR_SUBFRAME_SIZE; i++)
01006             p->excitation[i] *= p->pitch_gain[4];
01007         ff_set_fixed_vector(p->excitation, &fixed_sparse, p->fixed_gain[4],
01008                             AMR_SUBFRAME_SIZE);
01009 
01010         // In the ref decoder, excitation is stored with no fractional bits.
01011         // This step prevents buzz in silent periods. The ref encoder can
01012         // emit long sequences with pitch factor greater than one. This
01013         // creates unwanted feedback if the excitation vector is nonzero.
01014         // (e.g. test sequence T19_795.COD in 3GPP TS 26.074)
01015         for (i = 0; i < AMR_SUBFRAME_SIZE; i++)
01016             p->excitation[i] = truncf(p->excitation[i]);
01017 
01018         // Smooth fixed gain.
01019         // The specification is ambiguous, but in the reference source, the
01020         // smoothed value is NOT fed back into later fixed gain smoothing.
01021         synth_fixed_gain = fixed_gain_smooth(p, p->lsf_q[subframe],
01022                                              p->lsf_avg, p->cur_frame_mode);
01023 
01024         synth_fixed_vector = anti_sparseness(p, &fixed_sparse, p->fixed_vector,
01025                                              synth_fixed_gain, spare_vector);
01026 
01027         if (synthesis(p, p->lpc[subframe], synth_fixed_gain,
01028                       synth_fixed_vector, &p->samples_in[LP_FILTER_ORDER], 0))
01029             // overflow detected -> rerun synthesis scaling pitch vector down
01030             // by a factor of 4, skipping pitch vector contribution emphasis
01031             // and adaptive gain control
01032             synthesis(p, p->lpc[subframe], synth_fixed_gain,
01033                       synth_fixed_vector, &p->samples_in[LP_FILTER_ORDER], 1);
01034 
01035         postfilter(p, p->lpc[subframe], buf_out + subframe * AMR_SUBFRAME_SIZE);
01036 
01037         // update buffers and history
01038         ff_clear_fixed_vector(p->fixed_vector, &fixed_sparse, AMR_SUBFRAME_SIZE);
01039         update_state(p);
01040     }
01041 
01042     ff_acelp_apply_order_2_transfer_function(buf_out, buf_out, highpass_zeros,
01043                                              highpass_poles,
01044                                              highpass_gain * AMR_SAMPLE_SCALE,
01045                                              p->high_pass_mem, AMR_BLOCK_SIZE);
01046 
01047     /* Update averaged lsf vector (used for fixed gain smoothing).
01048      *
01049      * Note that lsf_avg should not incorporate the current frame's LSFs
01050      * for fixed_gain_smooth.
01051      * The specification has an incorrect formula: the reference decoder uses
01052      * qbar(n-1) rather than qbar(n) in section 6.1(4) equation 71. */
01053     ff_weighted_vector_sumf(p->lsf_avg, p->lsf_avg, p->lsf_q[3],
01054                             0.84, 0.16, LP_FILTER_ORDER);
01055 
01056     *got_frame_ptr   = 1;
01057     *(AVFrame *)data = p->avframe;
01058 
01059     /* return the amount of bytes consumed if everything was OK */
01060     return frame_sizes_nb[p->cur_frame_mode] + 1; // +7 for rounding and +8 for TOC
01061 }
01062 
01063 
01064 AVCodec ff_amrnb_decoder = {
01065     .name           = "amrnb",
01066     .type           = AVMEDIA_TYPE_AUDIO,
01067     .id             = CODEC_ID_AMR_NB,
01068     .priv_data_size = sizeof(AMRContext),
01069     .init           = amrnb_decode_init,
01070     .decode         = amrnb_decode_frame,
01071     .capabilities   = CODEC_CAP_DR1,
01072     .long_name      = NULL_IF_CONFIG_SMALL("Adaptive Multi-Rate NarrowBand"),
01073     .sample_fmts    = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_FLT,AV_SAMPLE_FMT_NONE},
01074 };