• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • File List
  • Globals

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